summaryrefslogtreecommitdiff
path: root/java
diff options
context:
space:
mode:
Diffstat (limited to 'java')
-rw-r--r--java/broker-plugins/access-control/MANIFEST.MF42
-rw-r--r--java/broker-plugins/access-control/build.xml31
-rw-r--r--java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AbstractConfiguration.java77
-rw-r--r--java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/Action.java192
-rw-r--r--java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/ConfigurationFile.java56
-rw-r--r--java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/PlainConfiguration.java323
-rw-r--r--java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/Rule.java170
-rw-r--r--java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/RuleSet.java489
-rw-r--r--java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/XMLConfiguration.java31
-rw-r--r--java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/logging/AccessControl_logmessages.properties28
-rw-r--r--java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/AccessControl.java116
-rw-r--r--java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/AccessControlActivator.java42
-rw-r--r--java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/AccessControlConfiguration.java83
-rw-r--r--java/broker-plugins/access-control/src/main/resources/acl.xsd29
-rw-r--r--java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/AccessControlTest.java195
-rw-r--r--java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/RuleSetTest.java289
-rw-r--r--java/broker-plugins/experimental/info/MANIFEST.MF16
-rw-r--r--java/broker-plugins/experimental/info/build.properties31
-rw-r--r--java/broker-plugins/experimental/info/build.xml32
-rw-r--r--java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/Activator.java204
-rw-r--r--java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/AppInfo.java94
-rw-r--r--java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/Info.java143
-rw-r--r--java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/InfoService.java30
-rw-r--r--java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/InfoServiceImpl.java66
-rw-r--r--java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/SystemInfo.java91
-rw-r--r--java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/util/HttpPoster.java130
-rw-r--r--java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/util/IniFileReader.java193
-rw-r--r--java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/util/SoapClient.java155
-rw-r--r--java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/util/XMLWriter.java100
-rw-r--r--java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/systest/InfoPluginTest.java276
-rw-r--r--java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/HttpPosterTest.java107
-rw-r--r--java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/InfoServiceImplTest.java63
-rw-r--r--java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/InfoServlet.java57
-rw-r--r--java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/InfoTest.java112
-rw-r--r--java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/IniFileReaderTest.java136
-rw-r--r--java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/SoapClientTest.java208
-rw-r--r--java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/SystemInfoTest.java56
-rw-r--r--java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/XMLWriterTest.java132
-rw-r--r--java/broker-plugins/experimental/shutdown/MANIFEST.MF15
-rw-r--r--java/broker-plugins/experimental/shutdown/build.xml32
-rw-r--r--java/broker-plugins/experimental/shutdown/src/main/java/org/apache/qpid/shutdown/Activator.java71
-rw-r--r--java/broker-plugins/experimental/shutdown/src/main/java/org/apache/qpid/shutdown/Shutdown.java104
-rw-r--r--java/broker-plugins/experimental/shutdown/src/main/java/org/apache/qpid/shutdown/ShutdownMBean.java47
-rwxr-xr-xjava/broker-plugins/experimental/shutdown/src/main/java/shutdown.bnd25
-rw-r--r--java/broker-plugins/extras/MANIFEST.MF21
-rw-r--r--java/broker-plugins/extras/build.xml31
-rw-r--r--java/broker-plugins/extras/src/main/java/org/apache/qpid/extras/Activator.java48
-rw-r--r--java/broker-plugins/extras/src/main/java/org/apache/qpid/extras/exchanges/diagnostic/DiagnosticExchange.java229
-rw-r--r--java/broker-plugins/extras/src/main/java/org/apache/qpid/extras/exchanges/diagnostic/DiagnosticExchangeType.java57
-rw-r--r--java/broker-plugins/extras/src/main/java/org/apache/qpid/extras/exchanges/example/TestExchange.java257
-rw-r--r--java/broker-plugins/extras/src/main/java/org/apache/qpid/extras/exchanges/example/TestExchangeType.java57
-rw-r--r--java/broker-plugins/extras/src/test/java/org/apache/qpid/server/plugins/ExtrasTest.java74
-rw-r--r--java/broker-plugins/firewall/MANIFEST.MF36
-rw-r--r--java/broker-plugins/firewall/build.xml29
-rw-r--r--java/broker-plugins/firewall/src/main/java/org/apache/qpid/server/security/access/config/FirewallException.java46
-rw-r--r--java/broker-plugins/firewall/src/main/java/org/apache/qpid/server/security/access/config/FirewallRule.java137
-rw-r--r--java/broker-plugins/firewall/src/main/java/org/apache/qpid/server/security/access/plugins/Firewall.java136
-rw-r--r--java/broker-plugins/firewall/src/main/java/org/apache/qpid/server/security/access/plugins/FirewallActivator.java42
-rw-r--r--java/broker-plugins/firewall/src/main/java/org/apache/qpid/server/security/access/plugins/FirewallConfiguration.java102
-rw-r--r--java/broker-plugins/firewall/src/test/java/org/apache/qpid/server/security/access/FirewallConfigurationTest.java355
-rw-r--r--java/broker-plugins/firewall/src/test/java/org/apache/qpid/server/security/access/FirewallPluginTest.java282
-rw-r--r--java/broker-plugins/simple-xml/MANIFEST.MF36
-rw-r--r--java/broker-plugins/simple-xml/build.xml29
-rwxr-xr-xjava/broker-plugins/simple-xml/src/main/java/org/apache/qpid/server/security/access/config/PrincipalPermissions.java687
-rw-r--r--java/broker-plugins/simple-xml/src/main/java/org/apache/qpid/server/security/access/plugins/SimpleXML.java427
-rw-r--r--java/broker-plugins/simple-xml/src/main/java/org/apache/qpid/server/security/access/plugins/SimpleXMLActivator.java42
-rw-r--r--java/broker-plugins/simple-xml/src/main/java/org/apache/qpid/server/security/access/plugins/SimpleXMLConfiguration.java57
-rw-r--r--java/broker-plugins/simple-xml/src/test/java/org/apache/qpid/server/security/access/PrincipalPermissionsTest.java209
-rw-r--r--java/broker/bin/create-example-ssl-stores.bat36
-rwxr-xr-xjava/broker/bin/create-example-ssl-stores.sh38
-rwxr-xr-xjava/broker/bin/msTool.sh60
-rwxr-xr-xjava/broker/bin/qpid-passwd35
-rwxr-xr-xjava/broker/bin/qpid-server56
-rw-r--r--java/broker/bin/qpid-server.bat201
-rwxr-xr-xjava/broker/bin/qpid.stop178
-rwxr-xr-xjava/broker/bin/qpid.stopall27
-rw-r--r--java/broker/build.xml83
-rw-r--r--java/broker/etc/access19
-rw-r--r--java/broker/etc/config.xml109
-rw-r--r--java/broker/etc/debug.log4j.xml114
-rw-r--r--java/broker/etc/log4j.xml125
-rw-r--r--java/broker/etc/md5passwd21
-rw-r--r--java/broker/etc/mstool-log4j.xml54
-rw-r--r--java/broker/etc/passwd23
-rw-r--r--java/broker/etc/passwdVhost19
-rw-r--r--java/broker/etc/qpid-server.conf25
-rw-r--r--java/broker/etc/qpid-server.conf.jpp49
-rw-r--r--java/broker/etc/qpid.passwd23
-rw-r--r--java/broker/etc/virtualhosts.xml162
-rwxr-xr-xjava/broker/python-test.xml56
-rw-r--r--java/broker/scripts/resetAlerting.sh116
-rw-r--r--java/broker/src/main/grammar/SelectorParser.jj621
-rw-r--r--java/broker/src/main/java/log4j.properties24
-rw-r--r--java/broker/src/main/java/org/apache/log4j/QpidCompositeRollingAppender.java1125
-rw-r--r--java/broker/src/main/java/org/apache/log4j/xml/QpidLog4JConfigurator.java320
-rw-r--r--java/broker/src/main/java/org/apache/qpid/configuration/Configuration.java188
-rw-r--r--java/broker/src/main/java/org/apache/qpid/qmf/CompletionCode.java36
-rw-r--r--java/broker/src/main/java/org/apache/qpid/qmf/ManagementExchange.java557
-rw-r--r--java/broker/src/main/java/org/apache/qpid/qmf/QMFBrokerRequestCommand.java78
-rw-r--r--java/broker/src/main/java/org/apache/qpid/qmf/QMFBrokerResponseCommand.java46
-rw-r--r--java/broker/src/main/java/org/apache/qpid/qmf/QMFClass.java158
-rw-r--r--java/broker/src/main/java/org/apache/qpid/qmf/QMFClassIndicationCommand.java50
-rw-r--r--java/broker/src/main/java/org/apache/qpid/qmf/QMFClassQueryCommand.java90
-rw-r--r--java/broker/src/main/java/org/apache/qpid/qmf/QMFCommand.java54
-rw-r--r--java/broker/src/main/java/org/apache/qpid/qmf/QMFCommandCompletionCommand.java56
-rw-r--r--java/broker/src/main/java/org/apache/qpid/qmf/QMFCommandDecoder.java98
-rw-r--r--java/broker/src/main/java/org/apache/qpid/qmf/QMFCommandHeader.java63
-rw-r--r--java/broker/src/main/java/org/apache/qpid/qmf/QMFEventClass.java42
-rw-r--r--java/broker/src/main/java/org/apache/qpid/qmf/QMFEventCommand.java49
-rw-r--r--java/broker/src/main/java/org/apache/qpid/qmf/QMFEventSeverity.java33
-rw-r--r--java/broker/src/main/java/org/apache/qpid/qmf/QMFGetQueryCommand.java182
-rw-r--r--java/broker/src/main/java/org/apache/qpid/qmf/QMFMessage.java211
-rw-r--r--java/broker/src/main/java/org/apache/qpid/qmf/QMFMethod.java157
-rw-r--r--java/broker/src/main/java/org/apache/qpid/qmf/QMFMethodInvocation.java26
-rw-r--r--java/broker/src/main/java/org/apache/qpid/qmf/QMFMethodRequestCommand.java88
-rw-r--r--java/broker/src/main/java/org/apache/qpid/qmf/QMFMethodResponseCommand.java76
-rw-r--r--java/broker/src/main/java/org/apache/qpid/qmf/QMFObject.java76
-rw-r--r--java/broker/src/main/java/org/apache/qpid/qmf/QMFObjectClass.java44
-rw-r--r--java/broker/src/main/java/org/apache/qpid/qmf/QMFOperation.java67
-rw-r--r--java/broker/src/main/java/org/apache/qpid/qmf/QMFPackage.java67
-rw-r--r--java/broker/src/main/java/org/apache/qpid/qmf/QMFPackageIndicationCommand.java46
-rw-r--r--java/broker/src/main/java/org/apache/qpid/qmf/QMFPackageQueryCommand.java86
-rw-r--r--java/broker/src/main/java/org/apache/qpid/qmf/QMFProperty.java123
-rw-r--r--java/broker/src/main/java/org/apache/qpid/qmf/QMFSchemaRequestCommand.java88
-rw-r--r--java/broker/src/main/java/org/apache/qpid/qmf/QMFSchemaResponseCommand.java83
-rw-r--r--java/broker/src/main/java/org/apache/qpid/qmf/QMFService.java1670
-rw-r--r--java/broker/src/main/java/org/apache/qpid/qmf/QMFStatistic.java61
-rw-r--r--java/broker/src/main/java/org/apache/qpid/qmf/QMFType.java53
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/AMQBrokerManagerMBean.java400
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/AMQChannel.java1465
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/ExtractResendAndRequeue.java133
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/Main.java617
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/ack/UnacknowledgedMessageMap.java72
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/ack/UnacknowledgedMessageMapImpl.java175
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/binding/Binding.java118
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/binding/BindingFactory.java289
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/configuration/BindingConfig.java41
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/configuration/BindingConfigType.java112
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/configuration/BridgeConfig.java48
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/configuration/BridgeConfigType.java169
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/configuration/BrokerConfig.java57
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/configuration/BrokerConfigType.java143
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/configuration/ConfigObjectType.java30
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/configuration/ConfigProperty.java66
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/configuration/ConfigStore.java184
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/configuration/ConfigurationManager.java53
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/configuration/ConfiguredObject.java37
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/configuration/ConnectionConfig.java49
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/configuration/ConnectionConfigType.java145
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/configuration/ExchangeConfig.java55
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/configuration/ExchangeConfigType.java113
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/configuration/ExchangeConfiguration.java58
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/configuration/ExchangeConfigurationPlugin.java29
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/configuration/LinkConfig.java57
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/configuration/LinkConfigType.java136
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/configuration/QueueConfig.java86
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/configuration/QueueConfigType.java121
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/configuration/QueueConfiguration.java208
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/configuration/ServerConfiguration.java860
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/configuration/SessionConfig.java55
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/configuration/SessionConfigType.java136
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/configuration/SubscriptionConfig.java47
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/configuration/SubscriptionConfigType.java136
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/configuration/SystemConfig.java42
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/configuration/SystemConfigImpl.java136
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/configuration/SystemConfigType.java128
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/configuration/TopicConfig.java78
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/configuration/TopicConfiguration.java269
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/configuration/VirtualHostConfig.java34
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/configuration/VirtualHostConfigType.java96
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/configuration/VirtualHostConfiguration.java342
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/configuration/management/ConfigurationManagementMBean.java48
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/configuration/plugins/ConfigurationPlugin.java454
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/configuration/plugins/ConfigurationPluginFactory.java38
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/configuration/plugins/SlowConsumerDetectionConfiguration.java89
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/configuration/plugins/SlowConsumerDetectionPolicyConfiguration.java76
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/configuration/plugins/SlowConsumerDetectionQueueConfiguration.java153
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/connection/ConnectionRegistry.java81
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/connection/IConnectionRegistry.java42
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/exchange/AbstractExchange.java403
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/exchange/AbstractExchangeMBean.java182
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/exchange/DefaultExchangeFactory.java146
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/exchange/DefaultExchangeRegistry.java164
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/exchange/DirectExchange.java216
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/exchange/DirectExchangeMBean.java81
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/exchange/Exchange.java145
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeFactory.java43
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeInUseException.java45
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeInitialiser.java54
-rwxr-xr-xjava/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeReferrer.java26
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeRegistry.java55
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeType.java35
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/exchange/FanoutExchange.java206
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/exchange/FanoutExchangeMBean.java70
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/exchange/HeadersBinding.java260
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/exchange/HeadersExchange.java260
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/exchange/HeadersExchangeMBean.java98
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/exchange/MessageRouter.java40
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/exchange/TopicExchange.java369
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/exchange/TopicExchangeMBean.java77
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/exchange/headers/HeaderKey.java40
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/exchange/headers/HeaderKeyDictionary.java50
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/exchange/headers/HeaderMatcherResult.java25
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/exchange/headers/HeadersMatcherDFAState.java339
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/exchange/headers/HeadersParser.java441
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicExchangeResult.java201
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicMatcherDFAState.java295
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicMatcherResult.java25
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicNormalizer.java96
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicParser.java613
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicWord.java54
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicWordDictionary.java63
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/federation/Bridge.java823
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/federation/BrokerLink.java512
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/filter/ArithmeticExpression.java275
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/filter/BinaryExpression.java106
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/filter/BooleanExpression.java38
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/filter/ComparisonExpression.java599
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/filter/ConstantExpression.java209
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/filter/Expression.java36
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/filter/FilterManager.java37
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/filter/FilterManagerFactory.java75
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/filter/JMSSelectorFilter.java63
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/filter/LogicExpression.java120
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/filter/MessageFilter.java28
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/filter/NoConsumerFilter.java48
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/filter/PropertyExpression.java235
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/filter/SimpleFilterManager.java94
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/filter/UnaryExpression.java362
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/filter/XPathExpression.java126
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/filter/XQueryExpression.java57
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/filter/XalanXPathEvaluator.java101
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/flow/AbstractFlowCreditManager.java71
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/flow/BytesOnlyCreditManager.java89
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/flow/CreditCreditManager.java188
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/flow/FlowCreditManager.java46
-rwxr-xr-xjava/broker/src/main/java/org/apache/qpid/server/flow/FlowCreditManager_0_10.java28
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/flow/LimitlessCreditManager.java54
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/flow/MessageAndBytesCreditManager.java92
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/flow/MessageOnlyCreditManager.java88
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/flow/Pre0_10CreditManager.java195
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/flow/WindowCreditManager.java213
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/AccessRequestHandler.java77
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/BasicAckMethodHandler.java67
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/BasicCancelMethodHandler.java74
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/BasicConsumeMethodHandler.java173
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/BasicGetMethodHandler.java206
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/BasicPublishMethodHandler.java96
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/BasicQosHandler.java58
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/BasicRecoverMethodHandler.java73
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/BasicRecoverSyncMethodHandler.java83
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/BasicRejectMethodHandler.java125
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/ChannelCloseHandler.java77
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/ChannelCloseOkHandler.java53
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/ChannelFlowHandler.java66
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/ChannelOpenHandler.java141
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionCloseMethodHandler.java72
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionCloseOkMethodHandler.java63
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionOpenMethodHandler.java101
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionSecureOkMethodHandler.java126
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionStartOkMethodHandler.java162
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionTuneOkMethodHandler.java58
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/ExchangeBoundHandler.java178
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/ExchangeDeclareHandler.java108
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/ExchangeDeleteHandler.java71
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/OnCurrentThreadExecutor.java34
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/QueueBindHandler.java159
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/QueueDeclareHandler.java254
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/QueueDeleteHandler.java125
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/QueuePurgeHandler.java123
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/QueueUnbindHandler.java123
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/ServerMethodDispatcherImpl.java574
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/ServerMethodDispatcherImpl_0_9.java164
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/ServerMethodDispatcherImpl_0_91.java168
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/ServerMethodDispatcherImpl_8_0.java86
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/TxCommitHandler.java76
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/TxRollbackHandler.java82
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/TxSelectHandler.java63
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/UnexpectedMethodException.java36
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/information/management/ServerInformationMBean.java146
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/logging/AbstractRootMessageLogger.java59
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/logging/CompositeStartupMessageLogger.java51
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/logging/Log4jMessageLogger.java74
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/logging/LogActor.java66
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/logging/LogMessage.java26
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/logging/LogSubject.java36
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/logging/NullRootMessageLogger.java47
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/logging/RootMessageLogger.java75
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/logging/SystemOutMessageLogger.java51
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/logging/actors/AMQPChannelActor.java64
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/logging/actors/AMQPConnectionActor.java54
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/logging/actors/AbstractActor.java71
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/logging/actors/BrokerActor.java53
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/logging/actors/CurrentActor.java125
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/logging/actors/GenericActor.java85
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/logging/actors/ManagementActor.java114
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/logging/actors/QueueActor.java55
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/logging/actors/SubscriptionActor.java46
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/logging/management/LoggingManagementMBean.java825
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/logging/messages/Binding_logmessages.properties22
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/logging/messages/Broker_logmessages.properties38
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/logging/messages/Channel_logmessages.properties34
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/logging/messages/ConfigStore_logmessages.properties27
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/logging/messages/Connection_logmessages.properties24
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/logging/messages/Exchange_logmessages.properties24
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/logging/messages/ManagementConsole_logmessages.properties33
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/logging/messages/MessageStore_logmessages.properties28
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/logging/messages/Queue_logmessages.properties26
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/logging/messages/Subscription_logmessages.properties24
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/logging/messages/TransactionLog_logmessages.properties33
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/logging/messages/VirtualHost_logmessages.properties26
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/logging/subjects/AbstractLogSubject.java63
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/logging/subjects/BindingLogSubject.java49
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/logging/subjects/ChannelLogSubject.java56
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/logging/subjects/ConnectionLogSubject.java107
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/logging/subjects/ExchangeLogSubject.java36
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/logging/subjects/LogSubjectFormat.java107
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/logging/subjects/MessageStoreLogSubject.java36
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/logging/subjects/QueueLogSubject.java36
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/logging/subjects/SubscriptionLogSubject.java55
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/management/AMQManagedObject.java106
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/management/DefaultManagedObject.java156
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/management/JMXManagedObjectRegistry.java447
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/management/MBeanIntrospector.java396
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/management/MBeanInvocationHandlerImpl.java329
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/management/Managable.java34
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/management/ManagedObject.java59
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/management/ManagedObjectRegistry.java50
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/management/NoopManagedObjectRegistry.java60
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/message/AMQMessage.java346
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/message/AMQMessageHeader.java55
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/message/AMQMessageReference.java44
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/message/ContentHeaderBodyAdapter.java127
-rwxr-xr-xjava/broker/src/main/java/org/apache/qpid/server/message/EnqueableMessage.java27
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/message/InboundMessage.java37
-rwxr-xr-xjava/broker/src/main/java/org/apache/qpid/server/message/MessageContentSource.java31
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/message/MessageMetaData.java320
-rwxr-xr-xjava/broker/src/main/java/org/apache/qpid/server/message/MessageMetaData_0_10.java242
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/message/MessageReference.java58
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/message/MessageTransferHeader.java153
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/message/MessageTransferMessage.java149
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/message/ServerMessage.java50
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/message/TransferMessageReference.java39
-rwxr-xr-xjava/broker/src/main/java/org/apache/qpid/server/output/HeaderPropertiesConverter.java124
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/output/ProtocolOutputConverter.java60
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/output/ProtocolOutputConverterRegistry.java61
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/output/amqp0_8/ProtocolOutputConverterImpl.java273
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/output/amqp0_9/ProtocolOutputConverterImpl.java383
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/output/amqp0_9_1/ProtocolOutputConverterImpl.java383
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/plugins/Activator.java50
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/plugins/Plugin.java31
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/plugins/PluginFactory.java31
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/plugins/PluginManager.java342
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/protocol/AMQConnectionModel.java72
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/protocol/AMQNoMethodHandlerException.java46
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolEngine.java1361
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolEngineFactory.java50
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolSession.java235
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolSessionMBean.java417
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/protocol/AMQSessionModel.java54
-rwxr-xr-xjava/broker/src/main/java/org/apache/qpid/server/protocol/MultiVersionProtocolEngine.java425
-rwxr-xr-xjava/broker/src/main/java/org/apache/qpid/server/protocol/MultiVersionProtocolEngineFactory.java75
-rwxr-xr-xjava/broker/src/main/java/org/apache/qpid/server/protocol/ProtocolEngine_0_10.java201
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/AMQPriorityQueue.java90
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/AMQQueue.java275
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/AMQQueueFactory.java253
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/AMQQueueMBean.java647
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/BaseQueue.java42
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/ConflationQueue.java47
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/ConflationQueueList.java167
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/DefaultQueueRegistry.java75
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/FailedDequeueException.java50
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/Filterable.java34
-rwxr-xr-xjava/broker/src/main/java/org/apache/qpid/server/queue/InboundMessageAdapter.java71
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/IncomingMessage.java300
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/MessageCleanupException.java52
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/NotificationCheck.java132
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/PriorityQueueList.java162
-rwxr-xr-xjava/broker/src/main/java/org/apache/qpid/server/queue/QueueContext.java49
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/QueueEntry.java210
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/QueueEntryImpl.java550
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/QueueEntryIterator.java30
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/QueueEntryList.java36
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/QueueEntryListFactory.java26
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/QueueNotificationListener.java27
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/QueueRegistry.java44
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/QueueRunner.java84
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/SimpleAMQQueue.java2233
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/SimpleQueueEntryList.java198
-rwxr-xr-xjava/broker/src/main/java/org/apache/qpid/server/queue/SubFlushRunner.java96
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/registry/ApplicationRegistry.java655
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/registry/BrokerConfigAdapter.java161
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/registry/ConfigurationFileApplicationRegistry.java69
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/registry/IApplicationRegistry.java103
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/AbstractPlugin.java53
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/AbstractProxyPlugin.java132
-rwxr-xr-xjava/broker/src/main/java/org/apache/qpid/server/security/PrincipalHolder.java29
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/Result.java46
-rwxr-xr-xjava/broker/src/main/java/org/apache/qpid/server/security/SecurityManager.java416
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/SecurityPlugin.java47
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/SecurityPluginActivator.java74
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/SecurityPluginFactory.java30
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/access/ObjectProperties.java318
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/access/ObjectType.java95
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/access/Operation.java55
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/access/Permission.java47
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/access/plugins/AllowAll.java99
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/access/plugins/BasicPlugin.java45
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/access/plugins/DenyAll.java99
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/access/plugins/LegacyAccess.java87
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/auth/AuthenticationResult.java61
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/auth/database/Base64MD5PasswordFilePrincipalDatabase.java567
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/auth/database/ConfigurationFilePrincipalDatabaseManager.java194
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/auth/database/HashedUser.java169
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PlainPasswordFilePrincipalDatabase.java503
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PlainUser.java106
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PrincipalDatabase.java105
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PrincipalDatabaseManager.java35
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PropertiesPrincipalDatabase.java169
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PropertiesPrincipalDatabaseManager.java49
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/auth/management/AMQUserManagementMBean.java211
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/auth/manager/AuthenticationManager.java40
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/auth/manager/PrincipalDatabaseAuthenticationManager.java184
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/auth/rmi/RMIPasswordAuthenticator.java119
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/AuthenticationProviderInitialiser.java76
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/JCAProvider.java46
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/UsernamePasswordInitialiser.java123
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/UsernamePrincipal.java44
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/amqplain/AmqPlainInitialiser.java38
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/amqplain/AmqPlainSaslServer.java132
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/amqplain/AmqPlainSaslServerFactory.java61
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/anonymous/AnonymousInitialiser.java39
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/anonymous/AnonymousSaslServer.java88
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/anonymous/AnonymousSaslServerFactory.java64
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HashedInitialiser.java50
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HashedSaslServer.java105
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HashedServerFactory.java61
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HexInitialiser.java144
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HexSaslServer.java105
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HexServerFactory.java61
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5Initialiser.java71
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/plain/PlainInitialiser.java38
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/plain/PlainPasswordCallback.java81
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/plain/PlainSaslServer.java155
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/plain/PlainSaslServerFactory.java61
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/state/AMQState.java36
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/state/AMQStateManager.java265
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/state/IllegalStateTransitionException.java52
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/state/StateAwareMethodListener.java35
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/state/StateListener.java30
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/stats/StatisticsCounter.java163
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/stats/StatisticsGatherer.java118
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/store/AbstractMessageStore.java43
-rwxr-xr-xjava/broker/src/main/java/org/apache/qpid/server/store/ConfigurationRecoveryHandler.java57
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/store/DerbyMessageStore.java1846
-rwxr-xr-xjava/broker/src/main/java/org/apache/qpid/server/store/DurableConfigurationStore.java131
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/store/MemoryMessageStore.java196
-rwxr-xr-xjava/broker/src/main/java/org/apache/qpid/server/store/MessageMetaDataType.java41
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/store/MessageStore.java80
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/store/MessageStoreClosedException.java36
-rwxr-xr-xjava/broker/src/main/java/org/apache/qpid/server/store/MessageStoreRecoveryHandler.java33
-rwxr-xr-xjava/broker/src/main/java/org/apache/qpid/server/store/StorableMessageMetaData.java36
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/store/StoreContext.java73
-rwxr-xr-xjava/broker/src/main/java/org/apache/qpid/server/store/StoredMemoryMessage.java80
-rwxr-xr-xjava/broker/src/main/java/org/apache/qpid/server/store/StoredMessage.java38
-rwxr-xr-xjava/broker/src/main/java/org/apache/qpid/server/store/TransactionLog.java91
-rwxr-xr-xjava/broker/src/main/java/org/apache/qpid/server/store/TransactionLogRecoveryHandler.java33
-rwxr-xr-xjava/broker/src/main/java/org/apache/qpid/server/store/TransactionLogResource.java26
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/subscription/ClientDeliveryMethod.java29
-rwxr-xr-xjava/broker/src/main/java/org/apache/qpid/server/subscription/ExplicitAcceptDispositionChangeListener.java93
-rwxr-xr-xjava/broker/src/main/java/org/apache/qpid/server/subscription/ImplicitAcceptDispositionChangeListener.java86
-rwxr-xr-xjava/broker/src/main/java/org/apache/qpid/server/subscription/MessageAcceptCompletionListener.java57
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/subscription/RecordDeliveryMethod.java28
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/subscription/Subscription.java109
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/subscription/SubscriptionFactory.java59
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/subscription/SubscriptionFactoryImpl.java95
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/subscription/SubscriptionImpl.java785
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/subscription/SubscriptionList.java245
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/subscription/Subscription_0_10.java957
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/transport/QpidAcceptor.java44
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/transport/ServerConnection.java346
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/transport/ServerConnectionDelegate.java158
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/transport/ServerSession.java678
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/transport/ServerSessionDelegate.java1244
-rwxr-xr-xjava/broker/src/main/java/org/apache/qpid/server/txn/AutoCommitTransaction.java258
-rwxr-xr-xjava/broker/src/main/java/org/apache/qpid/server/txn/LocalTransaction.java309
-rwxr-xr-xjava/broker/src/main/java/org/apache/qpid/server/txn/ServerTransaction.java110
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/util/CircularBuffer.java131
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/util/LoggingProxy.java105
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/virtualhost/HouseKeepingTask.java76
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/virtualhost/ManagedVirtualHost.java44
-rwxr-xr-xjava/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHost.java100
-rwxr-xr-xjava/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHostConfigRecoveryHandler.java360
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHostImpl.java876
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHostRegistry.java109
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/ConfiguredQueueBindingListener.java106
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/SlowConsumerDetection.java158
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/VirtualHostHouseKeepingPlugin.java54
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/VirtualHostPlugin.java43
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/VirtualHostPluginFactory.java28
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/logging/SlowConsumerDetection_logmessages.properties23
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/logging/TopicDeletePolicy_logmessages.properties22
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/policies/TopicDeletePolicy.java141
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/policies/TopicDeletePolicyConfiguration.java81
-rw-r--r--java/broker/src/main/java/org/apache/qpid/slowconsumerdetection/policies/SlowConsumerPolicyPlugin.java29
-rw-r--r--java/broker/src/main/java/org/apache/qpid/slowconsumerdetection/policies/SlowConsumerPolicyPluginFactory.java27
-rw-r--r--java/broker/src/main/java/org/apache/qpid/tools/messagestore/MessageStoreTool.java652
-rw-r--r--java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/AbstractCommand.java66
-rw-r--r--java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Clear.java85
-rw-r--r--java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Command.java36
-rw-r--r--java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Copy.java59
-rw-r--r--java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Dump.java305
-rw-r--r--java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Help.java98
-rw-r--r--java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/List.java314
-rw-r--r--java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Load.java94
-rw-r--r--java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Move.java202
-rw-r--r--java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Purge.java67
-rw-r--r--java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Quit.java54
-rw-r--r--java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Select.java233
-rw-r--r--java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Show.java516
-rw-r--r--java/broker/src/main/java/org/apache/qpid/tools/security/Passwd.java81
-rw-r--r--java/broker/src/main/java/org/apache/qpid/tools/utils/CommandParser.java51
-rw-r--r--java/broker/src/main/java/org/apache/qpid/tools/utils/Console.java90
-rw-r--r--java/broker/src/main/java/org/apache/qpid/tools/utils/SimpleCommandParser.java121
-rw-r--r--java/broker/src/main/java/org/apache/qpid/tools/utils/SimpleConsole.java364
-rw-r--r--java/broker/src/test/java/org/apache/log4j/xml/QpidLog4JConfiguratorTest.java396
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/AMQBrokerManagerMBeanTest.java94
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/ExtractResendAndRequeueTest.java255
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/RunBrokerWithCommand.java132
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/SelectorParserTest.java128
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/ack/AcknowledgeTest.java120
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/configuration/QueueConfigurationTest.java145
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/configuration/ServerConfigurationTest.java1492
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/configuration/TopicConfigurationTest.java130
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/configuration/VirtualHostConfigurationTest.java233
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/configuration/plugins/ConfigurationPluginTest.java210
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/exchange/AbstractHeadersExchangeTestBase.java625
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/exchange/ExchangeMBeanTest.java195
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/exchange/HeadersBindingTest.java317
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/exchange/HeadersExchangeTest.java124
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/exchange/TopicExchangeTest.java441
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/logging/Log4jMessageLoggerTest.java271
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/logging/LogMessageTest.java169
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/logging/UnitTestMessageLogger.java72
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/logging/UnitTestMessageLoggerTest.java103
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/logging/actors/AMQPChannelActorTest.java221
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/logging/actors/AMQPConnectionActorTest.java132
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/logging/actors/BaseActorTestCase.java91
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/logging/actors/BaseConnectionActorTestCase.java33
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/logging/actors/CurrentActorTest.java256
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/logging/actors/ManagementActorTest.java103
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/logging/actors/QueueActorTest.java73
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/logging/actors/SubscriptionActorTest.java85
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/logging/actors/TestLogActor.java37
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/logging/management/LoggingManagementMBeanTest.java431
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/logging/messages/AbstractTestMessages.java109
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/logging/messages/BindingMessagesTest.java64
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/logging/messages/BrokerMessagesTest.java116
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/logging/messages/ChannelMessagesTest.java64
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/logging/messages/ConnectionMessagesTest.java90
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/logging/messages/ExchangeMessagesTest.java80
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/logging/messages/ManagementConsoleMessagesTest.java107
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/logging/messages/MessageStoreMessagesTest.java125
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/logging/messages/QueueMessagesTest.java239
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/logging/messages/SubscriptionMessagesTest.java86
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/logging/messages/VirtualHostMessagesTest.java51
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/logging/subjects/AbstractTestLogSubject.java288
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/logging/subjects/BindingLogSubjectTest.java71
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/logging/subjects/ChannelLogSubjectTest.java58
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/logging/subjects/ConnectionLogSubjectTest.java46
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/logging/subjects/ExchangeLogSubjectTest.java58
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/logging/subjects/MessageStoreLogSubjectTest.java62
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/logging/subjects/QueueLogSubjectTest.java63
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/logging/subjects/SubscriptionLogSubjectTest.java105
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/logging/subjects/TestBlankSubject.java33
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/management/AMQUserManagementMBeanTest.java191
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/plugins/MockPluginManager.java56
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/plugins/PluginTest.java56
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/protocol/AMQProtocolSessionMBeanTest.java146
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/protocol/InternalTestProtocolSession.java213
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/protocol/MaxChannelsTest.java79
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/queue/AMQPriorityQueueTest.java108
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueAlertTest.java350
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueFactoryTest.java75
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueMBeanTest.java456
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/queue/AckTest.java427
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/queue/MockAMQMessage.java43
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/queue/MockAMQQueue.java614
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/queue/MockMessagePublishInfo.java52
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/queue/MockQueueEntry.java234
-rwxr-xr-xjava/broker/src/test/java/org/apache/qpid/server/queue/MockStoredMessage.java92
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/queue/QueueEntryTest.java97
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/queue/SimpleAMQQueueTest.java817
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/queue/SimpleAMQQueueThreadPoolTest.java59
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/queue/SimpleQueueEntryListTest.java159
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/registry/ApplicationRegistryShutdownTest.java105
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/security/auth/database/Base64MD5PasswordFilePrincipalDatabaseTest.java466
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/security/auth/database/HashedUserTest.java95
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/security/auth/database/PlainPasswordFilePrincipalDatabaseTest.java416
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/security/auth/database/PlainUserTest.java78
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/PrincipalDatabaseAuthenticationManagerTest.java209
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/security/auth/rmi/RMIPasswordAuthenticatorTest.java267
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/CRAMMD5HexInitialiserTest.java137
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/CRAMMD5HexServerTest.java230
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/SaslServerTestCase.java66
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/TestPrincipalDatabase.java91
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/amqplain/AMQPlainSaslServerTest.java43
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/plain/PlainSaslServerTest.java39
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/stats/StatisticsCounterTest.java144
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/store/MessageStoreShutdownTest.java81
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/store/MessageStoreTest.java908
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/store/ReferenceCountingTest.java163
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/store/SkeletonMessageStore.java226
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/store/TestMemoryMessageStore.java98
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/store/TestableMemoryMessageStore.java157
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/subscription/MockSubscription.java262
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/subscription/QueueBrowserUsesNoAckTest.java77
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/txn/AutoCommitTransactionTest.java442
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/txn/LocalTransactionTest.java557
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/txn/MockAction.java56
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/txn/MockServerMessage.java114
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/txn/MockStoreTransaction.java136
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/util/InternalBrokerBaseCase.java365
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/util/LoggingProxyTest.java88
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/util/TestApplicationRegistry.java48
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/SlowConsumerDetectionConfigurationTest.java346
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/SlowConsumerDetectionPolicyConfigurationTest.java104
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/SlowConsumerDetectionQueueConfigurationTest.java185
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/policies/TopicDeletePolicyConfigurationTest.java88
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/policies/TopicDeletePolicyTest.java293
-rw-r--r--java/broker/src/test/java/org/apache/qpid/util/MockChannel.java40
-rw-r--r--java/broker/src/velocity/java/org/apache/qpid/server/logging/GenerateLogMessages.java527
-rw-r--r--java/broker/src/velocity/templates/org/apache/qpid/server/logging/messages/LogMessages.vm200
-rw-r--r--java/broker/src/xsl/qmf.xsl872
-rw-r--r--java/build.deps145
-rw-r--r--java/build.xml297
-rw-r--r--java/client/README.txt51
-rw-r--r--java/client/build.xml72
-rw-r--r--java/client/example/build.xml28
-rw-r--r--java/client/example/src/main/java/README.txt33
-rw-r--r--java/client/example/src/main/java/org/apache/qpid/example/Drain.java105
-rw-r--r--java/client/example/src/main/java/org/apache/qpid/example/Hello.java74
-rw-r--r--java/client/example/src/main/java/org/apache/qpid/example/MapReceiver.java52
-rw-r--r--java/client/example/src/main/java/org/apache/qpid/example/MapSender.java83
-rw-r--r--java/client/example/src/main/java/org/apache/qpid/example/OptionParser.java335
-rw-r--r--java/client/example/src/main/java/org/apache/qpid/example/Spout.java148
-rw-r--r--java/client/example/src/main/java/org/apache/qpid/example/hello.properties27
-rw-r--r--java/client/example/src/main/java/org/apache/qpid/example/publisher/FileMessageDispatcher.java163
-rw-r--r--java/client/example/src/main/java/org/apache/qpid/example/publisher/FileMessageFactory.java138
-rw-r--r--java/client/example/src/main/java/org/apache/qpid/example/publisher/MessageFactoryException.java29
-rw-r--r--java/client/example/src/main/java/org/apache/qpid/example/publisher/MonitorMessageDispatcher.java141
-rw-r--r--java/client/example/src/main/java/org/apache/qpid/example/publisher/MonitorPublisher.java105
-rw-r--r--java/client/example/src/main/java/org/apache/qpid/example/publisher/MultiMessageDispatcher.java141
-rw-r--r--java/client/example/src/main/java/org/apache/qpid/example/publisher/Publisher.java208
-rw-r--r--java/client/example/src/main/java/org/apache/qpid/example/publisher/TopicPublisher.java59
-rw-r--r--java/client/example/src/main/java/org/apache/qpid/example/publisher/UndeliveredMessageException.java32
-rw-r--r--java/client/example/src/main/java/org/apache/qpid/example/pubsub/Client.java72
-rw-r--r--java/client/example/src/main/java/org/apache/qpid/example/pubsub/ConnectionSetup.java123
-rw-r--r--java/client/example/src/main/java/org/apache/qpid/example/pubsub/Publisher.java81
-rw-r--r--java/client/example/src/main/java/org/apache/qpid/example/pubsub/Subscriber.java98
-rw-r--r--java/client/example/src/main/java/org/apache/qpid/example/shared/ConnectionException.java29
-rw-r--r--java/client/example/src/main/java/org/apache/qpid/example/shared/ContextException.java29
-rw-r--r--java/client/example/src/main/java/org/apache/qpid/example/shared/FileUtils.java168
-rw-r--r--java/client/example/src/main/java/org/apache/qpid/example/shared/InitialContextHelper.java81
-rw-r--r--java/client/example/src/main/java/org/apache/qpid/example/shared/Statics.java57
-rw-r--r--java/client/example/src/main/java/org/apache/qpid/example/shared/example.properties40
-rw-r--r--java/client/example/src/main/java/org/apache/qpid/example/simple/reqresp/Client.java263
-rw-r--r--java/client/example/src/main/java/org/apache/qpid/example/simple/reqresp/Server.java236
-rw-r--r--java/client/example/src/main/java/org/apache/qpid/example/subscriber/MonitoredSubscriber.java139
-rw-r--r--java/client/example/src/main/java/org/apache/qpid/example/subscriber/MonitoredSubscriptionWrapper.java47
-rw-r--r--java/client/example/src/main/java/org/apache/qpid/example/subscriber/Subscriber.java182
-rw-r--r--java/client/example/src/main/java/org/apache/qpid/example/subscriber/SubscriptionWrapper.java46
-rw-r--r--java/client/example/src/main/java/org/apache/qpid/example/transport/ExistingSocketConnectorDemo.java171
-rwxr-xr-xjava/client/example/src/main/java/runSample.sh72
-rw-r--r--java/client/src/main/grammar/SelectorParser.jj609
-rwxr-xr-xjava/client/src/main/java/client.bnd26
-rw-r--r--java/client/src/main/java/client.log4j33
-rw-r--r--java/client/src/main/java/org/apache/mina/transport/socket/nio/ExistingSocketConnector.java478
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/AMQAnyDestination.java88
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/AMQAuthenticationException.java42
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/AMQBrokerDetails.java414
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/AMQConnection.java1493
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/AMQConnectionDelegate.java66
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/AMQConnectionDelegate_0_10.java460
-rwxr-xr-xjava/client/src/main/java/org/apache/qpid/client/AMQConnectionDelegate_0_9.java40
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/AMQConnectionDelegate_8_0.java325
-rwxr-xr-xjava/client/src/main/java/org/apache/qpid/client/AMQConnectionDelegate_9_1.java39
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/AMQConnectionFactory.java566
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/AMQConnectionURL.java311
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/AMQDestination.java941
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/AMQHeadersExchange.java54
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/AMQNoConsumersException.java40
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/AMQNoRouteException.java40
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/AMQQueue.java172
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/AMQQueueBrowser.java143
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/AMQQueueSessionAdaptor.java204
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/AMQSession.java3489
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/AMQSessionAdapter.java26
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/AMQSessionDirtyException.java42
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/AMQSession_0_10.java1372
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/AMQSession_0_8.java619
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/AMQTemporaryQueue.java69
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/AMQTemporaryTopic.java72
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/AMQTopic.java224
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/AMQTopicSessionAdaptor.java226
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/AMQUndefinedDestination.java40
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/BasicMessageConsumer.java1079
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/BasicMessageConsumer_0_10.java529
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/BasicMessageConsumer_0_8.java95
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/BasicMessageProducer.java601
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/BasicMessageProducer_0_10.java269
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/BasicMessageProducer_0_8.java229
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/ChannelToSessionMap.java167
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/Closeable.java101
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/ConnectionTuneParameters.java72
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/CustomJMSXProperty.java66
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/DispatcherCallback.java36
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/JMSAMQException.java67
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/JmsNotImplementedException.java31
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/MessageConsumerPair.java43
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/QpidConnectionMetaData.java97
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/QueueReceiverAdaptor.java115
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/QueueSenderAdapter.java227
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/SSLConfiguration.java61
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/TemporaryDestination.java38
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/TopicPublisherAdapter.java205
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/TopicSubscriberAdaptor.java132
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/XAConnectionImpl.java78
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/XAResourceImpl.java522
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/XASessionImpl.java159
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/failover/FailoverException.java49
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/failover/FailoverHandler.java268
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/failover/FailoverNoopSupport.java75
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/failover/FailoverProtectedOperation.java49
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/failover/FailoverRetrySupport.java104
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/failover/FailoverState.java64
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/failover/FailoverSupport.java47
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/handler/AccessRequestOkMethodHandler.java50
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/handler/BasicCancelOkMethodHandler.java55
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/handler/BasicDeliverMethodHandler.java54
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/handler/BasicReturnMethodHandler.java58
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/handler/ChannelCloseMethodHandler.java119
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/handler/ChannelCloseOkMethodHandler.java49
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/handler/ChannelFlowMethodHandler.java51
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/handler/ChannelFlowOkMethodHandler.java52
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/handler/ClientMethodDispatcherImpl.java543
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/handler/ClientMethodDispatcherImpl_0_9.java153
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/handler/ClientMethodDispatcherImpl_0_91.java158
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/handler/ClientMethodDispatcherImpl_8_0.java85
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/handler/ConnectionCloseMethodHandler.java113
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/handler/ConnectionOpenOkMethodHandler.java48
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/handler/ConnectionRedirectMethodHandler.java71
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/handler/ConnectionSecureMethodHandler.java70
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/handler/ConnectionStartMethodHandler.java239
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/handler/ConnectionTuneMethodHandler.java85
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/handler/ExchangeBoundOkMethodHandler.java57
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/handler/QueueDeleteOkMethodHandler.java57
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/AMQMessageDelegate.java140
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/AMQMessageDelegateFactory.java54
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/AMQMessageDelegate_0_10.java980
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/AMQMessageDelegate_0_8.java576
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/AMQPEncodedMapMessage.java122
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/AMQPEncodedMapMessageFactory.java46
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/AbstractAMQMessageDelegate.java206
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/AbstractBytesMessage.java124
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/AbstractBytesTypedMessage.java804
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/AbstractJMSMessage.java536
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/AbstractJMSMessageFactory.java173
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/CloseConsumerMessage.java43
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/FieldTableSupport.java54
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/JMSBytesMessage.java386
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/JMSBytesMessageFactory.java44
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/JMSHeaderAdapter.java553
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/JMSMapMessage.java512
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/JMSMapMessageFactory.java42
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/JMSObjectMessage.java176
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/JMSObjectMessageFactory.java41
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/JMSStreamMessage.java206
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/JMSStreamMessageFactory.java40
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/JMSTextMessage.java189
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/JMSTextMessageFactory.java42
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/MessageConverter.java195
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/MessageFactory.java49
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/MessageFactoryRegistry.java173
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/ReturnMessage.java47
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/UnprocessedMessage.java58
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/UnprocessedMessage_0_10.java53
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/UnprocessedMessage_0_8.java163
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/messaging/address/AddressHelper.java332
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/messaging/address/Link.java172
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/messaging/address/Node.java148
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/messaging/address/QpidExchangeOptions.java45
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/messaging/address/QpidQueueOptions.java103
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/protocol/AMQProtocolHandler.java881
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/protocol/AMQProtocolSession.java477
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/protocol/BlockingMethodFrameListener.java136
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/protocol/HeartbeatConfig.java61
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/protocol/HeartbeatDiagnostics.java121
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/protocol/ProtocolBufferMonitorFilter.java115
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/security/AMQCallbackHandler.java30
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/security/CallbackHandlerRegistry.java231
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/security/CallbackHandlerRegistry.properties22
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/security/DynamicSaslRegistrar.java210
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/security/DynamicSaslRegistrar.properties21
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/security/JCAProvider.java72
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/security/UsernameHashedPasswordCallbackHandler.java102
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/security/UsernamePasswordCallbackHandler.java60
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/security/amqplain/AmqPlainSaslClient.java105
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/security/amqplain/AmqPlainSaslClientFactory.java63
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/security/anonymous/AnonymousSaslClient.java52
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/security/anonymous/AnonymousSaslClientFactory.java52
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/security/crammd5hashed/CRAMMD5HashedSaslClientFactory.java72
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/state/AMQMethodNotImplementedException.java32
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/state/AMQState.java60
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/state/AMQStateChangedEvent.java48
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/state/AMQStateListener.java26
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/state/AMQStateManager.java221
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/state/StateAwareMethodListener.java38
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/state/StateWaiter.java128
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/state/listener/SpecificMethodFrameListener.java41
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/transport/AMQNoTransportForProtocolException.java59
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/transport/AMQTransportConnectionException.java43
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/transport/ITransportConnection.java32
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/transport/SocketTransportConnection.java90
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/transport/TransportConnection.java351
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/transport/VmPipeTransportConnection.java63
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/url/URLParser.java253
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/url/URLParser_0_10.java423
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/util/BlockingWaiter.java348
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/util/FlowControllingBlockingQueue.java135
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/vmbroker/AMQVMBrokerCreationException.java60
-rw-r--r--java/client/src/main/java/org/apache/qpid/collections/KeyValue.java46
-rw-r--r--java/client/src/main/java/org/apache/qpid/collections/ReferenceMap.java957
-rw-r--r--java/client/src/main/java/org/apache/qpid/collections/keyvalue/AbstractKeyValue.java83
-rw-r--r--java/client/src/main/java/org/apache/qpid/collections/keyvalue/AbstractMapEntry.java96
-rw-r--r--java/client/src/main/java/org/apache/qpid/collections/keyvalue/DefaultMapEntry.java67
-rw-r--r--java/client/src/main/java/org/apache/qpid/filter/ArithmeticExpression.java268
-rw-r--r--java/client/src/main/java/org/apache/qpid/filter/BinaryExpression.java103
-rw-r--r--java/client/src/main/java/org/apache/qpid/filter/BooleanExpression.java33
-rw-r--r--java/client/src/main/java/org/apache/qpid/filter/ComparisonExpression.java589
-rw-r--r--java/client/src/main/java/org/apache/qpid/filter/ConstantExpression.java204
-rw-r--r--java/client/src/main/java/org/apache/qpid/filter/Expression.java35
-rw-r--r--java/client/src/main/java/org/apache/qpid/filter/JMSSelectorFilter.java70
-rw-r--r--java/client/src/main/java/org/apache/qpid/filter/LogicExpression.java108
-rw-r--r--java/client/src/main/java/org/apache/qpid/filter/MessageFilter.java27
-rw-r--r--java/client/src/main/java/org/apache/qpid/filter/PropertyExpression.java297
-rw-r--r--java/client/src/main/java/org/apache/qpid/filter/UnaryExpression.java321
-rw-r--r--java/client/src/main/java/org/apache/qpid/jms/BrokerDetails.java119
-rw-r--r--java/client/src/main/java/org/apache/qpid/jms/ChannelLimitReachedException.java46
-rw-r--r--java/client/src/main/java/org/apache/qpid/jms/Connection.java69
-rw-r--r--java/client/src/main/java/org/apache/qpid/jms/ConnectionListener.java58
-rw-r--r--java/client/src/main/java/org/apache/qpid/jms/ConnectionURL.java96
-rw-r--r--java/client/src/main/java/org/apache/qpid/jms/FailoverPolicy.java324
-rw-r--r--java/client/src/main/java/org/apache/qpid/jms/Message.java30
-rw-r--r--java/client/src/main/java/org/apache/qpid/jms/MessageConsumer.java27
-rw-r--r--java/client/src/main/java/org/apache/qpid/jms/MessageProducer.java57
-rw-r--r--java/client/src/main/java/org/apache/qpid/jms/Session.java101
-rw-r--r--java/client/src/main/java/org/apache/qpid/jms/TopicSubscriber.java32
-rw-r--r--java/client/src/main/java/org/apache/qpid/jms/failover/FailoverExchangeMethod.java320
-rw-r--r--java/client/src/main/java/org/apache/qpid/jms/failover/FailoverMethod.java79
-rw-r--r--java/client/src/main/java/org/apache/qpid/jms/failover/FailoverRoundRobinServers.java253
-rw-r--r--java/client/src/main/java/org/apache/qpid/jms/failover/FailoverSingleServer.java166
-rw-r--r--java/client/src/main/java/org/apache/qpid/jms/failover/NoFailover.java62
-rw-r--r--java/client/src/main/java/org/apache/qpid/jndi/Example.properties40
-rw-r--r--java/client/src/main/java/org/apache/qpid/jndi/NameParserImpl.java37
-rw-r--r--java/client/src/main/java/org/apache/qpid/jndi/PropertiesFileInitialContextFactory.java369
-rw-r--r--java/client/src/main/java/org/apache/qpid/jndi/ReadOnlyContext.java527
-rw-r--r--java/client/src/main/java/org/apache/qpid/naming/ReadOnlyContext.java509
-rw-r--r--java/client/src/main/java/org/apache/qpid/naming/jndi.properties40
-rw-r--r--java/client/src/main/java/org/apache/qpid/nclient/MessagePartListener.java46
-rw-r--r--java/client/src/main/java/org/apache/qpid/nclient/util/ByteBufferMessage.java190
-rw-r--r--java/client/src/main/java/org/apache/qpid/nclient/util/MessageListener.java34
-rw-r--r--java/client/src/main/java/org/apache/qpid/nclient/util/MessagePartListenerAdapter.java88
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/IBMPerfTest/JNDIBindConnectionFactory.java185
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/IBMPerfTest/JNDIBindQueue.java213
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/IBMPerfTest/JNDIBindTopic.java212
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/IBMPerfTest/README.txt11
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/cluster/Client.java129
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/codec/BasicDeliverTest.java277
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/codec/Client.java133
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/codec/Server.java103
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/config/AMQConnectionFactoryInitialiser.java35
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/config/AbstractConfig.java69
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/config/ConnectionFactoryInitialiser.java29
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/config/Connector.java40
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/config/ConnectorConfig.java28
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/config/JBossConnectionFactoryInitialiser.java117
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/flow/ChannelFlowTest.java112
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/fragmentation/TestLargePublisher.java196
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/fragmentation/TestLargeSubscriber.java167
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/headers/Listener.java117
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/headers/MessageFactory.java175
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/headers/Publisher.java133
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/jndi/referenceable/Bind.java273
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/jndi/referenceable/Lookup.java196
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/jndi/referenceable/Unbind.java166
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/latency/LatencyTest.java153
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/mina/AcceptorTest.java102
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/mina/BlockingAcceptorTest.java93
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/mina/WriterTest.java271
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/multiconsumer/AMQTest.java269
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/pubsub1/TestPublisher.java176
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/pubsub1/TestSubscriber.java122
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/test/unit/client/connection/TestManyConnections.java95
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/test/unit/jndi/PropertiesFileInitialContextFactoryTest.java153
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/test/unit/jndi/example.properties38
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/topic/Config.java243
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/topic/Listener.java141
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/topic/MessageFactory.java155
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/topic/Publisher.java175
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/transacted/Config.java110
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/transacted/Ping.java45
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/transacted/Pong.java45
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/transacted/Relay.java127
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/transacted/Start.java44
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/weblogic/ServiceProvider.java151
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/weblogic/ServiceRequestingClient.java185
-rw-r--r--java/client/src/test/java/org/apache/mina/transport/vmpipe/support/VmPipeIdleStatusChecker.java125
-rw-r--r--java/client/src/test/java/org/apache/qpid/client/AMQQueueTest.java42
-rw-r--r--java/client/src/test/java/org/apache/qpid/client/MockAMQConnection.java94
-rw-r--r--java/client/src/test/java/org/apache/qpid/client/message/AbstractJMSMessageTest.java57
-rw-r--r--java/client/src/test/java/org/apache/qpid/client/message/TestMessageHelper.java46
-rw-r--r--java/client/src/test/java/org/apache/qpid/client/protocol/AMQProtocolHandlerTest.java289
-rw-r--r--java/client/src/test/java/org/apache/qpid/client/protocol/MockIoSession.java312
-rw-r--r--java/client/src/test/java/org/apache/qpid/jms/FailoverPolicyTest.java338
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/basic/FieldTableKeyEnumeratorTest.java96
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/basic/FieldTablePropertyTest.java62
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/client/BrokerDetails/BrokerDetailsTest.java99
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/client/channelclose/ChannelCloseMethodHandlerNoCloseOk.java97
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/client/channelclose/NoCloseOKStateManager.java65
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/client/connectionurl/ConnectionURLTest.java588
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/client/destinationurl/DestinationURLTest.java197
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/client/message/BytesMessageTest.java569
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/client/message/MapMessageTest.java383
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/client/message/StreamMessageTest.java623
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/client/message/TextMessageTest.java300
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/jndi/ConnectionFactoryTest.java75
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/jndi/JNDIPropertyFileTest.java70
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/jndi/JNDITest.properties28
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/message/MessageConverterTest.java140
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/message/NonQpidMessage.java420
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/message/TestAMQSession.java204
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/tests.properties45
-rw-r--r--java/client/test/bin/IBM-JNDI-Setup.bat69
-rwxr-xr-xjava/client/test/bin/IBM-JNDI-Setup.sh27
-rw-r--r--java/client/test/bin/IBM-Publisher.bat62
-rwxr-xr-xjava/client/test/bin/IBM-Publisher.sh22
-rw-r--r--java/client/test/bin/IBM-PutGet.bat62
-rwxr-xr-xjava/client/test/bin/IBM-PutGet.sh21
-rw-r--r--java/client/test/bin/IBM-README.txt19
-rw-r--r--java/client/test/bin/IBM-Receiver.bat62
-rwxr-xr-xjava/client/test/bin/IBM-Receiver.sh22
-rw-r--r--java/client/test/bin/IBM-Sender.bat62
-rwxr-xr-xjava/client/test/bin/IBM-Sender.sh22
-rw-r--r--java/client/test/bin/IBM-Subscriber.bat62
-rwxr-xr-xjava/client/test/bin/IBM-Subscriber.sh22
-rwxr-xr-xjava/client/test/bin/headersListener.sh22
-rwxr-xr-xjava/client/test/bin/headersListenerGroup.sh25
-rwxr-xr-xjava/client/test/bin/headersPublisher.sh22
-rwxr-xr-xjava/client/test/bin/run_many.sh30
-rwxr-xr-xjava/client/test/bin/serviceProvidingClient.sh24
-rwxr-xr-xjava/client/test/bin/serviceRequestingClient.sh27
-rwxr-xr-xjava/client/test/bin/testService.sh22
-rwxr-xr-xjava/client/test/bin/topicListener.sh23
-rwxr-xr-xjava/client/test/bin/topicPublisher.sh22
-rw-r--r--java/client/test/etc/ApacheDS.properties24
-rw-r--r--java/client/test/example_build.xml104
-rw-r--r--java/common.xml350
-rw-r--r--java/common/Composite.tpl350
-rw-r--r--java/common/Constant.tpl35
-rw-r--r--java/common/Enum.tpl57
-rw-r--r--java/common/Invoker.tpl73
-rw-r--r--java/common/MethodDelegate.tpl37
-rw-r--r--java/common/Option.tpl42
-rw-r--r--java/common/StructFactory.tpl60
-rw-r--r--java/common/Type.tpl84
-rwxr-xr-xjava/common/bin/qpid-jaddr33
-rwxr-xr-xjava/common/bin/qpid-run259
-rw-r--r--java/common/build.xml102
-rwxr-xr-xjava/common/codegen89
-rw-r--r--java/common/etc/qpid-run.conf25
-rw-r--r--java/common/etc/qpid-run.conf.dev26
-rw-r--r--java/common/genutil.py256
-rw-r--r--java/common/protocol-version.xml70
-rw-r--r--java/common/readme.txt4
-rwxr-xr-xjava/common/src/main/java/common.bnd25
-rw-r--r--java/common/src/main/java/org/apache/configuration/PropertyNameResolver.java129
-rw-r--r--java/common/src/main/java/org/apache/mina/common/FixedSizeByteBufferAllocator.java467
-rw-r--r--java/common/src/main/java/org/apache/mina/common/support/DefaultIoFuture.java227
-rw-r--r--java/common/src/main/java/org/apache/mina/common/support/IoServiceListenerSupport.java351
-rw-r--r--java/common/src/main/java/org/apache/mina/filter/WriteBufferFullExeception.java48
-rw-r--r--java/common/src/main/java/org/apache/mina/filter/WriteBufferLimitFilterBuilder.java272
-rw-r--r--java/common/src/main/java/org/apache/mina/filter/codec/OurCumulativeProtocolDecoder.java197
-rw-r--r--java/common/src/main/java/org/apache/mina/filter/codec/QpidProtocolCodecFilter.java440
-rw-r--r--java/common/src/main/java/org/apache/mina/transport/socket/nio/MultiThreadSocketAcceptor.java547
-rw-r--r--java/common/src/main/java/org/apache/mina/transport/socket/nio/MultiThreadSocketConnector.java486
-rw-r--r--java/common/src/main/java/org/apache/mina/transport/socket/nio/MultiThreadSocketFilterChain.java67
-rw-r--r--java/common/src/main/java/org/apache/mina/transport/socket/nio/MultiThreadSocketIoProcessor.java1026
-rw-r--r--java/common/src/main/java/org/apache/mina/transport/socket/nio/MultiThreadSocketSessionConfigImpl.java240
-rw-r--r--java/common/src/main/java/org/apache/mina/transport/socket/nio/MultiThreadSocketSessionImpl.java488
-rw-r--r--java/common/src/main/java/org/apache/mina/transport/vmpipe/QpidVmPipeConnector.java151
-rw-r--r--java/common/src/main/java/org/apache/qpid/AMQChannelClosedException.java41
-rw-r--r--java/common/src/main/java/org/apache/qpid/AMQChannelException.java59
-rw-r--r--java/common/src/main/java/org/apache/qpid/AMQConnectionClosedException.java44
-rw-r--r--java/common/src/main/java/org/apache/qpid/AMQConnectionException.java70
-rw-r--r--java/common/src/main/java/org/apache/qpid/AMQConnectionFailureException.java62
-rw-r--r--java/common/src/main/java/org/apache/qpid/AMQDisconnectedException.java39
-rw-r--r--java/common/src/main/java/org/apache/qpid/AMQException.java124
-rw-r--r--java/common/src/main/java/org/apache/qpid/AMQInternalException.java49
-rw-r--r--java/common/src/main/java/org/apache/qpid/AMQInvalidArgumentException.java45
-rw-r--r--java/common/src/main/java/org/apache/qpid/AMQInvalidRoutingKeyException.java39
-rw-r--r--java/common/src/main/java/org/apache/qpid/AMQPInvalidClassException.java42
-rw-r--r--java/common/src/main/java/org/apache/qpid/AMQProtocolException.java38
-rw-r--r--java/common/src/main/java/org/apache/qpid/AMQSecurityException.java54
-rw-r--r--java/common/src/main/java/org/apache/qpid/AMQStoreException.java48
-rw-r--r--java/common/src/main/java/org/apache/qpid/AMQTimeoutException.java39
-rw-r--r--java/common/src/main/java/org/apache/qpid/AMQUndeliveredException.java54
-rw-r--r--java/common/src/main/java/org/apache/qpid/AMQUnknownExchangeType.java43
-rw-r--r--java/common/src/main/java/org/apache/qpid/AMQUnresolvedAddressException.java50
-rw-r--r--java/common/src/main/java/org/apache/qpid/ConsoleOutput.java62
-rw-r--r--java/common/src/main/java/org/apache/qpid/QpidConfig.java111
-rw-r--r--java/common/src/main/java/org/apache/qpid/SerialException.java40
-rw-r--r--java/common/src/main/java/org/apache/qpid/ToyBroker.java208
-rw-r--r--java/common/src/main/java/org/apache/qpid/ToyClient.java108
-rw-r--r--java/common/src/main/java/org/apache/qpid/ToyExchange.java154
-rw-r--r--java/common/src/main/java/org/apache/qpid/api/Message.java126
-rw-r--r--java/common/src/main/java/org/apache/qpid/codec/AMQCodecFactory.java78
-rw-r--r--java/common/src/main/java/org/apache/qpid/codec/AMQDecoder.java340
-rw-r--r--java/common/src/main/java/org/apache/qpid/codec/AMQEncoder.java66
-rw-r--r--java/common/src/main/java/org/apache/qpid/common/AMQPFilterTypes.java61
-rw-r--r--java/common/src/main/java/org/apache/qpid/common/ClientProperties.java52
-rw-r--r--java/common/src/main/java/org/apache/qpid/common/Closeable.java27
-rw-r--r--java/common/src/main/java/org/apache/qpid/common/QpidProperties.java190
-rw-r--r--java/common/src/main/java/org/apache/qpid/configuration/Accessor.java273
-rw-r--r--java/common/src/main/java/org/apache/qpid/configuration/ClientProperties.java134
-rw-r--r--java/common/src/main/java/org/apache/qpid/configuration/Configured.java44
-rw-r--r--java/common/src/main/java/org/apache/qpid/configuration/PropertyException.java43
-rw-r--r--java/common/src/main/java/org/apache/qpid/configuration/PropertyUtils.java164
-rw-r--r--java/common/src/main/java/org/apache/qpid/configuration/QpidProperty.java181
-rw-r--r--java/common/src/main/java/org/apache/qpid/configuration/Validator.java31
-rw-r--r--java/common/src/main/java/org/apache/qpid/dtx/XidImpl.java259
-rw-r--r--java/common/src/main/java/org/apache/qpid/exchange/ExchangeDefaults.java67
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/AMQBody.java40
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/AMQDataBlock.java63
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockDecoder.java131
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockEncoder.java61
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/AMQFrame.java125
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/AMQFrameDecodingException.java47
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/AMQMethodBody.java83
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyFactory.java45
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyImpl.java258
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyInstanceFactory.java30
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/AMQMethodFactory.java90
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/AMQProtocolClassException.java39
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/AMQProtocolHeaderException.java41
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/AMQProtocolInstanceException.java39
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/AMQProtocolVersionException.java39
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/AMQShortString.java779
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/AMQShortStringTokenizer.java31
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/AMQType.java795
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/AMQTypeMap.java48
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/AMQTypedValue.java179
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/BasicContentHeaderProperties.java838
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/BodyFactory.java31
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/CommonContentHeaderProperties.java81
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/CompositeAMQDataBlock.java78
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/Content.java26
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/ContentBody.java121
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/ContentBodyFactory.java48
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/ContentHeaderBody.java141
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/ContentHeaderBodyFactory.java50
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/ContentHeaderProperties.java60
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/ContentHeaderPropertiesFactory.java59
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/DeferredDataBlock.java50
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/EncodableAMQDataBlock.java35
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/EncodingUtils.java1033
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/FieldTable.java1246
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/FieldTableFactory.java38
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/HeartbeatBody.java79
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/HeartbeatBodyFactory.java31
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/ProtocolInitiation.java223
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/SmallCompositeAMQDataBlock.java98
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/VersionSpecificRegistry.java198
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/abstraction/AbstractMethodConverter.java47
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/abstraction/ContentChunk.java32
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/abstraction/MessagePublishInfo.java38
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/abstraction/MessagePublishInfoConverter.java32
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/abstraction/MessagePublishInfoImpl.java85
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/abstraction/ProtocolVersionMethodConverter.java36
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/amqp_0_9/AMQMethodBody_0_9.java37
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/amqp_0_9/MethodConverter_0_9.java134
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/amqp_0_91/AMQMethodBody_0_91.java37
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/amqp_0_91/MethodConverter_0_91.java132
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/amqp_8_0/AMQMethodBody_8_0.java40
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/amqp_8_0/MethodConverter_8_0.java113
-rw-r--r--java/common/src/main/java/org/apache/qpid/messaging/Address.java75
-rw-r--r--java/common/src/main/java/org/apache/qpid/messaging/util/AddressParser.java380
-rw-r--r--java/common/src/main/java/org/apache/qpid/messaging/util/JAddr.java97
-rw-r--r--java/common/src/main/java/org/apache/qpid/messaging/util/LexError.java37
-rw-r--r--java/common/src/main/java/org/apache/qpid/messaging/util/Lexer.java84
-rw-r--r--java/common/src/main/java/org/apache/qpid/messaging/util/Lexicon.java103
-rw-r--r--java/common/src/main/java/org/apache/qpid/messaging/util/LineInfo.java93
-rw-r--r--java/common/src/main/java/org/apache/qpid/messaging/util/ParseError.java58
-rw-r--r--java/common/src/main/java/org/apache/qpid/messaging/util/Parser.java85
-rw-r--r--java/common/src/main/java/org/apache/qpid/messaging/util/PyPrint.java146
-rw-r--r--java/common/src/main/java/org/apache/qpid/messaging/util/Token.java106
-rw-r--r--java/common/src/main/java/org/apache/qpid/pool/Job.java253
-rw-r--r--java/common/src/main/java/org/apache/qpid/pool/ReadWriteJobQueue.java432
-rw-r--r--java/common/src/main/java/org/apache/qpid/pool/ReadWriteRunnable.java26
-rw-r--r--java/common/src/main/java/org/apache/qpid/pool/ReferenceCountingExecutorService.java215
-rw-r--r--java/common/src/main/java/org/apache/qpid/protocol/AMQConstant.java236
-rw-r--r--java/common/src/main/java/org/apache/qpid/protocol/AMQMethodEvent.java95
-rw-r--r--java/common/src/main/java/org/apache/qpid/protocol/AMQMethodListener.java70
-rw-r--r--java/common/src/main/java/org/apache/qpid/protocol/AMQProtocolWriter.java43
-rw-r--r--java/common/src/main/java/org/apache/qpid/protocol/AMQVersionAwareProtocolSession.java64
-rw-r--r--java/common/src/main/java/org/apache/qpid/protocol/ProtocolEngine.java61
-rw-r--r--java/common/src/main/java/org/apache/qpid/protocol/ProtocolEngineFactory.java31
-rw-r--r--java/common/src/main/java/org/apache/qpid/protocol/ProtocolVersionAware.java53
-rw-r--r--java/common/src/main/java/org/apache/qpid/security/AMQPCallbackHandler.java28
-rw-r--r--java/common/src/main/java/org/apache/qpid/security/UsernamePasswordCallbackHandler.java60
-rw-r--r--java/common/src/main/java/org/apache/qpid/ssl/SSLContextFactory.java195
-rw-r--r--java/common/src/main/java/org/apache/qpid/thread/DefaultThreadFactory.java45
-rw-r--r--java/common/src/main/java/org/apache/qpid/thread/LoggingUncaughtExceptionHandler.java60
-rw-r--r--java/common/src/main/java/org/apache/qpid/thread/QpidThreadExecutor.java42
-rw-r--r--java/common/src/main/java/org/apache/qpid/thread/RealtimeThreadFactory.java72
-rw-r--r--java/common/src/main/java/org/apache/qpid/thread/ThreadFactory.java28
-rw-r--r--java/common/src/main/java/org/apache/qpid/thread/Threading.java47
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/Binary.java154
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/Binding.java36
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/ClientDelegate.java320
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/Connection.java703
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/ConnectionDelegate.java102
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/ConnectionException.java70
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/ConnectionListener.java38
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/ConnectionSettings.java336
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/Field.java83
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/Future.java37
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/Header.java92
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/Method.java236
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/NetworkDriver.java63
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/NetworkDriverConfiguration.java44
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/OpenException.java34
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/ProtocolDelegate.java40
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/ProtocolError.java88
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/ProtocolEvent.java41
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/ProtocolHeader.java123
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/ProtocolVersionException.java62
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/ProtocolViolationException.java35
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/Range.java125
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/RangeSet.java152
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/Receiver.java38
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/Sender.java39
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/SenderException.java52
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/ServerDelegate.java203
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/Session.java1057
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/SessionClosedException.java49
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/SessionDelegate.java212
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/SessionException.java61
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/SessionListener.java42
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/Struct.java142
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/TransportBuilder.java78
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/TransportException.java51
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/codec/AbstractDecoder.java478
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/codec/AbstractEncoder.java621
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/codec/BBDecoder.java149
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/codec/BBEncoder.java357
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/codec/Decoder.java283
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/codec/Encodable.java44
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/codec/Encoder.java282
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/network/Assembler.java256
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/network/ConnectionBinding.java103
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/network/Disassembler.java233
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/network/Frame.java151
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/network/InputHandler.java205
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/network/NetworkDelegate.java42
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/network/NetworkEvent.java34
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/network/NetworkTransport.java38
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/network/Transport.java56
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/network/io/InputHandler_0_9.java130
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/network/io/IoAcceptor.java92
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/network/io/IoContext.java35
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/network/io/IoNetworkTransport.java116
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/network/io/IoReceiver.java162
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/network/io/IoSender.java307
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/network/io/IoTransport.java231
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/network/mina/MINANetworkDriver.java435
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/network/mina/MinaHandler.java274
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/network/mina/MinaSender.java90
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/network/nio/NioHandler.java135
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/network/nio/NioSender.java126
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/network/security/SecurityLayer.java185
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/network/security/sasl/SASLEncryptor.java66
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/network/security/sasl/SASLReceiver.java86
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/network/security/sasl/SASLSender.java123
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/network/security/ssl/QpidClientX509KeyManager.java100
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/network/security/ssl/SSLReceiver.java202
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/network/security/ssl/SSLSender.java274
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/network/security/ssl/SSLUtil.java197
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/util/Functions.java102
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/util/Logger.java130
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/util/SliceIterator.java59
-rw-r--r--java/common/src/main/java/org/apache/qpid/transport/util/Waiter.java63
-rw-r--r--java/common/src/main/java/org/apache/qpid/url/AMQBindingURL.java237
-rw-r--r--java/common/src/main/java/org/apache/qpid/url/BindingURL.java60
-rw-r--r--java/common/src/main/java/org/apache/qpid/url/BindingURLParser.java478
-rw-r--r--java/common/src/main/java/org/apache/qpid/url/URLHelper.java173
-rw-r--r--java/common/src/main/java/org/apache/qpid/url/URLSyntaxException.java97
-rw-r--r--java/common/src/main/java/org/apache/qpid/util/CommandLineParser.java695
-rw-r--r--java/common/src/main/java/org/apache/qpid/util/ConcurrentLinkedMessageQueueAtomicSize.java258
-rw-r--r--java/common/src/main/java/org/apache/qpid/util/ConcurrentLinkedQueueAtomicSize.java70
-rw-r--r--java/common/src/main/java/org/apache/qpid/util/ConcurrentLinkedQueueNoSize.java38
-rw-r--r--java/common/src/main/java/org/apache/qpid/util/FileUtils.java395
-rw-r--r--java/common/src/main/java/org/apache/qpid/util/MessageQueue.java43
-rw-r--r--java/common/src/main/java/org/apache/qpid/util/NameUUIDGen.java59
-rw-r--r--java/common/src/main/java/org/apache/qpid/util/NetMatcher.java264
-rw-r--r--java/common/src/main/java/org/apache/qpid/util/PrettyPrintingUtils.java75
-rw-r--r--java/common/src/main/java/org/apache/qpid/util/RandomUUIDGen.java39
-rw-r--r--java/common/src/main/java/org/apache/qpid/util/Serial.java108
-rw-r--r--java/common/src/main/java/org/apache/qpid/util/Strings.java260
-rw-r--r--java/common/src/main/java/org/apache/qpid/util/UUIDGen.java36
-rw-r--r--java/common/src/main/java/org/apache/qpid/util/UUIDs.java59
-rw-r--r--java/common/src/main/java/org/apache/qpid/util/concurrent/AlreadyUnblockedException.java34
-rw-r--r--java/common/src/main/java/org/apache/qpid/util/concurrent/BatchSynchQueue.java122
-rw-r--r--java/common/src/main/java/org/apache/qpid/util/concurrent/BatchSynchQueueBase.java834
-rw-r--r--java/common/src/main/java/org/apache/qpid/util/concurrent/BooleanLatch.java128
-rw-r--r--java/common/src/main/java/org/apache/qpid/util/concurrent/Capacity.java35
-rw-r--r--java/common/src/main/java/org/apache/qpid/util/concurrent/SynchBuffer.java50
-rw-r--r--java/common/src/main/java/org/apache/qpid/util/concurrent/SynchException.java52
-rw-r--r--java/common/src/main/java/org/apache/qpid/util/concurrent/SynchQueue.java48
-rw-r--r--java/common/src/main/java/org/apache/qpid/util/concurrent/SynchRecord.java74
-rw-r--r--java/common/src/main/java/org/apache/qpid/util/concurrent/SynchRef.java51
-rw-r--r--java/common/src/test/java/org/apache/mina/SocketIOTest/IOWriterClient.java396
-rw-r--r--java/common/src/test/java/org/apache/mina/SocketIOTest/IOWriterServer.java157
-rw-r--r--java/common/src/test/java/org/apache/qpid/AMQExceptionTest.java106
-rw-r--r--java/common/src/test/java/org/apache/qpid/codec/AMQDecoderTest.java151
-rw-r--r--java/common/src/test/java/org/apache/qpid/codec/MockAMQVersionAwareProtocolSession.java105
-rw-r--r--java/common/src/test/java/org/apache/qpid/framing/AMQShortStringTest.java109
-rw-r--r--java/common/src/test/java/org/apache/qpid/framing/BasicContentHeaderPropertiesTest.java188
-rw-r--r--java/common/src/test/java/org/apache/qpid/framing/PropertyFieldTableTest.java974
-rw-r--r--java/common/src/test/java/org/apache/qpid/framing/abstraction/MessagePublishInfoImplTest.java99
-rw-r--r--java/common/src/test/java/org/apache/qpid/pool/ReferenceCountingExecutorServiceTest.java159
-rw-r--r--java/common/src/test/java/org/apache/qpid/session/TestSession.java277
-rw-r--r--java/common/src/test/java/org/apache/qpid/test/utils/QpidTestCase.java130
-rw-r--r--java/common/src/test/java/org/apache/qpid/thread/ThreadFactoryTest.java104
-rw-r--r--java/common/src/test/java/org/apache/qpid/transport/ConnectionTest.java446
-rw-r--r--java/common/src/test/java/org/apache/qpid/transport/GenTest.java44
-rw-r--r--java/common/src/test/java/org/apache/qpid/transport/RangeSetTest.java238
-rw-r--r--java/common/src/test/java/org/apache/qpid/transport/TestNetworkDriver.java133
-rw-r--r--java/common/src/test/java/org/apache/qpid/transport/codec/BBEncoderTest.java47
-rw-r--r--java/common/src/test/java/org/apache/qpid/transport/network/mina/MINANetworkDriverTest.java494
-rw-r--r--java/common/src/test/java/org/apache/qpid/util/CommandLineParserTest.java554
-rw-r--r--java/common/src/test/java/org/apache/qpid/util/FileUtilsTest.java612
-rw-r--r--java/common/src/test/java/org/apache/qpid/util/PropertyUtilsTest.java48
-rw-r--r--java/common/src/test/java/org/apache/qpid/util/SerialTest.java82
-rw-r--r--java/common/templates/method/MethodBodyInterface.vm62
-rw-r--r--java/common/templates/method/version/MethodBodyClass.vm213
-rw-r--r--java/common/templates/model/ClientMethodDispatcherInterface.vm56
-rw-r--r--java/common/templates/model/MethodDispatcherInterface.vm39
-rw-r--r--java/common/templates/model/MethodRegistryClass.vm104
-rw-r--r--java/common/templates/model/ProtocolVersionListClass.vm201
-rw-r--r--java/common/templates/model/ServerMethodDispatcherInterface.vm56
-rw-r--r--java/common/templates/model/version/AmqpConstantsClass.vm37
-rw-r--r--java/common/templates/model/version/ClientMethodDispatcherInterface.vm55
-rw-r--r--java/common/templates/model/version/MethodDispatcherInterface.vm43
-rw-r--r--java/common/templates/model/version/MethodRegistryClass.vm193
-rw-r--r--java/common/templates/model/version/ServerMethodDispatcherInterface.vm55
-rw-r--r--java/common/templating.py119
-rw-r--r--java/doc/AMQBlazeDetailedDesign.vsdbin120320 -> 0 bytes
-rw-r--r--java/doc/FramingClassDiagram.vsdbin206848 -> 0 bytes
-rw-r--r--java/doc/Qpid-architecture.diabin2149 -> 0 bytes
-rw-r--r--java/doc/broker-0.5-network.diabin5187 -> 0 bytes
-rw-r--r--java/doc/broker-0.N-network-phase-1.diabin4283 -> 0 bytes
-rw-r--r--java/doc/broker-0.N-state.diabin2477 -> 0 bytes
-rw-r--r--java/doc/broker-overview.diabin1263 -> 0 bytes
-rw-r--r--java/doc/broker-priority-queue-subscription.diabin2991 -> 0 bytes
-rw-r--r--java/doc/broker-queue-subscription.diabin2129 -> 0 bytes
-rw-r--r--java/doc/client-0.5-connection-creation.diabin3158 -> 0 bytes
-rw-r--r--java/doc/client-0.5-network-processing.diabin5331 -> 0 bytes
-rw-r--r--java/doc/client-0.N-network-processing.diabin4039 -> 0 bytes
-rw-r--r--java/doc/common-0.N-network.diabin1858 -> 0 bytes
-rw-r--r--java/doc/network-driver-protocol-engine-sequence.diabin1826 -> 0 bytes
-rw-r--r--java/doc/noddy-network-blocks.diabin1877 -> 0 bytes
-rw-r--r--java/etc/code-style.xml272
-rw-r--r--java/etc/coding_standards.xml138
-rw-r--r--java/etc/license_header.txt20
-rw-r--r--java/etc/log4j.xml61
-rwxr-xr-xjava/genpom177
-rw-r--r--java/integrationtests/README.txt13
-rwxr-xr-xjava/integrationtests/bin/interoptests.py180
-rw-r--r--java/integrationtests/build.xml28
-rw-r--r--java/integrationtests/docs/RunningSustainedTests.txt17
-rw-r--r--java/integrationtests/jar-with-dependencies.xml47
-rw-r--r--java/integrationtests/src/main/java/org/apache/qpid/interop/clienttestcases/TestCase1DummyRun.java135
-rw-r--r--java/integrationtests/src/main/java/org/apache/qpid/interop/clienttestcases/TestCase2BasicP2P.java209
-rw-r--r--java/integrationtests/src/main/java/org/apache/qpid/interop/clienttestcases/TestCase3BasicPubSub.java239
-rw-r--r--java/integrationtests/src/main/java/org/apache/qpid/interop/clienttestcases/TestCase4P2PMessageSize.java214
-rw-r--r--java/integrationtests/src/main/java/org/apache/qpid/interop/clienttestcases/TestCase5PubSubMessageSize.java243
-rw-r--r--java/integrationtests/src/main/java/org/apache/qpid/interop/testcases/InteropTestCase1DummyRun.java84
-rw-r--r--java/integrationtests/src/main/java/org/apache/qpid/interop/testcases/InteropTestCase2BasicP2P.java90
-rw-r--r--java/integrationtests/src/main/java/org/apache/qpid/interop/testcases/InteropTestCase3BasicPubSub.java88
-rw-r--r--java/integrationtests/src/main/java/org/apache/qpid/interop/testcases/InteropTestCase4P2PMessageSize.java193
-rw-r--r--java/integrationtests/src/main/java/org/apache/qpid/interop/testcases/InteropTestCase5PubSubMessageSize.java193
-rw-r--r--java/integrationtests/src/main/java/org/apache/qpid/sustained/SustainedClientTestCase.java906
-rw-r--r--java/integrationtests/src/main/java/org/apache/qpid/sustained/SustainedTestCase.java126
-rw-r--r--java/integrationtests/src/resources/sustained-log4j.xml69
-rw-r--r--java/ivy.xml39
-rw-r--r--java/ivysettings-nexus.xml30
-rw-r--r--java/junit-toolkit/build.xml26
-rw-r--r--java/junit-toolkit/src/main/org/apache/qpid/junit/concurrency/DefaultThreadFactory.java48
-rw-r--r--java/junit-toolkit/src/main/org/apache/qpid/junit/concurrency/PossibleDeadlockException.java46
-rw-r--r--java/junit-toolkit/src/main/org/apache/qpid/junit/concurrency/TestRunnable.java239
-rw-r--r--java/junit-toolkit/src/main/org/apache/qpid/junit/concurrency/ThreadTestCoordinator.java486
-rw-r--r--java/junit-toolkit/src/main/org/apache/qpid/junit/concurrency/ThreadTestExample.java145
-rw-r--r--java/junit-toolkit/src/main/org/apache/qpid/junit/concurrency/package.html28
-rw-r--r--java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/AsymptoticTestCase.java303
-rw-r--r--java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/AsymptoticTestDecorator.java173
-rw-r--r--java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/BaseThrottle.java98
-rw-r--r--java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/BatchedThrottle.java94
-rw-r--r--java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/DurationTestDecorator.java205
-rw-r--r--java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/InstrumentedTest.java66
-rw-r--r--java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/NullResultPrinter.java92
-rw-r--r--java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/ParameterVariationTestDecorator.java175
-rw-r--r--java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/ScaledTestDecorator.java391
-rw-r--r--java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/SetupTaskAware.java55
-rw-r--r--java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/SetupTaskHandler.java92
-rw-r--r--java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/ShutdownHookable.java42
-rw-r--r--java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/SleepThrottle.java81
-rw-r--r--java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/TKTestResult.java654
-rw-r--r--java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/TKTestRunner.java694
-rw-r--r--java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/TestRunnerImprovedErrorHandling.java131
-rw-r--r--java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/TestThreadAware.java54
-rw-r--r--java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/Throttle.java73
-rw-r--r--java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/TimingController.java198
-rw-r--r--java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/TimingControllerAware.java43
-rw-r--r--java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/WrappedSuiteTestDecorator.java134
-rw-r--r--java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/listeners/CSVTestListener.java572
-rw-r--r--java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/listeners/ConsoleTestListener.java274
-rw-r--r--java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/listeners/TKTestListener.java142
-rw-r--r--java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/listeners/XMLTestListener.java410
-rw-r--r--java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/listeners/package.html27
-rw-r--r--java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/package.html33
-rw-r--r--java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/util/CommandLineParser.java787
-rw-r--r--java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/util/ContextualProperties.java494
-rw-r--r--java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/util/MathUtils.java428
-rw-r--r--java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/util/ParsedProperties.java390
-rw-r--r--java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/util/SizeOf.java94
-rw-r--r--java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/util/StackQueue.java131
-rw-r--r--java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/util/TestContextProperties.java202
-rw-r--r--java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/util/TestUtils.java54
-rw-r--r--java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/util/package.html27
-rw-r--r--java/lib/backport-util-concurrent-2.2.jarbin326319 -> 0 bytes
-rw-r--r--java/lib/bnd-0.0.384.jarbin668180 -> 0 bytes
-rw-r--r--java/lib/cobertura/README.txt10
-rw-r--r--java/lib/com.ibm.icu_3.8.1.v20080530.jarbin4467363 -> 0 bytes
-rw-r--r--java/lib/commons-beanutils-core-1.8.0.jarbin206035 -> 0 bytes
-rw-r--r--java/lib/commons-cli-1.0.jarbin30117 -> 0 bytes
-rw-r--r--java/lib/commons-codec-1.3.jarbin46725 -> 0 bytes
-rw-r--r--java/lib/commons-collections-3.2.jarbin571259 -> 0 bytes
-rw-r--r--java/lib/commons-configuration-1.6.jarbin298829 -> 0 bytes
-rw-r--r--java/lib/commons-digester-1.8.1.jarbin146108 -> 0 bytes
-rw-r--r--java/lib/commons-lang-2.2.jarbin243016 -> 0 bytes
-rw-r--r--java/lib/commons-logging-1.0.4.jarbin38015 -> 0 bytes
-rw-r--r--java/lib/derby-10.6.1.0.jarbin2623509 -> 0 bytes
-rw-r--r--java/lib/findbugs/README.txt30
-rw-r--r--java/lib/geronimo-jms_1.1_spec-1.0.jarbin28211 -> 0 bytes
-rw-r--r--java/lib/ivy/README.txt11
-rw-r--r--java/lib/javacc.jarbin378781 -> 0 bytes
-rw-r--r--java/lib/jetty-6.1.14.jarbin516429 -> 0 bytes
-rw-r--r--java/lib/jetty-servlet-tester-6.1.14.jarbin9206 -> 0 bytes
-rw-r--r--java/lib/jetty-util-6.1.14.jarbin163122 -> 0 bytes
-rw-r--r--java/lib/junit-3.8.1.jarbin121070 -> 0 bytes
-rw-r--r--java/lib/jython-2.5.0.jarbin8580107 -> 0 bytes
-rw-r--r--java/lib/log4j-1.2.12.jarbin358085 -> 0 bytes
-rw-r--r--java/lib/maven-ant-tasks-2.1.1.jarbin1314262 -> 0 bytes
-rwxr-xr-xjava/lib/mina-core-1.0.1.jarbin313338 -> 0 bytes
-rwxr-xr-xjava/lib/mina-filter-ssl-1.0.1.jarbin28950 -> 0 bytes
-rw-r--r--java/lib/org.apache.commons.codec_1.3.0.v20080530-1600.jarbin53757 -> 0 bytes
-rw-r--r--java/lib/org.apache.felix.framework-2.0.5.jarbin391763 -> 0 bytes
-rw-r--r--java/lib/org.eclipse.core.commands_3.4.0.I20080509-2000.jarbin105794 -> 0 bytes
-rw-r--r--java/lib/org.eclipse.core.contenttype_3.3.0.v20080604-1400.jarbin86969 -> 0 bytes
-rw-r--r--java/lib/org.eclipse.core.databinding_1.1.1.M20080827-0800b.jarbin347799 -> 0 bytes
-rw-r--r--java/lib/org.eclipse.core.expressions_3.4.0.v20080603-2000.jarbin83841 -> 0 bytes
-rw-r--r--java/lib/org.eclipse.core.jobs_3.4.0.v20080512.jarbin82491 -> 0 bytes
-rw-r--r--java/lib/org.eclipse.core.runtime.compatibility.registry_3.2.200.v20080610/META-INF/ECLIPSE.RSAbin3487 -> 0 bytes
-rw-r--r--java/lib/org.eclipse.core.runtime.compatibility.registry_3.2.200.v20080610/META-INF/ECLIPSE.SF17
-rw-r--r--java/lib/org.eclipse.core.runtime.compatibility.registry_3.2.200.v20080610/META-INF/MANIFEST.MF25
-rw-r--r--java/lib/org.eclipse.core.runtime.compatibility.registry_3.2.200.v20080610/META-INF/eclipse.inf3
-rw-r--r--java/lib/org.eclipse.core.runtime.compatibility.registry_3.2.200.v20080610/about.html28
-rw-r--r--java/lib/org.eclipse.core.runtime.compatibility.registry_3.2.200.v20080610/fragment.properties12
-rw-r--r--java/lib/org.eclipse.core.runtime.compatibility.registry_3.2.200.v20080610/runtime_registry_compatibility.jarbin10994 -> 0 bytes
-rw-r--r--java/lib/org.eclipse.core.runtime_3.4.0.v20080512.jarbin69019 -> 0 bytes
-rw-r--r--java/lib/org.eclipse.equinox.app_1.1.0.v20080421-2006.jarbin79866 -> 0 bytes
-rw-r--r--java/lib/org.eclipse.equinox.common_3.4.0.v20080421-2006.jarbin94649 -> 0 bytes
-rw-r--r--java/lib/org.eclipse.equinox.launcher.carbon.macosx_1.0.101.R34x_v20080731/META-INF/ECLIPSE.RSAbin3487 -> 0 bytes
-rw-r--r--java/lib/org.eclipse.equinox.launcher.carbon.macosx_1.0.101.R34x_v20080731/META-INF/ECLIPSE.SF17
-rw-r--r--java/lib/org.eclipse.equinox.launcher.carbon.macosx_1.0.101.R34x_v20080731/META-INF/MANIFEST.MF25
-rw-r--r--java/lib/org.eclipse.equinox.launcher.carbon.macosx_1.0.101.R34x_v20080731/META-INF/eclipse.inf3
-rw-r--r--java/lib/org.eclipse.equinox.launcher.carbon.macosx_1.0.101.R34x_v20080731/about.html28
-rw-r--r--java/lib/org.eclipse.equinox.launcher.carbon.macosx_1.0.101.R34x_v20080731/eclipse_1115.sobin118028 -> 0 bytes
-rw-r--r--java/lib/org.eclipse.equinox.launcher.carbon.macosx_1.0.101.R34x_v20080731/launcher.carbon.macosx.properties12
-rw-r--r--java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_1.0.101.R34x_v20080805/META-INF/ECLIPSE.RSAbin3487 -> 0 bytes
-rw-r--r--java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_1.0.101.R34x_v20080805/META-INF/ECLIPSE.SF17
-rw-r--r--java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_1.0.101.R34x_v20080805/META-INF/MANIFEST.MF25
-rw-r--r--java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_1.0.101.R34x_v20080805/META-INF/eclipse.inf3
-rw-r--r--java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_1.0.101.R34x_v20080805/about.html28
-rw-r--r--java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_1.0.101.R34x_v20080805/eclipse_1115.sobin133193 -> 0 bytes
-rw-r--r--java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_1.0.101.R34x_v20080805/launcher.gtk.linux.x86.properties12
-rw-r--r--java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.0.101.R34x_v20080731/META-INF/ECLIPSE.RSAbin3487 -> 0 bytes
-rw-r--r--java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.0.101.R34x_v20080731/META-INF/ECLIPSE.SF17
-rw-r--r--java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.0.101.R34x_v20080731/META-INF/MANIFEST.MF25
-rw-r--r--java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.0.101.R34x_v20080731/META-INF/eclipse.inf3
-rw-r--r--java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.0.101.R34x_v20080731/about.html28
-rw-r--r--java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.0.101.R34x_v20080731/eclipse_1115.sobin169725 -> 0 bytes
-rw-r--r--java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.0.101.R34x_v20080731/launcher.gtk.linux.x86_64.properties12
-rw-r--r--java/lib/org.eclipse.equinox.launcher.gtk.solaris.sparc_1.0.101.R34x_v20080731/META-INF/ECLIPSE.RSAbin3487 -> 0 bytes
-rw-r--r--java/lib/org.eclipse.equinox.launcher.gtk.solaris.sparc_1.0.101.R34x_v20080731/META-INF/ECLIPSE.SF17
-rw-r--r--java/lib/org.eclipse.equinox.launcher.gtk.solaris.sparc_1.0.101.R34x_v20080731/META-INF/MANIFEST.MF25
-rw-r--r--java/lib/org.eclipse.equinox.launcher.gtk.solaris.sparc_1.0.101.R34x_v20080731/META-INF/eclipse.inf3
-rw-r--r--java/lib/org.eclipse.equinox.launcher.gtk.solaris.sparc_1.0.101.R34x_v20080731/about.html28
-rw-r--r--java/lib/org.eclipse.equinox.launcher.gtk.solaris.sparc_1.0.101.R34x_v20080731/eclipse_1115.sobin76500 -> 0 bytes
-rw-r--r--java/lib/org.eclipse.equinox.launcher.gtk.solaris.sparc_1.0.101.R34x_v20080731/launcher.gtk.solaris.sparc.properties12
-rw-r--r--java/lib/org.eclipse.equinox.launcher.win32.win32.x86_1.0.101.R34x_v20080731/META-INF/ECLIPSE.RSAbin3487 -> 0 bytes
-rw-r--r--java/lib/org.eclipse.equinox.launcher.win32.win32.x86_1.0.101.R34x_v20080731/META-INF/ECLIPSE.SF17
-rw-r--r--java/lib/org.eclipse.equinox.launcher.win32.win32.x86_1.0.101.R34x_v20080731/META-INF/MANIFEST.MF25
-rw-r--r--java/lib/org.eclipse.equinox.launcher.win32.win32.x86_1.0.101.R34x_v20080731/META-INF/eclipse.inf3
-rw-r--r--java/lib/org.eclipse.equinox.launcher.win32.win32.x86_1.0.101.R34x_v20080731/about.html28
-rw-r--r--java/lib/org.eclipse.equinox.launcher.win32.win32.x86_1.0.101.R34x_v20080731/eclipse_1115.dllbin81920 -> 0 bytes
-rw-r--r--java/lib/org.eclipse.equinox.launcher.win32.win32.x86_1.0.101.R34x_v20080731/launcher.win32.win32.x86.properties12
-rw-r--r--java/lib/org.eclipse.equinox.launcher_1.0.101.R34x_v20080819.jarbin43682 -> 0 bytes
-rw-r--r--java/lib/org.eclipse.equinox.preferences_3.2.201.R34x_v20080709.jarbin104280 -> 0 bytes
-rw-r--r--java/lib/org.eclipse.equinox.registry_3.4.0.v20080516-0950.jarbin172936 -> 0 bytes
-rw-r--r--java/lib/org.eclipse.help_3.3.101.v20080702_34x.jarbin216698 -> 0 bytes
-rw-r--r--java/lib/org.eclipse.jface.databinding_1.2.1.M20080827-0800a.jarbin196505 -> 0 bytes
-rw-r--r--java/lib/org.eclipse.jface_3.4.1.M20080827-2000.jarbin1040433 -> 0 bytes
-rw-r--r--java/lib/org.eclipse.osgi_3.4.2.R34x_v20080826-1230.jarbin997883 -> 0 bytes
-rw-r--r--java/lib/org.eclipse.swt.carbon.macosx_3.4.1.v3449c.jarbin1852007 -> 0 bytes
-rw-r--r--java/lib/org.eclipse.swt.gtk.linux.x86_3.4.1.v3449c.jarbin2006608 -> 0 bytes
-rw-r--r--java/lib/org.eclipse.swt.gtk.linux.x86_64_3.4.1.v3449c.jarbin2123120 -> 0 bytes
-rw-r--r--java/lib/org.eclipse.swt.gtk.solaris.sparc_3.4.1.v3449c.jarbin1877410 -> 0 bytes
-rw-r--r--java/lib/org.eclipse.swt.win32.win32.x86_3.4.1.v3449c.jarbin2123125 -> 0 bytes
-rw-r--r--java/lib/org.eclipse.swt_3.4.1.v3449c.jarbin15807 -> 0 bytes
-rw-r--r--java/lib/org.eclipse.ui.forms_3.3.101.v20080708_34x.jarbin298053 -> 0 bytes
-rw-r--r--java/lib/org.eclipse.ui.workbench_3.4.1.M20080827-0800a.jarbin3922042 -> 0 bytes
-rw-r--r--java/lib/org.eclipse.ui_3.4.1.M20080910-0800.jarbin145322 -> 0 bytes
-rw-r--r--java/lib/poms/backport-util-concurrent-2.2.xml22
-rw-r--r--java/lib/poms/commons-beanutils-core-1.8.0.xml22
-rw-r--r--java/lib/poms/commons-cli-1.0.xml22
-rw-r--r--java/lib/poms/commons-codec-1.3.xml22
-rw-r--r--java/lib/poms/commons-collections-3.2.xml22
-rw-r--r--java/lib/poms/commons-configuration-1.6.xml22
-rw-r--r--java/lib/poms/commons-digester-1.8.1.xml22
-rw-r--r--java/lib/poms/commons-lang-2.2.xml22
-rw-r--r--java/lib/poms/commons-logging-1.0.4.xml22
-rw-r--r--java/lib/poms/commons-pool-1.4.xml22
-rw-r--r--java/lib/poms/derby-10.6.1.0.xml22
-rw-r--r--java/lib/poms/geronimo-jms_1.1_spec-1.0.xml22
-rw-r--r--java/lib/poms/junit-3.8.1.xml22
-rw-r--r--java/lib/poms/log4j-1.2.12.xml22
-rw-r--r--java/lib/poms/mina-core-1.0.1.xml22
-rw-r--r--java/lib/poms/mina-filter-ssl-1.0.1.xml22
-rw-r--r--java/lib/poms/org.apache.felix.framework-2.0.5.xml22
-rw-r--r--java/lib/poms/org.osgi.core-1.0.0.xml22
-rw-r--r--java/lib/poms/slf4j-api-1.6.1.xml22
-rw-r--r--java/lib/poms/slf4j-log4j12-1.6.1.xml22
-rw-r--r--java/lib/poms/xalan-2.7.0.xml22
-rw-r--r--java/lib/servlet-api.jarbin88224 -> 0 bytes
-rw-r--r--java/lib/slf4j-api-1.6.1.jarbin25496 -> 0 bytes
-rw-r--r--java/lib/slf4j-log4j12-1.6.1.jarbin9753 -> 0 bytes
-rw-r--r--java/lib/xalan-2.7.0.jarbin2730442 -> 0 bytes
-rw-r--r--java/management/common/build.xml26
-rw-r--r--java/management/common/src/main/java/management-common.bnd27
-rw-r--r--java/management/common/src/main/java/org/apache/qpid/management/common/JMXConnnectionFactory.java290
-rw-r--r--java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/ConfigurationManagement.java41
-rw-r--r--java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/LoggingManagement.java164
-rw-r--r--java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/ManagedBroker.java248
-rw-r--r--java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/ManagedConnection.java271
-rw-r--r--java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/ManagedExchange.java133
-rw-r--r--java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/ManagedQueue.java438
-rw-r--r--java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/ServerInformation.java202
-rw-r--r--java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/UserManagement.java214
-rw-r--r--java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/annotations/MBeanAttribute.java41
-rw-r--r--java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/annotations/MBeanConstructor.java39
-rw-r--r--java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/annotations/MBeanDescription.java38
-rw-r--r--java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/annotations/MBeanOperation.java43
-rw-r--r--java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/annotations/MBeanOperationParameter.java37
-rw-r--r--java/management/common/src/main/java/org/apache/qpid/management/common/sasl/CRAMMD5HashedSaslClientFactory.java60
-rw-r--r--java/management/common/src/main/java/org/apache/qpid/management/common/sasl/ClientSaslFactory.java54
-rw-r--r--java/management/common/src/main/java/org/apache/qpid/management/common/sasl/Constants.java33
-rw-r--r--java/management/common/src/main/java/org/apache/qpid/management/common/sasl/JCAProvider.java56
-rw-r--r--java/management/common/src/main/java/org/apache/qpid/management/common/sasl/PlainSaslClient.java203
-rw-r--r--java/management/common/src/main/java/org/apache/qpid/management/common/sasl/SaslProvider.java35
-rw-r--r--java/management/common/src/main/java/org/apache/qpid/management/common/sasl/UserPasswordCallbackHandler.java73
-rw-r--r--java/management/common/src/main/java/org/apache/qpid/management/common/sasl/UsernameHashedPasswordCallbackHandler.java108
-rw-r--r--java/management/common/src/test/java/org/apache/qpid/management/common/mbeans/ManagedQueueTest.java80
-rw-r--r--java/management/eclipse-plugin/META-INF/MANIFEST.MF22
-rw-r--r--java/management/eclipse-plugin/build-release-common.properties33
-rw-r--r--java/management/eclipse-plugin/build-release-linux-gtk-x86.properties36
-rw-r--r--java/management/eclipse-plugin/build-release-linux-gtk-x86_64.properties36
-rw-r--r--java/management/eclipse-plugin/build-release-macosx.properties40
-rw-r--r--java/management/eclipse-plugin/build-release-macosx.xml101
-rw-r--r--java/management/eclipse-plugin/build-release-solaris-gtk-sparc.properties39
-rw-r--r--java/management/eclipse-plugin/build-release-win32-win32-x86.properties34
-rw-r--r--java/management/eclipse-plugin/build-release.xml172
-rw-r--r--java/management/eclipse-plugin/build.xml88
-rw-r--r--java/management/eclipse-plugin/icons/add.gifbin318 -> 0 bytes
-rw-r--r--java/management/eclipse-plugin/icons/back.gifbin327 -> 0 bytes
-rw-r--r--java/management/eclipse-plugin/icons/configuration_management.gifbin343 -> 0 bytes
-rw-r--r--java/management/eclipse-plugin/icons/delete.gifbin143 -> 0 bytes
-rw-r--r--java/management/eclipse-plugin/icons/failure.gifbin353 -> 0 bytes
-rw-r--r--java/management/eclipse-plugin/icons/icon_ClosedFolder.gifbin160 -> 0 bytes
-rw-r--r--java/management/eclipse-plugin/icons/icon_OpenFolder.gifbin152 -> 0 bytes
-rw-r--r--java/management/eclipse-plugin/icons/logging_management.gifbin381 -> 0 bytes
-rw-r--r--java/management/eclipse-plugin/icons/mbean_view.pngbin2046 -> 0 bytes
-rw-r--r--java/management/eclipse-plugin/icons/notifications.gifbin104 -> 0 bytes
-rw-r--r--java/management/eclipse-plugin/icons/qpidConnections.gifbin200 -> 0 bytes
-rw-r--r--java/management/eclipse-plugin/icons/qpidmc.gifbin1225 -> 0 bytes
-rw-r--r--java/management/eclipse-plugin/icons/qpidmc16.gifbin928 -> 0 bytes
-rw-r--r--java/management/eclipse-plugin/icons/qpidmc32.bmpbin1139 -> 0 bytes
-rw-r--r--java/management/eclipse-plugin/icons/qpidmc32.gifbin1139 -> 0 bytes
-rw-r--r--java/management/eclipse-plugin/icons/reconnect.gifbin327 -> 0 bytes
-rw-r--r--java/management/eclipse-plugin/icons/refresh.gifbin336 -> 0 bytes
-rw-r--r--java/management/eclipse-plugin/icons/server_information.gifbin614 -> 0 bytes
-rw-r--r--java/management/eclipse-plugin/icons/splash.bmpbin275178 -> 0 bytes
-rw-r--r--java/management/eclipse-plugin/icons/stop.gifbin215 -> 0 bytes
-rw-r--r--java/management/eclipse-plugin/icons/success.gifbin343 -> 0 bytes
-rw-r--r--java/management/eclipse-plugin/icons/user_management.gifbin597 -> 0 bytes
-rw-r--r--java/management/eclipse-plugin/icons/virtualhost_manager.gifbin607 -> 0 bytes
-rw-r--r--java/management/eclipse-plugin/plugin.properties20
-rw-r--r--java/management/eclipse-plugin/plugin.xml225
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/Activator.java83
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ApiVersion.java110
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/Application.java63
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ApplicationActionBarAdvisor.java96
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ApplicationRegistry.java189
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ApplicationWorkbenchAdvisor.java46
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ApplicationWorkbenchWindowAdvisor.java65
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/Constants.java153
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ManagedBean.java176
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ManagedObject.java40
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ManagedServer.java84
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/Perspective.java46
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/RefreshIntervalComboPanel.java131
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ServerRegistry.java264
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/AbstractAction.java220
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/AddServer.java313
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/BackAction.java59
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/CloseConnection.java56
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/ReconnectServer.java264
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/Refresh.java53
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/RemoveServer.java50
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/VersionAction.java94
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/exceptions/InfoRequiredException.java36
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/exceptions/ManagementConsoleException.java31
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/ClientListener.java84
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/ClientNotificationListener.java40
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/JMXManagedObject.java71
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/JMXServerRegistry.java612
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/MBeanUtility.java619
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/AttributeData.java96
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/ManagedAttributeModel.java118
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/NotificationInfoModel.java51
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/NotificationObject.java132
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/OperationData.java110
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/OperationDataModel.java72
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/ParameterData.java95
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/AttributesTabControl.java922
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/INotificationViewer.java32
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/MBeanTabFolderFactory.java466
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/MBeanView.java605
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/NavigationView.java1372
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/NotificationsTabControl.java388
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/NumberVerifyListener.java46
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/OperationTabControl.java920
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/TabControl.java103
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/TreeObject.java126
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/VHNotificationsTabControl.java484
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/ViewUtility.java1032
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/connection/ConnectionOperationsTabControl.java545
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/exchange/ExchangeOperationsTabControl.java722
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/exchange/HeadersExchangeOperationsTabControl.java711
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/logging/ConfigurationFileTabControl.java591
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/logging/LoggingTableContentProvider.java52
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/logging/LoggingTableLabelProvider.java59
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/logging/LoggingTableSorter.java90
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/logging/RuntimeTabControl.java595
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/queue/QueueOperationsTabControl.java1111
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/type/ConnectionTypeTabControl.java50
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/type/ExchangeTypeTabControl.java45
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/type/MBeanTypeTabControl.java456
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/type/QueueTypeTabControl.java786
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/users/UserManagementTabControl.java925
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/vhost/VHostTabControl.java871
-rw-r--r--java/management/eclipse-plugin/src/main/resources/.eclipseproduct23
-rw-r--r--java/management/eclipse-plugin/src/main/resources/jmxremote.sasl-plugin/MANIFEST.MF20
-rw-r--r--java/management/eclipse-plugin/src/main/resources/linux-gtk-x86/Configuration/config.ini49
-rw-r--r--java/management/eclipse-plugin/src/main/resources/linux-gtk-x86/libcairo-swt.sobin266168 -> 0 bytes
-rw-r--r--java/management/eclipse-plugin/src/main/resources/linux-gtk-x86/qpidmcbin52576 -> 0 bytes
-rw-r--r--java/management/eclipse-plugin/src/main/resources/linux-gtk-x86/qpidmc.ini37
-rw-r--r--java/management/eclipse-plugin/src/main/resources/linux-gtk-x86_64/Configuration/config.ini49
-rw-r--r--java/management/eclipse-plugin/src/main/resources/linux-gtk-x86_64/libcairo-swt.sobin335360 -> 0 bytes
-rw-r--r--java/management/eclipse-plugin/src/main/resources/linux-gtk-x86_64/qpidmcbin67927 -> 0 bytes
-rw-r--r--java/management/eclipse-plugin/src/main/resources/linux-gtk-x86_64/qpidmc.ini37
-rw-r--r--java/management/eclipse-plugin/src/main/resources/macosx/Configuration/config.ini49
-rw-r--r--java/management/eclipse-plugin/src/main/resources/macosx/Contents/Info.plist55
-rwxr-xr-xjava/management/eclipse-plugin/src/main/resources/macosx/Contents/MacOS/qpidmcbin59200 -> 0 bytes
-rw-r--r--java/management/eclipse-plugin/src/main/resources/macosx/Contents/MacOS/qpidmc.ini42
-rw-r--r--java/management/eclipse-plugin/src/main/resources/macosx/Contents/Resources/Console.icnsbin51007 -> 0 bytes
-rw-r--r--java/management/eclipse-plugin/src/main/resources/solaris-gtk-sparc/Configuration/config.ini49
-rw-r--r--java/management/eclipse-plugin/src/main/resources/solaris-gtk-sparc/Qpidmc.l.pm311
-rw-r--r--java/management/eclipse-plugin/src/main/resources/solaris-gtk-sparc/Qpidmc.m.pm295
-rw-r--r--java/management/eclipse-plugin/src/main/resources/solaris-gtk-sparc/Qpidmc.s.pm287
-rw-r--r--java/management/eclipse-plugin/src/main/resources/solaris-gtk-sparc/Qpidmc.t.pm279
-rwxr-xr-xjava/management/eclipse-plugin/src/main/resources/solaris-gtk-sparc/qpidmcbin31668 -> 0 bytes
-rw-r--r--java/management/eclipse-plugin/src/main/resources/solaris-gtk-sparc/qpidmc.ini40
-rw-r--r--java/management/eclipse-plugin/src/main/resources/win32-win32-x86/Configuration/config.ini49
-rw-r--r--java/management/eclipse-plugin/src/main/resources/win32-win32-x86/qpidmc.exebin57344 -> 0 bytes
-rw-r--r--java/management/eclipse-plugin/src/main/resources/win32-win32-x86/qpidmc.ini36
-rw-r--r--java/management/eclipse-plugin/src/test/java/org/apache/qpid/management/ui/ApiVersionTest.java177
-rw-r--r--java/management/eclipse-plugin/src/test/java/org/apache/qpid/management/ui/ApplicationRegistryTest.java43
-rw-r--r--java/management/eclipse-plugin/src/test/java/org/apache/qpid/management/ui/ManagementConsoleTest.java122
-rw-r--r--java/management/example/build.xml27
-rw-r--r--java/management/example/src/main/java/org/apache/qpid/example/jmxexample/AddQueue.java149
-rw-r--r--java/management/example/src/main/java/org/apache/qpid/example/jmxexample/DeleteMessagesFromTopOfTmp.java119
-rw-r--r--java/management/example/src/main/java/org/apache/qpid/example/jmxexample/QueueInformation.java362
-rw-r--r--java/maven-settings.xml2
-rw-r--r--java/module.xml909
-rw-r--r--java/perftests/RunningPerformanceTests.txt141
-rwxr-xr-xjava/perftests/bin/monitoring/monitor-broker.sh221
-rwxr-xr-xjava/perftests/bin/monitoring/runTests.sh148
-rwxr-xr-xjava/perftests/bin/monitoring/stop-monitored-broker.sh124
-rwxr-xr-xjava/perftests/bin/processing/process.sh388
-rwxr-xr-xjava/perftests/bin/processing/processAll.sh58
-rwxr-xr-xjava/perftests/bin/processing/processTests.py850
-rwxr-xr-xjava/perftests/bin/run_many.sh30
-rwxr-xr-xjava/perftests/bin/topicListener.sh32
-rwxr-xr-xjava/perftests/bin/topicPublisher.sh31
-rw-r--r--java/perftests/build.xml339
-rw-r--r--java/perftests/dist-zip.xml45
-rw-r--r--java/perftests/etc/jndi/activemq.properties20
-rw-r--r--java/perftests/etc/jndi/failovertest.properties19
-rw-r--r--java/perftests/etc/jndi/perftests.properties19
-rw-r--r--java/perftests/etc/jndi/swiftmq.properties20
-rw-r--r--java/perftests/etc/perftests.log4j46
-rwxr-xr-xjava/perftests/etc/scripts/CTQ-Qpid-1.sh21
-rwxr-xr-xjava/perftests/etc/scripts/CTQ-Qpid-2.sh21
-rwxr-xr-xjava/perftests/etc/scripts/CTQ-Qpid-3.sh21
-rwxr-xr-xjava/perftests/etc/scripts/CTQ-Qpid-4.sh21
-rwxr-xr-xjava/perftests/etc/scripts/CTQ-Qpid-5.sh21
-rwxr-xr-xjava/perftests/etc/scripts/CTQ-Qpid-6.sh21
-rwxr-xr-xjava/perftests/etc/scripts/Connections.sh20
-rwxr-xr-xjava/perftests/etc/scripts/JobQueue.sh20
-rwxr-xr-xjava/perftests/etc/scripts/Latency.sh21
-rwxr-xr-xjava/perftests/etc/scripts/MessageSize.sh20
-rwxr-xr-xjava/perftests/etc/scripts/PT-Qpid-13.sh42
-rwxr-xr-xjava/perftests/etc/scripts/PT-Qpid-14.sh41
-rwxr-xr-xjava/perftests/etc/scripts/Reliability.sh20
-rwxr-xr-xjava/perftests/etc/scripts/RunAll.sh23
-rwxr-xr-xjava/perftests/etc/scripts/RunCore.sh22
-rw-r--r--java/perftests/etc/scripts/Test-ActiveMQ.sh32
-rw-r--r--java/perftests/etc/scripts/Test-SwiftMQ.sh30
-rwxr-xr-xjava/perftests/etc/scripts/Throughput.sh20
-rwxr-xr-xjava/perftests/etc/scripts/drainBroker.sh41
-rwxr-xr-xjava/perftests/etc/scripts/extractResults.sh34
-rwxr-xr-xjava/perftests/etc/scripts/extractThroughputResults.sh51
-rwxr-xr-xjava/perftests/etc/scripts/fillBroker.sh41
-rwxr-xr-xjava/perftests/etc/scripts/sendAndWaitClient.sh22
-rwxr-xr-xjava/perftests/etc/scripts/testWithPreFill.sh41
-rw-r--r--java/perftests/generate-scripts74
-rw-r--r--java/perftests/jar-with-dependencies.xml91
-rw-r--r--java/perftests/scripts.xml328
-rw-r--r--java/perftests/src/main/java/org/apache/qpid/client/message/TestMessageFactory.java120
-rw-r--r--java/perftests/src/main/java/org/apache/qpid/config/AMQConnectionFactoryInitialiser.java35
-rw-r--r--java/perftests/src/main/java/org/apache/qpid/config/AbstractConfig.java69
-rw-r--r--java/perftests/src/main/java/org/apache/qpid/config/ConnectionFactoryInitialiser.java29
-rw-r--r--java/perftests/src/main/java/org/apache/qpid/config/Connector.java40
-rw-r--r--java/perftests/src/main/java/org/apache/qpid/config/ConnectorConfig.java28
-rw-r--r--java/perftests/src/main/java/org/apache/qpid/config/JBossConnectionFactoryInitialiser.java112
-rw-r--r--java/perftests/src/main/java/org/apache/qpid/oldtopic/Config.java243
-rw-r--r--java/perftests/src/main/java/org/apache/qpid/oldtopic/Listener.java141
-rw-r--r--java/perftests/src/main/java/org/apache/qpid/oldtopic/MessageFactory.java153
-rw-r--r--java/perftests/src/main/java/org/apache/qpid/oldtopic/Publisher.java175
-rw-r--r--java/perftests/src/main/java/org/apache/qpid/ping/PingAsyncTestPerf.java322
-rw-r--r--java/perftests/src/main/java/org/apache/qpid/ping/PingClient.java112
-rw-r--r--java/perftests/src/main/java/org/apache/qpid/ping/PingDurableClient.java452
-rw-r--r--java/perftests/src/main/java/org/apache/qpid/ping/PingLatencyTestPerf.java311
-rw-r--r--java/perftests/src/main/java/org/apache/qpid/ping/PingSendOnlyClient.java93
-rw-r--r--java/perftests/src/main/java/org/apache/qpid/ping/PingTestPerf.java281
-rw-r--r--java/perftests/src/main/java/org/apache/qpid/requestreply/PingPongBouncer.java453
-rw-r--r--java/perftests/src/main/java/org/apache/qpid/requestreply/PingPongProducer.java1833
-rw-r--r--java/perftests/src/main/java/org/apache/qpid/requestreply/PingPongTestPerf.java251
-rw-r--r--java/perftests/src/main/java/org/apache/qpid/test/testcases/MessageThroughputPerf.java207
-rw-r--r--java/perftests/src/main/java/org/apache/qpid/topic/Config.java326
-rw-r--r--java/perftests/src/main/java/org/apache/qpid/topic/Listener.java303
-rw-r--r--java/perftests/src/main/java/org/apache/qpid/topic/MessageFactory.java157
-rw-r--r--java/perftests/src/main/java/org/apache/qpid/topic/Publisher.java186
-rw-r--r--java/perftests/src/main/java/org/apache/qpid/topic/TopicWithSelectorsTransientVolumeTest.java344
-rw-r--r--java/perftests/src/main/java/org/apache/qpid/topic/topicselectors.properties24
-rw-r--r--java/release-docs/RELEASE_NOTES.txt21
-rw-r--r--java/resources/LICENSE826
-rw-r--r--java/resources/NOTICE113
-rw-r--r--java/resources/README.txt40
-rw-r--r--java/systests/build.xml29
-rw-r--r--java/systests/etc/bin/fail.py88
-rwxr-xr-xjava/systests/etc/bin/testclients.sh23
-rw-r--r--java/systests/etc/config-systests-ServerConfigurationTest-New.xml77
-rw-r--r--java/systests/etc/config-systests-ServerConfigurationTest-Old.xml91
-rw-r--r--java/systests/etc/config-systests-acl-settings.xml26
-rw-r--r--java/systests/etc/config-systests-acl.xml30
-rw-r--r--java/systests/etc/config-systests-aclv2-settings.xml30
-rw-r--r--java/systests/etc/config-systests-aclv2.xml30
-rw-r--r--java/systests/etc/config-systests-derby-settings.xml26
-rw-r--r--java/systests/etc/config-systests-derby.xml30
-rw-r--r--java/systests/etc/config-systests-firewall-2.xml108
-rw-r--r--java/systests/etc/config-systests-firewall-3.xml110
-rw-r--r--java/systests/etc/config-systests-firewall-settings.xml30
-rw-r--r--java/systests/etc/config-systests-firewall.xml31
-rw-r--r--java/systests/etc/config-systests-settings.xml32
-rw-r--r--java/systests/etc/config-systests.xml29
-rw-r--r--java/systests/etc/global-default.txt31
-rw-r--r--java/systests/etc/global-externaladminacl-changeloggerleveldenied.txt24
-rw-r--r--java/systests/etc/global-externaladminacl-getallloggerlevelsdenied.txt25
-rw-r--r--java/systests/etc/test-default.txt73
-rw-r--r--java/systests/etc/test-externalacljmx-deleteexchangefailure.txt26
-rw-r--r--java/systests/etc/test-externalacljmx.txt35
-rw-r--r--java/systests/etc/test-logging.txt23
-rw-r--r--java/systests/etc/test2-default.txt21
-rw-r--r--java/systests/etc/virtualhosts-ServerConfigurationTest-New.xml45
-rw-r--r--java/systests/etc/virtualhosts-systests-acl-settings.xml180
-rw-r--r--java/systests/etc/virtualhosts-systests-acl.xml29
-rw-r--r--java/systests/etc/virtualhosts-systests-aclv2-settings.xml48
-rw-r--r--java/systests/etc/virtualhosts-systests-aclv2.xml29
-rw-r--r--java/systests/etc/virtualhosts-systests-derby-settings.xml54
-rw-r--r--java/systests/etc/virtualhosts-systests-derby.xml29
-rw-r--r--java/systests/etc/virtualhosts-systests-firewall-2.xml47
-rw-r--r--java/systests/etc/virtualhosts-systests-firewall-3.xml47
-rw-r--r--java/systests/etc/virtualhosts-systests-firewall.xml29
-rw-r--r--java/systests/etc/virtualhosts-systests.xml28
-rw-r--r--java/systests/src/main/java/org/apache/mina/transport/vmpipe/support/VmPipeIdleStatusChecker.java125
-rw-r--r--java/systests/src/main/java/org/apache/qpid/client/AMQQueueDeferredOrderingTest.java145
-rw-r--r--java/systests/src/main/java/org/apache/qpid/client/AMQTestConnection_0_10.java34
-rw-r--r--java/systests/src/main/java/org/apache/qpid/client/DispatcherTest.java238
-rw-r--r--java/systests/src/main/java/org/apache/qpid/client/MessageListenerMultiConsumerImmediatePrefetch.java44
-rw-r--r--java/systests/src/main/java/org/apache/qpid/client/MessageListenerMultiConsumerTest.java253
-rw-r--r--java/systests/src/main/java/org/apache/qpid/client/MessageListenerTest.java261
-rw-r--r--java/systests/src/main/java/org/apache/qpid/client/MultipleJCAProviderRegistrationTest.java82
-rw-r--r--java/systests/src/main/java/org/apache/qpid/client/ResetMessageListenerTest.java229
-rw-r--r--java/systests/src/main/java/org/apache/qpid/client/SessionCreateTest.java63
-rw-r--r--java/systests/src/main/java/org/apache/qpid/client/message/AMQPEncodedMapMessageTest.java283
-rw-r--r--java/systests/src/main/java/org/apache/qpid/client/message/NonQpidObjectMessage.java236
-rw-r--r--java/systests/src/main/java/org/apache/qpid/client/ssl/SSLTest.java181
-rw-r--r--java/systests/src/main/java/org/apache/qpid/management/jmx/ManagementActorLoggingTest.java536
-rw-r--r--java/systests/src/main/java/org/apache/qpid/management/jmx/MessageConnectionStatisticsTest.java102
-rw-r--r--java/systests/src/main/java/org/apache/qpid/management/jmx/MessageStatisticsConfigurationTest.java177
-rw-r--r--java/systests/src/main/java/org/apache/qpid/management/jmx/MessageStatisticsDeliveryTest.java110
-rw-r--r--java/systests/src/main/java/org/apache/qpid/management/jmx/MessageStatisticsReportingTest.java90
-rw-r--r--java/systests/src/main/java/org/apache/qpid/management/jmx/MessageStatisticsTest.java233
-rw-r--r--java/systests/src/main/java/org/apache/qpid/management/jmx/MessageStatisticsTestCase.java128
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/BrokerStartupTest.java149
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/configuration/ServerConfigurationFileTest.java89
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/exchange/MessagingTestConfigProperties.java308
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/exchange/ReturnUnroutableMandatoryMessageTest.java309
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/failover/FailoverMethodTest.java254
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/failover/MessageDisappearWithIOExceptionTest.java338
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/failure/HeapExhaustion.java236
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/logging/AbstractTestLogging.java448
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/logging/AccessControlLoggingTest.java174
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/logging/AlertingTest.java202
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/logging/BindingLoggingTest.java271
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/logging/BrokerLoggingTest.java1003
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/logging/ChannelLoggingTest.java313
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/logging/ConnectionLoggingTest.java192
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/logging/DerbyMessageStoreLoggingTest.java574
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/logging/DurableQueueLoggingTest.java307
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/logging/ExchangeLoggingTest.java217
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/logging/ManagementLoggingTest.java305
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/logging/MemoryMessageStoreLoggingTest.java186
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/logging/QueueLoggingTest.java183
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/logging/SubscriptionLoggingTest.java458
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/logging/TransientQueueLoggingTest.java30
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/logging/VirtualHostLoggingTest.java134
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/persistent/NoLocalAfterRecoveryTest.java246
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/queue/ConflationQueueTest.java435
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/queue/DeepQueueConsumeWithSelector.java159
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/queue/ModelTest.java343
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/queue/MultipleTransactedBatchProducerTest.java246
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/queue/PersistentTestManual.java276
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/queue/PriorityTest.java212
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/queue/ProducerFlowControlTest.java496
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/queue/QueueDepthWithSelectorTest.java176
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/queue/SubscriptionTestHelper.java294
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/queue/TimeToLiveTest.java370
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/security/acl/AbstractACLTestCase.java285
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/security/acl/ExhaustiveACLTest.java195
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/security/acl/ExternalACLFileTest.java184
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/security/acl/ExternalACLJMXTest.java244
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/security/acl/ExternalACLTest.java37
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/security/acl/ExternalAdminACLTest.java186
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/security/acl/SimpleACLTest.java644
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/security/firewall/FirewallConfigTest.java298
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/store/PersistentStoreTest.java193
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/store/SlowMessageStore.java321
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/util/AveragedRun.java66
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/util/RunStats.java57
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/util/TimedRun.java52
-rw-r--r--java/systests/src/main/java/org/apache/qpid/systest/GlobalQueuesTest.java223
-rw-r--r--java/systests/src/main/java/org/apache/qpid/systest/GlobalTopicsTest.java36
-rw-r--r--java/systests/src/main/java/org/apache/qpid/systest/MergeConfigurationTest.java124
-rw-r--r--java/systests/src/main/java/org/apache/qpid/systest/SubscriptionTest.java146
-rw-r--r--java/systests/src/main/java/org/apache/qpid/systest/TestingBaseCase.java241
-rw-r--r--java/systests/src/main/java/org/apache/qpid/systest/TopicTest.java85
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/client/CancelTest.java100
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/client/DupsOkTest.java167
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/client/FlowControlTest.java213
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/client/QueueBrowserAutoAckTest.java528
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/client/QueueBrowserClientAckTest.java34
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/client/QueueBrowserDupsOkTest.java31
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/client/QueueBrowserNoAckTest.java33
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/client/QueueBrowserPreAckTest.java32
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/client/QueueBrowserTransactedTest.java31
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/client/RollbackOrderTest.java194
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/client/destination/AddressBasedDestinationTest.java1072
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/client/failover/FailoverTest.java389
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/client/message/JMSDestinationTest.java373
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/client/message/MessageToStringTest.java257
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/client/message/ObjectMessageTest.java141
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/client/message/SelectorTest.java310
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/client/queue/LVQTest.java84
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/client/queue/QueuePolicyTest.java110
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/client/timeouts/SyncWaitDelayTest.java112
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/client/timeouts/SyncWaitTimeoutDelayTest.java72
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/AMQPPublisher.java54
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/Assertion.java39
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/AssertionBase.java66
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/BrokerLifecycleAware.java70
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/CauseFailure.java42
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/CauseFailureUserPrompt.java65
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/Circuit.java109
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/CircuitEnd.java91
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/CircuitEndBase.java152
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/DropInTest.java51
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/ExceptionMonitor.java205
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/FrameworkBaseCase.java301
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/FrameworkClientBaseCase.java31
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/FrameworkTestContext.java48
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/LocalAMQPCircuitFactory.java168
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/LocalCircuitFactory.java316
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/MessageIdentityVector.java167
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/MessageMonitor.java105
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/MessagingTestConfigProperties.java685
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/NotApplicableAssertion.java112
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/Publisher.java74
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/Receiver.java92
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/TestCaseVector.java88
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/TestClientDetails.java86
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/TestUtils.java192
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/clocksynch/ClockSynchFailureException.java45
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/clocksynch/ClockSynchThread.java124
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/clocksynch/ClockSynchronizer.java69
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/clocksynch/LocalClockSynchronizer.java73
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/clocksynch/UDPClockReference.java165
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/clocksynch/UDPClockSynchronizer.java463
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/distributedcircuit/DistributedCircuitImpl.java469
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/distributedcircuit/DistributedPublisherImpl.java95
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/distributedcircuit/DistributedReceiverImpl.java95
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/distributedcircuit/TestClientCircuitEnd.java324
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/distributedtesting/Coordinator.java539
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/distributedtesting/DistributedTestDecorator.java166
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/distributedtesting/FanOutTestDecorator.java244
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/distributedtesting/InteropTestDecorator.java209
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/distributedtesting/OptOutTestCase.java69
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/distributedtesting/TestClient.java499
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/distributedtesting/TestClientControlledTest.java108
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/listeners/XMLTestListener.java409
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/localcircuit/LocalAMQPPublisherImpl.java133
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/localcircuit/LocalCircuitImpl.java306
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/localcircuit/LocalPublisherImpl.java170
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/localcircuit/LocalReceiverImpl.java144
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/package.html43
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/qpid/AMQPFeatureDecorator.java96
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/qpid/CauseFailureDecorator.java95
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/qpid/CauseFailureInVM.java70
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/qpid/InVMBrokerDecorator.java136
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/sequencers/BaseCircuitFactory.java136
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/sequencers/CircuitFactory.java102
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/sequencers/FanOutCircuitFactory.java198
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/framework/sequencers/InteropCircuitFactory.java152
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/testcases/FailoverTest.java119
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/testcases/ImmediateMessageTest.java303
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/testcases/MandatoryMessageTest.java321
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/testcases/RollbackTest.java132
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/testcases/TTLTest.java154
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/ack/Acknowledge2ConsumersTest.java193
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/ack/AcknowledgeAfterFailoverOnMessageTest.java429
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/ack/AcknowledgeAfterFailoverTest.java317
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/ack/AcknowledgeOnMessageTest.java226
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/ack/AcknowledgeTest.java179
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/ack/FailoverBeforeConsumingRecoverTest.java40
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/ack/QuickAcking.java148
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/ack/RecoverTest.java450
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/basic/BytesMessageTest.java284
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/basic/FieldTableMessageTest.java163
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/basic/InvalidDestinationTest.java104
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/basic/LargeMessageTest.java190
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/basic/MapMessageTest.java1271
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/basic/MultipleConnectionTest.java218
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/basic/ObjectMessageTest.java278
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/basic/PropertyValueTest.java408
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/basic/PubSubTwoConnectionTest.java75
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/basic/ReceiveTest.java82
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/basic/SessionStartTest.java115
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/basic/TextMessageTest.java248
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/basic/close/CloseTest.java58
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/client/AMQConnectionTest.java405
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/client/AMQSessionTest.java110
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/client/DynamicQueueExchangeCreateTest.java90
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/client/channelclose/ChannelCloseOkTest.java239
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/client/channelclose/ChannelCloseTest.java394
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/client/channelclose/CloseWithBlockingReceiveTest.java81
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/client/connection/CloseAfterConnectionFailureTest.java124
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/client/connection/ConnectionCloseTest.java111
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/client/connection/ConnectionStartTest.java158
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/client/connection/ConnectionTest.java301
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/client/connection/ExceptionListenerTest.java62
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/client/forwardall/Client.java143
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/client/forwardall/CombinedTest.java69
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/client/forwardall/Service.java95
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/client/forwardall/ServiceCreator.java112
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/client/forwardall/SpecialQueue.java46
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/client/message/ObjectMessageTest.java335
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/client/protocol/AMQProtocolSessionTest.java106
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/client/temporaryqueue/TemporaryQueueTest.java258
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/close/CloseBeforeAckTest.java142
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/close/JavaServerCloseRaceConditionTest.java119
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/close/MessageRequeueTest.java373
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/close/TopicPublisherCloseTest.java69
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/close/VerifyAckingOkDuringClose.java160
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/ct/DurableSubscriberTest.java506
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/message/JMSPropertiesTest.java204
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/message/StreamMessageTest.java162
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/message/UTF8En4
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/message/UTF8Jp4
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/message/UTF8Test.java111
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/publish/DirtyTransactedPublishTest.java403
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/topic/DurableSubscriptionTest.java844
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/topic/TopicPublisherTest.java76
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/topic/TopicSessionTest.java453
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/transacted/CommitRollbackTest.java572
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/transacted/TransactedTest.java348
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/transacted/TransactionTimeoutConfigurationTest.java82
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/transacted/TransactionTimeoutDisabledTest.java72
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/transacted/TransactionTimeoutTest.java335
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/transacted/TransactionTimeoutTestCase.java253
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/xa/AbstractXATestCase.java132
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/xa/FaultTest.java409
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/xa/QueueTest.java657
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/unit/xa/TopicTest.java1711
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/utils/ConversationFactory.java476
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/utils/FailoverBaseCase.java115
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/utils/JMXTestUtils.java435
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/utils/QpidBrokerTestCase.java1363
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/utils/QpidClientConnection.java289
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/utils/QpidClientConnectionHelper.java295
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/utils/ReflectionUtils.java228
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/utils/ReflectionUtilsException.java44
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/utils/protocol/TestIoSession.java104
-rw-r--r--java/systests/src/main/java/org/apache/qpid/util/ClasspathScanner.java234
-rw-r--r--java/systests/src/main/java/org/apache/qpid/util/LogMonitor.java238
-rw-r--r--java/systests/src/main/java/org/apache/qpid/util/LogMonitorTest.java275
-rw-r--r--java/systests/src/main/java/systests.log4j28
-rw-r--r--java/tasks/src/org/apache/qpid/tasks/BaseTask.java74
-rw-r--r--java/tasks/src/org/apache/qpid/tasks/Foreach.java84
-rw-r--r--java/tasks/src/org/apache/qpid/tasks/Map.java99
-rw-r--r--java/tasks/src/org/apache/qpid/tasks/PropertyMapper.java50
-rw-r--r--java/tasks/src/org/apache/qpid/tasks/Require.java80
-rw-r--r--java/test-profiles/08StandaloneExcludes41
-rwxr-xr-xjava/test-profiles/CPPExcludes175
-rw-r--r--java/test-profiles/CPPNoPrefetchExcludes31
-rw-r--r--java/test-profiles/CPPPrefetchExcludes23
-rw-r--r--java/test-profiles/CPPTransientExcludes29
-rw-r--r--java/test-profiles/Excludes53
-rwxr-xr-xjava/test-profiles/Java010Excludes82
-rw-r--r--java/test-profiles/JavaExcludes54
-rw-r--r--java/test-profiles/JavaInVMExcludes45
-rw-r--r--java/test-profiles/JavaPersistentExcludes21
-rw-r--r--java/test-profiles/JavaStandaloneExcludes55
-rw-r--r--java/test-profiles/JavaTransientExcludes32
-rw-r--r--java/test-profiles/XAExcludes22
-rwxr-xr-xjava/test-profiles/clean-dir25
-rw-r--r--java/test-profiles/cpp.async.excludes21
-rw-r--r--java/test-profiles/cpp.async.testprofile21
-rw-r--r--java/test-profiles/cpp.cluster.testprofile28
-rw-r--r--java/test-profiles/cpp.excludes29
-rw-r--r--java/test-profiles/cpp.noprefetch.testprofile21
-rw-r--r--java/test-profiles/cpp.ssl.excludes20
-rw-r--r--java/test-profiles/cpp.ssl.testprofile29
-rw-r--r--java/test-profiles/cpp.testprofile38
-rw-r--r--java/test-profiles/default.testprofile61
-rw-r--r--java/test-profiles/java-derby.0.10.testprofile29
-rw-r--r--java/test-profiles/java-derby.testprofile33
-rw-r--r--java/test-profiles/java.0.10.testprofile26
-rw-r--r--java/test-profiles/java.testprofile28
-rwxr-xr-xjava/test-profiles/kill-broker26
-rw-r--r--java/test-profiles/log4j-test.xml70
-rwxr-xr-xjava/test-profiles/start-broker37
-rw-r--r--java/test-profiles/test-provider.properties51
-rw-r--r--java/test-profiles/test_resources/ssl/CA_db/cert8.dbbin65536 -> 0 bytes
-rw-r--r--java/test-profiles/test_resources/ssl/CA_db/key3.dbbin16384 -> 0 bytes
-rw-r--r--java/test-profiles/test_resources/ssl/CA_db/rootca.crt13
-rw-r--r--java/test-profiles/test_resources/ssl/CA_db/secmod.dbbin16384 -> 0 bytes
-rw-r--r--java/test-profiles/test_resources/ssl/app1.crt15
-rw-r--r--java/test-profiles/test_resources/ssl/app1.req10
-rw-r--r--java/test-profiles/test_resources/ssl/app2.crt15
-rw-r--r--java/test-profiles/test_resources/ssl/app2.req10
-rw-r--r--java/test-profiles/test_resources/ssl/certstore.jksbin591 -> 0 bytes
-rw-r--r--java/test-profiles/test_resources/ssl/keystore.jksbin4296 -> 0 bytes
-rw-r--r--java/test-profiles/test_resources/ssl/pfile1
-rw-r--r--java/test-profiles/test_resources/ssl/server_db/cert8.dbbin65536 -> 0 bytes
-rw-r--r--java/test-profiles/test_resources/ssl/server_db/key3.dbbin16384 -> 0 bytes
-rw-r--r--java/test-profiles/test_resources/ssl/server_db/secmod.dbbin16384 -> 0 bytes
-rw-r--r--java/test-profiles/test_resources/ssl/server_db/server.crt14
-rw-r--r--java/test-profiles/test_resources/ssl/server_db/server.req21
-rw-r--r--java/testkit/README.txt6
-rw-r--r--java/testkit/bin/run_soak_client.sh70
-rw-r--r--java/testkit/bin/soak_report.sh161
-rw-r--r--java/testkit/build.xml27
-rw-r--r--java/testkit/src/main/java/org/apache/qpid/testkit/soak/ResourceLeakTest.java180
-rw-r--r--java/tools/README.txt153
-rwxr-xr-xjava/tools/bin/perf_report.sh140
-rw-r--r--java/tools/bin/qpid-bench35
-rwxr-xr-xjava/tools/bin/qpid-python-testkit30
-rw-r--r--java/tools/bin/run_pub.sh24
-rw-r--r--java/tools/bin/run_sub.sh25
-rw-r--r--java/tools/bin/set-testkit-env.sh88
-rw-r--r--java/tools/bin/setenv.sh49
-rwxr-xr-xjava/tools/bin/testkit.py278
-rw-r--r--java/tools/build.xml27
-rw-r--r--java/tools/etc/test.log4j28
-rw-r--r--java/tools/src/main/java/org/apache/qpid/testkit/Client.java154
-rw-r--r--java/tools/src/main/java/org/apache/qpid/testkit/ErrorHandler.java27
-rw-r--r--java/tools/src/main/java/org/apache/qpid/testkit/Receiver.java216
-rw-r--r--java/tools/src/main/java/org/apache/qpid/testkit/Sender.java197
-rw-r--r--java/tools/src/main/java/org/apache/qpid/testkit/TestLauncher.java370
-rw-r--r--java/tools/src/main/java/org/apache/qpid/tools/JNDICheck.java200
-rw-r--r--java/tools/src/main/java/org/apache/qpid/tools/LatencyTest.java349
-rw-r--r--java/tools/src/main/java/org/apache/qpid/tools/MessageFactory.java64
-rw-r--r--java/tools/src/main/java/org/apache/qpid/tools/PerfBase.java78
-rw-r--r--java/tools/src/main/java/org/apache/qpid/tools/PerfConsumer.java267
-rw-r--r--java/tools/src/main/java/org/apache/qpid/tools/PerfProducer.java262
-rw-r--r--java/tools/src/main/java/org/apache/qpid/tools/QpidBench.java904
-rw-r--r--java/tools/src/main/java/org/apache/qpid/tools/TestParams.java170
-rw-r--r--java/upload.xml90
2051 files changed, 0 insertions, 317397 deletions
diff --git a/java/broker-plugins/access-control/MANIFEST.MF b/java/broker-plugins/access-control/MANIFEST.MF
deleted file mode 100644
index 1cd285ba20..0000000000
--- a/java/broker-plugins/access-control/MANIFEST.MF
+++ /dev/null
@@ -1,42 +0,0 @@
-Manifest-Version: 1.0
-Bundle-ManifestVersion: 2
-Bundle-Name: Qpid Broker-Plugins Access Control
-Bundle-SymbolicName: broker-plugins-access-control
-Bundle-Description: Access control plugin for Qpid.
-Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt
-Bundle-DocURL: http://qpid.apache.org/acl.html
-Bundle-Version: 1.0.0
-Bundle-Activator: org.apache.qpid.server.security.access.plugins.AccessControlActivator
-Bundle-RequiredExecutionEnvironment: JavaSE-1.5
-Bundle-ClassPath: .
-Bundle-ActivationPolicy: lazy
-Import-Package: org.apache.qpid,
- org.apache.qpid.exchange,
- org.apache.qpid.framing,
- org.apache.qpid.junit.extensions.util,
- org.apache.qpid.protocol,
- org.apache.qpid.server.configuration,
- org.apache.qpid.server.configuration.plugins,
- org.apache.qpid.server.exchange,
- org.apache.qpid.server.management,
- org.apache.qpid.server.logging,
- org.apache.qpid.server.logging.actors,
- org.apache.qpid.server.logging.subjects,
- org.apache.qpid.server.plugins,
- org.apache.qpid.server.queue,
- org.apache.qpid.server.registry,
- org.apache.qpid.server.security,
- org.apache.qpid.server.security.access,
- org.apache.qpid.server.virtualhost,
- org.apache.qpid.util,
- org.apache.commons.configuration;version=1.0.0,
- org.apache.commons.lang;version=1.0.0,
- org.apache.commons.lang.builder;version=1.0.0,
- org.apache.log4j;version=1.0.0,
- javax.management;version=1.0.0,
- javax.management.openmbean;version=1.0.0,
- org.osgi.util.tracker;version=1.0.0,
- org.osgi.framework;version=1.3
-Private-Package: org.apache.qpid.server.security.access.config,
- org.apache.qpid.server.security.access.logging
-Export-Package: org.apache.qpid.server.security.access.plugins
diff --git a/java/broker-plugins/access-control/build.xml b/java/broker-plugins/access-control/build.xml
deleted file mode 100644
index 89f8240fd5..0000000000
--- a/java/broker-plugins/access-control/build.xml
+++ /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.
- -->
-<project name="Qpid Broker-Plugins Access Control" default="build">
- <property name="module.depends" value="common broker broker-plugins" />
- <property name="module.test.depends" value="test common/test broker/test management/common systests" />
-
- <property name="module.manifest" value="MANIFEST.MF" />
- <property name="module.plugin" value="true" />
-
- <import file="../../module.xml" />
-
- <target name="bundle" depends="bundle-tasks"/>
-
- <target name="precompile" depends="gen_logging"/>
-</project>
diff --git a/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AbstractConfiguration.java b/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AbstractConfiguration.java
deleted file mode 100644
index a684e52ce4..0000000000
--- a/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AbstractConfiguration.java
+++ /dev/null
@@ -1,77 +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.config;
-
-import java.io.File;
-
-import org.apache.commons.configuration.ConfigurationException;
-import org.apache.log4j.Logger;
-
-public abstract class AbstractConfiguration implements ConfigurationFile
-{
- protected static final Logger _logger = Logger.getLogger(ConfigurationFile.class);
-
- protected File _file;
- protected RuleSet _config;
-
- public AbstractConfiguration(File file)
- {
- _file = file;
- }
-
- public File getFile()
- {
- return _file;
- }
-
- public RuleSet load() throws ConfigurationException
- {
- _config = new RuleSet();
- return _config;
- }
-
- public RuleSet getConfiguration()
- {
- return _config;
- }
-
- public boolean save(RuleSet configuration)
- {
- return true;
- }
-
- public RuleSet reload()
- {
- RuleSet oldRules = _config;
-
- try
- {
- RuleSet newRules = load();
- _config = newRules;
- }
- catch (Exception e)
- {
- _config = oldRules;
- }
-
- return _config;
- }
-}
diff --git a/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/Action.java b/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/Action.java
deleted file mode 100644
index fdbd96e63e..0000000000
--- a/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/Action.java
+++ /dev/null
@@ -1,192 +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.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;
-import org.apache.commons.lang.builder.ToStringBuilder;
-import org.apache.commons.lang.builder.ToStringStyle;
-import org.apache.qpid.server.security.access.ObjectProperties;
-import org.apache.qpid.server.security.access.ObjectType;
-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}.
- * 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
- * the empty string or "*" matching all values, and "*" at the end of a rule value indicating prefix matching.
- * <p>
- * The {@link #matches(Action)} method is intended to be used when determining precedence of rules, and
- * {@link #equals(Object)} and {@link #hashCode()} are intended for use in maps. This is due to the wildcard matching
- * described above.
- */
-public class Action
-{
- private Operation _operation;
- private ObjectType _object;
- private ObjectProperties _properties;
-
- public Action(Operation operation)
- {
- this(operation, ObjectType.ALL);
- }
-
- public Action(Operation operation, ObjectType object, String name)
- {
- this(operation, object, new ObjectProperties(name));
- }
-
- public Action(Operation operation, ObjectType object)
- {
- this(operation, object, ObjectProperties.EMPTY);
- }
-
- public Action(Operation operation, ObjectType object, ObjectProperties properties)
- {
- setOperation(operation);
- setObjectType(object);
- setProperties(properties);
- }
-
- public Operation getOperation()
- {
- return _operation;
- }
-
- public void setOperation(Operation operation)
- {
- _operation = operation;
- }
-
- public ObjectType getObjectType()
- {
- return _object;
- }
-
- public void setObjectType(ObjectType object)
- {
- _object = object;
- }
-
- public ObjectProperties getProperties()
- {
- return _properties;
- }
-
- public void setProperties(ObjectProperties properties)
- {
- _properties = properties;
- }
-
- public boolean isAllowed()
- {
- return _object.isAllowed(_operation);
- }
-
- /** @see Comparable#compareTo(Object) */
- public boolean matches(Action a)
- {
- return (Operation.ALL == a.getOperation()
- || (getOperation() == a.getOperation()
- && getObjectType() == a.getObjectType()
- && _properties.matches(a.getProperties())));
- }
-
- /**
- * An ordering based on specificity
- *
- * @see Comparator#compare(Object, Object)
- */
- public class Specificity implements Comparator<Action>
- {
- public int compare(Action a, Action b)
- {
- if (a.getOperation() == Operation.ALL && b.getOperation() != Operation.ALL)
- {
- return 1; // B is more specific
- }
- else if (b.getOperation() == Operation.ALL && a.getOperation() != Operation.ALL)
- {
- return 1; // A is more specific
- }
- 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
- {
- return a.getOperation().compareTo(b.getOperation()); // Arbitrary
- }
- }
- }
-
- /** @see Object#equals(Object) */
- @Override
- public boolean equals(Object o)
- {
- if (!(o instanceof Action))
- {
- return false;
- }
- Action a = (Action) o;
-
- return new EqualsBuilder()
- .append(_operation, a.getOperation())
- .append(_object, a.getObjectType())
- .appendSuper(_properties.equals(a.getProperties()))
- .isEquals();
- }
-
- /** @see Object#hashCode() */
- @Override
- public int hashCode()
- {
- return new HashCodeBuilder()
- .append(_operation)
- .append(_operation)
- .append(_properties)
- .toHashCode();
- }
-
- /** @see Object#toString() */
- @Override
- public String toString()
- {
- return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
- .append("operation", _operation)
- .append("objectType", _object)
- .append("properties", _properties)
- .toString();
- }
-}
diff --git a/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/ConfigurationFile.java b/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/ConfigurationFile.java
deleted file mode 100644
index 8b1a00259b..0000000000
--- a/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/ConfigurationFile.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.server.security.access.config;
-
-import java.io.File;
-
-import org.apache.commons.configuration.ConfigurationException;
-
-public interface ConfigurationFile
-{
- /**
- * Return the actual {@link File} object containing the configuration.
- */
- File getFile();
-
- /**
- * Load this configuration file's contents into a {@link RuleSet}.
- *
- * @throws ConfigurationException if the configuration file has errors.
- * @throws IllegalArgumentException if individual tokens cannot be parsed.
- */
- RuleSet load() throws ConfigurationException;
-
- /**
- * Reload this configuration file's contents.
- *
- * @throws ConfigurationException if the configuration file has errors.
- * @throws IllegalArgumentException if individual tokens cannot be parsed.
- */
- RuleSet reload() throws ConfigurationException;
-
- RuleSet getConfiguration();
-
- /**
- * TODO document me.
- */
- boolean save(RuleSet configuration);
-}
diff --git a/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/PlainConfiguration.java b/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/PlainConfiguration.java
deleted file mode 100644
index 9f2168a31c..0000000000
--- a/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/PlainConfiguration.java
+++ /dev/null
@@ -1,323 +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.config;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileReader;
-import java.io.IOException;
-import java.io.StreamTokenizer;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Stack;
-
-import org.apache.commons.configuration.ConfigurationException;
-import org.apache.commons.lang.StringUtils;
-import org.apache.qpid.server.security.access.ObjectProperties;
-import org.apache.qpid.server.security.access.ObjectType;
-import org.apache.qpid.server.security.access.Operation;
-import org.apache.qpid.server.security.access.Permission;
-
-public class PlainConfiguration extends AbstractConfiguration
-{
- public static final Character COMMENT = '#';
- public static final Character CONTINUATION = '\\';
-
- public static final String GROUP = "group";
- public static final String ACL = "acl";
- public static final String CONFIG = "config";
-
- public static final String UNRECOGNISED_INITIAL_MSG = "Unrecognised initial token '%s' at line %d";
- public static final String NOT_ENOUGH_TOKENS_MSG = "Not enough tokens at line %d";
- public static final String NUMBER_NOT_ALLOWED_MSG = "Number not allowed before '%s' at line %d";
- public static final String CANNOT_LOAD_MSG = "Cannot load config file %s";
- public static final String PREMATURE_CONTINUATION_MSG = "Premature continuation character at line %d";
- public static final String PREMATURE_EOF_MSG = "Premature end of file reached at line %d";
- public static final String PARSE_TOKEN_FAILED_MSG = "Failed to parse token at line %d";
- public static final String CONFIG_NOT_FOUND_MSG = "Cannot find config file %s";
- public static final String NOT_ENOUGH_GROUP_MSG = "Not enough data for a group at line %d";
- public static final String NOT_ENOUGH_ACL_MSG = "Not enough data for an acl at line %d";
- public static final String NOT_ENOUGH_CONFIG_MSG = "Not enough data for config at line %d";
- public static final String BAD_ACL_RULE_NUMBER_MSG = "Invalid rule number at line %d";
- public static final String PROPERTY_KEY_ONLY_MSG = "Incomplete property (key only) at line %d";
- public static final String PROPERTY_NO_EQUALS_MSG = "Incomplete property (no equals) at line %d";
- public static final String PROPERTY_NO_VALUE_MSG = "Incomplete property (no value) at line %d";
-
- private StreamTokenizer _st;
-
- public PlainConfiguration(File file)
- {
- super(file);
- }
-
- @Override
- public RuleSet load() throws ConfigurationException
- {
- RuleSet ruleSet = super.load();
-
- try
- {
- _st = new StreamTokenizer(new BufferedReader(new FileReader(_file)));
- _st.resetSyntax(); // setup the tokenizer
-
- _st.commentChar(COMMENT); // single line comments
- _st.eolIsSignificant(true); // return EOL as a token
- _st.lowerCaseMode(true); // case insensitive tokens
- _st.ordinaryChar('='); // equals is a token
- _st.ordinaryChar(CONTINUATION); // continuation character (when followed by EOL)
- _st.quoteChar('"'); // double quote
- _st.quoteChar('\''); // single quote
- _st.whitespaceChars('\u0000', '\u0020'); // whitespace (to be ignored) TODO properly
- _st.wordChars('a', 'z'); // unquoted token characters [a-z]
- _st.wordChars('A', 'Z'); // [A-Z]
- _st.wordChars('0', '9'); // [0-9]
- _st.wordChars('_', '_'); // underscore
- _st.wordChars('-', '-'); // dash
- _st.wordChars('.', '.'); // dot
- _st.wordChars('*', '*'); // star
- _st.wordChars('@', '@'); // at
- _st.wordChars(':', ':'); // colon
-
- // parse the acl file lines
- Stack<String> stack = new Stack<String>();
- int current;
- do {
- current = _st.nextToken();
- switch (current)
- {
- case StreamTokenizer.TT_EOF:
- case StreamTokenizer.TT_EOL:
- if (stack.isEmpty())
- {
- break; // blank line
- }
-
- // pull out the first token from the bottom of the stack and check arguments exist
- String first = stack.firstElement();
- stack.removeElementAt(0);
- if (stack.isEmpty())
- {
- throw new ConfigurationException(String.format(NOT_ENOUGH_TOKENS_MSG, getLine()));
- }
-
- // check for and parse optional initial number for ACL lines
- Integer number = null;
- if (StringUtils.isNumeric(first))
- {
- // set the acl number and get the next element
- number = Integer.valueOf(first);
- first = stack.firstElement();
- stack.removeElementAt(0);
- }
-
- if (StringUtils.equalsIgnoreCase(ACL, first))
- {
- parseAcl(number, stack);
- }
- else if (number == null)
- {
- if (StringUtils.equalsIgnoreCase(GROUP, first))
- {
- parseGroup(stack);
- }
- else if (StringUtils.equalsIgnoreCase(CONFIG, first))
- {
- parseConfig(stack);
- }
- else
- {
- throw new ConfigurationException(String.format(UNRECOGNISED_INITIAL_MSG, first, getLine()));
- }
- }
- else
- {
- throw new ConfigurationException(String.format(NUMBER_NOT_ALLOWED_MSG, first, getLine()));
- }
-
- // reset stack, start next line
- stack.clear();
- break;
- case StreamTokenizer.TT_NUMBER:
- stack.push(Integer.toString(Double.valueOf(_st.nval).intValue()));
- break;
- case StreamTokenizer.TT_WORD:
- stack.push(_st.sval); // token
- break;
- default:
- if (_st.ttype == CONTINUATION)
- {
- int next = _st.nextToken();
- if (next == StreamTokenizer.TT_EOL)
- {
- break; // continue reading next line
- }
-
- // invalid location for continuation character (add one to line beacuse we ate the EOL)
- throw new ConfigurationException(String.format(PREMATURE_CONTINUATION_MSG, getLine() + 1));
- }
- else if (_st.ttype == '\'' || _st.ttype == '"')
- {
- stack.push(_st.sval); // quoted token
- }
- else
- {
- stack.push(Character.toString((char) _st.ttype)); // single character
- }
- }
- } while (current != StreamTokenizer.TT_EOF);
-
- if (!stack.isEmpty())
- {
- throw new ConfigurationException(String.format(PREMATURE_EOF_MSG, getLine()));
- }
- }
- catch (IllegalArgumentException iae)
- {
- throw new ConfigurationException(String.format(PARSE_TOKEN_FAILED_MSG, getLine()), iae);
- }
- catch (FileNotFoundException fnfe)
- {
- throw new ConfigurationException(String.format(CONFIG_NOT_FOUND_MSG, getFile().getName()), fnfe);
- }
- catch (IOException ioe)
- {
- throw new ConfigurationException(String.format(CANNOT_LOAD_MSG, getFile().getName()), ioe);
- }
-
- return ruleSet;
- }
-
- private void parseGroup(List<String> args) throws ConfigurationException
- {
- if (args.size() < 2)
- {
- throw new ConfigurationException(String.format(NOT_ENOUGH_GROUP_MSG, getLine()));
- }
-
- getConfiguration().addGroup(args.get(0), args.subList(1, args.size()));
- }
-
- private void parseAcl(Integer number, List<String> args) throws ConfigurationException
- {
- if (args.size() < 3)
- {
- throw new ConfigurationException(String.format(NOT_ENOUGH_ACL_MSG, getLine()));
- }
-
- Permission permission = Permission.parse(args.get(0));
- String identity = args.get(1);
- Operation operation = Operation.parse(args.get(2));
-
- if (number != null && !getConfiguration().isValidNumber(number))
- {
- throw new ConfigurationException(String.format(BAD_ACL_RULE_NUMBER_MSG, getLine()));
- }
-
- if (args.size() == 3)
- {
- getConfiguration().grant(number, identity, permission, operation);
- }
- else
- {
- ObjectType object = ObjectType.parse(args.get(3));
- ObjectProperties properties = toObjectProperties(args.subList(4, args.size()));
-
- getConfiguration().grant(number, identity, permission, operation, object, properties);
- }
- }
-
- private void parseConfig(List<String> args) throws ConfigurationException
- {
- if (args.size() < 3)
- {
- throw new ConfigurationException(String.format(NOT_ENOUGH_CONFIG_MSG, getLine()));
- }
-
- Map<String, Boolean> properties = toPluginProperties(args);
-
- getConfiguration().configure(properties);
- }
-
- /** Converts a {@link List} of "name", "=", "value" tokens into a {@link Map}. */
- protected ObjectProperties toObjectProperties(List<String> args) throws ConfigurationException
- {
- ObjectProperties properties = new ObjectProperties();
- Iterator<String> i = args.iterator();
- while (i.hasNext())
- {
- String key = i.next();
- if (!i.hasNext())
- {
- throw new ConfigurationException(String.format(PROPERTY_KEY_ONLY_MSG, getLine()));
- }
- if (!"=".equals(i.next()))
- {
- throw new ConfigurationException(String.format(PROPERTY_NO_EQUALS_MSG, getLine()));
- }
- if (!i.hasNext())
- {
- throw new ConfigurationException(String.format(PROPERTY_NO_VALUE_MSG, getLine()));
- }
- String value = i.next();
-
- // parse property key
- ObjectProperties.Property property = ObjectProperties.Property.parse(key);
- properties.put(property, value);
- }
- return properties;
- }
-
- /** Converts a {@link List} of "name", "=", "value" tokens into a {@link Map}. */
- protected Map<String, Boolean> toPluginProperties(List<String> args) throws ConfigurationException
- {
- Map<String, Boolean> properties = new HashMap<String, Boolean>();
- Iterator<String> i = args.iterator();
- while (i.hasNext())
- {
- String key = i.next().toLowerCase();
- if (!i.hasNext())
- {
- throw new ConfigurationException(String.format(PROPERTY_KEY_ONLY_MSG, getLine()));
- }
- if (!"=".equals(i.next()))
- {
- throw new ConfigurationException(String.format(PROPERTY_NO_EQUALS_MSG, getLine()));
- }
- if (!i.hasNext())
- {
- throw new ConfigurationException(String.format(PROPERTY_NO_VALUE_MSG, getLine()));
- }
-
- // parse property value and save
- Boolean value = Boolean.valueOf(i.next());
- properties.put(key, value);
- }
- return properties;
- }
-
- protected int getLine()
- {
- return _st.lineno() - 1;
- }
-}
diff --git a/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/Rule.java b/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/Rule.java
deleted file mode 100644
index 15d6b67192..0000000000
--- a/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/Rule.java
+++ /dev/null
@@ -1,170 +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.config;
-
-import org.apache.commons.lang.builder.CompareToBuilder;
-import org.apache.commons.lang.builder.EqualsBuilder;
-import org.apache.commons.lang.builder.HashCodeBuilder;
-import org.apache.commons.lang.builder.ToStringBuilder;
-import org.apache.commons.lang.builder.ToStringStyle;
-import org.apache.qpid.server.security.access.Permission;
-
-/**
- * An access control v2 rule.
- *
- * A rule consists of {@link Permission} for a particular identity to perform an {@link Action}. The identity
- * may be either a user or a group.
- */
-public class Rule implements Comparable<Rule>
-{
- /** String indicating all identitied. */
- public static final String ALL = "all";
-
- private Integer _number;
- private Boolean _enabled = Boolean.TRUE;
- private String _identity;
- private Action _action;
- private Permission _permission;
-
- public Rule(Integer number, String identity, Action action, Permission permission)
- {
- setNumber(number);
- setIdentity(identity);
- setAction(action);
- setPermission(permission);
- }
-
- public Rule(String identity, Action action, Permission permission)
- {
- this(null, identity, action, permission);
- }
-
- public boolean isEnabled()
- {
- return _enabled;
- }
-
- public void setEnabled(boolean enabled)
- {
- _enabled = enabled;
- }
-
- public void enable()
- {
- _enabled = Boolean.TRUE;
- }
-
- public void disable()
- {
- _enabled = Boolean.FALSE;
- }
-
- public Integer getNumber()
- {
- return _number;
- }
-
- public void setNumber(Integer number)
- {
- _number = number;
- }
-
- public String getIdentity()
- {
- return _identity;
- }
-
- public void setIdentity(String identity)
- {
- _identity = identity;
- }
-
- public Action getAction()
- {
- return _action;
- }
-
- public void setAction(Action action)
- {
- _action = action;
- }
-
- public Permission getPermission()
- {
- return _permission;
- }
-
- public void setPermission(Permission permission)
- {
- _permission = permission;
- }
-
- /** @see Comparable#compareTo(Object) */
- public int compareTo(Rule r)
- {
- return new CompareToBuilder()
- .append(getAction(), r.getAction())
- .append(getIdentity(), r.getIdentity())
- .append(getPermission(), r.getPermission())
- .toComparison();
- }
-
- /** @see Object#equals(Object) */
- @Override
- public boolean equals(Object o)
- {
- if (!(o instanceof Rule))
- {
- return false;
- }
- Rule r = (Rule) o;
-
- return new EqualsBuilder()
- .append(getIdentity(), r.getIdentity())
- .append(getAction(), r.getAction())
- .append(getPermission(), r.getPermission())
- .isEquals();
- }
-
- /** @see Object#hashCode() */
- @Override
- public int hashCode()
- {
- return new HashCodeBuilder()
- .append(getIdentity())
- .append(getAction())
- .append(getPermission())
- .toHashCode();
- }
-
- /** @see Object#toString() */
- @Override
- public String toString()
- {
- return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
- .append("#", getNumber())
- .append("identity", getIdentity())
- .append("action", getAction())
- .append("permission", getPermission())
- .append("enabled", isEnabled())
- .toString();
- }
-}
diff --git a/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/RuleSet.java b/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/RuleSet.java
deleted file mode 100644
index ebc73440ed..0000000000
--- a/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/RuleSet.java
+++ /dev/null
@@ -1,489 +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.config;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.EnumMap;
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.SortedMap;
-import java.util.TreeMap;
-import java.util.WeakHashMap;
-
-import org.apache.commons.lang.BooleanUtils;
-import org.apache.commons.lang.StringUtils;
-import org.apache.log4j.Logger;
-import org.apache.qpid.exchange.ExchangeDefaults;
-import org.apache.qpid.server.logging.actors.CurrentActor;
-import org.apache.qpid.server.security.Result;
-import org.apache.qpid.server.security.access.ObjectProperties;
-import org.apache.qpid.server.security.access.ObjectType;
-import org.apache.qpid.server.security.access.Operation;
-import org.apache.qpid.server.security.access.Permission;
-import org.apache.qpid.server.security.access.logging.AccessControlMessages;
-
-/**
- * Models the rule configuration for the access control plugin.
- *
- * The access control rule definitions are loaded from an external configuration file, passed in as the
- * target to the {@link load(ConfigurationFile)} method. The file specified
- */
-public class RuleSet
-{
- private static final Logger _logger = Logger.getLogger(RuleSet.class);
-
- private static final String AT = "@";
- private static final String SLASH = "/";
-
- public static final String DEFAULT_ALLOW = "defaultallow";
- public static final String DEFAULT_DENY = "defaultdeny";
- public static final String TRANSITIVE = "transitive";
- public static final String EXPAND = "expand";
- public static final String AUTONUMBER = "autonumber";
- public static final String CONTROLLED = "controlled";
- public static final String VALIDATE = "validate";
-
- public static final List<String> CONFIG_PROPERTIES = Arrays.asList(
- DEFAULT_ALLOW, DEFAULT_DENY, TRANSITIVE, EXPAND, AUTONUMBER, CONTROLLED
- );
-
- private static final Integer _increment = 10;
-
- private final Map<String, List<String>> _groups = new HashMap<String, List<String>>();
- private final SortedMap<Integer, Rule> _rules = new TreeMap<Integer, Rule>();
- private final Map<String, Map<Operation, Map<ObjectType, List<Rule>>>> _cache =
- new WeakHashMap<String, Map<Operation, Map<ObjectType, List<Rule>>>>();
- private final Map<String, Boolean> _config = new HashMap<String, Boolean>();
-
- public RuleSet()
- {
- // set some default configuration properties
- configure(DEFAULT_DENY, Boolean.TRUE);
- configure(TRANSITIVE, Boolean.TRUE);
- }
-
- /**
- * Clear the contents, invluding groups, rules and configuration.
- */
- public void clear()
- {
- _rules.clear();
- _cache.clear();
- _config.clear();
- _groups.clear();
- }
-
- public int getRuleCount()
- {
- return _rules.size();
- }
-
- /**
- * Filtered rules list based on an identity and operation.
- *
- * Allows only enabled rules with identity equal to all, the same, or a group with identity as a member,
- * and operation is either all or the same operation.
- */
- public List<Rule> getRules(String identity, Operation operation, ObjectType objectType)
- {
- // Lookup identity in cache and create empty operation map if required
- Map<Operation, Map<ObjectType, List<Rule>>> operations = _cache.get(identity);
- if (operations == null)
- {
- operations = new EnumMap<Operation, Map<ObjectType, List<Rule>>>(Operation.class);
- _cache.put(identity, operations);
- }
-
- // Lookup operation and create empty object type map if required
- Map<ObjectType, List<Rule>> objects = operations.get(operation);
- if (objects == null)
- {
- objects = new EnumMap<ObjectType, List<Rule>>(ObjectType.class);
- operations.put(operation, objects);
- }
-
- // Lookup object type rules for the operation
- if (!objects.containsKey(objectType))
- {
- boolean controlled = false;
- List<Rule> filtered = new LinkedList<Rule>();
- for (Rule rule : _rules.values())
- {
- if (rule.isEnabled()
- && (rule.getAction().getOperation() == Operation.ALL || rule.getAction().getOperation() == operation)
- && (rule.getAction().getObjectType() == ObjectType.ALL || rule.getAction().getObjectType() == objectType))
- {
- controlled = true;
-
- if (rule.getIdentity().equalsIgnoreCase(Rule.ALL)
- || rule.getIdentity().equalsIgnoreCase(identity)
- || (_groups.containsKey(rule.getIdentity()) && _groups.get(rule.getIdentity()).contains(identity)))
- {
- filtered.add(rule);
- }
- }
- }
-
- // Return null if there are no rules at all for this operation and object type
- if (filtered.isEmpty() && controlled == false)
- {
- filtered = null;
- }
-
- // Save the rules we selected
- objects.put(objectType, filtered);
- }
-
- // Return the cached rules
- return objects.get(objectType);
- }
-
- public boolean isValidNumber(Integer number)
- {
- return !_rules.containsKey(number);
- }
-
- public void grant(Integer number, String identity, Permission permission, Operation operation)
- {
- Action action = new Action(operation);
- addRule(number, identity, permission, action);
- }
-
- public void grant(Integer number, String identity, Permission permission, Operation operation, ObjectType object, ObjectProperties properties)
- {
- Action action = new Action(operation, object, properties);
- addRule(number, identity, permission, action);
- }
-
- public boolean ruleExists(String identity, Action action)
- {
- for (Rule rule : _rules.values())
- {
- if (rule.getIdentity().equals(identity) && rule.getAction().equals(action))
- {
- return true;
- }
- }
- return false;
- }
-
- private Permission noLog(Permission permission)
- {
- switch (permission)
- {
- case ALLOW:
- case ALLOW_LOG:
- return Permission.ALLOW;
- case DENY:
- case DENY_LOG:
- default:
- return Permission.DENY;
- }
- }
-
- // TODO make this work when group membership is not known at file parse time
- public void addRule(Integer number, String identity, Permission permission, Action action)
- {
- if (!action.isAllowed())
- {
- throw new IllegalArgumentException("Action is not allowd: " + action);
- }
- if (ruleExists(identity, action))
- {
- return;
- }
-
- // expand actions - possibly multiply number by
- if (isSet(EXPAND))
- {
- if (action.getOperation() == Operation.CREATE && action.getObjectType() == ObjectType.TOPIC)
- {
- addRule(null, identity, noLog(permission), new Action(Operation.BIND, ObjectType.EXCHANGE,
- new ObjectProperties("amq.topic", action.getProperties().get(ObjectProperties.Property.NAME))));
- ObjectProperties topicProperties = new ObjectProperties();
- topicProperties.put(ObjectProperties.Property.DURABLE, true);
- addRule(null, identity, permission, new Action(Operation.CREATE, ObjectType.QUEUE, topicProperties));
- return;
- }
- if (action.getOperation() == Operation.DELETE && action.getObjectType() == ObjectType.TOPIC)
- {
- addRule(null, identity, noLog(permission), new Action(Operation.UNBIND, ObjectType.EXCHANGE,
- new ObjectProperties("amq.topic", action.getProperties().get(ObjectProperties.Property.NAME))));
- ObjectProperties topicProperties = new ObjectProperties();
- topicProperties.put(ObjectProperties.Property.DURABLE, true);
- addRule(null, identity, permission, new Action(Operation.DELETE, ObjectType.QUEUE, topicProperties));
- return;
- }
- }
-
- // transitive action dependencies
- if (isSet(TRANSITIVE))
- {
- if (action.getOperation() == Operation.CREATE && action.getObjectType() == ObjectType.QUEUE)
- {
- ObjectProperties exchProperties = new ObjectProperties(action.getProperties());
- exchProperties.setName(ExchangeDefaults.DEFAULT_EXCHANGE_NAME);
- exchProperties.put(ObjectProperties.Property.ROUTING_KEY, action.getProperties().get(ObjectProperties.Property.NAME));
- addRule(null, identity, noLog(permission), new Action(Operation.BIND, ObjectType.EXCHANGE, exchProperties));
- if (action.getProperties().isSet(ObjectProperties.Property.AUTO_DELETE))
- {
- addRule(null, identity, noLog(permission), new Action(Operation.DELETE, ObjectType.QUEUE, action.getProperties()));
- }
- }
- else if (action.getOperation() == Operation.DELETE && action.getObjectType() == ObjectType.QUEUE)
- {
- ObjectProperties exchProperties = new ObjectProperties(action.getProperties());
- exchProperties.setName(ExchangeDefaults.DEFAULT_EXCHANGE_NAME);
- exchProperties.put(ObjectProperties.Property.ROUTING_KEY, action.getProperties().get(ObjectProperties.Property.NAME));
- addRule(null, identity, noLog(permission), new Action(Operation.UNBIND, ObjectType.EXCHANGE, exchProperties));
- }
- else if (action.getOperation() != Operation.ACCESS && action.getObjectType() != ObjectType.VIRTUALHOST)
- {
- addRule(null, identity, noLog(permission), new Action(Operation.ACCESS, ObjectType.VIRTUALHOST));
- }
- }
-
- // set rule number if needed
- Rule rule = new Rule(number, identity, action, permission);
- if (rule.getNumber() == null)
- {
- if (_rules.isEmpty())
- {
- rule.setNumber(0);
- }
- else
- {
- rule.setNumber(_rules.lastKey() + _increment);
- }
- }
-
- // save rule
- _cache.remove(identity);
- _rules.put(rule.getNumber(), rule);
- }
-
- public void enableRule(int ruleNumber)
- {
- _rules.get(Integer.valueOf(ruleNumber)).enable();
- }
-
- public void disableRule(int ruleNumber)
- {
- _rules.get(Integer.valueOf(ruleNumber)).disable();
- }
-
- public boolean addGroup(String group, List<String> constituents)
- {
- if (_groups.containsKey(group))
- {
- // cannot redefine
- return false;
- }
- else
- {
- _groups.put(group, new ArrayList<String>());
- }
-
- for (String name : constituents)
- {
- if (name.equalsIgnoreCase(group))
- {
- // recursive definition
- return false;
- }
-
- if (!checkName(name))
- {
- // invalid name
- return false;
- }
-
- if (_groups.containsKey(name))
- {
- // is a group
- _groups.get(group).addAll(_groups.get(name));
- }
- else
- {
- // is a user
- if (!isvalidUserName(name))
- {
- // invalid username
- return false;
- }
- _groups.get(group).add(name);
- }
- }
- return true;
- }
-
- /** Return true if the name is well-formed (contains legal characters). */
- protected boolean checkName(String name)
- {
- for (int i = 0; i < name.length(); i++)
- {
- Character c = name.charAt(i);
- if (!Character.isLetterOrDigit(c) && c != '-' && c != '_' && c != '@' && c != '.' && c != '/')
- {
- return false;
- }
- }
- return true;
- }
-
- /** Returns true if a username has the name[@domain][/realm] format */
- protected boolean isvalidUserName(String name)
- {
- // check for '@' and '/' in namne
- int atPos = name.indexOf(AT);
- int slashPos = name.indexOf(SLASH);
- boolean atFound = atPos != StringUtils.INDEX_NOT_FOUND && atPos == name.lastIndexOf(AT);
- boolean slashFound = slashPos != StringUtils.INDEX_NOT_FOUND && slashPos == name.lastIndexOf(SLASH);
-
- // must be at least one character after '@' or '/'
- if (atFound && atPos > name.length() - 2)
- {
- return false;
- }
- if (slashFound && slashPos > name.length() - 2)
- {
- return false;
- }
-
- // must be at least one character between '@' and '/'
- if (atFound && slashFound)
- {
- return (atPos < (slashPos - 1));
- }
-
- // otherwise all good
- return true;
- }
-
- // C++ broker authorise function prototype
- // virtual bool authorise(const std::string& id, const Action& action, const ObjectType& objType,
- // const std::string& name, std::map<Property, std::string>* params=0);
-
- // Possibly add a String name paramater?
-
- /**
- * Check the authorisation granted to a particular identity for an operation on an object type with
- * specific properties.
- *
- * Looks up the entire ruleset, whcih may be cached, for the user and operation and goes through the rules
- * in order to find the first one that matches. Either defers if there are no rules, returns the result of
- * the first match found, or denies access if there are no matching rules. Normally, it would be expected
- * to have a default deny or allow rule at the end of an access configuration however.
- */
- public Result check(String identity, Operation operation, ObjectType objectType, ObjectProperties properties)
- {
- // Create the action to check
- Action action = new Action(operation, objectType, properties);
-
- // get the list of rules relevant for this request
- List<Rule> rules = getRules(identity, operation, objectType);
- if (rules == null)
- {
- if (isSet(CONTROLLED))
- {
- // Abstain if there are no rules for this operation
- return Result.ABSTAIN;
- }
- else
- {
- return getDefault();
- }
- }
-
- // Iterate through a filtered set of rules dealing with this identity and operation
- for (Rule current : rules)
- {
- // Check if action matches
- if (action.matches(current.getAction()))
- {
- Permission permission = current.getPermission();
-
- switch (permission)
- {
- case ALLOW_LOG:
- CurrentActor.get().message(AccessControlMessages.ALLOWED(
- action.getOperation().toString(), action.getObjectType().toString(), action.getProperties().toString()));
- case ALLOW:
- return Result.ALLOWED;
- case DENY_LOG:
- CurrentActor.get().message(AccessControlMessages.DENIED(
- action.getOperation().toString(), action.getObjectType().toString(), action.getProperties().toString()));
- case DENY:
- return Result.DENIED;
- }
-
- return Result.DENIED;
- }
- }
-
- // Defer to the next plugin of this type, if it exists
- return Result.DEFER;
- }
-
- /** Default deny. */
- public Result getDefault()
- {
- if (isSet(DEFAULT_ALLOW))
- {
- return Result.ALLOWED;
- }
- if (isSet(DEFAULT_DENY))
- {
- return Result.DENIED;
- }
- return Result.ABSTAIN;
- }
-
- /**
- * Check if a configuration property is set.
- */
- protected boolean isSet(String key)
- {
- return BooleanUtils.isTrue(_config.get(key));
- }
-
- /**
- * Configure properties for the plugin instance.
- *
- * @param properties
- */
- public void configure(Map<String, Boolean> properties)
- {
- _config.putAll(properties);
- }
-
- /**
- * Configure a single property for the plugin instance.
- *
- * @param key
- * @param value
- */
- public void configure(String key, Boolean value)
- {
- _config.put(key, value);
- }
-}
diff --git a/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/XMLConfiguration.java b/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/XMLConfiguration.java
deleted file mode 100644
index a4f6f8b65a..0000000000
--- a/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/XMLConfiguration.java
+++ /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.
- *
- */
-package org.apache.qpid.server.security.access.config;
-
-import java.io.File;
-
-public class XMLConfiguration extends AbstractConfiguration
-{
- public XMLConfiguration(File file)
- {
- super(file);
- }
-}
diff --git a/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/logging/AccessControl_logmessages.properties b/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/logging/AccessControl_logmessages.properties
deleted file mode 100644
index bf80df3722..0000000000
--- a/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/logging/AccessControl_logmessages.properties
+++ /dev/null
@@ -1,28 +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.
-#
-
-# org.apache.qpid.server.security.access.logging.AccessControl
-
-# Access Control logging message i18n strings.
-
-# 'accept-log' rule message
-ALLOWED = ACL-1001 : Allowed : {0} {1} {2}
-
-# 'deny-log' rule message
-DENIED = ACL-1002 : Denied : {0} {1} {2} \ No newline at end of file
diff --git a/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/AccessControl.java b/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/AccessControl.java
deleted file mode 100644
index 69cfa173bd..0000000000
--- a/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/AccessControl.java
+++ /dev/null
@@ -1,116 +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.security.Principal;
-
-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.AbstractPlugin;
-import org.apache.qpid.server.security.Result;
-import org.apache.qpid.server.security.SecurityManager;
-import org.apache.qpid.server.security.SecurityPluginFactory;
-import org.apache.qpid.server.security.access.ObjectProperties;
-import org.apache.qpid.server.security.access.ObjectType;
-import org.apache.qpid.server.security.access.Operation;
-import org.apache.qpid.server.security.access.config.RuleSet;
-
-/**
- * This access control plugin implements version two plain text access control.
- */
-public class AccessControl extends AbstractPlugin
-{
- public static final Logger _logger = Logger.getLogger(AccessControl.class);
-
- private RuleSet _ruleSet;
-
- public static final SecurityPluginFactory<AccessControl> FACTORY = new SecurityPluginFactory<AccessControl>()
- {
- public Class<AccessControl> getPluginClass()
- {
- return AccessControl.class;
- }
-
- public String getPluginName()
- {
- return AccessControl.class.getName();
- }
-
- public AccessControl newInstance(ConfigurationPlugin config) throws ConfigurationException
- {
- AccessControlConfiguration configuration = config.getConfiguration(AccessControlConfiguration.class.getName());
-
- // If there is no configuration for this plugin then don't load it.
- if (configuration == null)
- {
- return null;
- }
-
- AccessControl plugin = new AccessControl();
- plugin.configure(configuration);
- return plugin;
- }
- };
-
- public Result getDefault()
- {
- return _ruleSet.getDefault();
- }
-
- /**
- * Object instance access authorisation.
- *
- * Delegate to the {@link #authorise(Operation, ObjectType, ObjectProperties)} method, with
- * the operation set to ACCESS and no object properties.
- */
- public Result access(ObjectType objectType, Object instance)
- {
- return authorise(Operation.ACCESS, objectType, ObjectProperties.EMPTY);
- }
-
- /**
- * Check if an operation is authorised by asking the configuration object about the access
- * control rules granted to the current thread's {@link Principal}. If there is no current
- * user the plugin will abstain.
- */
- public Result authorise(Operation operation, ObjectType objectType, ObjectProperties properties)
- {
- Principal principal = SecurityManager.getThreadPrincipal();
-
- // Abstain if there is no user associated with this thread
- if (principal == null)
- {
- return Result.ABSTAIN;
- }
-
- return _ruleSet.check(principal.getName(), operation, objectType, properties);
- }
-
- public void configure(ConfigurationPlugin config)
- {
- super.configure(config);
-
- AccessControlConfiguration accessConfig = (AccessControlConfiguration) _config;
-
- _ruleSet = accessConfig.getRuleSet();
- }
-}
diff --git a/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/AccessControlActivator.java b/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/AccessControlActivator.java
deleted file mode 100644
index 72eac7dbe6..0000000000
--- a/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/AccessControlActivator.java
+++ /dev/null
@@ -1,42 +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 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}.
- */
-public class AccessControlActivator extends SecurityPluginActivator
-{
- public SecurityPluginFactory getFactory()
- {
- return AccessControl.FACTORY;
- }
-
- public ConfigurationPluginFactory getConfigurationFactory()
- {
- return AccessControlConfiguration.FACTORY;
- }
-}
diff --git a/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/AccessControlConfiguration.java b/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/AccessControlConfiguration.java
deleted file mode 100644
index f7db740ebc..0000000000
--- a/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/AccessControlConfiguration.java
+++ /dev/null
@@ -1,83 +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.io.File;
-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.access.config.ConfigurationFile;
-import org.apache.qpid.server.security.access.config.PlainConfiguration;
-import org.apache.qpid.server.security.access.config.RuleSet;
-
-public class AccessControlConfiguration extends ConfigurationPlugin
-{
- public static final ConfigurationPluginFactory FACTORY = new ConfigurationPluginFactory()
- {
- public ConfigurationPlugin newInstance(String path, Configuration config) throws ConfigurationException
- {
- ConfigurationPlugin instance = new AccessControlConfiguration();
- instance.setConfiguration(path, config);
- return instance;
- }
-
- public List<String> getParentPaths()
- {
- return Arrays.asList("security.aclv2", "virtualhosts.virtualhost.security.aclv2");
- }
- };
-
- private RuleSet _ruleSet;
-
- public String[] getElementsProcessed()
- {
- return new String[] { "" };
- }
-
- public String getFileName()
- {
- return _configuration.getString("");
- }
-
- public void validateConfiguration() throws ConfigurationException
- {
- String filename = getFileName();
- if (filename == null)
- {
- throw new ConfigurationException("No ACL file name specified");
- }
-
- File aclFile = new File(filename);
-
- ConfigurationFile configFile = new PlainConfiguration(aclFile);
- _ruleSet = configFile.load();
- }
-
- public RuleSet getRuleSet()
- {
- return _ruleSet;
- }
-
-}
diff --git a/java/broker-plugins/access-control/src/main/resources/acl.xsd b/java/broker-plugins/access-control/src/main/resources/acl.xsd
deleted file mode 100644
index 9a165b50b8..0000000000
--- a/java/broker-plugins/access-control/src/main/resources/acl.xsd
+++ /dev/null
@@ -1,29 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- -
- - Licensed to the Apache Software Foundation (ASF) under one
- - or more contributor license agreements. See the NOTICE file
- - distributed with this work for additional information
- - regarding copyright ownership. The ASF licenses this file
- - to you under the Apache License, Version 2.0 (the
- - "License"); you may not use this file except in compliance
- - with the License. You may obtain a copy of the License at
- -
- - http://www.apache.org/licenses/LICENSE-2.0
- -
- - Unless required by applicable law or agreed to in writing,
- - software distributed under the License is distributed on an
- - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- - KIND, either express or implied. See the License for the
- - specific language governing permissions and limitations
- - under the License.
- -
- -->
-<xs:schema
- xmlns="http://qpid.apache.org/schema/qpid/broker/security/acl.xsd"
- xmlns:xs="http://www.w3.org/2001/XMLSchema"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- targetNamespace="http://qpid.apache.org/schema/qpid/broker/security/acl.xsd"
- elementFormDefault="qualified">
- <xs:element name="aclv2" type="xs:string" />
-</xs:schema>
diff --git a/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/AccessControlTest.java b/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/AccessControlTest.java
deleted file mode 100644
index 309a3aeb2c..0000000000
--- a/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/AccessControlTest.java
+++ /dev/null
@@ -1,195 +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.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileWriter;
-import java.io.PrintWriter;
-
-import junit.framework.TestCase;
-
-import org.apache.commons.configuration.ConfigurationException;
-import org.apache.qpid.server.security.access.config.ConfigurationFile;
-import org.apache.qpid.server.security.access.config.PlainConfiguration;
-import org.apache.qpid.server.security.access.config.RuleSet;
-
-/**
- * These tests check that the ACL file parsing works correctly.
- *
- * For each message that can be returned in a {@link ConfigurationException}, an ACL file is created that should trigger this
- * particular message.
- */
-public class AccessControlTest extends TestCase
-{
- public void writeACLConfig(String...aclData) throws Exception
- {
- File acl = File.createTempFile(getClass().getName() + getName(), "acl");
- acl.deleteOnExit();
-
- // Write ACL file
- PrintWriter aclWriter = new PrintWriter(new FileWriter(acl));
- for (String line : aclData)
- {
- aclWriter.println(line);
- }
- aclWriter.close();
-
- // Load ruleset
- ConfigurationFile configFile = new PlainConfiguration(acl);
- RuleSet ruleSet = configFile.load();
- }
-
- public void testMissingACLConfig() throws Exception
- {
- try
- {
- // Load ruleset
- ConfigurationFile configFile = new PlainConfiguration(new File("doesnotexist"));
- RuleSet ruleSet = configFile.load();
-
- fail("fail");
- }
- catch (ConfigurationException ce)
- {
- assertEquals(String.format(PlainConfiguration.CONFIG_NOT_FOUND_MSG, "doesnotexist"), ce.getMessage());
- assertTrue(ce.getCause() instanceof FileNotFoundException);
- assertEquals("doesnotexist (No such file or directory)", ce.getCause().getMessage());
- }
- }
-
- public void testACLFileSyntaxContinuation() throws Exception
- {
- try
- {
- writeACLConfig("ACL ALLOW ALL \\ ALL");
- fail("fail");
- }
- catch (ConfigurationException ce)
- {
- assertEquals(String.format(PlainConfiguration.PREMATURE_CONTINUATION_MSG, 1), ce.getMessage());
- }
- }
-
- public void testACLFileSyntaxTokens() throws Exception
- {
- try
- {
- writeACLConfig("ACL unparsed ALL ALL");
- fail("fail");
- }
- catch (ConfigurationException ce)
- {
- assertEquals(String.format(PlainConfiguration.PARSE_TOKEN_FAILED_MSG, 1), ce.getMessage());
- assertTrue(ce.getCause() instanceof IllegalArgumentException);
- assertEquals("Not a valid permission: unparsed", ce.getCause().getMessage());
- }
- }
-
- public void testACLFileSyntaxNotEnoughGroup() throws Exception
- {
- try
- {
- writeACLConfig("GROUP blah");
- fail("fail");
- }
- catch (ConfigurationException ce)
- {
- assertEquals(String.format(PlainConfiguration.NOT_ENOUGH_GROUP_MSG, 1), ce.getMessage());
- }
- }
-
- public void testACLFileSyntaxNotEnoughACL() throws Exception
- {
- try
- {
- writeACLConfig("ACL ALLOW");
- fail("fail");
- }
- catch (ConfigurationException ce)
- {
- assertEquals(String.format(PlainConfiguration.NOT_ENOUGH_ACL_MSG, 1), ce.getMessage());
- }
- }
-
- public void testACLFileSyntaxNotEnoughConfig() throws Exception
- {
- try
- {
- writeACLConfig("CONFIG");
- fail("fail");
- }
- catch (ConfigurationException ce)
- {
- assertEquals(String.format(PlainConfiguration.NOT_ENOUGH_TOKENS_MSG, 1), ce.getMessage());
- }
- }
-
- public void testACLFileSyntaxNotEnough() throws Exception
- {
- try
- {
- writeACLConfig("INVALID");
- fail("fail");
- }
- catch (ConfigurationException ce)
- {
- assertEquals(String.format(PlainConfiguration.NOT_ENOUGH_TOKENS_MSG, 1), ce.getMessage());
- }
- }
-
- public void testACLFileSyntaxPropertyKeyOnly() throws Exception
- {
- try
- {
- writeACLConfig("ACL ALLOW adk CREATE QUEUE name");
- fail("fail");
- }
- catch (ConfigurationException ce)
- {
- assertEquals(String.format(PlainConfiguration.PROPERTY_KEY_ONLY_MSG, 1), ce.getMessage());
- }
- }
-
- public void testACLFileSyntaxPropertyNoEquals() throws Exception
- {
- try
- {
- writeACLConfig("ACL ALLOW adk CREATE QUEUE name test");
- fail("fail");
- }
- catch (ConfigurationException ce)
- {
- assertEquals(String.format(PlainConfiguration.PROPERTY_NO_EQUALS_MSG, 1), ce.getMessage());
- }
- }
-
- public void testACLFileSyntaxPropertyNoValue() throws Exception
- {
- try
- {
- writeACLConfig("ACL ALLOW adk CREATE QUEUE name =");
- fail("fail");
- }
- catch (ConfigurationException ce)
- {
- assertEquals(String.format(PlainConfiguration.PROPERTY_NO_VALUE_MSG, 1), ce.getMessage());
- }
- }
-}
diff --git a/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/RuleSetTest.java b/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/RuleSetTest.java
deleted file mode 100644
index aad7290557..0000000000
--- a/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/RuleSetTest.java
+++ /dev/null
@@ -1,289 +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 org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.server.security.Result;
-import org.apache.qpid.server.security.access.ObjectProperties;
-import org.apache.qpid.server.security.access.ObjectType;
-import org.apache.qpid.server.security.access.Operation;
-import org.apache.qpid.server.security.access.Permission;
-import org.apache.qpid.server.security.access.config.RuleSet;
-import org.apache.qpid.test.utils.QpidTestCase;
-
-/**
- * This test checks that the {@link RuleSet} object which forms the core of the access control plugin performs correctly.
- *
- * The ruleset is configured directly rather than using an external file by adding rules individually, calling the
- * {@link RuleSet#grant(Integer, String, Permission, Operation, ObjectType, ObjectProperties)} method. Then, the
- * access control mechanism is validated by checking whether operations would be authorised by calling the
- * {@link RuleSet#check(String, Operation, ObjectType, ObjectProperties)} method.
- */
-public class RuleSetTest extends QpidTestCase
-{
- private RuleSet _ruleSet;
-
- // Common things that are passed to frame constructors
- private AMQShortString _queueName = new AMQShortString(this.getClass().getName() + "queue");
- private AMQShortString _exchangeName = new AMQShortString("amq.direct");
- private AMQShortString _exchangeType = new AMQShortString("direct");
-
- @Override
- public void setUp() throws Exception
- {
- super.setUp();
-
- _ruleSet = new RuleSet();
- _ruleSet.configure(RuleSet.TRANSITIVE, Boolean.FALSE);
- }
-
- @Override
- public void tearDown() throws Exception
- {
- _ruleSet.clear();
- super.tearDown();
- }
-
- public void assertDenyGrantAllow(String identity, Operation operation, ObjectType objectType)
- {
- assertDenyGrantAllow(identity, operation, objectType, ObjectProperties.EMPTY);
- }
-
- public void assertDenyGrantAllow(String identity, Operation operation, ObjectType objectType, ObjectProperties properties)
- {
- assertEquals(Result.DENIED, _ruleSet.check(identity, operation, objectType, properties));
- _ruleSet.grant(0, identity, Permission.ALLOW, operation, objectType, properties);
- assertEquals(1, _ruleSet.getRuleCount());
- assertEquals(Result.ALLOWED, _ruleSet.check(identity, operation, objectType, properties));
- }
-
- public void testEmptyRuleSet()
- {
- assertNotNull(_ruleSet);
- assertEquals(_ruleSet.getRuleCount(), 0);
- assertEquals(_ruleSet.getDefault(), _ruleSet.check("user", Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY));
- }
-
- public void testVirtualHostAccess() throws Exception
- {
- assertDenyGrantAllow("user", Operation.ACCESS, ObjectType.VIRTUALHOST);
- }
-
- public void testQueueCreateNamed() throws Exception
- {
- assertDenyGrantAllow("user", Operation.CREATE, ObjectType.QUEUE, new ObjectProperties(_queueName));
- }
-
- public void testQueueCreatenamedNullRoutingKey()
- {
- ObjectProperties properties = new ObjectProperties(_queueName);
- properties.put(ObjectProperties.Property.ROUTING_KEY, (String) null);
-
- assertDenyGrantAllow("user", Operation.CREATE, ObjectType.QUEUE, properties);
- }
-
- public void testExchangeCreate()
- {
- ObjectProperties properties = new ObjectProperties(_exchangeName);
- properties.put(ObjectProperties.Property.TYPE, _exchangeType.asString());
-
- assertDenyGrantAllow("user", Operation.CREATE, ObjectType.EXCHANGE, properties);
- }
-
- public void testConsume()
- {
- assertDenyGrantAllow("user", Operation.CONSUME, ObjectType.QUEUE);
- }
-
- public void testPublish()
- {
- assertDenyGrantAllow("user", Operation.PUBLISH, ObjectType.EXCHANGE);
- }
-
- /**
- * If the consume permission for temporary queues is for an unnamed queue then it should
- * be global for any temporary queue but not for any non-temporary queue
- */
- public void testTemporaryUnnamedQueueConsume()
- {
- ObjectProperties temporary = new ObjectProperties();
- temporary.put(ObjectProperties.Property.AUTO_DELETE, Boolean.TRUE);
-
- ObjectProperties normal = new ObjectProperties();
- normal.put(ObjectProperties.Property.AUTO_DELETE, Boolean.FALSE);
-
- assertEquals(Result.DENIED, _ruleSet.check("user", Operation.CONSUME, ObjectType.QUEUE, temporary));
- _ruleSet.grant(0, "user", Permission.ALLOW, Operation.CONSUME, ObjectType.QUEUE, temporary);
- assertEquals(1, _ruleSet.getRuleCount());
- assertEquals(Result.ALLOWED, _ruleSet.check("user", Operation.CONSUME, ObjectType.QUEUE, temporary));
-
- // defer to global if exists, otherwise default answer - this is handled by the security manager
- assertEquals(Result.DEFER, _ruleSet.check("user", Operation.CONSUME, ObjectType.QUEUE, normal));
- }
-
- /**
- * Test that temporary queue permissions before queue perms in the ACL config work correctly
- */
- public void testTemporaryQueueFirstConsume()
- {
- ObjectProperties temporary = new ObjectProperties(_queueName);
- temporary.put(ObjectProperties.Property.AUTO_DELETE, Boolean.TRUE);
-
- ObjectProperties normal = new ObjectProperties(_queueName);
- normal.put(ObjectProperties.Property.AUTO_DELETE, Boolean.FALSE);
-
- assertEquals(Result.DENIED, _ruleSet.check("user", Operation.CONSUME, ObjectType.QUEUE, temporary));
-
- // should not matter if the temporary permission is processed first or last
- _ruleSet.grant(1, "user", Permission.ALLOW, Operation.CONSUME, ObjectType.QUEUE, normal);
- _ruleSet.grant(2, "user", Permission.ALLOW, Operation.CONSUME, ObjectType.QUEUE, temporary);
- assertEquals(2, _ruleSet.getRuleCount());
-
- assertEquals(Result.ALLOWED, _ruleSet.check("user", Operation.CONSUME, ObjectType.QUEUE, normal));
- assertEquals(Result.ALLOWED, _ruleSet.check("user", Operation.CONSUME, ObjectType.QUEUE, temporary));
- }
-
- /**
- * Test that temporary queue permissions after queue perms in the ACL config work correctly
- */
- public void testTemporaryQueueLastConsume()
- {
- ObjectProperties temporary = new ObjectProperties(_queueName);
- temporary.put(ObjectProperties.Property.AUTO_DELETE, Boolean.TRUE);
-
- ObjectProperties normal = new ObjectProperties(_queueName);
- normal.put(ObjectProperties.Property.AUTO_DELETE, Boolean.FALSE);
-
- assertEquals(Result.DENIED, _ruleSet.check("user", Operation.CONSUME, ObjectType.QUEUE, temporary));
-
- // should not matter if the temporary permission is processed first or last
- _ruleSet.grant(1, "user", Permission.ALLOW, Operation.CONSUME, ObjectType.QUEUE, temporary);
- _ruleSet.grant(2, "user", Permission.ALLOW, Operation.CONSUME, ObjectType.QUEUE, normal);
- assertEquals(2, _ruleSet.getRuleCount());
-
- assertEquals(Result.ALLOWED, _ruleSet.check("user", Operation.CONSUME, ObjectType.QUEUE, normal));
- assertEquals(Result.ALLOWED, _ruleSet.check("user", Operation.CONSUME, ObjectType.QUEUE, temporary));
- }
-
- /*
- * Test different rules for temporary queues.
- */
-
- /**
- * The more generic rule first is used, so both requests are allowed.
- */
- public void testFirstNamedSecondTemporaryQueueDenied()
- {
- ObjectProperties named = new ObjectProperties(_queueName);
- ObjectProperties namedTemporary = new ObjectProperties(_queueName);
- namedTemporary.put(ObjectProperties.Property.AUTO_DELETE, Boolean.TRUE);
-
- assertEquals(Result.DENIED, _ruleSet.check("user", Operation.CREATE, ObjectType.QUEUE, named));
- assertEquals(Result.DENIED, _ruleSet.check("user", Operation.CREATE, ObjectType.QUEUE, namedTemporary));
-
- _ruleSet.grant(1, "user", Permission.ALLOW, Operation.CREATE, ObjectType.QUEUE, named);
- _ruleSet.grant(2, "user", Permission.DENY, Operation.CREATE, ObjectType.QUEUE, namedTemporary);
- assertEquals(2, _ruleSet.getRuleCount());
-
- assertEquals(Result.ALLOWED, _ruleSet.check("user", Operation.CREATE, ObjectType.QUEUE, named));
- assertEquals(Result.ALLOWED, _ruleSet.check("user", Operation.CREATE, ObjectType.QUEUE, namedTemporary));
- }
-
- /**
- * The more specific rule is first, so those requests are denied.
- */
- public void testFirstTemporarySecondNamedQueueDenied()
- {
- ObjectProperties named = new ObjectProperties(_queueName);
- ObjectProperties namedTemporary = new ObjectProperties(_queueName);
- namedTemporary.put(ObjectProperties.Property.AUTO_DELETE, Boolean.TRUE);
-
- assertEquals(Result.DENIED, _ruleSet.check("user", Operation.CREATE, ObjectType.QUEUE, named));
- assertEquals(Result.DENIED, _ruleSet.check("user", Operation.CREATE, ObjectType.QUEUE, namedTemporary));
-
- _ruleSet.grant(1, "user", Permission.DENY, Operation.CREATE, ObjectType.QUEUE, namedTemporary);
- _ruleSet.grant(2, "user", Permission.ALLOW, Operation.CREATE, ObjectType.QUEUE, named);
- assertEquals(2, _ruleSet.getRuleCount());
-
- assertEquals(Result.ALLOWED, _ruleSet.check("user", Operation.CREATE, ObjectType.QUEUE, named));
- assertEquals(Result.DENIED, _ruleSet.check("user", Operation.CREATE, ObjectType.QUEUE, namedTemporary));
- }
-
- /**
- * The more specific rules are first, so those requests are denied.
- */
- public void testFirstTemporarySecondDurableThirdNamedQueueDenied()
- {
- ObjectProperties named = new ObjectProperties(_queueName);
- ObjectProperties namedTemporary = new ObjectProperties(_queueName);
- namedTemporary.put(ObjectProperties.Property.AUTO_DELETE, Boolean.TRUE);
- ObjectProperties namedDurable = new ObjectProperties(_queueName);
- namedDurable.put(ObjectProperties.Property.DURABLE, Boolean.TRUE);
-
- assertEquals(Result.DENIED, _ruleSet.check("user", Operation.CREATE, ObjectType.QUEUE, named));
- assertEquals(Result.DENIED, _ruleSet.check("user", Operation.CREATE, ObjectType.QUEUE, namedTemporary));
- assertEquals(Result.DENIED, _ruleSet.check("user", Operation.CREATE, ObjectType.QUEUE, namedDurable));
-
- _ruleSet.grant(1, "user", Permission.DENY, Operation.CREATE, ObjectType.QUEUE, namedTemporary);
- _ruleSet.grant(2, "user", Permission.DENY, Operation.CREATE, ObjectType.QUEUE, namedDurable);
- _ruleSet.grant(3, "user", Permission.ALLOW, Operation.CREATE, ObjectType.QUEUE, named);
- assertEquals(3, _ruleSet.getRuleCount());
-
- assertEquals(Result.ALLOWED, _ruleSet.check("user", Operation.CREATE, ObjectType.QUEUE, named));
- assertEquals(Result.DENIED, _ruleSet.check("user", Operation.CREATE, ObjectType.QUEUE, namedTemporary));
- assertEquals(Result.DENIED, _ruleSet.check("user", Operation.CREATE, ObjectType.QUEUE, namedDurable));
- }
-
- public void testNamedTemporaryQueueAllowed()
- {
- ObjectProperties named = new ObjectProperties(_queueName);
- ObjectProperties namedTemporary = new ObjectProperties(_queueName);
- namedTemporary.put(ObjectProperties.Property.AUTO_DELETE, Boolean.TRUE);
-
- assertEquals(Result.DENIED, _ruleSet.check("user", Operation.CREATE, ObjectType.QUEUE, named));
- assertEquals(Result.DENIED, _ruleSet.check("user", Operation.CREATE, ObjectType.QUEUE, namedTemporary));
-
- _ruleSet.grant(1, "user", Permission.ALLOW, Operation.CREATE, ObjectType.QUEUE, namedTemporary);
- _ruleSet.grant(2, "user", Permission.ALLOW, Operation.CREATE, ObjectType.QUEUE, named);
- assertEquals(2, _ruleSet.getRuleCount());
-
- assertEquals(Result.ALLOWED, _ruleSet.check("user", Operation.CREATE, ObjectType.QUEUE, named));
- assertEquals(Result.ALLOWED, _ruleSet.check("user", Operation.CREATE, ObjectType.QUEUE, namedTemporary));
- }
-
- public void testNamedTemporaryQueueDeniedAllowed()
- {
- ObjectProperties named = new ObjectProperties(_queueName);
- ObjectProperties namedTemporary = new ObjectProperties(_queueName);
- namedTemporary.put(ObjectProperties.Property.AUTO_DELETE, Boolean.TRUE);
-
- assertEquals(Result.DENIED, _ruleSet.check("user", Operation.CREATE, ObjectType.QUEUE, named));
- assertEquals(Result.DENIED, _ruleSet.check("user", Operation.CREATE, ObjectType.QUEUE, namedTemporary));
-
- _ruleSet.grant(1, "user", Permission.ALLOW, Operation.CREATE, ObjectType.QUEUE, namedTemporary);
- _ruleSet.grant(2, "user", Permission.DENY, Operation.CREATE, ObjectType.QUEUE, named);
- assertEquals(2, _ruleSet.getRuleCount());
-
- assertEquals(Result.DENIED, _ruleSet.check("user", Operation.CREATE, ObjectType.QUEUE, named));
- assertEquals(Result.ALLOWED, _ruleSet.check("user", Operation.CREATE, ObjectType.QUEUE, namedTemporary));
- }
-}
diff --git a/java/broker-plugins/experimental/info/MANIFEST.MF b/java/broker-plugins/experimental/info/MANIFEST.MF
deleted file mode 100644
index f213104d8d..0000000000
--- a/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/java/broker-plugins/experimental/info/build.properties b/java/broker-plugins/experimental/info/build.properties
deleted file mode 100644
index bdbbe1c2af..0000000000
--- a/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/java/broker-plugins/experimental/info/build.xml b/java/broker-plugins/experimental/info/build.xml
deleted file mode 100644
index c5881aa839..0000000000
--- a/java/broker-plugins/experimental/info/build.xml
+++ /dev/null
@@ -1,32 +0,0 @@
-<!--
- -
- - Licensed to the Apache Software Foundation (ASF) under one
-nn - or more contributor license agreements. See the NOTICE file
- -n distributed with this work for additional information
- - regarding copyright ownership. The ASF licenses this file
- - to you under the Apache License, Version 2.0 (the
- - "License"); you may not use this file except in compliance
- - with the License. You may obtain a copy of the License at
- -
- - http://www.apache.org/licenses/LICENSE-2.0
- -
- - Unless required by applicable law or agreed to in writing,
- - software distributed under the License is distributed on an
- - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- - KIND, either express or implied. See the License for the
- - specific language governing permissions and limitations
- - under the License.
- -
- -->
-<project name="AMQ Broker Info Plugin" default="build">
-
- <property name="module.depends" value="common broker broker-plugins"/>
- <property name="module.test.depends" value="test broker/test management/common client systests common/test"/>
- <property name="module.manifest" value="MANIFEST.MF"/>
- <property name="module.plugin" value="true"/>
-
- <import file="../../../module.xml"/>
-
- <target name="bundle" depends="bundle-tasks"/>
-
-</project>
diff --git a/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/Activator.java b/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/Activator.java
deleted file mode 100644
index c7d3fd38ff..0000000000
--- a/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/Activator.java
+++ /dev/null
@@ -1,204 +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<String> _soapPropList = Arrays.asList("soap.hostname",
- "soap.port", "soap.path", "soap.action", "soap.envelope");
-
- private final List<String> _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);
- sendInfo("STARTUP");
- }
- }
-
- /**
- * 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<? extends Map<String, ?>> 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<? extends Map<String, ?>> 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/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/AppInfo.java b/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/AppInfo.java
deleted file mode 100644
index a5d267282b..0000000000
--- a/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/AppInfo.java
+++ /dev/null
@@ -1,94 +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<String> appProps = Arrays.asList("QPID_HOME",
- "QPID_WORK");
-
- private static Map<String, String> appInfoMap = new TreeMap<String, String>();
-
- /**
- * getInfo method retrieves a key-value map for specific application properties
- *
- * @return Map<String,String>
- */
- public static Map<String, String> getInfo()
- {
-
- // Gather the selected app props
- Properties sysprops = System.getProperties();
- String propName;
- for (Iterator<Entry<Object, Object>> it = sysprops.entrySet()
- .iterator(); it.hasNext();)
- {
- Entry<Object, Object> 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.getJMXManagementPort() + "");
- appInfoMap.put("port", sc.getPorts().toString());
- appInfoMap.put("version", QpidProperties.getReleaseVersion());
- appInfoMap.put("vhosts", "standalone");
- appInfoMap.put("JMXPrincipalDatabase", sc
- .getJMXPrincipalDatabase());
- appInfoMap.put("KeystorePath", sc.getKeystorePath());
- appInfoMap.put("PluginDirectory", sc.getPluginDirectory());
- appInfoMap.put("CertType", sc.getCertType());
- appInfoMap.put("QpidWork", sc.getQpidWork());
- appInfoMap.put("Bind", sc.getBind());
- }
- }
- catch (Exception e)
- {
- // drop everything to be silent
- }
- return appInfoMap;
-
- }
-
-}
diff --git a/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/Info.java b/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/Info.java
deleted file mode 100644
index 2fb9382526..0000000000
--- a/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<T extends Map<String, ?>>
-{
- private T _info;
-
- /**
- * Constructor.
- *
- * @param info instantiates the object with a Map<String,?>
- */
- public Info(T info)
- {
- _info = info;
- }
-
- @Override
- public String toString()
- {
- String result = "";
- for (Iterator<String> 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<String> 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<String> 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<String, String> attr = new HashMap<String, String>();
- xw.writeOpenTag("qpidinfo", attr);
- String key;
- for (Iterator<String> 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<String, String> toMap()
- {
- String key;
- HashMap<String, String> infoMap = new HashMap<String, String>();
- for (Iterator<String> it = _info.keySet().iterator(); it.hasNext();)
- {
- key = it.next();
- infoMap.put(key, _info.get(key).toString());
- }
- return infoMap;
- }
-
-}
diff --git a/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/InfoService.java b/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/InfoService.java
deleted file mode 100644
index 2804dfb1b4..0000000000
--- a/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/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/InfoServiceImpl.java b/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/InfoServiceImpl.java
deleted file mode 100644
index 5522f2701e..0000000000
--- a/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<String, String> infoMap = new TreeMap<String, String>();
-
- /**
- * 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<? extends Map<String,?>> 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<SortedMap<String, String>>(infoMap);
- }
-
-}
diff --git a/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/SystemInfo.java b/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/SystemInfo.java
deleted file mode 100644
index 8bd94fe14d..0000000000
--- a/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<String, String> sysInfoMap = new TreeMap<String, String>();
-
- private static final List<String> 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<String,String>
- */
- public static Map<String, String> 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<Entry<Object, Object>> it = sysprops.entrySet()
- .iterator(); it.hasNext();)
- {
- Entry<Object, Object> en = it.next();
- propName = en.getKey().toString();
- if (sysProps.indexOf(propName) >= 0)
- {
- sysInfoMap.put(propName, en.getValue().toString());
- }
- }
-
- return sysInfoMap;
-
- }
-
-}
diff --git a/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/util/HttpPoster.java b/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/util/HttpPoster.java
deleted file mode 100644
index d27980be05..0000000000
--- a/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<String, String> _header;
-
- private final List<String> _response = new ArrayList<String>();
-
- 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<String, String>();
- 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<String> 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<String> response received from the http server
- */
- public List<String> get_response()
- {
- return _response;
- }
-
-}
diff --git a/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/util/IniFileReader.java b/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/util/IniFileReader.java
deleted file mode 100644
index 60a025d322..0000000000
--- a/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 <String,Properties> (section name, associated properties)
- * is generated as a result of processing the ini file.
- */
-public class IniFileReader
-{
- private final Map<String, Properties> _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<String, Properties>();
- }
-
- /**
- * 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<String,Properties> The parsed content of the ini file in this structure
- */
- public Map<String, Properties> getSections()
- {
- return _sections;
- }
-
-}
diff --git a/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/util/SoapClient.java b/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/util/SoapClient.java
deleted file mode 100644
index 0f66085fc3..0000000000
--- a/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<String, String> 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<String, String> 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/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/util/XMLWriter.java b/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/util/XMLWriter.java
deleted file mode 100644
index a266edae00..0000000000
--- a/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("<?xml version=\"1.0\"?>\n");
- }
-
- public void writeTag(String tagName, Map<String, String> attributes,
- String value)
- {
- writeOpenTag(tagName, attributes);
- writeValue(value);
- writeCloseTag(tagName);
- }
-
- public void writeOpenTag(String tagName, Map<String, String> 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("</" + tagName + ">\n");
- }
-
- private String escapeXML(String xmlStr)
- {
- if (null == xmlStr)
- return null;
- xmlStr = xmlStr.replaceAll("&", "&amp;");
- xmlStr = xmlStr.replace("<", "&lt;");
- xmlStr = xmlStr.replace(">", "&gt;");
- xmlStr = xmlStr.replace("\"", "&quot;");
- xmlStr = xmlStr.replace("'", "&apos;");
- return xmlStr;
- }
-
-}
diff --git a/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/systest/InfoPluginTest.java b/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/systest/InfoPluginTest.java
deleted file mode 100644
index 156c9eb138..0000000000
--- a/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/systest/InfoPluginTest.java
+++ /dev/null
@@ -1,276 +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 = "<?xml version=\"1.0\"?><soap:Envelope xmlns:soap=\"http://www.w3.org/2001/12/soap-envelope\" soap:encodingStyle=\"http://www.w3.org/2001/12/soap-encoding\">";
-
- private final String _soapEnvelopeTail = "</soap:Envelope>";
-
- private String _soapMessage1 = "@ACTION" + "-" + "@VERSION";
-
- private String _soapMessage2 = "@VERSION" + "-" + "@ACTION";
-
- private CountDownLatch _latch = new CountDownLatch(2);
-
- final List<List<String>> _recv = new ArrayList<List<String>>();
-
- 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<String> buf = new ArrayList<String>();
- 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);
- System.out.println("*** Latch countdown");
- _latch.countDown();
- synchronized (_recv)
- {
- _recv.add(buf);
- }
- }
- 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/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/HttpPosterTest.java b/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/HttpPosterTest.java
deleted file mode 100644
index 4f76fea8ef..0000000000
--- a/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<String> response = hp.get_response();
- assertTrue(response.size() > 0);
- assertEquals("OK <br>", response.get(0).toString());
-
- // Failure Test
- hp = getHttpPoster("http://localhost/nonexistent");
- hp.run();
- response = hp.get_response();
- assertTrue(response.size() == 0);
-
- }
-
-}
diff --git a/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/InfoServiceImplTest.java b/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/InfoServiceImplTest.java
deleted file mode 100644
index 9f359582a5..0000000000
--- a/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<? extends Map<String, String>> info = (Info<? extends Map<String, String>>) _isi
- .invoke("START");
- assertNotNull(info);
- Properties props = info.toProps();
- assertNotNull(props);
- List<String> 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/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/InfoServlet.java b/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/InfoServlet.java
deleted file mode 100644
index 6b12a2d80c..0000000000
--- a/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 <br>\n");
- System.out.println("ServletResponse: OK");
- }
-
-} \ No newline at end of file
diff --git a/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/InfoTest.java b/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/InfoTest.java
deleted file mode 100644
index bb4965ef1e..0000000000
--- a/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<String, String> _infoPayLoad = null;
-
- private Info<HashMap<String, String>> _info = null;
-
- protected void setUp() throws Exception
- {
- super.setUp();
- _infoPayLoad = new HashMap<String, String>();
- _infoPayLoad.put("test", "Test");
- _info = new Info<HashMap<String, String>>(_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("<?xml version=\"1.0\"?>\n");
- sb.append("<qpidinfo>\n");
- sb.append("<test>\n");
- sb.append(INDENT + "Test\n");
- sb.append("</test>\n");
- sb.append("</qpidinfo>\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<String, String> 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/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/IniFileReaderTest.java b/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/IniFileReaderTest.java
deleted file mode 100644
index 77ecaa2176..0000000000
--- a/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<String, Properties> 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 '[<name>]'
- */
- 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/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/SoapClientTest.java b/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/SoapClientTest.java
deleted file mode 100644
index a3d993a39f..0000000000
--- a/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>@IP</ip>");
- destprops.setProperty("soap.action", "send");
- HashMap<String, String> soapmap = new HashMap<String, String>();
- 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<String> response = new ArrayList<String>();
- 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("<ip>127.0.0.1</ip>"));
- 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: <ip>127.0.0.1</ip>
- */
- 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("<?xml version=\"1.0\"?><ip=@IP><port=@PORT>");
- 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", "<addr>@IP:@PORT</addr>");
- HashMap<String, String> soapmap = new HashMap<String, String>();
-
- /// 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", ("<addr>" + ip + ":" + port + "</addr>").equals(sc.getXMLData().toString()));
- }
-
-}
diff --git a/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/SystemInfoTest.java b/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/SystemInfoTest.java
deleted file mode 100644
index 6cb8e3a90a..0000000000
--- a/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<String, String> sysInfoMap = SystemInfo.getInfo();
- assertNotNull("SystemInfo.getInfo() returned null", sysInfoMap);
- List<String> 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/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/XMLWriterTest.java b/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/XMLWriterTest.java
deleted file mode 100644
index f352226361..0000000000
--- a/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", "<?xml version=\"1.0\"?>\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<String, String>(), "TEST");
- assertEquals("XMLWriter.writeTag(...) failed", "<test>\n" + INDENT + "TEST\n" + "</test>\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", "<test>\n" + INDENT + "TEST\n" + "</test>\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<String, String> attr = new HashMap<String, String>();
- attr.put("id", "1");
-
- xw.writeTag("test", attr, "TEST");
- assertEquals("XMLWriter.writeTag(...) failed", "<test id=\"1\">\n" + INDENT + "TEST\n" + "</test>\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<String, String> attr = new HashMap<String, String>();
- xw.writeOpenTag("test", attr);
- assertEquals("XMLWriter.writeOpenTag(...) failed", "<test>\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", "<test>\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<String, String> attr = new HashMap<String, String>();
-
- attr.put("id", "1");
- xw.writeOpenTag("test1", attr);
- assertEquals("XMLWriter.writeOpenTag(...) failed", "<test1 id=\"1\">\n", xw.getXML().toString());
- }
-
- /** Test Close Tag is correctly written */
- public void testWriteCloseTag()
- {
- xw = new XMLWriter(new StringBuffer());
- assertNotNull(xw);
- xw.writeCloseTag("test");
- assertEquals("</test>\n", xw.getXML().toString());
- }
-
-}
diff --git a/java/broker-plugins/experimental/shutdown/MANIFEST.MF b/java/broker-plugins/experimental/shutdown/MANIFEST.MF
deleted file mode 100644
index 49e90c6aad..0000000000
--- a/java/broker-plugins/experimental/shutdown/MANIFEST.MF
+++ /dev/null
@@ -1,15 +0,0 @@
-Manifest-Version: 1.0
-Bundle-ManifestVersion: 2
-Bundle-Name: Experimental Shutdown
-Bundle-Description: Experimental Qpid Broker Shutdown Plugin
-Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt
-Bundle-DocURL: http://qpid.apache.org/
-Bundle-SymbolicName: broker-plugins-experimental-shutdown;singleton:=true
-Bundle-Version: 1.0.0
-Bundle-Activator: org.apache.qpid.shutdown.Activator
-Import-Package: javax.management;resolution:=optional,
- org.apache.log4j,
- org.osgi.framework
-Bundle-RequiredExecutionEnvironment: J2SE-1.5
-Bundle-ActivationPolicy: lazy
-
diff --git a/java/broker-plugins/experimental/shutdown/build.xml b/java/broker-plugins/experimental/shutdown/build.xml
deleted file mode 100644
index ec4fce374e..0000000000
--- a/java/broker-plugins/experimental/shutdown/build.xml
+++ /dev/null
@@ -1,32 +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.
- -
- -->
-<project name="AMQ Broker Shutdown Plugin" default="build">
-
- <property name="module.depends" value="common broker broker-plugins"/>
- <property name="module.test.depends" value="test broker/test management/common client systests"/>
- <property name="module.manifest" value="MANIFEST.MF"/>
- <property name="module.plugin" value="true"/>
-
- <import file="../../../module.xml"/>
-
- <target name="bundle" depends="bundle-tasks"/>
-
-</project>
diff --git a/java/broker-plugins/experimental/shutdown/src/main/java/org/apache/qpid/shutdown/Activator.java b/java/broker-plugins/experimental/shutdown/src/main/java/org/apache/qpid/shutdown/Activator.java
deleted file mode 100644
index ad5e7707b6..0000000000
--- a/java/broker-plugins/experimental/shutdown/src/main/java/org/apache/qpid/shutdown/Activator.java
+++ /dev/null
@@ -1,71 +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.shutdown;
-
-import java.lang.management.ManagementFactory;
-
-import javax.management.InstanceNotFoundException;
-import javax.management.MBeanServer;
-import javax.management.ObjectName;
-
-import org.apache.log4j.Logger;
-import org.osgi.framework.BundleActivator;
-import org.osgi.framework.BundleContext;
-
-public class Activator implements BundleActivator
-{
- private static final Logger _logger = Logger.getLogger(Activator.class);
-
- private static final String SHUTDOWN_MBEAN_NAME = "org.apache.qpid:type=ShutdownMBean";
-
- /** @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext) */
- public void start(BundleContext ctx) throws Exception {
- Shutdown shutdown = new Shutdown();
- if (ctx != null)
- {
- ctx.registerService(ShutdownMBean.class.getName(), shutdown, null);
- }
-
- // MBean registration
- MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
- ObjectName name = new ObjectName(SHUTDOWN_MBEAN_NAME);
- mbs.registerMBean(shutdown, name);
-
- _logger.info("Shutdown plugin MBean registered");
- }
-
- /** @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext) */
- public void stop(BundleContext ctx) throws Exception
- {
- // Unregister MBean
- MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
- ObjectName name = new ObjectName(SHUTDOWN_MBEAN_NAME);
- try
- {
- mbs.unregisterMBean(name);
- }
- catch (InstanceNotFoundException e)
- {
- //ignore
- }
-
- _logger.info("Shutdown plugin MBean unregistered");
- }
-}
diff --git a/java/broker-plugins/experimental/shutdown/src/main/java/org/apache/qpid/shutdown/Shutdown.java b/java/broker-plugins/experimental/shutdown/src/main/java/org/apache/qpid/shutdown/Shutdown.java
deleted file mode 100644
index 9a6f85fe9c..0000000000
--- a/java/broker-plugins/experimental/shutdown/src/main/java/org/apache/qpid/shutdown/Shutdown.java
+++ /dev/null
@@ -1,104 +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.shutdown;
-
-import java.text.DateFormat;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.ScheduledThreadPoolExecutor;
-import java.util.concurrent.TimeUnit;
-
-import org.apache.log4j.Logger;
-
-/**
- * Implementation of the JMX broker shutdown plugin.
- */
-public class Shutdown implements ShutdownMBean
-{
- private static final Logger _logger = Logger.getLogger(Shutdown.class);
-
- private static final String FORMAT = "yyyyy/MM/dd hh:mm:ss";
- private static final int THREAD_COUNT = 1;
- private static final ScheduledExecutorService EXECUTOR = new ScheduledThreadPoolExecutor(THREAD_COUNT);
-
- private final Runnable _shutdown = new SystemExiter();
-
- /** @see ShutdownMBean#shutdown() */
- public void shutdown()
- {
- _logger.info("Shutting down at user's request");
- shutdownBroker(0);
- }
-
- /** @see ShutdownMBean#shutdown(long) */
- public void shutdown(long delay)
- {
- _logger.info("Scheduled broker shutdown after " + delay + "ms");
- shutdownBroker(delay);
- }
-
- /** @see ShutdownMBean#shutdownAt(String) */
- public void shutdownAt(String when)
- {
- Date date;
- DateFormat df = new SimpleDateFormat(FORMAT);
- try
- {
- date = df.parse(when);
- }
- catch (ParseException e)
- {
- _logger.error("Invalid date \"" + when + "\": expecting " + FORMAT, e);
- return;
- }
- _logger.info("Scheduled broker shutdown at " + when);
- long now = System.currentTimeMillis();
- long time = date.getTime();
- if (time > now)
- {
- shutdownBroker(time - now);
- }
- else
- {
- shutdownBroker(0);
- }
- }
-
- /**
- * Submits the {@link SystemExiter} job to shutdown the broker.
- */
- private void shutdownBroker(long delay)
- {
- EXECUTOR.schedule(_shutdown, delay, TimeUnit.MILLISECONDS);
- }
-
- /**
- * Shutting down the system in another thread to avoid JMX exceptions being thrown.
- */
- class SystemExiter implements Runnable
- {
- public void run()
- {
- System.exit(0);
- }
- }
-}
diff --git a/java/broker-plugins/experimental/shutdown/src/main/java/org/apache/qpid/shutdown/ShutdownMBean.java b/java/broker-plugins/experimental/shutdown/src/main/java/org/apache/qpid/shutdown/ShutdownMBean.java
deleted file mode 100644
index 6294f869e9..0000000000
--- a/java/broker-plugins/experimental/shutdown/src/main/java/org/apache/qpid/shutdown/ShutdownMBean.java
+++ /dev/null
@@ -1,47 +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.shutdown;
-
-/**
- * Shutdown plugin JMX MBean interface.
- *
- * Shuts the Qpid broker down via JMX.
- */
-public interface ShutdownMBean
-{
- /**
- * Broker will be shut down immediately.
- */
- public void shutdown();
-
- /**
- * Broker will be shutdown after the specified delay
- *
- * @param delay the number of ms to wait
- */
- public void shutdown(long delay);
-
- /**
- * Broker will be shutdown at the specified date and time.
- *
- * @param when the date and time to shutdown
- */
- public void shutdownAt(String when);
-}
diff --git a/java/broker-plugins/experimental/shutdown/src/main/java/shutdown.bnd b/java/broker-plugins/experimental/shutdown/src/main/java/shutdown.bnd
deleted file mode 100755
index f49578ba8c..0000000000
--- a/java/broker-plugins/experimental/shutdown/src/main/java/shutdown.bnd
+++ /dev/null
@@ -1,25 +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.
-#
-
-ver: 0.11.0
-
-Bundle-SymbolicName: qpid-shutdown-plugin
-Bundle-Version: ${ver}
-Export-Package: *;version=${ver}
-Bundle-RequiredExecutionEnvironment: J2SE-1.5
diff --git a/java/broker-plugins/extras/MANIFEST.MF b/java/broker-plugins/extras/MANIFEST.MF
deleted file mode 100644
index f4ef6e8178..0000000000
--- a/java/broker-plugins/extras/MANIFEST.MF
+++ /dev/null
@@ -1,21 +0,0 @@
-Bundle-ManifestVersion: 2
-Bundle-Name: Qpid Broker-Plugins Extras
-Bundle-SymbolicName: broker-plugins-extras
-Bundle-Description: Extra exchange types plugin for Qpid.
-Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt
-Bundle-DocURL: http://www.apache.org/
-Bundle-Activator: org.apache.qpid.extras.Activator
-Private-Package: org.apache.qpid.extras,
- org.apache.qpid.extras.exchanges.diagnostic,
- org.apache.qpid.extras.exchanges.example
-Import-Package: org.apache.qpid,
- org.apache.qpid.framing,
- org.apache.qpid.junit.extensions.util,
- org.apache.qpid.protocol,
- org.apache.qpid.server.exchange,
- org.apache.qpid.server.management,
- org.apache.qpid.server.queue,
- org.apache.qpid.server.virtualhost,
- javax.management;version=1.0.0,
- javax.management.openmbean;version=1.0.0,
- org.osgi.framework;version=1.3
diff --git a/java/broker-plugins/extras/build.xml b/java/broker-plugins/extras/build.xml
deleted file mode 100644
index 7c1d0be49f..0000000000
--- a/java/broker-plugins/extras/build.xml
+++ /dev/null
@@ -1,31 +0,0 @@
-<!--
- -
- - Licensed to the Apache Software Foundation (ASF) under one
-nn - or more contributor license agreements. See the NOTICE file
- -n distributed with this work for additional information
- - regarding copyright ownership. The ASF licenses this file
- - to you under the Apache License, Version 2.0 (the
- - "License"); you may not use this file except in compliance
- - with the License. You may obtain a copy of the License at
- -
- - http://www.apache.org/licenses/LICENSE-2.0
- -
- - Unless required by applicable law or agreed to in writing,
- - software distributed under the License is distributed on an
- - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- - KIND, either express or implied. See the License for the
- - specific language governing permissions and limitations
- - under the License.
- -
- -->
-<project name="Qpid Broker-Plugins Extras" default="build">
- <property name="module.depends" value="common client management/common broker broker-plugins"/>
- <property name="module.test.depends" value="test broker/test common/test"/>
- <property name="module.manifest" value="MANIFEST.MF"/>
- <property name="module.plugin" value="true"/>
-
- <import file="../../module.xml"/>
-
-
- <target name="bundle" depends="bundle-tasks" />
-</project>
diff --git a/java/broker-plugins/extras/src/main/java/org/apache/qpid/extras/Activator.java b/java/broker-plugins/extras/src/main/java/org/apache/qpid/extras/Activator.java
deleted file mode 100644
index ca6c05a435..0000000000
--- a/java/broker-plugins/extras/src/main/java/org/apache/qpid/extras/Activator.java
+++ /dev/null
@@ -1,48 +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.extras;
-
-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;
-
-/**
- *
- * @author aidan
- *
- * Dummy class, used by PluginTest
- */
-
-public class Activator implements BundleActivator
-{
-
- public void start(BundleContext ctx) throws Exception
- {
- ctx.registerService(ExchangeType.class.getName(), new TestExchangeType(), null);
- ctx.registerService(ExchangeType.class.getName(), new DiagnosticExchangeType(), null);
- }
-
- public void stop(BundleContext ctx) throws Exception
- {
- }
-}
diff --git a/java/broker-plugins/extras/src/main/java/org/apache/qpid/extras/exchanges/diagnostic/DiagnosticExchange.java b/java/broker-plugins/extras/src/main/java/org/apache/qpid/extras/exchanges/diagnostic/DiagnosticExchange.java
deleted file mode 100644
index 5d2c0dd5b2..0000000000
--- a/java/broker-plugins/extras/src/main/java/org/apache/qpid/extras/exchanges/diagnostic/DiagnosticExchange.java
+++ /dev/null
@@ -1,229 +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.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;
-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.exchange.AbstractExchange;
-import org.apache.qpid.server.exchange.AbstractExchangeMBean;
-import org.apache.qpid.server.exchange.ExchangeType;
-import org.apache.qpid.server.message.InboundMessage;
-import org.apache.qpid.server.queue.AMQQueue;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-
-/**
- * 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
- * current memory usage to the "memory" property of the message and places it on the
- * diagnosticqueue for retrieval
- */
-public class DiagnosticExchange extends AbstractExchange
-{
- private static final Logger _logger = Logger.getLogger(DiagnosticExchange.class);
-
- 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.
- */
- @MBeanDescription("Management Bean for Diagnostic Exchange")
- private final class DiagnosticExchangeMBean extends AbstractExchangeMBean<DiagnosticExchange>
- {
- /**
- * Usual constructor.
- *
- * @throws JMException
- */
- @MBeanConstructor("Creates an MBean for AMQ Diagnostic exchange")
- public DiagnosticExchangeMBean() throws JMException
- {
- super(DiagnosticExchange.this);
-
- init();
- }
-
- /**
- * Returns nothing, there can be no tabular data for this...
- *
- * @throws OpenDataException
- * @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;
- }
-
- /**
- * This exchange type doesn't support queues, so this method does
- * nothing.
- *
- * @param queueName the queue you'll fail to create
- * @param binding the binding you'll fail to create
- * @throws JMException an exception that will never be thrown
- */
- @Override
- public void createNewBinding(String queueName, String binding) throws JMException
- {
- // No Op
- }
-
- /**
- * This exchange type doesn't support queues.
- *
- * @see #createNewBinding(String, String)
- */
- @Override
- public void removeBinding(String queueName, String binding) throws JMException
- {
- // No Op
- }
- }
-
-
- public static final ExchangeType<DiagnosticExchange> TYPE = new ExchangeType<DiagnosticExchange>()
- {
-
- public AMQShortString getName()
- {
- return DIAGNOSTIC_EXCHANGE_CLASS;
- }
-
- public Class<DiagnosticExchange> getExchangeClass()
- {
- return DiagnosticExchange.class;
- }
-
- public DiagnosticExchange newInstance(VirtualHost host,
- AMQShortString name,
- boolean durable,
- int ticket,
- boolean autoDelete) throws AMQException
- {
- DiagnosticExchange exch = new DiagnosticExchange();
- exch.initialise(host,name,durable,ticket,autoDelete);
- return exch;
- }
-
- public AMQShortString getDefaultExchangeName()
- {
- return DIAGNOSTIC_EXCHANGE_NAME ;
- }
- };
-
- public DiagnosticExchange()
- {
- super(TYPE);
- }
-
- /**
- * Creates a new MBean instance
- *
- * @return the newly created MBean
- * @throws AMQException
- * if something goes wrong
- */
- protected AbstractExchangeMBean createMBean() throws JMException
- {
- return new DiagnosticExchange.DiagnosticExchangeMBean();
- }
-
- public Logger getLogger()
- {
- return _logger;
- }
-
- public void registerQueue(String routingKey, AMQQueue queue, Map<String, Object> args) throws AMQException
- {
- // No op
- }
-
-
- public boolean isBound(AMQShortString routingKey, AMQQueue queue)
- {
- return false;
- }
-
- public boolean isBound(AMQShortString routingKey)
- {
- return false;
- }
-
- public boolean isBound(AMQQueue queue)
- {
- return false;
- }
-
- public boolean hasBindings()
- {
- return false;
- }
-
- public ArrayList<AMQQueue> 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<AMQQueue> queues = new ArrayList<AMQQueue>();
- queues.add(q);
- return queues;
- }
-
-
- public boolean isBound(AMQShortString routingKey, FieldTable arguments,
- AMQQueue queue) {
- // TODO Auto-generated method stub
- return false;
- }
-
- protected void onBind(final Binding binding)
- {
- // No op
- }
-
- protected void onUnbind(final Binding binding)
- {
- // No op
- }
-}
diff --git a/java/broker-plugins/extras/src/main/java/org/apache/qpid/extras/exchanges/diagnostic/DiagnosticExchangeType.java b/java/broker-plugins/extras/src/main/java/org/apache/qpid/extras/exchanges/diagnostic/DiagnosticExchangeType.java
deleted file mode 100644
index b4d0d1aa0d..0000000000
--- a/java/broker-plugins/extras/src/main/java/org/apache/qpid/extras/exchanges/diagnostic/DiagnosticExchangeType.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.extras.exchanges.diagnostic;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.server.exchange.ExchangeType;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-
-/**
- * Exchange type class for getting hold of the exchange.
- */
-public final class DiagnosticExchangeType implements ExchangeType<DiagnosticExchange>
-{
-
- public AMQShortString getName()
- {
- return DiagnosticExchange.DIAGNOSTIC_EXCHANGE_CLASS;
- }
-
- public Class<DiagnosticExchange> getExchangeClass()
- {
- return DiagnosticExchange.class;
- }
-
- public DiagnosticExchange newInstance(VirtualHost host, AMQShortString name, boolean durable, int ticket, boolean autoDelete)
- throws AMQException
- {
- DiagnosticExchange exch = new DiagnosticExchange();
- exch.initialise(host, name, durable, ticket, autoDelete);
- return exch;
- }
-
- public AMQShortString getDefaultExchangeName()
- {
- return DiagnosticExchange.DIAGNOSTIC_EXCHANGE_NAME;
- }
-}
diff --git a/java/broker-plugins/extras/src/main/java/org/apache/qpid/extras/exchanges/example/TestExchange.java b/java/broker-plugins/extras/src/main/java/org/apache/qpid/extras/exchanges/example/TestExchange.java
deleted file mode 100644
index def0b3f91a..0000000000
--- a/java/broker-plugins/extras/src/main/java/org/apache/qpid/extras/exchanges/example/TestExchange.java
+++ /dev/null
@@ -1,257 +0,0 @@
-package org.apache.qpid.extras.exchanges.example;
-/*
- *
- * 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 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;
-import org.apache.qpid.server.binding.Binding;
-import org.apache.qpid.server.configuration.ConfiguredObject;
-import org.apache.qpid.server.configuration.ExchangeConfigType;
-import org.apache.qpid.server.configuration.VirtualHostConfig;
-import org.apache.qpid.server.exchange.Exchange;
-import org.apache.qpid.server.exchange.ExchangeReferrer;
-import org.apache.qpid.server.exchange.ExchangeType;
-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;
-
-public class TestExchange implements Exchange
-{
-
- public void close() throws AMQException
- {
- }
-
-
-
- public void addBindingListener(final BindingListener listener)
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void removeBindingListener(final BindingListener listener)
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public AMQShortString getNameShortString()
- {
- return null;
- }
-
- public AMQShortString getTypeShortString()
- {
- return null;
- }
-
- public boolean hasBindings()
- {
- return false;
- }
-
- public boolean isBound(String bindingKey, AMQQueue queue)
- {
- return false;
- }
-
- public boolean isBound(String bindingKey)
- {
- return false;
- }
-
- public void addCloseTask(final Task task)
- {
-
- }
-
- public void removeCloseTask(final Task task)
- {
-
- }
-
- public Exchange getAlternateExchange()
- {
- return null;
- }
-
- public Map<String, Object> getArguments()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public long getBindingCount()
- {
- return 0; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public long getBindingCountHigh()
- {
- return 0; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public long getMsgReceives()
- {
- return 0; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public long getMsgRoutes()
- {
- return 0; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public long getByteReceives()
- {
- return 0; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public long getByteRoutes()
- {
- return 0; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public long getCreateTime()
- {
- return 0; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void setAlternateExchange(Exchange exchange)
- {
-
- }
-
- public void removeReference(ExchangeReferrer exchange)
- {
-
- }
-
- public void addReference(ExchangeReferrer exchange)
- {
-
- }
-
- public boolean hasReferrers()
- {
- return false;
- }
-
- public void addBinding(final Binding binding)
- {
-
- }
-
- public void removeBinding(final Binding binding)
- {
-
- }
-
- public Collection<Binding> getBindings()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void initialise(VirtualHost host, AMQShortString name, boolean durable, boolean autoDelete)
- throws AMQException
- {
- }
-
- public VirtualHostConfig getVirtualHost()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public String getName()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public ExchangeType getType()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean isAutoDelete()
- {
- return false;
- }
-
- public boolean isBound(AMQShortString routingKey, FieldTable arguments, AMQQueue queue)
- {
- return false;
- }
-
- public boolean isBound(AMQShortString routingKey, AMQQueue queue)
- {
- return false;
- }
-
- public boolean isBound(AMQShortString routingKey)
- {
- return false;
- }
-
- public boolean isBound(AMQQueue queue)
- {
- return false;
- }
-
- public UUID getId()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public ExchangeConfigType getConfigType()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public ConfiguredObject getParent()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean isDurable()
- {
- return false;
- }
-
- public ArrayList<? extends BaseQueue> route(InboundMessage message)
- {
- return new ArrayList<AMQQueue>();
- }
-
- public int getTicket()
- {
- return 0;
- }
-
- public void initialise(VirtualHost arg0, AMQShortString arg1, boolean arg2, int arg3, boolean arg4)
- throws AMQException
- {
- }
-}
diff --git a/java/broker-plugins/extras/src/main/java/org/apache/qpid/extras/exchanges/example/TestExchangeType.java b/java/broker-plugins/extras/src/main/java/org/apache/qpid/extras/exchanges/example/TestExchangeType.java
deleted file mode 100644
index db02ca13ea..0000000000
--- a/java/broker-plugins/extras/src/main/java/org/apache/qpid/extras/exchanges/example/TestExchangeType.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.extras.exchanges.example;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.server.exchange.Exchange;
-import org.apache.qpid.server.exchange.ExchangeType;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-
-public class TestExchangeType implements ExchangeType
-{
-
- public Class getExchangeClass()
- {
- return TestExchange.class;
- }
-
- public AMQShortString getName()
- {
- return null;
- }
-
- public Exchange newInstance(VirtualHost host, AMQShortString name, boolean durable,
- int token, boolean autoDelete)
- throws AMQException
- {
- TestExchange ex = new TestExchange();
- ex.initialise(host, name, durable, token, autoDelete);
- return ex;
- }
-
- public AMQShortString getDefaultExchangeName()
- {
- return new AMQShortString("test.exchange");
- }
-
-}
diff --git a/java/broker-plugins/extras/src/test/java/org/apache/qpid/server/plugins/ExtrasTest.java b/java/broker-plugins/extras/src/test/java/org/apache/qpid/server/plugins/ExtrasTest.java
deleted file mode 100644
index 57b6e19b5d..0000000000
--- a/java/broker-plugins/extras/src/test/java/org/apache/qpid/server/plugins/ExtrasTest.java
+++ /dev/null
@@ -1,74 +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.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;
-import org.apache.qpid.server.registry.IApplicationRegistry;
-import org.apache.qpid.server.util.TestApplicationRegistry;
-
-import java.util.Map;
-
-public class ExtrasTest extends TestCase
-{
- private static final String TEST_EXCHANGE_CLASS = "org.apache.qpid.extras.exchanges.example.TestExchangeType";
-
- private static final String PLUGIN_DIRECTORY = System.getProperty("example.plugin.target");
- private static final String CACHE_DIRECTORY = System.getProperty("example.cache.target");
-
- IApplicationRegistry _registry;
-
- @Override
- public void setUp() throws Exception
- {
- PropertiesConfiguration properties = new PropertiesConfiguration();
- properties.addProperty("plugin-directory", PLUGIN_DIRECTORY);
- properties.addProperty("cache-directory", CACHE_DIRECTORY);
- ServerConfiguration config = new ServerConfiguration(properties);
-
- // This Test requires an application Registry
- ApplicationRegistry.initialise(new TestApplicationRegistry(config));
- _registry = ApplicationRegistry.getInstance();
- }
-
- @Override
- public void tearDown() throws Exception
- {
- ApplicationRegistry.remove();
- }
-
- public void testLoadExchanges() throws Exception
- {
- PluginManager manager = _registry.getPluginManager();
- Map<String, ExchangeType<?>> exchanges = manager.getExchanges();
- assertNotNull("No exchanges found in " + PLUGIN_DIRECTORY, exchanges);
- assertEquals("Wrong number of exchanges found in " + PLUGIN_DIRECTORY, 2, exchanges.size());
- assertNotNull("Wrong exchange found in " + PLUGIN_DIRECTORY, exchanges.get(TEST_EXCHANGE_CLASS));
- }
-
- public void testNoExchanges() throws Exception
- {
- PluginManager manager = new PluginManager("/path/to/nowhere", "/tmp");
- Map<String, ExchangeType<?>> exchanges = manager.getExchanges();
- assertTrue("Exchanges found", exchanges.isEmpty());
- }
-}
diff --git a/java/broker-plugins/firewall/MANIFEST.MF b/java/broker-plugins/firewall/MANIFEST.MF
deleted file mode 100644
index 6ceea119da..0000000000
--- a/java/broker-plugins/firewall/MANIFEST.MF
+++ /dev/null
@@ -1,36 +0,0 @@
-Manifest-Version: 1.0
-Bundle-ManifestVersion: 2
-Bundle-Name: Qpid Broker-Plugins Firewall
-Bundle-SymbolicName: broker-plugins-firewall
-Bundle-Description: Firewall plugin for Qpid.
-Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt
-Bundle-DocURL: http://www.apache.org/
-Bundle-Version: 1.0.0
-Bundle-Activator: org.apache.qpid.server.security.access.plugins.FirewallActivator
-Bundle-RequiredExecutionEnvironment: JavaSE-1.6
-Bundle-ClassPath: .
-Bundle-ActivationPolicy: lazy
-Import-Package: org.apache.qpid,
- org.apache.qpid.framing,
- org.apache.qpid.junit.extensions.util,
- org.apache.qpid.protocol,
- org.apache.qpid.server.configuration,
- org.apache.qpid.server.configuration.plugins,
- org.apache.qpid.server.exchange,
- org.apache.qpid.server.management,
- org.apache.qpid.server.plugins,
- org.apache.qpid.server.queue,
- org.apache.qpid.server.security,
- org.apache.qpid.server.security.access,
- org.apache.qpid.server.virtualhost,
- org.apache.qpid.util,
- org.apache.commons.configuration;version=1.0.0,
- org.apache.commons.lang;version=1.0.0,
- org.apache.commons.lang.builder;version=1.0.0,
- org.apache.log4j;version=1.0.0,
- javax.management;version=1.0.0,
- javax.management.openmbean;version=1.0.0,
- org.osgi.util.tracker;version=1.0.0,
- org.osgi.framework;version=1.3
-Private-Package: org.apache.qpid.server.security.access.config
-Export-Package: org.apache.qpid.server.security.access.plugins;uses:="org.osgi.framework"
diff --git a/java/broker-plugins/firewall/build.xml b/java/broker-plugins/firewall/build.xml
deleted file mode 100644
index 576435de7f..0000000000
--- a/java/broker-plugins/firewall/build.xml
+++ /dev/null
@@ -1,29 +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.
- -->
-<project name="Qpid Broker-Plugins Firewall" default="build">
- <property name="module.depends" value="common broker broker-plugins" />
- <property name="module.test.depends" value="test broker/test common/test management/common" />
-
- <property name="module.manifest" value="MANIFEST.MF" />
- <property name="module.plugin" value="true" />
-
- <import file="../../module.xml" />
-
- <target name="bundle" depends="bundle-tasks" />
-</project>
diff --git a/java/broker-plugins/firewall/src/main/java/org/apache/qpid/server/security/access/config/FirewallException.java b/java/broker-plugins/firewall/src/main/java/org/apache/qpid/server/security/access/config/FirewallException.java
deleted file mode 100644
index a9e3fdc242..0000000000
--- a/java/broker-plugins/firewall/src/main/java/org/apache/qpid/server/security/access/config/FirewallException.java
+++ /dev/null
@@ -1,46 +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.config;
-
-/**
- * Firewall plugin exception.
- */
-public class FirewallException extends Exception
-{
- /** serialVersionUID */
- private static final long serialVersionUID = 4526157149690917805L;
-
- public FirewallException() {
- super();
- }
-
- public FirewallException(String message) {
- super(message);
- }
-
- public FirewallException(String message, Throwable cause) {
- super(message, cause);
- }
-
- public FirewallException(Throwable cause) {
- super(cause);
- }
-} \ No newline at end of file
diff --git a/java/broker-plugins/firewall/src/main/java/org/apache/qpid/server/security/access/config/FirewallRule.java b/java/broker-plugins/firewall/src/main/java/org/apache/qpid/server/security/access/config/FirewallRule.java
deleted file mode 100644
index f257b58867..0000000000
--- a/java/broker-plugins/firewall/src/main/java/org/apache/qpid/server/security/access/config/FirewallRule.java
+++ /dev/null
@@ -1,137 +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.config;
-
-import java.net.InetAddress;
-import java.util.List;
-import java.util.concurrent.Callable;
-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";
- public static final String DENY = "DENY";
-
- private static final long DNS_TIMEOUT = 30000;
- private static final ExecutorService DNS_LOOKUP = Executors.newCachedThreadPool();
-
- private Result _access;
- private NetMatcher _network;
- private Pattern[] _hostnamePatterns;
-
- public FirewallRule(String access, List networks, List hostnames)
- {
- _access = (access.equalsIgnoreCase(ALLOW)) ? Result.ALLOWED : Result.DENIED;
-
- if (networks != null && networks.size() > 0)
- {
- String[] networkStrings = objListToStringArray(networks);
- _network = new NetMatcher(networkStrings);
- }
-
- if (hostnames != null && hostnames.size() > 0)
- {
- int i = 0;
- _hostnamePatterns = new Pattern[hostnames.size()];
- for (String hostname : objListToStringArray(hostnames))
- {
- _hostnamePatterns[i++] = Pattern.compile(hostname);
- }
- }
- }
-
- private String[] objListToStringArray(List objList)
- {
- String[] networkStrings = new String[objList.size()];
- int i = 0;
- for (Object network : objList)
- {
- networkStrings[i++] = (String) network;
- }
- return networkStrings;
- }
-
- public boolean match(InetAddress remote) throws FirewallException
- {
- if (_hostnamePatterns != null)
- {
- String hostname = getHostname(remote);
- if (hostname == null)
- {
- throw new FirewallException("DNS lookup failed");
- }
- for (Pattern pattern : _hostnamePatterns)
- {
- if (pattern.matcher(hostname).matches())
- {
- return true;
- }
- }
- return false;
- }
- else
- {
- return _network.matchInetNetwork(remote);
- }
- }
-
- /**
- * @param remote the InetAddress to look up
- * @return the hostname, null if not found, takes longer than 30s to find or otherwise fails
- */
- private String getHostname(final InetAddress remote) throws FirewallException
- {
- FutureTask<String> lookup = new FutureTask<String>(new Callable<String>()
- {
- public String call()
- {
- return remote.getCanonicalHostName();
- }
- });
- DNS_LOOKUP.execute(lookup);
-
- try
- {
- return lookup.get(DNS_TIMEOUT, TimeUnit.MILLISECONDS);
- }
- catch (Exception e)
- {
- return null;
- }
- finally
- {
- lookup.cancel(true);
- }
- }
-
- public Result getAccess()
- {
- return _access;
- }
-} \ No newline at end of file
diff --git a/java/broker-plugins/firewall/src/main/java/org/apache/qpid/server/security/access/plugins/Firewall.java b/java/broker-plugins/firewall/src/main/java/org/apache/qpid/server/security/access/plugins/Firewall.java
deleted file mode 100644
index a6ea9d261e..0000000000
--- a/java/broker-plugins/firewall/src/main/java/org/apache/qpid/server/security/access/plugins/Firewall.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.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;
-import org.apache.qpid.server.security.SecurityPluginFactory;
-import org.apache.qpid.server.security.access.ObjectProperties;
-import org.apache.qpid.server.security.access.ObjectType;
-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;
-
-public class Firewall extends AbstractPlugin
-{
- public static final SecurityPluginFactory<Firewall> FACTORY = new SecurityPluginFactory<Firewall>()
- {
- public Firewall newInstance(ConfigurationPlugin config) throws ConfigurationException
- {
- FirewallConfiguration configuration = config.getConfiguration(FirewallConfiguration.class.getName());
-
- // If there is no configuration for this plugin then don't load it.
- if (configuration == null)
- {
- return null;
- }
-
- Firewall plugin = new Firewall();
- plugin.configure(configuration);
- return plugin;
- }
-
- public Class<Firewall> getPluginClass()
- {
- return Firewall.class;
- }
-
- public String getPluginName()
- {
- return Firewall.class.getName();
- }
- };
-
- private Result _default = Result.ABSTAIN;
- private FirewallRule[] _rules;
-
- public Result getDefault()
- {
- return _default;
- }
-
- public Result authorise(Operation operation, ObjectType objectType, ObjectProperties properties)
- {
- return Result.ABSTAIN; // We only deal with access requests
- }
-
- public Result access(ObjectType objectType, Object instance)
- {
- if (objectType != ObjectType.VIRTUALHOST)
- {
- return Result.ABSTAIN; // We are only interested in access to virtualhosts
- }
-
- if (!(instance instanceof InetSocketAddress))
- {
- return Result.ABSTAIN; // We need an internet address
- }
-
- InetAddress address = ((InetSocketAddress) instance).getAddress();
-
- try
- {
- for (FirewallRule rule : _rules)
- {
- boolean match = rule.match(address);
- if (match)
- {
- return rule.getAccess();
- }
- }
- return getDefault();
- }
- catch (FirewallException fe)
- {
- return Result.DENIED;
- }
- }
-
-
- public void configure(ConfigurationPlugin config)
- {
- super.configure(config);
- FirewallConfiguration firewallConfiguration = (FirewallConfiguration) _config;
-
- // Get default action
- _default = firewallConfiguration.getDefaultAction();
-
- Configuration finalConfig = firewallConfiguration.getConfiguration();
-
- // all rules must have an access attribute
- int numRules = finalConfig.getList("rule[@access]").size();
- _rules = new FirewallRule[numRules];
- for (int i = 0; i < numRules; i++)
- {
- FirewallRule rule = new FirewallRule(finalConfig.getString("rule(" + i + ")[@access]"),
- finalConfig.getList("rule(" + i + ")[@network]"),
- finalConfig.getList("rule(" + i + ")[@hostname]"));
- _rules[i] = rule;
- }
-
- }
-}
diff --git a/java/broker-plugins/firewall/src/main/java/org/apache/qpid/server/security/access/plugins/FirewallActivator.java b/java/broker-plugins/firewall/src/main/java/org/apache/qpid/server/security/access/plugins/FirewallActivator.java
deleted file mode 100644
index c20bba8d2c..0000000000
--- a/java/broker-plugins/firewall/src/main/java/org/apache/qpid/server/security/access/plugins/FirewallActivator.java
+++ /dev/null
@@ -1,42 +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 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}.
- */
-public class FirewallActivator extends SecurityPluginActivator
-{
- public SecurityPluginFactory getFactory()
- {
- return Firewall.FACTORY;
- }
-
- public ConfigurationPluginFactory getConfigurationFactory()
- {
- return FirewallConfiguration.FACTORY;
- }
-}
diff --git a/java/broker-plugins/firewall/src/main/java/org/apache/qpid/server/security/access/plugins/FirewallConfiguration.java b/java/broker-plugins/firewall/src/main/java/org/apache/qpid/server/security/access/plugins/FirewallConfiguration.java
deleted file mode 100644
index b10656d622..0000000000
--- a/java/broker-plugins/firewall/src/main/java/org/apache/qpid/server/security/access/plugins/FirewallConfiguration.java
+++ /dev/null
@@ -1,102 +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.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;
-
-public class FirewallConfiguration extends ConfigurationPlugin
-{
- CompositeConfiguration _finalConfig;
-
- public static final ConfigurationPluginFactory FACTORY = new ConfigurationPluginFactory()
- {
- public ConfigurationPlugin newInstance(String path, Configuration config) throws ConfigurationException
- {
- ConfigurationPlugin instance = new FirewallConfiguration();
- instance.setConfiguration(path, config);
- return instance;
- }
-
- public List<String> getParentPaths()
- {
- return Arrays.asList("security.firewall", "virtualhosts.virtualhost.security.firewall");
- }
- };
-
- public String[] getElementsProcessed()
- {
- return new String[] { "" };
- }
-
- public Configuration getConfiguration()
- {
- return _finalConfig;
- }
-
- public Result getDefaultAction()
- {
- String defaultAction = _configuration.getString("[@default-action]");
- if (defaultAction == null)
- {
- return Result.ABSTAIN;
- }
- else if (defaultAction.equalsIgnoreCase(FirewallRule.ALLOW))
- {
- return Result.ALLOWED;
- }
- else
- {
- return Result.DENIED;
- }
- }
-
-
-
- @Override
- public void validateConfiguration() throws ConfigurationException
- {
- // Valid Configuration either has xml links to new files
- _finalConfig = new CompositeConfiguration(_configuration);
- List subFiles = _configuration.getList("xml[@fileName]");
- for (Object subFile : subFiles)
- {
- _finalConfig.addConfiguration(new XMLConfiguration((String) subFile));
- }
-
- // all rules must have an access attribute or a default value
- if (_finalConfig.getList("rule[@access]").size() == 0 &&
- _configuration.getString("[@default-action]") == null)
- {
- throw new ConfigurationException("No rules or default-action found in firewall configuration.");
- }
- }
-
-}
diff --git a/java/broker-plugins/firewall/src/test/java/org/apache/qpid/server/security/access/FirewallConfigurationTest.java b/java/broker-plugins/firewall/src/test/java/org/apache/qpid/server/security/access/FirewallConfigurationTest.java
deleted file mode 100644
index ebede414f4..0000000000
--- a/java/broker-plugins/firewall/src/test/java/org/apache/qpid/server/security/access/FirewallConfigurationTest.java
+++ /dev/null
@@ -1,355 +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;
-
-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.util.InternalBrokerBaseCase;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-import org.apache.qpid.server.virtualhost.VirtualHostRegistry;
-
-public class FirewallConfigurationTest extends InternalBrokerBaseCase
-{
- public void testFirewallConfiguration() throws Exception
- {
- // Write out config
- File mainFile = File.createTempFile(getClass().getName(), null);
- mainFile.deleteOnExit();
- writeConfigFile(mainFile, false);
-
- // Load config
- ApplicationRegistry reg = new ConfigurationFileApplicationRegistry(mainFile);
- try
- {
- ApplicationRegistry.initialise(reg, 1);
-
- // Test config
- assertFalse(reg.getSecurityManager().accessVirtualhost("test", new InetSocketAddress("127.0.0.1", 65535)));
- assertTrue(reg.getSecurityManager().accessVirtualhost("test", new InetSocketAddress("127.1.2.3", 65535)));
- }
- finally
- {
- ApplicationRegistry.remove(1);
- }
- }
-
- public void testCombinedConfigurationFirewall() throws Exception
- {
- // Write out config
- File mainFile = File.createTempFile(getClass().getName(), null);
- File fileA = File.createTempFile(getClass().getName(), null);
- File fileB = File.createTempFile(getClass().getName(), null);
-
- mainFile.deleteOnExit();
- fileA.deleteOnExit();
- fileB.deleteOnExit();
-
- FileWriter out = new FileWriter(mainFile);
- out.write("<configuration><system/>");
- out.write("<xml fileName=\"" + fileA.getAbsolutePath() + "\"/>");
- out.write("</configuration>");
- out.close();
-
- out = new FileWriter(fileA);
- out.write("<broker>\n");
- out.write("\t<plugin-directory>${QPID_HOME}/lib/plugins</plugin-directory>\n");
- out.write("\t<cache-directory>${QPID_WORK}/cache</cache-directory>\n");
- out.write("\t<management><enabled>false</enabled></management>\n");
- out.write("\t<security>\n");
- out.write("\t\t<principal-databases>\n");
- out.write("\t\t\t<principal-database>\n");
- out.write("\t\t\t\t<name>passwordfile</name>\n");
- out.write("\t\t\t\t<class>org.apache.qpid.server.security.auth.database.PlainPasswordFilePrincipalDatabase</class>\n");
- out.write("\t\t\t\t<attributes>\n");
- out.write("\t\t\t\t\t<attribute>\n");
- out.write("\t\t\t\t\t\t<name>passwordFile</name>\n");
- out.write("\t\t\t\t\t\t<value>/dev/null</value>\n");
- out.write("\t\t\t\t\t</attribute>\n");
- out.write("\t\t\t\t</attributes>\n");
- out.write("\t\t\t</principal-database>\n");
- out.write("\t\t</principal-databases>\n");
- out.write("\t\t<jmx>\n");
- out.write("\t\t\t<principal-database>passwordfile</principal-database>\n");
- out.write("\t\t</jmx>\n");
- out.write("\t\t<firewall>\n");
- out.write("\t\t\t<xml fileName=\"" + fileB.getAbsolutePath() + "\"/>");
- out.write("\t\t</firewall>\n");
- out.write("\t</security>\n");
- out.write("\t<virtualhosts>\n");
- out.write("\t\t<virtualhost>\n");
- out.write("\t\t\t<name>test</name>\n");
- out.write("\t\t</virtualhost>\n");
- out.write("\t</virtualhosts>\n");
- out.write("</broker>\n");
- out.close();
-
- out = new FileWriter(fileB);
- out.write("<firewall>\n");
- out.write("\t<rule access=\"deny\" network=\"127.0.0.1\"/>");
- out.write("</firewall>\n");
- out.close();
-
- // Load config
- ApplicationRegistry reg = new ConfigurationFileApplicationRegistry(mainFile);
- try
- {
- ApplicationRegistry.initialise(reg, 1);
-
- // Test config
- assertFalse(reg.getSecurityManager().accessVirtualhost("test", new InetSocketAddress("127.0.0.1", 65535)));
- }
- finally
- {
- ApplicationRegistry.remove(1);
- }
- }
-
- public void testConfigurationFirewallReload() throws Exception
- {
- // Write out config
- File mainFile = File.createTempFile(getClass().getName(), null);
-
- mainFile.deleteOnExit();
- writeConfigFile(mainFile, false);
-
- // Load config
- ApplicationRegistry reg = new ConfigurationFileApplicationRegistry(mainFile);
- try
- {
- ApplicationRegistry.initialise(reg, 1);
-
- // Test config
- assertFalse(reg.getSecurityManager().accessVirtualhost("test", new InetSocketAddress("127.0.0.1", 65535)));
-
- // Switch to deny the connection
- writeConfigFile(mainFile, true);
-
- reg.getConfiguration().reparseConfigFileSecuritySections();
-
- assertTrue(reg.getSecurityManager().accessVirtualhost("test", new InetSocketAddress("127.0.0.1", 65535)));
- }
- finally
- {
- ApplicationRegistry.remove(1);
- }
- }
-
- public void testCombinedConfigurationFirewallReload() throws Exception
- {
- // Write out config
- File mainFile = File.createTempFile(getClass().getName(), null);
- File fileA = File.createTempFile(getClass().getName(), null);
- File fileB = File.createTempFile(getClass().getName(), null);
-
- mainFile.deleteOnExit();
- fileA.deleteOnExit();
- fileB.deleteOnExit();
-
- FileWriter out = new FileWriter(mainFile);
- out.write("<configuration><system/>");
- out.write("<xml fileName=\"" + fileA.getAbsolutePath() + "\"/>");
- out.write("</configuration>");
- out.close();
-
- out = new FileWriter(fileA);
- out.write("<broker>\n");
- out.write("\t<plugin-directory>${QPID_HOME}/lib/plugins</plugin-directory>\n");
- out.write("\t<management><enabled>false</enabled></management>\n");
- out.write("\t<security>\n");
- out.write("\t\t<principal-databases>\n");
- out.write("\t\t\t<principal-database>\n");
- out.write("\t\t\t\t<name>passwordfile</name>\n");
- out.write("\t\t\t\t<class>org.apache.qpid.server.security.auth.database.PlainPasswordFilePrincipalDatabase</class>\n");
- out.write("\t\t\t\t<attributes>\n");
- out.write("\t\t\t\t\t<attribute>\n");
- out.write("\t\t\t\t\t\t<name>passwordFile</name>\n");
- out.write("\t\t\t\t\t\t<value>/dev/null</value>\n");
- out.write("\t\t\t\t\t</attribute>\n");
- out.write("\t\t\t\t</attributes>\n");
- out.write("\t\t\t</principal-database>\n");
- out.write("\t\t</principal-databases>\n");
- out.write("\t\t<jmx>\n");
- out.write("\t\t\t<principal-database>passwordfile</principal-database>\n");
- out.write("\t\t</jmx>\n");
- out.write("\t\t<firewall>\n");
- out.write("\t\t\t<xml fileName=\"" + fileB.getAbsolutePath() + "\"/>");
- out.write("\t\t</firewall>\n");
- out.write("\t</security>\n");
- out.write("\t<virtualhosts>\n");
- out.write("\t\t<virtualhost>\n");
- out.write("\t\t\t<name>test</name>\n");
- out.write("\t\t</virtualhost>\n");
- out.write("\t</virtualhosts>\n");
- out.write("</broker>\n");
- out.close();
-
- out = new FileWriter(fileB);
- out.write("<firewall>\n");
- out.write("\t<rule access=\"deny\" network=\"127.0.0.1\"/>");
- out.write("</firewall>\n");
- out.close();
-
- // Load config
- ApplicationRegistry reg = new ConfigurationFileApplicationRegistry(mainFile);
- try
- {
- ApplicationRegistry.initialise(reg, 1);
-
- // Test config
- assertFalse(reg.getSecurityManager().accessVirtualhost("test", new InetSocketAddress("127.0.0.1", 65535)));
-
- RandomAccessFile fileBRandom = new RandomAccessFile(fileB, "rw");
- fileBRandom.setLength(0);
- fileBRandom.seek(0);
- fileBRandom.close();
-
- out = new FileWriter(fileB);
- out.write("<firewall>\n");
- out.write("\t<rule access=\"allow\" network=\"127.0.0.1\"/>");
- out.write("</firewall>\n");
- out.close();
-
- reg.getConfiguration().reparseConfigFileSecuritySections();
-
- assertTrue(reg.getSecurityManager().accessVirtualhost("test", new InetSocketAddress("127.0.0.1", 65535)));
-
- fileBRandom = new RandomAccessFile(fileB, "rw");
- fileBRandom.setLength(0);
- fileBRandom.seek(0);
- fileBRandom.close();
-
- out = new FileWriter(fileB);
- out.write("<firewall>\n");
- out.write("\t<rule access=\"deny\" network=\"127.0.0.1\"/>");
- out.write("</firewall>\n");
- out.close();
-
- reg.getConfiguration().reparseConfigFileSecuritySections();
-
- assertFalse(reg.getSecurityManager().accessVirtualhost("test", new InetSocketAddress("127.0.0.1", 65535)));
- }
- finally
- {
- ApplicationRegistry.remove(1);
- }
- }
-
- private void writeFirewallVhostsFile(File vhostsFile, boolean allow) throws IOException
- {
- FileWriter out = new FileWriter(vhostsFile);
- String ipAddr = "127.0.0.1"; // FIXME: get this from InetAddress.getLocalHost().getAddress() ?
- out.write("<virtualhosts><virtualhost>");
- out.write("<name>test</name>");
- out.write("<test>");
- out.write("<security><firewall>");
- out.write("<rule access=\""+((allow) ? "allow" : "deny")+"\" network=\""+ipAddr +"\"/>");
- out.write("</firewall></security>");
- out.write("</test>");
- out.write("</virtualhost></virtualhosts>");
- out.close();
- }
-
- private void writeConfigFile(File mainFile, boolean allow) throws IOException {
- writeConfigFile(mainFile, allow, true, null, "test");
- }
-
- /*
- XMLConfiguration config = new XMLConfiguration(mainFile);
- PluginManager pluginManager = new MockPluginManager("");
- SecurityManager manager = new SecurityManager(config, pluginManager, Firewall.FACTORY);
-
- */
- private void writeConfigFile(File mainFile, boolean allow, boolean includeVhosts, File vhostsFile, String name) throws IOException {
- FileWriter out = new FileWriter(mainFile);
- out.write("<broker>\n");
- out.write("\t<plugin-directory>${QPID_HOME}/lib/plugins</plugin-directory>\n");
- out.write("\t<management><enabled>false</enabled></management>\n");
- out.write("\t<security>\n");
- out.write("\t\t<principal-databases>\n");
- out.write("\t\t\t<principal-database>\n");
- out.write("\t\t\t\t<name>passwordfile</name>\n");
- out.write("\t\t\t\t<class>org.apache.qpid.server.security.auth.database.PlainPasswordFilePrincipalDatabase</class>\n");
- out.write("\t\t\t\t<attributes>\n");
- out.write("\t\t\t\t\t<attribute>\n");
- out.write("\t\t\t\t\t\t<name>passwordFile</name>\n");
- out.write("\t\t\t\t\t\t<value>/dev/null</value>\n");
- out.write("\t\t\t\t\t</attribute>\n");
- out.write("\t\t\t\t</attributes>\n");
- out.write("\t\t\t</principal-database>\n");
- out.write("\t\t</principal-databases>\n");
- out.write("\t\t<jmx>\n");
- out.write("\t\t\t<principal-database>passwordfile</principal-database>\n");
- out.write("\t\t</jmx>\n");
- out.write("\t\t<firewall>\n");
- out.write("\t\t\t<rule access=\""+ ((allow) ? "allow" : "deny") +"\" network=\"127.0.0.1\"/>");
- out.write("\t\t</firewall>\n");
- out.write("\t</security>\n");
- if (includeVhosts)
- {
- out.write("\t<virtualhosts>\n");
- out.write("\t\t<default>test</default>\n");
- out.write("\t\t<virtualhost>\n");
- out.write(String.format("\t\t\t<name>%s</name>\n", name));
- out.write("\t\t</virtualhost>\n");
- out.write("\t</virtualhosts>\n");
- }
- if (vhostsFile != null)
- {
- out.write("\t<virtualhosts>"+vhostsFile.getAbsolutePath()+"</virtualhosts>\n");
- }
- out.write("</broker>\n");
- out.close();
- }
-
- /**
- * Test that configuration loads correctly when virtual hosts are specified in an external
- * configuration file only.
- * <p>
- * Test for QPID-2360
- */
- public void testExternalFirewallVirtualhostXMLFile() throws Exception
- {
- // Write out config
- File mainFile = File.createTempFile(getClass().getName(), "config");
- mainFile.deleteOnExit();
- File vhostsFile = File.createTempFile(getClass().getName(), "vhosts");
- vhostsFile.deleteOnExit();
- writeConfigFile(mainFile, false, false, vhostsFile, null);
- writeFirewallVhostsFile(vhostsFile, false);
-
- // Load config
- ApplicationRegistry reg = new ConfigurationFileApplicationRegistry(mainFile);
- ApplicationRegistry.initialise(reg, 1);
-
- // Test config
- VirtualHostRegistry virtualHostRegistry = reg.getVirtualHostRegistry();
- VirtualHost virtualHost = virtualHostRegistry.getVirtualHost("test");
-
- assertEquals("Incorrect virtualhost count", 1, virtualHostRegistry.getVirtualHosts().size());
- assertEquals("Incorrect virtualhost name", "test", virtualHost.getName());
- }
-}
diff --git a/java/broker-plugins/firewall/src/test/java/org/apache/qpid/server/security/access/FirewallPluginTest.java b/java/broker-plugins/firewall/src/test/java/org/apache/qpid/server/security/access/FirewallPluginTest.java
deleted file mode 100644
index 2b04962c89..0000000000
--- a/java/broker-plugins/firewall/src/test/java/org/apache/qpid/server/security/access/FirewallPluginTest.java
+++ /dev/null
@@ -1,282 +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;
-
-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.security.Result;
-import org.apache.qpid.server.security.access.plugins.Firewall;
-import org.apache.qpid.server.security.access.plugins.FirewallConfiguration;
-import org.apache.qpid.server.util.InternalBrokerBaseCase;
-
-public class FirewallPluginTest extends InternalBrokerBaseCase
-{
- public class RuleInfo
- {
- private String _access;
- private String _network;
- private String _hostname;
-
- public void setAccess(String _access)
- {
- this._access = _access;
- }
-
- public String getAccess()
- {
- return _access;
- }
-
- public void setNetwork(String _network)
- {
- this._network = _network;
- }
-
- public String getNetwork()
- {
- return _network;
- }
-
- public void setHostname(String _hostname)
- {
- this._hostname = _hostname;
- }
-
- public String getHostname()
- {
- return _hostname;
- }
- }
-
- // IP address
- private SocketAddress _address;
-
- @Override
- public void setUp() throws Exception
- {
- super.setUp();
-
- _address = new InetSocketAddress("127.0.0.1", 65535);
- }
-
- private Firewall initialisePlugin(String defaultAction, RuleInfo[] rules) throws IOException, ConfigurationException
- {
- // Create sample config file
- File confFile = File.createTempFile(getClass().getSimpleName()+"conffile", null);
- confFile.deleteOnExit();
- BufferedWriter buf = new BufferedWriter(new FileWriter(confFile));
- buf.write("<firewall default-action=\""+defaultAction+"\">\n");
- if (rules != null)
- {
- for (RuleInfo rule : rules)
- {
- buf.write("<rule");
- buf.write(" access=\""+rule.getAccess()+"\"");
- if (rule.getHostname() != null)
- {
- buf.write(" hostname=\""+rule.getHostname()+"\"");
- }
- if (rule.getNetwork() != null)
- {
- buf.write(" network=\""+rule.getNetwork()+"\"");
- }
- buf.write("/>\n");
- }
- }
- buf.write("</firewall>");
- buf.close();
-
- // Configure plugin
- FirewallConfiguration config = new FirewallConfiguration();
- config.setConfiguration("", new XMLConfiguration(confFile));
- Firewall plugin = new Firewall();
- plugin.configure(config);
- return plugin;
- }
-
- private Firewall initialisePlugin(String string) throws ConfigurationException, IOException
- {
- return initialisePlugin(string, null);
- }
-
- public void testDefaultAction() throws Exception
- {
- // Test simple deny
- Firewall plugin = initialisePlugin("deny");
- assertEquals(Result.DENIED, plugin.access(ObjectType.VIRTUALHOST, _address));
-
- // Test simple allow
- plugin = initialisePlugin("allow");
- assertEquals(Result.ALLOWED, plugin.access(ObjectType.VIRTUALHOST, _address));
- }
-
-
- public void testSingleIPRule() throws Exception
- {
- RuleInfo rule = new RuleInfo();
- rule.setAccess("allow");
- rule.setNetwork("192.168.23.23");
-
- Firewall plugin = initialisePlugin("deny", new RuleInfo[]{rule});
-
- assertEquals(Result.DENIED, plugin.access(ObjectType.VIRTUALHOST, _address));
-
- // Set IP so that we're connected from the right address
- _address = new InetSocketAddress("192.168.23.23", 65535);
- assertEquals(Result.ALLOWED, plugin.access(ObjectType.VIRTUALHOST, _address));
- }
-
- public void testSingleNetworkRule() throws Exception
- {
- RuleInfo rule = new RuleInfo();
- rule.setAccess("allow");
- rule.setNetwork("192.168.23.0/24");
-
- Firewall plugin = initialisePlugin("deny", new RuleInfo[]{rule});
-
- assertEquals(Result.DENIED, plugin.access(ObjectType.VIRTUALHOST, _address));
-
- // Set IP so that we're connected from the right address
- _address = new InetSocketAddress("192.168.23.23", 65535);
- assertEquals(Result.ALLOWED, plugin.access(ObjectType.VIRTUALHOST, _address));
- }
-
- public void testSingleHostRule() throws Exception
- {
- RuleInfo rule = new RuleInfo();
- rule.setAccess("allow");
- rule.setHostname(new InetSocketAddress("127.0.0.1", 5672).getHostName());
-
- Firewall plugin = initialisePlugin("deny", new RuleInfo[]{rule});
-
- // Set IP so that we're connected from the right address
- _address = new InetSocketAddress("127.0.0.1", 65535);
- assertEquals(Result.ALLOWED, plugin.access(ObjectType.VIRTUALHOST, _address));
- }
-
- public void testSingleHostWilcardRule() throws Exception
- {
- RuleInfo rule = new RuleInfo();
- rule.setAccess("allow");
- String hostname = new InetSocketAddress("127.0.0.1", 0).getHostName();
- rule.setHostname(".*"+hostname.subSequence(hostname.length() - 1, hostname.length())+"*");
- Firewall plugin = initialisePlugin("deny", new RuleInfo[]{rule});
-
- // Set IP so that we're connected from the right address
- _address = new InetSocketAddress("127.0.0.1", 65535);
- assertEquals(Result.ALLOWED, plugin.access(ObjectType.VIRTUALHOST, _address));
- }
-
- public void testSeveralFirstAllowsAccess() throws Exception
- {
- RuleInfo firstRule = new RuleInfo();
- firstRule.setAccess("allow");
- firstRule.setNetwork("192.168.23.23");
-
- RuleInfo secondRule = new RuleInfo();
- secondRule.setAccess("deny");
- secondRule.setNetwork("192.168.42.42");
-
- RuleInfo thirdRule = new RuleInfo();
- thirdRule.setAccess("deny");
- thirdRule.setHostname("localhost");
-
- Firewall plugin = initialisePlugin("deny", new RuleInfo[]{firstRule, secondRule, thirdRule});
-
- assertEquals(Result.DENIED, plugin.access(ObjectType.VIRTUALHOST, _address));
-
- // Set IP so that we're connected from the right address
- _address = new InetSocketAddress("192.168.23.23", 65535);
- assertEquals(Result.ALLOWED, plugin.access(ObjectType.VIRTUALHOST, _address));
- }
-
- public void testSeveralLastAllowsAccess() throws Exception
- {
- RuleInfo firstRule = new RuleInfo();
- firstRule.setAccess("deny");
- firstRule.setHostname("localhost");
-
- RuleInfo secondRule = new RuleInfo();
- secondRule.setAccess("deny");
- secondRule.setNetwork("192.168.42.42");
-
- RuleInfo thirdRule = new RuleInfo();
- thirdRule.setAccess("allow");
- thirdRule.setNetwork("192.168.23.23");
-
- Firewall plugin = initialisePlugin("deny", new RuleInfo[]{firstRule, secondRule, thirdRule});
-
- assertEquals(Result.DENIED, plugin.access(ObjectType.VIRTUALHOST, _address));
-
- // Set IP so that we're connected from the right address
- _address = new InetSocketAddress("192.168.23.23", 65535);
- assertEquals(Result.ALLOWED, plugin.access(ObjectType.VIRTUALHOST, _address));
- }
-
- public void testNetmask() throws Exception
- {
- RuleInfo firstRule = new RuleInfo();
- firstRule.setAccess("allow");
- firstRule.setNetwork("192.168.23.0/24");
- Firewall plugin = initialisePlugin("deny", new RuleInfo[]{firstRule});
-
- assertEquals(Result.DENIED, plugin.access(ObjectType.VIRTUALHOST, _address));
-
- // Set IP so that we're connected from the right address
- _address = new InetSocketAddress("192.168.23.23", 65535);
- assertEquals(Result.ALLOWED, plugin.access(ObjectType.VIRTUALHOST, _address));
- }
-
- public void testCommaSeperatedNetmask() throws Exception
- {
- RuleInfo firstRule = new RuleInfo();
- firstRule.setAccess("allow");
- firstRule.setNetwork("10.1.1.1/8, 192.168.23.0/24");
- Firewall plugin = initialisePlugin("deny", new RuleInfo[]{firstRule});
-
- assertEquals(Result.DENIED, plugin.access(ObjectType.VIRTUALHOST, _address));
-
- // Set IP so that we're connected from the right address
- _address = new InetSocketAddress("192.168.23.23", 65535);
- assertEquals(Result.ALLOWED, plugin.access(ObjectType.VIRTUALHOST, _address));
- }
-
- public void testCommaSeperatedHostnames() throws Exception
- {
- RuleInfo firstRule = new RuleInfo();
- firstRule.setAccess("allow");
- firstRule.setHostname("foo, bar, "+new InetSocketAddress("127.0.0.1", 5672).getHostName());
- Firewall plugin = initialisePlugin("deny", new RuleInfo[]{firstRule});
-
- // Set IP so that we're connected from the right address
- _address = new InetSocketAddress("10.0.0.1", 65535);
- assertEquals(Result.DENIED, plugin.access(ObjectType.VIRTUALHOST, _address));
-
- // Set IP so that we're connected from the right address
- _address = new InetSocketAddress("127.0.0.1", 65535);
- assertEquals(Result.ALLOWED, plugin.access(ObjectType.VIRTUALHOST, _address));
- }
-}
diff --git a/java/broker-plugins/simple-xml/MANIFEST.MF b/java/broker-plugins/simple-xml/MANIFEST.MF
deleted file mode 100644
index 04fe7518df..0000000000
--- a/java/broker-plugins/simple-xml/MANIFEST.MF
+++ /dev/null
@@ -1,36 +0,0 @@
-Manifest-Version: 1.0
-Bundle-ManifestVersion: 2
-Bundle-Name: Qpid Broker-Plugins Simple XML
-Bundle-SymbolicName: broker-plugins-simple-xml
-Bundle-Description: Simple XML ACL plugin for Qpid.
-Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt
-Bundle-DocURL: http://www.apache.org/
-Bundle-Version: 1.0.0
-Bundle-Activator: org.apache.qpid.server.security.access.plugins.SimpleXMLActivator
-Bundle-RequiredExecutionEnvironment: JavaSE-1.5
-Bundle-ClassPath: .
-Bundle-ActivationPolicy: lazy
-Import-Package: org.apache.qpid,
- org.apache.qpid.framing,
- org.apache.qpid.junit.extensions.util,
- org.apache.qpid.protocol,
- org.apache.qpid.server.configuration,
- org.apache.qpid.server.configuration.plugins,
- org.apache.qpid.server.exchange,
- org.apache.qpid.server.management,
- org.apache.qpid.server.plugins,
- org.apache.qpid.server.queue,
- org.apache.qpid.server.security,
- org.apache.qpid.server.security.access,
- org.apache.qpid.server.virtualhost,
- org.apache.qpid.util,
- org.apache.commons.configuration;version=1.0.0,
- org.apache.commons.lang;version=1.0.0,
- org.apache.commons.lang.builder;version=1.0.0,
- org.apache.log4j;version=1.0.0,
- javax.management;version=1.0.0,
- javax.management.openmbean;version=1.0.0,
- org.osgi.util.tracker;version=1.0.0,
- org.osgi.framework;version=1.3
-Private-Package: org.apache.qpid.server.security.access.config
-Export-Package: org.apache.qpid.server.security.access.plugins
diff --git a/java/broker-plugins/simple-xml/build.xml b/java/broker-plugins/simple-xml/build.xml
deleted file mode 100644
index d3cd451648..0000000000
--- a/java/broker-plugins/simple-xml/build.xml
+++ /dev/null
@@ -1,29 +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.
- -->
-<project name="Qpid Broker-Plugins Simple XML" default="build">
- <property name="module.depends" value="common broker broker-plugins" />
- <property name="module.test.depends" value="test broker/test common/test management/common systests" />
-
- <property name="module.manifest" value="MANIFEST.MF" />
- <property name="module.plugin" value="true" />
-
- <import file="../../module.xml" />
-
- <target name="bundle" depends="bundle-tasks" />
-</project>
diff --git a/java/broker-plugins/simple-xml/src/main/java/org/apache/qpid/server/security/access/config/PrincipalPermissions.java b/java/broker-plugins/simple-xml/src/main/java/org/apache/qpid/server/security/access/config/PrincipalPermissions.java
deleted file mode 100755
index d9fc292f03..0000000000
--- a/java/broker-plugins/simple-xml/src/main/java/org/apache/qpid/server/security/access/config/PrincipalPermissions.java
+++ /dev/null
@@ -1,687 +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.config;
-
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-import org.apache.commons.lang.StringUtils;
-import org.apache.log4j.Logger;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.server.security.Result;
-
-@SuppressWarnings("unchecked")
-public class PrincipalPermissions
-{
- public enum Permission
- {
- CONSUME,
- PUBLISH,
- CREATEQUEUE,
- CREATEEXCHANGE,
- ACCESS,
- BIND,
- UNBIND,
- DELETE,
- PURGE
- }
-
- private static final Logger _logger = Logger.getLogger(PrincipalPermissions.class);
-
- private static final Object CONSUME_QUEUES_KEY = new Object();
- private static final Object CONSUME_TEMPORARY_KEY = new Object();
- private static final Object CONSUME_OWN_QUEUES_ONLY_KEY = new Object();
-
- private static final Object CREATE_QUEUES_KEY = new Object();
- private static final Object CREATE_EXCHANGES_KEY = new Object();
-
-
- private static final Object CREATE_QUEUE_TEMPORARY_KEY = new Object();
- private static final Object CREATE_QUEUE_QUEUES_KEY = new Object();
- private static final Object CREATE_QUEUE_EXCHANGES_KEY = new Object();
-
- private static final Object CREATE_QUEUE_EXCHANGES_ROUTINGKEYS_KEY = new Object();
-
- private static final int PUBLISH_EXCHANGES_KEY = 0;
-
- private Map _permissions;
- private boolean _fullVHostAccess = false;
-
- private String _user;
-
-
- public PrincipalPermissions(String user)
- {
- _user = user;
- _permissions = new ConcurrentHashMap();
- }
-
- /**
- *
- * @param permission the type of permission to check
- *
- * @param parameters vararg depending on what permission was passed in
- * ACCESS: none
- * BIND: none
- * CONSUME: AMQShortString queueName, Boolean temporary, Boolean ownQueueOnly
- * CREATEQUEUE: Boolean temporary, AMQShortString queueName, AMQShortString exchangeName, AMQShortString routingKey
- * CREATEEXCHANGE: AMQShortString exchangeName, AMQShortString Class
- * DELETE: none
- * PUBLISH: Exchange exchange, AMQShortString routingKey
- * PURGE: none
- * UNBIND: none
- */
- public void grant(Permission permission, Object... parameters)
- {
- switch (permission)
- {
- case ACCESS:// Parameters : None
- grantAccess(permission);
- break;
- case CONSUME: // Parameters : AMQShortString queueName, Boolean Temporary, Boolean ownQueueOnly
- grantConsume(permission, parameters);
- break;
- case CREATEQUEUE: // Parameters : Boolean temporary, AMQShortString queueName
- // , AMQShortString exchangeName , AMQShortString routingKey
- grantCreateQueue(permission, parameters);
- break;
- case CREATEEXCHANGE:
- // Parameters AMQShortString exchangeName , AMQShortString Class
- grantCreateExchange(permission, parameters);
- break;
- case PUBLISH: // Parameters : Exchange exchange, AMQShortString routingKey
- grantPublish(permission, parameters);
- break;
- /* The other cases just fall through to no-op */
- case DELETE:
- case BIND: // All the details are currently included in the create setup.
- case PURGE:
- case UNBIND:
- break;
- }
-
- }
-
- private void grantAccess(Permission permission)
- {
- _fullVHostAccess = true;
- }
-
- private void grantPublish(Permission permission, Object... parameters) {
- Map publishRights = (Map) _permissions.get(permission);
-
- if (publishRights == null)
- {
- publishRights = new ConcurrentHashMap();
- _permissions.put(permission, publishRights);
- }
-
- if (parameters == null || parameters.length == 0)
- {
- //If we have no parameters then allow publish to all destinations
- // this is signified by having a null value for publish_exchanges
- }
- else
- {
- Map publish_exchanges = (Map) publishRights.get(PUBLISH_EXCHANGES_KEY);
-
- if (publish_exchanges == null)
- {
- publish_exchanges = new ConcurrentHashMap();
- publishRights.put(PUBLISH_EXCHANGES_KEY, publish_exchanges);
- }
-
-
- HashSet routingKeys = (HashSet) publish_exchanges.get(parameters[0]);
-
- // Check to see if we have a routing key
- if (parameters.length == 2)
- {
- if (routingKeys == null)
- {
- routingKeys = new HashSet<AMQShortString>();
- }
- //Add routing key to permitted publish destinations
- routingKeys.add(parameters[1]);
- }
-
- // Add the updated routingkey list or null if all values allowed
- publish_exchanges.put(parameters[0], routingKeys);
- }
- }
-
- private void grantCreateExchange(Permission permission, Object... parameters) {
- Map rights = (Map) _permissions.get(permission);
- if (rights == null)
- {
- rights = new ConcurrentHashMap();
- _permissions.put(permission, rights);
- }
-
- Map create_exchanges = (Map) rights.get(CREATE_EXCHANGES_KEY);
- if (create_exchanges == null)
- {
- create_exchanges = new ConcurrentHashMap();
- rights.put(CREATE_EXCHANGES_KEY, create_exchanges);
- }
-
- //Should perhaps error if parameters[0] is null;
- AMQShortString name = parameters.length > 0 ? (AMQShortString) parameters[0] : null;
- AMQShortString className = parameters.length > 1 ? (AMQShortString) parameters[1] : new AMQShortString("direct");
-
- //Store the exchangeName / class mapping if the mapping is null
- rights.put(name, className);
- }
-
- private void grantCreateQueue(Permission permission, Object... parameters)
- {
- Map createRights = (Map) _permissions.get(permission);
-
- if (createRights == null)
- {
- createRights = new ConcurrentHashMap();
- _permissions.put(permission, createRights);
- }
-
- //The existence of the empty map mean permission to all.
- if (parameters.length == 0)
- {
- return;
- }
-
- // Get the queues map
- Map create_queues = (Map) createRights.get(CREATE_QUEUES_KEY);
-
- //Initialiase the queue permissions if not already done
- if (create_queues == null)
- {
- create_queues = new ConcurrentHashMap();
- //initialise temp queue permission to false and overwrite below if true
- create_queues.put(CREATE_QUEUE_TEMPORARY_KEY, false);
- createRights.put(CREATE_QUEUES_KEY, create_queues);
- }
-
- //Create empty list of queues
- Map create_queues_queues = (Map) create_queues.get(CREATE_QUEUE_QUEUES_KEY);
-
- if (create_queues_queues == null)
- {
- create_queues_queues = new ConcurrentHashMap();
- create_queues.put(CREATE_QUEUE_QUEUES_KEY, create_queues_queues);
- }
-
- // If we are initialising and granting CREATE rights to all temporary queues, then that's all we do
- Boolean temporary = false;
- if (parameters.length == 1)
- {
- temporary = (Boolean) parameters[0];
- create_queues.put(CREATE_QUEUE_TEMPORARY_KEY, temporary);
- return;
- }
-
- //From here we can be permissioning a variety of things, with varying parameters
- AMQShortString queueName = parameters.length > 1 ? (AMQShortString) parameters[1] : null;
- AMQShortString exchangeName = parameters.length > 2 ? (AMQShortString) parameters[2] : null;
- //Set the routingkey to the specified value or the queueName if present
- AMQShortString routingKey = (parameters.length > 3 && null != parameters[3]) ? (AMQShortString) parameters[3] : queueName;
- // if we have a queueName then we need to store any associated exchange / rk bindings
- if (queueName != null)
- {
- Map queue = (Map) create_queues_queues.get(queueName);
- if (queue == null)
- {
- queue = new ConcurrentHashMap();
- create_queues_queues.put(queueName, queue);
- }
-
- if (exchangeName != null)
- {
- queue.put(exchangeName, routingKey);
- }
-
- //If no exchange is specified then the presence of the queueName in the map says any exchange is ok
- }
-
- // Store the exchange that we are being granted rights to. This will be used as part of binding
-
- //Lookup the list of exchanges
- Map create_queues_exchanges = (Map) create_queues.get(CREATE_QUEUE_EXCHANGES_KEY);
-
- if (create_queues_exchanges == null)
- {
- create_queues_exchanges = new ConcurrentHashMap();
- create_queues.put(CREATE_QUEUE_EXCHANGES_KEY, create_queues_exchanges);
- }
-
- //if we have an exchange
- if (exchangeName != null)
- {
- //Retrieve the list of permitted exchanges.
- Map exchanges = (Map) create_queues_exchanges.get(exchangeName);
-
- if (exchanges == null)
- {
- exchanges = new ConcurrentHashMap();
- create_queues_exchanges.put(exchangeName, exchanges);
- }
-
- //Store the binding details of queue/rk for this exchange.
- if (queueName != null)
- {
- //Retrieve the list of permitted routingKeys.
- Map rKeys = (Map) exchanges.get(exchangeName);
-
- if (rKeys == null)
- {
- rKeys = new ConcurrentHashMap();
- exchanges.put(CREATE_QUEUE_EXCHANGES_ROUTINGKEYS_KEY, rKeys);
- }
-
- rKeys.put(queueName, routingKey);
- }
- }
- }
-
- /**
- * Grant consume permissions
- */
- private void grantConsume(Permission permission, Object... parameters)
- {
- Map consumeRights = (Map) _permissions.get(permission);
-
- if (consumeRights == null)
- {
- consumeRights = new ConcurrentHashMap();
- _permissions.put(permission, consumeRights);
-
- //initialise own and temporary rights to false to be overwritten below if set
- consumeRights.put(CONSUME_TEMPORARY_KEY, false);
- consumeRights.put(CONSUME_OWN_QUEUES_ONLY_KEY, false);
- }
-
-
- //if we only have one param then we're permissioning temporary queues and topics
- if (parameters.length == 1)
- {
- Boolean temporary = (Boolean) parameters[0];
-
- if (temporary)
- {
- consumeRights.put(CONSUME_TEMPORARY_KEY, true);
- }
- }
-
- //if we have 2 parameters - should be a contract for this, but for now we'll handle it as is
- if (parameters.length == 2)
- {
- AMQShortString queueName = (AMQShortString) parameters[0];
- Boolean ownQueueOnly = (Boolean) parameters[1];
-
- if (ownQueueOnly)
- {
- consumeRights.put(CONSUME_OWN_QUEUES_ONLY_KEY, true);
- }
-
- LinkedList queues = (LinkedList) consumeRights.get(CONSUME_QUEUES_KEY);
- if (queues == null)
- {
- queues = new LinkedList();
- consumeRights.put(CONSUME_QUEUES_KEY, queues);
- }
-
- if (queueName != null)
- {
- queues.add(queueName);
- }
- }
- }
-
- /**
- *
- * @param permission the type of permission to check
- *
- * @param parameters vararg depending on what permission was passed in
- * ACCESS: none
- * BIND: QueueBindBody bindmethod, Exchange exchange, AMQQueue queue, AMQShortString routingKey
- * CONSUME: AMQQueue queue
- * CREATEQUEUE: Boolean autodelete, AMQShortString name
- * CREATEEXCHANGE: AMQShortString exchangeName
- * DELETE: none
- * PUBLISH: Exchange exchange, AMQShortString routingKey
- * PURGE: none
- * UNBIND: none
- */
- public Result authorise(Permission permission, String... parameters)
- {
-
- switch (permission)
- {
- case ACCESS://No Parameters
- return Result.ALLOWED; // The existence of this user-specific PP infers some level of access is authorised
- case BIND: // Parameters : QueueBindMethod , exhangeName , queueName, routingKey
- return authoriseBind(parameters);
- case CREATEQUEUE:// Parameters : autoDelete, queueName
- return authoriseCreateQueue(permission, parameters);
- case CREATEEXCHANGE: //Parameters: exchangeName
- return authoriseCreateExchange(permission, parameters);
- case CONSUME: // Parameters : queueName, autoDelete, owner
- return authoriseConsume(permission, parameters);
- case PUBLISH: // Parameters : exchangeName, routingKey
- return authorisePublish(permission, parameters);
- /* Fall through */
- case DELETE:
- case PURGE:
- case UNBIND:
- default:
- if(_fullVHostAccess)
- {
- //user has been granted full access to the vhost
- return Result.ALLOWED;
- }
- else
- {
- //SimpleXML ACL does not implement these permissions and should abstain
- return Result.ABSTAIN;
- }
- }
-
- }
-
- private Result authoriseConsume(Permission permission, String... parameters)
- {
- if(_fullVHostAccess)
- {
- //user has been granted full access to the vhost
- return Result.ALLOWED;
- }
-
- if (parameters.length == 3)
- {
- AMQShortString queueName = new AMQShortString(parameters[0]);
- Boolean autoDelete = Boolean.valueOf(parameters[1]);
- AMQShortString owner = new AMQShortString(parameters[2]);
- Map queuePermissions = (Map) _permissions.get(permission);
-
- _logger.error("auth consume on " + StringUtils.join(parameters, ", "));
-
- if (queuePermissions == null)
- {
- //we have a problem - we've never granted this type of permission .....
- return Result.DENIED;
- }
-
- List queues = (List) queuePermissions.get(CONSUME_QUEUES_KEY);
-
- Boolean temporaryQueues = (Boolean) queuePermissions.get(CONSUME_TEMPORARY_KEY);
- Boolean ownQueuesOnly = (Boolean) queuePermissions.get(CONSUME_OWN_QUEUES_ONLY_KEY);
-
-
- // If user is allowed to consume from temporary queues and this is a temp queue then allow it.
- if (temporaryQueues && autoDelete)
- {
- // This will allow consumption from any temporary queue including ones not owned by this user.
- // Of course the exclusivity will not be broken.
- {
-
- // if not limited to ownQueuesOnly then ok else check queue Owner.
- return (!ownQueuesOnly || owner.equals(_user)) ? Result.ALLOWED : Result.DENIED;
- }
- }
- //if this is a temporary queue and the user does not have permissions for temporary queues then deny
- else if (!temporaryQueues && autoDelete)
- {
- return Result.DENIED;
- }
-
- // if queues are white listed then ensure it is ok
- if (queues != null)
- {
- // if no queues are listed then ALL are ok othereise it must be specified.
- if (ownQueuesOnly)
- {
- if (owner.equals(_user))
- {
- return (queues.size() == 0 || queues.contains(queueName)) ? Result.ALLOWED : Result.DENIED;
- }
- else
- {
- return Result.DENIED;
- }
- }
-
- // If we are
- return (queues.size() == 0 || queues.contains(queueName)) ? Result.ALLOWED : Result.DENIED;
- }
- }
-
- // Can't authenticate without the right parameters
- return Result.DENIED;
- }
-
- private Result authorisePublish(Permission permission, String... parameters)
- {
- if(_fullVHostAccess)
- {
- //user has been granted full access to the vhost
- return Result.ALLOWED;
- }
-
- Map publishRights = (Map) _permissions.get(permission);
-
- if (publishRights == null)
- {
- return Result.DENIED;
- }
-
- Map exchanges = (Map) publishRights.get(PUBLISH_EXCHANGES_KEY);
-
- // Having no exchanges listed gives full publish rights to all exchanges
- if (exchanges == null)
- {
- return Result.ALLOWED;
- }
- // Otherwise exchange must be listed in the white list
-
- // If the map doesn't have the exchange then it isn't allowed
- AMQShortString exchangeName = new AMQShortString(parameters[0]);
- if (!exchanges.containsKey(exchangeName))
- {
- return Result.DENIED;
- }
- else
- {
- // Get valid routing keys
- HashSet routingKeys = (HashSet) exchanges.get(exchangeName);
-
- // Having no routingKeys in the map then all are allowed.
- if (routingKeys == null)
- {
- return Result.ALLOWED;
- }
- else
- {
- // We have routingKeys so a match must be found to allowed binding
- Iterator keys = routingKeys.iterator();
-
- AMQShortString publishRKey = new AMQShortString(parameters[1]);
-
- boolean matched = false;
- while (keys.hasNext() && !matched)
- {
- AMQShortString rkey = (AMQShortString) keys.next();
-
- if (rkey.endsWith("*"))
- {
- matched = publishRKey.startsWith(rkey.subSequence(0, rkey.length() - 1));
- }
- else
- {
- matched = publishRKey.equals(rkey);
- }
- }
- return (matched) ? Result.ALLOWED : Result.DENIED;
- }
- }
- }
-
- private Result authoriseCreateExchange(Permission permission, String... parameters)
- {
- if(_fullVHostAccess)
- {
- //user has been granted full access to the vhost
- return Result.ALLOWED;
- }
-
- Map rights = (Map) _permissions.get(permission);
-
- AMQShortString exchangeName = new AMQShortString(parameters[0]);
-
- // If the exchange list is doesn't exist then all is allowed else
- // check the valid exchanges
- if (rights == null || rights.containsKey(exchangeName))
- {
- return Result.ALLOWED;
- }
- else
- {
- return Result.DENIED;
- }
- }
-
- private Result authoriseCreateQueue(Permission permission, String... parameters)
- {
- if(_fullVHostAccess)
- {
- //user has been granted full access to the vhost
- return Result.ALLOWED;
- }
-
- Map createRights = (Map) _permissions.get(permission);
-
- // If there are no create rights then deny request
- if (createRights == null)
- {
- return Result.DENIED;
- }
-
- //Look up the Queue Creation Rights
- Map create_queues = (Map) createRights.get(CREATE_QUEUES_KEY);
-
- //Lookup the list of queues allowed to be created
- Map create_queues_queues = (Map) create_queues.get(CREATE_QUEUE_QUEUES_KEY);
-
-
- Boolean autoDelete = Boolean.valueOf(parameters[0]);
- AMQShortString queueName = new AMQShortString(parameters[1]);
-
- if (autoDelete)// we have a temporary queue
- {
- return ((Boolean) create_queues.get(CREATE_QUEUE_TEMPORARY_KEY)) ? Result.ALLOWED : Result.DENIED;
- }
- else
- {
- // If there is a white list then check
- if (create_queues_queues == null || create_queues_queues.containsKey(queueName))
- {
- return Result.ALLOWED;
- }
- else
- {
- return Result.DENIED;
- }
-
- }
- }
-
- private Result authoriseBind(String... parameters)
- {
- if(_fullVHostAccess)
- {
- //user has been granted full access to the vhost
- return Result.ALLOWED;
- }
-
- AMQShortString exchangeName = new AMQShortString(parameters[1]);
- AMQShortString bind_queueName = new AMQShortString(parameters[2]);
- AMQShortString routingKey = new AMQShortString(parameters[3]);
-
- //Get all Create Rights for this user
- Map bindCreateRights = (Map) _permissions.get(Permission.CREATEQUEUE);
-
- //Lookup the list of queues
- Map bind_create_queues_queues = (Map) bindCreateRights.get(CREATE_QUEUE_QUEUES_KEY);
-
- // Check and see if we have a queue white list to check
- if (bind_create_queues_queues != null)
- {
- //There a white list for queues
- Map exchangeDetails = (Map) bind_create_queues_queues.get(bind_queueName);
-
- if (exchangeDetails == null) //Then all queue can be bound to all exchanges.
- {
- return Result.ALLOWED;
- }
-
- // Check to see if we have a white list of routingkeys to check
- Map rkeys = (Map) exchangeDetails.get(exchangeName);
-
- // if keys is null then any rkey is allowed on this exchange
- if (rkeys == null)
- {
- // There is no routingkey white list
- return Result.ALLOWED;
- }
- else
- {
- // We have routingKeys so a match must be found to allowed binding
- Iterator keys = rkeys.keySet().iterator();
-
- boolean matched = false;
- while (keys.hasNext() && !matched)
- {
- AMQShortString rkey = (AMQShortString) keys.next();
- if (rkey.endsWith("*"))
- {
- matched = routingKey.startsWith(rkey.subSequence(0, rkey.length() - 1).toString());
- }
- else
- {
- matched = routingKey.equals(rkey);
- }
- }
-
-
- return (matched) ? Result.ALLOWED : Result.DENIED;
- }
-
-
- }
- else
- {
- //no white list so all allowed.
- return Result.ALLOWED;
- }
- }
-}
diff --git a/java/broker-plugins/simple-xml/src/main/java/org/apache/qpid/server/security/access/plugins/SimpleXML.java b/java/broker-plugins/simple-xml/src/main/java/org/apache/qpid/server/security/access/plugins/SimpleXML.java
deleted file mode 100644
index ab43653122..0000000000
--- a/java/broker-plugins/simple-xml/src/main/java/org/apache/qpid/server/security/access/plugins/SimpleXML.java
+++ /dev/null
@@ -1,427 +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 static org.apache.qpid.server.security.access.ObjectProperties.Property.*;
-
-import java.security.Principal;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-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.security.AbstractPlugin;
-import org.apache.qpid.server.security.Result;
-import org.apache.qpid.server.security.SecurityManager;
-import org.apache.qpid.server.security.SecurityPluginFactory;
-import org.apache.qpid.server.security.access.ObjectProperties;
-import org.apache.qpid.server.security.access.ObjectType;
-import org.apache.qpid.server.security.access.Operation;
-import org.apache.qpid.server.security.access.config.PrincipalPermissions;
-import org.apache.qpid.server.security.access.config.PrincipalPermissions.Permission;
-
-/**
- * This uses the default
- */
-public class SimpleXML extends AbstractPlugin
-{
- public static final Logger _logger = Logger.getLogger(SimpleXML.class);
-
- private Map<String, PrincipalPermissions> _users;
-
- public static final SecurityPluginFactory<SimpleXML> FACTORY = new SecurityPluginFactory<SimpleXML>()
- {
- public SimpleXML newInstance(ConfigurationPlugin config) throws ConfigurationException
- {
- SimpleXMLConfiguration configuration = config.getConfiguration(SimpleXMLConfiguration.class.getName());
-
- // If there is no configuration for this plugin then don't load it.
- if (configuration == null)
- {
- return null;
- }
-
- SimpleXML plugin = new SimpleXML();
- plugin.configure(configuration);
- return plugin;
- }
-
- public String getPluginName()
- {
- return SimpleXML.class.getName();
- }
-
- public Class<SimpleXML> getPluginClass()
- {
- return SimpleXML.class;
- }
- };
-
- public void configure(ConfigurationPlugin config)
- {
- super.configure(config);
-
- SimpleXMLConfiguration configuration = (SimpleXMLConfiguration) _config;
-
- _users = new ConcurrentHashMap<String, PrincipalPermissions>();
-
- processConfig(configuration.getConfiguration());
- }
-
- private void processConfig(Configuration config)
- {
- processPublish(config);
- processConsume(config);
- processCreate(config);
- processAccess(config);
- }
-
- /**
- * @param config XML Configuration
- */
- private void processAccess(Configuration config)
- {
- Configuration accessConfig = config.subset("access");
-
- if (accessConfig.isEmpty())
- {
- //there is no access configuration to process
- return;
- }
-
- // Process users that have full access permission
- String[] users = accessConfig.getStringArray("users.user");
-
- for (String user : users)
- {
- grant(Permission.ACCESS, user);
- }
- }
-
- /**
- * Publish format takes Exchange + Routing Key Pairs
- *
- * @param config XML Configuration
- */
- private void processPublish(Configuration config)
- {
- Configuration publishConfig = config.subset("publish");
-
- // Process users that have full publish permission
- String[] users = publishConfig.getStringArray("users.user");
-
- for (String user : users)
- {
- grant(Permission.PUBLISH, user);
- }
-
- // Process exchange limited users
- int exchangeCount = 0;
- Configuration exchangeConfig = publishConfig.subset("exchanges.exchange(" + exchangeCount + ")");
-
- while (!exchangeConfig.isEmpty())
- {
- // Get Exchange Name
- AMQShortString exchangeName = new AMQShortString(exchangeConfig.getString("name"));
-
- // Get Routing Keys
- int keyCount = 0;
- Configuration routingkeyConfig = exchangeConfig.subset("routing_keys.routing_key(" + keyCount + ")");
-
- while (!routingkeyConfig.isEmpty())
- {
- // Get RoutingKey Value
- AMQShortString routingKeyValue = new AMQShortString(routingkeyConfig.getString("value"));
-
- // Apply Exchange + RoutingKey permissions to Users
- users = routingkeyConfig.getStringArray("users.user");
- for (String user : users)
- {
- grant(Permission.PUBLISH, user, exchangeName, routingKeyValue);
- }
-
- // Apply permissions to Groups
-
- // Check for more configs
- keyCount++;
- routingkeyConfig = exchangeConfig.subset("routing_keys.routing_key(" + keyCount + ")");
- }
-
- // Apply Exchange wide permissions to Users
- users = exchangeConfig.getStringArray("exchange(" + exchangeCount + ").users.user");
-
- for (String user : users)
- {
- grant(Permission.PUBLISH, user, exchangeName);
- }
-
- // Apply permissions to Groups
- exchangeCount++;
- exchangeConfig = publishConfig.subset("exchanges.exchange(" + exchangeCount + ")");
- }
- }
-
- private void grant(Permission permission, String user, Object... parameters)
- {
- PrincipalPermissions permissions = _users.get(user);
-
- if (permissions == null)
- {
- permissions = new PrincipalPermissions(user);
- }
-
- _users.put(user, permissions);
- permissions.grant(permission, parameters);
- }
-
- /**
- * @param config XML Configuration
- */
- private void processConsume(Configuration config)
- {
- boolean temporary = false;
- Configuration tempConfig = null;
- Configuration consumeConfig = config.subset("consume");
-
- tempConfig = consumeConfig.subset("queues.temporary(0)");
- if (tempConfig != null)
- {
- temporary = true;
- }
-
- //Permission all users who have rights to temp queues and topics
- if (tempConfig != null && !tempConfig.isEmpty())
- {
- String[] tempUsers = tempConfig.getStringArray("users.user");
- for (String user : tempUsers)
- {
- grant(Permission.CONSUME, user, temporary);
- }
- }
-
- // Process queue limited users
- int queueCount = 0;
- Configuration queueConfig = consumeConfig.subset("queues.queue(" + queueCount + ")");
-
- while (!queueConfig.isEmpty())
- {
- // Get queue Name
- AMQShortString queueName = new AMQShortString(queueConfig.getString("name"));
- // if there is no name then there may be a temporary element
-
- boolean ownQueues = queueConfig.containsKey("own_queues");
-
- // Process permissions for this queue
- String[] users = queueConfig.getStringArray("users.user");
- for (String user : users)
- {
- grant(Permission.CONSUME, user, queueName, ownQueues);
- }
-
- // See if we have another config
- queueCount++;
- queueConfig = consumeConfig.subset("queues.queue(" + queueCount + ")");
- }
-
- // Process users that have full consume permission
- String[] users = consumeConfig.getStringArray("users.user");
-
- for (String user : users)
- {
- //NOTE: this call does not appear to do anything inside the grant section for consume
- grant(Permission.CONSUME, user);
- }
- }
-
- /**
- * @param config XML Configuration
- */
- private void processCreate(Configuration config)
- {
- boolean temporary = false;
- Configuration tempConfig = null;
-
- Configuration createConfig = config.subset("create");
-
- tempConfig = createConfig.subset("queues.temporary(0)");
- if (tempConfig != null)
- {
- temporary = true;
- }
-
- //Permission all users who have rights to temp queues and topics
- if (tempConfig != null && !tempConfig.isEmpty())
- {
- String[] tempUsers = tempConfig.getStringArray("users.user");
- for (String user : tempUsers)
- {
- grant(Permission.CREATEQUEUE, user, temporary);
- }
- }
- // Process create permissions for queue creation
- int queueCount = 0;
- Configuration queueConfig = createConfig.subset("queues.queue(" + queueCount + ")");
-
- while (!queueConfig.isEmpty())
- {
- // Get queue Name
- AMQShortString queueName = new AMQShortString(queueConfig.getString("name"));
-
- int exchangeCount = 0;
- Configuration exchangeConfig = queueConfig.subset("exchanges.exchange(" + exchangeCount + ")");
-
- while (!exchangeConfig.isEmpty())
- {
-
- AMQShortString exchange = new AMQShortString(exchangeConfig.getString("name"));
- AMQShortString routingKey = new AMQShortString(exchangeConfig.getString("routing_key"));
-
- // Process permissions for this queue
- String[] users = exchangeConfig.getStringArray("users.user");
- for (String user : users)
- {
- //This is broken as the user name is not stored
- grant(Permission.CREATEEXCHANGE, user, exchange);
-
- //This call could be cleaned up as temporary is now being set earlier (above)
- grant(Permission.CREATEQUEUE, user, temporary, (queueName.equals("") ? null : queueName), (exchange
- .equals("") ? null : exchange), (routingKey.equals("") ? null : routingKey));
- }
-
- // See if we have another config
- exchangeCount++;
- exchangeConfig = queueConfig.subset("exchanges.exchange(" + exchangeCount + ")");
- }
-
- // Process users that are not bound to an exchange
- String[] users = queueConfig.getStringArray("users.user");
-
- for (String user : users)
- {
- grant(Permission.CREATEQUEUE, user, temporary, queueName);
- }
-
- // See if we have another config
- queueCount++;
- queueConfig = createConfig.subset("queues.queue(" + queueCount + ")");
- }
-
- // Process create permissions for exchange creation
- int exchangeCount = 0;
- Configuration exchangeConfig = createConfig.subset("exchanges.exchange(" + exchangeCount + ")");
-
- while (!exchangeConfig.isEmpty())
- {
- AMQShortString exchange = new AMQShortString(exchangeConfig.getString("name"));
- AMQShortString clazz = new AMQShortString(exchangeConfig.getString("class"));
-
- // Process permissions for this queue
- String[] users = exchangeConfig.getStringArray("users.user");
- for (String user : users)
- {
- //And this is broken too
- grant(Permission.CREATEEXCHANGE, user, exchange, clazz);
- }
-
- // See if we have another config
- exchangeCount++;
- exchangeConfig = queueConfig.subset("exchanges.exchange(" + exchangeCount + ")");
- }
-
- // Process users that have full create permission
- String[] users = createConfig.getStringArray("users.user");
-
- for (String user : users)
- {
- grant(Permission.CREATEEXCHANGE, user);
- grant(Permission.CREATEQUEUE, user);
- }
- }
-
- public Result access(ObjectType objectType, Object instance)
- {
- Principal principal = SecurityManager.getThreadPrincipal();
- if (principal == null)
- {
- return getDefault(); // Default if there is no user associated with the thread
- }
- PrincipalPermissions principalPermissions = _users.get(principal.getName());
- if (principalPermissions == null)
- {
- return Result.DENIED;
- }
-
- // Authorise object access
- if (objectType == ObjectType.VIRTUALHOST)
- {
- return principalPermissions.authorise(Permission.ACCESS);
- }
-
- // Default
- return getDefault();
- }
-
- public Result authorise(Operation operation, ObjectType objectType, ObjectProperties properties)
- {
- Principal principal = SecurityManager.getThreadPrincipal();
- if (principal == null)
- {
- return getDefault(); // Default if there is no user associated with the thread
- }
- PrincipalPermissions principalPermissions = _users.get(principal.getName());
- if (principalPermissions == null)
- {
- return Result.DENIED;
- }
-
- // Authorise operation
- switch (operation)
- {
- case CONSUME:
- return principalPermissions.authorise(Permission.CONSUME, properties.get(NAME), properties.get(AUTO_DELETE), properties.get(OWNER));
- case PUBLISH:
- return principalPermissions.authorise(Permission.PUBLISH, properties.get(NAME), properties.get(ROUTING_KEY));
- case CREATE:
- if (objectType == ObjectType.EXCHANGE)
- {
- return principalPermissions.authorise(Permission.CREATEEXCHANGE, properties.get(NAME));
- }
- else if (objectType == ObjectType.QUEUE)
- {
- return principalPermissions.authorise(Permission.CREATEQUEUE, properties.get(AUTO_DELETE), properties.get(NAME));
- }
- case ACCESS:
- return principalPermissions.authorise(Permission.ACCESS);
- case BIND:
- return principalPermissions.authorise(Permission.BIND, null, properties.get(NAME), properties.get(QUEUE_NAME), properties.get(ROUTING_KEY));
- case UNBIND:
- return principalPermissions.authorise(Permission.UNBIND);
- case DELETE:
- return principalPermissions.authorise(Permission.DELETE);
- case PURGE:
- return principalPermissions.authorise(Permission.PURGE);
- }
-
- // Default
- return getDefault();
- }
-}
diff --git a/java/broker-plugins/simple-xml/src/main/java/org/apache/qpid/server/security/access/plugins/SimpleXMLActivator.java b/java/broker-plugins/simple-xml/src/main/java/org/apache/qpid/server/security/access/plugins/SimpleXMLActivator.java
deleted file mode 100644
index c09a9da0d8..0000000000
--- a/java/broker-plugins/simple-xml/src/main/java/org/apache/qpid/server/security/access/plugins/SimpleXMLActivator.java
+++ /dev/null
@@ -1,42 +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 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 SimpleXML}.
- */
-public class SimpleXMLActivator extends SecurityPluginActivator
-{
- public SecurityPluginFactory getFactory()
- {
- return SimpleXML.FACTORY;
- }
-
- public ConfigurationPluginFactory getConfigurationFactory()
- {
- return SimpleXMLConfiguration.FACTORY;
- }
-}
diff --git a/java/broker-plugins/simple-xml/src/main/java/org/apache/qpid/server/security/access/plugins/SimpleXMLConfiguration.java b/java/broker-plugins/simple-xml/src/main/java/org/apache/qpid/server/security/access/plugins/SimpleXMLConfiguration.java
deleted file mode 100644
index e95c21b590..0000000000
--- a/java/broker-plugins/simple-xml/src/main/java/org/apache/qpid/server/security/access/plugins/SimpleXMLConfiguration.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.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;
-
-public class SimpleXMLConfiguration extends ConfigurationPlugin
-{
- public static final ConfigurationPluginFactory FACTORY = new ConfigurationPluginFactory()
- {
- public ConfigurationPlugin newInstance(String path, Configuration config) throws ConfigurationException
- {
- ConfigurationPlugin instance = new SimpleXMLConfiguration();
- instance.setConfiguration(path, config);
- return instance;
- }
-
- public List<String> getParentPaths()
- {
- return Arrays.asList("security.access_control_list", "virtualhosts.virtualhost.security.access_control_list");
- }
- };
-
- public String[] getElementsProcessed()
- {
- return new String[] { "" };
- }
-
- public Configuration getConfiguration()
- {
- return _configuration;
- }
-}
diff --git a/java/broker-plugins/simple-xml/src/test/java/org/apache/qpid/server/security/access/PrincipalPermissionsTest.java b/java/broker-plugins/simple-xml/src/test/java/org/apache/qpid/server/security/access/PrincipalPermissionsTest.java
deleted file mode 100644
index 65ab12a095..0000000000
--- a/java/broker-plugins/simple-xml/src/test/java/org/apache/qpid/server/security/access/PrincipalPermissionsTest.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.security.access;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.server.security.Result;
-import org.apache.qpid.server.security.access.config.PrincipalPermissions;
-import org.apache.qpid.server.security.access.config.PrincipalPermissions.Permission;
-import org.apache.qpid.test.utils.QpidTestCase;
-
-public class PrincipalPermissionsTest extends QpidTestCase
-{
- private String _user = "user";
- private PrincipalPermissions _perms;
-
- // Common things that are passed to frame constructors
- private AMQShortString _queueName = new AMQShortString(this.getClass().getName() + "queue");
- private AMQShortString _tempQueueName = new AMQShortString(this.getClass().getName() + "tempqueue");
- private AMQShortString _exchangeName = new AMQShortString("amq.direct");
- private AMQShortString _routingKey = new AMQShortString(this.getClass().getName() + "route");
- private boolean _autoDelete = false;
- private AMQShortString _exchangeType = new AMQShortString("direct");
- private Boolean _temporary = false;
- private Boolean _ownQueue = false;
-
- @Override
- public void setUp() throws Exception
- {
- super.setUp();
-
- _perms = new PrincipalPermissions(_user);
- }
-
-
- public void testPrincipalPermissions()
- {
- assertNotNull(_perms);
- assertEquals(Result.ALLOWED, _perms.authorise(Permission.ACCESS, (String[]) null));
- }
-
- // FIXME: test has been disabled since the permissions assume that the user has tried to create
- // the queue first. QPID-1597
- public void disableTestBind() throws Exception
- {
- String[] args = new String[]{null, _exchangeName.asString(), _queueName.asString(), _routingKey.asString()};
-
- assertEquals(Result.DENIED, _perms.authorise(Permission.BIND, args));
- _perms.grant(Permission.BIND, (Object[]) null);
- assertEquals(Result.ALLOWED, _perms.authorise(Permission.BIND, args));
- }
-
- public void testQueueCreate()
- {
- Object[] grantArgs = new Object[]{_temporary , _queueName, _exchangeName, _routingKey};
- String[] authArgs = new String[]{Boolean.toString(_autoDelete), _queueName.asString()};
-
- assertEquals(Result.DENIED, _perms.authorise(Permission.CREATEQUEUE, authArgs));
- _perms.grant(Permission.CREATEQUEUE, grantArgs);
- assertEquals(Result.ALLOWED, _perms.authorise(Permission.CREATEQUEUE, authArgs));
- }
-
- public void testQueueCreateWithNullRoutingKey()
- {
- Object[] grantArgs = new Object[]{_temporary , _queueName, _exchangeName, null};
- String[] authArgs = new String[]{Boolean.toString(_autoDelete), _queueName.asString()};
-
- assertEquals(Result.DENIED, _perms.authorise(Permission.CREATEQUEUE, authArgs));
- _perms.grant(Permission.CREATEQUEUE, grantArgs);
- assertEquals(Result.ALLOWED, _perms.authorise(Permission.CREATEQUEUE, authArgs));
- }
-
- // FIXME disabled, this fails due to grant putting the grant into the wrong map QPID-1598
- public void disableTestExchangeCreate()
- {
- String[] authArgs = new String[]{_exchangeName.asString()};
- Object[] grantArgs = new Object[]{_exchangeName, _exchangeType};
-
- assertEquals(Result.DENIED, _perms.authorise(Permission.CREATEEXCHANGE, authArgs));
- _perms.grant(Permission.CREATEEXCHANGE, grantArgs);
- assertEquals(Result.ALLOWED, _perms.authorise(Permission.CREATEEXCHANGE, authArgs));
- }
-
- public void testConsume()
- {
- String[] authArgs = new String[]{_queueName.asString(), Boolean.toString(_autoDelete), _user};
- Object[] grantArgs = new Object[]{_queueName, _ownQueue};
-
- // FIXME: This throws a null pointer exception QPID-1599
- // assertFalse(_perms.authorise(Permission.CONSUME, authArgs));
- _perms.grant(Permission.CONSUME, grantArgs);
- assertEquals(Result.ALLOWED, _perms.authorise(Permission.CONSUME, authArgs));
- }
-
- public void testPublish() throws AMQException
- {
- String[] authArgs = new String[]{_exchangeName.asString(), _routingKey.asString()};
- Object[] grantArgs = new Object[]{_exchangeName, _routingKey};
-
- assertEquals(Result.DENIED, _perms.authorise(Permission.PUBLISH, authArgs));
- _perms.grant(Permission.PUBLISH, grantArgs);
- assertEquals(Result.ALLOWED, _perms.authorise(Permission.PUBLISH, authArgs));
- }
-
- public void testVhostAccess()
- {
- //Tests that granting a user Virtualhost level access allows all authorisation requests
- //where previously they would be denied
-
- //QPID-2133 createExchange rights currently allow all exchange creation unless rights for creating some
- //specific exchanges are granted. Grant a specific exchange creation to cause all others to be denied.
- Object[] createArgsCreateExchange = new Object[]{new AMQShortString("madeup"), _exchangeType};
- String[] authArgsCreateExchange = new String[]{_exchangeName.asString()};
- assertEquals("Exchange creation was not allowed", Result.ALLOWED, _perms.authorise(Permission.CREATEEXCHANGE, authArgsCreateExchange));
- _perms.grant(Permission.CREATEEXCHANGE, createArgsCreateExchange);
-
- String[] authArgsPublish = new String[]{_exchangeName.asString(), _routingKey.asString()};
- String[] authArgsConsume = new String[]{_queueName.asString(), Boolean.toString(_autoDelete), _user};
- String[] authArgsCreateQueue = new String[]{Boolean.toString(_autoDelete), _queueName.asString()};
-// QueueBindBodyImpl bind = new QueueBindBodyImpl(_ticket, _queueName, _exchangeName, _routingKey, _nowait, _arguments);
- String[] authArgsBind = new String[]{ null, _exchangeName.asString(), _queueName.asString(), _routingKey.asString()};
-
- assertEquals("Exchange creation was not denied", Result.DENIED, _perms.authorise(Permission.CREATEEXCHANGE, authArgsCreateExchange));
- assertEquals("Publish was not denied", Result.DENIED, _perms.authorise(Permission.PUBLISH, authArgsPublish));
- assertEquals("Consume creation was not denied", Result.DENIED, _perms.authorise(Permission.CONSUME, authArgsConsume));
- assertEquals("Queue creation was not denied", Result.DENIED, _perms.authorise(Permission.CREATEQUEUE, authArgsCreateQueue));
- //BIND pre-grant authorise check disabled due to QPID-1597
- //assertEquals("Binding creation was not denied", Result.DENIED, _perms.authorise(Permission.BIND, authArgsBind));
-
- _perms.grant(Permission.ACCESS);
-
- assertEquals("Exchange creation was not allowed", Result.ALLOWED, _perms.authorise(Permission.CREATEEXCHANGE, authArgsCreateExchange));
- assertEquals("Publish was not allowed", Result.ALLOWED, _perms.authorise(Permission.PUBLISH, authArgsPublish));
- assertEquals("Consume creation was not allowed", Result.ALLOWED, _perms.authorise(Permission.CONSUME, authArgsConsume));
- assertEquals("Queue creation was not allowed", Result.ALLOWED, _perms.authorise(Permission.CREATEQUEUE, authArgsCreateQueue));
- assertEquals("Binding creation was not allowed", Result.ALLOWED, _perms.authorise(Permission.BIND, authArgsBind));
- }
-
- /**
- * If the consume permission for temporary queues is for an unnamed queue then is should
- * be global for any temporary queue but not for any non-temporary queue
- */
- public void testTemporaryUnnamedQueueConsume()
- {
- String[] authNonTempQArgs = new String[]{_queueName.asString(), Boolean.toString(_autoDelete), _user};
- String[] authTempQArgs = new String[]{_tempQueueName.asString(), Boolean.TRUE.toString(), _user};
- Object[] grantArgs = new Object[]{true};
-
- _perms.grant(Permission.CONSUME, grantArgs);
-
- //Next line shows up bug - non temp queue should be denied
- assertEquals(Result.DENIED, _perms.authorise(Permission.CONSUME, authNonTempQArgs));
- assertEquals(Result.ALLOWED, _perms.authorise(Permission.CONSUME, authTempQArgs));
- }
-
- /**
- * Test that temporary queue permissions before queue perms in the ACL config work correctly
- */
- public void testTemporaryQueueFirstConsume()
- {
- String[] authNonTempQArgs = new String[]{_queueName.asString(), Boolean.toString(_autoDelete), _user};
- String[] authTempQArgs = new String[]{_tempQueueName.asString(), Boolean.TRUE.toString(), _user};
- Object[] grantArgs = new Object[]{true};
- Object[] grantNonTempQArgs = new Object[]{_queueName, _ownQueue};
-
- //should not matter if the temporary permission is processed first or last
- _perms.grant(Permission.CONSUME, grantNonTempQArgs);
- _perms.grant(Permission.CONSUME, grantArgs);
-
- assertEquals(Result.ALLOWED, _perms.authorise(Permission.CONSUME, authNonTempQArgs));
- assertEquals(Result.ALLOWED, _perms.authorise(Permission.CONSUME, authTempQArgs));
- }
-
- /**
- * Test that temporary queue permissions after queue perms in the ACL config work correctly
- */
- public void testTemporaryQueueLastConsume()
- {
- String[] authNonTempQArgs = new String[]{_queueName.asString(), Boolean.toString(_autoDelete), _user};
- String[] authTempQArgs = new String[]{_tempQueueName.asString(), Boolean.TRUE.toString(), _user};
- Object[] grantArgs = new Object[]{true};
- Object[] grantNonTempQArgs = new Object[]{_queueName, _ownQueue};
-
- //should not matter if the temporary permission is processed first or last
- _perms.grant(Permission.CONSUME, grantArgs);
- _perms.grant(Permission.CONSUME, grantNonTempQArgs);
-
- assertEquals(Result.ALLOWED, _perms.authorise(Permission.CONSUME, authNonTempQArgs));
- assertEquals(Result.ALLOWED, _perms.authorise(Permission.CONSUME, authTempQArgs));
- }
-}
diff --git a/java/broker/bin/create-example-ssl-stores.bat b/java/broker/bin/create-example-ssl-stores.bat
deleted file mode 100644
index 5419c098d5..0000000000
--- a/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/java/broker/bin/create-example-ssl-stores.sh b/java/broker/bin/create-example-ssl-stores.sh
deleted file mode 100755
index bfcb3dfecf..0000000000
--- a/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/java/broker/bin/msTool.sh b/java/broker/bin/msTool.sh
deleted file mode 100755
index e190a0a46a..0000000000
--- a/java/broker/bin/msTool.sh
+++ /dev/null
@@ -1,60 +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.
-#
-
-die() {
- if [[ $1 = -usage ]]; then
- shift
- usage=true
- else
- usage=false
- fi
- echo "$@"
- $usage && echo
- $usage && usage
- exit 1
-}
-
-cygwin=false
-if [[ "$(uname -a | fgrep Cygwin)" != "" ]]; then
- cygwin=true
-fi
-
-if [ -z "$QPID_TOOLS" ]; then
- if [ -z "$QPID_HOME" ]; then
- die "QPID_TOOLS must be set"
- else
- QPID_TOOLS=$QPID_HOME
- fi
-fi
-
-if $cygwin; then
- QPID_TOOLS=$(cygpath -w $QPID_TOOLS)
-fi
-
-# Set classpath to include Qpid jar with all required jars in manifest
-QPID_LIBS=$QPID_TOOLS/lib/qpid-all.jar
-
-# Set other variables used by the qpid-run script before calling
-export JAVA=java \
- JAVA_VM=-server \
- JAVA_OPTS=-Dlog4j.configuration=file:$QPID_TOOLS/etc/mstool-log4j.xml \
- QPID_CLASSPATH=$QPID_LIBS
-
-. qpid-run org.apache.qpid.tools.messagestore.MessageStoreTool "$@"
diff --git a/java/broker/bin/qpid-passwd b/java/broker/bin/qpid-passwd
deleted file mode 100755
index f432e00ab8..0000000000
--- a/java/broker/bin/qpid-passwd
+++ /dev/null
@@ -1,35 +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.
-#
-
-WHEREAMI=`dirname $0`
-if [ -z "$QPID_HOME" ]; then
- export QPID_HOME=`cd $WHEREAMI/../ && pwd`
-fi
-
-# Set classpath to include Qpid jar with all required jars in manifest
-QPID_LIBS=$QPID_HOME/lib/qpid-all.jar
-
-# Set other variables used by the qpid-run script before calling
-export JAVA=java \
- JAVA_VM=-server \
- JAVA_MEM=-Xmx1024m \
- QPID_CLASSPATH=$QPID_LIBS
-
-. ${QPID_HOME}/bin/qpid-run org.apache.qpid.tools.security.Passwd "$@"
diff --git a/java/broker/bin/qpid-server b/java/broker/bin/qpid-server
deleted file mode 100755
index 90b11da202..0000000000
--- a/java/broker/bin/qpid-server
+++ /dev/null
@@ -1,56 +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.
-#
-WHEREAMI=`dirname $0`
-if [ -z "$QPID_HOME" ]; then
- export QPID_HOME=`cd $WHEREAMI/../ && pwd`
-fi
-
-if [ -z "$QPID_WORK" ]; then
- echo "Setting QPID_WORK to $HOME as default"
- QPID_WORK=$HOME
-fi
-
-# Set to help us get round the manifold problems of ps/pgrep on various
-# platforms which gather up to prevent qpid_stop from working .....
-if [ -z "$QPID_PNAME" ]; then
- export QPID_PNAME=" -DPNAME=QPBRKR"
-fi
-
-# Set classpath to include Qpid jar with all required jars in manifest
-QPID_LIBS=$QPID_HOME/lib/qpid-all.jar
-
-# Set other variables used by the qpid-run script before calling
-export JAVA=java \
- JAVA_VM=-server \
- JAVA_MEM=-Xmx1024m \
- JAVA_GC="-XX:+UseConcMarkSweepGC -XX:+HeapDumpOnOutOfMemoryError" \
- QPID_CLASSPATH=$QPID_LIBS \
- QPID_RUN_LOG=2
-
-QPID_OPTS="$QPID_OPTS -Damqj.read_write_pool_size=32 -DQPID_LOG_APPEND=$QPID_LOG_APPEND"
-
-# Echo the PID to file. Since qpid-run is sourced and uses exec to
-# launch the broker, this will give the brokers PID.
-if [ -z "$QPID_PID_FILENAME" ]; then
- export QPID_PID_FILENAME="qpid-server.pid"
-fi
-echo $$ > ${QPID_WORK}/${QPID_PID_FILENAME}
-
-. ${QPID_HOME}/bin/qpid-run org.apache.qpid.server.Main "$@"
diff --git a/java/broker/bin/qpid-server.bat b/java/broker/bin/qpid-server.bat
deleted file mode 100644
index c81f5fc3e7..0000000000
--- a/java/broker/bin/qpid-server.bat
+++ /dev/null
@@ -1,201 +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
-
-@echo off
-REM Script to run the Qpid Java Broker
-
-rem Guess QPID_HOME if not defined
-set CURRENT_DIR=%cd%
-if not "%QPID_HOME%" == "" goto gotHome
-set QPID_HOME=%CURRENT_DIR%
-echo %QPID_HOME%
-if exist "%QPID_HOME%\bin\qpid-server.bat" goto okHome
-cd ..
-set QPID_HOME=%cd%
-cd %CURRENT_DIR%
-:gotHome
-if exist "%QPID_HOME%\bin\qpid-server.bat" goto okHome
-echo The QPID_HOME environment variable is not defined correctly
-echo This environment variable is needed to run this program
-goto end
-:okHome
-
-REM set QPID_WORK if not set
-if not "%QPID_WORK%" == "" goto okQpidWork
-if "%HOME%" == "" goto noHome
-set QPID_WOKR=%HOME%
-goto okQpidWork
-
-:noHome
-set QPID_WORK=c:\Temp
-if not exist %QPID_WORK% md %QPID_WORK%
-:okQpidWork
-
-if not "%JAVA_HOME%" == "" goto gotJavaHome
-echo The JAVA_HOME environment variable is not defined
-echo This environment variable is needed to run this program
-goto end
-:gotJavaHome
-if not exist "%JAVA_HOME%\bin\java.exe" goto noJavaHome
-goto okJavaHome
-:noJavaHome
-echo The JAVA_HOME environment variable is not defined correctly
-echo This environment variable is needed to run this program.
-goto end
-:okJavaHome
-
-REM set loggin level if not set
-if "%AMQJ_LOGGING_LEVEL%" == "" set AMQJ_LOGGING_LEVEL=info
-
-REM Set the default system properties that we'll use now that they have
-REM all been initialised
-set SYSTEM_PROPS=-Damqj.logging.level=%AMQJ_LOGGING_LEVEL% "-DQPID_HOME=%QPID_HOME%" "-DQPID_WORK=%QPID_WORK%"
-
-if "%EXTERNAL_CLASSPATH%" == "" set EXTERNAL_CLASSPATH=%CLASSPATH%
-
-REM Use QPID_CLASSPATH if set
-if "%QPID_CLASSPATH%" == "" goto noQpidClasspath
-set CLASSPATH=%QPID_CLASSPATH%
-echo Using CLASSPATH: %CLASSPATH%
-goto afterQpidClasspath
-
-:noQpidClasspath
-echo Warning: Qpid classpath not set. CLASSPATH set to %QPID_HOME%\lib\qpid-all.jar
-set CLASSPATH=%QPID_HOME%\lib\qpid-all.jar
-:afterQpidClasspath
-
-REM start parsing -run arguments
-set QPID_ARGS=
-if "%1" == "" goto endRunArgs
-:runLoop
-set var=%1
-if "%var:~0,5%" == "-run:" goto runFound
-set QPID_ARGS=%QPID_ARGS% %1
-:beforeRunShift
-shift
-if not "%1"=="" goto runLoop
-goto endRunArgs
-
-:runFound
-if "%var%" == "-run:debug" goto runDebug
-if "%var%" == "-run:jpda" goto runJdpa
-if "%var:~0,24%" == "-run:external-classpath-" goto runExternalClasspath
-if "%var%" == "-run:print-classpath" goto runPrintCP
-if "%var%" == "-run:help" goto runHelp
-echo "unrecognized -run option '%var%'. For using external classpaths use -run:external-classpath-option"
-goto end
-
-:runDebug
-REM USAGE: print the classpath and command before running it
-set debug=true
-goto beforeRunShift
-
-:runJdpa
-REM USAGE: adds debugging options to the java command, use
-REM USAGE: JDPA_TRANSPORT and JPDA_ADDRESS to customize the debugging
-REM USAGE: behavior and use JPDA_OPTS to override it entirely
-if "%JPDA_OPTS%" == "" goto beforeRunShift
-if "%JPDA_TRANSPORT%" == "" set JPDA_TRANSPORT=-dt_socket
-if "%JPDA_ADDRESS%" == "" set JPDA_ADDRESS=8000
-set JPDA_OPTS="-Xdebug -Xrunjdwp:transport=%JPDA_TRANSPORT%,address=%JPDA_ADDRESS%,server=y,suspend=n"
-set QPID_OPTS="%QPID_OPTS% %JPDA_OPTS%"
-goto beforeRunShift
-
-:runExternalClasspath
-echo Using external classpath %var%
-REM USAGE: Format is -run:external-classpath-first/last/ignore/only as equals special in DOS
-REM USAGE: controls how the CLASSPATH environment variable is used by
-REM USAGE: this script, value can be one of ignore (the default), first,
-REM USAGE: last, and only
-if "%var%" == "-run:external-classpath-ignore" goto beforeRunShift
-if "%var%" == "-run:external-classpath-first" goto extCPFirst
-if "%var%" == "-run:external-classpath-last" goto extCPLast
-if "%var%" == "-run:external-classpath-only" goto extCPOnly
-echo Invalid value provided for external classpath.
-goto end
-
-:extCPFirst
-set CLASSPATH=%EXTERNAL_CLASSPATH%;%CLASSPATH%
-goto beforeRunShift
-
-:extCPLast
-set CLASSPATH=%CLASSPATH%;%EXTERNAL_CLASSPATH%
-goto beforeRunShift
-
-:extCPonly
-set CLASSPATH=%EXTERNAL_CLASSPATH%
-goto beforeRunShift
-
-:runPrintCP
-REM USAGE: print the classpath
-echo %CLASSPATH%
-goto beforeRunShift
-
-:runHelp
-REM USAGE: print this message
-echo -------------------------------------------------------------------------------------------
-echo -run:option where option can be the following.
-echo debug : Prints classpath and command before running it
-echo jpda : Adds remote debugging info using JPDA_OPTS. Use JPDA_TRANSPORT and JPDA_ADDRESS to
-echo customize, JPDA_OPTS to override
-echo external-classpath : Valid values are: ignore, first, last and only.
-echo print-classpath : Prints classpath before running command
-echo help : Prints this message
-echo --------------------------------------------------------------------------------------------
-goto end
-
-REM end parsing -run arguments
-:endRunArgs
-
-set JAVA_VM=-server
-set JAVA_MEM=-Xmx1024m
-set JAVA_GC=-XX:+UseConcMarkSweepGC -XX:+HeapDumpOnOutOfMemoryError
-
-REM Use QPID_JAVA_GC if set
-if "%QPID_JAVA_GC%" == "" goto noQpidJavaGC
-set JAVA_GC=%QPID_JAVA_GC%
-echo Using QPID_JAVA_GC setting: %QPID_JAVA_GC%
-goto afteQpidJavaGC
-
-:noQPidJavaGC
-echo Info: QPID_JAVA_GC not set. Defaulting to JAVA_GC %JAVA_GC%
-:afterQpidJavaGC
-
-REM Use QPID_JAVA_MEM if set
-if "%QPID_JAVA_MEM%" == "" goto noQpidJavaMem
-set JAVA_MEM=%QPID_JAVA_MEM%
-echo Using QPID_JAVA_MEM setting: %QPID_JAVA_MEM%
-goto afterQpidJavaMem
-
-:noQpidJavaMem
-echo Info: QPID_JAVA_MEM not set. Defaulting to JAVA_MEM %JAVA_MEM%
-:afterQpidJavaMem
-
-
-rem QPID_OPTS intended to hold any -D props for use
-rem user must enclose any value for QPID_OPTS in double quotes
-:runCommand
-set MODULE_JARS=%QPID_MODULE_JARS%
-set COMMAND="%JAVA_HOME%\bin\java" %JAVA_VM% %JAVA_MEM% %JAVA_GC% %QPID_OPTS% %SYSTEM_PROPS% -cp "%CLASSPATH%;%MODULE_JARS%" org.apache.qpid.server.Main %QPID_ARGS%
-
-if "%debug%" == "true" echo %CLASSPATH%;%LAUNCH_JAR%;%MODULE_JARS%
-if "%debug%" == "true" echo %COMMAND%
-%COMMAND%
-
-:end
diff --git a/java/broker/bin/qpid.stop b/java/broker/bin/qpid.stop
deleted file mode 100755
index 316f8dff46..0000000000
--- a/java/broker/bin/qpid.stop
+++ /dev/null
@@ -1,178 +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.
-#
-
-# qpid.stop Script
-#
-# Script checks for a given pid running DEFAULT_SEARCH and attempts to quit it
-#
-
-MAX_ATTEMPTS=2
-SLEEP_DELAY=1
-DEFAULT_SEARCH="PNAME=QPBRKR"
-
-if [ -z "$QPID_STOP_SEARCH" ]; then
- SEARCH=$DEFAULT_SEARCH;
-else
- SEARCH=$QPID_STOP_SEARCH;
-fi
-
-#
-# Forcably Quit the specified PID($1)
-#
-forceQuit()
-{
-kill -9 $1
-}
-
-#
-# Gracefully ask the PID($1) to quit
-#
-quit()
-{
-kill $1
-}
-
-#
-# grep for the session ID ($1) and return 0 for successful quit and 1 for process alive
-#
-lookup_pid()
-{
-result=`ps -e | grep $1 | wc -l`
-}
-
-#
-# grep ps for all instances of $SEARCH for the current user and collect PIDs
-#
-lookup_all_pids()
-{
-pids=`pgrep -f -U $USER $SEARCH`
-result_all=`echo -n $pids | wc -w`
-}
-
-#
-# check that the PID passed in is for a Qpid broker owned by this user and alive
-#
-validate_pid()
-{
-result=`pgrep -fl $SEARCH | grep $1 | wc -l`
-}
-
-#
-# Show the PS output for given set of pids
-#
-showPids()
-{
-ps -o user,pid,args -p $pids
-}
-
-#
-# Sleep and then check then lookup the PID($1) to ensure it has quit
-#
-check()
-{
-echo "Waiting $SLEEP_DELAY second for $1 to exit"
-sleep $SLEEP_DELAY
-lookup_pid $1
-}
-
-#
-# Verify the PID($1) is available
-#
-verifyPid()
-{
-validate_pid $1
-if [[ $[$result] == 1 ]] ; then
- brokerspid=$1
-else
- echo "Unable to locate Qpid Broker Process with PID $1. Check PID and try again."
- exit -1
-fi
-}
-
-#
-# Stops all Qpid brokers for current user
-#
-qpid_stopall_brokers()
-{
-for pid in $pids ; do
- lookup_pid $pid;
- brokerspid=$pid;
- stop_broker $pid;
-done
-}
-
-#
-# Stops Qpid broker with brokerspid id
-#
-stop_broker()
-{
-# Attempt to quit the process MAX_ATTEMPTS Times
-attempt=0
-while [[ $[$result] > 0 && $[$attempt] < $[$MAX_ATTEMPTS] ]] ; do
- quit $brokerspid
- check $brokerspid
- attempt=$[$attempt + 1]
-done
-
-# Check that it has quit
-if [[ $[$result] == 0 ]] ; then
- echo "Process quit"
-else
-
- attempt=0
- # Now attempt to force quit the process
- while [[ $[$result] > 0 && $[$attempt] < $[$MAX_ATTEMPTS] ]] ; do
- forceQuit $brokerspid
- check $brokerspid
- attempt=$[$attempt + 1]
- done
-
- # Output final status
- if [[ $[$result] > 0 && $[$attempt] == $[$MAX_ATTEMPTS] ]] ; then
- echo "Stopped trying to kill process: $brokerspid"
- echo "Attempted to stop $attempt times"
- else
- echo "Done "
- fi
-fi
-
-}
-
-#
-# Main Run
-#
-
-# Check if we are killing all qpid pids or just one.
-# Now uses local function qpid_stopall_brokers
-if [[ $# == 0 ]] ; then
- lookup_all_pids
- if [[ $[$result_all] > 0 ]] ; then
- echo "Killing All Qpid Brokers for user: '$USER'"
- qpid_stopall_brokers
- else
- echo "No Qpid Brokers found running for user: " $USER
- fi
- exit $result
-else
- verifyPid $1
- stop_broker
- exit $result
-fi
-
diff --git a/java/broker/bin/qpid.stopall b/java/broker/bin/qpid.stopall
deleted file mode 100755
index b0ad506629..0000000000
--- a/java/broker/bin/qpid.stopall
+++ /dev/null
@@ -1,27 +0,0 @@
-#!/bin/bash
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-#
-
-# qpid.stopall script
-#
-# Script attempts to stop all PROGRAMs running under the current user
-# Utilises qpid.stop to perform the actual stopping
-#
-
-qpid.stop $*
diff --git a/java/broker/build.xml b/java/broker/build.xml
deleted file mode 100644
index edd71effaa..0000000000
--- a/java/broker/build.xml
+++ /dev/null
@@ -1,83 +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.
- -
- -->
-<project name="AMQ Broker" default="build">
-
- <property name="module.depends" value="management/common common"/>
- <property name="module.test.depends" value="common/test" />
- <property name="module.main" value="org.apache.qpid.server.Main"/>
-
- <import file="../module.xml"/>
-
- <property name="output.dir" value="${module.precompiled}/org/apache/qpid/server/filter/jms/selector"/>
-
- <property name="qmf.input.file" value="${project.root}/../specs/management-schema.xml"/>
- <property name="qmf.xsl.file" value="${project.root}/broker/src/xsl/qmf.xsl"/>
- <property name="qmf.output.dir" value="${module.precompiled}/org/apache/qpid/qmf/schema"/>
- <property name="qmf.output.file" value="BrokerSchema.java"/>
-
-
- <target name="precompile" depends="gen_logging,gen_qmf">
- <mkdir dir="${output.dir}"/>
- <!-- Compile Selcector Code -->
- <javacc target="src/main/grammar/SelectorParser.jj"
- outputdirectory="${output.dir}"
- javacchome="${project.root}/lib"/>
- </target>
-
-
- <target name="check_qmf_deps">
- <uptodate property="gen_qmf.notRequired" targetfile="${qmf.output.dir}/${qmf.output.file}">
- <srcfiles file="${qmf.input.file}"/>
- <srcfiles file="${qmf.xsl.file}"/>
- </uptodate>
- </target>
-
- <target name="gen_qmf" depends="check_qmf_deps" unless="gen_qmf.notRequired">
- <xslt in="${qmf.input.file}" out="${qmf.output.dir}/${qmf.output.file}" style="${qmf.xsl.file}"/>
- </target>
-
- <target name="copy-etc-release" if="module.etc.exists" description="copy etc directory if it exists to build tree">
- <copy todir="${module.release}/etc" failonerror="false" flatten="true">
- <fileset dir="${module.etc}" excludes="*.conf,*.jpp"/>
- </copy>
- </target>
-
- <target name="copy-bin-release" description="copy dependencies into module release">
- <copy todir="${module.release}/bin" failonerror="true">
- <fileset dir="${module.bin}"/>
- </copy>
- <copy todir="${module.release}/bin" failonerror="true" flatten="true">
- <fileset dir="${basedir}/../common/bin"/>
- </copy>
- <chmod dir="${module.release}/bin" perm="ugo+rx" includes="**/*"/>
- <fixcrlf srcdir="${module.release}/bin" fixlast="true" eol="unix"/>
- <fixcrlf srcdir="${module.release}/bin" fixlast="true" eol="dos" includes="*.bat"/>
- </target>
-
- <target name="release-bin-other" description="copy broker-plugins into module release">
- <copy todir="${module.release}/lib/plugins" failonerror="true">
- <fileset dir="${build.lib}/plugins"/>
- </copy>
- </target>
-
- <target name="release-bin" depends="release-bin-tasks"/>
-
-</project>
diff --git a/java/broker/etc/access b/java/broker/etc/access
deleted file mode 100644
index 58b7443fa9..0000000000
--- a/java/broker/etc/access
+++ /dev/null
@@ -1,19 +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.
-
-guest:localhost(rw),test(rw) \ No newline at end of file
diff --git a/java/broker/etc/config.xml b/java/broker/etc/config.xml
deleted file mode 100644
index ec386ab669..0000000000
--- a/java/broker/etc/config.xml
+++ /dev/null
@@ -1,109 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-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.
- -
- -->
-<broker>
- <prefix>${QPID_HOME}</prefix>
- <work>${QPID_WORK}</work>
- <conf>${prefix}/etc</conf>
-
- <plugin-directory>${QPID_HOME}/lib/plugins</plugin-directory>
- <cache-directory>${QPID_WORK}/cache</cache-directory>
-
- <connector>
- <!-- To enable SSL edit the keystorePath and keystorePassword
- and set enabled to true.
- To disasble Non-SSL port set sslOnly to true -->
- <ssl>
- <enabled>false</enabled>
- <sslOnly>false</sslOnly>
- <keystorePath>/path/to/keystore.ks</keystorePath>
- <keystorePassword>keystorepass</keystorePassword>
- </ssl>
- <qpidnio>false</qpidnio>
- <protectio>
- <enabled>false</enabled>
- <readBufferLimitSize>262144</readBufferLimitSize>
- <writeBufferLimitSize>262144</writeBufferLimitSize>
- </protectio>
- <transport>nio</transport>
- <port>5672</port>
- <sslport>8672</sslport>
- <socketReceiveBuffer>32768</socketReceiveBuffer>
- <socketSendBuffer>32768</socketSendBuffer>
- </connector>
- <management>
- <enabled>true</enabled>
- <jmxport>8999</jmxport>
- <ssl>
- <enabled>false</enabled>
- <!-- Update below path to your keystore location, or run the bin/create-example-ssl-stores(.sh|.bat)
- script from within the etc/ folder to generate an example store with self-signed cert -->
- <keyStorePath>${conf}/qpid.keystore</keyStorePath>
- <keyStorePassword>password</keyStorePassword>
- </ssl>
- </management>
- <advanced>
- <filterchain enableExecutorPool="true"/>
- <framesize>65535</framesize>
- <compressBufferOnQueue>false</compressBufferOnQueue>
- <enableJMSXUserID>false</enableJMSXUserID>
- <locale>en_US</locale>
- </advanced>
-
- <security>
- <principal-databases>
- <!-- Example use of Base64 encoded MD5 hashes for authentication via CRAM-MD5-Hashed -->
- <principal-database>
- <name>passwordfile</name>
- <class>org.apache.qpid.server.security.auth.database.PlainPasswordFilePrincipalDatabase</class>
- <attributes>
- <attribute>
- <name>passwordFile</name>
- <value>${conf}/passwd</value>
- </attribute>
- </attributes>
- </principal-database>
- </principal-databases>
-
- <allow-all />
-
- <msg-auth>false</msg-auth>
-
- <jmx>
- <principal-database>passwordfile</principal-database>
- </jmx>
- </security>
-
- <virtualhosts>${conf}/virtualhosts.xml</virtualhosts>
-
- <heartbeat>
- <delay>0</delay>
- <timeoutFactor>2.0</timeoutFactor>
- </heartbeat>
- <queue>
- <auto_register>true</auto_register>
- </queue>
-
- <status-updates>ON</status-updates>
-
-</broker>
-
-
diff --git a/java/broker/etc/debug.log4j.xml b/java/broker/etc/debug.log4j.xml
deleted file mode 100644
index fc0bd9f34f..0000000000
--- a/java/broker/etc/debug.log4j.xml
+++ /dev/null
@@ -1,114 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- -
- - Licensed to the Apache Software Foundation (ASF) under one
- - or more contributor license agreements. See the NOTICE file
- - distributed with this work for additional information
- - regarding copyright ownership. The ASF licenses this file
- - to you under the Apache License, Version 2.0 (the
- - "License"); you may not use this file except in compliance
- - with the License. You may obtain a copy of the License at
- -
- - http://www.apache.org/licenses/LICENSE-2.0
- -
- - Unless required by applicable law or agreed to in writing,
- - software distributed under the License is distributed on an
- - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- - KIND, either express or implied. See the License for the
- - specific language governing permissions and limitations
- - under the License.
- -
- --><!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
-
-<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="null" threshold="null">
- <appender class="org.apache.log4j.QpidCompositeRollingAppender" name="ArchivingFileAppender">
- <!-- Ensure that logs allways have the dateFormat set-->
- <param name="StaticLogFileName" value="false"/>
- <param name="File" value="${QPID_WORK}/log/${logprefix}qpid${logsuffix}.log"/>
- <param name="Append" value="false"/>
- <!-- Change the direction so newer files have bigger numbers -->
- <!-- So log.1 is written then log.2 etc This prevents a lot of file renames at log rollover -->
- <param name="CountDirection" value="1"/>
- <!-- Use default 10MB -->
- <!--param name="MaxFileSize" value="100000"/-->
- <param name="DatePattern" value="'.'yyyy-MM-dd-HH-mm"/>
- <!-- Unlimited number of backups -->
- <param name="MaxSizeRollBackups" value="-1"/>
- <!-- Compress(gzip) the backup files-->
- <param name="CompressBackupFiles" value="true"/>
- <!-- Compress the backup files using a second thread -->
- <param name="CompressAsync" value="true"/>
- <!-- Start at zero numbered files-->
- <param name="ZeroBased" value="true"/>
- <!-- Backup Location -->
- <param name="backupFilesToPath" value="${QPID_WORK}/backup/log"/>
-
- <layout class="org.apache.log4j.PatternLayout">
- <param name="ConversionPattern" value="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/>
- </layout>
- </appender>
-
- <appender class="org.apache.log4j.FileAppender" name="FileAppender">
- <param name="File" value="${QPID_WORK}/log/${logprefix}qpid${logsuffix}.log"/>
- <param name="Append" value="false"/>
-
- <layout class="org.apache.log4j.PatternLayout">
- <param name="ConversionPattern" value="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/>
- </layout>
- </appender>
-
- <appender class="org.apache.log4j.FileAppender" name="AlertFile">
- <param name="File" value="${QPID_WORK}/log/alert.log"/>
- <param name="Append" value="false"/>
-
- <layout class="org.apache.log4j.PatternLayout">
- <param name="ConversionPattern" value="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/>
- </layout>
- </appender>
-
- <appender class="org.apache.log4j.ConsoleAppender" name="STDOUT">
-
- <layout class="org.apache.log4j.PatternLayout">
- <param name="ConversionPattern" value="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/>
- </layout>
- </appender>
-
- <category additivity="true" name="Qpid.Broker">
- <priority value="debug"/>
- <appender-ref ref="AlertFile"/>
- <!--appender-ref ref="STDOUT"/-->
- </category>
-
-
- <category additivity="true" name="org.apache.qpid.server.queue.AMQQueueMBean">
- <priority value="info"/>
- <appender-ref ref="AlertFile"/>
- </category>
-
-
- <!-- Provide warnings to standard output -->
- <!--category additivity="true" name="org.apache.qpid">
- <priority value="warn"/>
- <appender-ref ref="STDOUT"/>
- </category-->
-
-
- <!-- Additional level settings for debugging -->
- <!-- Each class in the Broker is a category that can have its logging level adjusted. -->
- <!-- This will provide more details if available about that classes processing. -->
- <!--category additivity="true" name="org.apache.qpid.server.txn">
- <priority value="debug"/>
- </category>-->
-
- <!--<category additivity="true" name="org.apache.qpid.server.store">
- <priority value="debug"/>
- </category-->
-
- <!-- Log all info events to file -->
- <root>
- <priority value="debug"/>
- <appender-ref ref="STDOUT"/>
- <!--appender-ref ref="FileAppender"/-->
- </root>
-
-</log4j:configuration>
diff --git a/java/broker/etc/log4j.xml b/java/broker/etc/log4j.xml
deleted file mode 100644
index 7dbb1bc87d..0000000000
--- a/java/broker/etc/log4j.xml
+++ /dev/null
@@ -1,125 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- -
- - Licensed to the Apache Software Foundation (ASF) under one
- - or more contributor license agreements. See the NOTICE file
- - distributed with this work for additional information
- - regarding copyright ownership. The ASF licenses this file
- - to you under the Apache License, Version 2.0 (the
- - "License"); you may not use this file except in compliance
- - with the License. You may obtain a copy of the License at
- -
- - http://www.apache.org/licenses/LICENSE-2.0
- -
- - Unless required by applicable law or agreed to in writing,
- - software distributed under the License is distributed on an
- - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- - KIND, either express or implied. See the License for the
- - specific language governing permissions and limitations
- - under the License.
- -
- --><!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
-
-<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="null" threshold="null">
- <appender class="org.apache.log4j.QpidCompositeRollingAppender" name="ArchivingFileAppender">
- <!-- Ensure that logs always have the DatePattern appended to the filename.
- DEFAULT IF NOT CONFIGURED: true -->
- <param name="StaticLogFileName" value="true"/>
- <param name="file" value="${QPID_WORK}/log/${logprefix}qpid${logsuffix}.log"/>
- <!-- Style of rolling to use, by:
- File Size(1)
- Date(2)
- Both(3)
-
- When Date (or Both) is enabled then the value of DatePattern will determine
- when the new file is made. e.g. a DatePattern of "'.'yyyy-MM-dd-HH-mm"
- which includes minutes will cause a new backup file to be made every minute.
-
- DEFAULT IF NOT CONFIGURED: 3 -->
- <param name="RollingStyle" value="1"/>
- <!-- Set the count direction:
- Negative numbers mean backups are numbered <latest>, .0, .1, .2,..., .n
- 0 means backup is DatePattern stamped and followed with a Positive number
- if the DatePattern stamp clashes with other existing backups.
- Positive numbers mean backups are numbered 0, 1, 2, ..., n, <latest>
-
- DEFAULT IF NOT CONFIGURED: -1 -->
- <param name="CountDirection" value="0"/>
- <!-- Maximum File Size:
- DEFAULT IF NOT CONFIGURED: 10MB -->
- <param name="MaxFileSize" value="1MB"/>
- <!-- Date Pattern:
- DEFAULT IF NOT CONFIGURED: "'.'yyyy-MM-dd" -->
- <param name="DatePattern" value="'.'yyyy-MM-dd-HH-mm"/>
- <!-- Maximum number of backup files:
- 0 means no backups
- -1 means infinite backups
-
- DEFAULT IF NOT CONFIGURED: 0 -->
- <param name="MaxSizeRollBackups" value="-1"/>
- <!-- Compress(gzip) the backup files to the backup location:
- DEFAULT IF NOT CONFIGURED: FALSE -->
- <param name="CompressBackupFiles" value="true"/>
- <!-- Compress the backup files using a second thread:
- DEFAULT IF NOT CONFIGURED: FALSE -->
- <param name="CompressAsync" value="true"/>
- <!-- Backup Location:
- DEFAULT IF NOT CONFIGURED: same dir as log file -->
- <param name="backupFilesToPath" value="${QPID_WORK}/backup/log"/>
-
- <layout class="org.apache.log4j.PatternLayout">
- <param name="ConversionPattern" value="%d %-5p [%t] (%F:%L) - %m%n"/>
- </layout>
- </appender>
-
- <appender class="org.apache.log4j.FileAppender" name="FileAppender">
- <param name="File" value="${QPID_WORK}/log/${logprefix}qpid${logsuffix}.log"/>
- <param name="Append" value="false"/>
-
- <layout class="org.apache.log4j.PatternLayout">
- <param name="ConversionPattern" value="%d %-5p [%t] (%F:%L) - %m%n"/>
- </layout>
- </appender>
-
- <appender class="org.apache.log4j.ConsoleAppender" name="STDOUT">
- <layout class="org.apache.log4j.PatternLayout">
- <param name="ConversionPattern" value="%d %-5p [%t] (%F:%L) - %m%n"/>
- </layout>
- </appender>
-
- <category additivity="true" name="org.apache.qpid.server.queue.AMQQueueMBean">
- <priority value="info"/>
- </category>
-
- <!-- Provide warnings to standard output -->
- <category additivity="true" name="org.apache.qpid">
- <priority value="warn"/>
- </category>
-
- <!-- Enable info messages for the status-logging hierarchy -->
- <logger additivity="true" name="qpid.message">
- <level value="info"/>
- </logger>
-
-
-
- <!-- Examples of additional logging settings -->
- <!-- Used to generate extra debug. See debug.log4j.xml -->
-
- <!--<category additivity="true" name="org.apache.qpid.server.store">
- <priority value="debug"/>
- </category-->
-
- <!-- Set the commons logging that the XML parser uses to WARN, it is very chatty at debug -->
- <logger name="org.apache.commons">
- <level value="WARN"/>
- </logger>
-
- <!-- Log all info events to file -->
- <root>
- <priority value="info"/>
- <appender-ref ref="FileAppender"/>
- <!--appender-ref ref="ArchivingFileAppender"/-->
- </root>
-
-</log4j:configuration>
diff --git a/java/broker/etc/md5passwd b/java/broker/etc/md5passwd
deleted file mode 100644
index 6a149919de..0000000000
--- a/java/broker/etc/md5passwd
+++ /dev/null
@@ -1,21 +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.
-#
-guest:CE4DQ6BIb/BVMN9scFyLtA==
-admin:ISMvKXpXpadDiUoOSoAfww==
-user:aBzonUodYLhwSa8s9A10sA==
diff --git a/java/broker/etc/mstool-log4j.xml b/java/broker/etc/mstool-log4j.xml
deleted file mode 100644
index 8c46010e2d..0000000000
--- a/java/broker/etc/mstool-log4j.xml
+++ /dev/null
@@ -1,54 +0,0 @@
-<?xml version="1.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.
- -
- -->
-<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
-<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
-
- <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
-
- <layout class="org.apache.log4j.PatternLayout">
- <!--param name="ConversionPattern" value="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/-->
- <param name="ConversionPattern" value="%d %-5p [%t] (%F:%L) - %m%n"/>
- </layout>
- </appender>
-
- <category name="org.apache.qpid.tools">
- <priority value="info"/>
- </category>
-
- <category name="org.apache.qpid">
- <priority value="error"/>
- </category>
-
- <category name="org.apache.qpid.server.security">
- <priority value="error"/>
- </category>
-
- <category name="org.apache.qpid.server.management">
- <priority value="error"/>
- </category>
-
-
- <root>
- <priority value="info"/>
- <appender-ref ref="STDOUT"/>
- </root>
-</log4j:configuration>
diff --git a/java/broker/etc/passwd b/java/broker/etc/passwd
deleted file mode 100644
index 99f0f05c6a..0000000000
--- a/java/broker/etc/passwd
+++ /dev/null
@@ -1,23 +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.
-#
-guest:guest
-client:guest
-server:guest
-admin:admin
-
diff --git a/java/broker/etc/passwdVhost b/java/broker/etc/passwdVhost
deleted file mode 100644
index 48ce8299b6..0000000000
--- a/java/broker/etc/passwdVhost
+++ /dev/null
@@ -1,19 +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.
-#
-guest:guest:localhost,test
diff --git a/java/broker/etc/qpid-server.conf b/java/broker/etc/qpid-server.conf
deleted file mode 100644
index 8a16849b04..0000000000
--- a/java/broker/etc/qpid-server.conf
+++ /dev/null
@@ -1,25 +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.
-#
-
-QPID_LIBS=$QPID_HOME/lib/qpid-all.jar:$QPID_HOME/lib/bdbstore-launch.jar
-
-export JAVA=java \
- JAVA_VM=-server \
- JAVA_MEM=-Xmx1024m \
- CLASSPATH=$QPID_LIBS
diff --git a/java/broker/etc/qpid-server.conf.jpp b/java/broker/etc/qpid-server.conf.jpp
deleted file mode 100644
index 3ed2431ef3..0000000000
--- a/java/broker/etc/qpid-server.conf.jpp
+++ /dev/null
@@ -1,49 +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.
-#
-
-QPID_LIBS=$(build-classpath backport-util-concurrent \
- commons-beanutils \
- commons-beanutils-core \
- commons-cli \
- commons-codec \
- commons-collections \
- commons-configuration \
- commons-digester \
- commons-lang \
- commons-logging \
- commons-logging-api \
- dom4j \
- geronimo-jms-1.1-api \
- isorelax \
- jaxen \
- log4j \
- mina/core \
- mina/filter-ssl \
- mina/java5 \
- msv-msv \
- qpid-broker \
- qpid-client \
- qpid-common \
- relaxngDatatype \
- slf4j)
-
-export JAVA=java \
- JAVA_VM=-server \
- JAVA_MEM=-Xmx1024m \
- CLASSPATH=$QPID_LIBS
diff --git a/java/broker/etc/qpid.passwd b/java/broker/etc/qpid.passwd
deleted file mode 100644
index dbfb9d1923..0000000000
--- a/java/broker/etc/qpid.passwd
+++ /dev/null
@@ -1,23 +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.
-#
-guest:CE4DQ6BIb/BVMN9scFyLtA==
-admin:ISMvKXpXpadDiUoOSoAfww==
-user:CE4DQ6BIb/BVMN9scFyLtA==
-server:CE4DQ6BIb/BVMN9scFyLtA==
-client:CE4DQ6BIb/BVMN9scFyLtA==
diff --git a/java/broker/etc/virtualhosts.xml b/java/broker/etc/virtualhosts.xml
deleted file mode 100644
index 5860bfe2cb..0000000000
--- a/java/broker/etc/virtualhosts.xml
+++ /dev/null
@@ -1,162 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-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.
- -
- -->
-<virtualhosts>
- <default>test</default>
- <virtualhost>
- <name>localhost</name>
- <localhost>
- <store>
- <class>org.apache.qpid.server.store.MemoryMessageStore
- </class>
- </store>
-
- <housekeeping>
- <threadCount>2</threadCount>
- <expiredMessageCheckPeriod>20000</expiredMessageCheckPeriod>
- </housekeeping>
-
- <exchanges>
- <exchange>
- <type>direct</type>
- <name>test.direct</name>
- <durable>true</durable>
- </exchange>
- <exchange>
- <type>topic</type>
- <name>test.topic</name>
- </exchange>
- </exchanges>
- <queues>
- <exchange>amq.direct</exchange>
- <maximumQueueDepth>4235264</maximumQueueDepth>
- <!-- 4Mb -->
- <maximumMessageSize>2117632</maximumMessageSize>
- <!-- 2Mb -->
- <maximumMessageAge>600000</maximumMessageAge>
- <!-- 10 mins -->
- <maximumMessageCount>50</maximumMessageCount>
- <!-- 50 messages -->
-
- <queue>
- <name>queue</name>
- </queue>
- <queue>
- <name>ping</name>
- </queue>
- <queue>
- <name>test-queue</name>
- <test-queue>
- <exchange>test.direct</exchange>
- <durable>true</durable>
- </test-queue>
- </queue>
- <queue>
- <name>test-ping</name>
- <test-ping>
- <exchange>test.direct</exchange>
- </test-ping>
- </queue>
-
- </queues>
- </localhost>
- </virtualhost>
-
-
- <virtualhost>
- <name>development</name>
- <development>
- <store>
- <class>org.apache.qpid.server.store.MemoryMessageStore
- </class>
- </store>
-
- <queues>
- <minimumAlertRepeatGap>30000</minimumAlertRepeatGap>
- <maximumMessageCount>50</maximumMessageCount>
- <queue>
- <name>queue</name>
- <queue>
- <exchange>amq.direct</exchange>
- <maximumQueueDepth>4235264</maximumQueueDepth>
- <!-- 4Mb -->
- <maximumMessageSize>2117632</maximumMessageSize>
- <!-- 2Mb -->
- <maximumMessageAge>600000</maximumMessageAge>
- <!-- 10 mins -->
- </queue>
- </queue>
- <queue>
- <name>ping</name>
- <ping>
- <exchange>amq.direct</exchange>
- <maximumQueueDepth>4235264</maximumQueueDepth>
- <!-- 4Mb -->
- <maximumMessageSize>2117632</maximumMessageSize>
- <!-- 2Mb -->
- <maximumMessageAge>600000</maximumMessageAge>
- <!-- 10 mins -->
- </ping>
- </queue>
- </queues>
- </development>
- </virtualhost>
- <virtualhost>
- <name>test</name>
- <test>
- <store>
- <class>org.apache.qpid.server.store.MemoryMessageStore
- </class>
- </store>
-
- <queues>
- <minimumAlertRepeatGap>30000</minimumAlertRepeatGap>
- <maximumMessageCount>50</maximumMessageCount>
- <queue>
- <name>queue</name>
- <queue>
- <exchange>amq.direct</exchange>
- <maximumQueueDepth>4235264</maximumQueueDepth>
- <!-- 4Mb -->
- <maximumMessageSize>2117632</maximumMessageSize>
- <!-- 2Mb -->
- <maximumMessageAge>600000</maximumMessageAge>
- <!-- 10 mins -->
- </queue>
- </queue>
- <queue>
- <name>ping</name>
- <ping>
- <exchange>amq.direct</exchange>
- <maximumQueueDepth>4235264</maximumQueueDepth>
- <!-- 4Mb -->
- <maximumMessageSize>2117632</maximumMessageSize>
- <!-- 2Mb -->
- <maximumMessageAge>600000</maximumMessageAge>
- <!-- 10 mins -->
- </ping>
- </queue>
- </queues>
- </test>
- </virtualhost>
-</virtualhosts>
-
-
diff --git a/java/broker/python-test.xml b/java/broker/python-test.xml
deleted file mode 100755
index 5c263e3169..0000000000
--- a/java/broker/python-test.xml
+++ /dev/null
@@ -1,56 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-Licensed to the Apache Software Foundation (ASF) under one
-or more contributor license agreements. See the NOTICE file
-distributed with this work for additional information
-regarding copyright ownership. The ASF licenses this file
-to you under the Apache License, Version 2.0 (the
-"License"); you may not use this file except in compliance
-with the License. You may obtain a copy of the License at
-
-http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing,
-software distributed under the License is distributed on an
-"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-KIND, either express or implied. See the License for the
-specific language governing permissions and limitations
-under the License.
--->
-
-<!-- ====================================================================== -->
-<!-- Ant build file (http://ant.apache.org/) for Ant 1.6.2 or above. -->
-<!-- ====================================================================== -->
-
-<project basedir="." default="default">
-
- <target name="default" >
- <echo message="Used via maven to run python tests."/>
- </target>
-
- <dirname property="broker.dir" file="${ant.file.python-test}"/>
-
- <property name="pythondir" value="${broker.dir}/../../python"/>
-
- <target name="run-tests" unless="skip-python-tests">
-
- <echo message="Starting Broker with command"/>
-
- <java classname="org.apache.qpid.server.RunBrokerWithCommand"
- fork="true"
- dir="${pythondir}"
- failonerror="true"
- >
- <arg value="${command}"/>
- <arg value="-p"/>
- <arg value="2110"/>
- <arg value="-m"/>
- <arg value="2111"/>
-
- <classpath refid="maven.test.classpath"/>
- <sysproperty key="QPID_HOME" value="${broker.dir}"/>
- <sysproperty key="QPID_WORK" value="${broker.dir}${file.separator}target"/>
- </java>
-
- </target>
-</project>
diff --git a/java/broker/scripts/resetAlerting.sh b/java/broker/scripts/resetAlerting.sh
deleted file mode 100644
index 18e8c64cb0..0000000000
--- a/java/broker/scripts/resetAlerting.sh
+++ /dev/null
@@ -1,116 +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.
-#
-#
-
-#
-# Alerting Rest Scripts to renabled the alerts on the queue.
-#
-# Defaults to Localhost broker
-#
-
-if [ -z "$QPID_ALERT_HOME" ]; then
- export QPID_ALERT_HOME=$(dirname $(dirname $(readlink -f $0)))
- export PATH=${PATH}:${QPID_ALERT_HOME}/bin
-fi
-
-USERNAME=$1
-PASSWORD=$2
-HOSTNAME=$3
-PORT=$4
-
-CLI="$QPID_ALERT_HOME/bin/qpid-cli -h ${HOSTNAME:-localhost} -p ${PORT:-8999}"
-AUTH=
-if [ -n $USERNAME ] ; then
- if [ "$USERNAME" == "-h" ] ; then
- echo "resetAlerting.sh: [<username> <password> [<hostname> [<port>]]]"
- exit 0
- fi
- if [ -n $PASSWORD ] ; then
- AUTH="-u $USERNAME -w $PASSWORD"
- else
- echo "Password must be specified with username"
- fi
-fi
-
-
-OUTPUT=0
-
-runCommand()
-{
- RET=`$CLI $1 $AUTH`
-}
-
-resetQueue()
-{
- vhost=$1
- queue=$2
- runCommand "get -o queue -v $vhost -n $queue -a MaximumQueueDepth"
- rawQDepth=$RET
- # Note that MaxQueueDepth is returned as Kb but set as b!
- queueDepth=$[ $rawQDepth * 1024 ]
- runCommand "get -o queue -v $vhost -n $queue -a MaximumMessageAge"
- messageAge=$RET
- runCommand "get -o queue -v $vhost -n $queue -a MaximumMessageCount"
- messageCount=$RET
- runCommand "get -o queue -v $vhost -n $queue -a MaximumMessageSize"
- messageSize=$RET
-
- if [ $OUTPUT == 1 ] ; then
- echo Current Values:
- echo MaximumQueueDepth : $queueDepth
- echo MaximumMessageAge : $messageAge
- echo MaximumMessageCount : $messageCount
- echo MaximumMessageSize : $messageSize
- fi
-
- runCommand "set -o queue -v $vhost -n $queue -a MaximumMessageSize -s $messageSize"
- runCommand "set -o queue -v $vhost -n $queue -a MaximumMessageAge -s $messageAge"
- runCommand "set -o queue -v $vhost -n $queue -a MaximumMessageCount -s $messageCount"
- runCommand "set -o queue -v $vhost -n $queue -a MaximumQueueDepth -s $queueDepth"
-}
-
-resetVirtualHost()
-{
- vhost=$1
- ignore=0
- for queue in `$CLI list -o queue -v $vhost $AUTH |grep '|' | cut -d '|' -f 1 ` ; do
-
- if [ $ignore == 0 ] ; then
- ignore=1
- else
- resetQueue $vhost $queue
- fi
-
- done
-}
-
-VHOST=`$CLI list -o virtualhost $AUTH`
-COUNT=`echo $VHOST | grep -c VirtualHost`
-if [ $COUNT -gt 0 ] ; then
- for vhost in `echo $VHOST |grep VirtualHost|cut -d '=' -f 3` ; do
-
- echo "Resetting alert levels for $vhost";
- resetVirtualHost $vhost;
- done
- echo "Alerting levels reset"
-else
- echo $VHOST
-fi
diff --git a/java/broker/src/main/grammar/SelectorParser.jj b/java/broker/src/main/grammar/SelectorParser.jj
deleted file mode 100644
index c9e01cd01f..0000000000
--- a/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 <http://www.activemq.org/site/home.html>
- //
-
-// ----------------------------------------------------------------------------
-// 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:
-{
- <LINE_COMMENT: "--" (~["\n","\r"])* ("\n"|"\r"|"\r\n") >
-}
-
-SKIP:
-{
- <BLOCK_COMMENT: "/*" (~["*"])* "*" ("*" | (~["*","/"] (~["*"])* "*"))* "/">
-}
-
-/* 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"])* (<EXPONENT>)? // matches: 5.5 or 5. or 5.5E10 or 5.E10
- | "." (["0"-"9"])+ (<EXPONENT>)? // matches: .5 or .5E10
- | (["0"-"9"])+ <EXPONENT> // 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()
- (
- <OR> right = andExpression()
- {
- left = LogicExpression.createOR(asBooleanExpression(left), asBooleanExpression(right));
- }
- )*
- )
- {
- return left;
- }
-
-}
-
-
-Expression andExpression() :
-{
- Expression left;
- Expression right;
-}
-{
- (
- left = equalityExpression()
- (
- <AND> 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)
- <IS> <NULL>
- {
- left = ComparisonExpression.createIsNull(left);
- }
- |
- <IS> <NOT> <NULL>
- {
- 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;
- }
- <LIKE> t = stringLitteral()
- [ <ESCAPE> u = stringLitteral() ]
- {
- left = ComparisonExpression.createLike(left, t, u);
- }
- |
- LOOKAHEAD(2)
- {
- u=null;
- }
- <NOT> <LIKE> t = stringLitteral() [ <ESCAPE> u = stringLitteral() ]
- {
- left = ComparisonExpression.createNotLike(left, t, u);
- }
- |
- <BETWEEN> low = addExpression() <AND> high = addExpression()
- {
- left = ComparisonExpression.createBetween(left, low, high);
- }
- |
- LOOKAHEAD(2)
- <NOT> <BETWEEN> low = addExpression() <AND> high = addExpression()
- {
- left = ComparisonExpression.createNotBetween(left, low, high);
- }
- |
- <IN>
- "("
- t = stringLitteral()
- {
- list = new ArrayList();
- list.add( t );
- }
- (
- ","
- t = stringLitteral()
- {
- list.add( t );
- }
-
- )*
- ")"
- {
- left = ComparisonExpression.createInFilter(left, list);
- }
- |
- LOOKAHEAD(2)
- <NOT> <IN>
- "("
- 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);
- }
- |
- <NOT> left=unaryExpr()
- {
- left = UnaryExpression.createNOT( asBooleanExpression(left) );
- }
- |
- <XPATH> s=stringLitteral()
- {
- left = UnaryExpression.createXPath( s );
- }
- |
- <XQUERY> 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 = <DECIMAL_LITERAL>
- {
- left = ConstantExpression.createFromDecimal(t.image);
- }
- )
- |
- (
- t = <HEX_LITERAL>
- {
- left = ConstantExpression.createFromHex(t.image);
- }
- )
- |
- (
- t = <OCTAL_LITERAL>
- {
- left = ConstantExpression.createFromOctal(t.image);
- }
- )
- |
- (
- t = <FLOATING_POINT_LITERAL>
- {
- left = ConstantExpression.createFloat(t.image);
- }
- )
- |
- (
- <TRUE>
- {
- left = ConstantExpression.TRUE;
- }
- )
- |
- (
- <FALSE>
- {
- left = ConstantExpression.FALSE;
- }
- )
- |
- (
- <NULL>
- {
- left = ConstantExpression.NULL;
- }
- )
- )
- {
- return left;
- }
-}
-
-String stringLitteral() :
-{
- Token t;
- StringBuffer rc = new StringBuffer();
- boolean first=true;
-}
-{
- t = <STRING_LITERAL>
- {
- // 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 = <ID>
- {
- left = new PropertyExpression(t.image);
- }
- |
- t = <QUOTED_ID>
- {
- // 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/java/broker/src/main/java/log4j.properties b/java/broker/src/main/java/log4j.properties
deleted file mode 100644
index 6788c65463..0000000000
--- a/java/broker/src/main/java/log4j.properties
+++ /dev/null
@@ -1,24 +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.
-#
-log4j.rootCategory=${amqj.logging.level}, console
-
-log4j.appender.console=org.apache.log4j.ConsoleAppender
-log4j.appender.console.Threshold=all
-log4j.appender.console.layout=org.apache.log4j.PatternLayout
-log4j.appender.console.layout.ConversionPattern=%t %d %p [%c{4}] %m%n
diff --git a/java/broker/src/main/java/org/apache/log4j/QpidCompositeRollingAppender.java b/java/broker/src/main/java/org/apache/log4j/QpidCompositeRollingAppender.java
deleted file mode 100644
index 4426a7aeec..0000000000
--- a/java/broker/src/main/java/org/apache/log4j/QpidCompositeRollingAppender.java
+++ /dev/null
@@ -1,1125 +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.log4j;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.Writer;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.concurrent.ConcurrentLinkedQueue;
-import java.util.concurrent.Executor;
-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;
-
-/**
- * <p>CompositeRollingAppender combines RollingFileAppender and DailyRollingFileAppender<br> 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
- * crossed at which time it rolls all of those files as per the DailyRollingFileAppender) based on the setting for
- * <code>rollingStyle</code>.<br> <br> To use CompositeRollingAppender to roll log files as they reach a certain size
- * (like RollingFileAppender), set rollingStyle=1 (@see config.size)<br> To use CompositeRollingAppender to roll log
- * files at certain time intervals (daily for example), set rollingStyle=2 and a datePattern (@see config.time)<br> To
- * have CompositeRollingAppender roll log files at a certain size AND rename those according to time intervals, set
- * rollingStyle=3 (@see config.composite)<br>
- *
- * <p>A of few additional optional features have been added:<br> -- Attach date pattern for current log file (@see
- * staticLogFileName)<br> -- Backup number increments for newer files (@see countDirection)<br> -- Infinite number of
- * backups by file size (@see maxSizeRollBackups)<br> <br> <p>A few notes and warnings: For large or infinite number of
- * backups countDirection > 0 is highly recommended, with staticLogFileName = false if time based rolling is also used
- * -- this will reduce the number of file renamings to few or none. Changing staticLogFileName or countDirection
- * without clearing the directory could have nasty side effects. If Date/Time based rolling is enabled,
- * CompositeRollingAppender will attempt to roll existing files in the directory without a date/time tag based on the
- * last modified date of the base log files last modification.<br> <br> <p>A maximum number of backups based on
- * date/time boundries would be nice but is not yet implemented.<br>
- *
- * @author Kevin Steppe
- * @author Heinz Richter
- * @author Eirik Lygre
- * @author Ceki G&uuml;lc&uuml;
- * @author Martin Ritchie
- */
-public class QpidCompositeRollingAppender extends FileAppender
-{
- // The code assumes that the following 'time' constants are in a increasing
- // sequence.
- static final int TOP_OF_TROUBLE = -1;
- static final int TOP_OF_MINUTE = 0;
- static final int TOP_OF_HOUR = 1;
- static final int HALF_DAY = 2;
- static final int TOP_OF_DAY = 3;
- static final int TOP_OF_WEEK = 4;
- static final int TOP_OF_MONTH = 5;
-
- /** Style of rolling to use */
- static final int BY_SIZE = 1;
- static final int BY_DATE = 2;
- static final int BY_COMPOSITE = 3;
-
- // Not currently used
- static final String S_BY_SIZE = "Size";
- static final String S_BY_DATE = "Date";
- static final String S_BY_COMPOSITE = "Composite";
-
- /** The date pattern. By default, the pattern is set to "'.'yyyy-MM-dd" meaning daily rollover. */
- private String datePattern = "'.'yyyy-MM-dd";
-
- /**
- * The actual formatted filename that is currently being written to or will be the file transferred to on roll over
- * (based on staticLogFileName).
- */
- private String scheduledFilename = null;
-
- /** The timestamp when we shall next recompute the filename. */
- private long nextCheck = System.currentTimeMillis() - 1;
-
- /** Holds date of last roll over */
- Date now = new Date();
-
- SimpleDateFormat sdf;
-
- /** Helper class to determine next rollover time */
- RollingCalendar rc = new RollingCalendar();
-
- /** The default maximum file size is 10MB. */
- protected 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;
-
- /** not yet implemented */
- protected int maxTimeRollBackups = -1;
- protected 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;
-
- /** 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;
-
- /**
- * 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;
-
- /** FileName provided in configuration. Used for rolling properly */
- protected String baseFileName;
-
- /** Do we want to .gz our backup files. */
- protected boolean compress = false;
-
- /** Do we want to use a second thread when compressing our backup files. */
- protected boolean compressAsync = false;
-
- /** Do we want to start numbering files at zero. */
- protected boolean zeroBased = false;
-
- /** Path provided in configuration. Used for moving backup files to */
- protected String backupFilesToPath = null;
- private final ConcurrentLinkedQueue<CompressJob> _compress = new ConcurrentLinkedQueue<CompressJob>();
- private AtomicBoolean _compressing = new AtomicBoolean(false);
- private static final String COMPRESS_EXTENSION = ".gz";
-
- /** The default constructor does nothing. */
- public QpidCompositeRollingAppender()
- { }
-
- /**
- * Instantiate a <code>CompositeRollingAppender</code> and open the file designated by <code>filename</code>. The
- * opened filename will become the ouput destination for this appender.
- */
- public QpidCompositeRollingAppender(Layout layout, String filename, String datePattern) throws IOException
- {
- this(layout, filename, datePattern, true);
- }
-
- /**
- * Instantiate a CompositeRollingAppender and open the file designated by <code>filename</code>. The opened filename
- * will become the ouput destination for this appender.
- *
- * <p>If the <code>append</code> parameter is true, the file will be appended to. Otherwise, the file desginated by
- * <code>filename</code> will be truncated before being opened.
- */
- public QpidCompositeRollingAppender(Layout layout, String filename, boolean append) throws IOException
- {
- super(layout, filename, append);
- }
-
- /**
- * Instantiate a CompositeRollingAppender and open the file designated by <code>filename</code>. The opened filename
- * will become the ouput destination for this appender.
- */
- public QpidCompositeRollingAppender(Layout layout, String filename, String datePattern, boolean append)
- throws IOException
- {
- super(layout, filename, append);
- this.datePattern = datePattern;
- activateOptions();
- }
-
- /**
- * Instantiate a CompositeRollingAppender and open the file designated by <code>filename</code>. The opened filename
- * will become the output destination for this appender.
- *
- * <p>The file will be appended to. DatePattern is default.
- */
- public QpidCompositeRollingAppender(Layout layout, String filename) throws IOException
- {
- super(layout, filename);
- }
-
- /**
- * The <b>DatePattern</b> takes a string in the same format as expected by {@link java.text.SimpleDateFormat}. This
- * options determines the rollover schedule.
- */
- public void setDatePattern(String pattern)
- {
- datePattern = pattern;
- }
-
- /** Returns the value of the <b>DatePattern</b> option. */
- public String getDatePattern()
- {
- return datePattern;
- }
-
- /** Returns the value of the <b>maxSizeRollBackups</b> option. */
- public int getMaxSizeRollBackups()
- {
- return maxSizeRollBackups;
- }
-
- /**
- * Get the maximum size that the output file is allowed to reach before being rolled over to backup files.
- *
- * @since 1.1
- */
- public long getMaximumFileSize()
- {
- return maxFileSize;
- }
-
- /**
- * <p>Set the maximum number of backup files to keep around based on file size.
- *
- * <p>The <b>MaxSizeRollBackups</b> option determines how many backup files are kept before the oldest is erased.
- * This option takes an integer value. If set to zero, then there will be no backup files and the log file will be
- * truncated when it reaches <code>MaxFileSize</code>. If a negative number is supplied then no deletions will be
- * made. Note that this could result in very slow performance as a large number of files are rolled over unless
- * {@link #setCountDirection} up is used.
- *
- * <p>The maximum applys to -each- time based group of files and -not- the total. Using a daily roll the maximum
- * total files would be (#days run) * (maxSizeRollBackups)
- */
- public void setMaxSizeRollBackups(int maxBackups)
- {
- maxSizeRollBackups = maxBackups;
- }
-
- /**
- * Set the maximum size that the output file is allowed to reach before being rolled over to backup files.
- *
- * <p>This method is equivalent to {@link #setMaxFileSize} except that it is required for differentiating the setter
- * taking a <code>long</code> argument from the setter taking a <code>String</code> argument by the JavaBeans {@link
- * java.beans.Introspector Introspector}.
- *
- * @see #setMaxFileSize(String)
- */
- public void setMaxFileSize(long maxFileSize)
- {
- this.maxFileSize = maxFileSize;
- }
-
- /**
- * Set the maximum size that the output file is allowed to reach before being rolled over to backup files.
- *
- * <p>This method is equivalent to {@link #setMaxFileSize} except that it is required for differentiating the setter
- * taking a <code>long</code> argument from the setter taking a <code>String</code> argument by the JavaBeans {@link
- * java.beans.Introspector Introspector}.
- *
- * @see #setMaxFileSize(String)
- */
- public void setMaximumFileSize(long maxFileSize)
- {
- this.maxFileSize = maxFileSize;
- }
-
- /**
- * Set the maximum size that the output file is allowed to reach before being rolled over to backup files.
- *
- * <p>In configuration files, the <b>MaxFileSize</b> option takes an long integer in the range 0 - 2^63. You can
- * specify the value with the suffixes "KB", "MB" or "GB" so that the integer is interpreted being expressed
- * respectively in kilobytes, megabytes or gigabytes. For example, the value "10KB" will be interpreted as 10240.
- */
- public void setMaxFileSize(String value)
- {
- maxFileSize = OptionConverter.toFileSize(value, maxFileSize + 1);
- }
-
- protected void setQWForFiles(Writer writer)
- {
- qw = new CountingQuietWriter(writer, errorHandler);
- }
-
- // Taken verbatum from DailyRollingFileAppender
- int computeCheckPeriod()
- {
- RollingCalendar c = new RollingCalendar();
- // set sate to 1970-01-01 00:00:00 GMT
- Date epoch = new Date(0);
- if (datePattern != null)
- {
- for (int i = TOP_OF_MINUTE; i <= TOP_OF_MONTH; i++)
- {
- String r0 = sdf.format(epoch);
- 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;
- }
- }
- }
-
- return TOP_OF_TROUBLE; // Deliberately head for trouble...
- }
-
- // Now for the new stuff
- /**
- * Handles append time behavior for CompositeRollingAppender. This checks if a roll over either by date (checked
- * first) or time (checked second) is need and then appends to the file last.
- */
- protected void subAppend(LoggingEvent event)
- {
-
- if (rollDate)
- {
- long n = System.currentTimeMillis();
- if (n >= nextCheck)
- {
- now.setTime(n);
- nextCheck = rc.getNextCheckMillis(now);
-
- rollOverTime();
- }
- }
-
- if (rollSize)
- {
- if ((fileName != null) && (((CountingQuietWriter) qw).getCount() >= maxFileSize))
- {
- rollOverSize();
- }
- }
-
- super.subAppend(event);
- }
-
- public void setFile(String file)
- {
- baseFileName = file.trim();
- fileName = file.trim();
- }
-
- /**
- * Creates and opens the file for logging. If <code>staticLogFileName</code> is false then the fully qualified name
- * is determined and used.
- */
- public synchronized void setFile(String fileName, boolean append) throws IOException
- {
- if (!staticLogFileName)
- {
- scheduledFilename = fileName = fileName.trim() + sdf.format(now);
- }
-
- super.setFile(fileName, append, bufferedIO, bufferSize);
-
- if (append)
- {
- File f = new File(fileName);
- ((CountingQuietWriter) qw).setCount(f.length());
- }
- }
-
- public int getCountDirection()
- {
- return countDirection;
- }
-
- public void setCountDirection(int direction)
- {
- countDirection = direction;
- }
-
- public int getRollingStyle()
- {
- return rollingStyle;
- }
-
- public void setRollingStyle(int style)
- {
- rollingStyle = style;
- switch (rollingStyle)
- {
-
- case BY_SIZE:
- rollDate = false;
- rollSize = true;
- break;
-
- case BY_DATE:
- rollDate = true;
- rollSize = false;
- break;
-
- case BY_COMPOSITE:
- rollDate = true;
- rollSize = true;
- break;
-
- default:
- errorHandler.error("Invalid rolling Style, use 1 (by size only), 2 (by date only) or 3 (both)");
- }
- }
-
- /*
- 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;
- }
-
- public void setStaticLogFileName(boolean s)
- {
- staticLogFileName = s;
- }
-
- public void setStaticLogFileName(String value)
- {
- setStaticLogFileName(OptionConverter.toBoolean(value, true));
- }
-
- public boolean getCompressBackupFiles()
- {
- return compress;
- }
-
- public void setCompressBackupFiles(boolean c)
- {
- compress = c;
- }
-
- public boolean getCompressAsync()
- {
- return compressAsync;
- }
-
- public void setCompressAsync(boolean c)
- {
- compressAsync = c;
- if (compressAsync)
- {
- executor = Executors.newFixedThreadPool(1);
-
- compressor = new Compressor();
- }
- }
-
- public boolean getZeroBased()
- {
- return zeroBased;
- }
-
- public void setZeroBased(boolean z)
- {
- zeroBased = z;
- }
-
- public String getBackupFilesToPath()
- {
- return backupFilesToPath;
- }
-
- public void setbackupFilesToPath(String path)
- {
- File td = new File(path);
- if (!td.exists())
- {
- td.mkdirs();
- }
-
- backupFilesToPath = path;
- }
-
- /**
- * Initializes based on exisiting conditions at time of <code> activateOptions</code>. The following is done:<br>
- * <br> A) determine curSizeRollBackups<br> B) determine curTimeRollBackups (not implemented)<br> C) initiates a
- * roll over if needed for crossing a date boundary since the last run.
- */
- protected void existingInit()
- {
- curTimeRollBackups = 0;
-
- // part A starts here
- // This is now down at first log when curSizeRollBackup==0 see rollFile
- // part A ends here
-
- // part B not yet implemented
-
- // part C
- if (staticLogFileName && rollDate)
- {
- File old = new File(baseFileName);
- if (old.exists())
- {
- Date last = new Date(old.lastModified());
- if (!(sdf.format(last).equals(sdf.format(now))))
- {
- scheduledFilename = baseFileName + sdf.format(last);
- LogLog.debug("Initial roll over to: " + scheduledFilename);
- rollOverTime();
- }
- }
- }
-
- LogLog.debug("curSizeRollBackups after rollOver at: " + curSizeRollBackups);
- // part C ends here
-
- }
-
- /**
- * Sets initial conditions including date/time roll over information, first check, scheduledFilename, and calls
- * <code>existingInit</code> to initialize the current # of backups.
- */
- public void activateOptions()
- {
-
- // REMOVE removed rollDate from boolean to enable Alex's change
- if (datePattern != null)
- {
- 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);
- }
- else
- {
- if (rollDate)
- {
- LogLog.error("Either DatePattern or rollingStyle options are not set for [" + name + "].");
- }
- }
-
- existingInit();
-
- if (rollDate && (fileName != null) && (scheduledFilename == null))
- {
- scheduledFilename = fileName + sdf.format(now);
- }
-
- try
- {
- this.setFile(fileName, true);
- }
- catch (IOException e)
- {
- errorHandler.error("Cannot set file name:" + fileName);
- }
-
- super.activateOptions();
- }
-
- /**
- * Rollover the file(s) to date/time tagged file(s). Opens the new file (through setFile) and resets
- * curSizeRollBackups.
- */
- protected void rollOverTime()
- {
-
- curTimeRollBackups++;
-
- this.closeFile(); // keep windows happy.
-
-
- rollFile();
-
- try
- {
- curSizeRollBackups = 0; // We're cleared out the old date and are ready for the new
-
- // new scheduled name
- scheduledFilename = fileName + sdf.format(now);
- this.setFile(baseFileName, false);
- }
- catch (IOException e)
- {
- errorHandler.error("setFile(" + fileName + ", false) call failed.");
- }
-
- }
-
- /**
- * Renames file <code>from</code> to file <code>to</code>. It also checks for existence of target file and deletes
- * if it does.
- */
- protected void rollFile(String from, String to, boolean compress)
- {
- if (from.equals(to))
- {
- if (compress)
- {
- LogLog.error("Attempting to compress file with same output name.");
- }
-
- return;
- }
-
- if (backupFilesToPath != null)
- {
- to = backupFilesToPath + System.getProperty("file.separator") + new File(to).getName();
- }
-
- File target = new File(to);
-
- File file = new File(from);
- // Perform Roll by renaming
- if (!file.getPath().equals(target.getPath()))
- {
- file.renameTo(target);
- }
-
- // Compress file after it has been moved out the way... this is safe
- // as it will gain a .gz ending and we can then safely delete this file
- // as it will not be the statically named value.
- if (compress)
- {
- compress(target);
- }
-
- LogLog.debug(from + " -> " + to);
- }
-
- private void compress(File target)
- {
- if (compressAsync)
- {
- synchronized (_compress)
- {
- _compress.offer(new CompressJob(target, target));
- }
-
- startCompression();
- }
- else
- {
- doCompress(target, target);
- }
- }
-
- private void startCompression()
- {
- if (_compressing.compareAndSet(false, true))
- {
- executor.execute(compressor);
- }
- }
-
- /**
- * Delete the given file that is prepended with the relative path to the log
- * directory.
- *
- * Compress is enabled check for file with COMPRESS_EXTENSION(.gz)
- *
- * if backupFilesToPath is set then check in this directory not the
- * main log directory.
- */
- protected void deleteFile(String relativeFileName)
- {
- String fileName="";
- // If we have configured a backup location then we should look in there
- // for the file we are trying to delete
- if (backupFilesToPath != null)
- {
- File file = new File(relativeFileName);
-
- fileName = backupFilesToPath + System.getProperty("file.separator") + file.getName();
- }
-
- // If we are compressing the at the extension
- if (compress)
- {
- fileName += COMPRESS_EXTENSION;
- }
-
-
- File file = new File(fileName);
-
- if (file.exists())
- {
- file.delete();
- }
- }
-
- /**
- * Implements roll overs base on file size.
- *
- * <p>If the maximum number of size based backups is reached (<code>curSizeRollBackups == maxSizeRollBackups</code)
- * then the oldest file is deleted -- it's index determined by the sign of countDirection.<br> If
- * <code>countDirection</code> < 0, then files {<code>File.1</code>, ..., <code>File.curSizeRollBackups -1</code>}
- * are renamed to {<code>File.2</code>, ..., <code>File.curSizeRollBackups</code>}. Moreover, <code>File</code> is
- * renamed <code>File.1</code> and closed.<br>
- *
- * A new file is created to receive further log output.
- *
- * <p>If <code>maxSizeRollBackups</code> is equal to zero, then the <code>File</code> is truncated with no backup
- * files created.
- *
- * <p>If <code>maxSizeRollBackups</code> < 0, then <code>File</code> is renamed if needed and no files are deleted.
- */
-
- // synchronization not necessary since doAppend is alreasy synched
- protected void rollOverSize()
- {
- File file;
-
- this.closeFile(); // keep windows happy.
-
- LogLog.debug("rolling over count=" + ((CountingQuietWriter) qw).getCount());
- LogLog.debug("maxSizeRollBackups = " + maxSizeRollBackups);
- LogLog.debug("curSizeRollBackups = " + curSizeRollBackups);
- LogLog.debug("countDirection = " + countDirection);
-
- // If maxBackups <= 0, then there is no file renaming to be done.
- if (maxSizeRollBackups != 0)
- {
- rollFile();
- }
-
- try
- {
- // This will also close the file. This is OK since multiple
- // close operations are safe.
- this.setFile(baseFileName, false);
- }
- catch (IOException e)
- {
- LogLog.error("setFile(" + fileName + ", false) call failed.", e);
- }
- }
-
- /**
- * Perform file Rollover ensuring the countDirection is applied along with
- * the other options
- */
- private void rollFile()
- {
- LogLog.debug("CD="+countDirection+",start");
- if (countDirection < 0)
- {
- // If we haven't rolled yet then validate we have the right value
- // for curSizeRollBackups
- if (curSizeRollBackups == 0)
- {
- //Validate curSizeRollBackups
- curSizeRollBackups = countFileIndex(fileName);
- // decrement to offset the later increment
- curSizeRollBackups--;
- }
-
- // If we are not keeping an infinite set of backups the delete oldest
- if (maxSizeRollBackups > 0)
- {
- LogLog.debug("CD=-1,curSizeRollBackups:"+curSizeRollBackups);
- LogLog.debug("CD=-1,maxSizeRollBackups:"+maxSizeRollBackups);
-
- // Delete the oldest file.
- // curSizeRollBackups is never -1 so infinite backups are ok here
- if ((curSizeRollBackups - maxSizeRollBackups) >= 0)
- {
- //The oldest file is the one with the largest number
- // as the 0 is always fileName
- // which moves to fileName.1 etc.
- LogLog.debug("CD=-1,deleteFile:"+curSizeRollBackups);
- deleteFile(fileName + '.' + curSizeRollBackups);
- // decrement to offset the later increment
- curSizeRollBackups--;
- }
- }
- // Map {(maxBackupIndex - 1), ..., 2, 1} to {maxBackupIndex, ..., 3, 2}
- for (int i = curSizeRollBackups; i >= 1; i--)
- {
- String oldName = (fileName + "." + i);
- String newName = (fileName + '.' + (i + 1));
-
- // Ensure that when compressing we rename the compressed archives
- if (compress)
- {
- rollFile(oldName + COMPRESS_EXTENSION, newName + COMPRESS_EXTENSION, false);
- }
- else
- {
- rollFile(oldName, newName, false);
- }
- }
-
- curSizeRollBackups++;
- // Rename fileName to fileName.1
- rollFile(fileName, fileName + ".1", compress);
-
- } // REMOVE This code branching for Alexander Cerna's request
- else if (countDirection == 0)
- {
- // rollFile based on date pattern
- now.setTime(System.currentTimeMillis());
- String newFile = fileName + sdf.format(now);
-
- // If we haven't rolled yet then validate we have the right value
- // for curSizeRollBackups
- if (curSizeRollBackups == 0)
- {
- //Validate curSizeRollBackups
- curSizeRollBackups = countFileIndex(newFile);
- // to balance the increment just coming up. as the count returns
- // the next free number not the last used.
- curSizeRollBackups--;
- }
-
- // If we are not keeping an infinite set of backups the delete oldest
- if (maxSizeRollBackups > 0)
- {
- // Don't prune older files if they exist just go for the last
- // one based on our maxSizeRollBackups. This means we may have
- // more files left on disk that maxSizeRollBackups if this value
- // is adjusted between runs but that is an acceptable state.
- // Otherwise we would have to check on startup that we didn't
- // have more than maxSizeRollBackups and prune then.
-
- if (((curSizeRollBackups - maxSizeRollBackups) >= 0))
- {
- LogLog.debug("CD=0,curSizeRollBackups:"+curSizeRollBackups);
- LogLog.debug("CD=0,maxSizeRollBackups:"+maxSizeRollBackups);
-
- // delete the first and keep counting up.
- int oldestFileIndex = curSizeRollBackups - maxSizeRollBackups + 1;
- LogLog.debug("CD=0,deleteFile:"+oldestFileIndex);
- deleteFile(newFile + '.' + oldestFileIndex);
- }
- }
-
-
- String finalName = newFile;
-
- curSizeRollBackups++;
-
- // Add rollSize if it is > 0
- if (curSizeRollBackups > 0 )
- {
- finalName = newFile + '.' + curSizeRollBackups;
-
- }
-
- rollFile(fileName, finalName, compress);
- }
- else
- { // countDirection > 0
- // If we haven't rolled yet then validate we have the right value
- // for curSizeRollBackups
- if (curSizeRollBackups == 0)
- {
- //Validate curSizeRollBackups
- curSizeRollBackups = countFileIndex(fileName);
- // to balance the increment just coming up. as the count returns
- // the next free number not the last used.
- curSizeRollBackups--;
- }
-
- // If we are not keeping an infinite set of backups the delete oldest
- if (maxSizeRollBackups > 0)
- {
- LogLog.debug("CD=1,curSizeRollBackups:"+curSizeRollBackups);
- LogLog.debug("CD=1,maxSizeRollBackups:"+maxSizeRollBackups);
-
- // Don't prune older files if they exist just go for the last
- // one based on our maxSizeRollBackups. This means we may have
- // more files left on disk that maxSizeRollBackups if this value
- // is adjusted between runs but that is an acceptable state.
- // Otherwise we would have to check on startup that we didn't
- // have more than maxSizeRollBackups and prune then.
-
- if (((curSizeRollBackups - maxSizeRollBackups) >= 0))
- {
- // delete the first and keep counting up.
- int oldestFileIndex = curSizeRollBackups - maxSizeRollBackups + 1;
- LogLog.debug("CD=1,deleteFile:"+oldestFileIndex);
- deleteFile(fileName + '.' + oldestFileIndex);
- }
- }
-
-
- curSizeRollBackups++;
-
- rollFile(fileName, fileName + '.' + curSizeRollBackups, compress);
-
- }
- LogLog.debug("CD="+countDirection+",done");
- }
-
-
- private int countFileIndex(String fileName)
- {
- return countFileIndex(fileName, true);
- }
- /**
- * Use filename as a base name and find what count number we are up to by
- * looking at the files in this format:
- *
- * <filename>.<count>[COMPRESS_EXTENSION]
- *
- * If a count value of 1 cannot be found then a directory listing is
- * performed to try and identify if there is a valid value for <count>.
- *
- *
- * @param fileName the basefilename to use
- * @param checkBackupLocation should backupFilesToPath location be checked for existing backups
- * @return int the next free index
- */
- private int countFileIndex(String fileName, boolean checkBackupLocation)
- {
- String testFileName;
-
- // It is possible for index 1..n to be missing leaving n+1..n+1+m logs
- // in this scenario we should still return n+1+m+1
- int index=1;
-
- testFileName = fileName + "." + index;
-
- // Bail out early if there is a problem with the file
- if (new File(testFileName) == null
- || new File(testFileName + COMPRESS_EXTENSION) == null)
-
- {
- return index;
- }
-
- // Check that we do not have the 1..n missing scenario
- if (!(new File(testFileName).exists()
- || new File(testFileName + COMPRESS_EXTENSION).exists()))
-
- {
- int max=0;
- String prunedFileName = new File(fileName).getName();
-
- // Look through all files to find next index
- if (new File(fileName).getParentFile() != null)
- {
- for (File file : new File(fileName).getParentFile().listFiles())
- {
- String name = file.getName();
-
- if (name.startsWith(prunedFileName) && !name.equals(prunedFileName))
- {
- String parsedCount = name.substring(prunedFileName.length() + 1);
-
- if (parsedCount.endsWith(COMPRESS_EXTENSION))
- {
- parsedCount = parsedCount.substring(0, parsedCount.indexOf(COMPRESS_EXTENSION));
- }
-
- try
- {
- max = Integer.parseInt(parsedCount);
-
- // if we got a good value then update our index value.
- if (max > index)
- {
- // +1 as we want to return the next free value.
- index = max + 1;
- }
- }
- catch (NumberFormatException nfe)
- {
- //ignore it assume file doesn't exist.
- }
- }
- }
- }
-
- // Update testFileName
- testFileName = fileName + "." + index;
- }
-
-
- while (new File(testFileName).exists()
- || new File(testFileName + COMPRESS_EXTENSION).exists())
- {
- index++;
- testFileName = fileName + "." + index;
- }
-
- if (checkBackupLocation && index == 1 && backupFilesToPath != null)
- {
- LogLog.debug("Trying backup location:"+backupFilesToPath + System.getProperty("file.separator") + fileName);
- return countFileIndex(backupFilesToPath + System.getProperty("file.separator") + new File(fileName).getName(), false);
- }
-
- return index;
- }
-
- protected synchronized void doCompress(File from, File to)
- {
- String toFile;
-
- toFile = to.getPath() + COMPRESS_EXTENSION;
-
- File target = new File(toFile);
- if (target.exists())
- {
- LogLog.debug("deleting existing target file: " + target);
- target.delete();
- }
-
- try
- {
- // Create the GZIP output stream
- GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(target));
- try
- {
- // Open the input file
- FileInputStream in = new FileInputStream(from);
- try
- {
- // Transfer bytes from the input file to the GZIP output stream
- byte[] buf = new byte[1024];
- int len;
- while ((len = in.read(buf)) > 0)
- {
- out.write(buf, 0, len);
- }
- }
- finally
- {
- in.close();
- }
-
- // Complete the GZIP file
- out.finish();
- }
- finally
- {
- out.close();
- }
- // Remove old file.
- from.delete();
- }
- catch (IOException e)
- {
- if (target.exists())
- {
- target.delete();
- }
-
- rollFile(from.getPath(), to.getPath(), false);
- }
- }
-
- private static class CompressJob
- {
- File _from, _to;
-
- CompressJob(File from, File to)
- {
- _from = from;
- _to = to;
- }
-
- File getFrom()
- {
- return _from;
- }
-
- File getTo()
- {
- return _to;
- }
- }
-
- Compressor compressor = null;
-
- Executor executor;
-
- private class Compressor implements Runnable
- {
- public void run()
- {
- boolean running = true;
- while (running)
- {
- CompressJob job = _compress.poll();
-
- doCompress(job.getFrom(), job.getTo());
-
- synchronized (_compress)
- {
- if (_compress.isEmpty())
- {
- running = false;
- _compressing.set(false);
- }
- }
- }
-
- }
- }
-}
diff --git a/java/broker/src/main/java/org/apache/log4j/xml/QpidLog4JConfigurator.java b/java/broker/src/main/java/org/apache/log4j/xml/QpidLog4JConfigurator.java
deleted file mode 100644
index 1200ba6e0b..0000000000
--- a/java/broker/src/main/java/org/apache/log4j/xml/QpidLog4JConfigurator.java
+++ /dev/null
@@ -1,320 +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.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;
-
-/**
- * Substitute for the Log4J XMLWatchdog (as used by DOMConfigurator.configureAndWatch)
- *
- * Extends the default behaviour with a strict parser check on the XML file before allowing the reconfiguration to proceed,
- * ensuring that any parser error or warning prevents initiation of a configuration update by Log4J, which aborts mid-update
- * upon fatal errors from the parser and proceeds in the event of 'regular' parser errors and warnings, in all cases allowing
- * startup to proceed with whatever half-baked configuration then exists.
- */
-public class QpidLog4JConfigurator
-{
- //lock to protect access to the configuration file
- //shared with LoggingManagementMBean
- public static final ReentrantLock LOCK = new ReentrantLock();
- private static Logger _logger;
- private static DOMConfigurator domConfig = new DOMConfigurator();
-
- private QpidLog4JConfigurator()
- {
- //no instances
- }
-
- public static void configure(String filename) throws IOException, ParserConfigurationException,
- SAXException, IllegalLoggerLevelException
- {
- try
- {
- LOCK.lock();
-
- parseXMLConfigFile(filename);
- checkLoggerLevels(filename);
-
- DOMConfigurator.configure(filename);
-
- if(_logger == null)
- {
- _logger = Logger.getLogger(QpidLog4JConfigurator.class);
- }
- }
- finally
- {
- LOCK.unlock();
- }
- }
-
- public static void configureAndWatch(String filename, long delay) throws IOException, ParserConfigurationException,
- SAXException, IllegalLoggerLevelException
- {
- parseXMLConfigFile(filename);
- checkLoggerLevels(filename);
-
- QpidLog4JXMLWatchdog watchdog = new QpidLog4JXMLWatchdog(filename);
- watchdog.setDelay(delay);
- watchdog.start();
- }
-
- private static void parseXMLConfigFile(String fileName) throws IOException, SAXException,
- ParserConfigurationException
- {
- try
- {
- LOCK.lock();
-
- //check file was specified, exists, and is readable
- if(fileName == null)
- {
- throw new IOException("Provided log4j XML configuration filename was null");
- }
-
- File configFile = new File(fileName);
-
- if (!configFile.exists())
- {
- throw new IOException("The log4j XML configuration file does not exist: " + fileName);
- }
- else if (!configFile.canRead())
- {
- throw new IOException("The log4j XML configuration file is not readable: " + fileName);
- }
-
- //parse it
- DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
- DocumentBuilder docBuilder;
-
- ErrorHandler errHandler = new QpidLog4JSaxErrorHandler();
-
- docFactory.setValidating(true);
- docBuilder = docFactory.newDocumentBuilder();
- docBuilder.setErrorHandler(errHandler);
- docBuilder.setEntityResolver(new Log4jEntityResolver());
- docBuilder.parse(fileName);
- }
- finally
- {
- LOCK.unlock();
- }
- }
-
- public static class QpidLog4JSaxErrorHandler implements ErrorHandler
- {
- public void error(SAXParseException e) throws SAXException
- {
- if(_logger != null)
- {
- _logger.warn(constructMessage("Error parsing XML file", e));
- }
- else
- {
- System.err.println(constructMessage("Error parsing XML file", e));
- }
- }
-
- public void fatalError(SAXParseException e) throws SAXException
- {
- throw new SAXException(constructMessage("Fatal error parsing XML file", e));
- }
-
- public void warning(SAXParseException e) throws SAXException
- {
- if(_logger != null)
- {
- _logger.warn(constructMessage("Warning parsing XML file", e));
- }
- else
- {
- System.err.println(constructMessage("Warning parsing XML file", e));
- }
- }
-
- private static String constructMessage(final String msg, final SAXParseException ex)
- {
- return msg + ": Line " + ex.getLineNumber()+" column " +ex.getColumnNumber() + ": " + ex.getMessage();
- }
- }
-
- private static class QpidLog4JXMLWatchdog extends XMLWatchdog
- {
- public QpidLog4JXMLWatchdog(String filename)
- {
- super(filename);
- }
-
- public void doOnChange()
- {
- try
- {
- LOCK.lock();
-
- try
- {
- parseXMLConfigFile(filename);
- }
- catch (Exception e)
- {
- //logger will be instantiated following first configuration success, which has been pre-validated
- //and so the null check should never actually be required.
- if(_logger != null)
- {
- _logger.warn("Parsing the log4j XML configuration file generated errors/warnings. " +
- "The new configuration was not applied. Correct the issues to prompt " +
- "another update attempt: " + e.getMessage());
- }
- return;
- }
-
- try
- {
- checkLoggerLevels(filename);
- }
- catch (Exception e)
- {
- //logger will be instantiated following first configuration success, which has been pre-validated
- //and so the null check should never actually be required.
- if(_logger != null)
- {
- _logger.warn("Errors were found when validating the logger level values in the " +
- "log4j XML configuration file. The new configuration was not applied. " +
- "Correct the issues to prompt another update attempt: " + e.getMessage());
- }
- return;
- }
-
- //everything checked was ok, let the normal update process proceed
- super.doOnChange();
-
- //a configuration has now been applied, enable logging for future attempts
- if(_logger == null)
- {
- _logger = Logger.getLogger(QpidLog4JConfigurator.class);
- }
-
- _logger.info("Applied log4j configuration from: " + filename);
- }
- finally
- {
- LOCK.unlock();
- }
-
- }
- }
-
- protected static void checkLoggerLevels(String filename) throws IllegalLoggerLevelException, IOException
- {
- //check that the logger levels specified in the XML are actually valid
-
- try
- {
- LOCK.lock();
-
- //get the Logger levels to check
- Map<String, String> loggersLevels;
- loggersLevels = LoggingManagementMBean.retrieveConfigFileLoggersLevels(filename);
- //add the RootLogger to the list too
- String rootLoggerlevelString = LoggingManagementMBean.retrieveConfigFileRootLoggerLevel(filename);
- loggersLevels.put("Root", rootLoggerlevelString);
-
-
- for (Map.Entry<String, String> entry : loggersLevels.entrySet())
- {
- String loggerName = entry.getKey();
- String levelString = entry.getValue();
-
- //let log4j replace any properties in the string
- String log4jConfiguredString = domConfig.subst(levelString);
-
- if(log4jConfiguredString.equals("") && ! log4jConfiguredString.equals(levelString))
- {
- //log4j has returned an empty string but this isnt what we gave it.
- //There may have been an undefined property. Unlike an incorrect
- //literal value, we will allow this case to proceed, but warn users.
-
- if(_logger != null)
- {
- _logger.warn("Unable to detect Level value from '" + levelString
- +"' for logger '" + loggerName + "', Log4J will default this to DEBUG");
- }
- else
- {
- System.err.println("Unable to detect Level value from '" + levelString
- +"' for logger " + loggerName + ", Log4J will default this to DEBUG");
- }
-
- continue;
- }
-
- checkLevel(loggerName,log4jConfiguredString);
- }
- }
- finally
- {
- LOCK.unlock();
- }
- }
-
- private static void checkLevel(String loggerName, String levelString) throws IllegalLoggerLevelException
- {
- if("null".equalsIgnoreCase(levelString) || "inherited".equalsIgnoreCase(levelString))
- {
- //the string "null" signals to inherit from a parent logger
- return;
- }
-
- Level level = Level.toLevel(levelString);
-
- //above Level.toLevel call returns a DEBUG Level if the request fails. Check the result.
- if (level.equals(Level.DEBUG) && !(levelString.equalsIgnoreCase("debug")))
- {
- //received DEBUG but we did not ask for it, the Level request failed.
- throw new IllegalLoggerLevelException("Level '" + levelString + "' specified for Logger '" + loggerName + "' is invalid");
- }
- }
-
- public static class IllegalLoggerLevelException extends Exception
- {
- private static final long serialVersionUID = 1L;
-
- public IllegalLoggerLevelException(String msg)
- {
- super(msg);
- }
- }
-}
-
diff --git a/java/broker/src/main/java/org/apache/qpid/configuration/Configuration.java b/java/broker/src/main/java/org/apache/qpid/configuration/Configuration.java
deleted file mode 100644
index 0b63c68854..0000000000
--- a/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/java/broker/src/main/java/org/apache/qpid/qmf/CompletionCode.java b/java/broker/src/main/java/org/apache/qpid/qmf/CompletionCode.java
deleted file mode 100644
index 706ab3974a..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/qmf/CompletionCode.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.qmf;
-
-public enum CompletionCode
-{
- OK,
- UNKNOWN_OBJECT,
- UNKNOWN_METHOD,
- NOT_IMPLEMENTED,
- INVALID_PARAMETER,
- FEATURE_NOT_IMPLEMENTED,
- FORBIDDEN,
- EXCEPTION,
- UNKNOWN_PACKAGE,
- UNKNOWN_CLASS;
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/qmf/ManagementExchange.java b/java/broker/src/main/java/org/apache/qpid/qmf/ManagementExchange.java
deleted file mode 100644
index 593c1616fb..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/qmf/ManagementExchange.java
+++ /dev/null
@@ -1,557 +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.qmf;
-
-import org.apache.qpid.AMQException;
-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.ConfigStore;
-import org.apache.qpid.server.configuration.ConfiguredObject;
-import org.apache.qpid.server.configuration.ExchangeConfigType;
-import org.apache.qpid.server.exchange.Exchange;
-import org.apache.qpid.server.exchange.ExchangeReferrer;
-import org.apache.qpid.server.exchange.ExchangeType;
-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;
-import org.apache.qpid.server.queue.BaseQueue;
-import org.apache.qpid.server.virtualhost.HouseKeepingTask;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-
-import java.nio.ByteBuffer;
-import java.util.ArrayList;
-import java.util.Collection;
-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;
-import java.util.concurrent.CopyOnWriteArraySet;
-import java.util.concurrent.atomic.AtomicLong;
-
-public class ManagementExchange implements Exchange, QMFService.Listener
-{
- private static final AMQShortString QPID_MANAGEMENT = new AMQShortString("qpid.management");
- private static final AMQShortString QPID_MANAGEMENT_TYPE = new AMQShortString("management");
-
- private VirtualHost _virtualHost;
-
- private final TopicParser _parser = new TopicParser();
-
- private final Map<AMQShortString, TopicExchangeResult> _topicExchangeResults =
- new ConcurrentHashMap<AMQShortString, TopicExchangeResult>();
-
- private final Set<Binding> _bindingSet = new CopyOnWriteArraySet<Binding>();
- private UUID _id;
- private static final String AGENT_BANK = "0";
-
- private int _bindingCountHigh;
- private final AtomicLong _msgReceived = new AtomicLong();
- private final AtomicLong _bytesReceived = new AtomicLong();
-
- private final CopyOnWriteArrayList<BindingListener> _listeners = new CopyOnWriteArrayList<Exchange.BindingListener>();
-
- //TODO : persist creation time
- private long _createTime = System.currentTimeMillis();
-
-
- private class ManagementQueue implements BaseQueue
- {
- private final String NAME_AS_STRING = "##__mgmt_pseudo_queue__##" + UUID.randomUUID().toString();
- private final AMQShortString NAME_AS_SHORT_STRING = new AMQShortString(NAME_AS_STRING);
-
- public void enqueue(ServerMessage message) throws AMQException
- {
- long size = message.getSize();
-
- ByteBuffer buf = ByteBuffer.allocate((int) size);
-
- int offset = 0;
-
- while(offset < size)
- {
- offset += message.getContent(buf,offset);
- }
-
- buf.flip();
- QMFCommandDecoder commandDecoder = new QMFCommandDecoder(getQMFService(),buf);
- QMFCommand cmd;
- while((cmd = commandDecoder.decode()) != null)
- {
- cmd.process(_virtualHost, message);
- }
-
- }
-
- public void enqueue(ServerMessage message, PostEnqueueAction action) throws AMQException
- {
- enqueue(message);
- }
-
- public boolean isDurable()
- {
- return false;
- }
-
- public AMQShortString getNameShortString()
- {
- return NAME_AS_SHORT_STRING;
- }
-
- public String getResourceName()
- {
- return NAME_AS_STRING;
- }
- }
-
-
- private final ManagementQueue _mgmtQueue = new ManagementQueue();
-
- public ManagementExchange()
- {
- }
-
- public static final ExchangeType<ManagementExchange> TYPE = new ExchangeType<ManagementExchange>()
- {
-
- public AMQShortString getName()
- {
- return QPID_MANAGEMENT_TYPE;
- }
-
- public Class<ManagementExchange> getExchangeClass()
- {
- return ManagementExchange.class;
- }
-
- public ManagementExchange newInstance(VirtualHost host,
- AMQShortString name,
- boolean durable,
- int ticket,
- boolean autoDelete) throws AMQException
- {
- ManagementExchange exch = new ManagementExchange();
- exch.initialise(host, name, durable, ticket, autoDelete);
- return exch;
- }
-
- public AMQShortString getDefaultExchangeName()
- {
- return QPID_MANAGEMENT;
- }
- };
-
-
- public AMQShortString getNameShortString()
- {
- return QPID_MANAGEMENT;
- }
-
- public AMQShortString getTypeShortString()
- {
- return QPID_MANAGEMENT_TYPE;
- }
-
- public void initialise(VirtualHost host, AMQShortString name, boolean durable, int ticket, boolean autoDelete)
- throws AMQException
- {
- if(!QPID_MANAGEMENT.equals(name))
- {
- throw new AMQException("Can't create more than one Management exchange");
- }
- _virtualHost = host;
- _id = host.getConfigStore().createId();
- _virtualHost.scheduleHouseKeepingTask(_virtualHost.getBroker().getManagementPublishInterval(), new UpdateTask(_virtualHost));
- getConfigStore().addConfiguredObject(this);
- getQMFService().addListener(this);
- }
-
- public UUID getId()
- {
- return _id;
- }
-
- public ExchangeConfigType getConfigType()
- {
- return ExchangeConfigType.getInstance();
- }
-
- public ConfiguredObject getParent()
- {
- return _virtualHost;
- }
-
- public boolean isDurable()
- {
- return true;
- }
-
- public VirtualHost getVirtualHost()
- {
- return _virtualHost;
- }
-
- public String getName()
- {
- return QPID_MANAGEMENT.toString();
- }
-
- public ExchangeType getType()
- {
- return TYPE;
- }
-
- public boolean isAutoDelete()
- {
- return false;
- }
-
- public int getTicket()
- {
- return 0;
- }
-
- public void close() throws AMQException
- {
- getConfigStore().removeConfiguredObject(this);
- }
-
- public ConfigStore getConfigStore()
- {
- return getVirtualHost().getConfigStore();
- }
-
- public synchronized void addBinding(final Binding b)
- {
-
- if(_bindingSet.add(b))
- {
- AMQShortString routingKey = TopicNormalizer.normalize(new AMQShortString(b.getBindingKey()));
-
- TopicExchangeResult result = _topicExchangeResults.get(routingKey);
- if(result == null)
- {
- result = new TopicExchangeResult();
- result.addUnfilteredQueue(b.getQueue());
- _parser.addBinding(routingKey, result);
- _topicExchangeResults.put(routingKey,result);
- }
- else
- {
- result.addUnfilteredQueue(b.getQueue());
- }
-
- result.addBinding(b);
- }
-
- for(BindingListener listener : _listeners)
- {
- listener.bindingAdded(this, b);
- }
-
- if(_bindingSet.size() > _bindingCountHigh)
- {
- _bindingCountHigh = _bindingSet.size();
- }
-
- String bindingKey = b.getBindingKey();
-
- if(bindingKey.startsWith("schema.") || bindingKey.startsWith("*.") || bindingKey.startsWith("#."))
- {
- publishAllSchema();
- }
- if(bindingKey.startsWith("console.") || bindingKey.startsWith("*.") || bindingKey.startsWith("#."))
- {
- publishAllConsole();
- }
-
- }
-
- void publishAllConsole()
- {
- QMFService qmfService = getQMFService();
-
- long sampleTime = System.currentTimeMillis();
-
- for(QMFPackage pkg : qmfService.getSupportedSchemas())
- {
- for(QMFClass qmfClass : pkg.getClasses())
- {
- Collection<QMFObject> qmfObjects = qmfService.getObjects(qmfClass);
-
- publishObjectsToConsole(sampleTime, qmfObjects);
- }
-
- }
-
- }
-
- private QMFService getQMFService()
- {
- return _virtualHost.getApplicationRegistry().getQMFService();
- }
-
- void publishObjectsToConsole(final long sampleTime,
- final Collection<QMFObject> qmfObjects)
- {
- if(!qmfObjects.isEmpty() && hasBindings())
- {
- QMFClass qmfClass = qmfObjects.iterator().next().getQMFClass();
- ArrayList<QMFCommand> commands = new ArrayList<QMFCommand>();
-
-
- for(QMFObject obj : qmfObjects)
- {
- commands.add(obj.asConfigInfoCmd(sampleTime));
- commands.add(obj.asInstrumentInfoCmd(sampleTime));
- }
-
- publishToConsole(qmfClass, commands);
- }
- }
-
- private void publishToConsole(final QMFClass qmfClass, final ArrayList<QMFCommand> commands)
- {
- if(!commands.isEmpty() && hasBindings())
- {
- String routingKey = "console.obj.1." + AGENT_BANK + "." + qmfClass.getPackage().getName() + "." + qmfClass.getName();
- QMFMessage message = new QMFMessage(routingKey,commands.toArray(new QMFCommand[commands.size()]));
-
- Collection<TopicMatcherResult> results = _parser.parse(new AMQShortString(routingKey));
- HashSet<AMQQueue> queues = new HashSet<AMQQueue>();
- for(TopicMatcherResult result : results)
- {
- TopicExchangeResult res = (TopicExchangeResult)result;
-
- for(Binding b : res.getBindings())
- {
- b.incrementMatches();
- }
-
- queues.addAll(((TopicExchangeResult)result).getUnfilteredQueues());
- }
- for(AMQQueue queue : queues)
- {
- try
- {
- queue.enqueue(message);
- }
- catch (AMQException e)
- {
- throw new RuntimeException(e);
- }
- }
- }
- }
-
- void publishAllSchema()
- {
-
- }
-
- public synchronized void removeBinding(final Binding binding)
- {
- if(_bindingSet.remove(binding))
- {
- AMQShortString bindingKey = TopicNormalizer.normalize(new AMQShortString(binding.getBindingKey()));
- TopicExchangeResult result = _topicExchangeResults.get(bindingKey);
- result.removeBinding(binding);
- result.removeUnfilteredQueue(binding.getQueue());
- }
-
- for(BindingListener listener : _listeners)
- {
- listener.bindingRemoved(this, binding);
- }
- }
-
- public synchronized Collection<Binding> getBindings()
- {
- return new ArrayList<Binding>(_bindingSet);
- }
-
- public ArrayList<BaseQueue> route(InboundMessage message)
- {
- ArrayList<BaseQueue> queues = new ArrayList<BaseQueue>(1);
- _msgReceived.incrementAndGet();
- _bytesReceived.addAndGet(message.getSize());
- queues.add(_mgmtQueue);
- return queues;
- }
-
- public boolean isBound(AMQShortString routingKey, FieldTable arguments, AMQQueue queue)
- {
- return false; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean isBound(AMQShortString routingKey, AMQQueue queue)
- {
- return false; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean isBound(AMQShortString routingKey)
- {
- return false; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean isBound(AMQQueue queue)
- {
- return false; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean hasBindings()
- {
- return !_bindingSet.isEmpty();
- }
-
- public boolean isBound(String bindingKey, AMQQueue queue)
- {
- return false; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean isBound(String bindingKey)
- {
- return false; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void addCloseTask(final Task task)
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void removeCloseTask(final Task task)
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
-
-
- public Exchange getAlternateExchange()
- {
- return null;
- }
-
- public Map<String, Object> getArguments()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void setAlternateExchange(Exchange exchange)
- {
-
- }
-
- public void removeReference(ExchangeReferrer exchange)
- {
- }
-
- public void addReference(ExchangeReferrer exchange)
- {
- }
-
- public boolean hasReferrers()
- {
- return true;
- }
-
-
-
- private class UpdateTask extends HouseKeepingTask
- {
- public UpdateTask(VirtualHost vhost)
- {
- super(vhost);
- }
-
- public void execute()
- {
- publishAllConsole();
- publishAllSchema();
- }
-
- }
-
- public void objectCreated(final QMFObject obj)
- {
- publishObjectsToConsole(System.currentTimeMillis(), Collections.singleton(obj));
- }
-
- public void objectDeleted(final QMFObject obj)
- {
- publishObjectsToConsole(System.currentTimeMillis(), Collections.singleton(obj));
- }
-
- public long getBindingCount()
- {
- return getBindings().size();
- }
-
- public long getBindingCountHigh()
- {
- return _bindingCountHigh;
- }
-
- public long getMsgReceives()
- {
- return _msgReceived.get();
- }
-
- public long getMsgRoutes()
- {
- return getMsgReceives();
- }
-
- public long getByteReceives()
- {
- return _bytesReceived.get();
- }
-
- public long getByteRoutes()
- {
- return getByteReceives();
- }
-
- public long getCreateTime()
- {
- return _createTime;
- }
-
- public void addBindingListener(final BindingListener listener)
- {
- _listeners.add(listener);
- }
-
- public void removeBindingListener(final BindingListener listener)
- {
- _listeners.remove(listener);
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/qmf/QMFBrokerRequestCommand.java b/java/broker/src/main/java/org/apache/qpid/qmf/QMFBrokerRequestCommand.java
deleted file mode 100644
index b98daf7cb1..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/qmf/QMFBrokerRequestCommand.java
+++ /dev/null
@@ -1,78 +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.qmf;
-
-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.server.exchange.Exchange;
-import org.apache.qpid.server.queue.BaseQueue;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.management.common.mbeans.ManagedConnection;
-
-import java.util.ArrayList;
-
-public class QMFBrokerRequestCommand extends QMFCommand
-{
-
- public QMFBrokerRequestCommand(QMFCommandHeader header, BBDecoder buf)
- {
- super(header);
- }
-
- public void process(VirtualHost virtualHost, ServerMessage message)
- {
- String exchangeName = message.getMessageHeader().getReplyToExchange();
- String queueName = message.getMessageHeader().getReplyToRoutingKey();
-
- QMFCommand[] commands = new QMFCommand[2];
- commands[0] = new QMFBrokerResponseCommand(this, virtualHost);
- commands[1] = new QMFCommandCompletionCommand(this);
-
- Exchange exchange = virtualHost.getExchangeRegistry().getExchange(exchangeName);
-
- for(QMFCommand cmd : commands)
- {
- QMFMessage responseMessage = new QMFMessage(queueName, cmd);
-
-
- ArrayList<? extends BaseQueue> queues = exchange.route(responseMessage);
-
-
- for(BaseQueue q : queues)
- {
- try
- {
- q.enqueue(responseMessage);
- }
- catch (AMQException e)
- {
- e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
- }
- }
- }
- }
-
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/qmf/QMFBrokerResponseCommand.java b/java/broker/src/main/java/org/apache/qpid/qmf/QMFBrokerResponseCommand.java
deleted file mode 100644
index ac01c47fe8..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/qmf/QMFBrokerResponseCommand.java
+++ /dev/null
@@ -1,46 +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.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
-{
- private QMFCommandHeader _header;
- private VirtualHost _virtualHost;
-
- public QMFBrokerResponseCommand(QMFBrokerRequestCommand qmfBrokerRequestCommand, VirtualHost virtualHost)
- {
- super( new QMFCommandHeader(qmfBrokerRequestCommand.getHeader().getVersion(),
- qmfBrokerRequestCommand.getHeader().getSeq(),
- QMFOperation.BROKER_RESPONSE));
- _virtualHost = virtualHost;
- }
-
- public void encode(BBEncoder encoder)
- {
- super.encode(encoder);
- encoder.writeUuid(_virtualHost.getBrokerId());
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/qmf/QMFClass.java b/java/broker/src/main/java/org/apache/qpid/qmf/QMFClass.java
deleted file mode 100644
index 3408ff09f4..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/qmf/QMFClass.java
+++ /dev/null
@@ -1,158 +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.qmf;
-
-import org.apache.qpid.server.configuration.ConfiguredObject;
-
-import java.util.Collection;
-import java.util.Map;
-import java.util.List;
-import java.util.LinkedHashMap;
-
-abstract public class QMFClass
-{
-
-
- public enum Type
- {
- OBJECT((byte)1),
- EVENT((byte)2);
-
- private final byte _value;
-
- Type(byte value)
- {
- _value = value;
- }
-
- public byte getValue()
- {
- return _value;
- }
- }
-
- private final Type _type;
- private QMFPackage _package;
- private final String _name;
- private byte[] _schemaHash;
-
- private Map<String, QMFProperty> _properties = new LinkedHashMap<String, QMFProperty>();
- private Map<String, QMFStatistic> _statistics = new LinkedHashMap<String, QMFStatistic>();
- private Map<String, QMFMethod> _methods = new LinkedHashMap<String, QMFMethod>();
-
-
-
- public QMFClass(Type type, String name, byte[] schemaHash, List<QMFProperty> properties,
- List<QMFStatistic> statistics, List<QMFMethod> methods)
- {
- this(type, name, schemaHash);
- setProperties(properties);
- setStatistics(statistics);
- setMethods(methods);
- }
-
-
- public QMFClass(Type type, String name, byte[] schemaHash)
-
- {
- _type = type;
- _name = name;
- _schemaHash = schemaHash;
-
- }
-
- protected void setProperties(List<QMFProperty> properties)
- {
- for(QMFProperty prop : properties)
- {
- _properties.put(prop.getName(), prop);
- }
- }
-
- protected void setStatistics(List<QMFStatistic> statistics)
- {
- for(QMFStatistic stat : statistics)
- {
- _statistics.put(stat.getName(), stat);
- }
- }
-
-
- protected void setMethods(List<QMFMethod> methods)
- {
- for(QMFMethod method : methods)
- {
- _methods.put(method.getName(), method);
- }
- }
-
- public void setPackage(QMFPackage aPackage)
- {
- _package = aPackage;
- for(QMFProperty prop : _properties.values())
- {
- prop.setQMFClass(this);
- }
- // TODO Statisics, Methods
- }
-
- public Type getType()
- {
- return _type;
- }
-
- public QMFPackage getPackage()
- {
- return _package;
- }
-
- public String getName()
- {
- return _name;
- }
-
- public byte[] getSchemaHash()
- {
- return _schemaHash;
- }
-
- public Collection<QMFProperty> getProperties()
- {
- return _properties.values();
- }
-
- public Collection<QMFStatistic> getStatistics()
- {
- return _statistics.values();
- }
-
- public Collection<QMFMethod> getMethods()
- {
- return _methods.values();
- }
-
- public QMFMethod getMethod(String methodName)
- {
- return _methods.get(methodName);
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/qmf/QMFClassIndicationCommand.java b/java/broker/src/main/java/org/apache/qpid/qmf/QMFClassIndicationCommand.java
deleted file mode 100644
index a956a9bd70..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/qmf/QMFClassIndicationCommand.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.qpid.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
-{
- private QMFClass _qmfClass;
-
- public QMFClassIndicationCommand(QMFClassQueryCommand qmfClassQueryCommand, QMFClass qmfClass)
- {
- super(new QMFCommandHeader(qmfClassQueryCommand.getHeader().getVersion(),
- qmfClassQueryCommand.getHeader().getSeq(),
- QMFOperation.CLASS_INDICATION));
- _qmfClass = qmfClass;
- }
-
-
- @Override
- public void encode(BBEncoder encoder)
- {
- super.encode(encoder);
- encoder.writeUint8(_qmfClass.getType().getValue());
- encoder.writeStr8(_qmfClass.getPackage().getName());
- encoder.writeStr8(_qmfClass.getName());
- encoder.writeBin128(_qmfClass.getSchemaHash());
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/qmf/QMFClassQueryCommand.java b/java/broker/src/main/java/org/apache/qpid/qmf/QMFClassQueryCommand.java
deleted file mode 100644
index 26a27cfa19..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/qmf/QMFClassQueryCommand.java
+++ /dev/null
@@ -1,90 +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.qmf;
-
-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.exchange.Exchange;
-import org.apache.qpid.server.queue.BaseQueue;
-import org.apache.qpid.server.registry.IApplicationRegistry;
-import org.apache.qpid.AMQException;
-
-import java.util.ArrayList;
-import java.util.Collection;
-
-public class QMFClassQueryCommand extends QMFCommand
-{
- private final String _package;
-
- public QMFClassQueryCommand(QMFCommandHeader header, BBDecoder decoder)
- {
- super(header);
- _package = decoder.readStr8();
- }
-
- public void process(VirtualHost virtualHost, ServerMessage message)
- {
- String exchangeName = message.getMessageHeader().getReplyToExchange();
- String routingKey = message.getMessageHeader().getReplyToRoutingKey();
-
- IApplicationRegistry appRegistry = virtualHost.getApplicationRegistry();
- QMFService service = appRegistry.getQMFService();
-
- QMFPackage qmfPackage = service.getPackage(_package);
- Collection<QMFClass> qmfClasses = qmfPackage.getClasses();
-
- QMFCommand[] commands = new QMFCommand[ qmfClasses.size() + 1 ];
-
- int i = 0;
- for(QMFClass qmfClass : qmfClasses)
- {
- commands[i++] = new QMFClassIndicationCommand(this, qmfClass);
- }
- commands[ commands.length - 1 ] = new QMFCommandCompletionCommand(this);
-
-
- for(QMFCommand cmd : commands)
- {
-
-
- QMFMessage responseMessage = new QMFMessage(routingKey, cmd);
-
- Exchange exchange = virtualHost.getExchangeRegistry().getExchange(exchangeName);
-
- ArrayList<? extends BaseQueue> queues = exchange.route(responseMessage);
-
- for(BaseQueue q : queues)
- {
- try
- {
- q.enqueue(responseMessage);
- }
- catch (AMQException e)
- {
- e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
- }
- }
- }
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/qmf/QMFCommand.java b/java/broker/src/main/java/org/apache/qpid/qmf/QMFCommand.java
deleted file mode 100644
index 4f143701af..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/qmf/QMFCommand.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.qpid.qmf;
-
-import org.apache.qpid.server.message.ServerMessage;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-import org.apache.qpid.transport.codec.BBEncoder;
-
-public abstract class QMFCommand
-{
-
- private final QMFCommandHeader _header;
-
- protected QMFCommand(QMFCommandHeader header)
- {
- _header = header;
- }
-
-
- public void process(final VirtualHost virtualHost, final ServerMessage message)
- {
- throw new UnsupportedOperationException();
- }
-
- public void encode(BBEncoder encoder)
- {
- _header.encode(encoder);
-
- }
-
- public QMFCommandHeader getHeader()
- {
- return _header;
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/qmf/QMFCommandCompletionCommand.java b/java/broker/src/main/java/org/apache/qpid/qmf/QMFCommandCompletionCommand.java
deleted file mode 100644
index f163e434d1..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/qmf/QMFCommandCompletionCommand.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.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
-{
-
- private final CompletionCode _status;
- private final String _text;
-
- public QMFCommandCompletionCommand(QMFCommand command)
- {
- this(command, CompletionCode.OK, "");
- }
- public QMFCommandCompletionCommand(QMFCommand command, CompletionCode status, String text)
- {
- super( new QMFCommandHeader(command.getHeader().getVersion(),
- command.getHeader().getSeq(),
- QMFOperation.COMMAND_COMPLETION));
-
- _status = status;
- _text = text;
- }
-
-
- @Override
- public void encode(BBEncoder encoder)
- {
- super.encode(encoder);
- encoder.writeInt32(_status.ordinal());
- encoder.writeStr8(_text);
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/qmf/QMFCommandDecoder.java b/java/broker/src/main/java/org/apache/qpid/qmf/QMFCommandDecoder.java
deleted file mode 100644
index ac036dfa19..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/qmf/QMFCommandDecoder.java
+++ /dev/null
@@ -1,98 +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.qmf;
-
-import org.apache.qpid.transport.codec.BBDecoder;
-
-import java.nio.ByteBuffer;
-
-public class QMFCommandDecoder
-{
- private BBDecoder _decoder;
-
-
- private static final QMFOperation[] OP_CODES = new QMFOperation[256];
- private final QMFService _qmfService;
-
- static
- {
- for(QMFOperation op : QMFOperation.values())
- {
- OP_CODES[op.getOpcode()] = op;
- }
- }
-
- public QMFCommandDecoder(final QMFService qmfService, ByteBuffer buf)
- {
- _qmfService = qmfService;
- _decoder = new BBDecoder();
- _decoder.init(buf);
- }
-
- public QMFCommand decode()
- {
- if(_decoder.hasRemaining())
- {
- QMFCommandHeader header = readQMFHeader();
-
- switch(header.getOperation())
- {
- case BROKER_REQUEST:
- return new QMFBrokerRequestCommand(header, _decoder);
- case PACKAGE_QUERY:
- return new QMFPackageQueryCommand(header, _decoder);
- case CLASS_QUERY:
- return new QMFClassQueryCommand(header, _decoder);
- case SCHEMA_REQUEST:
- return new QMFSchemaRequestCommand(header, _decoder);
- case METHOD_REQUEST:
- return new QMFMethodRequestCommand(header, _decoder, _qmfService);
- case GET_QUERY:
- return new QMFGetQueryCommand(header, _decoder);
- default:
- System.out.println("Unknown command");
-
- }
-
- return null;
- }
- else
- {
- return null;
- }
- }
-
- private QMFCommandHeader readQMFHeader()
- {
- if(_decoder.readInt8() == (byte) 'A'
- && _decoder.readInt8() == (byte) 'M')
- {
- byte version = _decoder.readInt8();
- short opCode = _decoder.readUint8();
- int seq = _decoder.readInt32();
-
- return new QMFCommandHeader(version, seq, OP_CODES[opCode]);
-
- }
- return null;
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/qmf/QMFCommandHeader.java b/java/broker/src/main/java/org/apache/qpid/qmf/QMFCommandHeader.java
deleted file mode 100644
index c4d771317f..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/qmf/QMFCommandHeader.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.qmf;
-
-import org.apache.qpid.transport.codec.BBEncoder;
-
-public class QMFCommandHeader
-{
- private final byte _version;
- private final int _seq;
-
- private final QMFOperation _operation;
-
- public QMFCommandHeader(byte version, int seq, QMFOperation operation)
- {
- _version = version;
- _seq = seq;
- _operation = operation;
- }
-
- public byte getVersion()
- {
- return _version;
- }
-
- public int getSeq()
- {
- return _seq;
- }
-
- public QMFOperation getOperation()
- {
- return _operation;
- }
-
- public void encode(BBEncoder encoder)
- {
- encoder.writeUint8((short)'A');
- encoder.writeUint8((short)'M');
- encoder.writeInt8(_version);
- encoder.writeUint8((short)_operation.getOpcode());
- encoder.writeInt32(_seq);
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/qmf/QMFEventClass.java b/java/broker/src/main/java/org/apache/qpid/qmf/QMFEventClass.java
deleted file mode 100644
index ec471f18e8..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/qmf/QMFEventClass.java
+++ /dev/null
@@ -1,42 +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.qmf;
-
-import java.util.List;
-
-public abstract class QMFEventClass extends QMFClass
-{
- public QMFEventClass(String name,
- byte[] schemaHash,
- List<QMFProperty> properties,
- List<QMFStatistic> statistics, List<QMFMethod> methods)
- {
- super(Type.EVENT, name, schemaHash, properties, statistics, methods);
- }
-
- public QMFEventClass(String name, byte[] schemaHash)
- {
- super(Type.EVENT, name, schemaHash);
- }
-
- abstract public QMFEventSeverity getSeverity();
-
-} \ No newline at end of file
diff --git a/java/broker/src/main/java/org/apache/qpid/qmf/QMFEventCommand.java b/java/broker/src/main/java/org/apache/qpid/qmf/QMFEventCommand.java
deleted file mode 100644
index d70c12db19..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/qmf/QMFEventCommand.java
+++ /dev/null
@@ -1,49 +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.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<T extends QMFEventClass> extends QMFCommand
-{
- private final long _timestamp;
-
- protected QMFEventCommand()
- {
- super(new QMFCommandHeader((byte)'2',0, QMFOperation.EVENT));
- _timestamp = System.currentTimeMillis();
- }
-
- abstract public T getEventClass();
-
- @Override
- public void encode(final BBEncoder encoder)
- {
- super.encode(encoder);
- encoder.writeStr8(getEventClass().getPackage().getName());
- encoder.writeStr8(getEventClass().getName());
- encoder.writeBin128(new byte[16]);
- encoder.writeUint64(_timestamp * 1000000L);
- encoder.writeUint8((short) getEventClass().getSeverity().ordinal());
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/qmf/QMFEventSeverity.java b/java/broker/src/main/java/org/apache/qpid/qmf/QMFEventSeverity.java
deleted file mode 100644
index 9f9c832732..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/qmf/QMFEventSeverity.java
+++ /dev/null
@@ -1,33 +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.qmf;
-
-public enum QMFEventSeverity
-{
- EMERGENCY,
- ALERT,
- CRITICAL,
- ERROR,
- WARN,
- NOTICE,
- INFORM,
- DEBUG
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/qmf/QMFGetQueryCommand.java b/java/broker/src/main/java/org/apache/qpid/qmf/QMFGetQueryCommand.java
deleted file mode 100644
index 8e8cb55a0d..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/qmf/QMFGetQueryCommand.java
+++ /dev/null
@@ -1,182 +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.qmf;
-
-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.exchange.Exchange;
-import org.apache.qpid.server.queue.BaseQueue;
-import org.apache.qpid.server.registry.IApplicationRegistry;
-import org.apache.qpid.AMQException;
-
-import java.util.*;
-
-public class QMFGetQueryCommand extends QMFCommand
-{
- private Map<String, Object> _map;
-
-
- public QMFGetQueryCommand(QMFCommandHeader header, BBDecoder decoder)
- {
- super(header);
-
- _map = decoder.readMap();
- }
-
- public void process(VirtualHost virtualHost, ServerMessage message)
- {
- String exchangeName = message.getMessageHeader().getReplyToExchange();
- String routingKey = message.getMessageHeader().getReplyToRoutingKey();
-
- IApplicationRegistry appRegistry = virtualHost.getApplicationRegistry();
- QMFService service = appRegistry.getQMFService();
-
- String className = (String) _map.get("_class");
- String packageName = (String) _map.get("_package");
- byte[] objectIdBytes = (byte[]) _map.get("_objectId");
- UUID objectId;
- if(objectIdBytes != null)
- {
- long msb = 0;
- long lsb = 0;
-
- for (int i = 0; i != 8; i++)
- {
- msb = (msb << 8) | (objectIdBytes[i] & 0xff);
- }
- for (int i = 8; i != 16; i++)
- {
- lsb = (lsb << 8) | (objectIdBytes[i] & 0xff);
- }
- objectId = new UUID(msb, lsb);
- }
- else
- {
- objectId = null;
- }
-
- List<QMFCommand> commands = new ArrayList<QMFCommand>();
- final long sampleTime = System.currentTimeMillis() * 1000000l;
-
- Collection<QMFPackage> packages;
-
- if(packageName != null && packageName.length() != 0)
- {
- QMFPackage qmfPackage = service.getPackage(packageName);
- if(qmfPackage == null)
- {
- packages = Collections.EMPTY_LIST;
- }
- else
- {
- packages = Collections.singleton(qmfPackage);
- }
- }
- else
- {
- packages = service.getSupportedSchemas();
- }
-
- for(QMFPackage qmfPackage : packages)
- {
-
- Collection<QMFClass> qmfClasses;
-
- if(className != null && className.length() != 0)
- {
- QMFClass qmfClass = qmfPackage.getQMFClass(className);
- if(qmfClass == null)
- {
- qmfClasses = Collections.EMPTY_LIST;
- }
- else
- {
- qmfClasses = Collections.singleton(qmfClass);
- }
- }
- else
- {
- qmfClasses = qmfPackage.getClasses();
- }
-
-
- for(QMFClass qmfClass : qmfClasses)
- {
- Collection<QMFObject> objects;
-
- if(objectId != null)
- {
- QMFObject obj = service.getObjectById(qmfClass, objectId);
- if(obj == null)
- {
- objects = Collections.EMPTY_LIST;
- }
- else
- {
- objects = Collections.singleton(obj);
- }
- }
- else
- {
- objects = service.getObjects(qmfClass);
- }
-
- for(QMFObject object : objects)
- {
-
- commands.add(object.asGetQueryResponseCmd(this, sampleTime));
- }
- }
-
-
- }
-
-
- commands.add( new QMFCommandCompletionCommand(this));
-
-
- for(QMFCommand cmd : commands)
- {
-
-
- QMFMessage responseMessage = new QMFMessage(routingKey, cmd);
-
- Exchange exchange = virtualHost.getExchangeRegistry().getExchange(exchangeName);
-
- ArrayList<? extends BaseQueue> queues = exchange.route(responseMessage);
-
- for(BaseQueue q : queues)
- {
- try
- {
- q.enqueue(responseMessage);
- }
- catch (AMQException e)
- {
- e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
- }
- }
- }
- }
-
-} \ No newline at end of file
diff --git a/java/broker/src/main/java/org/apache/qpid/qmf/QMFMessage.java b/java/broker/src/main/java/org/apache/qpid/qmf/QMFMessage.java
deleted file mode 100644
index 895ff643a2..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/qmf/QMFMessage.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.qmf;
-
-import org.apache.qpid.server.configuration.SessionConfig;
-import org.apache.qpid.server.message.*;
-import org.apache.qpid.transport.codec.BBEncoder;
-
-import java.nio.ByteBuffer;
-import java.util.Set;
-
-public class QMFMessage implements ServerMessage, InboundMessage, AMQMessageHeader
-{
-
- private ByteBuffer _content;
- private String _routingKey;
-
- public QMFMessage(String routingKey, QMFCommand command)
- {
- this(routingKey, new QMFCommand[] { command });
- }
-
-
- public QMFMessage(String routingKey, QMFCommand[] commands)
- {
- _routingKey = routingKey;
- BBEncoder encoder = new BBEncoder(256);
-
- for(QMFCommand cmd : commands)
- {
- cmd.encode(encoder);
- }
-
-
- _content = encoder.buffer();
- }
-
- public String getRoutingKey()
- {
- return _routingKey;
- }
-
- public AMQMessageHeader getMessageHeader()
- {
- return this;
- }
-
- public boolean isPersistent()
- {
- return false;
- }
-
- public boolean isRedelivered()
- {
- return false;
- }
-
- public long getSize()
- {
- return _content.limit();
- }
-
- public boolean isImmediate()
- {
- return false;
- }
-
- public String getCorrelationId()
- {
- return null;
- }
-
- public long getExpiration()
- {
- return 0;
- }
-
- public String getMessageId()
- {
- return null;
- }
-
- public String getMimeType()
- {
- return null;
- }
-
- public String getEncoding()
- {
- return null;
- }
-
- public byte getPriority()
- {
- return 4;
- }
-
- public long getTimestamp()
- {
- return 0;
- }
-
- public String getType()
- {
- return null;
- }
-
- public String getReplyTo()
- {
- return null;
- }
-
- public String getReplyToExchange()
- {
- return null;
- }
-
- public String getReplyToRoutingKey()
- {
- return null;
- }
-
- public Object getHeader(String name)
- {
- return null;
- }
-
- public boolean containsHeaders(Set<String> names)
- {
- return false;
- }
-
- public boolean containsHeader(String name)
- {
- return false;
- }
-
- public MessageReference newReference()
- {
- return new QMFMessageReference(this);
- }
-
- public Long getMessageNumber()
- {
- return null;
- }
-
- public long getArrivalTime()
- {
- return 0;
- }
-
- public int getContent(ByteBuffer buf, int offset)
- {
- ByteBuffer src = _content.duplicate();
- _content.position(offset);
- _content = _content.slice();
- int len = _content.remaining();
- if(len > buf.remaining())
- {
- len = buf.remaining();
- }
-
- buf.put(src);
-
- return len;
- }
-
- private static class QMFMessageReference extends MessageReference<QMFMessage>
- {
- public QMFMessageReference(QMFMessage message)
- {
- super(message);
- }
-
- protected void onReference(QMFMessage message)
- {
-
- }
-
- protected void onRelease(QMFMessage message)
- {
-
- }
- }
-
- public SessionConfig getSessionConfig()
- {
- return null;
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/qmf/QMFMethod.java b/java/broker/src/main/java/org/apache/qpid/qmf/QMFMethod.java
deleted file mode 100644
index 63e8fa6a1e..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/qmf/QMFMethod.java
+++ /dev/null
@@ -1,157 +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.qmf;
-
-import org.apache.qpid.transport.codec.Encoder;
-import org.apache.qpid.transport.codec.BBDecoder;
-
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.ArrayList;
-
-public abstract class QMFMethod<T extends QMFObject>
-{
- private final LinkedHashMap<String,Object> _map = new LinkedHashMap<String,Object>();
- private final List<Argument> _arguments = new ArrayList<Argument>();
-
- private static final String NAME = "name";
- private static final String TYPE = "type";
- private static final String REF_PACKAGE = "refPackage";
- private static final String REF_CLASS = "refClass";
- private static final String UNIT = "unit";
- private static final String MIN = "min";
- private static final String MAX = "max";
- private static final String MAX_LENGTH = "maxlen";
- private static final String DESCRIPTION = "desc";
- private static final String DEFAULT = "default";
- private static final String DIRECTION = "dir";
- private static final String ARG_COUNT = "argCount";
-
-
-
- public enum Direction
- {
- I,
- O,
- IO;
- }
-
- public class Argument
- {
- private final LinkedHashMap<String,Object> _map = new LinkedHashMap<String,Object>();
-
- public Argument(String name, QMFType type)
- {
- _map.put(NAME, name);
- _map.put(TYPE, type.codeValue());
- }
-
- public void setRefPackage(String refPackage)
- {
- _map.put(REF_PACKAGE, refPackage);
- }
-
- public void setRefClass(String refClass)
- {
- _map.put(REF_CLASS, refClass);
- }
-
- public void setUnit(String unit)
- {
- _map.put(UNIT, unit);
- }
-
- public void setMax(Number max)
- {
- _map.put(MAX, max);
- }
-
- public void setMin(Number min)
- {
- _map.put(MIN, min);
- }
-
- public void setMaxLength(int len)
- {
- _map.put(MAX_LENGTH, len);
- }
-
- public void setDefault(Object dflt)
- {
- _map.put(DEFAULT, dflt);
- }
-
- public void setDescription(String desc)
- {
- _map.put(DESCRIPTION, desc);
- }
-
- public void setDirection(Direction direction)
- {
- _map.put(DIRECTION, direction.toString());
- }
-
- public void encode(Encoder encoder)
- {
- encoder.writeMap(_map);
- }
-
- public String getName()
- {
- return (String) _map.get(NAME);
- }
- }
-
- public QMFMethod(String name, String description)
- {
- _map.put(NAME, name);
- _map.put(ARG_COUNT, 0);
- if(description != null)
- {
- _map.put(DESCRIPTION, description);
- }
-
- }
-
- abstract public QMFMethodInvocation<T> parse(final BBDecoder decoder);
-
- protected void addArgument(Argument arg)
- {
- _arguments.add(arg);
- _map.put(ARG_COUNT, _arguments.size());
- }
-
-
- public void encode(Encoder encoder)
- {
- encoder.writeMap(_map);
- for(Argument arg : _arguments)
- {
- arg.encode(encoder);
- }
- }
-
- public String getName()
- {
- return (String) _map.get(NAME);
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/qmf/QMFMethodInvocation.java b/java/broker/src/main/java/org/apache/qpid/qmf/QMFMethodInvocation.java
deleted file mode 100644
index 5348c2783f..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/qmf/QMFMethodInvocation.java
+++ /dev/null
@@ -1,26 +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.qmf;
-
-public interface QMFMethodInvocation<T extends QMFObject>
-{
- QMFMethodResponseCommand execute(T obj, QMFMethodRequestCommand cmd);
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/qmf/QMFMethodRequestCommand.java b/java/broker/src/main/java/org/apache/qpid/qmf/QMFMethodRequestCommand.java
deleted file mode 100644
index cf27e4b970..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/qmf/QMFMethodRequestCommand.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.qmf;
-
-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.exchange.Exchange;
-import org.apache.qpid.server.queue.BaseQueue;
-import org.apache.qpid.AMQException;
-
-import java.util.UUID;
-import java.util.ArrayList;
-
-public class QMFMethodRequestCommand extends QMFCommand
-{
- private QMFMethodInvocation _methodInstance;
- private QMFObject _object;
-
- public QMFMethodRequestCommand(final QMFCommandHeader header, final BBDecoder decoder, final QMFService qmfService)
- {
- super(header);
- UUID objectId = decoder.readUuid();
- String packageName = decoder.readStr8();
- String className = decoder.readStr8();
- byte[] hash = decoder.readBin128();
- String methodName = decoder.readStr8();
-
- QMFPackage qmfPackage = qmfService.getPackage(packageName);
- QMFClass qmfClass = qmfPackage.getQMFClass(className);
- _object = qmfService.getObjectById(qmfClass, objectId);
- QMFMethod method = qmfClass.getMethod(methodName);
- _methodInstance = method.parse(decoder);
-
- }
-
- public void process(final VirtualHost virtualHost, final ServerMessage message)
- {
- String exchangeName = message.getMessageHeader().getReplyToExchange();
- String queueName = message.getMessageHeader().getReplyToRoutingKey();
-
- QMFCommand[] commands = new QMFCommand[2];
- commands[0] = _methodInstance.execute(_object, this);
- commands[1] = new QMFCommandCompletionCommand(this);
-
- Exchange exchange = virtualHost.getExchangeRegistry().getExchange(exchangeName);
-
- for(QMFCommand cmd : commands)
- {
- QMFMessage responseMessage = new QMFMessage(queueName, cmd);
-
-
- ArrayList<? extends BaseQueue> queues = exchange.route(responseMessage);
-
-
- for(BaseQueue q : queues)
- {
- try
- {
- q.enqueue(responseMessage);
- }
- catch (AMQException e)
- {
- e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
- }
- }
- }
-
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/qmf/QMFMethodResponseCommand.java b/java/broker/src/main/java/org/apache/qpid/qmf/QMFMethodResponseCommand.java
deleted file mode 100644
index 5fea014ad8..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/qmf/QMFMethodResponseCommand.java
+++ /dev/null
@@ -1,76 +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.qmf;
-
-import org.apache.qpid.transport.codec.BBEncoder;
-
-public class QMFMethodResponseCommand extends QMFCommand
-{
- private CompletionCode _status = null;
- private String _msg = null;
-
- public QMFMethodResponseCommand(final QMFMethodRequestCommand cmd,
- CompletionCode status,
- String msg)
- {
- super( new QMFCommandHeader(cmd.getHeader().getVersion(),
- cmd.getHeader().getSeq(),
- QMFOperation.METHOD_RESPONSE));
-
- if(status == null)
- {
- _status = CompletionCode.OK;
- }
- else
- {
- _status = status;
- }
-
- _msg = msg;
- }
-
- public CompletionCode getStatus()
- {
- return _status;
- }
-
- public String getStatusText()
- {
- return _msg;
- }
-
- @Override
- public void encode(final BBEncoder encoder)
- {
- super.encode(encoder);
-
- encoder.writeUint32(_status.ordinal());
-
- if(_msg == null)
- {
- encoder.writeStr16(_status.toString());
- }
- else
- {
- encoder.writeStr16(_msg);
- }
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/qmf/QMFObject.java b/java/broker/src/main/java/org/apache/qpid/qmf/QMFObject.java
deleted file mode 100644
index d126717fc8..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/qmf/QMFObject.java
+++ /dev/null
@@ -1,76 +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.qmf;
-
-import java.util.UUID;
-
-public abstract class QMFObject<C extends QMFClass, D extends QMFObject.Delegate>
-{
- private long _deleteTime;
-
- public interface Delegate
- {
- UUID getId();
- long getCreateTime();
- }
-
-
- private D _delegate;
-
- protected QMFObject(D delegate)
- {
- _delegate = delegate;
- }
-
- public D getDelegate()
- {
- return _delegate;
- }
-
- abstract public C getQMFClass();
-
- public final UUID getId()
- {
- return _delegate.getId();
- }
-
- public final long getCreateTime()
- {
- return _delegate.getCreateTime();
- }
-
- public final void setDeleteTime()
- {
- _deleteTime = System.currentTimeMillis();
- }
-
- public final long getDeleteTime()
- {
- return _deleteTime;
- }
-
-
-
- abstract public QMFCommand asConfigInfoCmd(long sampleTime);
- abstract public QMFCommand asInstrumentInfoCmd(long sampleTime);
- abstract public QMFCommand asGetQueryResponseCmd(final QMFGetQueryCommand queryCommand, long sampleTime);
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/qmf/QMFObjectClass.java b/java/broker/src/main/java/org/apache/qpid/qmf/QMFObjectClass.java
deleted file mode 100644
index fefdecb8d7..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/qmf/QMFObjectClass.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.qmf;
-
-import java.util.List;
-
-public abstract class QMFObjectClass<T extends QMFObject, S extends QMFObject.Delegate> extends QMFClass
-{
- public QMFObjectClass(String name,
- byte[] schemaHash,
- List<QMFProperty> properties,
- List<QMFStatistic> statistics, List<QMFMethod> methods)
- {
- super(QMFClass.Type.OBJECT, name, schemaHash, properties, statistics, methods);
- }
-
- public QMFObjectClass(String name, byte[] schemaHash)
- {
- super(QMFClass.Type.OBJECT, name, schemaHash);
- }
-
-
- public abstract T newInstance(S delegate);
-
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/qmf/QMFOperation.java b/java/broker/src/main/java/org/apache/qpid/qmf/QMFOperation.java
deleted file mode 100644
index 6736b5d460..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/qmf/QMFOperation.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.qpid.qmf;
-
-public enum QMFOperation
-{
-
-
- BROKER_REQUEST('B'),
- BROKER_RESPONSE('b'), // This message contains a broker response, sent from the broker in response to a broker request message.
- COMMAND_COMPLETION('z'), // This message is sent to indicate the completion of a request.
- CLASS_QUERY('Q'), // Class query messages are used by a management console to request a list of schema classes that are known by the management broker.
- CLASS_INDICATION('q'), // Sent by the management broker, a class indication notifies the peer of the existence of a schema class.
- SCHEMA_REQUEST('S'), // Schema request messages are used to request the full schema details for a class.
- SCHEMA_RESPONSE('s'), // Schema response message contain a full description of the schema for a class.
- HEARTBEAT_INDEICATION('h'), // This message is published once per publish-interval. It can be used by a client to positively determine which objects did not change during the interval (since updates are not published for objects with no changes).
- CONFIG_INDICATION('c'),
- INSTRUMENTATION_INDICATION('i'),
- GET_QUERY_RESPONSE('g'), // This message contains a content record. Content records contain the values of all properties or statistics in an object. Such records are broadcast on a periodic interval if 1) a change has been made in the value of one of the elements, or 2) if a new management client has bound a queue to the management exchange.
- GET_QUERY('G'), // Sent by a management console, a get query requests that the management broker provide content indications for all objects that match the query criteria.
- METHOD_REQUEST('M'), // This message contains a method request.
- METHOD_RESPONSE('m'), // This message contains a method result.
- PACKAGE_QUERY('P'), // This message contains a schema package query request, requesting that the broker dump the list of known packages
- PACKAGE_INDICATION('p'), // This message contains a schema package indication, identifying a package known by the broker
- AGENT_ATTACH_REUQEST('A'), // This message is sent by a remote agent when it wishes to attach to a management broker
- AGENT_ATTACH_RESPONSE('a'), // The management broker sends this response if an attaching remote agent is permitted to join
- CONSOLE_ADDED_INDICATION('x'), // This message is sent to all remote agents by the management broker when a new console binds to the management exchange
- EVENT('e')
- ;
-
-
- private final char _opcode;
-
- private static final QMFOperation[] OP_CODES = new QMFOperation[256];
-
-
- QMFOperation(char opcode)
- {
- _opcode = opcode;
- }
-
-
- public char getOpcode()
- {
- return _opcode;
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/qmf/QMFPackage.java b/java/broker/src/main/java/org/apache/qpid/qmf/QMFPackage.java
deleted file mode 100644
index 681e64b799..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/qmf/QMFPackage.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.qpid.qmf;
-
-import java.util.Collection;
-import java.util.Map;
-import java.util.HashMap;
-
-public class QMFPackage
-{
- private final String _name;
- private final Map<String, QMFClass> _classes = new HashMap<String, QMFClass>();
-
- public QMFPackage(String name)
- {
- _name = name;
- }
-
- public QMFPackage(String name, Collection<QMFClass> classes)
- {
- this(name);
- setClasses(classes);
- }
-
- protected void setClasses(Collection<QMFClass> classes)
- {
- for(QMFClass qmfClass : classes)
- {
- qmfClass.setPackage(this);
- _classes.put(qmfClass.getName(), qmfClass);
- }
- }
-
- public String getName()
- {
- return _name;
- }
-
- public Collection<QMFClass> getClasses()
- {
- return _classes.values();
- }
-
- public QMFClass getQMFClass(String className)
- {
- return _classes.get(className);
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/qmf/QMFPackageIndicationCommand.java b/java/broker/src/main/java/org/apache/qpid/qmf/QMFPackageIndicationCommand.java
deleted file mode 100644
index 7053b80655..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/qmf/QMFPackageIndicationCommand.java
+++ /dev/null
@@ -1,46 +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.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
-{
- private String _supportedSchema;
-
- public QMFPackageIndicationCommand(QMFPackageQueryCommand qmfPackageQueryCommand, String supportedSchema)
- {
- super( new QMFCommandHeader(qmfPackageQueryCommand.getHeader().getVersion(),
- qmfPackageQueryCommand.getHeader().getSeq(),
- QMFOperation.PACKAGE_INDICATION));
- _supportedSchema = supportedSchema;
-
- }
-
- public void encode(BBEncoder encoder)
- {
- super.encode(encoder);
- encoder.writeStr8(_supportedSchema);
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/qmf/QMFPackageQueryCommand.java b/java/broker/src/main/java/org/apache/qpid/qmf/QMFPackageQueryCommand.java
deleted file mode 100644
index 6defd088de..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/qmf/QMFPackageQueryCommand.java
+++ /dev/null
@@ -1,86 +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.qmf;
-
-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.exchange.Exchange;
-import org.apache.qpid.server.queue.BaseQueue;
-import org.apache.qpid.server.registry.IApplicationRegistry;
-import org.apache.qpid.AMQException;
-
-import java.util.ArrayList;
-import java.util.Collection;
-
-public class QMFPackageQueryCommand extends QMFCommand
-{
- public QMFPackageQueryCommand(QMFCommandHeader header, BBDecoder decoder)
- {
- super(header);
- }
-
- public void process(VirtualHost virtualHost, ServerMessage message)
- {
- String exchangeName = message.getMessageHeader().getReplyToExchange();
- String routingKey = message.getMessageHeader().getReplyToRoutingKey();
-
-
- IApplicationRegistry appRegistry = virtualHost.getApplicationRegistry();
- QMFService service = appRegistry.getQMFService();
-
- Collection<QMFPackage> supportedSchemas = service.getSupportedSchemas();
-
- QMFCommand[] commands = new QMFCommand[ supportedSchemas.size() + 1 ];
-
- int i = 0;
- for(QMFPackage p : supportedSchemas)
- {
- commands[i++] = new QMFPackageIndicationCommand(this, p.getName());
- }
- commands[ commands.length - 1 ] = new QMFCommandCompletionCommand(this);
-
-
- for(QMFCommand cmd : commands)
- {
-
- QMFMessage responseMessage = new QMFMessage(routingKey, cmd);
-
- Exchange exchange = virtualHost.getExchangeRegistry().getExchange(exchangeName);
-
- ArrayList<? extends BaseQueue> queues = exchange.route(responseMessage);
-
-
- for(BaseQueue q : queues)
- {
- try
- {
- q.enqueue(responseMessage);
- }
- catch (AMQException e)
- {
- e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
- }
- }
- }
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/qmf/QMFProperty.java b/java/broker/src/main/java/org/apache/qpid/qmf/QMFProperty.java
deleted file mode 100644
index 5748722afe..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/qmf/QMFProperty.java
+++ /dev/null
@@ -1,123 +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.qmf;
-
-import org.apache.qpid.transport.codec.Encoder;
-
-import java.util.Map;
-import java.util.HashMap;
-import java.util.LinkedHashMap;
-
-public class QMFProperty
-{
- private final Map<String, Object> _map = new LinkedHashMap<String, Object>();
- private static final String NAME = "name";
- private static final String TYPE = "type";
- private static final String ACCESS = "access";
- private static final String INDEX = "index";
- private static final String OPTIONAL = "optional";
- private static final String REF_PACKAGE = "refPackage";
- private static final String REF_CLASS = "refClass";
- private static final String UNIT = "unit";
- private static final String MIN = "min";
- private static final String MAX = "max";
- private static final String MAX_LENGTH = "maxlen";
- private static final String DESCRIPTION = "desc";
-
-
- public static enum AccessCode
- {
- RC,
- RW,
- RO;
-
- public int codeValue()
- {
- return ordinal()+1;
- }
- }
-
- public QMFProperty(String name, QMFType type, AccessCode accessCode, boolean index, boolean optional)
- {
- _map.put(NAME, name);
- _map.put(TYPE, type.codeValue());
- _map.put(ACCESS, accessCode.codeValue());
- _map.put(INDEX, index ? 1 : 0);
- _map.put(OPTIONAL, optional ? 1 :0);
- }
-
-
- public void setQMFClass(QMFClass qmfClass)
- {
- /* _map.put(REF_CLASS, qmfClass.getName());
- _map.put(REF_PACKAGE, qmfClass.getPackage().getName());*/
- }
-
- public void setReferencedClass(String refClass)
- {
- _map.put(REF_CLASS, refClass);
- }
-
- public void setReferencedPackage(String refPackage)
- {
- _map.put(REF_CLASS, refPackage);
- }
-
-
- public String getName()
- {
- return (String) _map.get(NAME);
- }
-
-
- public void setUnit(String unit)
- {
- _map.put(UNIT, unit);
- }
-
- public void setMin(Number min)
- {
- _map.put(MIN, min);
- }
-
- public void setMax(Number max)
- {
- _map.put(MAX, max);
- }
-
- public void setMaxLength(int maxlen)
- {
- _map.put(MAX_LENGTH, maxlen);
- }
-
-
- public void setDescription(String description)
- {
- _map.put(DESCRIPTION, description);
- }
-
- public void encode(Encoder encoder)
- {
- encoder.writeMap(_map);
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/qmf/QMFSchemaRequestCommand.java b/java/broker/src/main/java/org/apache/qpid/qmf/QMFSchemaRequestCommand.java
deleted file mode 100644
index 3141676f10..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/qmf/QMFSchemaRequestCommand.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.qmf;
-
-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.server.exchange.Exchange;
-import org.apache.qpid.server.queue.BaseQueue;
-import org.apache.qpid.AMQException;
-
-import java.util.Collection;
-import java.util.ArrayList;
-
-public class QMFSchemaRequestCommand extends QMFCommand
-{
- private final String _packageName;
- private final String _className;
- private final byte[] _hash;
-
- public QMFSchemaRequestCommand(QMFCommandHeader header, BBDecoder decoder)
- {
- super(header);
- _packageName = decoder.readStr8();
- _className = decoder.readStr8();
- _hash = decoder.readBin128();
- }
-
- public void process(VirtualHost virtualHost, ServerMessage message)
- {
- String exchangeName = message.getMessageHeader().getReplyToExchange();
- String routingKey = message.getMessageHeader().getReplyToRoutingKey();
-
- IApplicationRegistry appRegistry = virtualHost.getApplicationRegistry();
- QMFService service = appRegistry.getQMFService();
-
- QMFPackage qmfPackage = service.getPackage(_packageName);
- QMFClass qmfClass = qmfPackage.getQMFClass( _className );
-
- QMFCommand[] commands = new QMFCommand[2];
- commands[0] = new QMFSchemaResponseCommand(this, qmfClass);
- commands[ 1 ] = new QMFCommandCompletionCommand(this);
-
-
-
- Exchange exchange = virtualHost.getExchangeRegistry().getExchange(exchangeName);
-
- for(QMFCommand cmd : commands)
- {
- QMFMessage responseMessage = new QMFMessage(routingKey, cmd);
-
-
- ArrayList<? extends BaseQueue> queues = exchange.route(responseMessage);
-
- for(BaseQueue q : queues)
- {
- try
- {
- q.enqueue(responseMessage);
- }
- catch (AMQException e)
- {
- e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
- }
- }
- }
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/qmf/QMFSchemaResponseCommand.java b/java/broker/src/main/java/org/apache/qpid/qmf/QMFSchemaResponseCommand.java
deleted file mode 100644
index fea2430130..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/qmf/QMFSchemaResponseCommand.java
+++ /dev/null
@@ -1,83 +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.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;
-
-public class QMFSchemaResponseCommand extends QMFCommand
-{
- private final QMFClass _qmfClass;
-
-
- public QMFSchemaResponseCommand(QMFSchemaRequestCommand qmfSchemaRequestCommand, QMFClass qmfClass)
- {
- super(new QMFCommandHeader(qmfSchemaRequestCommand.getHeader().getVersion(),
- qmfSchemaRequestCommand.getHeader().getSeq(),
- QMFOperation.SCHEMA_RESPONSE));
- _qmfClass = qmfClass;
- }
-
- @Override
- public void encode(BBEncoder encoder)
- {
- super.encode(encoder);
- encoder.writeUint8(_qmfClass.getType().getValue());
- encoder.writeStr8(_qmfClass.getPackage().getName());
- encoder.writeStr8(_qmfClass.getName());
- encoder.writeBin128(_qmfClass.getSchemaHash());
-
- Collection<QMFProperty> props = _qmfClass.getProperties();
- Collection<QMFStatistic> stats = _qmfClass.getStatistics();
- Collection<QMFMethod> methods = _qmfClass.getMethods();
-
- encoder.writeUint16(props.size());
- if(_qmfClass.getType() == QMFClass.Type.OBJECT)
- {
- encoder.writeUint16(stats.size());
- encoder.writeUint16(methods.size());
- }
-
- for(QMFProperty prop : props)
- {
- prop.encode(encoder);
- }
-
- if(_qmfClass.getType() == QMFClass.Type.OBJECT)
- {
-
- for(QMFStatistic stat : stats)
- {
- stat.encode(encoder);
- }
-
- for(QMFMethod method : methods)
- {
- method.encode(encoder);
- }
- }
-
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/qmf/QMFService.java b/java/broker/src/main/java/org/apache/qpid/qmf/QMFService.java
deleted file mode 100644
index 5192d5be6f..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/qmf/QMFService.java
+++ /dev/null
@@ -1,1670 +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.qmf;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.common.Closeable;
-import org.apache.qpid.qmf.schema.BrokerSchema;
-import org.apache.qpid.server.configuration.*;
-import org.apache.qpid.server.registry.IApplicationRegistry;
-
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.UUID;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.CopyOnWriteArrayList;
-
-public class QMFService implements ConfigStore.ConfigEventListener, Closeable
-{
-
-
- private IApplicationRegistry _applicationRegistry;
- private ConfigStore _configStore;
-
-
- private final Map<String, QMFPackage> _supportedSchemas = new HashMap<String, QMFPackage>();
- private static final Map<String, ConfigObjectType> _qmfClassMapping = new HashMap<String, ConfigObjectType>();
-
- static
- {
- _qmfClassMapping.put("system", SystemConfigType.getInstance());
- _qmfClassMapping.put("broker", BrokerConfigType.getInstance());
- _qmfClassMapping.put("vhost", VirtualHostConfigType.getInstance());
- _qmfClassMapping.put("exchange", ExchangeConfigType.getInstance());
- _qmfClassMapping.put("queue", QueueConfigType.getInstance());
- _qmfClassMapping.put("binding", BindingConfigType.getInstance());
- _qmfClassMapping.put("connection", ConnectionConfigType.getInstance());
- _qmfClassMapping.put("session", SessionConfigType.getInstance());
- _qmfClassMapping.put("subscription", SubscriptionConfigType.getInstance());
- _qmfClassMapping.put("link", LinkConfigType.getInstance());
- _qmfClassMapping.put("bridge", BridgeConfigType.getInstance());
- }
-
- private final Map<ConfigObjectType, ConfigObjectAdapter> _adapterMap =
- new HashMap<ConfigObjectType, ConfigObjectAdapter>();
- private final Map<ConfigObjectType,QMFClass> _classMap =
- new HashMap<ConfigObjectType,QMFClass>();
-
-
- private final ConcurrentHashMap<QMFClass,ConcurrentHashMap<ConfiguredObject, QMFObject>> _managedObjects =
- new ConcurrentHashMap<QMFClass,ConcurrentHashMap<ConfiguredObject, QMFObject>>();
-
- private final ConcurrentHashMap<QMFClass,ConcurrentHashMap<UUID, QMFObject>> _managedObjectsById =
- new ConcurrentHashMap<QMFClass,ConcurrentHashMap<UUID, QMFObject>>();
-
- private static final BrokerSchema PACKAGE = BrokerSchema.getPackage();
-
- public static interface Listener
- {
- public void objectCreated(QMFObject obj);
- public void objectDeleted(QMFObject obj);
- }
-
- private final CopyOnWriteArrayList<Listener> _listeners = new CopyOnWriteArrayList<Listener>();
-
- abstract class ConfigObjectAdapter<Q extends QMFObject<S,D>, S extends QMFObjectClass<Q,D>, D extends QMFObject.Delegate, T extends ConfigObjectType<T,C>, C extends ConfiguredObject<T,C>>
- {
- private final T _type;
- private final S _qmfClass;
-
-
- protected ConfigObjectAdapter(final T type, final S qmfClass)
- {
- _type = type;
- _qmfClass = qmfClass;
- _adapterMap.put(type,this);
- _classMap.put(type,qmfClass);
- }
-
- public T getType()
- {
- return _type;
- }
-
- public S getQMFClass()
- {
- return _qmfClass;
- }
-
- protected final Q newInstance(D delegate)
- {
- return _qmfClass.newInstance(delegate);
- }
-
- public abstract Q createQMFObject(C configObject);
- }
-
- private ConfigObjectAdapter<BrokerSchema.SystemObject,
- BrokerSchema.SystemClass,
- BrokerSchema.SystemDelegate,
- SystemConfigType,
- SystemConfig> _systemObjectAdapter =
- new ConfigObjectAdapter<BrokerSchema.SystemObject,
- BrokerSchema.SystemClass,
- BrokerSchema.SystemDelegate,
- SystemConfigType,
- SystemConfig>(SystemConfigType.getInstance(),
- PACKAGE.getQMFClassInstance(BrokerSchema.SystemClass.class))
- {
-
-
- public BrokerSchema.SystemObject createQMFObject(
- final SystemConfig configObject)
- {
- return newInstance(new SystemDelegate(configObject));
- }
- };
-
- private ConfigObjectAdapter<BrokerSchema.BrokerObject,
- BrokerSchema.BrokerClass,
- BrokerSchema.BrokerDelegate,
- BrokerConfigType,
- BrokerConfig> _brokerObjectAdapter =
- new ConfigObjectAdapter<BrokerSchema.BrokerObject,
- BrokerSchema.BrokerClass,
- BrokerSchema.BrokerDelegate,
- BrokerConfigType,
- BrokerConfig>(BrokerConfigType.getInstance(),
- PACKAGE.getQMFClassInstance(BrokerSchema.BrokerClass.class))
- {
-
- public BrokerSchema.BrokerObject createQMFObject(
- final BrokerConfig configObject)
- {
- return newInstance(new BrokerDelegate(configObject));
- }
- };
-
- private ConfigObjectAdapter<BrokerSchema.VhostObject,
- BrokerSchema.VhostClass,
- BrokerSchema.VhostDelegate,
- VirtualHostConfigType,
- VirtualHostConfig> _vhostObjectAdapter =
- new ConfigObjectAdapter<BrokerSchema.VhostObject,
- BrokerSchema.VhostClass,
- BrokerSchema.VhostDelegate,
- VirtualHostConfigType,
- VirtualHostConfig>(VirtualHostConfigType.getInstance(),
- PACKAGE.getQMFClassInstance(BrokerSchema.VhostClass.class))
- {
-
- public BrokerSchema.VhostObject createQMFObject(
- final VirtualHostConfig configObject)
- {
- return newInstance(new VhostDelegate(configObject));
- }
- };
-
-
- private ConfigObjectAdapter<BrokerSchema.ExchangeObject,
- BrokerSchema.ExchangeClass,
- BrokerSchema.ExchangeDelegate,
- ExchangeConfigType,
- ExchangeConfig> _exchangeObjectAdapter =
- new ConfigObjectAdapter<BrokerSchema.ExchangeObject,
- BrokerSchema.ExchangeClass,
- BrokerSchema.ExchangeDelegate,
- ExchangeConfigType,
- ExchangeConfig>(ExchangeConfigType.getInstance(),
- PACKAGE.getQMFClassInstance(BrokerSchema.ExchangeClass.class))
- {
-
- public BrokerSchema.ExchangeObject createQMFObject(
- final ExchangeConfig configObject)
- {
- return newInstance(new ExchangeDelegate(configObject));
- }
- };
-
-
- private ConfigObjectAdapter<BrokerSchema.QueueObject,
- BrokerSchema.QueueClass,
- BrokerSchema.QueueDelegate,
- QueueConfigType,
- QueueConfig> _queueObjectAdapter =
- new ConfigObjectAdapter<BrokerSchema.QueueObject,
- BrokerSchema.QueueClass,
- BrokerSchema.QueueDelegate,
- QueueConfigType,
- QueueConfig>(QueueConfigType.getInstance(),
- PACKAGE.getQMFClassInstance(BrokerSchema.QueueClass.class))
- {
-
- public BrokerSchema.QueueObject createQMFObject(
- final QueueConfig configObject)
- {
- return newInstance(new QueueDelegate(configObject));
- }
- };
-
-
- private ConfigObjectAdapter<BrokerSchema.BindingObject,
- BrokerSchema.BindingClass,
- BrokerSchema.BindingDelegate,
- BindingConfigType,
- BindingConfig> _bindingObjectAdapter =
- new ConfigObjectAdapter<BrokerSchema.BindingObject,
- BrokerSchema.BindingClass,
- BrokerSchema.BindingDelegate,
- BindingConfigType,
- BindingConfig>(BindingConfigType.getInstance(),
- PACKAGE.getQMFClassInstance(BrokerSchema.BindingClass.class))
- {
-
- public BrokerSchema.BindingObject createQMFObject(
- final BindingConfig configObject)
- {
- return newInstance(new BindingDelegate(configObject));
- }
- };
-
-
- private ConfigObjectAdapter<BrokerSchema.ConnectionObject,
- BrokerSchema.ConnectionClass,
- BrokerSchema.ConnectionDelegate,
- ConnectionConfigType,
- ConnectionConfig> _connectionObjectAdapter =
- new ConfigObjectAdapter<BrokerSchema.ConnectionObject,
- BrokerSchema.ConnectionClass,
- BrokerSchema.ConnectionDelegate,
- ConnectionConfigType,
- ConnectionConfig>(ConnectionConfigType.getInstance(),
- PACKAGE.getQMFClassInstance(BrokerSchema.ConnectionClass.class))
- {
-
- public BrokerSchema.ConnectionObject createQMFObject(
- final ConnectionConfig configObject)
- {
- return newInstance(new ConnectionDelegate(configObject));
- }
- };
-
-
- private ConfigObjectAdapter<BrokerSchema.SessionObject,
- BrokerSchema.SessionClass,
- BrokerSchema.SessionDelegate,
- SessionConfigType,
- SessionConfig> _sessionObjectAdapter =
- new ConfigObjectAdapter<BrokerSchema.SessionObject,
- BrokerSchema.SessionClass,
- BrokerSchema.SessionDelegate,
- SessionConfigType,
- SessionConfig>(SessionConfigType.getInstance(),
- PACKAGE.getQMFClassInstance(BrokerSchema.SessionClass.class))
- {
-
- public BrokerSchema.SessionObject createQMFObject(
- final SessionConfig configObject)
- {
- return newInstance(new SessionDelegate(configObject));
- }
- };
-
- private ConfigObjectAdapter<BrokerSchema.SubscriptionObject,
- BrokerSchema.SubscriptionClass,
- BrokerSchema.SubscriptionDelegate,
- SubscriptionConfigType,
- SubscriptionConfig> _subscriptionObjectAdapter =
- new ConfigObjectAdapter<BrokerSchema.SubscriptionObject,
- BrokerSchema.SubscriptionClass,
- BrokerSchema.SubscriptionDelegate,
- SubscriptionConfigType,
- SubscriptionConfig>(SubscriptionConfigType.getInstance(),
- PACKAGE.getQMFClassInstance(BrokerSchema.SubscriptionClass.class))
- {
-
- public BrokerSchema.SubscriptionObject createQMFObject(
- final SubscriptionConfig configObject)
- {
- return newInstance(new SubscriptionDelegate(configObject));
- }
- };
-
-
- private ConfigObjectAdapter<BrokerSchema.LinkObject,
- BrokerSchema.LinkClass,
- BrokerSchema.LinkDelegate,
- LinkConfigType,
- LinkConfig> _linkObjectAdapter =
- new ConfigObjectAdapter<BrokerSchema.LinkObject,
- BrokerSchema.LinkClass,
- BrokerSchema.LinkDelegate,
- LinkConfigType,
- LinkConfig>(LinkConfigType.getInstance(),
- PACKAGE.getQMFClassInstance(BrokerSchema.LinkClass.class))
- {
-
- public BrokerSchema.LinkObject createQMFObject(
- final LinkConfig configObject)
- {
- return newInstance(new LinkDelegate(configObject));
- }
- };
-
-
- private ConfigObjectAdapter<BrokerSchema.BridgeObject,
- BrokerSchema.BridgeClass,
- BrokerSchema.BridgeDelegate,
- BridgeConfigType,
- BridgeConfig> _bridgeObjectAdapter =
- new ConfigObjectAdapter<BrokerSchema.BridgeObject,
- BrokerSchema.BridgeClass,
- BrokerSchema.BridgeDelegate,
- BridgeConfigType,
- BridgeConfig>(BridgeConfigType.getInstance(),
- PACKAGE.getQMFClassInstance(BrokerSchema.BridgeClass.class))
- {
-
- public BrokerSchema.BridgeObject createQMFObject(
- final BridgeConfig configObject)
- {
- return newInstance(new BridgeDelegate(configObject));
- }
- };
-
-
-
- public QMFService(ConfigStore configStore, IApplicationRegistry applicationRegistry)
- {
- _configStore = configStore;
- _applicationRegistry = applicationRegistry;
- registerSchema(PACKAGE);
-
- for(ConfigObjectType v : _qmfClassMapping.values())
- {
- configStore.addConfigEventListener(v, this);
- }
- init();
- }
-
- public void close()
- {
- for(ConfigObjectType v : _qmfClassMapping.values())
- {
- _configStore.removeConfigEventListener(v, this);
- }
- _listeners.clear();
-
- _managedObjects.clear();
- _managedObjectsById.clear();
- _classMap.clear();
- _adapterMap.clear();
- _supportedSchemas.clear();
- }
-
-
- public void registerSchema(QMFPackage qmfPackage)
- {
- _supportedSchemas.put(qmfPackage.getName(), qmfPackage);
- }
-
-
- public Collection<QMFPackage> getSupportedSchemas()
- {
- return _supportedSchemas.values();
- }
-
- public QMFPackage getPackage(String aPackage)
- {
- return _supportedSchemas.get(aPackage);
- }
-
- public void onEvent(final ConfiguredObject object, final ConfigStore.Event evt)
- {
-
- switch (evt)
- {
- case CREATED:
- manageObject(object);
- break;
-
- case DELETED:
- unmanageObject(object);
- break;
- }
- }
-
- public QMFObject getObjectById(QMFClass qmfclass, UUID id)
- {
- ConcurrentHashMap<UUID, QMFObject> map = _managedObjectsById.get(qmfclass);
- if(map != null)
- {
- return map.get(id);
- }
- else
- {
- return null;
- }
- }
-
- private void unmanageObject(final ConfiguredObject object)
- {
- final QMFClass qmfClass = _classMap.get(object.getConfigType());
-
- if(qmfClass == null)
- {
- return;
- }
-
- ConcurrentHashMap<ConfiguredObject, QMFObject> classObjects = _managedObjects.get(qmfClass);
- if(classObjects != null)
- {
- QMFObject qmfObject = classObjects.remove(object);
- if(qmfObject != null)
- {
- _managedObjectsById.get(qmfClass).remove(object.getId());
- objectRemoved(qmfObject);
- }
- }
- }
-
- private void manageObject(final ConfiguredObject object)
- {
- ConfigObjectAdapter adapter = _adapterMap.get(object.getConfigType());
- QMFObject qmfObject = adapter.createQMFObject(object);
- final QMFClass qmfClass = qmfObject.getQMFClass();
- ConcurrentHashMap<ConfiguredObject, QMFObject> classObjects = _managedObjects.get(qmfClass);
-
- if(classObjects == null)
- {
- classObjects = new ConcurrentHashMap<ConfiguredObject, QMFObject>();
- if(_managedObjects.putIfAbsent(qmfClass, classObjects) != null)
- {
- classObjects = _managedObjects.get(qmfClass);
- }
- }
-
- ConcurrentHashMap<UUID, QMFObject> classObjectsById = _managedObjectsById.get(qmfClass);
- if(classObjectsById == null)
- {
- classObjectsById = new ConcurrentHashMap<UUID, QMFObject>();
- if(_managedObjectsById.putIfAbsent(qmfClass, classObjectsById) != null)
- {
- classObjectsById = _managedObjectsById.get(qmfClass);
- }
- }
-
- classObjectsById.put(object.getId(),qmfObject);
-
- if(classObjects.putIfAbsent(object, qmfObject) == null)
- {
- objectAdded(qmfObject);
- }
- }
-
- private void objectRemoved(final QMFObject qmfObject)
- {
- qmfObject.setDeleteTime();
- for(Listener l : _listeners)
- {
- l.objectDeleted(qmfObject);
- }
- }
-
- private void objectAdded(final QMFObject qmfObject)
- {
- for(Listener l : _listeners)
- {
- l.objectCreated(qmfObject);
- }
- }
-
- public void addListener(Listener l)
- {
- _listeners.add(l);
- }
-
- public void removeListener(Listener l)
- {
- _listeners.remove(l);
- }
-
-
- private void init()
- {
- for(QMFClass qmfClass : PACKAGE.getClasses())
- {
- ConfigObjectType configType = getConfigType(qmfClass);
- if(configType != null)
- {
- Collection<ConfiguredObject> objects = _configStore.getConfiguredObjects(configType);
- for(ConfiguredObject object : objects)
- {
- manageObject(object);
- }
- }
- }
- }
-
- public Collection<QMFObject> getObjects(QMFClass qmfClass)
- {
- ConcurrentHashMap<ConfiguredObject, QMFObject> classObjects = _managedObjects.get(qmfClass);
- if(classObjects != null)
- {
- return classObjects.values();
- }
- else
- {
- return Collections.EMPTY_SET;
- }
- }
-
- private QMFObject adapt(final ConfiguredObject object)
- {
- if(object == null)
- {
- return null;
- }
-
- QMFClass qmfClass = _classMap.get(object.getConfigType());
- ConcurrentHashMap<ConfiguredObject, QMFObject> classObjects = _managedObjects.get(qmfClass);
- if(classObjects != null)
- {
- QMFObject qmfObject = classObjects.get(object);
- if(qmfObject != null)
- {
- return qmfObject;
- }
- }
-
- return _adapterMap.get(object.getConfigType()).createQMFObject(object);
- }
-
- private ConfigObjectType getConfigType(final QMFClass qmfClass)
- {
- return _qmfClassMapping.get(qmfClass.getName());
- }
-
- private static class SystemDelegate implements BrokerSchema.SystemDelegate
- {
- private final SystemConfig _obj;
-
- public SystemDelegate(final SystemConfig obj)
- {
- _obj = obj;
- }
-
- public UUID getSystemId()
- {
- return _obj.getId();
- }
-
- public String getOsName()
- {
- return _obj.getOperatingSystemName();
- }
-
- public String getNodeName()
- {
- return _obj.getNodeName();
- }
-
- public String getRelease()
- {
- return _obj.getOSRelease();
- }
-
- public String getVersion()
- {
- return _obj.getOSVersion();
- }
-
- public String getMachine()
- {
- return _obj.getOSArchitecture();
- }
-
- public UUID getId()
- {
- return _obj.getId();
- }
-
- public long getCreateTime()
- {
- return _obj.getCreateTime();
- }
- }
-
- private class BrokerDelegate implements BrokerSchema.BrokerDelegate
- {
- private final BrokerConfig _obj;
-
- public BrokerDelegate(final BrokerConfig obj)
- {
- _obj = obj;
- }
-
- public BrokerSchema.SystemObject getSystemRef()
- {
- return (BrokerSchema.SystemObject) adapt(_obj.getSystem());
- }
-
- public String getName()
- {
- return "amqp-broker";
- }
-
- public Integer getPort()
- {
- return _obj.getPort();
- }
-
- public Integer getWorkerThreads()
- {
- return _obj.getWorkerThreads();
- }
-
- public Integer getMaxConns()
- {
- return _obj.getMaxConnections();
- }
-
- public Integer getConnBacklog()
- {
- return _obj.getConnectionBacklogLimit();
- }
-
- public Long getStagingThreshold()
- {
- return _obj.getStagingThreshold();
- }
-
- public Integer getMgmtPubInterval()
- {
- return _obj.getManagementPublishInterval();
- }
-
- public String getVersion()
- {
- return _obj.getVersion();
- }
-
- public String getDataDir()
- {
- return _obj.getDataDirectory();
- }
-
- public Long getUptime()
- {
- return (System.currentTimeMillis() - _obj.getCreateTime()) * 1000000L;
- }
-
- public BrokerSchema.BrokerClass.EchoMethodResponseCommand echo(final BrokerSchema.BrokerClass.EchoMethodResponseCommandFactory factory,
- final Long sequence,
- final String body)
- {
- return factory.createResponseCommand(sequence, body);
- }
-
- public BrokerSchema.BrokerClass.ConnectMethodResponseCommand connect(final BrokerSchema.BrokerClass.ConnectMethodResponseCommandFactory factory,
- final String host,
- final Long port,
- final Boolean durable,
- final String authMechanism,
- final String username,
- final String password,
- final String transport)
- {
- _obj.createBrokerConnection(transport, host, port.intValue(), durable, authMechanism, username, password);
-
- return factory.createResponseCommand();
- }
-
- public BrokerSchema.BrokerClass.QueueMoveMessagesMethodResponseCommand queueMoveMessages(final BrokerSchema.BrokerClass.QueueMoveMessagesMethodResponseCommandFactory factory,
- final String srcQueue,
- final String destQueue,
- final Long qty)
- {
- // TODO
- return factory.createResponseCommand(CompletionCode.NOT_IMPLEMENTED);
- }
-
- public BrokerSchema.BrokerClass.GetLogLevelMethodResponseCommand getLogLevel(final BrokerSchema.BrokerClass.GetLogLevelMethodResponseCommandFactory factory)
- {
- // TODO: The Java broker has numerous loggers, so we can't really implement this method properly.
- return factory.createResponseCommand(CompletionCode.NOT_IMPLEMENTED);
- }
-
- public BrokerSchema.BrokerClass.SetLogLevelMethodResponseCommand setLogLevel(final BrokerSchema.BrokerClass.SetLogLevelMethodResponseCommandFactory factory, String level)
- {
- // TODO: The Java broker has numerous loggers, so we can't really implement this method properly.
- return factory.createResponseCommand(CompletionCode.NOT_IMPLEMENTED);
- }
-
- public BrokerSchema.BrokerClass.CreateMethodResponseCommand create(final BrokerSchema.BrokerClass.CreateMethodResponseCommandFactory factory,
- final String type,
- final String name,
- final Map properties,
- final java.lang.Boolean lenient)
- {
- //TODO:
- return factory.createResponseCommand(CompletionCode.NOT_IMPLEMENTED);
- }
-
- public BrokerSchema.BrokerClass.DeleteMethodResponseCommand delete(final BrokerSchema.BrokerClass.DeleteMethodResponseCommandFactory factory,
- final String type,
- final String name,
- final Map options)
- {
- //TODO:
- return factory.createResponseCommand(CompletionCode.NOT_IMPLEMENTED);
- }
-
- public UUID getId()
- {
- return _obj.getId();
- }
-
- public long getCreateTime()
- {
- return _obj.getCreateTime();
- }
- }
-
- private class VhostDelegate implements BrokerSchema.VhostDelegate
- {
- private final VirtualHostConfig _obj;
-
- public VhostDelegate(final VirtualHostConfig obj)
- {
- _obj = obj;
- }
-
- public BrokerSchema.BrokerObject getBrokerRef()
- {
- return (BrokerSchema.BrokerObject) adapt(_obj.getBroker());
- }
-
- public String getName()
- {
- return _obj.getName();
- }
-
- public String getFederationTag()
- {
- return _obj.getFederationTag();
- }
-
- public UUID getId()
- {
- return _obj.getId();
- }
-
- public long getCreateTime()
- {
- return _obj.getCreateTime();
- }
- }
-
- private class ExchangeDelegate implements BrokerSchema.ExchangeDelegate
- {
- private final ExchangeConfig _obj;
-
- public ExchangeDelegate(final ExchangeConfig obj)
- {
- _obj = obj;
- }
-
- public BrokerSchema.VhostObject getVhostRef()
- {
- return (BrokerSchema.VhostObject) adapt(_obj.getVirtualHost());
- }
-
- public String getName()
- {
- return _obj.getName();
- }
-
- public String getType()
- {
- return _obj.getType().getName().toString();
- }
-
- public Boolean getDurable()
- {
- return _obj.isDurable();
- }
-
- public Boolean getAutoDelete()
- {
- return _obj.isAutoDelete();
- }
-
- public BrokerSchema.ExchangeObject getAltExchange()
- {
- if(_obj.getAlternateExchange() != null)
- {
- return (BrokerSchema.ExchangeObject) adapt(_obj.getAlternateExchange());
- }
- else
- {
- return null;
- }
- }
-
- public Map getArguments()
- {
- return _obj.getArguments();
- }
-
- public Long getProducerCount()
- {
- // TODO
- return 0l;
- }
-
- public Long getProducerCountHigh()
- {
- // TODO
- return 0l;
- }
-
- public Long getProducerCountLow()
- {
- // TODO
- return 0l;
- }
-
- public Long getBindingCount()
- {
- return _obj.getBindingCount();
- }
-
- public Long getBindingCountHigh()
- {
- return _obj.getBindingCountHigh();
- }
-
- public Long getBindingCountLow()
- {
- // TODO
- return 0l;
- }
-
- public Long getMsgReceives()
- {
- return _obj.getMsgReceives();
- }
-
- public Long getMsgDrops()
- {
- return getMsgReceives() - getMsgRoutes();
- }
-
- public Long getMsgRoutes()
- {
- return _obj.getMsgRoutes();
- }
-
- public Long getByteReceives()
- {
- return _obj.getByteReceives();
- }
-
- public Long getByteDrops()
- {
- return getByteReceives() - getByteRoutes();
- }
-
- public Long getByteRoutes()
- {
- return _obj.getByteRoutes();
- }
-
- public UUID getId()
- {
- return _obj.getId();
- }
-
- public long getCreateTime()
- {
- return _obj.getCreateTime();
- }
- }
-
- private class QueueDelegate implements BrokerSchema.QueueDelegate
- {
- private final QueueConfig _obj;
-
- public QueueDelegate(final QueueConfig obj)
- {
- _obj = obj;
- }
-
- public BrokerSchema.VhostObject getVhostRef()
- {
- return (BrokerSchema.VhostObject) adapt(_obj.getVirtualHost());
- }
-
- public String getName()
- {
- return _obj.getName();
- }
-
- public Boolean getDurable()
- {
- return _obj.isDurable();
- }
-
- public Boolean getAutoDelete()
- {
- return _obj.isAutoDelete();
- }
-
- public Boolean getExclusive()
- {
- return _obj.isExclusive();
- }
-
- public BrokerSchema.ExchangeObject getAltExchange()
- {
- if(_obj.getAlternateExchange() != null)
- {
- return (BrokerSchema.ExchangeObject) adapt(_obj.getAlternateExchange());
- }
- else
- {
- return null;
- }
- }
-
- public Long getMsgTotalEnqueues()
- {
- return _obj.getReceivedMessageCount();
- }
-
- public Long getMsgTotalDequeues()
- {
- return _obj.getMessageDequeueCount();
- }
-
- public Long getMsgTxnEnqueues()
- {
- return _obj.getMsgTxnEnqueues();
- }
-
- public Long getMsgTxnDequeues()
- {
- return _obj.getMsgTxnDequeues();
- }
-
- public Long getMsgPersistEnqueues()
- {
- return _obj.getPersistentMsgEnqueues();
- }
-
- public Long getMsgPersistDequeues()
- {
- return _obj.getPersistentMsgDequeues();
- }
-
- public Long getMsgDepth()
- {
- return (long) _obj.getMessageCount();
- }
-
- public Long getByteDepth()
- {
- return _obj.getQueueDepth();
- }
-
- public Long getByteTotalEnqueues()
- {
- return _obj.getTotalEnqueueSize();
- }
-
- public Long getByteTotalDequeues()
- {
- return _obj.getTotalDequeueSize();
- }
-
- public Long getByteTxnEnqueues()
- {
- return _obj.getByteTxnEnqueues();
- }
-
- public Long getByteTxnDequeues()
- {
- return _obj.getByteTxnDequeues();
- }
-
- public Long getBytePersistEnqueues()
- {
- return _obj.getPersistentByteEnqueues();
- }
-
- public Long getBytePersistDequeues()
- {
- return _obj.getPersistentByteDequeues();
- }
-
- public Long getConsumerCount()
- {
- return (long) _obj.getConsumerCount();
- }
-
- public Long getConsumerCountHigh()
- {
- return (long) _obj.getConsumerCountHigh();
- }
-
- public Long getConsumerCountLow()
- {
- // TODO
- return 0l;
- }
-
- public Long getBindingCount()
- {
- return (long) _obj.getBindingCount();
- }
-
- public Long getBindingCountHigh()
- {
- return (long) _obj.getBindingCountHigh();
- }
-
- public Long getBindingCountLow()
- {
- // TODO
- return 0l;
- }
-
- public Long getUnackedMessages()
- {
- return _obj.getUnackedMessageCount();
- }
-
- public Long getUnackedMessagesHigh()
- {
- return _obj.getUnackedMessageCountHigh();
- }
-
- public Long getUnackedMessagesLow()
- {
- // TODO
- return 0l;
- }
-
- public Long getMessageLatencySamples()
- {
- // TODO
- return 0l;
- }
-
- public Long getMessageLatencyMin()
- {
- // TODO
- return 0l;
- }
-
- public Long getMessageLatencyMax()
- {
- // TODO
- return 0l;
- }
-
- public Long getMessageLatencyAverage()
- {
- // TODO
- return 0l;
- }
-
- public Boolean getFlowStopped()
- {
- return Boolean.FALSE;
- }
-
- public Long getFlowStoppedCount()
- {
- return 0L;
- }
-
- public BrokerSchema.QueueClass.PurgeMethodResponseCommand purge(final BrokerSchema.QueueClass.PurgeMethodResponseCommandFactory factory,
- final Long request)
- {
- try
- {
- _obj.purge(request);
- } catch (AMQException e)
- {
- // TODO
- throw new RuntimeException();
- }
- return factory.createResponseCommand();
- }
-
- public BrokerSchema.QueueClass.RerouteMethodResponseCommand reroute(final BrokerSchema.QueueClass.RerouteMethodResponseCommandFactory factory,
- final Long request,
- final Boolean useAltExchange,
- final String exchange)
- {
- //TODO
- return factory.createResponseCommand(CompletionCode.NOT_IMPLEMENTED);
- }
-
-
- public Map getArguments()
- {
- return _obj.getArguments();
- }
-
- public UUID getId()
- {
- return _obj.getId();
- }
-
- public long getCreateTime()
- {
- return _obj.getCreateTime();
- }
- }
-
- private class BindingDelegate implements BrokerSchema.BindingDelegate
- {
- private final BindingConfig _obj;
-
- public BindingDelegate(final BindingConfig obj)
- {
- _obj = obj;
- }
-
- public BrokerSchema.ExchangeObject getExchangeRef()
- {
- return (BrokerSchema.ExchangeObject) adapt(_obj.getExchange());
- }
-
- public BrokerSchema.QueueObject getQueueRef()
- {
- return (BrokerSchema.QueueObject) adapt(_obj.getQueue());
- }
-
- public String getBindingKey()
- {
- return _obj.getBindingKey();
- }
-
- public Map getArguments()
- {
- return _obj.getArguments();
- }
-
- public String getOrigin()
- {
- return _obj.getOrigin();
- }
-
- public Long getMsgMatched()
- {
- // TODO
- return _obj.getMatches();
- }
-
- public UUID getId()
- {
- return _obj.getId();
- }
-
- public long getCreateTime()
- {
- return _obj.getCreateTime();
- }
- }
-
- private class ConnectionDelegate implements BrokerSchema.ConnectionDelegate
- {
- private final ConnectionConfig _obj;
-
- public ConnectionDelegate(final ConnectionConfig obj)
- {
- _obj = obj;
- }
-
- public BrokerSchema.VhostObject getVhostRef()
- {
- return (BrokerSchema.VhostObject) adapt(_obj.getVirtualHost());
- }
-
- public String getAddress()
- {
- return _obj.getAddress();
- }
-
- public Boolean getIncoming()
- {
- return _obj.isIncoming();
- }
-
- public Boolean getSystemConnection()
- {
- return _obj.isSystemConnection();
- }
-
- public Boolean getFederationLink()
- {
- return _obj.isFederationLink();
- }
-
- public String getAuthIdentity()
- {
- return _obj.getAuthId();
- }
-
- public String getRemoteProcessName()
- {
- return _obj.getRemoteProcessName();
- }
-
- public Long getRemotePid()
- {
- Integer remotePID = _obj.getRemotePID();
- return remotePID == null ? null : (long) remotePID;
- }
-
- public Long getRemoteParentPid()
- {
- Integer remotePPID = _obj.getRemoteParentPID();
- return remotePPID == null ? null : (long) remotePPID;
-
- }
-
- public Boolean getClosing()
- {
- return false;
- }
-
- public Long getFramesFromClient()
- {
- // TODO
- return 0l;
- }
-
- public Long getFramesToClient()
- {
- // TODO
- return 0l;
- }
-
- public Long getBytesFromClient()
- {
- // TODO
- return 0l;
- }
-
- public Long getBytesToClient()
- {
- // TODO
- return 0l;
- }
-
- public Long getMsgsFromClient()
- {
- // TODO
- return 0l;
- }
-
- public Long getMsgsToClient()
- {
- // TODO
- return 0l;
- }
-
- public BrokerSchema.ConnectionClass.CloseMethodResponseCommand close(final BrokerSchema.ConnectionClass.CloseMethodResponseCommandFactory factory)
- {
- _obj.mgmtClose();
-
- return factory.createResponseCommand();
- }
-
- public UUID getId()
- {
- return _obj.getId();
- }
-
- public long getCreateTime()
- {
- return _obj.getCreateTime();
- }
-
- public Boolean getShadow()
- {
- return _obj.isShadow();
- }
- }
-
- private class SessionDelegate implements BrokerSchema.SessionDelegate
- {
- private final SessionConfig _obj;
-
- public SessionDelegate(final SessionConfig obj)
- {
- _obj = obj;
- }
-
- public BrokerSchema.VhostObject getVhostRef()
- {
- return (BrokerSchema.VhostObject) adapt(_obj.getVirtualHost());
- }
-
- public String getName()
- {
- return _obj.getSessionName();
- }
-
- public Integer getChannelId()
- {
- return _obj.getChannel();
- }
-
- public BrokerSchema.ConnectionObject getConnectionRef()
- {
- return (BrokerSchema.ConnectionObject) adapt(_obj.getConnectionConfig());
- }
-
- public Long getDetachedLifespan()
- {
- return _obj.getDetachedLifespan();
- }
-
- public Boolean getAttached()
- {
- return _obj.isAttached();
- }
-
- public Long getExpireTime()
- {
- return _obj.getExpiryTime();
- }
-
- public Long getMaxClientRate()
- {
- return _obj.getMaxClientRate();
- }
-
- public Long getFramesOutstanding()
- {
- // TODO
- return 0l;
- }
-
- public Long getTxnStarts()
- {
- return _obj.getTxnStarts();
- }
-
- public Long getTxnCommits()
- {
- return _obj.getTxnCommits();
- }
-
- public Long getTxnRejects()
- {
- return _obj.getTxnRejects();
- }
-
- public Long getTxnCount()
- {
- return _obj.getTxnCount();
- }
-
- public Long getClientCredit()
- {
- // TODO
- return 0l;
- }
-
- public BrokerSchema.SessionClass.SolicitAckMethodResponseCommand solicitAck(final BrokerSchema.SessionClass.SolicitAckMethodResponseCommandFactory factory)
- {
- //TODO
- return factory.createResponseCommand(CompletionCode.NOT_IMPLEMENTED);
- }
-
- public BrokerSchema.SessionClass.DetachMethodResponseCommand detach(final BrokerSchema.SessionClass.DetachMethodResponseCommandFactory factory)
- {
- //TODO
- return factory.createResponseCommand(CompletionCode.NOT_IMPLEMENTED);
- }
-
- public BrokerSchema.SessionClass.ResetLifespanMethodResponseCommand resetLifespan(final BrokerSchema.SessionClass.ResetLifespanMethodResponseCommandFactory factory)
- {
- //TODO
- return factory.createResponseCommand(CompletionCode.NOT_IMPLEMENTED);
- }
-
- public BrokerSchema.SessionClass.CloseMethodResponseCommand close(final BrokerSchema.SessionClass.CloseMethodResponseCommandFactory factory)
- {
- try
- {
- _obj.mgmtClose();
- }
- catch (AMQException e)
- {
- return factory.createResponseCommand(CompletionCode.EXCEPTION, e.getMessage());
- }
-
- return factory.createResponseCommand();
- }
-
- public UUID getId()
- {
- return _obj.getId();
- }
-
- public long getCreateTime()
- {
- return _obj.getCreateTime();
- }
- }
-
- private class SubscriptionDelegate implements BrokerSchema.SubscriptionDelegate
- {
- private final SubscriptionConfig _obj;
-
- private SubscriptionDelegate(final SubscriptionConfig obj)
- {
- _obj = obj;
- }
-
-
- public BrokerSchema.SessionObject getSessionRef()
- {
- return (BrokerSchema.SessionObject) adapt(_obj.getSessionConfig());
- }
-
- public BrokerSchema.QueueObject getQueueRef()
- {
- return (BrokerSchema.QueueObject) adapt(_obj.getQueue());
- }
-
- public String getName()
- {
- return _obj.getName();
- }
-
- public Boolean getBrowsing()
- {
- return _obj.isBrowsing();
- }
-
- public Boolean getAcknowledged()
- {
- return _obj.isExplicitAcknowledge();
- }
-
- public Boolean getExclusive()
- {
- return _obj.isExclusive();
- }
-
- public String getCreditMode()
- {
- return _obj.getCreditMode();
- }
-
- public Map getArguments()
- {
- return _obj.getArguments();
- }
-
- public Long getDelivered()
- {
- return _obj.getDelivered();
- }
-
- public UUID getId()
- {
- return _obj.getId();
- }
-
- public long getCreateTime()
- {
- return _obj.getCreateTime();
- }
- }
-
- private class BridgeDelegate implements BrokerSchema.BridgeDelegate
- {
- private final BridgeConfig _obj;
-
- private BridgeDelegate(final BridgeConfig obj)
- {
- _obj = obj;
- }
-
- public BrokerSchema.LinkObject getLinkRef()
- {
- return (BrokerSchema.LinkObject) adapt(_obj.getLink());
- }
-
- public Integer getChannelId()
- {
- return _obj.getChannelId();
- }
-
- public Boolean getDurable()
- {
- return _obj.isDurable();
- }
-
- public String getSrc()
- {
- return _obj.getSource();
- }
-
- public String getDest()
- {
- return _obj.getDestination();
- }
-
- public String getKey()
- {
- return _obj.getKey();
- }
-
- public Boolean getSrcIsQueue()
- {
- return _obj.isQueueBridge();
- }
-
- public Boolean getSrcIsLocal()
- {
- return _obj.isLocalSource();
- }
-
- public String getTag()
- {
- return _obj.getTag();
- }
-
- public String getExcludes()
- {
- return _obj.getExcludes();
- }
-
- public Boolean getDynamic()
- {
- return _obj.isDynamic();
- }
-
- public Integer getSync()
- {
- return _obj.getAckBatching();
- }
-
- public BrokerSchema.BridgeClass.CloseMethodResponseCommand close(final BrokerSchema.BridgeClass.CloseMethodResponseCommandFactory factory)
- {
- return null;
- }
-
- public UUID getId()
- {
- return _obj.getId();
- }
-
- public long getCreateTime()
- {
- return _obj.getCreateTime();
- }
- }
-
- private class LinkDelegate implements BrokerSchema.LinkDelegate
- {
- private final LinkConfig _obj;
-
- private LinkDelegate(final LinkConfig obj)
- {
- _obj = obj;
- }
-
- public BrokerSchema.VhostObject getVhostRef()
- {
- return (BrokerSchema.VhostObject) adapt(_obj.getVirtualHost());
- }
-
- public String getHost()
- {
- return _obj.getHost();
- }
-
- public Integer getPort()
- {
- return _obj.getPort();
- }
-
- public String getTransport()
- {
- return _obj.getTransport();
- }
-
- public Boolean getDurable()
- {
- return _obj.isDurable();
- }
-
- public String getState()
- {
- // TODO
- return "";
- }
-
- public String getLastError()
- {
- // TODO
- return "";
- }
-
- public BrokerSchema.LinkClass.CloseMethodResponseCommand close(final BrokerSchema.LinkClass.CloseMethodResponseCommandFactory factory)
- {
- _obj.close();
- return factory.createResponseCommand();
- }
-
- public BrokerSchema.LinkClass.BridgeMethodResponseCommand bridge(final BrokerSchema.LinkClass.BridgeMethodResponseCommandFactory factory,
- final Boolean durable,
- final String src,
- final String dest,
- final String key,
- final String tag,
- final String excludes,
- final Boolean srcIsQueue,
- final Boolean srcIsLocal,
- final Boolean dynamic,
- final Integer sync)
- {
- _obj.createBridge(durable, dynamic, srcIsQueue, srcIsLocal, src, dest, key, tag, excludes);
- return factory.createResponseCommand();
- }
-
- public UUID getId()
- {
- return _obj.getId();
- }
-
- public long getCreateTime()
- {
- return _obj.getCreateTime();
- }
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/qmf/QMFStatistic.java b/java/broker/src/main/java/org/apache/qpid/qmf/QMFStatistic.java
deleted file mode 100644
index 89d650e03b..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/qmf/QMFStatistic.java
+++ /dev/null
@@ -1,61 +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.qmf;
-
-import org.apache.qpid.transport.codec.Encoder;
-
-import java.util.LinkedHashMap;
-
-public class QMFStatistic
-{
- private final LinkedHashMap<String,Object> _map = new LinkedHashMap<String,Object>();
- private static final String NAME = "name";
- private static final String TYPE = "type";
- private static final String UNIT = "unit";
- private static final String DESCRIPTION = "desc";
-
-
- public QMFStatistic(String name, QMFType type, String unit, String description)
- {
- _map.put(NAME, name);
- _map.put(TYPE, type.codeValue());
- if(unit != null)
- {
- _map.put(UNIT, unit);
- }
- if(description != null)
- {
- _map.put(DESCRIPTION, description);
- }
-
- }
-
- public void encode(Encoder encoder)
- {
- encoder.writeMap(_map);
- }
-
- public String getName()
- {
- return (String) _map.get(NAME);
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/qmf/QMFType.java b/java/broker/src/main/java/org/apache/qpid/qmf/QMFType.java
deleted file mode 100644
index 0e01c27db5..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/qmf/QMFType.java
+++ /dev/null
@@ -1,53 +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.qmf;
-
-public enum QMFType
-{
-
- UINT8,
- UINT16,
- UINT32,
- UINT64,
- UNKNOWN,
- STR8,
- STR16,
- ABSTIME,
- DELTATIME,
- OBJECTREFERENCE,
- BOOLEAN,
- FLOAT,
- DOUBLE,
- UUID,
- MAP,
- INT8,
- INT16,
- INT32,
- INT64,
- OBJECT,
- LIST,
- ARRAY;
-
- public int codeValue()
- {
- return ordinal()+1;
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/AMQBrokerManagerMBean.java b/java/broker/src/main/java/org/apache/qpid/server/AMQBrokerManagerMBean.java
deleted file mode 100644
index d1ea5dba69..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/AMQBrokerManagerMBean.java
+++ /dev/null
@@ -1,400 +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;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-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.management.common.mbeans.ManagedBroker;
-import org.apache.qpid.management.common.mbeans.ManagedQueue;
-import org.apache.qpid.management.common.mbeans.annotations.MBeanConstructor;
-import org.apache.qpid.management.common.mbeans.annotations.MBeanDescription;
-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.management.AMQManagedObject;
-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.AMQQueueMBean;
-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;
-
-/**
- * This MBean implements the broker management interface and exposes the
- * Broker level management features like creating and deleting exchanges and queue.
- */
-@MBeanDescription("This MBean exposes the broker level management features")
-public class AMQBrokerManagerMBean extends AMQManagedObject implements ManagedBroker
-{
- private final QueueRegistry _queueRegistry;
- private final ExchangeRegistry _exchangeRegistry;
- private final ExchangeFactory _exchangeFactory;
- private final DurableConfigurationStore _durableConfig;
-
- private final VirtualHostImpl.VirtualHostMBean _virtualHostMBean;
-
- @MBeanConstructor("Creates the Broker Manager MBean")
- public AMQBrokerManagerMBean(VirtualHostImpl.VirtualHostMBean virtualHostMBean) throws JMException
- {
- super(ManagedBroker.class, ManagedBroker.TYPE);
-
- _virtualHostMBean = virtualHostMBean;
- VirtualHost virtualHost = virtualHostMBean.getVirtualHost();
-
- _queueRegistry = virtualHost.getQueueRegistry();
- _exchangeRegistry = virtualHost.getExchangeRegistry();
- _durableConfig = virtualHost.getDurableConfigurationStore();
- _exchangeFactory = virtualHost.getExchangeFactory();
- }
-
- public String getObjectInstanceName()
- {
- return _virtualHostMBean.getVirtualHost().getName();
- }
-
- /**
- * Returns an array of the exchange types available for creation.
- * @since Qpid JMX API 1.3
- * @throws IOException
- */
- public String[] getExchangeTypes() throws IOException
- {
- ArrayList<String> exchangeTypes = new ArrayList<String>();
- for(ExchangeType<? extends Exchange> ex : _exchangeFactory.getPublicCreatableTypes())
- {
- exchangeTypes.add(ex.getName().toString());
- }
-
- return exchangeTypes.toArray(new String[0]);
- }
-
- /**
- * Returns a list containing the names of the attributes available for the Queue mbeans.
- * @since Qpid JMX API 1.3
- * @throws IOException
- */
- public List<String> retrieveQueueAttributeNames() throws IOException
- {
- return ManagedQueue.QUEUE_ATTRIBUTES;
- }
-
- /**
- * Returns a List of Object Lists containing the requested attribute values (in the same sequence requested) for each queue in the virtualhost.
- * If a particular attribute cant be found or raises an mbean/reflection exception whilst being gathered its value is substituted with the String "-".
- * @since Qpid JMX API 1.3
- * @throws IOException
- */
- public List<List<Object>> retrieveQueueAttributeValues(String[] attributes) throws IOException
- {
- if(_queueRegistry.getQueues().size() == 0)
- {
- return new ArrayList<List<Object>>();
- }
-
- List<List<Object>> queueAttributesList = new ArrayList<List<Object>>(_queueRegistry.getQueues().size());
-
- int attributesLength = attributes.length;
-
- for(AMQQueue queue : _queueRegistry.getQueues())
- {
- AMQQueueMBean mbean = (AMQQueueMBean) queue.getManagedObject();
-
- if(mbean == null)
- {
- continue;
- }
-
- List<Object> attributeValues = new ArrayList<Object>(attributesLength);
-
- for(int i=0; i < attributesLength; i++)
- {
- try
- {
- attributeValues.add(mbean.getAttribute(attributes[i]));
- }
- catch (Exception e)
- {
- attributeValues.add("-");
- }
- }
-
- queueAttributesList.add(attributeValues);
- }
-
- return queueAttributesList;
- }
-
- /**
- * Creates new exchange and registers it with the registry.
- *
- * @param exchangeName
- * @param type
- * @param durable
- * @throws JMException
- * @throws MBeanException
- */
- public void createNewExchange(String exchangeName, String type, boolean durable) throws JMException, MBeanException
- {
- CurrentActor.set(new ManagementActor(_logActor.getRootMessageLogger()));
- try
- {
- synchronized (_exchangeRegistry)
- {
- Exchange exchange = _exchangeRegistry.getExchange(new AMQShortString(exchangeName));
- if (exchange == null)
- {
- exchange = _exchangeFactory.createExchange(new AMQShortString(exchangeName), new AMQShortString(type),
- durable, false, 0);
- _exchangeRegistry.registerExchange(exchange);
- if (durable)
- {
- _durableConfig.createExchange(exchange);
- }
- }
- else
- {
- throw new JMException("The exchange \"" + exchangeName + "\" already exists.");
- }
- }
- }
- catch (AMQException ex)
- {
- JMException jme = new JMException(ex.toString());
- throw new MBeanException(jme, "Error in creating exchange " + exchangeName);
- }
- finally
- {
- CurrentActor.remove();
- }
- }
-
- /**
- * Unregisters the exchange from registry.
- *
- * @param exchangeName
- * @throws JMException
- * @throws MBeanException
- */
- public void unregisterExchange(String exchangeName) throws JMException, MBeanException
- {
- // 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()));
- try
- {
- _exchangeRegistry.unregisterExchange(new AMQShortString(exchangeName), false);
- }
- catch (AMQException ex)
- {
- JMException jme = new JMException(ex.toString());
- throw new MBeanException(jme, "Error in unregistering exchange " + exchangeName);
- }
- finally
- {
- CurrentActor.remove();
- }
- }
-
- /**
- * Creates a new queue and registers it with the registry and puts it
- * in persistance storage if durable queue.
- *
- * @param queueName
- * @param durable
- * @param owner
- * @throws JMException
- * @throws MBeanException
- */
- public void createNewQueue(String queueName, String owner, boolean durable) throws JMException, MBeanException
- {
- AMQQueue queue = _queueRegistry.getQueue(new AMQShortString(queueName));
- if (queue != null)
- {
- throw new JMException("The queue \"" + queueName + "\" already exists.");
- }
-
- CurrentActor.set(new ManagementActor(_logActor.getRootMessageLogger()));
- try
- {
- AMQShortString ownerShortString = null;
- if (owner != null)
- {
- ownerShortString = new AMQShortString(owner);
- }
-
- queue = AMQQueueFactory.createAMQQueueImpl(new AMQShortString(queueName), durable, ownerShortString, false, false, getVirtualHost(), null);
- if (queue.isDurable() && !queue.isAutoDelete())
- {
- _durableConfig.createQueue(queue);
- }
-
- _queueRegistry.registerQueue(queue);
- }
- catch (AMQException ex)
- {
- JMException jme = new JMException(ex.toString());
- throw new MBeanException(jme, "Error in creating queue " + queueName);
- }
- finally
- {
- CurrentActor.remove();
- }
- }
-
- private VirtualHost getVirtualHost()
- {
- return _virtualHostMBean.getVirtualHost();
- }
-
- /**
- * Deletes the queue from queue registry and persistant storage.
- *
- * @param queueName
- * @throws JMException
- * @throws MBeanException
- */
- public void deleteQueue(String queueName) throws JMException, MBeanException
- {
- AMQQueue queue = _queueRegistry.getQueue(new AMQShortString(queueName));
- if (queue == null)
- {
- throw new JMException("The Queue " + queueName + " is not a registered queue.");
- }
-
- CurrentActor.set(new ManagementActor(_logActor.getRootMessageLogger()));
- try
- {
- queue.delete();
- if (queue.isDurable())
- {
- _durableConfig.removeQueue(queue);
- }
- }
- catch (AMQException ex)
- {
- JMException jme = new JMException(ex.toString());
- throw new MBeanException(jme, "Error in deleting queue " + queueName);
- }
- finally
- {
- CurrentActor.remove();
- }
- }
-
- @Override
- public ManagedObject getParentObject()
- {
- return _virtualHostMBean;
- }
-
- // This will have a single instance for a virtual host, so not having the name property in the ObjectName
- @Override
- public ObjectName getObjectName() throws MalformedObjectNameException
- {
- return getObjectNameForSingleInstanceMBean();
- }
-
- public void resetStatistics() throws Exception
- {
- getVirtualHost().resetStatistics();
- }
-
- public double getPeakMessageDeliveryRate()
- {
- return getVirtualHost().getMessageDeliveryStatistics().getPeak();
- }
-
- public double getPeakDataDeliveryRate()
- {
- return getVirtualHost().getDataDeliveryStatistics().getPeak();
- }
-
- public double getMessageDeliveryRate()
- {
- return getVirtualHost().getMessageDeliveryStatistics().getRate();
- }
-
- public double getDataDeliveryRate()
- {
- return getVirtualHost().getDataDeliveryStatistics().getRate();
- }
-
- public long getTotalMessagesDelivered()
- {
- return getVirtualHost().getMessageDeliveryStatistics().getTotal();
- }
-
- public long getTotalDataDelivered()
- {
- return getVirtualHost().getDataDeliveryStatistics().getTotal();
- }
-
- public double getPeakMessageReceiptRate()
- {
- return getVirtualHost().getMessageReceiptStatistics().getPeak();
- }
-
- public double getPeakDataReceiptRate()
- {
- return getVirtualHost().getDataReceiptStatistics().getPeak();
- }
-
- public double getMessageReceiptRate()
- {
- return getVirtualHost().getMessageReceiptStatistics().getRate();
- }
-
- public double getDataReceiptRate()
- {
- return getVirtualHost().getDataReceiptStatistics().getRate();
- }
-
- public long getTotalMessagesReceived()
- {
- return getVirtualHost().getMessageReceiptStatistics().getTotal();
- }
-
- public long getTotalDataReceived()
- {
- return getVirtualHost().getDataReceiptStatistics().getTotal();
- }
-
- public boolean isStatisticsEnabled()
- {
- return getVirtualHost().isStatisticsEnabled();
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/AMQChannel.java b/java/broker/src/main/java/org/apache/qpid/server/AMQChannel.java
deleted file mode 100644
index 08eb05680c..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/AMQChannel.java
+++ /dev/null
@@ -1,1465 +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;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.AMQConnectionException;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.AMQSecurityException;
-import org.apache.qpid.framing.AMQMethodBody;
-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.FieldTable;
-import org.apache.qpid.framing.MethodRegistry;
-import org.apache.qpid.framing.abstraction.ContentChunk;
-import org.apache.qpid.framing.abstraction.MessagePublishInfo;
-import org.apache.qpid.protocol.AMQConstant;
-import org.apache.qpid.server.ack.UnacknowledgedMessageMap;
-import org.apache.qpid.server.ack.UnacknowledgedMessageMapImpl;
-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.SessionConfig;
-import org.apache.qpid.server.configuration.SessionConfigType;
-import org.apache.qpid.server.exchange.Exchange;
-import org.apache.qpid.server.flow.FlowCreditManager;
-import org.apache.qpid.server.flow.Pre0_10CreditManager;
-import org.apache.qpid.server.logging.LogActor;
-import org.apache.qpid.server.logging.LogSubject;
-import org.apache.qpid.server.logging.actors.AMQPChannelActor;
-import org.apache.qpid.server.logging.actors.CurrentActor;
-import org.apache.qpid.server.logging.messages.ChannelMessages;
-import org.apache.qpid.server.logging.subjects.ChannelLogSubject;
-import org.apache.qpid.server.message.AMQMessage;
-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.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.IncomingMessage;
-import org.apache.qpid.server.queue.QueueEntry;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-import org.apache.qpid.server.store.MessageStore;
-import org.apache.qpid.server.store.StoredMessage;
-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.txn.AutoCommitTransaction;
-import org.apache.qpid.server.txn.LocalTransaction;
-import org.apache.qpid.server.txn.ServerTransaction;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.SortedSet;
-import java.util.TreeSet;
-import java.util.UUID;
-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
-{
- public static final int DEFAULT_PREFETCH = 5000;
-
- private static final Logger _logger = Logger.getLogger(AMQChannel.class);
-
- private static final boolean MSG_AUTH =
- ApplicationRegistry.getInstance().getConfiguration().getMsgAuth();
-
-
- private final int _channelId;
-
-
- private final Pre0_10CreditManager _creditManager = new Pre0_10CreditManager(0l,0l);
-
- /**
- * The delivery tag is unique per channel. This is pre-incremented before putting into the deliver frame so that
- * value of this represents the <b>last</b> tag sent out
- */
- private long _deliveryTag = 0;
-
- /** A channel has a default queue (the last declared) that is used when no queue name is explictily set */
- private AMQQueue _defaultQueue;
-
- /** This tag is unique per subscription to a queue. The server returns this in response to a basic.consume request. */
- private int _consumerTag;
-
- /**
- * The current message - which may be partial in the sense that not all frames have been received yet - which has
- * been received by this channel. As the frames are received the message gets updated and once all frames have been
- * received the message can then be routed.
- */
- private IncomingMessage _currentMessage;
-
- /** Maps from consumer tag to subscription instance. Allows us to unsubscribe from a queue. */
- protected final Map<AMQShortString, Subscription> _tag2SubscriptionMap = new HashMap<AMQShortString, Subscription>();
-
- private final MessageStore _messageStore;
-
- private UnacknowledgedMessageMap _unacknowledgedMessageMap = new UnacknowledgedMessageMapImpl(DEFAULT_PREFETCH);
-
- // Set of messages being acknoweledged in the current transaction
- private SortedSet<QueueEntry> _acknowledgedMessages = new TreeSet<QueueEntry>();
-
- private final AtomicBoolean _suspended = new AtomicBoolean(false);
-
- private ServerTransaction _transaction;
-
- private final AtomicLong _txnStarts = new AtomicLong(0);
- private final AtomicLong _txnCommits = new AtomicLong(0);
- private final AtomicLong _txnRejects = new AtomicLong(0);
- private final AtomicLong _txnCount = new AtomicLong(0);
- private final AtomicLong _txnUpdateTime = new AtomicLong(0);
-
- private final AMQProtocolSession _session;
- private AtomicBoolean _closing = new AtomicBoolean(false);
-
- private final ConcurrentMap<AMQQueue, Boolean> _blockingQueues = new ConcurrentHashMap<AMQQueue, Boolean>();
-
- private final AtomicBoolean _blocking = new AtomicBoolean(false);
-
-
- private LogActor _actor;
- private LogSubject _logSubject;
- private volatile boolean _rollingBack;
-
- private static final Runnable NULL_TASK = new Runnable() { public void run() {} };
- private List<QueueEntry> _resendList = new ArrayList<QueueEntry>();
- private static final
- AMQShortString IMMEDIATE_DELIVERY_REPLY_TEXT = new AMQShortString("Immediate delivery is not possible.");
- private final UUID _id;
- private long _createTime = System.currentTimeMillis();
-
- public AMQChannel(AMQProtocolSession session, int channelId, MessageStore messageStore)
- throws AMQException
- {
- _session = session;
- _channelId = channelId;
-
- _actor = new AMQPChannelActor(this, session.getLogActor().getRootMessageLogger());
- _logSubject = new ChannelLogSubject(this);
- _id = getConfigStore().createId();
- _actor.message(ChannelMessages.CREATE());
-
- getConfigStore().addConfiguredObject(this);
-
- _messageStore = messageStore;
-
- // by default the session is non-transactional
- _transaction = new AutoCommitTransaction(_messageStore);
- }
-
- public ConfigStore getConfigStore()
- {
- return getVirtualHost().getConfigStore();
- }
-
- /** Sets this channel to be part of a local transaction */
- public void setLocalTransactional()
- {
- _transaction = new LocalTransaction(_messageStore);
- _txnStarts.incrementAndGet();
- }
-
- public boolean isTransactional()
- {
- // this does not look great but there should only be one "non-transactional"
- // transactional context, while there could be several transactional ones in
- // theory
- return !(_transaction instanceof AutoCommitTransaction);
- }
-
- public boolean inTransaction()
- {
- return isTransactional() && _txnUpdateTime.get() > 0 && _transaction.getTransactionStartTime() > 0;
- }
-
- private void incrementOutstandingTxnsIfNecessary()
- {
- if(isTransactional())
- {
- //There can currently only be at most one outstanding transaction
- //due to only having LocalTransaction support. Set value to 1 if 0.
- _txnCount.compareAndSet(0,1);
- }
- }
-
- private void decrementOutstandingTxnsIfNecessary()
- {
- if(isTransactional())
- {
- //There can currently only be at most one outstanding transaction
- //due to only having LocalTransaction support. Set value to 0 if 1.
- _txnCount.compareAndSet(1,0);
- }
- }
-
- public Long getTxnStarts()
- {
- return _txnStarts.get();
- }
-
- public Long getTxnCommits()
- {
- return _txnCommits.get();
- }
-
- public Long getTxnRejects()
- {
- return _txnRejects.get();
- }
-
- public Long getTxnCount()
- {
- return _txnCount.get();
- }
-
- public int getChannelId()
- {
- return _channelId;
- }
-
- public void setPublishFrame(MessagePublishInfo info, final Exchange e) throws AMQSecurityException
- {
- if (!getVirtualHost().getSecurityManager().authorisePublish(info.isImmediate(), info.getRoutingKey().asString(), e.getName()))
- {
- throw new AMQSecurityException("Permission denied: " + e.getName());
- }
- _currentMessage = new IncomingMessage(info);
- _currentMessage.setExchange(e);
- }
-
- public void publishContentHeader(ContentHeaderBody contentHeaderBody)
- throws AMQException
- {
- if (_currentMessage == null)
- {
- throw new AMQException("Received content header without previously receiving a BasicPublish frame");
- }
- else
- {
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Content header received on channel " + _channelId);
- }
-
- _currentMessage.setContentHeaderBody(contentHeaderBody);
-
- _currentMessage.setExpiration();
-
-
- MessageMetaData mmd = _currentMessage.headersReceived();
- final StoredMessage<MessageMetaData> handle = _messageStore.addMessage(mmd);
- _currentMessage.setStoredMessage(handle);
-
- routeCurrentMessage();
-
-
- _transaction.addPostTransactionAction(new ServerTransaction.Action()
- {
-
- public void postCommit()
- {
- }
-
- public void onRollback()
- {
- handle.remove();
- }
- });
-
- deliverCurrentMessageIfComplete();
- }
- }
-
- private void deliverCurrentMessageIfComplete()
- throws AMQException
- {
- // check and deliver if header says body length is zero
- if (_currentMessage.allContentReceived())
- {
- try
- {
- _currentMessage.getStoredMessage().flushToStore();
-
- final ArrayList<? extends BaseQueue> destinationQueues = _currentMessage.getDestinationQueues();
-
- if(!checkMessageUserId(_currentMessage.getContentHeader()))
- {
- _transaction.addPostTransactionAction(new WriteReturnAction(AMQConstant.ACCESS_REFUSED, "Access Refused", _currentMessage));
- }
- else
- {
- if(destinationQueues == null || _currentMessage.getDestinationQueues().isEmpty())
- {
- if (_currentMessage.isMandatory() || _currentMessage.isImmediate())
- {
- _transaction.addPostTransactionAction(new WriteReturnAction(AMQConstant.NO_ROUTE, "No Route for message", _currentMessage));
- }
- else
- {
- _logger.warn("MESSAGE DISCARDED: No routes for message - " + createAMQMessage(_currentMessage));
- }
-
- }
- else
- {
- _transaction.enqueue(destinationQueues, _currentMessage, new MessageDeliveryAction(_currentMessage, destinationQueues, isTransactional()));
- incrementOutstandingTxnsIfNecessary();
- updateTransactionalActivity();
- }
- }
- }
- finally
- {
- long bodySize = _currentMessage.getSize();
- long timestamp = ((BasicContentHeaderProperties) _currentMessage.getContentHeader().getProperties()).getTimestamp();
- _session.registerMessageReceived(bodySize, timestamp);
- _currentMessage = null;
- }
- }
-
- }
-
- public void publishContentBody(ContentBody contentBody) throws AMQException
- {
- if (_currentMessage == null)
- {
- throw new AMQException("Received content body without previously receiving a JmsPublishBody");
- }
-
- if (_logger.isDebugEnabled())
- {
- _logger.debug(debugIdentity() + "Content body received on channel " + _channelId);
- }
-
- try
- {
-
- // returns true iff the message was delivered (i.e. if all data was
- // received
- final ContentChunk contentChunk =
- _session.getMethodRegistry().getProtocolVersionMethodConverter().convertToContentChunk(contentBody);
-
- _currentMessage.addContentBodyFrame(contentChunk);
-
- deliverCurrentMessageIfComplete();
- }
- catch (AMQException e)
- {
- // we want to make sure we don't keep a reference to the message in the
- // event of an error
- _currentMessage = null;
- throw e;
- }
- }
-
- protected void routeCurrentMessage() throws AMQException
- {
- _currentMessage.route();
- }
-
- public long getNextDeliveryTag()
- {
- return ++_deliveryTag;
- }
-
- public int getNextConsumerTag()
- {
- return ++_consumerTag;
- }
-
-
- public Subscription getSubscription(AMQShortString subscription)
- {
- return _tag2SubscriptionMap.get(subscription);
- }
-
- /**
- * Subscribe to a queue. We register all subscriptions in the channel so that if the channel is closed we can clean
- * up all subscriptions, even if the client does not explicitly unsubscribe from all queues.
- *
- * @param tag the tag chosen by the client (if null, server will generate one)
- * @param queue the queue to subscribe to
- * @param acks Are acks enabled for this subscriber
- * @param filters Filters to apply to this subscriber
- *
- * @param noLocal Flag stopping own messages being receivied.
- * @param exclusive Flag requesting exclusive access to the queue
- * @return the consumer tag. This is returned to the subscriber and used in subsequent unsubscribe requests
- *
- * @throws AMQException if something goes wrong
- */
- public AMQShortString subscribeToQueue(AMQShortString tag, AMQQueue queue, boolean acks,
- FieldTable filters, boolean noLocal, boolean exclusive) throws AMQException
- {
- if (tag == null)
- {
- tag = new AMQShortString("sgen_" + getNextConsumerTag());
- }
-
- if (_tag2SubscriptionMap.containsKey(tag))
- {
- throw new AMQException("Consumer already exists with same tag: " + tag);
- }
-
- Subscription subscription =
- SubscriptionFactoryImpl.INSTANCE.createSubscription(_channelId, _session, tag, acks, filters, noLocal, _creditManager);
-
-
- // So to keep things straight we put before the call and catch all exceptions from the register and tidy up.
- // We add before we register as the Async Delivery process may AutoClose the subscriber
- // so calling _cT2QM.remove before we have done put which was after the register succeeded.
- // So to keep things straight we put before the call and catch all exceptions from the register and tidy up.
-
- _tag2SubscriptionMap.put(tag, subscription);
-
- try
- {
- queue.registerSubscription(subscription, exclusive);
- }
- catch (AMQException e)
- {
- _tag2SubscriptionMap.remove(tag);
- throw e;
- }
- return tag;
- }
-
- /**
- * Unsubscribe a consumer from a queue.
- * @param consumerTag
- * @return true if the consumerTag had a mapped queue that could be unregistered.
- * @throws AMQException
- */
- public boolean unsubscribeConsumer(AMQShortString consumerTag) throws AMQException
- {
-
- Subscription sub = _tag2SubscriptionMap.remove(consumerTag);
- if (sub != null)
- {
- try
- {
- sub.getSendLock();
- sub.getQueue().unregisterSubscription(sub);
- }
- finally
- {
- sub.releaseSendLock();
- }
- return true;
- }
- else
- {
- _logger.warn("Attempt to unsubscribe consumer with tag '"+consumerTag+"' which is not registered.");
- }
- return false;
- }
-
- /**
- * Called from the protocol session to close this channel and clean up. T
- *
- * @throws AMQException if there is an error during closure
- */
- public void close() throws AMQException
- {
- if(!_closing.compareAndSet(false, true))
- {
- //Channel is already closing
- return;
- }
-
- CurrentActor.get().message(_logSubject, ChannelMessages.CLOSE());
-
- unsubscribeAllConsumers();
- _transaction.rollback();
-
- try
- {
- requeue();
- }
- catch (AMQException e)
- {
- _logger.error("Caught AMQException whilst attempting to reque:" + e);
- }
-
- getConfigStore().removeConfiguredObject(this);
-
- }
-
- private void unsubscribeAllConsumers() throws AMQException
- {
- if (_logger.isInfoEnabled())
- {
- if (!_tag2SubscriptionMap.isEmpty())
- {
- _logger.info("Unsubscribing all consumers on channel " + toString());
- }
- else
- {
- _logger.info("No consumers to unsubscribe on channel " + toString());
- }
- }
-
- for (Map.Entry<AMQShortString, Subscription> me : _tag2SubscriptionMap.entrySet())
- {
- if (_logger.isInfoEnabled())
- {
- _logger.info("Unsubscribing consumer '" + me.getKey() + "' on channel " + toString());
- }
-
- Subscription sub = me.getValue();
-
- try
- {
- sub.getSendLock();
- sub.getQueue().unregisterSubscription(sub);
- }
- finally
- {
- sub.releaseSendLock();
- }
-
- }
-
- _tag2SubscriptionMap.clear();
- }
-
- /**
- * Add a message to the channel-based list of unacknowledged messages
- *
- * @param entry the record of the message on the queue that was delivered
- * @param deliveryTag the delivery tag used when delivering the message (see protocol spec for description of the
- * delivery tag)
- * @param subscription The consumer that is to acknowledge this message.
- */
- public void addUnacknowledgedMessage(QueueEntry entry, long deliveryTag, Subscription subscription)
- {
- if (_logger.isDebugEnabled())
- {
- if (entry.getQueue() == null)
- {
- _logger.debug("Adding unacked message with a null queue:" + entry);
- }
- else
- {
- if (_logger.isDebugEnabled())
- {
- _logger.debug(debugIdentity() + " Adding unacked message(" + entry.getMessage().toString() + " DT:" + deliveryTag
- + ") with a queue(" + entry.getQueue() + ") for " + subscription);
- }
- }
- }
-
- _unacknowledgedMessageMap.add(deliveryTag, entry);
-
- }
-
- private final String id = "(" + System.identityHashCode(this) + ")";
-
- public String debugIdentity()
- {
- return _channelId + id;
- }
-
- /**
- * Called to attempt re-delivery all outstanding unacknowledged messages on the channel. May result in delivery to
- * this same channel or to other subscribers.
- *
- * @throws org.apache.qpid.AMQException if the requeue fails
- */
- public void requeue() throws AMQException
- {
- // we must create a new map since all the messages will get a new delivery tag when they are redelivered
- Collection<QueueEntry> messagesToBeDelivered = _unacknowledgedMessageMap.cancelAllMessages();
-
- if (!messagesToBeDelivered.isEmpty())
- {
- if (_logger.isInfoEnabled())
- {
- _logger.info("Requeuing " + messagesToBeDelivered.size() + " unacked messages. for " + toString());
- }
-
- }
-
- for (QueueEntry unacked : messagesToBeDelivered)
- {
- if (!unacked.isQueueDeleted())
- {
- // Mark message redelivered
- unacked.setRedelivered();
-
- // Ensure message is released for redelivery
- unacked.release();
-
- }
- else
- {
- unacked.discard();
- }
- }
-
- }
-
- /**
- * Requeue a single message
- *
- * @param deliveryTag The message to requeue
- *
- * @throws AMQException If something goes wrong.
- */
- public void requeue(long deliveryTag) throws AMQException
- {
- QueueEntry unacked = _unacknowledgedMessageMap.remove(deliveryTag);
-
- if (unacked != null)
- {
- // Mark message redelivered
- unacked.setRedelivered();
-
- // Ensure message is released for redelivery
- if (!unacked.isQueueDeleted())
- {
-
- // Ensure message is released for redelivery
- unacked.release();
-
- }
- else
- {
- _logger.warn(System.identityHashCode(this) + " Requested requeue of message(" + unacked
- + "):" + deliveryTag + " but no queue defined and no DeadLetter queue so DROPPING message.");
-
- unacked.discard();
- }
- }
- else
- {
- _logger.warn("Requested requeue of message:" + deliveryTag + " but no such delivery tag exists."
- + _unacknowledgedMessageMap.size());
-
- }
-
- }
-
- /**
- * Called to resend all outstanding unacknowledged messages to this same channel.
- *
- * @param requeue Are the messages to be requeued or dropped.
- *
- * @throws AMQException When something goes wrong.
- */
- public void resend(final boolean requeue) throws AMQException
- {
-
-
- final Map<Long, QueueEntry> msgToRequeue = new LinkedHashMap<Long, QueueEntry>();
- final Map<Long, QueueEntry> msgToResend = new LinkedHashMap<Long, QueueEntry>();
-
- if (_logger.isDebugEnabled())
- {
- _logger.debug("unacked map Size:" + _unacknowledgedMessageMap.size());
- }
-
- // Process the Unacked-Map.
- // Marking messages who still have a consumer for to be resent
- // and those that don't to be requeued.
- _unacknowledgedMessageMap.visit(new ExtractResendAndRequeue(_unacknowledgedMessageMap,
- msgToRequeue,
- msgToResend,
- requeue,
- _messageStore));
-
-
- // Process Messages to Resend
- if (_logger.isDebugEnabled())
- {
- if (!msgToResend.isEmpty())
- {
- _logger.debug("Preparing (" + msgToResend.size() + ") message to resend.");
- }
- else
- {
- _logger.debug("No message to resend.");
- }
- }
-
- for (Map.Entry<Long, QueueEntry> entry : msgToResend.entrySet())
- {
- QueueEntry message = entry.getValue();
- long deliveryTag = entry.getKey();
-
-
-
- ServerMessage msg = message.getMessage();
- 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();
-
- Subscription sub = message.getDeliveredSubscription();
-
- if (sub != null)
- {
-
- if(!queue.resend(message,sub))
- {
- msgToRequeue.put(deliveryTag, message);
- }
- }
- else
- {
-
- if (_logger.isInfoEnabled())
- {
- _logger.info("DeliveredSubscription not recorded so just requeueing(" + message.toString()
- + ")to prevent loss");
- }
- // move this message to requeue
- msgToRequeue.put(deliveryTag, message);
- }
- } // for all messages
- // } else !isSuspend
-
- if (_logger.isInfoEnabled())
- {
- if (!msgToRequeue.isEmpty())
- {
- _logger.info("Preparing (" + msgToRequeue.size() + ") message to requeue to.");
- }
- }
-
- // Process Messages to Requeue at the front of the queue
- for (Map.Entry<Long, QueueEntry> entry : msgToRequeue.entrySet())
- {
- QueueEntry message = entry.getValue();
- long deliveryTag = entry.getKey();
- _unacknowledgedMessageMap.remove(deliveryTag);
-
- message.setRedelivered();
- message.release();
-
- }
- }
-
-
- /**
- * Acknowledge one or more messages.
- *
- * @param deliveryTag the last delivery tag
- * @param multiple if true will acknowledge all messages up to an including the delivery tag. if false only
- * acknowledges the single message specified by the delivery tag
- *
- * @throws AMQException if the delivery tag is unknown (e.g. not outstanding) on this channel
- */
- public void acknowledgeMessage(long deliveryTag, boolean multiple) throws AMQException
- {
- Collection<QueueEntry> ackedMessages = getAckedMessages(deliveryTag, multiple);
- _transaction.dequeue(ackedMessages, new MessageAcknowledgeAction(ackedMessages));
- updateTransactionalActivity();
- }
-
- private Collection<QueueEntry> getAckedMessages(long deliveryTag, boolean multiple)
- {
-
- Map<Long, QueueEntry> ackedMessageMap = new LinkedHashMap<Long,QueueEntry>();
- _unacknowledgedMessageMap.collect(deliveryTag, multiple, ackedMessageMap);
- _unacknowledgedMessageMap.remove(ackedMessageMap);
- return ackedMessageMap.values();
- }
-
- /**
- * Used only for testing purposes.
- *
- * @return the map of unacknowledged messages
- */
- public UnacknowledgedMessageMap getUnacknowledgedMessageMap()
- {
- return _unacknowledgedMessageMap;
- }
-
- /**
- * Called from the ChannelFlowHandler to suspend this Channel
- * @param suspended boolean, should this Channel be suspended
- */
- public void setSuspended(boolean suspended)
- {
- boolean wasSuspended = _suspended.getAndSet(suspended);
- if (wasSuspended != suspended)
- {
- // Log Flow Started before we start the subscriptions
- if (!suspended)
- {
- _actor.message(_logSubject, ChannelMessages.FLOW("Started"));
- }
-
-
- // This section takes two different approaches to perform to perform
- // the same function. Ensuring that the Subscription has taken note
- // of the change in Channel State
-
- // Here we have become unsuspended and so we ask each the queue to
- // perform an Async delivery for each of the subscriptions in this
- // Channel. The alternative would be to ensure that the subscription
- // had received the change in suspension state. That way the logic
- // behind decieding to start an async delivery was located with the
- // Subscription.
- if (wasSuspended)
- {
- // may need to deliver queued messages
- for (Subscription s : _tag2SubscriptionMap.values())
- {
- s.getQueue().deliverAsync(s);
- }
- }
-
-
- // Here we have become suspended so we need to ensure that each of
- // the Subscriptions has noticed this change so that we can be sure
- // they are not still sending messages. Again the code here is a
- // very simplistic approach to ensure that the change of suspension
- // has been noticed by each of the Subscriptions. Unlike the above
- // case we don't actually need to do anything else.
- if (!wasSuspended)
- {
- // may need to deliver queued messages
- for (Subscription s : _tag2SubscriptionMap.values())
- {
- try
- {
- s.getSendLock();
- }
- finally
- {
- s.releaseSendLock();
- }
- }
- }
-
-
- // Log Suspension only after we have confirmed all suspensions are
- // stopped.
- if (suspended)
- {
- _actor.message(_logSubject, ChannelMessages.FLOW("Stopped"));
- }
-
- }
- }
-
- public boolean isSuspended()
- {
- return _suspended.get() || _closing.get() || _session.isClosing();
- }
-
- public void commit() throws AMQException
- {
- if (!isTransactional())
- {
- throw new AMQException("Fatal error: commit called on non-transactional channel");
- }
-
- _transaction.commit();
-
- _txnCommits.incrementAndGet();
- _txnStarts.incrementAndGet();
- decrementOutstandingTxnsIfNecessary();
- }
-
- public void rollback() throws AMQException
- {
- rollback(NULL_TASK);
- }
-
- public void rollback(Runnable postRollbackTask) throws AMQException
- {
- if (!isTransactional())
- {
- throw new AMQException("Fatal error: commit called on non-transactional channel");
- }
-
- // stop all subscriptions
- _rollingBack = true;
- boolean requiresSuspend = _suspended.compareAndSet(false,true);
-
- // ensure all subscriptions have seen the change to the channel state
- for(Subscription sub : _tag2SubscriptionMap.values())
- {
- sub.getSendLock();
- sub.releaseSendLock();
- }
-
- try
- {
- _transaction.rollback();
- }
- finally
- {
- _rollingBack = false;
-
- _txnRejects.incrementAndGet();
- _txnStarts.incrementAndGet();
- decrementOutstandingTxnsIfNecessary();
- }
-
- postRollbackTask.run();
-
- for(QueueEntry entry : _resendList)
- {
- Subscription sub = entry.getDeliveredSubscription();
- if(sub == null || sub.isClosed())
- {
- entry.release();
- }
- else
- {
- sub.getQueue().resend(entry, sub);
- }
- }
- _resendList.clear();
-
- if(requiresSuspend)
- {
- _suspended.set(false);
- for(Subscription sub : _tag2SubscriptionMap.values())
- {
- sub.getQueue().deliverAsync(sub);
- }
-
- }
-
-
- }
-
- /**
- * Update last transaction activity timestamp
- */
- private void updateTransactionalActivity()
- {
- if (isTransactional())
- {
- _txnUpdateTime.set(System.currentTimeMillis());
- }
- }
-
- public String toString()
- {
- return "["+_session.toString()+":"+_channelId+"]";
- }
-
- public void setDefaultQueue(AMQQueue queue)
- {
- _defaultQueue = queue;
- }
-
- public AMQQueue getDefaultQueue()
- {
- return _defaultQueue;
- }
-
-
- public boolean isClosing()
- {
- return _closing.get();
- }
-
- public AMQProtocolSession getProtocolSession()
- {
- return _session;
- }
-
- public FlowCreditManager getCreditManager()
- {
- return _creditManager;
- }
-
- public void setCredit(final long prefetchSize, final int prefetchCount)
- {
- _actor.message(ChannelMessages.PREFETCH_SIZE(prefetchSize, prefetchCount));
- _creditManager.setCreditLimits(prefetchSize, prefetchCount);
- }
-
- public MessageStore getMessageStore()
- {
- return _messageStore;
- }
-
- private final ClientDeliveryMethod _clientDeliveryMethod = new ClientDeliveryMethod()
- {
-
- public void deliverToClient(final Subscription sub, final QueueEntry entry, final long deliveryTag)
- throws AMQException
- {
- getProtocolSession().getProtocolOutputConverter().writeDeliver(entry, getChannelId(),
- deliveryTag, sub.getConsumerTag());
- _session.registerMessageDelivered(entry.getMessage().getSize());
- }
-
- };
-
- public ClientDeliveryMethod getClientDeliveryMethod()
- {
- return _clientDeliveryMethod;
- }
-
- private final RecordDeliveryMethod _recordDeliveryMethod = new RecordDeliveryMethod()
- {
-
- public void recordMessageDelivery(final Subscription sub, final QueueEntry entry, final long deliveryTag)
- {
- addUnacknowledgedMessage(entry, deliveryTag, sub);
- }
- };
-
- public RecordDeliveryMethod getRecordDeliveryMethod()
- {
- return _recordDeliveryMethod;
- }
-
-
- private AMQMessage createAMQMessage(IncomingMessage incomingMessage)
- throws AMQException
- {
-
- AMQMessage message = new AMQMessage(incomingMessage.getStoredMessage());
-
- message.setExpiration(incomingMessage.getExpiration());
- message.setClientIdentifier(_session);
- return message;
- }
-
- private boolean checkMessageUserId(ContentHeaderBody header)
- {
- AMQShortString userID =
- header.getProperties() instanceof BasicContentHeaderProperties
- ? ((BasicContentHeaderProperties) header.getProperties()).getUserId()
- : null;
-
- return (!MSG_AUTH || _session.getPrincipal().getName().equals(userID == null? "" : userID.toString()));
-
- }
-
- public Object getID()
- {
- return _channelId;
- }
-
- public AMQConnectionModel getConnectionModel()
- {
- return _session;
- }
-
- public String getClientID()
- {
- return String.valueOf(_session.getContextKey());
- }
-
- public LogSubject getLogSubject()
- {
- return _logSubject;
- }
-
- private class MessageDeliveryAction implements ServerTransaction.Action
- {
- private IncomingMessage _incommingMessage;
- private ArrayList<? extends BaseQueue> _destinationQueues;
-
- public MessageDeliveryAction(IncomingMessage currentMessage,
- ArrayList<? extends BaseQueue> destinationQueues,
- boolean transactional)
- {
- _incommingMessage = currentMessage;
- _destinationQueues = destinationQueues;
- }
-
- public void postCommit()
- {
- try
- {
- final boolean immediate = _incommingMessage.isImmediate();
-
- final AMQMessage amqMessage = createAMQMessage(_incommingMessage);
- MessageReference ref = amqMessage.newReference();
-
- for(final BaseQueue queue : _destinationQueues)
- {
- BaseQueue.PostEnqueueAction action;
-
- if(immediate)
- {
- action = new ImmediateAction(queue);
- }
- else
- {
- action = null;
- }
-
- queue.enqueue(amqMessage, action);
-
- if(queue instanceof AMQQueue)
- {
- ((AMQQueue)queue).checkCapacity(AMQChannel.this);
- }
-
- }
- ref.release();
- }
- catch (AMQException e)
- {
- // TODO
- throw new RuntimeException(e);
- }
-
-
-
-
-
- }
-
- public void onRollback()
- {
- // Maybe keep track of entries that were created and then delete them here in case of failure
- // to in memory enqueue
- }
-
- private class ImmediateAction implements BaseQueue.PostEnqueueAction
- {
- private final BaseQueue _queue;
-
- public ImmediateAction(BaseQueue queue)
- {
- _queue = queue;
- }
-
- public void onEnqueue(QueueEntry entry)
- {
- if (!entry.getDeliveredToConsumer() && entry.acquire())
- {
-
-
- ServerTransaction txn = new LocalTransaction(_messageStore);
- Collection<QueueEntry> entries = new ArrayList<QueueEntry>(1);
- entries.add(entry);
- final AMQMessage message = (AMQMessage) entry.getMessage();
- txn.dequeue(_queue, entry.getMessage(),
- new MessageAcknowledgeAction(entries)
- {
- @Override
- public void postCommit()
- {
- try
- {
- final
- ProtocolOutputConverter outputConverter =
- _session.getProtocolOutputConverter();
-
- outputConverter.writeReturn(message.getMessagePublishInfo(),
- message.getContentHeaderBody(),
- message,
- _channelId,
- AMQConstant.NO_CONSUMERS.getCode(),
- IMMEDIATE_DELIVERY_REPLY_TEXT);
- }
- catch (AMQException e)
- {
- throw new RuntimeException(e);
- }
- super.postCommit();
- }
- }
- );
- txn.commit();
-
-
- }
-
- }
- }
- }
-
- private class MessageAcknowledgeAction implements ServerTransaction.Action
- {
- private final Collection<QueueEntry> _ackedMessages;
-
-
- public MessageAcknowledgeAction(Collection<QueueEntry> ackedMessages)
- {
- _ackedMessages = ackedMessages;
- }
-
- public void postCommit()
- {
- try
- {
- for(QueueEntry entry : _ackedMessages)
- {
- entry.discard();
- }
- }
- finally
- {
- _acknowledgedMessages.clear();
- }
-
- }
-
- public void onRollback()
- {
- // explicit rollbacks resend the message after the rollback-ok is sent
- if(_rollingBack)
- {
- _resendList.addAll(_ackedMessages);
- }
- else
- {
- try
- {
- for(QueueEntry entry : _ackedMessages)
- {
- entry.release();
- }
- }
- finally
- {
- _acknowledgedMessages.clear();
- }
- }
-
- }
- }
-
- private class WriteReturnAction implements ServerTransaction.Action
- {
- private final AMQConstant _errorCode;
- private final IncomingMessage _message;
- private final String _description;
-
- public WriteReturnAction(AMQConstant errorCode,
- String description,
- IncomingMessage message)
- {
- _errorCode = errorCode;
- _message = message;
- _description = description;
- }
-
- public void postCommit()
- {
- try
- {
- _session.getProtocolOutputConverter().writeReturn(_message.getMessagePublishInfo(),
- _message.getContentHeader(),
- _message,
- _channelId,
- _errorCode.getCode(),
- new AMQShortString(_description));
- }
- catch (AMQException e)
- {
- //TODO
- throw new RuntimeException(e);
- }
-
- }
-
- public void onRollback()
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
- }
-
-
- public LogActor getLogActor()
- {
- return _actor;
- }
-
- public void block(AMQQueue queue)
- {
- if(_blockingQueues.putIfAbsent(queue, Boolean.TRUE) == null)
- {
-
- if(_blocking.compareAndSet(false,true))
- {
- _actor.message(_logSubject, ChannelMessages.FLOW_ENFORCED(queue.getNameShortString().toString()));
- flow(false);
- }
- }
- }
-
- public void unblock(AMQQueue queue)
- {
- if(_blockingQueues.remove(queue))
- {
- if(_blocking.compareAndSet(true,false))
- {
- _actor.message(_logSubject, ChannelMessages.FLOW_REMOVED());
-
- flow(true);
- }
- }
- }
-
- private void flow(boolean flow)
- {
- MethodRegistry methodRegistry = _session.getMethodRegistry();
- AMQMethodBody responseBody = methodRegistry.createChannelFlowBody(flow);
- _session.writeFrame(responseBody.generateFrame(_channelId));
- }
-
- public boolean getBlocking()
- {
- return _blocking.get();
- }
-
- public VirtualHost getVirtualHost()
- {
- return getProtocolSession().getVirtualHost();
- }
-
-
- public ConfiguredObject getParent()
- {
- return getVirtualHost();
- }
-
- public SessionConfigType getConfigType()
- {
- return SessionConfigType.getInstance();
- }
-
- public int getChannel()
- {
- return getChannelId();
- }
-
- public boolean isAttached()
- {
- return true;
- }
-
- public long getDetachedLifespan()
- {
- return 0;
- }
-
- public ConnectionConfig getConnectionConfig()
- {
- return (AMQProtocolEngine)getProtocolSession();
- }
-
- public Long getExpiryTime()
- {
- return null;
- }
-
- public Long getMaxClientRate()
- {
- return null;
- }
-
- public boolean isDurable()
- {
- return false;
- }
-
- public UUID getId()
- {
- return _id;
- }
-
- public String getSessionName()
- {
- return getConnectionConfig().getAddress() + "/" + getChannelId();
- }
-
- public long getCreateTime()
- {
- return _createTime;
- }
-
- public void mgmtClose() throws AMQException
- {
- _session.mgmtCloseChannel(_channelId);
- }
-
- public void checkTransactionStatus(long openWarn, long openClose, long idleWarn, long idleClose) throws AMQException
- {
- if (inTransaction())
- {
- long currentTime = System.currentTimeMillis();
- long openTime = currentTime - _transaction.getTransactionStartTime();
- long idleTime = currentTime - _txnUpdateTime.get();
-
- // Log a warning on idle or open transactions
- if (idleWarn > 0L && idleTime > idleWarn)
- {
- CurrentActor.get().message(_logSubject, ChannelMessages.IDLE_TXN(idleTime));
- _logger.warn("IDLE TRANSACTION ALERT " + _logSubject.toString() + " " + idleTime + " ms");
- }
- else if (openWarn > 0L && openTime > openWarn)
- {
- CurrentActor.get().message(_logSubject, ChannelMessages.OPEN_TXN(openTime));
- _logger.warn("OPEN TRANSACTION ALERT " + _logSubject.toString() + " " + openTime + " ms");
- }
-
- // Close connection for idle or open transactions that have timed out
- if (idleClose > 0L && idleTime > idleClose)
- {
- getConnectionModel().closeSession(this, AMQConstant.RESOURCE_ERROR, "Idle transaction timed out");
- }
- else if (openClose > 0L && openTime > openClose)
- {
- getConnectionModel().closeSession(this, AMQConstant.RESOURCE_ERROR, "Open transaction timed out");
- }
- }
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/ExtractResendAndRequeue.java b/java/broker/src/main/java/org/apache/qpid/server/ExtractResendAndRequeue.java
deleted file mode 100644
index 9da02e0600..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/ExtractResendAndRequeue.java
+++ /dev/null
@@ -1,133 +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;
-
-import org.apache.qpid.server.ack.UnacknowledgedMessageMap;
-import org.apache.qpid.server.queue.QueueEntry;
-import org.apache.qpid.server.subscription.Subscription;
-import org.apache.qpid.server.store.TransactionLog;
-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 java.util.Map;
-
-public class ExtractResendAndRequeue implements UnacknowledgedMessageMap.Visitor
-{
- private static final Logger _log = Logger.getLogger(ExtractResendAndRequeue.class);
-
- private final Map<Long, QueueEntry> _msgToRequeue;
- private final Map<Long, QueueEntry> _msgToResend;
- private final boolean _requeueIfUnabletoResend;
- private final UnacknowledgedMessageMap _unacknowledgedMessageMap;
- private final TransactionLog _transactionLog;
-
- public ExtractResendAndRequeue(UnacknowledgedMessageMap unacknowledgedMessageMap,
- Map<Long, QueueEntry> msgToRequeue,
- Map<Long, QueueEntry> msgToResend,
- boolean requeueIfUnabletoResend,
- TransactionLog txnLog)
- {
- _unacknowledgedMessageMap = unacknowledgedMessageMap;
- _msgToRequeue = msgToRequeue;
- _msgToResend = msgToResend;
- _requeueIfUnabletoResend = requeueIfUnabletoResend;
- _transactionLog = txnLog;
- }
-
- public boolean callback(final long deliveryTag, QueueEntry message) throws AMQException
- {
-
- message.setRedelivered();
- final Subscription subscription = message.getDeliveredSubscription();
- if (subscription != null)
- {
- // Consumer exists
- if (!subscription.isClosed())
- {
- _msgToResend.put(deliveryTag, message);
- }
- else // consumer has gone
- {
- _msgToRequeue.put(deliveryTag, message);
- }
- }
- else
- {
- // Message has no consumer tag, so was "delivered" to a GET
- // or consumer no longer registered
- // cannot resend, so re-queue.
- if (!message.isQueueDeleted())
- {
- if (_requeueIfUnabletoResend)
- {
- _msgToRequeue.put(deliveryTag, message);
- }
- else
- {
-
- dequeueEntry(message);
- _log.info("No DeadLetter Queue and requeue not requested so dropping message:" + message);
- }
- }
- else
- {
- dequeueEntry(message);
- _log.warn("Message.queue is null and no DeadLetter Queue so dropping message:" + message);
- }
- }
-
- // false means continue processing
- return false;
- }
-
-
- private void dequeueEntry(final QueueEntry node)
- {
- ServerTransaction txn = new AutoCommitTransaction(_transactionLog);
- dequeueEntry(node, txn);
- }
-
- private void dequeueEntry(final QueueEntry node, ServerTransaction txn)
- {
- txn.dequeue(node.getQueue(), node.getMessage(),
- new ServerTransaction.Action()
- {
-
- public void postCommit()
- {
- node.discard();
- }
-
- public void onRollback()
- {
-
- }
- });
- }
-
- public void visitComplete()
- {
- _unacknowledgedMessageMap.clear();
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/Main.java b/java/broker/src/main/java/org/apache/qpid/server/Main.java
deleted file mode 100644
index 9d3c4dd2e8..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/Main.java
+++ /dev/null
@@ -1,617 +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;
-
-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 org.apache.commons.cli.CommandLine;
-import org.apache.commons.cli.HelpFormatter;
-import org.apache.commons.cli.Option;
-import org.apache.commons.cli.OptionBuilder;
-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.log4j.PropertyConfigurator;
-import org.apache.log4j.xml.QpidLog4JConfigurator;
-import org.apache.qpid.common.QpidProperties;
-import org.apache.qpid.framing.ProtocolVersion;
-import org.apache.qpid.server.configuration.ServerConfiguration;
-import org.apache.qpid.server.configuration.management.ConfigurationManagementMBean;
-import org.apache.qpid.server.information.management.ServerInformationMBean;
-import org.apache.qpid.server.logging.SystemOutMessageLogger;
-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.logging.management.LoggingManagementMBean;
-import org.apache.qpid.server.logging.messages.BrokerMessages;
-import org.apache.qpid.server.protocol.AMQProtocolEngineFactory;
-import org.apache.qpid.server.protocol.MultiVersionProtocolEngineFactory;
-import org.apache.qpid.server.protocol.MultiVersionProtocolEngineFactory.VERSION;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-import org.apache.qpid.server.registry.ConfigurationFileApplicationRegistry;
-import org.apache.qpid.server.transport.QpidAcceptor;
-import org.apache.qpid.ssl.SSLContextFactory;
-import org.apache.qpid.transport.NetworkDriver;
-import org.apache.qpid.transport.network.mina.MINANetworkDriver;
-
-/**
- * Main entry point for AMQPD.
- *
- */
-public class Main
-{
- private static Logger _logger;
-
- private static final String DEFAULT_CONFIG_FILE = "etc/config.xml";
-
- public static final String DEFAULT_LOG_CONFIG_FILENAME = "log4j.xml";
- public static final String QPID_HOME = "QPID_HOME";
- private static final int IPV4_ADDRESS_LENGTH = 4;
-
- private static final char IPV4_LITERAL_SEPARATOR = '.';
-
- protected static class InitException extends Exception
- {
- InitException(String msg, Throwable cause)
- {
- super(msg, cause);
- }
- }
-
- protected final Options options = new Options();
- protected CommandLine commandLine;
-
- protected Main(String[] args)
- {
- setOptions(options);
- if (parseCommandline(args))
- {
- execute();
- }
- }
-
- protected boolean parseCommandline(String[] args)
- {
- try
- {
- commandLine = new PosixParser().parse(options, args);
-
- return true;
- }
- catch (ParseException e)
- {
- System.err.println("Error: " + e.getMessage());
- HelpFormatter formatter = new HelpFormatter();
- formatter.printHelp("Qpid", options, true);
-
- return false;
- }
- }
-
- @SuppressWarnings("static-access")
- protected void setOptions(Options options)
- {
- Option help = new Option("h", "help", false, "print this message");
- Option version = new Option("v", "version", false, "print the version information and exit");
- Option configFile =
- OptionBuilder.withArgName("file").hasArg().withDescription("use given configuration file").withLongOpt("config")
- .create("c");
- Option port =
- OptionBuilder.withArgName("port").hasArg()
- .withDescription("listen on the specified port. Overrides any value in the config file")
- .withLongOpt("port").create("p");
-
- Option exclude0_10 =
- OptionBuilder.withArgName("exclude-0-10").hasArg()
- .withDescription("when listening on the specified port do not accept AMQP0-10 connections. The specified port must be one specified on the command line")
- .withLongOpt("exclude-0-10").create();
-
- Option exclude0_9_1 =
- OptionBuilder.withArgName("exclude-0-9-1").hasArg()
- .withDescription("when listening on the specified port do not accept AMQP0-9-1 connections. The specified port must be one specified on the command line")
- .withLongOpt("exclude-0-9-1").create();
-
-
- Option exclude0_9 =
- OptionBuilder.withArgName("exclude-0-9").hasArg()
- .withDescription("when listening on the specified port do not accept AMQP0-9 connections. The specified port must be one specified on the command line")
- .withLongOpt("exclude-0-9").create();
-
-
- Option exclude0_8 =
- OptionBuilder.withArgName("exclude-0-8").hasArg()
- .withDescription("when listening on the specified port do not accept AMQP0-8 connections. The specified port must be one specified on the command line")
- .withLongOpt("exclude-0-8").create();
-
-
- Option mport =
- OptionBuilder.withArgName("mport").hasArg()
- .withDescription("listen on the specified management port. Overrides any value in the config file")
- .withLongOpt("mport").create("m");
-
-
- Option bind =
- OptionBuilder.withArgName("bind").hasArg()
- .withDescription("bind to the specified address. Overrides any value in the config file")
- .withLongOpt("bind").create("b");
- Option logconfig =
- OptionBuilder.withArgName("logconfig").hasArg()
- .withDescription("use the specified log4j xml configuration file. By "
- + "default looks for a file named " + DEFAULT_LOG_CONFIG_FILENAME
- + " in the same directory as the configuration file").withLongOpt("logconfig").create("l");
- Option logwatchconfig =
- OptionBuilder.withArgName("logwatch").hasArg()
- .withDescription("monitor the log file configuration file for changes. Units are seconds. "
- + "Zero means do not check for changes.").withLongOpt("logwatch").create("w");
-
- options.addOption(help);
- options.addOption(version);
- options.addOption(configFile);
- options.addOption(logconfig);
- options.addOption(logwatchconfig);
- options.addOption(port);
- options.addOption(exclude0_10);
- options.addOption(exclude0_9_1);
- options.addOption(exclude0_9);
- options.addOption(exclude0_8);
- options.addOption(mport);
- options.addOption(bind);
- }
-
- protected void execute()
- {
- // note this understands either --help or -h. If an option only has a long name you can use that but if
- // an option has a short name and a long name you must use the short name here.
- if (commandLine.hasOption("h"))
- {
- HelpFormatter formatter = new HelpFormatter();
- formatter.printHelp("Qpid", options, true);
- }
- else if (commandLine.hasOption("v"))
- {
- String ver = QpidProperties.getVersionString();
-
- StringBuilder protocol = new StringBuilder("AMQP version(s) [major.minor]: ");
-
- boolean first = true;
- for (ProtocolVersion pv : ProtocolVersion.getSupportedProtocolVersions())
- {
- if (first)
- {
- first = false;
- }
- else
- {
- protocol.append(", ");
- }
-
- protocol.append(pv.getMajorVersion()).append('-').append(pv.getMinorVersion());
-
- }
-
- System.out.println(ver + " (" + protocol + ")");
- }
- else
- {
- try
- {
- CurrentActor.set(new BrokerActor(new SystemOutMessageLogger()));
- startup();
- CurrentActor.remove();
- }
- catch (InitException e)
- {
- System.out.println("Initialisation Error : " + e.getMessage());
- shutdown(1);
- }
- catch (Throwable e)
- {
- System.out.println("Error initialising message broker: " + e);
- e.printStackTrace();
- shutdown(1);
- }
- }
- }
-
- protected void shutdown(int status)
- {
- ApplicationRegistry.removeAll();
- System.exit(status);
- }
-
- protected void startup() throws Exception
- {
- final String QpidHome = System.getProperty(QPID_HOME);
- final File defaultConfigFile = new File(QpidHome, DEFAULT_CONFIG_FILE);
- final File configFile = new File(commandLine.getOptionValue("c", defaultConfigFile.getPath()));
- 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
- {
- CurrentActor.get().message(BrokerMessages.CONFIG(configFile.getAbsolutePath()));
- }
-
- String logConfig = commandLine.getOptionValue("l");
- String logWatchConfig = commandLine.getOptionValue("w", "0");
-
- int logWatchTime = 0;
- try
- {
- logWatchTime = Integer.parseInt(logWatchConfig);
- }
- catch (NumberFormatException e)
- {
- System.err.println("Log watch configuration value of " + logWatchConfig + " is invalid. Must be "
- + "a non-negative integer. Using default of zero (no watching configured");
- }
-
- File logConfigFile;
- if (logConfig != null)
- {
- logConfigFile = new File(logConfig);
- configureLogging(logConfigFile, logWatchTime);
- }
- else
- {
- File configFileDirectory = configFile.getParentFile();
- logConfigFile = new File(configFileDirectory, DEFAULT_LOG_CONFIG_FILENAME);
- configureLogging(logConfigFile, logWatchTime);
- }
-
- ConfigurationFileApplicationRegistry config = new ConfigurationFileApplicationRegistry(configFile);
- ServerConfiguration serverConfig = config.getConfiguration();
- updateManagementPort(serverConfig, commandLine.getOptionValue("m"));
-
- ApplicationRegistry.initialise(config);
-
- // We have already loaded the BrokerMessages class by this point so we
- // need to refresh the locale setting incase we had a different value in
- // the configuration.
- BrokerMessages.reload();
-
- // AR.initialise() sets and removes its own actor so we now need to set the actor
- // for the remainder of the startup, and the default actor if the stack is empty
- CurrentActor.set(new BrokerActor(config.getCompositeStartupMessageLogger()));
- CurrentActor.setDefault(new BrokerActor(config.getRootMessageLogger()));
- GenericActor.setDefaultMessageLogger(config.getRootMessageLogger());
-
-
- try
- {
- configureLoggingManagementMBean(logConfigFile, logWatchTime);
-
- ConfigurationManagementMBean configMBean = new ConfigurationManagementMBean();
- configMBean.register();
-
- ServerInformationMBean sysInfoMBean = new ServerInformationMBean(config);
- sysInfoMBean.register();
-
-
- String[] portStr = commandLine.getOptionValues("p");
-
- Set<Integer> ports = new HashSet<Integer>();
- Set<Integer> exclude_0_10 = new HashSet<Integer>();
- Set<Integer> exclude_0_9_1 = new HashSet<Integer>();
- Set<Integer> exclude_0_9 = new HashSet<Integer>();
- Set<Integer> exclude_0_8 = new HashSet<Integer>();
-
- if(portStr == null || portStr.length == 0)
- {
-
- parsePortList(ports, serverConfig.getPorts());
- parsePortList(exclude_0_10, serverConfig.getPortExclude010());
- parsePortList(exclude_0_9_1, serverConfig.getPortExclude091());
- parsePortList(exclude_0_9, serverConfig.getPortExclude09());
- parsePortList(exclude_0_8, serverConfig.getPortExclude08());
-
- }
- else
- {
- parsePortArray(ports, portStr);
- parsePortArray(exclude_0_10, commandLine.getOptionValues("exclude-0-10"));
- parsePortArray(exclude_0_9_1, commandLine.getOptionValues("exclude-0-9-1"));
- parsePortArray(exclude_0_9, commandLine.getOptionValues("exclude-0-9"));
- parsePortArray(exclude_0_8, commandLine.getOptionValues("exclude-0-8"));
-
- }
-
-
-
-
- String bindAddr = commandLine.getOptionValue("b");
- if (bindAddr == null)
- {
- bindAddr = serverConfig.getBind();
- }
- InetAddress bindAddress = null;
-
-
-
- if (bindAddr.equals("wildcard"))
- {
- bindAddress = new InetSocketAddress(0).getAddress();
- }
- else
- {
- bindAddress = InetAddress.getByAddress(parseIP(bindAddr));
- }
-
- String hostName = bindAddress.getCanonicalHostName();
-
-
- String keystorePath = serverConfig.getKeystorePath();
- String keystorePassword = serverConfig.getKeystorePassword();
- String certType = serverConfig.getCertType();
- SSLContextFactory sslFactory = null;
-
- if (!serverConfig.getSSLOnly())
- {
-
- for(int port : ports)
- {
-
- NetworkDriver driver = new MINANetworkDriver();
-
- Set<VERSION> supported = EnumSet.allOf(VERSION.class);
-
- if(exclude_0_10.contains(port))
- {
- supported.remove(VERSION.v0_10);
- }
-
- if(exclude_0_9_1.contains(port))
- {
- supported.remove(VERSION.v0_9_1);
- }
- if(exclude_0_9.contains(port))
- {
- supported.remove(VERSION.v0_9);
- }
- if(exclude_0_8.contains(port))
- {
- supported.remove(VERSION.v0_8);
- }
-
- MultiVersionProtocolEngineFactory protocolEngineFactory =
- new MultiVersionProtocolEngineFactory(hostName, supported);
-
-
-
- driver.bind(port, new InetAddress[]{bindAddress}, protocolEngineFactory,
- serverConfig.getNetworkConfiguration(), null);
- ApplicationRegistry.getInstance().addAcceptor(new InetSocketAddress(bindAddress, port),
- new QpidAcceptor(driver,"TCP"));
- CurrentActor.get().message(BrokerMessages.LISTENING("TCP", port));
-
- }
-
- }
-
- if (serverConfig.getEnableSSL())
- {
- sslFactory = new SSLContextFactory(keystorePath, keystorePassword, certType);
- NetworkDriver driver = new MINANetworkDriver();
- driver.bind(serverConfig.getSSLPort(), new InetAddress[]{bindAddress},
- new AMQProtocolEngineFactory(), serverConfig.getNetworkConfiguration(), sslFactory);
- ApplicationRegistry.getInstance().addAcceptor(new InetSocketAddress(bindAddress, serverConfig.getSSLPort()),
- new QpidAcceptor(driver,"TCP"));
- CurrentActor.get().message(BrokerMessages.LISTENING("TCP/SSL", serverConfig.getSSLPort()));
- }
-
- CurrentActor.get().message(BrokerMessages.READY());
-
- }
- finally
- {
- // Startup is complete so remove the AR initialised Startup actor
- CurrentActor.remove();
- }
-
-
-
- }
-
- private void parsePortArray(Set<Integer> ports, String[] portStr)
- throws InitException
- {
- if(portStr != null)
- {
- for(int i = 0; i < portStr.length; i++)
- {
- try
- {
- ports.add(Integer.parseInt(portStr[i]));
- }
- catch (NumberFormatException e)
- {
- throw new InitException("Invalid port: " + portStr[i], e);
- }
- }
- }
- }
-
- private void parsePortList(Set<Integer> output, List input)
- throws InitException
- {
- if(input != null)
- {
- for(Object port : input)
- {
- try
- {
- output.add(Integer.parseInt(String.valueOf(port)));
- }
- catch (NumberFormatException e)
- {
- throw new InitException("Invalid port: " + port, e);
- }
- }
- }
- }
-
- /**
- * Update the configuration data with the management port.
- * @param configuration
- * @param managementPort The string from the command line
- */
- private void updateManagementPort(ServerConfiguration configuration, String managementPort)
- {
- if (managementPort != null)
- {
- try
- {
- configuration.setJMXManagementPort(Integer.parseInt(managementPort));
- }
- catch (NumberFormatException e)
- {
- _logger.warn("Invalid management port: " + managementPort + " will use:" + configuration.getJMXManagementPort(), e);
- }
- }
- }
-
- public static void main(String[] args)
- {
- //if the -Dlog4j.configuration property has not been set, enable the init override
- //to stop Log4J wondering off and picking up the first log4j.xml/properties file it
- //finds from the classpath when we get the first Loggers
- if(System.getProperty("log4j.configuration") == null)
- {
- System.setProperty("log4j.defaultInitOverride", "true");
- }
-
- //now that the override status is know, we can instantiate the Loggers
- _logger = Logger.getLogger(Main.class);
-
- new Main(args);
- }
-
- 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, int logWatchTime) throws InitException, IOException
- {
- if (logConfigFile.exists() && logConfigFile.canRead())
- {
- CurrentActor.get().message(BrokerMessages.LOG_CONFIG(logConfigFile.getAbsolutePath()));
-
- if (logWatchTime > 0)
- {
- System.out.println("log file " + logConfigFile.getAbsolutePath() + " will be checked for changes every "
- + logWatchTime + " seconds");
- // log4j expects the watch interval in milliseconds
- try
- {
- QpidLog4JConfigurator.configureAndWatch(logConfigFile.getPath(), logWatchTime * 1000);
- }
- catch (Exception e)
- {
- throw new InitException(e.getMessage(),e);
- }
- }
- else
- {
- try
- {
- QpidLog4JConfigurator.configure(logConfigFile.getPath());
- }
- catch (Exception e)
- {
- throw new InitException(e.getMessage(),e);
- }
- }
- }
- else
- {
- System.err.println("Logging configuration error: unable to read file " + logConfigFile.getAbsolutePath());
- System.err.println("Using the fallback internal log4j.properties configuration");
-
- InputStream propsFile = this.getClass().getResourceAsStream("/log4j.properties");
- if(propsFile == null)
- {
- throw new IOException("Unable to load the fallback internal log4j.properties configuration file");
- }
- else
- {
- try
- {
- Properties fallbackProps = new Properties();
- fallbackProps.load(propsFile);
- PropertyConfigurator.configure(fallbackProps);
- }
- finally
- {
- propsFile.close();
- }
- }
- }
- }
-
- private void configureLoggingManagementMBean(File logConfigFile, int logWatchTime) throws Exception
- {
- LoggingManagementMBean blm = new LoggingManagementMBean(logConfigFile.getPath(),logWatchTime);
-
- blm.register();
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/ack/UnacknowledgedMessageMap.java b/java/broker/src/main/java/org/apache/qpid/server/ack/UnacknowledgedMessageMap.java
deleted file mode 100644
index 3bad73d86d..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/ack/UnacknowledgedMessageMap.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.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;
-
-
-public interface UnacknowledgedMessageMap
-{
- public interface Visitor
- {
- /**
- * @param deliveryTag
- *@param message the message being iterated over @return true to stop iteration, false to continue
- * @throws AMQException
- */
- boolean callback(final long deliveryTag, QueueEntry message) throws AMQException;
-
- void visitComplete();
- }
-
- void visit(Visitor visitor) throws AMQException;
-
- void add(long deliveryTag, QueueEntry message);
-
- void collect(long deliveryTag, boolean multiple, Map<Long, QueueEntry> msgs);
-
- void remove(Map<Long,QueueEntry> msgs);
-
- QueueEntry remove(long deliveryTag);
-
- Collection<QueueEntry> cancelAllMessages();
-
- int size();
-
- void clear();
-
- QueueEntry get(long deliveryTag);
-
- /**
- * Get the set of delivery tags that are outstanding.
- *
- * @return a set of delivery tags
- */
- Set<Long> getDeliveryTags();
-
-}
-
-
diff --git a/java/broker/src/main/java/org/apache/qpid/server/ack/UnacknowledgedMessageMapImpl.java b/java/broker/src/main/java/org/apache/qpid/server/ack/UnacknowledgedMessageMapImpl.java
deleted file mode 100644
index d920d97c1a..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/ack/UnacknowledgedMessageMapImpl.java
+++ /dev/null
@@ -1,175 +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.ack;
-
-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();
-
- private long _unackedSize;
-
- private Map<Long, QueueEntry> _map;
-
- private long _lastDeliveryTag;
-
- private final int _prefetchLimit;
-
- public UnacknowledgedMessageMapImpl(int prefetchLimit)
- {
- _prefetchLimit = prefetchLimit;
- _map = new LinkedHashMap<Long, QueueEntry>(prefetchLimit);
- }
-
- public void collect(long deliveryTag, boolean multiple, Map<Long, QueueEntry> msgs)
- {
- if (multiple)
- {
- collect(deliveryTag, msgs);
- }
- else
- {
- final QueueEntry entry = get(deliveryTag);
- if(entry != null)
- {
- msgs.put(deliveryTag, entry);
- }
- }
-
- }
-
- public void remove(Map<Long,QueueEntry> msgs)
- {
- synchronized (_lock)
- {
- for (Long deliveryTag : msgs.keySet())
- {
- remove(deliveryTag);
- }
- }
- }
-
- public QueueEntry remove(long deliveryTag)
- {
- synchronized (_lock)
- {
-
- QueueEntry message = _map.remove(deliveryTag);
- if(message != null)
- {
- _unackedSize -= message.getMessage().getSize();
-
- }
-
- return message;
- }
- }
-
- public void visit(Visitor visitor) throws AMQException
- {
- synchronized (_lock)
- {
- Set<Map.Entry<Long, QueueEntry>> currentEntries = _map.entrySet();
- for (Map.Entry<Long, QueueEntry> entry : currentEntries)
- {
- visitor.callback(entry.getKey().longValue(), entry.getValue());
- }
- visitor.visitComplete();
- }
- }
-
- public void add(long deliveryTag, QueueEntry message)
- {
- synchronized (_lock)
- {
- _map.put(deliveryTag, message);
- _unackedSize += message.getMessage().getSize();
- _lastDeliveryTag = deliveryTag;
- }
- }
-
- public Collection<QueueEntry> cancelAllMessages()
- {
- synchronized (_lock)
- {
- Collection<QueueEntry> currentEntries = _map.values();
- _map = new LinkedHashMap<Long, QueueEntry>(_prefetchLimit);
- _unackedSize = 0l;
- return currentEntries;
- }
- }
-
- public int size()
- {
- synchronized (_lock)
- {
- return _map.size();
- }
- }
-
- public void clear()
- {
- synchronized (_lock)
- {
- _map.clear();
- _unackedSize = 0l;
- }
- }
-
- public QueueEntry get(long key)
- {
- synchronized (_lock)
- {
- return _map.get(key);
- }
- }
-
- public Set<Long> getDeliveryTags()
- {
- synchronized (_lock)
- {
- return _map.keySet();
- }
- }
-
- private void collect(long key, Map<Long, QueueEntry> msgs)
- {
- synchronized (_lock)
- {
- for (Map.Entry<Long, QueueEntry> entry : _map.entrySet())
- {
- msgs.put(entry.getKey(),entry.getValue());
- if (entry.getKey() == key)
- {
- break;
- }
- }
- }
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/binding/Binding.java b/java/broker/src/main/java/org/apache/qpid/server/binding/Binding.java
deleted file mode 100644
index 60c9a86b76..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/binding/Binding.java
+++ /dev/null
@@ -1,118 +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.binding;
-
-import org.apache.qpid.server.exchange.Exchange;
-import org.apache.qpid.server.queue.AMQQueue;
-
-import java.util.Collections;
-import java.util.Map;
-import java.util.UUID;
-import java.util.concurrent.atomic.AtomicLong;
-
-public class Binding
-{
- private final String _bindingKey;
- private final AMQQueue _queue;
- private final Exchange _exchange;
- private final Map<String, Object> _arguments;
- private final UUID _id;
- private final AtomicLong _matches = new AtomicLong();
-
- public Binding(UUID id, final String bindingKey, final AMQQueue queue, final Exchange exchange, final Map<String, Object> arguments)
- {
- _id = id;
- _bindingKey = bindingKey;
- _queue = queue;
- _exchange = exchange;
- _arguments = arguments == null ? Collections.EMPTY_MAP : Collections.unmodifiableMap(arguments);
- }
-
- public UUID getId()
- {
- return _id;
- }
-
- public String getBindingKey()
- {
- return _bindingKey;
- }
-
- public AMQQueue getQueue()
- {
- return _queue;
- }
-
- public Exchange getExchange()
- {
- return _exchange;
- }
-
- public Map<String, Object> getArguments()
- {
- return _arguments;
- }
-
- public void incrementMatches()
- {
- _matches.incrementAndGet();
- }
-
- public long getMatches()
- {
- return _matches.get();
- }
-
- boolean isDurable()
- {
- return _queue.isDurable() && _exchange.isDurable();
- }
-
- @Override
- public boolean equals(final Object o)
- {
- if (this == o)
- {
- return true;
- }
-
- if (o == null || !(o instanceof Binding))
- {
- return false;
- }
-
- final Binding binding = (Binding) o;
-
- return (_bindingKey == null ? binding.getBindingKey() == null : _bindingKey.equals(binding.getBindingKey()))
- && (_exchange == null ? binding.getExchange() == null : _exchange.equals(binding.getExchange()))
- && (_queue == null ? binding.getQueue() == null : _queue.equals(binding.getQueue()));
- }
-
- @Override
- public int hashCode()
- {
- int result = _bindingKey == null ? 1 : _bindingKey.hashCode();
- result = 31 * result + (_queue == null ? 3 : _queue.hashCode());
- result = 31 * result + (_exchange == null ? 5 : _exchange.hashCode());
- return result;
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/binding/BindingFactory.java b/java/broker/src/main/java/org/apache/qpid/server/binding/BindingFactory.java
deleted file mode 100644
index 400ce50bc4..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/binding/BindingFactory.java
+++ /dev/null
@@ -1,289 +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.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;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.FieldTable;
-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;
-import org.apache.qpid.server.logging.subjects.BindingLogSubject;
-import org.apache.qpid.server.queue.AMQQueue;
-import org.apache.qpid.server.store.DurableConfigurationStore;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-
-public class BindingFactory
-{
- private final VirtualHost _virtualHost;
- private final DurableConfigurationStore.Source _configSource;
- private final Exchange _defaultExchange;
-
- private final ConcurrentHashMap<BindingImpl, BindingImpl> _bindings = new ConcurrentHashMap<BindingImpl, BindingImpl>();
-
-
- public BindingFactory(final VirtualHost vhost)
- {
- this(vhost, vhost.getExchangeRegistry().getDefaultExchange());
- }
-
- public BindingFactory(final DurableConfigurationStore.Source configSource, final Exchange defaultExchange)
- {
- _configSource = configSource;
- _defaultExchange = defaultExchange;
- if (configSource instanceof VirtualHost)
- {
- _virtualHost = (VirtualHost) configSource;
- }
- else
- {
- _virtualHost = null;
- }
- }
-
- public VirtualHost getVirtualHost()
- {
- return _virtualHost;
- }
-
-
-
- private final class BindingImpl extends Binding implements AMQQueue.Task, Exchange.Task, BindingConfig
- {
- private final BindingLogSubject _logSubject;
- //TODO : persist creation time
- private long _createTime = System.currentTimeMillis();
-
- private BindingImpl(String bindingKey, final AMQQueue queue, final Exchange exchange, final Map<String, Object> arguments)
- {
- super(queue.getVirtualHost().getConfigStore().createId(), bindingKey, queue, exchange, arguments);
- _logSubject = new BindingLogSubject(bindingKey,exchange,queue);
-
- }
-
-
- public void doTask(final AMQQueue queue) throws AMQException
- {
- removeBinding(this);
- }
-
- public void onClose(final Exchange exchange) throws AMQSecurityException, AMQInternalException
- {
- removeBinding(this);
- }
-
- void logCreation()
- {
- CurrentActor.get().message(_logSubject, BindingMessages.CREATED(String.valueOf(getArguments()), getArguments() != null && !getArguments().isEmpty()));
- }
-
- void logDestruction()
- {
- CurrentActor.get().message(_logSubject, BindingMessages.DELETED());
- }
-
- public String getOrigin()
- {
- return (String) getArguments().get("qpid.fed.origin");
- }
-
- public long getCreateTime()
- {
- return _createTime;
- }
-
- public BindingConfigType getConfigType()
- {
- return BindingConfigType.getInstance();
- }
-
- public ConfiguredObject getParent()
- {
- return _virtualHost;
- }
-
- public boolean isDurable()
- {
- return getQueue().isDurable() && getExchange().isDurable();
- }
-
- }
-
-
-
- public boolean addBinding(String bindingKey, AMQQueue queue, Exchange exchange, Map<String, Object> arguments) throws AMQSecurityException, AMQInternalException
- {
- return makeBinding(bindingKey, queue, exchange, arguments, false, false);
- }
-
-
- public boolean replaceBinding(final String bindingKey,
- final AMQQueue queue,
- final Exchange exchange,
- final Map<String, Object> arguments) throws AMQSecurityException, AMQInternalException
- {
- return makeBinding(bindingKey, queue, exchange, arguments, false, true);
- }
-
- private boolean makeBinding(String bindingKey, AMQQueue queue, Exchange exchange, Map<String, Object> arguments, boolean restore, boolean force) throws AMQSecurityException, AMQInternalException
- {
- assert queue != null;
- if (bindingKey == null)
- {
- bindingKey = "";
- }
- if (exchange == null)
- {
- exchange = _defaultExchange;
- }
- if (arguments == null)
- {
- arguments = Collections.emptyMap();
- }
-
- //Perform ACLs
- if (!getVirtualHost().getSecurityManager().authoriseBind(exchange, queue, new AMQShortString(bindingKey)))
- {
- throw new AMQSecurityException("Permission denied: binding " + bindingKey);
- }
-
- BindingImpl b = new BindingImpl(bindingKey,queue,exchange,arguments);
- BindingImpl existingMapping = _bindings.putIfAbsent(b,b);
- if (existingMapping == null || force)
- {
- if (existingMapping != null)
- {
- removeBinding(existingMapping);
- }
-
- if (b.isDurable() && !restore)
- {
- _configSource.getDurableConfigurationStore().bindQueue(exchange,new AMQShortString(bindingKey),queue,FieldTable.convertToFieldTable(arguments));
- }
-
- queue.addQueueDeleteTask(b);
- exchange.addCloseTask(b);
- queue.addBinding(b);
- exchange.addBinding(b);
- getConfigStore().addConfiguredObject(b);
- b.logCreation();
-
- return true;
- }
- else
- {
- return false;
- }
- }
-
- private ConfigStore getConfigStore()
- {
- return getVirtualHost().getConfigStore();
- }
-
- public void restoreBinding(final String bindingKey, final AMQQueue queue, final Exchange exchange, final Map<String, Object> argumentMap) throws AMQSecurityException, AMQInternalException
- {
- makeBinding(bindingKey,queue,exchange,argumentMap,true, false);
- }
-
- public void removeBinding(final Binding b) throws AMQSecurityException, AMQInternalException
- {
- removeBinding(b.getBindingKey(), b.getQueue(), b.getExchange(), b.getArguments());
- }
-
-
- public Binding removeBinding(String bindingKey, AMQQueue queue, Exchange exchange, Map<String, Object> arguments) throws AMQSecurityException, AMQInternalException
- {
- assert queue != null;
- if (bindingKey == null)
- {
- bindingKey = "";
- }
- if (exchange == null)
- {
- exchange = _defaultExchange;
- }
- if (arguments == null)
- {
- arguments = Collections.emptyMap();
- }
-
- // Check access
- if (!getVirtualHost().getSecurityManager().authoriseUnbind(exchange, new AMQShortString(bindingKey), queue))
- {
- throw new AMQSecurityException("Permission denied: binding " + bindingKey);
- }
-
- BindingImpl b = _bindings.remove(new BindingImpl(bindingKey,queue,exchange,arguments));
-
- if (b != null)
- {
- exchange.removeBinding(b);
- queue.removeBinding(b);
- exchange.removeCloseTask(b);
- queue.removeQueueDeleteTask(b);
-
- if (b.isDurable())
- {
- _configSource.getDurableConfigurationStore().unbindQueue(exchange,
- new AMQShortString(bindingKey),
- queue,
- FieldTable.convertToFieldTable(arguments));
- }
- b.logDestruction();
- getConfigStore().removeConfiguredObject(b);
- }
-
- return b;
- }
-
- public Binding getBinding(String bindingKey, AMQQueue queue, Exchange exchange, Map<String, Object> arguments)
- {
- assert queue != null;
- if(bindingKey == null)
- {
- bindingKey = "";
- }
- if(exchange == null)
- {
- exchange = _defaultExchange;
- }
- if(arguments == null)
- {
- arguments = Collections.emptyMap();
- }
-
- BindingImpl b = new BindingImpl(bindingKey,queue,exchange,arguments);
- return _bindings.get(b);
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/BindingConfig.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/BindingConfig.java
deleted file mode 100644
index 233134abc5..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/configuration/BindingConfig.java
+++ /dev/null
@@ -1,41 +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.configuration;
-
-import java.util.Map;
-
-
-public interface BindingConfig extends ConfiguredObject<BindingConfigType, BindingConfig>
-{
-
- ExchangeConfig getExchange();
-
- QueueConfig getQueue();
-
- String getBindingKey();
-
- Map<String, Object> getArguments();
-
- String getOrigin();
-
- long getMatches();
-} \ No newline at end of file
diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/BindingConfigType.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/BindingConfigType.java
deleted file mode 100644
index 5cd064ff42..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/configuration/BindingConfigType.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.server.configuration;
-
-import org.apache.qpid.server.exchange.ExchangeType;
-
-import java.util.*;
-
-public final class BindingConfigType extends ConfigObjectType<BindingConfigType, BindingConfig>
-{
- private static final List<BindingProperty<?>> BINDING_PROPERTIES = new ArrayList<BindingProperty<?>>();
-
- public static interface BindingProperty<S> extends ConfigProperty<BindingConfigType, BindingConfig, S>
- {
- }
-
- private abstract static class BindingReadWriteProperty<S> extends ConfigProperty.ReadWriteConfigProperty<BindingConfigType, BindingConfig, S> implements BindingProperty<S>
- {
- public BindingReadWriteProperty(String name)
- {
- super(name);
- BINDING_PROPERTIES.add(this);
- }
- }
-
- private abstract static class BindingReadOnlyProperty<S> extends ConfigProperty.ReadOnlyConfigProperty<BindingConfigType, BindingConfig, S> implements BindingProperty<S>
- {
- public BindingReadOnlyProperty(String name)
- {
- super(name);
- BINDING_PROPERTIES.add(this);
- }
- }
-
- public static final BindingReadOnlyProperty<ExchangeConfig> EXCHANGE_PROPERTY = new BindingReadOnlyProperty<ExchangeConfig>("exchange")
- {
- public ExchangeConfig getValue(BindingConfig object)
- {
- return object.getExchange();
- }
- };
-
- public static final BindingReadOnlyProperty<QueueConfig> QUEUE_PROPERTY = new BindingReadOnlyProperty<QueueConfig>("queue")
- {
- public QueueConfig getValue(BindingConfig object)
- {
- return object.getQueue();
- }
- };
-
- public static final BindingReadOnlyProperty<String> BINDING_KEY_PROPERTY = new BindingReadOnlyProperty<String>("bindingKey")
- {
- public String getValue(BindingConfig object)
- {
- return object.getBindingKey();
- }
- };
-
- public static final BindingReadOnlyProperty<Map<String,Object>> ARGUMENTS = new BindingReadOnlyProperty<Map<String,Object>>("arguments")
- {
- public Map<String,Object> getValue(BindingConfig object)
- {
- return object.getArguments();
- }
- };
-
- public static final BindingReadOnlyProperty<String> ORIGIN_PROPERTY = new BindingReadOnlyProperty<String>("origin")
- {
- public String getValue(BindingConfig object)
- {
- return object.getOrigin();
- }
- };
-
- private static final BindingConfigType INSTANCE = new BindingConfigType();
-
- private BindingConfigType()
- {
- }
-
- public Collection<BindingProperty<?>> getProperties()
- {
- return Collections.unmodifiableList(BINDING_PROPERTIES);
- }
-
- public static BindingConfigType getInstance()
- {
- return INSTANCE;
- }
-
-
-
-} \ No newline at end of file
diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/BridgeConfig.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/BridgeConfig.java
deleted file mode 100644
index 00ed5fd0dd..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/configuration/BridgeConfig.java
+++ /dev/null
@@ -1,48 +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.configuration;
-
-public interface BridgeConfig extends ConfiguredObject<BridgeConfigType, BridgeConfig>
-{
-
- boolean isDynamic();
-
- boolean isQueueBridge();
-
- boolean isLocalSource();
-
- String getSource();
-
- String getDestination();
-
- String getKey();
-
- String getTag();
-
- String getExcludes();
-
- LinkConfig getLink();
-
- Integer getChannelId();
-
- int getAckBatching();
-} \ No newline at end of file
diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/BridgeConfigType.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/BridgeConfigType.java
deleted file mode 100644
index a8d3cd9ec3..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/configuration/BridgeConfigType.java
+++ /dev/null
@@ -1,169 +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.configuration;
-
-import org.apache.qpid.server.exchange.ExchangeType;
-
-import java.util.*;
-
-public final class BridgeConfigType extends ConfigObjectType<BridgeConfigType, BridgeConfig>
-{
- private static final List<BridgeProperty<?>> BRIDGE_PROPERTIES = new ArrayList<BridgeProperty<?>>();
-
- public static interface BridgeProperty<S> extends ConfigProperty<BridgeConfigType, BridgeConfig, S>
- {
- }
-
- private abstract static class BridgeReadWriteProperty<S> extends ConfigProperty.ReadWriteConfigProperty<BridgeConfigType, BridgeConfig, S> implements BridgeProperty<S>
- {
- public BridgeReadWriteProperty(String name)
- {
- super(name);
- BRIDGE_PROPERTIES.add(this);
- }
- }
-
- private abstract static class BridgeReadOnlyProperty<S> extends ConfigProperty.ReadOnlyConfigProperty<BridgeConfigType, BridgeConfig, S> implements BridgeProperty<S>
- {
- public BridgeReadOnlyProperty(String name)
- {
- super(name);
- BRIDGE_PROPERTIES.add(this);
- }
- }
-
- public static final BridgeReadOnlyProperty<LinkConfig> LINK_PROPERTY = new BridgeReadOnlyProperty<LinkConfig>("link")
- {
- public LinkConfig getValue(BridgeConfig object)
- {
- return object.getLink();
- }
- };
-
- public static final BridgeReadOnlyProperty<Integer> CHANNEL_ID_PROPERTY = new BridgeReadOnlyProperty<Integer>("channelId")
- {
- public Integer getValue(BridgeConfig object)
- {
- return object.getChannelId();
- }
- };
-
- public static final BridgeReadOnlyProperty<Boolean> DURABLE_PROPERTY = new BridgeReadOnlyProperty<Boolean>("durable")
- {
- public Boolean getValue(BridgeConfig object)
- {
- return object.isDurable();
- }
- };
-
- public static final BridgeReadOnlyProperty<String> SOURCE_PROPERTY = new BridgeReadOnlyProperty<String>("source")
- {
- public String getValue(BridgeConfig object)
- {
- return object.getSource();
- }
- };
-
- public static final BridgeReadOnlyProperty<String> DESTINATION_PROPERTY = new BridgeReadOnlyProperty<String>("destination")
- {
- public String getValue(BridgeConfig object)
- {
- return object.getDestination();
- }
- };
-
- public static final BridgeReadOnlyProperty<String> KEY_PROPERTY = new BridgeReadOnlyProperty<String>("key")
- {
- public String getValue(BridgeConfig object)
- {
- return object.getKey();
- }
- };
-
- public static final BridgeReadOnlyProperty<Boolean> QUEUE_BRIDGE_PROPERTY = new BridgeReadOnlyProperty<Boolean>("queueBridge")
- {
- public Boolean getValue(BridgeConfig object)
- {
- return object.isQueueBridge();
- }
- };
-
- public static final BridgeReadOnlyProperty<Boolean> LOCAL_SOURCE_PROPERTY = new BridgeReadOnlyProperty<Boolean>("localSource")
- {
- public Boolean getValue(BridgeConfig object)
- {
- return object.isLocalSource();
- }
- };
-
- public static final BridgeReadOnlyProperty<String> TAG_PROPERTY = new BridgeReadOnlyProperty<String>("tag")
- {
- public String getValue(BridgeConfig object)
- {
- return object.getTag();
- }
- };
-
- public static final BridgeReadOnlyProperty<String> EXCLUDES_PROPERTY = new BridgeReadOnlyProperty<String>("excludes")
- {
- public String getValue(BridgeConfig object)
- {
- return object.getExcludes();
- }
- };
-
- public static final BridgeReadOnlyProperty<Boolean> DYNAMIC_PROPERTY = new BridgeReadOnlyProperty<Boolean>("dynamic")
- {
- public Boolean getValue(BridgeConfig object)
- {
- return object.isDynamic();
- }
- };
-
- public static final BridgeReadOnlyProperty<Integer> ACK_BATCHING_PROPERTY = new BridgeReadOnlyProperty<Integer>("ackBatching")
- {
- public Integer getValue(BridgeConfig object)
- {
- return object.getAckBatching();
- }
- };
-
-
- private static final BridgeConfigType INSTANCE = new BridgeConfigType();
-
- private BridgeConfigType()
- {
- }
-
- public Collection<BridgeProperty<?>> getProperties()
- {
- return Collections.unmodifiableList(BRIDGE_PROPERTIES);
- }
-
- public static BridgeConfigType getInstance()
- {
- return INSTANCE;
- }
-
-
-
-} \ No newline at end of file
diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/BrokerConfig.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/BrokerConfig.java
deleted file mode 100644
index 5cdb886821..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/configuration/BrokerConfig.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.configuration;
-
-
-public interface BrokerConfig extends ConfiguredObject<BrokerConfigType,BrokerConfig>
-{
- void setSystem(SystemConfig system);
-
- SystemConfig getSystem();
-
- Integer getPort();
-
- Integer getWorkerThreads();
-
- Integer getMaxConnections();
-
- Integer getConnectionBacklogLimit();
-
- Long getStagingThreshold();
-
- Integer getManagementPublishInterval();
-
- String getVersion();
-
- String getDataDirectory();
-
- void addVirtualHost(VirtualHostConfig virtualHost);
-
- void createBrokerConnection(String transport,
- String host,
- int port,
- boolean durable,
- String authMechanism,
- String username, String password);
-
- String getFederationTag();
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/BrokerConfigType.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/BrokerConfigType.java
deleted file mode 100644
index 82b2fc82d2..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/configuration/BrokerConfigType.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.
- *
- */
-
-package org.apache.qpid.server.configuration;
-
-import java.util.*;
-import java.io.File;
-
-public final class BrokerConfigType extends ConfigObjectType<BrokerConfigType, BrokerConfig>
-{
- private static final List<BrokerProperty<?>> BROKER_PROPERTIES = new ArrayList<BrokerProperty<?>>();
-
- public static interface BrokerProperty<S> extends ConfigProperty<BrokerConfigType, BrokerConfig, S>
- {
- }
-
- private abstract static class BrokerReadWriteProperty<S> extends ConfigProperty.ReadWriteConfigProperty<BrokerConfigType, BrokerConfig, S> implements BrokerProperty<S>
- {
- public BrokerReadWriteProperty(String name)
- {
- super(name);
- BROKER_PROPERTIES.add(this);
- }
- }
-
- private abstract static class BrokerReadOnlyProperty<S> extends ConfigProperty.ReadOnlyConfigProperty<BrokerConfigType, BrokerConfig, S> implements BrokerProperty<S>
- {
- public BrokerReadOnlyProperty(String name)
- {
- super(name);
- BROKER_PROPERTIES.add(this);
- }
- }
-
- public static final BrokerReadOnlyProperty<SystemConfig> SYSTEM_PROPERTY = new BrokerReadOnlyProperty<SystemConfig>("system")
- {
- public SystemConfig getValue(BrokerConfig object)
- {
- return object.getSystem();
- }
- };
-
- public static final BrokerReadOnlyProperty<Integer> PORT_PROPERTY = new BrokerReadOnlyProperty<Integer>("port")
- {
- public Integer getValue(BrokerConfig object)
- {
- return object.getPort();
- }
- };
-
- public static final BrokerReadOnlyProperty<Integer> WORKER_THREADS_PROPERTY = new BrokerReadOnlyProperty<Integer>("workerThreads")
- {
- public Integer getValue(BrokerConfig object)
- {
- return object.getWorkerThreads();
- }
- };
-
- public static final BrokerReadOnlyProperty<Integer> MAX_CONNECTIONS_PROPERTY = new BrokerReadOnlyProperty<Integer>("maxConnections")
- {
- public Integer getValue(BrokerConfig object)
- {
- return object.getMaxConnections();
- }
- };
-
- public static final BrokerReadOnlyProperty<Integer> CONNECTION_BACKLOG_LIMIT_PROPERTY = new BrokerReadOnlyProperty<Integer>("connectionBacklog")
- {
- public Integer getValue(BrokerConfig object)
- {
- return object.getConnectionBacklogLimit();
- }
- };
-
- public static final BrokerReadOnlyProperty<Long> STAGING_THRESHOLD_PROPERTY = new BrokerReadOnlyProperty<Long>("stagingThreshold")
- {
- public Long getValue(BrokerConfig object)
- {
- return object.getStagingThreshold();
- }
- };
-
- public static final BrokerReadOnlyProperty<Integer> MANAGEMENT_PUBLISH_INTERVAL_PROPERTY = new BrokerReadOnlyProperty<Integer>("mgmtPublishInterval")
- {
- public Integer getValue(BrokerConfig object)
- {
- return object.getManagementPublishInterval();
- }
- };
-
- public static final BrokerReadOnlyProperty<String> VERSION_PROPERTY = new BrokerReadOnlyProperty<String>("version")
- {
- public String getValue(BrokerConfig object)
- {
- return object.getVersion();
- }
- };
-
- public static final BrokerReadOnlyProperty<String> DATA_DIR_PROPERTY = new BrokerReadOnlyProperty<String>("dataDirectory")
- {
- public String getValue(BrokerConfig object)
- {
- return object.getDataDirectory();
- }
- };
-
- private static final BrokerConfigType INSTANCE = new BrokerConfigType();
-
- private BrokerConfigType()
- {
- }
-
- public Collection<BrokerProperty<?>> getProperties()
- {
- return Collections.unmodifiableList(BROKER_PROPERTIES);
- }
-
- public static BrokerConfigType getInstance()
- {
- return INSTANCE;
- }
-
-
-
-} \ No newline at end of file
diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/ConfigObjectType.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/ConfigObjectType.java
deleted file mode 100644
index c45aaaf1ee..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/configuration/ConfigObjectType.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.
- *
- */
-
-package org.apache.qpid.server.configuration;
-
-import java.util.Collection;
-
-public abstract class ConfigObjectType<T extends ConfigObjectType<T,C>, C extends ConfiguredObject<T,C>>
-{
- public abstract Collection<? extends ConfigProperty<T, C, ?>> getProperties();
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/ConfigProperty.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/ConfigProperty.java
deleted file mode 100644
index 2d88ba00a0..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/configuration/ConfigProperty.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.
- *
- */
-
-package org.apache.qpid.server.configuration;
-
-public interface ConfigProperty<T extends ConfigObjectType<T,C>, C extends ConfiguredObject<T,C>, S>
-{
- public String getName();
-
- public S getValue(C object);
-
- public void setValue(C object, S value);
-
- public void clearValue(C object);
-
- public abstract static class ReadWriteConfigProperty<T extends ConfigObjectType<T,C>, C extends ConfiguredObject<T,C>,S> implements ConfigProperty<T, C, S>
- {
- private final String _name;
-
- protected ReadWriteConfigProperty(String name)
- {
- _name = name;
- }
-
- public final String getName()
- {
- return _name;
- }
- }
-
- public abstract static class ReadOnlyConfigProperty<T extends ConfigObjectType<T,C>, C extends ConfiguredObject<T,C>, S> extends ReadWriteConfigProperty<T, C, S>
- {
- protected ReadOnlyConfigProperty(String name)
- {
- super(name);
- }
-
- public final void setValue(C object, S value)
- {
- throw new UnsupportedOperationException("Cannot set value '"+getName()+"' as this property is read-only");
- }
-
- public final void clearValue(C object)
- {
- throw new UnsupportedOperationException("Cannot set value '"+getName()+"' as this property is read-only");
- }
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/ConfigStore.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/ConfigStore.java
deleted file mode 100644
index 0e03e33be8..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/configuration/ConfigStore.java
+++ /dev/null
@@ -1,184 +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.configuration;
-
-import java.util.UUID;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.CopyOnWriteArrayList;
-import java.util.concurrent.atomic.AtomicLong;
-import java.util.concurrent.atomic.AtomicReference;
-
-public class ConfigStore
-{
- private ConcurrentHashMap<ConfigObjectType, ConcurrentHashMap<UUID, ConfiguredObject>> _typeMap =
- new ConcurrentHashMap<ConfigObjectType, ConcurrentHashMap<UUID, ConfiguredObject>>();
-
- private ConcurrentHashMap<ConfigObjectType, CopyOnWriteArrayList<ConfigEventListener>> _listenerMap =
- new ConcurrentHashMap<ConfigObjectType, CopyOnWriteArrayList<ConfigEventListener>>();
-
- private AtomicReference<SystemConfig> _root = new AtomicReference<SystemConfig>(null);
-
- private final AtomicLong _objectIdSource = new AtomicLong(0l);
-
-
- public enum Event
- {
- CREATED, DELETED
- }
-
- public interface ConfigEventListener<T extends ConfigObjectType<T,C>, C extends ConfiguredObject<T, C>>
- {
- void onEvent(C object, Event evt);
- }
-
- private ConfigStore()
- {
- }
-
- public <T extends ConfigObjectType<T, C>, C extends ConfiguredObject<T, C>> ConfiguredObject<T, C> getConfiguredObject(ConfigObjectType<T,C> type, UUID id)
- {
- ConcurrentHashMap<UUID, ConfiguredObject> typeMap = _typeMap.get(type);
- if(typeMap != null)
- {
- return typeMap.get(id);
- }
- else
- {
- return null;
- }
-
- }
-
- public <T extends ConfigObjectType<T, C>, C extends ConfiguredObject<T, C>> Collection<? extends C> getConfiguredObjects(ConfigObjectType<T,C> type)
- {
- ConcurrentHashMap typeMap = _typeMap.get(type);
- if(typeMap != null)
- {
- return typeMap.values();
- }
- else
- {
- return Collections.EMPTY_LIST;
- }
-
- }
-
- public <T extends ConfigObjectType<T, C>, C extends ConfiguredObject<T, C>> void addConfiguredObject(ConfiguredObject<T, C> object)
- {
- ConcurrentHashMap typeMap = _typeMap.get(object.getConfigType());
- if(typeMap == null)
- {
- typeMap = new ConcurrentHashMap();
- ConcurrentHashMap oldMap = _typeMap.putIfAbsent(object.getConfigType(), typeMap);
- if(oldMap != null)
- {
- typeMap = oldMap;
- }
-
- }
-
- typeMap.put(object.getId(), object);
- sendEvent(Event.CREATED, object);
- }
-
-
- public <T extends ConfigObjectType<T, C>, C extends ConfiguredObject<T, C>> void removeConfiguredObject(ConfiguredObject<T, C> object)
- {
- ConcurrentHashMap typeMap = _typeMap.get(object.getConfigType());
- if(typeMap != null)
- {
- typeMap.remove(object.getId());
- sendEvent(Event.DELETED, object);
- }
- }
-
- public <T extends ConfigObjectType<T, C>, C extends ConfiguredObject<T, C>> void addConfigEventListener(T type, ConfigEventListener<T,C> listener)
- {
- CopyOnWriteArrayList listeners = _listenerMap.get(type);
- if(listeners == null)
- {
- listeners = new CopyOnWriteArrayList();
- CopyOnWriteArrayList oldListeners = _listenerMap.putIfAbsent(type, listeners);
- if(oldListeners != null)
- {
- listeners = oldListeners;
- }
-
- }
-
- listeners.add(listener);
-
- }
-
- public <T extends ConfigObjectType<T, C>, C extends ConfiguredObject<T, C>> void removeConfigEventListener(T type, ConfigEventListener<T,C> listener)
- {
- CopyOnWriteArrayList listeners = _listenerMap.get(type);
- if(listeners != null)
- {
- listeners.remove(listener);
- }
- }
-
- private void sendEvent(Event e, ConfiguredObject o)
- {
- CopyOnWriteArrayList<ConfigEventListener> listeners = _listenerMap.get(o.getConfigType());
- if(listeners != null)
- {
- for(ConfigEventListener listener : listeners)
- {
- listener.onEvent(o, e);
- }
- }
- }
-
- public boolean setRoot(SystemConfig object)
- {
- if(_root.compareAndSet(null,object))
- {
- addConfiguredObject(object);
- return true;
- }
- else
- {
- return false;
- }
- }
-
- public UUID createId()
- {
- return new UUID(0l, _objectIdSource.getAndIncrement());
- }
-
-
- public SystemConfig getRoot()
- {
- return _root.get();
- }
-
- public static ConfigStore newInstance()
- {
- return new ConfigStore();
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/ConfigurationManager.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/ConfigurationManager.java
deleted file mode 100644
index 2c492ff6b9..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/configuration/ConfigurationManager.java
+++ /dev/null
@@ -1,53 +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.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;
-
-public class ConfigurationManager
-{
- public List<ConfigurationPlugin> getConfigurationPlugins(String configurationElement, Configuration configuration) throws ConfigurationException
- {
- List<ConfigurationPlugin> plugins = new ArrayList<ConfigurationPlugin>();
- Map<List<String>, ConfigurationPluginFactory> factories =
- ApplicationRegistry.getInstance().getPluginManager().getConfigurationPlugins();
-
- for (Entry<List<String>, ConfigurationPluginFactory> entry : factories.entrySet())
- {
- if (entry.getKey().contains(configurationElement))
- {
- ConfigurationPluginFactory factory = entry.getValue();
- plugins.add(factory.newInstance(configurationElement, configuration));
- }
- }
-
- return plugins;
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/ConfiguredObject.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/ConfiguredObject.java
deleted file mode 100644
index 78666a3f93..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/configuration/ConfiguredObject.java
+++ /dev/null
@@ -1,37 +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.configuration;
-
-import java.util.UUID;
-
-public interface ConfiguredObject<T extends ConfigObjectType<T,C>, C extends ConfiguredObject<T, C>>
-{
- public UUID getId();
-
- public T getConfigType();
-
- public ConfiguredObject<T,C> getParent();
-
- public boolean isDurable();
-
- long getCreateTime();
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/ConnectionConfig.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/ConnectionConfig.java
deleted file mode 100644
index 0dd36fe1fe..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/configuration/ConnectionConfig.java
+++ /dev/null
@@ -1,49 +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.configuration;
-
-public interface ConnectionConfig extends ConfiguredObject<ConnectionConfigType, ConnectionConfig>
-{
- VirtualHostConfig getVirtualHost();
-
- String getAddress();
-
- Boolean isIncoming();
-
- Boolean isSystemConnection();
-
- Boolean isFederationLink();
-
- String getAuthId();
-
- String getRemoteProcessName();
-
- Integer getRemotePID();
-
- Integer getRemoteParentPID();
-
- ConfigStore getConfigStore();
-
- Boolean isShadow();
-
- void mgmtClose();
-} \ No newline at end of file
diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/ConnectionConfigType.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/ConnectionConfigType.java
deleted file mode 100644
index 9750b12dea..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/configuration/ConnectionConfigType.java
+++ /dev/null
@@ -1,145 +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.configuration;
-
-import org.apache.qpid.server.exchange.ExchangeType;
-
-import java.util.*;
-
-public final class ConnectionConfigType extends ConfigObjectType<ConnectionConfigType, ConnectionConfig>
-{
- private static final List<ConnectionProperty<?>> CONNECTION_PROPERTIES = new ArrayList<ConnectionProperty<?>>();
-
- public static interface ConnectionProperty<S> extends ConfigProperty<ConnectionConfigType, ConnectionConfig, S>
- {
- }
-
- private abstract static class ConnectionReadWriteProperty<S> extends ConfigProperty.ReadWriteConfigProperty<ConnectionConfigType, ConnectionConfig, S> implements ConnectionProperty<S>
- {
- public ConnectionReadWriteProperty(String name)
- {
- super(name);
- CONNECTION_PROPERTIES.add(this);
- }
- }
-
- private abstract static class ConnectionReadOnlyProperty<S> extends ConfigProperty.ReadOnlyConfigProperty<ConnectionConfigType, ConnectionConfig, S> implements ConnectionProperty<S>
- {
- public ConnectionReadOnlyProperty(String name)
- {
- super(name);
- CONNECTION_PROPERTIES.add(this);
- }
- }
-
- public static final ConnectionReadOnlyProperty<VirtualHostConfig> VIRTUAL_HOST_PROPERTY = new ConnectionReadOnlyProperty<VirtualHostConfig>("virtualHost")
- {
- public VirtualHostConfig getValue(ConnectionConfig object)
- {
- return object.getVirtualHost();
- }
- };
-
- public static final ConnectionReadOnlyProperty<String> ADDRESS_PROPERTY = new ConnectionReadOnlyProperty<String>("address")
- {
- public String getValue(ConnectionConfig object)
- {
- return object.getAddress();
- }
- };
-
- public static final ConnectionReadOnlyProperty<Boolean> INCOMING_PROPERTY = new ConnectionReadOnlyProperty<Boolean>("incoming")
- {
- public Boolean getValue(ConnectionConfig object)
- {
- return object.isIncoming();
- }
- };
-
- public static final ConnectionReadOnlyProperty<Boolean> SYSTEM_CONNECTION_PROPERTY = new ConnectionReadOnlyProperty<Boolean>("systemConnection")
- {
- public Boolean getValue(ConnectionConfig object)
- {
- return object.isSystemConnection();
- }
- };
-
- public static final ConnectionReadOnlyProperty<Boolean> FEDERATION_LINK_PROPERTY = new ConnectionReadOnlyProperty<Boolean>("federationLink")
- {
- public Boolean getValue(ConnectionConfig object)
- {
- return object.isFederationLink();
- }
- };
-
- public static final ConnectionReadOnlyProperty<String> AUTH_ID_PROPERTY = new ConnectionReadOnlyProperty<String>("authId")
- {
- public String getValue(ConnectionConfig object)
- {
- return object.getAuthId();
- }
- };
-
- public static final ConnectionReadOnlyProperty<String> REMOTE_PROCESS_NAME_PROPERTY = new ConnectionReadOnlyProperty<String>("remoteProcessName")
- {
- public String getValue(ConnectionConfig object)
- {
- return object.getRemoteProcessName();
- }
- };
-
-
- public static final ConnectionReadOnlyProperty<Integer> REMOTE_PID_PROPERTY = new ConnectionReadOnlyProperty<Integer>("remotePid")
- {
- public Integer getValue(ConnectionConfig object)
- {
- return object.getRemotePID();
- }
- };
-
- public static final ConnectionReadOnlyProperty<Integer> REMOTE_PARENT_PID_PROPERTY = new ConnectionReadOnlyProperty<Integer>("remoteParentPid")
- {
- public Integer getValue(ConnectionConfig object)
- {
- return object.getRemoteParentPID();
- }
- };
-
- private static final ConnectionConfigType INSTANCE = new ConnectionConfigType();
-
- private ConnectionConfigType()
- {
- }
-
- public Collection<ConnectionProperty<?>> getProperties()
- {
- return Collections.unmodifiableList(CONNECTION_PROPERTIES);
- }
-
- public static ConnectionConfigType getInstance()
- {
- return INSTANCE;
- }
-
-
-
-} \ No newline at end of file
diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/ExchangeConfig.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/ExchangeConfig.java
deleted file mode 100644
index 41c51d9684..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/configuration/ExchangeConfig.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.qpid.server.configuration;
-
-import org.apache.qpid.server.exchange.ExchangeType;
-
-import java.util.Map;
-
-
-public interface ExchangeConfig extends ConfiguredObject<ExchangeConfigType, ExchangeConfig>
-{
- VirtualHostConfig getVirtualHost();
-
- String getName();
-
- ExchangeType getType();
-
- boolean isAutoDelete();
-
- ExchangeConfig getAlternateExchange();
-
- Map<String, Object> getArguments();
-
-
- long getBindingCount();
-
- long getBindingCountHigh();
-
- long getMsgReceives();
-
- long getMsgRoutes();
-
- long getByteReceives();
-
- long getByteRoutes();
-} \ No newline at end of file
diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/ExchangeConfigType.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/ExchangeConfigType.java
deleted file mode 100644
index 2095301ad6..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/configuration/ExchangeConfigType.java
+++ /dev/null
@@ -1,113 +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.configuration;
-
-import org.apache.qpid.server.exchange.ExchangeType;
-
-import java.util.*;
-
-public final class ExchangeConfigType extends ConfigObjectType<ExchangeConfigType, ExchangeConfig>
-{
- private static final List<ExchangeProperty<?>> EXCHANGE_PROPERTIES = new ArrayList<ExchangeProperty<?>>();
-
- public static interface ExchangeProperty<S> extends ConfigProperty<ExchangeConfigType, ExchangeConfig, S>
- {
- }
-
- private abstract static class ExchangeReadWriteProperty<S> extends ConfigProperty.ReadWriteConfigProperty<ExchangeConfigType, ExchangeConfig, S> implements ExchangeProperty<S>
- {
- public ExchangeReadWriteProperty(String name)
- {
- super(name);
- EXCHANGE_PROPERTIES.add(this);
- }
- }
-
- private abstract static class ExchangeReadOnlyProperty<S> extends ConfigProperty.ReadOnlyConfigProperty<ExchangeConfigType, ExchangeConfig, S> implements ExchangeProperty<S>
- {
- public ExchangeReadOnlyProperty(String name)
- {
- super(name);
- EXCHANGE_PROPERTIES.add(this);
- }
- }
-
- public static final ExchangeReadOnlyProperty<VirtualHostConfig> VIRTUAL_HOST_PROPERTY = new ExchangeReadOnlyProperty<VirtualHostConfig>("virtualHost")
- {
- public VirtualHostConfig getValue(ExchangeConfig object)
- {
- return object.getVirtualHost();
- }
- };
-
- public static final ExchangeReadOnlyProperty<String> NAME_PROPERTY = new ExchangeReadOnlyProperty<String>("name")
- {
- public String getValue(ExchangeConfig object)
- {
- return object.getName();
- }
- };
-
- public static final ExchangeReadOnlyProperty<Boolean> AUTODELETE_PROPERTY = new ExchangeReadOnlyProperty<Boolean>("autodelete")
- {
- public Boolean getValue(ExchangeConfig object)
- {
- return object.isAutoDelete();
- }
- };
-
-
- public static final ExchangeReadOnlyProperty<ExchangeConfig> ALTERNATE_EXCHANGE_PROPERTY = new ExchangeReadOnlyProperty<ExchangeConfig>("alternateExchange")
- {
- public ExchangeConfig getValue(ExchangeConfig object)
- {
- return object.getAlternateExchange();
- }
- };
-
- public static final ExchangeReadOnlyProperty<Map<String,Object>> ARGUMENTS = new ExchangeReadOnlyProperty<Map<String,Object>>("arguments")
- {
- public Map<String,Object> getValue(ExchangeConfig object)
- {
- return object.getArguments();
- }
- };
-
- private static final ExchangeConfigType INSTANCE = new ExchangeConfigType();
-
- private ExchangeConfigType()
- {
- }
-
- public Collection<ExchangeProperty<?>> getProperties()
- {
- return Collections.unmodifiableList(EXCHANGE_PROPERTIES);
- }
-
- public static ExchangeConfigType getInstance()
- {
- return INSTANCE;
- }
-
-
-
-} \ No newline at end of file
diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/ExchangeConfiguration.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/ExchangeConfiguration.java
deleted file mode 100644
index c7cf0c0892..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/configuration/ExchangeConfiguration.java
+++ /dev/null
@@ -1,58 +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.configuration;
-
-import org.apache.commons.configuration.Configuration;
-
-
-public class ExchangeConfiguration
-{
-
- private Configuration _config;
- private String _name;
-
- public ExchangeConfiguration(String exchName, Configuration subset)
- {
- _name = exchName;
- _config = subset;
- }
-
- public String getName()
- {
- return _name;
- }
-
- public String getType()
- {
- return _config.getString("type","direct");
- }
-
- public boolean getDurable()
- {
- return _config.getBoolean("durable", false);
- }
-
- public boolean getAutoDelete()
- {
- return _config.getBoolean("autodelete",false);
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/ExchangeConfigurationPlugin.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/ExchangeConfigurationPlugin.java
deleted file mode 100644
index bfb2de4235..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/configuration/ExchangeConfigurationPlugin.java
+++ /dev/null
@@ -1,29 +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.configuration;
-
-import org.apache.qpid.server.configuration.plugins.ConfigurationPlugin;
-import org.apache.qpid.server.queue.AMQQueue;
-
-public interface ExchangeConfigurationPlugin
-{
- ConfigurationPlugin getConfiguration(AMQQueue queue);
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/LinkConfig.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/LinkConfig.java
deleted file mode 100644
index 5a6159df34..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/configuration/LinkConfig.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.configuration;
-
-import org.apache.qpid.server.exchange.ExchangeType;
-
-import java.util.Map;
-
-
-public interface LinkConfig extends ConfiguredObject<LinkConfigType, LinkConfig>
-{
- VirtualHostConfig getVirtualHost();
-
-
- String getTransport();
-
- String getHost();
-
- int getPort();
-
- String getRemoteVhost();
-
- String getAuthMechanism();
-
- String getUsername();
-
- String getPassword();
-
- void close();
-
- void createBridge(boolean durable,
- boolean dynamic,
- boolean srcIsQueue,
- boolean srcIsLocal,
- String src,
- String dest,
- String key, String tag, String excludes);
-} \ No newline at end of file
diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/LinkConfigType.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/LinkConfigType.java
deleted file mode 100644
index 4dc46b70c9..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/configuration/LinkConfigType.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.server.configuration;
-
-import org.apache.qpid.server.exchange.ExchangeType;
-
-import java.util.*;
-
-public final class LinkConfigType extends ConfigObjectType<LinkConfigType, LinkConfig>
-{
- private static final List<LinkProperty<?>> LINK_PROPERTIES = new ArrayList<LinkProperty<?>>();
-
- public static interface LinkProperty<S> extends ConfigProperty<LinkConfigType, LinkConfig, S>
- {
- }
-
- private abstract static class LinkReadWriteProperty<S> extends ConfigProperty.ReadWriteConfigProperty<LinkConfigType, LinkConfig, S> implements LinkProperty<S>
- {
- public LinkReadWriteProperty(String name)
- {
- super(name);
- LINK_PROPERTIES.add(this);
- }
- }
-
- private abstract static class LinkReadOnlyProperty<S> extends ConfigProperty.ReadOnlyConfigProperty<LinkConfigType, LinkConfig, S> implements LinkProperty<S>
- {
- public LinkReadOnlyProperty(String name)
- {
- super(name);
- LINK_PROPERTIES.add(this);
- }
- }
-
- public static final LinkReadOnlyProperty<VirtualHostConfig> VIRTUAL_HOST_PROPERTY = new LinkReadOnlyProperty<VirtualHostConfig>("virtualHost")
- {
- public VirtualHostConfig getValue(LinkConfig object)
- {
- return object.getVirtualHost();
- }
- };
-
- public static final LinkReadOnlyProperty<String> TRANSPORT_PROPERTY = new LinkReadOnlyProperty<String>("transport")
- {
- public String getValue(LinkConfig object)
- {
- return object.getTransport();
- }
- };
-
- public static final LinkReadOnlyProperty<String> HOST_PROPERTY = new LinkReadOnlyProperty<String>("host")
- {
- public String getValue(LinkConfig object)
- {
- return object.getHost();
- }
- };
-
- public static final LinkReadOnlyProperty<Integer> PORT_PROPERTY = new LinkReadOnlyProperty<Integer>("host")
- {
- public Integer getValue(LinkConfig object)
- {
- return object.getPort();
- }
- };
-
- public static final LinkReadOnlyProperty<String> REMOTE_VHOST_PROPERTY = new LinkReadOnlyProperty<String>("remoteVhost")
- {
- public String getValue(LinkConfig object)
- {
- return object.getRemoteVhost();
- }
- };
-
- public static final LinkReadOnlyProperty<String> AUTH_MECHANISM_PROPERTY = new LinkReadOnlyProperty<String>("authMechanism")
- {
- public String getValue(LinkConfig object)
- {
- return object.getAuthMechanism();
- }
- };
-
- public static final LinkReadOnlyProperty<String> USERNAME_PROPERTY = new LinkReadOnlyProperty<String>("username")
- {
- public String getValue(LinkConfig object)
- {
- return object.getUsername();
- }
- };
-
- public static final LinkReadOnlyProperty<String> PASSWORD_PROPERTY = new LinkReadOnlyProperty<String>("password")
- {
- public String getValue(LinkConfig object)
- {
- return object.getPassword();
- }
- };
-
- private static final LinkConfigType INSTANCE = new LinkConfigType();
-
- private LinkConfigType()
- {
- }
-
- public Collection<LinkProperty<?>> getProperties()
- {
- return Collections.unmodifiableList(LINK_PROPERTIES);
- }
-
- public static LinkConfigType getInstance()
- {
- return INSTANCE;
- }
-
-
-
-} \ No newline at end of file
diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/QueueConfig.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/QueueConfig.java
deleted file mode 100644
index be34c8d63d..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/configuration/QueueConfig.java
+++ /dev/null
@@ -1,86 +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.configuration;
-
-import java.util.Map;
-
-import org.apache.qpid.AMQException;
-
-
-public interface QueueConfig extends ConfiguredObject<QueueConfigType, QueueConfig>
-{
- VirtualHostConfig getVirtualHost();
-
- String getName();
-
- boolean isExclusive();
-
- boolean isAutoDelete();
-
- ExchangeConfig getAlternateExchange();
-
- Map<String, Object> getArguments();
-
- long getReceivedMessageCount();
-
- int getMessageCount();
-
- long getQueueDepth();
-
- int getConsumerCount();
-
- int getConsumerCountHigh();
-
- int getBindingCount();
-
- int getBindingCountHigh();
-
- ConfigStore getConfigStore();
-
- long getMessageDequeueCount();
-
- long getTotalEnqueueSize();
-
- long getTotalDequeueSize();
-
- long getByteTxnEnqueues();
-
- long getByteTxnDequeues();
-
- long getMsgTxnEnqueues();
-
- long getMsgTxnDequeues();
-
- long getPersistentByteEnqueues();
-
- long getPersistentByteDequeues();
-
- long getPersistentMsgEnqueues();
-
- long getPersistentMsgDequeues();
-
- long getUnackedMessageCount();
-
- long getUnackedMessageCountHigh();
-
- void purge(long request) throws AMQException;
-} \ No newline at end of file
diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/QueueConfigType.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/QueueConfigType.java
deleted file mode 100644
index a794ed9747..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/configuration/QueueConfigType.java
+++ /dev/null
@@ -1,121 +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.configuration;
-
-import org.apache.qpid.server.exchange.ExchangeType;
-
-import java.util.*;
-
-public final class QueueConfigType extends ConfigObjectType<QueueConfigType, QueueConfig>
-{
- private static final List<QueueProperty<?>> QUEUE_PROPERTIES = new ArrayList<QueueProperty<?>>();
-
- public static interface QueueProperty<S> extends ConfigProperty<QueueConfigType, QueueConfig, S>
- {
- }
-
- private abstract static class QueueReadWriteProperty<S> extends ConfigProperty.ReadWriteConfigProperty<QueueConfigType, QueueConfig, S> implements QueueProperty<S>
- {
- public QueueReadWriteProperty(String name)
- {
- super(name);
- QUEUE_PROPERTIES.add(this);
- }
- }
-
- private abstract static class QueueReadOnlyProperty<S> extends ConfigProperty.ReadOnlyConfigProperty<QueueConfigType, QueueConfig, S> implements QueueProperty<S>
- {
- public QueueReadOnlyProperty(String name)
- {
- super(name);
- QUEUE_PROPERTIES.add(this);
- }
- }
-
- public static final QueueReadOnlyProperty<VirtualHostConfig> VISTUAL_HOST_PROPERTY = new QueueReadOnlyProperty<VirtualHostConfig>("virtualHost")
- {
- public VirtualHostConfig getValue(QueueConfig object)
- {
- return object.getVirtualHost();
- }
- };
-
- public static final QueueReadOnlyProperty<String> NAME_PROPERTY = new QueueReadOnlyProperty<String>("name")
- {
- public String getValue(QueueConfig object)
- {
- return object.getName();
- }
- };
-
- public static final QueueReadOnlyProperty<Boolean> AUTODELETE_PROPERTY = new QueueReadOnlyProperty<Boolean>("autodelete")
- {
- public Boolean getValue(QueueConfig object)
- {
- return object.isAutoDelete();
- }
- };
-
- public static final QueueReadOnlyProperty<Boolean> EXCLUSIVE_PROPERTY = new QueueReadOnlyProperty<Boolean>("exclusive")
- {
- public Boolean getValue(QueueConfig object)
- {
- return object.isExclusive();
- }
- };
-
- public static final QueueReadOnlyProperty<ExchangeConfig> ALTERNATE_EXCHANGE_PROPERTY = new QueueReadOnlyProperty<ExchangeConfig>("alternateExchange")
- {
- public ExchangeConfig getValue(QueueConfig object)
- {
- return object.getAlternateExchange();
- }
- };
-
- public static final QueueReadOnlyProperty<Map<String,Object>> ARGUMENTS = new QueueReadOnlyProperty<Map<String,Object>>("arguments")
- {
- public Map<String,Object> getValue(QueueConfig object)
- {
- return object.getArguments();
- }
- };
-
-
- private static final QueueConfigType INSTANCE = new QueueConfigType();
-
- private QueueConfigType()
- {
- }
-
- public Collection<QueueProperty<?>> getProperties()
- {
- return Collections.unmodifiableList(QUEUE_PROPERTIES);
- }
-
- public static QueueConfigType getInstance()
- {
- return INSTANCE;
- }
-
-
-
-} \ No newline at end of file
diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/QueueConfiguration.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/QueueConfiguration.java
deleted file mode 100644
index 4512de6fb4..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/configuration/QueueConfiguration.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.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;
-
-public class QueueConfiguration extends ConfigurationPlugin
-{
- private String _name;
- private VirtualHostConfiguration _vHostConfig;
-
- public QueueConfiguration(String name, VirtualHostConfiguration virtualHostConfiguration) throws ConfigurationException
- {
- _vHostConfig = virtualHostConfiguration;
- _name = name;
-
- CompositeConfiguration mungedConf = new CompositeConfiguration();
- mungedConf.addConfiguration(_vHostConfig.getConfig().subset("queues.queue." + name));
- mungedConf.addConfiguration(_vHostConfig.getConfig().subset("queues"));
-
- setConfiguration("virtualhosts.virtualhost.queues.queue", mungedConf);
- }
-
- public String[] getElementsProcessed()
- {
- return new String[]{"maximumMessageSize",
- "maximumQueueDepth",
- "maximumMessageCount",
- "maximumMessageAge",
- "minimumAlertRepeatGap",
- "durable",
- "exchange",
- "exclusive",
- "queue",
- "autodelete",
- "priority",
- "priorities",
- "routingKey",
- "capacity",
- "flowResumeCapacity",
- "lvq",
- "lvqKey"
- };
- }
-
- @Override
- public void validateConfiguration() throws ConfigurationException
- {
- //Currently doesn't do validation
- }
-
- public VirtualHostConfiguration getVirtualHostConfiguration()
- {
- return _vHostConfig;
- }
-
- public boolean getDurable()
- {
- return getBooleanValue("durable");
- }
-
- public boolean getExclusive()
- {
- return getBooleanValue("exclusive");
- }
-
- public boolean getAutoDelete()
- {
- return getBooleanValue("autodelete");
- }
-
- public String getOwner()
- {
- return getStringValue("owner", null);
- }
-
- public boolean getPriority()
- {
- return getBooleanValue("priority");
- }
-
- public int getPriorities()
- {
- return getIntValue("priorities", -1);
- }
-
- public String getExchange()
- {
- return getStringValue("exchange", ExchangeDefaults.DEFAULT_EXCHANGE_NAME.asString());
- }
-
- public List getRoutingKeys()
- {
- return getListValue("routingKey");
- }
-
- public String getName()
- {
- return _name;
- }
-
- public int getMaximumMessageAge()
- {
- return getIntValue("maximumMessageAge", _vHostConfig.getMaximumMessageAge());
- }
-
- public long getMaximumQueueDepth()
- {
- return getLongValue("maximumQueueDepth", _vHostConfig.getMaximumQueueDepth());
- }
-
- public long getMaximumMessageSize()
- {
- return getLongValue("maximumMessageSize", _vHostConfig.getMaximumMessageSize());
- }
-
- public long getMaximumMessageCount()
- {
- return getLongValue("maximumMessageCount", _vHostConfig.getMaximumMessageCount());
- }
-
- public long getMinimumAlertRepeatGap()
- {
- return getLongValue("minimumAlertRepeatGap", _vHostConfig.getMinimumAlertRepeatGap());
- }
-
- public long getCapacity()
- {
- return getLongValue("capacity", _vHostConfig.getCapacity());
- }
-
- public long getFlowResumeCapacity()
- {
- return getLongValue("flowResumeCapacity", _vHostConfig.getFlowResumeCapacity());
- }
-
- public boolean isLVQ()
- {
- return getBooleanValue("lvq");
- }
-
- public String getLVQKey()
- {
- return getStringValue("lvqKey", null);
- }
-
-
- public static class QueueConfig extends ConfigurationPlugin
- {
- @Override
- public String[] getElementsProcessed()
- {
- return new String[]{"name"};
- }
-
- public String getName()
- {
- return getStringValue("name");
- }
-
-
- public void validateConfiguration() throws ConfigurationException
- {
- if (_configuration.isEmpty())
- {
- throw new ConfigurationException("Queue section cannot be empty.");
- }
-
- if (getName() == null)
- {
- throw new ConfigurationException("Queue section must have a 'name' element.");
- }
-
- }
-
-
- @Override
- public String formatToString()
- {
- return "Name:"+getName();
- }
-
-
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/ServerConfiguration.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/ServerConfiguration.java
deleted file mode 100644
index 297f7abdb8..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/configuration/ServerConfiguration.java
+++ /dev/null
@@ -1,860 +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.configuration;
-
-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;
-import org.apache.commons.configuration.ConfigurationFactory;
-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.management.ConfigurationManagementMBean;
-import org.apache.qpid.server.configuration.plugins.ConfigurationPlugin;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-import org.apache.qpid.server.virtualhost.VirtualHostRegistry;
-import org.apache.qpid.transport.NetworkDriverConfiguration;
-
-import sun.misc.Signal;
-import sun.misc.SignalHandler;
-
-public class ServerConfiguration extends ConfigurationPlugin implements SignalHandler
-{
- protected static final Logger _logger = Logger.getLogger(ServerConfiguration.class);
-
- // Default Configuration values
- public static final int DEFAULT_BUFFER_READ_LIMIT_SIZE = 262144;
- public static final int DEFAULT_BUFFER_WRITE_LIMIT_SIZE = 262144;
- public static final boolean DEFAULT_BROKER_CONNECTOR_PROTECTIO_ENABLED = false;
- public static final String DEFAULT_STATUS_UPDATES = "on";
- public static final String SECURITY_CONFIG_RELOADED = "SECURITY CONFIGURATION RELOADED";
-
- public static final int DEFAULT_FRAME_SIZE = 65536;
- public static final int DEFAULT_PORT = 5672;
- public static final int DEFAULT_SSL_PORT = 8672;
- public static final long DEFAULT_HOUSEKEEPING_PERIOD = 30000L;
- public static final int DEFAULT_JMXPORT = 8999;
-
- public static final String QPID_HOME = "QPID_HOME";
- public static final String QPID_WORK = "QPID_WORK";
- public static final String LIB_DIR = "lib";
- public static final String PLUGIN_DIR = "plugins";
- public static final String CACHE_DIR = "cache";
-
- private Map<String, VirtualHostConfiguration> _virtualHosts = new HashMap<String, VirtualHostConfiguration>();
-
- private File _configFile;
- private File _vhostsFile;
-
- private Logger _log = Logger.getLogger(this.getClass());
-
- private ConfigurationManagementMBean _mbean;
-
- // Map of environment variables to config items
- private static final Map<String, String> envVarMap = new HashMap<String, String>();
-
- // Configuration values to be read from the configuration file
- //todo Move all properties to static values to ensure system testing can be performed.
- public static final String CONNECTOR_PROTECTIO_ENABLED = "connector.protectio.enabled";
- public static final String CONNECTOR_PROTECTIO_READ_BUFFER_LIMIT_SIZE = "connector.protectio.readBufferLimitSize";
- public static final String CONNECTOR_PROTECTIO_WRITE_BUFFER_LIMIT_SIZE = "connector.protectio.writeBufferLimitSize";
- public static final String MGMT_CUSTOM_REGISTRY_SOCKET = "management.custom-registry-socket";
- public static final String STATUS_UPDATES = "status-updates";
- public static final String ADVANCED_LOCALE = "advanced.locale";
-
- {
- envVarMap.put("QPID_PORT", "connector.port");
- envVarMap.put("QPID_ENABLEDIRECTBUFFERS", "advanced.enableDirectBuffers");
- envVarMap.put("QPID_SSLPORT", "connector.ssl.port");
- envVarMap.put("QPID_NIO", "connector.qpidnio");
- envVarMap.put("QPID_WRITEBIASED", "advanced.useWriteBiasedPool");
- envVarMap.put("QPID_JMXPORT", "management.jmxport");
- envVarMap.put("QPID_FRAMESIZE", "advanced.framesize");
- envVarMap.put("QPID_MSGAUTH", "security.msg-auth");
- envVarMap.put("QPID_AUTOREGISTER", "auto_register");
- envVarMap.put("QPID_MANAGEMENTENABLED", "management.enabled");
- envVarMap.put("QPID_HEARTBEATDELAY", "heartbeat.delay");
- envVarMap.put("QPID_HEARTBEATTIMEOUTFACTOR", "heartbeat.timeoutFactor");
- envVarMap.put("QPID_MAXIMUMMESSAGEAGE", "maximumMessageAge");
- envVarMap.put("QPID_MAXIMUMMESSAGECOUNT", "maximumMessageCount");
- envVarMap.put("QPID_MAXIMUMQUEUEDEPTH", "maximumQueueDepth");
- envVarMap.put("QPID_MAXIMUMMESSAGESIZE", "maximumMessageSize");
- envVarMap.put("QPID_MAXIMUMCHANNELCOUNT", "maximumChannelCount");
- envVarMap.put("QPID_MINIMUMALERTREPEATGAP", "minimumAlertRepeatGap");
- envVarMap.put("QPID_QUEUECAPACITY", "capacity");
- envVarMap.put("QPID_FLOWRESUMECAPACITY", "flowResumeCapacity");
- 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");
- }
-
- /**
- * Loads the given file and sets up the HUP signal handler.
- *
- * This will load the file and present the root level properties but will
- * not perform any virtualhost configuration.
- * <p>
- * To perform this {@link #initialise()} must be called.
- * <p>
- * This has been made a two step process to allow the Plugin Manager and
- * Configuration Manager to be initialised in the Application Registry.
- * <p>
- * If using this ServerConfiguration via an ApplicationRegistry there is no
- * need to explictly call {@link #initialise()} as this is done via the
- * {@link ApplicationRegistry#initialise()} method.
- *
- * @param configurationURL
- * @throws org.apache.commons.configuration.ConfigurationException
- */
- public ServerConfiguration(File configurationURL) throws ConfigurationException
- {
- this(parseConfig(configurationURL));
- _configFile = configurationURL;
- try
- {
- Signal sig = new sun.misc.Signal("HUP");
- sun.misc.Signal.handle(sig, this);
- }
- catch (Exception e)
- {
- _logger.info("Signal HUP not supported for OS: " + System.getProperty("os.name"));
- // We're on something that doesn't handle SIGHUP, how sad, Windows.
- }
- }
-
- /**
- * Wraps the given Commons Configuration as a ServerConfiguration.
- *
- * Mainly used during testing and in locations where configuration is not
- * desired but the interface requires configuration.
- * <p>
- * If the given configuration has VirtualHost configuration then
- * {@link #initialise()} must be called to perform the required setup.
- * <p>
- * This has been made a two step process to allow the Plugin Manager and
- * Configuration Manager to be initialised in the Application Registry.
- * <p>
- * If using this ServerConfiguration via an ApplicationRegistry there is no
- * need to explictly call {@link #initialise()} as this is done via the
- * {@link ApplicationRegistry#initialise()} method.
- *
- * @param conf
- */
- public ServerConfiguration(Configuration conf)
- {
- _configuration = conf;
- }
-
- /**
- * Processes this configuration and setups any VirtualHosts defined in the
- * configuration.
- *
- * This has been separated from the constructor to allow the PluginManager
- * time to be created and provide plugins to the ConfigurationManager for
- * processing here.
- * <p>
- * Called by {@link ApplicationRegistry#initialise()}.
- * <p>
- * NOTE: A DEFAULT ApplicationRegistry must exist when using this method
- * or a new ApplicationRegistry will be created.
- *
- * @throws ConfigurationException
- */
- public void initialise() throws ConfigurationException
- {
- setConfiguration("", _configuration);
- setupVirtualHosts(_configuration);
- }
-
- public String[] getElementsProcessed()
- {
- return new String[] { "" };
- }
-
- @Override
- public void validateConfiguration() throws ConfigurationException
- {
- // Support for security.jmx.access was removed when JMX access rights were incorporated into the main ACL.
- // This ensure that users remove the element from their configuration file.
-
- if (getListValue("security.jmx.access").size() > 0)
- {
- String message = "Validation error : security/jmx/access is no longer a supported element within the configuration xml."
- + (_configFile == null ? "" : " Configuration file : " + _configFile);
- throw new ConfigurationException(message);
- }
- }
-
- /*
- * Modified to enforce virtualhosts configuration in external file or main file, but not
- * both, as a fix for QPID-2360 and QPID-2361.
- */
- @SuppressWarnings("unchecked")
- protected void setupVirtualHosts(Configuration conf) throws ConfigurationException
- {
- List<String> vhostFiles = conf.getList("virtualhosts");
- Configuration vhostConfig = conf.subset("virtualhosts");
-
- // Only one configuration mechanism allowed
- if (!vhostFiles.isEmpty() && !vhostConfig.subset("virtualhost").isEmpty())
- {
- throw new ConfigurationException("Only one of external or embedded virtualhosts configuration allowed.");
- }
-
- // We can only have one vhosts XML file included
- if (vhostFiles.size() > 1)
- {
- throw new ConfigurationException("Only one external virtualhosts configuration file allowed, multiple filenames found.");
- }
-
- // Virtualhost configuration object
- Configuration vhostConfiguration = new HierarchicalConfiguration();
-
- // Load from embedded configuration if possible
- if (!vhostConfig.subset("virtualhost").isEmpty())
- {
- vhostConfiguration = vhostConfig;
- }
- else
- {
- // Load from the external configuration if possible
- for (String fileName : vhostFiles)
- {
- // Open the vhosts XML file and copy values from it to our config
- _vhostsFile = new File(fileName);
- if (!_vhostsFile.exists())
- {
- throw new ConfigurationException("Virtualhosts file does not exist");
- }
- vhostConfiguration = parseConfig(new File(fileName));
-
- // save the default virtualhost name
- String defaultVirtualHost = vhostConfiguration.getString("default");
- _configuration.setProperty("virtualhosts.default", defaultVirtualHost);
- }
- }
-
- // Now extract the virtual host names from the configuration object
- List hosts = vhostConfiguration.getList("virtualhost.name");
- for (int j = 0; j < hosts.size(); j++)
- {
- String name = (String) hosts.get(j);
-
- // Add the virtual hosts to the server configuration
- VirtualHostConfiguration virtualhost = new VirtualHostConfiguration(name, vhostConfiguration.subset("virtualhost." + name));
- _virtualHosts.put(virtualhost.getName(), virtualhost);
- }
- }
-
- private static void substituteEnvironmentVariables(Configuration conf)
- {
- for (Entry<String, String> var : envVarMap.entrySet())
- {
- String val = System.getenv(var.getKey());
- if (val != null)
- {
- conf.setProperty(var.getValue(), val);
- }
- }
- }
-
- private static Configuration parseConfig(File file) throws ConfigurationException
- {
- ConfigurationFactory factory = new ConfigurationFactory();
- factory.setConfigurationFileName(file.getAbsolutePath());
- Configuration conf = factory.getConfiguration();
-
- Iterator<?> keys = conf.getKeys();
- if (!keys.hasNext())
- {
- keys = null;
- conf = flatConfig(file);
- }
-
- substituteEnvironmentVariables(conf);
-
- return conf;
- }
-
- /**
- * Check the configuration file to see if status updates are enabled.
- *
- * @return true if status updates are enabled
- */
- public boolean getStatusUpdatesEnabled()
- {
- // Retrieve the setting from configuration but default to on.
- String value = getStringValue(STATUS_UPDATES, DEFAULT_STATUS_UPDATES);
-
- return value.equalsIgnoreCase("on");
- }
-
- /**
- * The currently defined {@see Locale} for this broker
- *
- * @return the configuration defined locale
- */
- public Locale getLocale()
- {
- String localeString = getStringValue(ADVANCED_LOCALE);
- // Expecting locale of format langauge_country_variant
-
- // If the configuration does not have a defined locale use the JVM default
- if (localeString == null)
- {
- return Locale.getDefault();
- }
-
- String[] parts = localeString.split("_");
-
- Locale locale;
- switch (parts.length)
- {
- case 1:
- locale = new Locale(localeString);
- break;
- case 2:
- locale = new Locale(parts[0], parts[1]);
- break;
- default:
- StringBuilder variant = new StringBuilder(parts[2]);
- // If we have a variant such as the Java doc suggests for Spanish
- // Traditional_WIN we may end up with more than 3 parts on a
- // split with '_'. So we should recombine the variant.
- if (parts.length > 3)
- {
- for (int index = 3; index < parts.length; index++)
- {
- variant.append('_').append(parts[index]);
- }
- }
-
- locale = new Locale(parts[0], parts[1], variant.toString());
- }
-
- return locale;
- }
-
- // Our configuration class needs to make the interpolate method
- // public so it can be called below from the config method.
- public static class MyConfiguration extends CompositeConfiguration
- {
- public String interpolate(String obj)
- {
- return super.interpolate(obj);
- }
- }
-
- public final static Configuration flatConfig(File file) throws ConfigurationException
- {
- // We have to override the interpolate methods so that
- // interpolation takes place accross the entirety of the
- // composite configuration. Without doing this each
- // configuration object only interpolates variables defined
- // inside itself.
- final MyConfiguration conf = new MyConfiguration();
- conf.addConfiguration(new SystemConfiguration()
- {
- protected String interpolate(String o)
- {
- return conf.interpolate(o);
- }
- });
- conf.addConfiguration(new XMLConfiguration(file)
- {
- protected String interpolate(String o)
- {
- return conf.interpolate(o);
- }
- });
- return conf;
- }
-
- public String getConfigurationURL()
- {
- return _configFile == null ? "" : _configFile.getAbsolutePath();
- }
-
- public void handle(Signal arg0)
- {
- try
- {
- reparseConfigFileSecuritySections();
- }
- catch (ConfigurationException e)
- {
- _logger.error("Could not reload configuration file security sections", e);
- }
- }
-
- public void reparseConfigFileSecuritySections() throws ConfigurationException
- {
- if (_configFile != null)
- {
- Configuration newConfig = parseConfig(_configFile);
- setConfiguration("", newConfig);
- ApplicationRegistry.getInstance().getSecurityManager().configureHostPlugins(this);
-
- // Reload virtualhosts from correct location
- Configuration newVhosts;
- if (_vhostsFile == null)
- {
- newVhosts = newConfig.subset("virtualhosts");
- }
- else
- {
- newVhosts = parseConfig(_vhostsFile);
- }
-
- VirtualHostRegistry vhostRegistry = ApplicationRegistry.getInstance().getVirtualHostRegistry();
- for (String hostName : _virtualHosts.keySet())
- {
- VirtualHost vhost = vhostRegistry.getVirtualHost(hostName);
- Configuration vhostConfig = newVhosts.subset("virtualhost." + hostName);
- vhost.getConfiguration().setConfiguration("virtualhosts.virtualhost", vhostConfig); // XXX
- vhost.getSecurityManager().configureGlobalPlugins(this);
- vhost.getSecurityManager().configureHostPlugins(vhost.getConfiguration());
- }
-
- _logger.warn(SECURITY_CONFIG_RELOADED);
- }
- }
-
- public String getQpidWork()
- {
- return System.getProperty(QPID_WORK, System.getProperty("java.io.tmpdir"));
- }
-
- public String getQpidHome()
- {
- return System.getProperty(QPID_HOME);
- }
-
- public void setJMXManagementPort(int mport)
- {
- getConfig().setProperty("management.jmxport", mport);
- }
-
- public int getJMXManagementPort()
- {
- return getIntValue("management.jmxport", DEFAULT_JMXPORT);
- }
-
- public boolean getUseCustomRMISocketFactory()
- {
- return getBooleanValue(MGMT_CUSTOM_REGISTRY_SOCKET, true);
- }
-
- public void setUseCustomRMISocketFactory(boolean bool)
- {
- getConfig().setProperty(MGMT_CUSTOM_REGISTRY_SOCKET, bool);
- }
-
- public boolean getPlatformMbeanserver()
- {
- return getBooleanValue("management.platform-mbeanserver", true);
- }
-
- public String[] getVirtualHosts()
- {
- return _virtualHosts.keySet().toArray(new String[_virtualHosts.size()]);
- }
-
- public String getPluginDirectory()
- {
- return getStringValue("plugin-directory");
- }
-
- public String getCacheDirectory()
- {
- return getStringValue("cache-directory");
- }
-
- public VirtualHostConfiguration getVirtualHostConfig(String name)
- {
- return _virtualHosts.get(name);
- }
-
- public void setVirtualHostConfig(VirtualHostConfiguration config)
- {
- _virtualHosts.put(config.getName(), config);
- }
-
- public List<String> getPrincipalDatabaseNames()
- {
- return getListValue("security.principal-databases.principal-database.name");
- }
-
- public List<String> getPrincipalDatabaseClass()
- {
- return getListValue("security.principal-databases.principal-database.class");
- }
-
- public List<String> getPrincipalDatabaseAttributeNames(int index)
- {
- String name = "security.principal-databases.principal-database(" + index + ")." + "attributes.attribute.name";
- return getListValue(name);
- }
-
- public List<String> getPrincipalDatabaseAttributeValues(int index)
- {
- String name = "security.principal-databases.principal-database(" + index + ")." + "attributes.attribute.value";
- return getListValue(name);
- }
-
- public List<String> getManagementPrincipalDBs()
- {
- return getListValue("security.jmx.principal-database");
- }
-
- public int getFrameSize()
- {
- return getIntValue("advanced.framesize", DEFAULT_FRAME_SIZE);
- }
-
- public boolean getProtectIOEnabled()
- {
- return getBooleanValue(CONNECTOR_PROTECTIO_ENABLED, DEFAULT_BROKER_CONNECTOR_PROTECTIO_ENABLED);
- }
-
- public int getBufferReadLimit()
- {
- return getIntValue(CONNECTOR_PROTECTIO_READ_BUFFER_LIMIT_SIZE, DEFAULT_BUFFER_READ_LIMIT_SIZE);
- }
-
- public int getBufferWriteLimit()
- {
- return getIntValue(CONNECTOR_PROTECTIO_WRITE_BUFFER_LIMIT_SIZE, DEFAULT_BUFFER_WRITE_LIMIT_SIZE);
- }
-
- public boolean getSynchedClocks()
- {
- return getBooleanValue("advanced.synced-clocks");
- }
-
- public boolean getMsgAuth()
- {
- return getBooleanValue("security.msg-auth");
- }
-
- public String getJMXPrincipalDatabase()
- {
- return getStringValue("security.jmx.principal-database");
- }
-
- public String getManagementKeyStorePath()
- {
- return getStringValue("management.ssl.keyStorePath");
- }
-
- public boolean getManagementSSLEnabled()
- {
- return getBooleanValue("management.ssl.enabled", true);
- }
-
- public String getManagementKeyStorePassword()
- {
- return getStringValue("management.ssl.keyStorePassword");
- }
-
- public boolean getQueueAutoRegister()
- {
- return getBooleanValue("queue.auto_register", true);
- }
-
- public boolean getManagementEnabled()
- {
- return getBooleanValue("management.enabled", true);
- }
-
- public void setManagementEnabled(boolean enabled)
- {
- getConfig().setProperty("management.enabled", enabled);
- }
-
- public int getHeartBeatDelay()
- {
- return getIntValue("heartbeat.delay", 5);
- }
-
- public double getHeartBeatTimeout()
- {
- return getDoubleValue("heartbeat.timeoutFactor", 2.0);
- }
-
- public int getDeliveryPoolSize()
- {
- return getIntValue("delivery.poolsize");
- }
-
- public long getMaximumMessageAge()
- {
- return getLongValue("maximumMessageAge");
- }
-
- public long getMaximumMessageCount()
- {
- return getLongValue("maximumMessageCount");
- }
-
- public long getMaximumQueueDepth()
- {
- return getLongValue("maximumQueueDepth");
- }
-
- public long getMaximumMessageSize()
- {
- return getLongValue("maximumMessageSize");
- }
-
- public long getMinimumAlertRepeatGap()
- {
- return getLongValue("minimumAlertRepeatGap");
- }
-
- public long getCapacity()
- {
- return getLongValue("capacity");
- }
-
- public long getFlowResumeCapacity()
- {
- return getLongValue("flowResumeCapacity", getCapacity());
- }
-
- public int getProcessors()
- {
- return getIntValue("connector.processors", 4);
- }
-
- public List getPorts()
- {
- return getListValue("connector.port", Collections.singletonList(DEFAULT_PORT));
- }
-
- public List getPortExclude010()
- {
- return getListValue("connector.non010port");
- }
-
- public List getPortExclude091()
- {
- return getListValue("connector.non091port");
- }
-
- public List getPortExclude09()
- {
- return getListValue("connector.non09port");
- }
-
- public List getPortExclude08()
- {
- return getListValue("connector.non08port");
- }
-
- public String getBind()
- {
- return getStringValue("connector.bind", "wildcard");
- }
-
- public int getReceiveBufferSize()
- {
- return getIntValue("connector.socketReceiveBuffer", 32767);
- }
-
- public int getWriteBufferSize()
- {
- return getIntValue("connector.socketWriteBuffer", 32767);
- }
-
- public boolean getTcpNoDelay()
- {
- return getBooleanValue("connector.tcpNoDelay", true);
- }
-
- public boolean getEnableExecutorPool()
- {
- return getBooleanValue("advanced.filterchain[@enableExecutorPool]");
- }
-
- public boolean getEnableSSL()
- {
- return getBooleanValue("connector.ssl.enabled");
- }
-
- public boolean getSSLOnly()
- {
- return getBooleanValue("connector.ssl.sslOnly");
- }
-
- public int getSSLPort()
- {
- return getIntValue("connector.ssl.port", DEFAULT_SSL_PORT);
- }
-
- public String getKeystorePath()
- {
- return getStringValue("connector.ssl.keystorePath", "none");
- }
-
- public String getKeystorePassword()
- {
- return getStringValue("connector.ssl.keystorePassword", "none");
- }
-
- public String getCertType()
- {
- return getStringValue("connector.ssl.certType", "SunX509");
- }
-
- public boolean getQpidNIO()
- {
- return getBooleanValue("connector.qpidnio");
- }
-
- public boolean getUseBiasedWrites()
- {
- return getBooleanValue("advanced.useWriteBiasedPool");
- }
-
- public String getDefaultVirtualHost()
- {
- return getStringValue("virtualhosts.default");
- }
-
- public void setDefaultVirtualHost(String vhost)
- {
- getConfig().setProperty("virtualhosts.default", vhost);
- }
-
- public void setHousekeepingExpiredMessageCheckPeriod(long value)
- {
- getConfig().setProperty("housekeeping.expiredMessageCheckPeriod", value);
- }
-
- public long getHousekeepingCheckPeriod()
- {
- return getLongValue("housekeeping.checkPeriod",
- getLongValue("housekeeping.expiredMessageCheckPeriod",
- DEFAULT_HOUSEKEEPING_PERIOD));
- }
-
- public long getStatisticsSamplePeriod()
- {
- return getConfig().getLong("statistics.sample.period", 5000L);
- }
-
- public boolean isStatisticsGenerationBrokerEnabled()
- {
- return getConfig().getBoolean("statistics.generation.broker", false);
- }
-
- public boolean isStatisticsGenerationVirtualhostsEnabled()
- {
- return getConfig().getBoolean("statistics.generation.virtualhosts", false);
- }
-
- public boolean isStatisticsGenerationConnectionsEnabled()
- {
- return getConfig().getBoolean("statistics.generation.connections", false);
- }
-
- public long getStatisticsReportingPeriod()
- {
- return getConfig().getLong("statistics.reporting.period", 0L);
- }
-
- public boolean isStatisticsReportResetEnabled()
- {
- return getConfig().getBoolean("statistics.reporting.reset", false);
- }
-
- public NetworkDriverConfiguration getNetworkConfiguration()
- {
- return new NetworkDriverConfiguration()
- {
-
- public Integer getTrafficClass()
- {
- return null;
- }
-
- public Boolean getTcpNoDelay()
- {
- // Can't call parent getTcpNoDelay since it just calls this one
- return getBooleanValue("connector.tcpNoDelay", true);
- }
-
- public Integer getSoTimeout()
- {
- return null;
- }
-
- public Integer getSoLinger()
- {
- return null;
- }
-
- public Integer getSendBufferSize()
- {
- return getBufferWriteLimit();
- }
-
- public Boolean getReuseAddress()
- {
- return null;
- }
-
- public Integer getReceiveBufferSize()
- {
- return getBufferReadLimit();
- }
-
- public Boolean getOOBInline()
- {
- return null;
- }
-
- public Boolean getKeepAlive()
- {
- return null;
- }
- };
- }
-
- public int getMaxChannelCount()
- {
- return getIntValue("maximumChannelCount", 256);
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/SessionConfig.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/SessionConfig.java
deleted file mode 100644
index 8fef642eff..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/configuration/SessionConfig.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.qpid.server.configuration;
-
-import org.apache.qpid.AMQException;
-
-public interface SessionConfig extends ConfiguredObject<SessionConfigType, SessionConfig>
-{
- VirtualHostConfig getVirtualHost();
-
- String getSessionName();
-
- int getChannel();
-
- ConnectionConfig getConnectionConfig();
-
- boolean isAttached();
-
- long getDetachedLifespan();
-
- Long getExpiryTime();
-
- Long getMaxClientRate();
-
- Long getTxnStarts();
-
- Long getTxnCommits();
-
- Long getTxnRejects();
-
- Long getTxnCount();
-
- boolean isTransactional();
-
- void mgmtClose() throws AMQException;
-} \ No newline at end of file
diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/SessionConfigType.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/SessionConfigType.java
deleted file mode 100644
index 97cf275575..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/configuration/SessionConfigType.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.server.configuration;
-
-import org.apache.qpid.server.exchange.ExchangeType;
-
-import java.util.*;
-
-public final class SessionConfigType extends ConfigObjectType<SessionConfigType, SessionConfig>
-{
- private static final List<SessionProperty<?>> SESSION_PROPERTIES = new ArrayList<SessionProperty<?>>();
-
- public static interface SessionProperty<S> extends ConfigProperty<SessionConfigType, SessionConfig, S>
- {
- }
-
- private abstract static class SessionReadWriteProperty<S> extends ConfigProperty.ReadWriteConfigProperty<SessionConfigType, SessionConfig, S> implements SessionProperty<S>
- {
- public SessionReadWriteProperty(String name)
- {
- super(name);
- SESSION_PROPERTIES.add(this);
- }
- }
-
- private abstract static class SessionReadOnlyProperty<S> extends ConfigProperty.ReadOnlyConfigProperty<SessionConfigType, SessionConfig, S> implements SessionProperty<S>
- {
- public SessionReadOnlyProperty(String name)
- {
- super(name);
- SESSION_PROPERTIES.add(this);
- }
- }
-
- public static final SessionReadOnlyProperty<VirtualHostConfig> VIRTUAL_HOST_PROPERTY = new SessionReadOnlyProperty<VirtualHostConfig>("virtualHost")
- {
- public VirtualHostConfig getValue(SessionConfig object)
- {
- return object.getVirtualHost();
- }
- };
-
- public static final SessionReadOnlyProperty<String> NAME_PROPERTY = new SessionReadOnlyProperty<String>("name")
- {
- public String getValue(SessionConfig object)
- {
- return object.getSessionName();
- }
- };
-
- public static final SessionReadOnlyProperty<Integer> CHANNEL_ID_PROPERTY = new SessionReadOnlyProperty<Integer>("channelId")
- {
- public Integer getValue(SessionConfig object)
- {
- return object.getChannel();
- }
- };
-
- public static final SessionReadOnlyProperty<ConnectionConfig> CONNECTION_PROPERTY = new SessionReadOnlyProperty<ConnectionConfig>("connection")
- {
- public ConnectionConfig getValue(SessionConfig object)
- {
- return object.getConnectionConfig();
- }
- };
-
- public static final SessionReadOnlyProperty<Boolean> ATTACHED_PROPERTY = new SessionReadOnlyProperty<Boolean>("attached")
- {
- public Boolean getValue(SessionConfig object)
- {
- return object.isAttached();
- }
- };
-
- public static final SessionReadOnlyProperty<Long> DETACHED_LIFESPAN_PROPERTY = new SessionReadOnlyProperty<Long>("detachedLifespan")
- {
- public Long getValue(SessionConfig object)
- {
- return object.getDetachedLifespan();
- }
- };
-
- public static final SessionReadOnlyProperty<Long> EXPIRE_TIME_PROPERTY = new SessionReadOnlyProperty<Long>("expireTime")
- {
- public Long getValue(SessionConfig object)
- {
- return object.getExpiryTime();
- }
- };
-
- public static final SessionReadOnlyProperty<Long> MAX_CLIENT_RATE_PROPERTY = new SessionReadOnlyProperty<Long>("maxClientRate")
- {
- public Long getValue(SessionConfig object)
- {
- return object.getMaxClientRate();
- }
- };
-
- private static final SessionConfigType INSTANCE = new SessionConfigType();
-
- private SessionConfigType()
- {
- }
-
- public Collection<SessionProperty<?>> getProperties()
- {
- return Collections.unmodifiableList(SESSION_PROPERTIES);
- }
-
- public static SessionConfigType getInstance()
- {
- return INSTANCE;
- }
-
-
-
-} \ No newline at end of file
diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/SubscriptionConfig.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/SubscriptionConfig.java
deleted file mode 100644
index b101d70553..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/configuration/SubscriptionConfig.java
+++ /dev/null
@@ -1,47 +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.configuration;
-
-import java.util.Map;
-
-
-public interface SubscriptionConfig extends ConfiguredObject<SubscriptionConfigType, SubscriptionConfig>
-{
-
- SessionConfig getSessionConfig();
-
- QueueConfig getQueue();
-
- String getName();
-
- Map<String, Object> getArguments();
-
- String getCreditMode();
-
- boolean isBrowsing();
-
- boolean isExclusive();
-
- boolean isExplicitAcknowledge();
-
- Long getDelivered();
-} \ No newline at end of file
diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/SubscriptionConfigType.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/SubscriptionConfigType.java
deleted file mode 100644
index 99d3273b55..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/configuration/SubscriptionConfigType.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.server.configuration;
-
-
-import java.util.*;
-
-public final class SubscriptionConfigType extends ConfigObjectType<SubscriptionConfigType, SubscriptionConfig>
-{
- private static final List<SubscriptionProperty<?>> SUBSCRIPTION_PROPERTIES = new ArrayList<SubscriptionProperty<?>>();
-
- public static interface SubscriptionProperty<S> extends ConfigProperty<SubscriptionConfigType, SubscriptionConfig, S>
- {
- }
-
- private abstract static class SubscriptionReadWriteProperty<S> extends ConfigProperty.ReadWriteConfigProperty<SubscriptionConfigType, SubscriptionConfig, S> implements SubscriptionProperty<S>
- {
- public SubscriptionReadWriteProperty(String name)
- {
- super(name);
- SUBSCRIPTION_PROPERTIES.add(this);
- }
- }
-
- private abstract static class SubscriptionReadOnlyProperty<S> extends ConfigProperty.ReadOnlyConfigProperty<SubscriptionConfigType, SubscriptionConfig, S> implements SubscriptionProperty<S>
- {
- public SubscriptionReadOnlyProperty(String name)
- {
- super(name);
- SUBSCRIPTION_PROPERTIES.add(this);
- }
- }
-
- public static final SubscriptionReadOnlyProperty<SessionConfig> SESSION_PROPERTY = new SubscriptionReadOnlyProperty<SessionConfig>("session")
- {
- public SessionConfig getValue(SubscriptionConfig object)
- {
- return object.getSessionConfig();
- }
- };
-
- public static final SubscriptionReadOnlyProperty<QueueConfig> QUEUE_PROPERTY = new SubscriptionReadOnlyProperty<QueueConfig>("queue")
- {
- public QueueConfig getValue(SubscriptionConfig object)
- {
- return object.getQueue();
- }
- };
-
- public static final SubscriptionReadOnlyProperty<String> NAME_PROPERTY = new SubscriptionReadOnlyProperty<String>("name")
- {
- public String getValue(SubscriptionConfig object)
- {
- return object.getName();
- }
- };
-
- public static final SubscriptionReadOnlyProperty<Map<String,Object>> ARGUMENTS = new SubscriptionReadOnlyProperty<Map<String,Object>>("arguments")
- {
- public Map<String,Object> getValue(SubscriptionConfig object)
- {
- return object.getArguments();
- }
- };
-
- public static final SubscriptionReadOnlyProperty<String> CREDIT_MODE_PROPERTY = new SubscriptionReadOnlyProperty<String>("creditMode")
- {
- public String getValue(SubscriptionConfig object)
- {
- return object.getCreditMode();
- }
- };
-
- public static final SubscriptionReadOnlyProperty<Boolean> BROWSING_PROPERTY = new SubscriptionReadOnlyProperty<Boolean>("browsing")
- {
- public Boolean getValue(SubscriptionConfig object)
- {
- return object.isBrowsing();
- }
- };
-
- public static final SubscriptionReadOnlyProperty<Boolean> EXCLUSIVE_PROPERTY = new SubscriptionReadOnlyProperty<Boolean>("exclusive")
- {
- public Boolean getValue(SubscriptionConfig object)
- {
- return object.isExclusive();
- }
- };
-
- public static final SubscriptionReadOnlyProperty<Boolean> EXPLICIT_ACK_PROPERTY = new SubscriptionReadOnlyProperty<Boolean>("explicitAck")
- {
- public Boolean getValue(SubscriptionConfig object)
- {
- return object.isExplicitAcknowledge();
- }
- };
-
- private static final SubscriptionConfigType INSTANCE = new SubscriptionConfigType();
-
- private SubscriptionConfigType()
- {
- }
-
- public Collection<SubscriptionProperty<?>> getProperties()
- {
- return Collections.unmodifiableList(SUBSCRIPTION_PROPERTIES);
- }
-
-
- public static SubscriptionConfigType getInstance()
- {
- return INSTANCE;
- }
-
-
-
-} \ No newline at end of file
diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/SystemConfig.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/SystemConfig.java
deleted file mode 100644
index 8a9029fbfd..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/configuration/SystemConfig.java
+++ /dev/null
@@ -1,42 +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.configuration;
-
-public interface SystemConfig extends ConfiguredObject<SystemConfigType,SystemConfig>
-{
- String getName();
-
- String getOperatingSystemName();
-
- String getNodeName();
-
-
- String getOSRelease();
-
- String getOSVersion();
-
- String getOSArchitecture();
-
- void addBroker(BrokerConfig broker);
-
- void removeBroker(BrokerConfig broker);
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/SystemConfigImpl.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/SystemConfigImpl.java
deleted file mode 100644
index 09ebb07105..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/configuration/SystemConfigImpl.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.server.configuration;
-
-import java.util.UUID;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-
-public class SystemConfigImpl implements SystemConfig
-{
- private static final String OS_NAME = System.getProperty("os.name");
- private static final String OS_ARCH = System.getProperty("os.arch");
- private static final String OS_VERSION = System.getProperty("os.version");
-
- private final UUID _id;
- private String _name;
-
- private final String _host;
-
- private final Map<UUID, BrokerConfig> _brokers = new ConcurrentHashMap<UUID, BrokerConfig>();
-
- private final long _createTime = System.currentTimeMillis();
- private final ConfigStore _store;
-
- public SystemConfigImpl(ConfigStore store)
- {
- this(store.createId(), store);
- }
-
- public SystemConfigImpl(UUID id, ConfigStore store)
- {
- _id = id;
- _store = store;
- String host;
- try
- {
- InetAddress addr = InetAddress.getLocalHost();
- host = addr.getHostName();
- }
- catch (UnknownHostException e)
- {
- host="localhost";
- }
- _host = host;
- }
-
- public String getName()
- {
- return _name;
- }
-
- public String getOperatingSystemName()
- {
- return OS_NAME;
- }
-
- public String getNodeName()
- {
- return _host;
- }
-
- public String getOSRelease()
- {
- return OS_VERSION;
- }
-
- public String getOSVersion()
- {
- return "";
- }
-
- public String getOSArchitecture()
- {
- return OS_ARCH;
- }
-
- public UUID getId()
- {
- return _id;
- }
-
- public SystemConfigType getConfigType()
- {
- return SystemConfigType.getInstance();
- }
-
- public ConfiguredObject getParent()
- {
- return null;
- }
-
- public boolean isDurable()
- {
- return false;
- }
-
- public void addBroker(final BrokerConfig broker)
- {
- broker.setSystem(this);
- _store.addConfiguredObject(broker);
- _brokers.put(broker.getId(), broker);
- }
-
- public void removeBroker(final BrokerConfig broker)
- {
- _brokers.remove(broker.getId());
- _store.removeConfiguredObject(broker);
- }
-
- public long getCreateTime()
- {
- return _createTime;
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/SystemConfigType.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/SystemConfigType.java
deleted file mode 100644
index f5aabd2345..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/configuration/SystemConfigType.java
+++ /dev/null
@@ -1,128 +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.configuration;
-
-import java.util.*;
-
-public final class SystemConfigType extends ConfigObjectType<SystemConfigType, SystemConfig>
-{
- private static final List<SystemProperty<?>> SYSTEM_PROPERTIES = new ArrayList<SystemProperty<?>>();
-
- public static interface SystemProperty<S> extends ConfigProperty<SystemConfigType, SystemConfig, S>
- {
- }
-
- private abstract static class SystemReadWriteProperty<S> extends ConfigProperty.ReadWriteConfigProperty<SystemConfigType, SystemConfig, S> implements SystemProperty<S>
- {
- public SystemReadWriteProperty(String name)
- {
- super(name);
- SYSTEM_PROPERTIES.add(this);
- }
- }
-
- private abstract static class SystemReadOnlyProperty<S> extends ConfigProperty.ReadOnlyConfigProperty<SystemConfigType, SystemConfig, S> implements SystemProperty<S>
- {
- public SystemReadOnlyProperty(String name)
- {
- super(name);
- SYSTEM_PROPERTIES.add(this);
- }
- }
-
- public static final SystemReadOnlyProperty<String> NAME_PROPERTY = new SystemReadOnlyProperty<String>("name")
- {
- public String getValue(SystemConfig object)
- {
- return object.getName();
- }
- };
-
- public static final SystemReadOnlyProperty<UUID> ID_PROPERTY = new SystemReadOnlyProperty<UUID>("id")
- {
- public UUID getValue(SystemConfig object)
- {
- return object.getId();
- }
- };
-
- public static final SystemReadOnlyProperty<String> OS_NAME_PROPERTY = new SystemReadOnlyProperty<String>("osName")
- {
- public String getValue(SystemConfig object)
- {
- return object.getOperatingSystemName();
- }
- };
-
- public static final SystemReadOnlyProperty<String> NODE_NAME_PROPERTY = new SystemReadOnlyProperty<String>("nodeName")
- {
- public String getValue(SystemConfig object)
- {
- return object.getNodeName();
- }
- };
-
- public static final SystemReadOnlyProperty<String> RELEASE_PROPERTY = new SystemReadOnlyProperty<String>("release")
- {
- public String getValue(SystemConfig object)
- {
- return object.getOSRelease();
- }
- };
-
- public static final SystemReadOnlyProperty<String> VERSION_PROPERTY = new SystemReadOnlyProperty<String>("version")
- {
- public String getValue(SystemConfig object)
- {
- return object.getOSVersion();
- }
- };
-
- public static final SystemReadOnlyProperty<String> MACHINE_PROPERTY = new SystemReadOnlyProperty<String>("machine")
- {
- public String getValue(SystemConfig object)
- {
- return object.getOSArchitecture();
- }
- };
-
- private static final SystemConfigType INSTANCE = new SystemConfigType();
-
- private SystemConfigType()
- {
- }
-
- public Collection<SystemProperty<?>> getProperties()
- {
- return Collections.unmodifiableList(SYSTEM_PROPERTIES);
- }
-
-
-
- public static SystemConfigType getInstance()
- {
- return INSTANCE;
- }
-
-
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/TopicConfig.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/TopicConfig.java
deleted file mode 100644
index d5420d9718..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/configuration/TopicConfig.java
+++ /dev/null
@@ -1,78 +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.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();
- }
-
- @Override
- public String[] getElementsProcessed()
- {
- return new String[]{"name", "subscriptionName"};
- }
-
- public String getName()
- {
- // If we don't have a specific topic then this config is for all topics.
- return getStringValue("name", "#");
- }
-
- public String getSubscriptionName()
- {
- return getStringValue("subscriptionName");
- }
-
- public void validateConfiguration() throws ConfigurationException
- {
- if (_configuration.isEmpty())
- {
- throw new ConfigurationException("Topic section cannot be empty.");
- }
-
- if (getStringValue("name") == null && getSubscriptionName() == null)
- {
- throw new ConfigurationException("Topic section must have a 'name' or 'subscriptionName' element.");
- }
-
- System.err.println("********* Created TC:"+this);
- }
-
-
- @Override
- public String formatToString()
- {
- String response = "Topic:"+getName();
- if (getSubscriptionName() != null)
- {
- response += ", SubscriptionName:"+getSubscriptionName();
- }
-
- return response;
- }
-} \ No newline at end of file
diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/TopicConfiguration.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/TopicConfiguration.java
deleted file mode 100644
index 8716fed8c1..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/configuration/TopicConfiguration.java
+++ /dev/null
@@ -1,269 +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.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;
-import org.apache.qpid.server.exchange.TopicExchange;
-import org.apache.qpid.server.queue.AMQQueue;
-
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-
-public class TopicConfiguration extends ConfigurationPlugin implements ExchangeConfigurationPlugin
-{
- public static final ConfigurationPluginFactory FACTORY = new TopicConfigurationFactory();
-
- private static final String VIRTUALHOSTS_VIRTUALHOST_TOPICS = "virtualhosts.virtualhost.topics";
-
- public static class TopicConfigurationFactory implements ConfigurationPluginFactory
- {
-
- public ConfigurationPlugin newInstance(String path, Configuration config) throws ConfigurationException
- {
- TopicConfiguration topicsConfig = new TopicConfiguration();
- topicsConfig.setConfiguration(path, config);
- return topicsConfig;
- }
-
- public List<String> getParentPaths()
- {
- return Arrays.asList(VIRTUALHOSTS_VIRTUALHOST_TOPICS);
- }
- }
-
- Map<String, TopicConfig> _topics = new HashMap<String, TopicConfig>();
- Map<String, Map<String, TopicConfig>> _subscriptions = new HashMap<String, Map<String, TopicConfig>>();
-
- public String[] getElementsProcessed()
- {
- return new String[]{"topic"};
- }
-
- @Override
- public void validateConfiguration() throws ConfigurationException
- {
- if (_configuration.isEmpty())
- {
- throw new ConfigurationException("Topics section cannot be empty.");
- }
-
- int topics = _configuration.getList("topic.name").size() +
- _configuration.getList("topic.subscriptionName").size();
-
- for (int index = 0; index < topics; index++)
- {
- Configuration topicSubset = _configuration.subset("topic(" + index + ")");
-
- // This will occur when we have a subscriptionName that is bound to a
- // topic.
- if (topicSubset.isEmpty())
- {
- break;
- }
-
- TopicConfig topic = new TopicConfig();
-
- topic.setConfiguration(VIRTUALHOSTS_VIRTUALHOST_TOPICS + ".topic", topicSubset );
-
- String name = _configuration.getString("topic(" + index + ").name");
- String subscriptionName = _configuration.getString("topic(" + index + ").subscriptionName");
-
- // Record config if subscriptionName is there
- if (subscriptionName != null)
- {
- processSubscription(subscriptionName, topic);
- }
- else
- {
- // Otherwise record config as topic if we have the name
- if (name != null)
- {
- processTopic(name, topic);
- }
- }
- }
- }
-
- /**
- * @param name
- * @param topic
- *
- * @throws org.apache.commons.configuration.ConfigurationException
- *
- */
- private void processTopic(String name, TopicConfig topic) throws ConfigurationException
- {
- if (_topics.containsKey(name))
- {
- throw new ConfigurationException("Topics section cannot contain two entries for the same topic.");
- }
- else
- {
- _topics.put(name, topic);
- }
- }
-
-
- private void processSubscription(String name, TopicConfig topic) throws ConfigurationException
- {
- Map<String,TopicConfig> topics;
- if (_subscriptions.containsKey(name))
- {
- topics = _subscriptions.get(name);
-
- if (topics.containsKey(topic.getName()))
- {
- throw new ConfigurationException("Subcription cannot contain two entries for the same topic.");
- }
- }
- else
- {
- topics = new HashMap<String,TopicConfig>();
- }
-
- topics.put(topic.getName(),topic);
- _subscriptions.put(name, topics);
-
- }
-
- @Override
- public String formatToString()
- {
- return "Topics:" + _topics + ", Subscriptions:" + _subscriptions;
- }
-
- /**
- * This processes the given queue and apply configuration in the following
- * order:
- *
- * Global Topic Values -> Topic Values -> Subscription Values
- *
- * @param queue
- *
- * @return
- */
- public ConfigurationPlugin getConfiguration(AMQQueue queue)
- {
- //Create config with global topic configuration
- TopicConfig config = new TopicConfig();
-
- // Add global topic configuration
- config.addConfiguration(this);
-
- // Process Topic Bindings as these are more generic than subscriptions
- List<TopicConfig> boundToTopics = new LinkedList<TopicConfig>();
-
- //Merge the configuration in the order that they are bound
- for (Binding binding : queue.getBindings())
- {
- if (binding.getExchange().getType().equals(TopicExchange.TYPE))
- {
- // Identify topic for the binding key
- TopicConfig topicConfig = getTopicConfigForRoutingKey(binding.getBindingKey());
- if (topicConfig != null)
- {
- boundToTopics.add(topicConfig);
- }
- }
- }
-
- // If the Queue is bound to a number of topics then only use the global
- // topic configuration.
- // todo - What does it mean in terms of configuration to be bound to a
- // number of topics? Do we try and merge?
- // YES - right thing to do would be to merge from generic to specific.
- // Means we need to be able to get an ordered list of topics for this
- // binding.
- if (boundToTopics.size() == 1)
- {
- config.addConfiguration(boundToTopics.get(0));
- }
-
- // If we have a subscription then attempt to look it up.
- String subscriptionName = queue.getName();
-
- // Apply subscription configurations
- if (_subscriptions.containsKey(subscriptionName))
- {
-
- //Get all the Configuration that this subscription is bound to.
- Map<String, TopicConfig> topics = _subscriptions.get(subscriptionName);
-
- TopicConfig subscriptionSpecificConfig = null;
-
- // See if we have a TopicConfig in topics for a topic we are bound to.
- for (Binding binding : queue.getBindings())
- {
- if (binding.getExchange().getType().equals(TopicExchange.TYPE))
- {
- //todo - What does it mean to have multiple matches?
- // Take the first match we get
- if (subscriptionSpecificConfig == null)
- {
- // lookup the binding to see if we have a match in the subscription configs
- subscriptionSpecificConfig = topics.get(binding.getBindingKey());
- }
- }
- }
-
- //todo we don't account for wild cards here. only explicit matching and all subscriptions
- if (subscriptionSpecificConfig == null)
- {
- // lookup the binding to see if we have a match in the subscription configs
- subscriptionSpecificConfig = topics.get("#");
- }
-
- // Apply subscription specific config.
- if (subscriptionSpecificConfig != null)
- {
- config.addConfiguration(subscriptionSpecificConfig);
- }
- }
- return config;
- }
-
- /**
- * This method should perform the same heuristics as the TopicExchange
- * to attempt to identify a piece of configuration for the give routingKey.
- *
- * i.e. If we have 'stocks.*' defined in the config
- * and we bind 'stocks.appl' then we should return the 'stocks.*'
- * configuration.
- *
- * @param routingkey the key to lookup
- *
- * @return the TopicConfig if found.
- */
- private TopicConfig getTopicConfigForRoutingKey(String routingkey)
- {
- //todo actually perform TopicExchange style lookup not just straight
- // lookup as we are just now.
- return _topics.get(routingkey);
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/VirtualHostConfig.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/VirtualHostConfig.java
deleted file mode 100644
index 9256724c56..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/configuration/VirtualHostConfig.java
+++ /dev/null
@@ -1,34 +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.configuration;
-
-public interface VirtualHostConfig extends ConfiguredObject<VirtualHostConfigType, VirtualHostConfig>
-{
- String getName();
-
- BrokerConfig getBroker();
-
- String getFederationTag();
-
- void setBroker(BrokerConfig brokerConfig);
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/VirtualHostConfigType.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/VirtualHostConfigType.java
deleted file mode 100644
index 96682335bf..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/configuration/VirtualHostConfigType.java
+++ /dev/null
@@ -1,96 +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.configuration;
-
-import java.util.*;
-
-public class VirtualHostConfigType extends ConfigObjectType<VirtualHostConfigType, VirtualHostConfig>
-{
- private static final List<VirtualHostProperty<?>> VIRTUAL_HOST_PROPERTIES = new ArrayList<VirtualHostProperty<?>>();
- private static final VirtualHostConfigType INSTANCE = new VirtualHostConfigType();
-public static interface VirtualHostProperty<S> extends ConfigProperty<VirtualHostConfigType, VirtualHostConfig, S>
- {
- }
-
- private abstract static class VirtualHostReadWriteProperty<S> extends ConfigProperty.ReadWriteConfigProperty<VirtualHostConfigType, VirtualHostConfig, S> implements VirtualHostProperty<S>
- {
- public VirtualHostReadWriteProperty(String name)
- {
- super(name);
- VIRTUAL_HOST_PROPERTIES.add(this);
- }
- }
-
- private abstract static class VirtualHostReadOnlyProperty<S> extends ConfigProperty.ReadOnlyConfigProperty<VirtualHostConfigType, VirtualHostConfig, S> implements VirtualHostProperty<S>
- {
- public VirtualHostReadOnlyProperty(String name)
- {
- super(name);
- VIRTUAL_HOST_PROPERTIES.add(this);
- }
- }
-
-
- public static final VirtualHostReadOnlyProperty<String> NAME_PROPERTY = new VirtualHostReadOnlyProperty<String>("name")
- {
- public String getValue(VirtualHostConfig object)
- {
- return object.getName();
- }
- };
-
-
- public static final VirtualHostReadOnlyProperty<BrokerConfig> BROKER_PROPERTY = new VirtualHostReadOnlyProperty<BrokerConfig>("broker")
- {
- public BrokerConfig getValue(VirtualHostConfig object)
- {
- return object.getBroker();
- }
- };
-
- public static final VirtualHostReadOnlyProperty<String> FEDERATION_TAG_PROPERTY = new VirtualHostReadOnlyProperty<String>("federationTag")
- {
- public String getValue(VirtualHostConfig object)
- {
- return object.getFederationTag();
- }
- };
-
-
-
- public Collection<? extends ConfigProperty<VirtualHostConfigType, VirtualHostConfig, ?>> getProperties()
- {
- return Collections.unmodifiableList(VIRTUAL_HOST_PROPERTIES);
- }
-
-
- private VirtualHostConfigType()
- {
- }
-
- public static VirtualHostConfigType getInstance()
- {
- return INSTANCE;
- }
-
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/VirtualHostConfiguration.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/VirtualHostConfiguration.java
deleted file mode 100644
index a710230616..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/configuration/VirtualHostConfiguration.java
+++ /dev/null
@@ -1,342 +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.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;
-import org.apache.qpid.server.configuration.plugins.ConfigurationPlugin;
-import org.apache.qpid.server.queue.AMQQueue;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-import org.apache.qpid.server.store.MemoryMessageStore;
-
-public class VirtualHostConfiguration extends ConfigurationPlugin
-{
- private String _name;
- private Map<String, QueueConfiguration> _queues = new HashMap<String, QueueConfiguration>();
- private Map<String, ExchangeConfiguration> _exchanges = new HashMap<String, ExchangeConfiguration>();
-
- public VirtualHostConfiguration(String name, Configuration config) throws ConfigurationException
- {
- _name = name;
- setConfiguration(config);
- }
-
- /**
- * Apply the given configuration to this VirtualHostConfiguration
- *
- * @param config the config to apply
- * @throws ConfigurationException if a problem occurs with configuration
- */
- public void setConfiguration(Configuration config) throws ConfigurationException
- {
- setConfiguration("virtualhosts.virtualhost", config);
-
- Iterator i = getListValue("queues.queue.name").iterator();
-
- while (i.hasNext())
- {
- String queueName = (String) i.next();
- _queues.put(queueName, new QueueConfiguration(queueName, this));
- }
-
- i = getListValue("exchanges.exchange.name").iterator();
- int count = 0;
- while (i.hasNext())
- {
- CompositeConfiguration mungedConf = new CompositeConfiguration();
- mungedConf.addConfiguration(config.subset("exchanges.exchange(" + count++ + ")"));
- mungedConf.addConfiguration(_configuration.subset("exchanges"));
- String exchName = (String) i.next();
- _exchanges.put(exchName, new ExchangeConfiguration(exchName, mungedConf));
- }
- }
-
- public String getName()
- {
- return _name;
- }
-
- public long getHousekeepingExpiredMessageCheckPeriod()
- {
- return getLongValue("housekeeping.expiredMessageCheckPeriod", ApplicationRegistry.getInstance().getConfiguration().getHousekeepingCheckPeriod());
- }
-
- public String getAuthenticationDatabase()
- {
- return getStringValue("security.authentication.name");
- }
-
- public List getCustomExchanges()
- {
- return getListValue("custom-exchanges.class-name");
- }
-
- public Configuration getStoreConfiguration()
- {
- return _configuration.subset("store");
- }
-
- public String getMessageStoreClass()
- {
- return getStringValue("store.class", MemoryMessageStore.class.getName());
- }
-
- public void setMessageStoreClass(String storeClass)
- {
- _configuration.setProperty("store.class", storeClass);
- }
-
- public List getExchanges()
- {
- return getListValue("exchanges.exchange.name");
- }
-
- public String[] getQueueNames()
- {
- return _queues.keySet().toArray(new String[_queues.size()]);
- }
-
- public ExchangeConfiguration getExchangeConfiguration(String exchangeName)
- {
- return _exchanges.get(exchangeName);
- }
-
- public QueueConfiguration getQueueConfiguration(String queueName)
- {
- // We might be asked for the config for a queue we don't know about,
- // such as one that's been dynamically created. Those get the defaults by default.
- if (_queues.containsKey(queueName))
- {
- return _queues.get(queueName);
- }
- else
- {
- try
- {
- return new QueueConfiguration(queueName, this);
- }
- catch (ConfigurationException e)
- {
- // The configuration is empty so there can't be an error.
- return null;
- }
- }
- }
-
- public ConfigurationPlugin getQueueConfiguration(AMQQueue queue)
- {
- VirtualHostConfiguration hostConfig = queue.getVirtualHost().getConfiguration();
-
- // First check if we have a named queue configuration (the easy case)
- if (Arrays.asList(hostConfig.getQueueNames()).contains(queue.getName()))
- {
- return null;
- }
-
- // We don't have an explicit queue config we must find out what we need.
- ArrayList<Binding> bindings = new ArrayList<Binding>(queue.getBindings());
-
- List<AMQShortString> exchangeClasses = new ArrayList<AMQShortString>(bindings.size());
-
- //Remove default exchange
- for (int index = 0; index < bindings.size(); index++)
- {
- // Ignore the DEFAULT Exchange binding
- if (bindings.get(index).getExchange().getNameShortString().equals(ExchangeDefaults.DEFAULT_EXCHANGE_NAME))
- {
- bindings.remove(index);
- }
- else
- {
- exchangeClasses.add(bindings.get(index).getExchange().getType().getName());
-
- if (exchangeClasses.size() > 1)
- {
- // If we have more than 1 class of exchange then we can only use the global queue configuration.
- // and this will be returned from the default getQueueConfiguration
- return null;
- }
- }
- }
-
- // If we are just bound the the default exchange then use the default.
- if (bindings.isEmpty())
- {
- return null;
- }
-
- // If we are bound to only one type of exchange then we are going
- // to have to resolve the configuration for that exchange.
-
- String exchangeName = bindings.get(0).getExchange().getType().getName().toString();
-
- // Lookup a Configuration handler for this Exchange.
-
- // Build the expected class name. <Exchangename>sConfiguration
- // i.e. TopicConfiguration or HeadersConfiguration
- String exchangeClass = "org.apache.qpid.server.configuration."
- + exchangeName.substring(0, 1).toUpperCase()
- + exchangeName.substring(1) + "Configuration";
-
- ExchangeConfigurationPlugin exchangeConfiguration
- = (ExchangeConfigurationPlugin) queue.getVirtualHost().getConfiguration().getConfiguration(exchangeClass);
-
- // now need to perform the queue-topic-topics-queues magic.
- // So make a new ConfigurationObject that will hold all the configuration for this queue.
- ConfigurationPlugin queueConfig = new QueueConfiguration.QueueConfig();
-
- // Initialise the queue with any Global values we may have
- PropertiesConfiguration newQueueConfig = new PropertiesConfiguration();
- newQueueConfig.setProperty("name", queue.getName());
-
- try
- {
- //Set the queue name
- CompositeConfiguration mungedConf = new CompositeConfiguration();
- //Set the queue name
- mungedConf.addConfiguration(newQueueConfig);
- //Set the global queue configuration
- mungedConf.addConfiguration(getConfig().subset("queues"));
-
- // Set configuration
- queueConfig.setConfiguration("virtualhosts.virtualhost.queues", mungedConf);
- }
- catch (ConfigurationException e)
- {
- // This will not occur as queues only require a name.
- _logger.error("QueueConfiguration requirements have changed.");
- }
-
- // Merge any configuration the Exchange wishes to apply
- if (exchangeConfiguration != null)
- {
- queueConfig.addConfiguration(exchangeConfiguration.getConfiguration(queue));
- }
-
- //Finally merge in any specific queue configuration we have.
- if (_queues.containsKey(queue.getName()))
- {
- queueConfig.addConfiguration(_queues.get(queue.getName()));
- }
-
- return queueConfig;
- }
-
- public long getMemoryUsageMaximum()
- {
- return getLongValue("queues.maximumMemoryUsage");
- }
-
- public long getMemoryUsageMinimum()
- {
- return getLongValue("queues.minimumMemoryUsage");
- }
-
- public int getMaximumMessageAge()
- {
- return getIntValue("queues.maximumMessageAge");
- }
-
- public Long getMaximumQueueDepth()
- {
- return getLongValue("queues.maximumQueueDepth");
- }
-
- public Long getMaximumMessageSize()
- {
- return getLongValue("queues.maximumMessageSize");
- }
-
- public Long getMaximumMessageCount()
- {
- return getLongValue("queues.maximumMessageCount");
- }
-
- public Long getMinimumAlertRepeatGap()
- {
- return getLongValue("queues.minimumAlertRepeatGap");
- }
-
- public long getCapacity()
- {
- return getLongValue("queues.capacity");
- }
-
- public long getFlowResumeCapacity()
- {
- return getLongValue("queues.flowResumeCapacity", getCapacity());
- }
-
- public String[] getElementsProcessed()
- {
- return new String[]{"queues", "exchanges", "custom-exchanges", "store", "housekeeping"};
-
- }
-
- @Override
- public void validateConfiguration() throws ConfigurationException
- {
- // QPID-3249. Support for specifying authentication name at vhost level is no longer supported.
- if (getListValue("security.authentication.name").size() > 0)
- {
- String message = "Validation error : security/authentication/name is no longer a supported element within the configuration xml."
- + " It appears in virtual host definition : " + _name;
- throw new ConfigurationException(message);
- }
- }
-
- public int getHouseKeepingThreadCount()
- {
- return getIntValue("housekeeping.poolSize", Runtime.getRuntime().availableProcessors());
- }
-
- public long getTransactionTimeoutOpenWarn()
- {
- return getLongValue("transactionTimeout.openWarn", 0L);
- }
-
- public long getTransactionTimeoutOpenClose()
- {
- return getLongValue("transactionTimeout.openClose", 0L);
- }
-
- public long getTransactionTimeoutIdleWarn()
- {
- return getLongValue("transactionTimeout.idleWarn", 0L);
- }
-
- public long getTransactionTimeoutIdleClose()
- {
- return getLongValue("transactionTimeout.idleClose", 0L);
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/management/ConfigurationManagementMBean.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/management/ConfigurationManagementMBean.java
deleted file mode 100644
index cc402d5b4a..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/configuration/management/ConfigurationManagementMBean.java
+++ /dev/null
@@ -1,48 +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.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;
-
-public class ConfigurationManagementMBean extends AMQManagedObject implements ConfigurationManagement
-{
-
- public ConfigurationManagementMBean() throws NotCompliantMBeanException
- {
- super(ConfigurationManagement.class, ConfigurationManagement.TYPE);
- }
-
- public String getObjectInstanceName()
- {
- return ConfigurationManagement.TYPE;
- }
-
- public void reloadSecurityConfiguration() throws Exception
- {
- ApplicationRegistry.getInstance().getConfiguration().reparseConfigFileSecuritySections();
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/plugins/ConfigurationPlugin.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/plugins/ConfigurationPlugin.java
deleted file mode 100644
index 82b576ea51..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/configuration/plugins/ConfigurationPlugin.java
+++ /dev/null
@@ -1,454 +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.configuration.plugins;
-
-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 java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.NoSuchElementException;
-import java.util.Set;
-
-public abstract class ConfigurationPlugin
-{
- protected static final Logger _logger = Logger.getLogger(ConfigurationPlugin.class);
-
- private Map<String, ConfigurationPlugin>
- _pluginConfiguration = new HashMap<String, ConfigurationPlugin>();
-
- protected Configuration _configuration;
-
- /**
- * The Elements that this Plugin can process.
- *
- * For a Queues plugin that would be a list containing:
- * <ul>
- * <li>queue - the queue entries
- * <li>the alerting values for defaults
- * <li>exchange - the default exchange
- * <li>durable - set the default durablity
- * </ul>
- */
- abstract public String[] getElementsProcessed();
-
- /** Performs configuration validation. */
- public void validateConfiguration() throws ConfigurationException
- {
- // Override in sub-classes
- }
-
- public Configuration getConfig()
- {
- return _configuration;
- }
-
- public <C extends ConfigurationPlugin> C getConfiguration(String plugin)
- {
- return (C) _pluginConfiguration.get(plugin);
- }
-
- /**
- * Sets the configuration for this plugin
- *
- * @param path
- * @param configuration the configuration for this plugin.
- */
- public void setConfiguration(String path, Configuration configuration) throws ConfigurationException
- {
- _configuration = configuration;
-
- // Extract a list of elements for processing
- Iterator<?> keys = configuration.getKeys();
-
- Set<String> elements = new HashSet<String>();
- while (keys.hasNext())
- {
- String key = (String) keys.next();
-
- int elementNameIndex = key.indexOf(".");
-
- String element = key.trim();
- if (elementNameIndex != -1)
- {
- element = key.substring(0, elementNameIndex).trim();
- }
-
- // Trim any element properties
- elementNameIndex = element.indexOf("[");
- if (elementNameIndex > 0)
- {
- element = element.substring(0, elementNameIndex).trim();
- }
-
- elements.add(element);
- }
-
- //Remove the items we already expect in the configuration
- for (String tag : getElementsProcessed())
- {
-
- // Work round the issue with Commons configuration.
- // With an XMLConfiguration the key will be [@property]
- // but with a CompositeConfiguration it will be @property].
- // Hide this issue from our users so when/if we change the
- // configuration they don't have to.
- int bracketIndex = tag.indexOf("[");
- if (bracketIndex != -1)
- {
- tag = tag.substring(bracketIndex + 1, tag.length());
- }
-
- elements.remove(tag);
- }
-
- if (_logger.isInfoEnabled())
- {
- if (!elements.isEmpty())
- {
- _logger.info("Elements to lookup:" + path);
- for (String tag : elements)
- {
- _logger.info("Tag:'" + tag + "'");
- }
- }
- }
-
- // Process the elements in the configuration
- for (String element : elements)
- {
- ConfigurationManager configurationManager = ApplicationRegistry.getInstance().getConfigurationManager();
- Configuration handled = element.length() == 0 ? configuration : configuration.subset(element);
-
- String configurationElement = element;
- if (path.length() > 0)
- {
- configurationElement = path + "." + configurationElement;
- }
-
- List<ConfigurationPlugin> handlers = configurationManager.getConfigurationPlugins(configurationElement, handled);
-
- if(_logger.isDebugEnabled())
- {
- _logger.debug("For '" + element + "' found handlers (" + handlers.size() + "):" + handlers);
- }
-
- for (ConfigurationPlugin plugin : handlers)
- {
- _pluginConfiguration.put(plugin.getClass().getName(), plugin);
- }
- }
-
- validateConfiguration();
- }
-
- /** Helper method to print out list of keys in a {@link Configuration}. */
- public static final void showKeys(Configuration config)
- {
- if (config.isEmpty())
- {
- _logger.info("Configuration is empty");
- }
- else
- {
- Iterator<?> keys = config.getKeys();
- while (keys.hasNext())
- {
- String key = (String) keys.next();
- _logger.info("Configuration key: " + key);
- }
- }
- }
-
- protected boolean hasConfiguration()
- {
- return _configuration != null;
- }
-
- /// Getters
-
- protected double getDoubleValue(String property)
- {
- return getDoubleValue(property, 0.0);
- }
-
- protected double getDoubleValue(String property, double defaultValue)
- {
- return _configuration.getDouble(property, defaultValue);
- }
-
- protected long getLongValue(String property)
- {
- return getLongValue(property, 0);
- }
-
- protected long getLongValue(String property, long defaultValue)
- {
- return _configuration.getLong(property, defaultValue);
- }
-
- protected int getIntValue(String property)
- {
- return getIntValue(property, 0);
- }
-
- protected int getIntValue(String property, int defaultValue)
- {
- return _configuration.getInt(property, defaultValue);
- }
-
- protected String getStringValue(String property)
- {
- return getStringValue(property, null);
- }
-
- protected String getStringValue(String property, String defaultValue)
- {
- return _configuration.getString(property, defaultValue);
- }
-
- protected boolean getBooleanValue(String property)
- {
- return getBooleanValue(property, false);
- }
-
- protected boolean getBooleanValue(String property, boolean defaultValue)
- {
- return _configuration.getBoolean(property, defaultValue);
- }
-
- protected List getListValue(String property)
- {
- return getListValue(property, Collections.EMPTY_LIST);
- }
-
- protected List getListValue(String property, List defaultValue)
- {
- return _configuration.getList(property, defaultValue);
- }
-
- /// Validation Helpers
-
- protected boolean contains(String property)
- {
- return _configuration.getProperty(property) != null;
- }
-
- /**
- * Provide mechanism to validate Configuration contains a Postiive Long Value
- *
- * @param property
- *
- * @throws ConfigurationException
- */
- protected void validatePositiveLong(String property) throws ConfigurationException
- {
- try
- {
- if (!containsPositiveLong(property))
- {
- throw new ConfigurationException(this.getClass().getSimpleName()
- + ": '" + property +
- "' must be a Positive Long value.");
- }
- }
- catch (Exception e)
- {
- Throwable last = e;
-
- // Find the first cause
- if (e instanceof ConversionException)
- {
- Throwable t = e.getCause();
- while (t != null)
- {
- last = t;
- t = last.getCause();
- }
- }
-
- throw new ConfigurationException(this.getClass().getSimpleName() +
- ": unable to configure invalid " +
- property + ":" +
- _configuration.getString(property),
- last);
- }
- }
-
- protected boolean containsLong(String property)
- {
- try
- {
- _configuration.getLong(property);
- return true;
- }
- catch (NoSuchElementException e)
- {
- return false;
- }
- }
-
- protected boolean containsPositiveLong(String property)
- {
- try
- {
- long value = _configuration.getLong(property);
- return value > 0;
- }
- catch (NoSuchElementException e)
- {
- return false;
- }
-
- }
-
- protected boolean containsInt(String property)
- {
- try
- {
- _configuration.getInt(property);
- return true;
- }
- catch (NoSuchElementException e)
- {
- return false;
- }
- }
-
- protected boolean containsBoolean(String property)
- {
- try
- {
- _configuration.getBoolean(property);
- return true;
- }
- catch (NoSuchElementException e)
- {
- return false;
- }
- }
-
- /**
- * Given another configuration merge the configuration into our own config
- *
- * The new values being merged in will take precedence over existing values.
- *
- * In the simplistic case this means something like:
- *
- * So if we have configuration set
- * name = 'fooo'
- *
- * And the new configuration contains a name then that will be reset.
- * name = 'new'
- *
- * However this plugin will simply contain other plugins so the merge will
- * be called until we end up at a base plugin that understand how to merge
- * items. i.e Alerting values. Where the provided configuration will take
- * precedence.
- *
- * @param configuration the config to merge in to our own.
- */
- public void addConfiguration(ConfigurationPlugin configuration)
- {
- // If given configuration is null then there is nothing to process.
- if (configuration == null)
- {
- return;
- }
-
- // Merge all the sub configuration items
- for (Map.Entry<String, ConfigurationPlugin> newPlugins : configuration._pluginConfiguration.entrySet())
- {
- String key = newPlugins.getKey();
- ConfigurationPlugin config = newPlugins.getValue();
-
- if (_pluginConfiguration.containsKey(key))
- {
- //Merge the configuration if we already have this type of config
- _pluginConfiguration.get(key).mergeConfiguration(config);
- }
- else
- {
- //otherwise just add it to our config.
- _pluginConfiguration.put(key, config);
- }
- }
-
- //Merge the configuration itself
- String key = configuration.getClass().getName();
- if (_pluginConfiguration.containsKey(key))
- {
- //Merge the configuration if we already have this type of config
- _pluginConfiguration.get(key).mergeConfiguration(configuration);
- }
- else
- {
- //If we are adding a configuration of our own type then merge
- if (configuration.getClass() == this.getClass())
- {
- mergeConfiguration(configuration);
- }
- else
- {
- // just store this in case someone else needs it.
- _pluginConfiguration.put(key, configuration);
- }
-
- }
-
- }
-
- protected void mergeConfiguration(ConfigurationPlugin configuration)
- {
- _configuration = configuration.getConfig();
- }
-
- public String toString()
- {
- StringBuilder sb = new StringBuilder();
-
- sb.append("\n").append(getClass().getSimpleName());
- sb.append("=[ (").append(formatToString()).append(")");
-
- for(Map.Entry<String,ConfigurationPlugin> item : _pluginConfiguration.entrySet())
- {
- sb.append("\n").append(item.getValue());
- }
-
- sb.append("]\n");
-
- return sb.toString();
- }
-
- public String formatToString()
- {
- return super.toString();
- }
-
-}
-
-
diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/plugins/ConfigurationPluginFactory.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/plugins/ConfigurationPluginFactory.java
deleted file mode 100644
index 02560b296e..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/configuration/plugins/ConfigurationPluginFactory.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.configuration.plugins;
-
-import java.util.List;
-
-import org.apache.commons.configuration.Configuration;
-import org.apache.commons.configuration.ConfigurationException;
-
-public interface ConfigurationPluginFactory
-{
- /**
- * The Parent paths of the configuration that this plugin supports.
- *
- * For example, {@code queue} elements have a parent path of {@code virtualhosts.virtualhost}.
- */
- public List<String> getParentPaths();
-
- public ConfigurationPlugin newInstance(String path, Configuration config) throws ConfigurationException;
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/plugins/SlowConsumerDetectionConfiguration.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/plugins/SlowConsumerDetectionConfiguration.java
deleted file mode 100644
index 7a2632d923..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/configuration/plugins/SlowConsumerDetectionConfiguration.java
+++ /dev/null
@@ -1,89 +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.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;
-import java.util.concurrent.TimeUnit;
-
-public class SlowConsumerDetectionConfiguration extends ConfigurationPlugin
-{
- public static class SlowConsumerDetectionConfigurationFactory implements ConfigurationPluginFactory
- {
- public ConfigurationPlugin newInstance(String path, Configuration config) throws ConfigurationException
- {
- SlowConsumerDetectionConfiguration slowConsumerConfig = new SlowConsumerDetectionConfiguration();
- slowConsumerConfig.setConfiguration(path, config);
- return slowConsumerConfig;
- }
-
- public List<String> getParentPaths()
- {
- return Arrays.asList("virtualhosts.virtualhost.slow-consumer-detection");
- }
- }
-
- //Set Default time unit to seconds
- TimeUnit _timeUnit = TimeUnit.SECONDS;
-
- public String[] getElementsProcessed()
- {
- return new String[]{"delay",
- "timeunit"};
- }
-
- public long getDelay()
- {
- return getLongValue("delay", 10);
- }
-
- public TimeUnit getTimeUnit()
- {
- return _timeUnit;
- }
-
- @Override
- public void validateConfiguration() throws ConfigurationException
- {
- validatePositiveLong("delay");
-
- String timeUnit = getStringValue("timeunit");
-
- if (timeUnit != null)
- {
- try
- {
- _timeUnit = TimeUnit.valueOf(timeUnit.toUpperCase());
- }
- catch (IllegalArgumentException iae)
- {
- throw new ConfigurationException("Unable to configure Slow Consumer Detection invalid TimeUnit:" + timeUnit);
- }
- }
-
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/plugins/SlowConsumerDetectionPolicyConfiguration.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/plugins/SlowConsumerDetectionPolicyConfiguration.java
deleted file mode 100644
index ca8dec851a..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/configuration/plugins/SlowConsumerDetectionPolicyConfiguration.java
+++ /dev/null
@@ -1,76 +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.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;
-
-public class SlowConsumerDetectionPolicyConfiguration extends ConfigurationPlugin
-{
- public static class SlowConsumerDetectionPolicyConfigurationFactory implements ConfigurationPluginFactory
- {
- public ConfigurationPlugin newInstance(String path, Configuration config) throws ConfigurationException
- {
- SlowConsumerDetectionPolicyConfiguration slowConsumerConfig = new SlowConsumerDetectionPolicyConfiguration();
- slowConsumerConfig.setConfiguration(path, config);
- return slowConsumerConfig;
- }
-
- public List<String> getParentPaths()
- {
- return Arrays.asList(
- "virtualhosts.virtualhost.queues.slow-consumer-detection.policy",
- "virtualhosts.virtualhost.queues.queue.slow-consumer-detection.policy",
- "virtualhosts.virtualhost.topics.slow-consumer-detection.policy",
- "virtualhosts.virtualhost.topics.topic.slow-consumer-detection.policy");
- }
- }
-
- public String[] getElementsProcessed()
- {
- return new String[]{"name"};
- }
-
- public String getPolicyName()
- {
- return getStringValue("name");
- }
-
- @Override
- public void validateConfiguration() throws ConfigurationException
- {
- if (getPolicyName() == null)
- {
- throw new ConfigurationException("No Slow consumer policy defined.");
- }
- }
-
- @Override
- public String formatToString()
- {
- return "Policy:"+getPolicyName();
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/plugins/SlowConsumerDetectionQueueConfiguration.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/plugins/SlowConsumerDetectionQueueConfiguration.java
deleted file mode 100644
index 0638ea362f..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/configuration/plugins/SlowConsumerDetectionQueueConfiguration.java
+++ /dev/null
@@ -1,153 +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.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;
-import org.apache.qpid.slowconsumerdetection.policies.SlowConsumerPolicyPluginFactory;
-
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-public class SlowConsumerDetectionQueueConfiguration extends ConfigurationPlugin
-{
- private SlowConsumerPolicyPlugin _policyPlugin;
-
- public static class SlowConsumerDetectionQueueConfigurationFactory implements ConfigurationPluginFactory
- {
- public ConfigurationPlugin newInstance(String path, Configuration config) throws ConfigurationException
- {
- SlowConsumerDetectionQueueConfiguration slowConsumerConfig = new SlowConsumerDetectionQueueConfiguration();
- slowConsumerConfig.setConfiguration(path, config);
- return slowConsumerConfig;
- }
-
- public List<String> getParentPaths()
- {
- return Arrays.asList(
- "virtualhosts.virtualhost.queues.slow-consumer-detection",
- "virtualhosts.virtualhost.queues.queue.slow-consumer-detection",
- "virtualhosts.virtualhost.topics.slow-consumer-detection",
- "virtualhosts.virtualhost.topics.topic.slow-consumer-detection");
- }
- }
-
- public String[] getElementsProcessed()
- {
- return new String[]{"messageAge",
- "depth",
- "messageCount"};
- }
-
- public long getMessageAge()
- {
- return getLongValue("messageAge");
- }
-
- public long getDepth()
- {
- return getLongValue("depth");
- }
-
- public long getMessageCount()
- {
- return getLongValue("messageCount");
- }
-
- public SlowConsumerPolicyPlugin getPolicy()
- {
- return _policyPlugin;
- }
-
- @Override
- public void validateConfiguration() throws ConfigurationException
- {
- if (!containsPositiveLong("messageAge") &&
- !containsPositiveLong("depth") &&
- !containsPositiveLong("messageCount"))
- {
- throw new ConfigurationException("At least one configuration property" +
- "('messageAge','depth' or 'messageCount') must be specified.");
- }
-
- SlowConsumerDetectionPolicyConfiguration policyConfig = getConfiguration(SlowConsumerDetectionPolicyConfiguration.class.getName());
-
- PluginManager pluginManager = ApplicationRegistry.getInstance().getPluginManager();
- Map<String, SlowConsumerPolicyPluginFactory> factories = pluginManager.getSlowConsumerPlugins();
-
- if (policyConfig == null)
- {
- throw new ConfigurationException("No Slow Consumer Policy specified. Known Policies:" + factories.keySet());
- }
-
- if (_logger.isDebugEnabled())
- {
- Iterator<?> keys = policyConfig.getConfig().getKeys();
-
- while (keys.hasNext())
- {
- String key = (String) keys.next();
-
- _logger.debug("Policy Keys:" + key);
- }
-
- }
-
- SlowConsumerPolicyPluginFactory<SlowConsumerPolicyPlugin> pluginFactory = factories.get(policyConfig.getPolicyName().toLowerCase());
-
- if (pluginFactory == null)
- {
- throw new ConfigurationException("Unknown Slow Consumer Policy specified:" + policyConfig.getPolicyName() + " Known Policies:" + factories.keySet());
- }
-
- _policyPlugin = pluginFactory.newInstance(policyConfig);
-
- // Debug the creation of this Config
- _logger.debug(this);
- }
-
- public String formatToString()
- {
- StringBuilder sb = new StringBuilder();
- if (getMessageAge() > 0)
- {
- sb.append("Age:").append(getMessageAge()).append(":");
- }
- if (getDepth() > 0)
- {
- sb.append("Depth:").append(getDepth()).append(":");
- }
- if (getMessageCount() > 0)
- {
- sb.append("Count:").append(getMessageCount()).append(":");
- }
-
- sb.append("Policy[").append(getPolicy()).append("]");
- return sb.toString();
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/connection/ConnectionRegistry.java b/java/broker/src/main/java/org/apache/qpid/server/connection/ConnectionRegistry.java
deleted file mode 100644
index c06305ee4e..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/connection/ConnectionRegistry.java
+++ /dev/null
@@ -1,81 +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.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;
-
-public class ConnectionRegistry implements IConnectionRegistry, Closeable
-{
- private List<AMQConnectionModel> _registry = new CopyOnWriteArrayList<AMQConnectionModel>();
-
- private Logger _logger = Logger.getLogger(ConnectionRegistry.class);
-
- public void initialise()
- {
- // None required
- }
-
- /** Close all of the currently open connections. */
- public void close()
- {
- while (!_registry.isEmpty())
- {
- AMQConnectionModel connection = _registry.get(0);
- closeConnection(connection, AMQConstant.INTERNAL_ERROR, "Broker is shutting down");
- }
- }
-
- public void closeConnection(AMQConnectionModel connection, AMQConstant cause, String message)
- {
- try
- {
- connection.close(cause, message);
- }
- catch (AMQException e)
- {
- _logger.warn("Error closing connection:" + e.getMessage());
- }
- }
-
- public void registerConnection(AMQConnectionModel connnection)
- {
- _registry.add(connnection);
- }
-
- public void deregisterConnection(AMQConnectionModel connnection)
- {
- _registry.remove(connnection);
- }
-
- @Override
- public List<AMQConnectionModel> getConnections()
- {
- return new ArrayList<AMQConnectionModel>(_registry);
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/connection/IConnectionRegistry.java b/java/broker/src/main/java/org/apache/qpid/server/connection/IConnectionRegistry.java
deleted file mode 100644
index b4f5bffa57..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/connection/IConnectionRegistry.java
+++ /dev/null
@@ -1,42 +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.connection;
-
-import java.util.List;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.protocol.AMQConstant;
-import org.apache.qpid.server.protocol.AMQConnectionModel;
-
-public interface IConnectionRegistry
-{
- public void initialise();
-
- public void close() throws AMQException;
-
- public void closeConnection(AMQConnectionModel connection, AMQConstant cause, String message);
-
- public List<AMQConnectionModel> getConnections();
-
- public void registerConnection(AMQConnectionModel connnection);
-
- public void deregisterConnection(AMQConnectionModel connnection);
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/AbstractExchange.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/AbstractExchange.java
deleted file mode 100644
index d0231e4d80..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/exchange/AbstractExchange.java
+++ /dev/null
@@ -1,403 +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.log4j.Logger;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.AMQShortString;
-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.ExchangeConfigType;
-import org.apache.qpid.server.logging.LogSubject;
-import org.apache.qpid.server.logging.actors.CurrentActor;
-import org.apache.qpid.server.logging.messages.ExchangeMessages;
-import org.apache.qpid.server.logging.subjects.ExchangeLogSubject;
-import org.apache.qpid.server.management.Managable;
-import org.apache.qpid.server.management.ManagedObject;
-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.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;
-import java.util.Map;
-import java.util.UUID;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.CopyOnWriteArrayList;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.concurrent.atomic.AtomicLong;
-
-public abstract class AbstractExchange implements Exchange, Managable
-{
-
-
- private AMQShortString _name;
- private final AtomicBoolean _closed = new AtomicBoolean();
-
- private Exchange _alternateExchange;
-
- protected boolean _durable;
- protected int _ticket;
-
- private VirtualHost _virtualHost;
-
- private final List<Exchange.Task> _closeTaskList = new CopyOnWriteArrayList<Exchange.Task>();
-
-
- protected AbstractExchangeMBean _exchangeMbean;
-
- /**
- * Whether the exchange is automatically deleted once all queues have detached from it
- */
- protected boolean _autoDelete;
-
- //The logSubject for ths exchange
- private LogSubject _logSubject;
- private Map<ExchangeReferrer,Object> _referrers = new ConcurrentHashMap<ExchangeReferrer,Object>();
-
- private final CopyOnWriteArrayList<Binding> _bindings = new CopyOnWriteArrayList<Binding>();
- private final ExchangeType<? extends Exchange> _type;
- private UUID _id;
- private final AtomicInteger _bindingCountHigh = new AtomicInteger();
- private final AtomicLong _receivedMessageCount = new AtomicLong();
- private final AtomicLong _receivedMessageSize = new AtomicLong();
- private final AtomicLong _routedMessageCount = new AtomicLong();
- private final AtomicLong _routedMessageSize = new AtomicLong();
-
- private final CopyOnWriteArrayList<Exchange.BindingListener> _listeners = new CopyOnWriteArrayList<Exchange.BindingListener>();
-
- //TODO : persist creation time
- private long _createTime = System.currentTimeMillis();
-
- public AbstractExchange(final ExchangeType<? extends Exchange> type)
- {
- _type = type;
- }
-
- public AMQShortString getNameShortString()
- {
- return _name;
- }
-
- public final AMQShortString getTypeShortString()
- {
- return _type.getName();
- }
-
- /**
- * Concrete exchanges must implement this method in order to create the managed representation. This is
- * called during initialisation (template method pattern).
- * @return the MBean
- */
- protected abstract AbstractExchangeMBean createMBean() throws JMException;
-
- public void initialise(VirtualHost host, AMQShortString name, boolean durable, int ticket, boolean autoDelete)
- throws AMQException
- {
- _virtualHost = host;
- _name = name;
- _durable = durable;
- _autoDelete = autoDelete;
- _ticket = ticket;
-
- // TODO - fix
- _id = getConfigStore().createId();
-
- getConfigStore().addConfiguredObject(this);
- try
- {
- _exchangeMbean = createMBean();
- _exchangeMbean.register();
- }
- catch (JMException e)
- {
- getLogger().error(e);
- }
- _logSubject = new ExchangeLogSubject(this, this.getVirtualHost());
-
- // Log Exchange creation
- CurrentActor.get().message(ExchangeMessages.CREATED(String.valueOf(getTypeShortString()), String.valueOf(name), durable));
- }
-
- public ConfigStore getConfigStore()
- {
- return getVirtualHost().getConfigStore();
- }
-
- public abstract Logger getLogger();
-
- public boolean isDurable()
- {
- return _durable;
- }
-
- public boolean isAutoDelete()
- {
- return _autoDelete;
- }
-
- public int getTicket()
- {
- return _ticket;
- }
-
- public void close() throws AMQException
- {
-
- if(_closed.compareAndSet(false,true))
- {
- if (_exchangeMbean != null)
- {
- _exchangeMbean.unregister();
- }
- getConfigStore().removeConfiguredObject(this);
- if(_alternateExchange != null)
- {
- _alternateExchange.removeReference(this);
- }
-
- CurrentActor.get().message(_logSubject, ExchangeMessages.DELETED());
-
- for(Task task : _closeTaskList)
- {
- task.onClose(this);
- }
- _closeTaskList.clear();
- }
- }
-
- public String toString()
- {
- return getClass().getSimpleName() + "[" + getNameShortString() +"]";
- }
-
- public ManagedObject getManagedObject()
- {
- return _exchangeMbean;
- }
-
- public VirtualHost getVirtualHost()
- {
- return _virtualHost;
- }
-
- public QueueRegistry getQueueRegistry()
- {
- return getVirtualHost().getQueueRegistry();
- }
-
- public boolean isBound(String bindingKey, Map<String,Object> arguments, AMQQueue queue)
- {
- return isBound(new AMQShortString(bindingKey), queue);
- }
-
-
- public boolean isBound(String bindingKey, AMQQueue queue)
- {
- return isBound(new AMQShortString(bindingKey), queue);
- }
-
- public boolean isBound(String bindingKey)
- {
- return isBound(new AMQShortString(bindingKey));
- }
-
- public Exchange getAlternateExchange()
- {
- return _alternateExchange;
- }
-
- public void setAlternateExchange(Exchange exchange)
- {
- if(_alternateExchange != null)
- {
- _alternateExchange.removeReference(this);
- }
- if(exchange != null)
- {
- exchange.addReference(this);
- }
- _alternateExchange = exchange;
-
- }
-
- public void removeReference(ExchangeReferrer exchange)
- {
- _referrers.remove(exchange);
- }
-
- public void addReference(ExchangeReferrer exchange)
- {
- _referrers.put(exchange, Boolean.TRUE);
- }
-
- public boolean hasReferrers()
- {
- return !_referrers.isEmpty();
- }
-
- public void addCloseTask(final Task task)
- {
- _closeTaskList.add(task);
- }
-
- public void removeCloseTask(final Task task)
- {
- _closeTaskList.remove(task);
- }
-
- public final void addBinding(final Binding binding)
- {
- _bindings.add(binding);
- int bindingCountSize = _bindings.size();
- int maxBindingsSize;
- while((maxBindingsSize = _bindingCountHigh.get()) < bindingCountSize)
- {
- _bindingCountHigh.compareAndSet(maxBindingsSize, bindingCountSize);
- }
- for(BindingListener listener : _listeners)
- {
- listener.bindingAdded(this, binding);
- }
- onBind(binding);
- }
-
- public long getBindingCountHigh()
- {
- return _bindingCountHigh.get();
- }
-
- public final void removeBinding(final Binding binding)
- {
- onUnbind(binding);
- for(BindingListener listener : _listeners)
- {
- listener.bindingRemoved(this, binding);
- }
- _bindings.remove(binding);
- }
-
- public final Collection<Binding> getBindings()
- {
- return Collections.unmodifiableList(_bindings);
- }
-
- protected abstract void onBind(final Binding binding);
-
- protected abstract void onUnbind(final Binding binding);
-
-
- public String getName()
- {
- return _name.toString();
- }
-
- public ExchangeType getType()
- {
- return _type;
- }
-
- public Map<String, Object> getArguments()
- {
- // TODO - Fix
- return Collections.EMPTY_MAP;
- }
-
- public UUID getId()
- {
- return _id;
- }
-
- public ExchangeConfigType getConfigType()
- {
- return ExchangeConfigType.getInstance();
- }
-
- public ConfiguredObject getParent()
- {
- return _virtualHost;
- }
-
- public long getBindingCount()
- {
- return getBindings().size();
- }
-
-
-
- public final ArrayList<? extends BaseQueue> route(final InboundMessage message)
- {
- _receivedMessageCount.incrementAndGet();
- _receivedMessageSize.addAndGet(message.getSize());
- final ArrayList<? extends BaseQueue> queues = doRoute(message);
- if(queues != null && !queues.isEmpty())
- {
- _routedMessageCount.incrementAndGet();
- _routedMessageSize.addAndGet(message.getSize());
- }
- return queues;
- }
-
- protected abstract ArrayList<? extends BaseQueue> doRoute(final InboundMessage message);
-
- public long getMsgReceives()
- {
- return _receivedMessageCount.get();
- }
-
- public long getMsgRoutes()
- {
- return _routedMessageCount.get();
- }
-
- public long getByteReceives()
- {
- return _receivedMessageSize.get();
- }
-
- public long getByteRoutes()
- {
- return _routedMessageSize.get();
- }
-
- public long getCreateTime()
- {
- return _createTime;
- }
-
- public void addBindingListener(final BindingListener listener)
- {
- _listeners.add(listener);
- }
-
- public void removeBindingListener(final BindingListener listener)
- {
- _listeners.remove(listener);
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/AbstractExchangeMBean.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/AbstractExchangeMBean.java
deleted file mode 100644
index 0f1b709475..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/exchange/AbstractExchangeMBean.java
+++ /dev/null
@@ -1,182 +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 java.util.Collections;
-import java.util.Map;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.AMQSecurityException;
-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.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.MBeanException;
-import javax.management.NotCompliantMBeanException;
-import javax.management.ObjectName;
-import javax.management.MalformedObjectNameException;
-import javax.management.JMException;
-
-/**
- * Abstract MBean class. This has some of the methods implemented from
- * management intrerface for exchanges. Any implementaion of an
- * Exchange MBean should extend this class.
- */
-public abstract class AbstractExchangeMBean<T extends AbstractExchange> extends AMQManagedObject implements ManagedExchange
-{
- // open mbean data types for representing exchange bindings
- protected OpenType[] _bindingItemTypes;
- protected CompositeType _bindingDataType;
- protected TabularType _bindinglistDataType;
-
-
- private T _exchange;
-
- public AbstractExchangeMBean(final T abstractExchange) throws NotCompliantMBeanException
- {
- super(ManagedExchange.class, ManagedExchange.TYPE);
- _exchange = abstractExchange;
- }
-
- protected void init() throws OpenDataException
- {
- _bindingItemTypes = new OpenType[2];
- _bindingItemTypes[0] = SimpleType.STRING;
- _bindingItemTypes[1] = new ArrayType(1, SimpleType.STRING);
- _bindingDataType = new CompositeType("Exchange Binding", "Binding key and Queue names",
- COMPOSITE_ITEM_NAMES.toArray(new String[COMPOSITE_ITEM_NAMES.size()]),
- COMPOSITE_ITEM_DESCRIPTIONS.toArray(new String[COMPOSITE_ITEM_DESCRIPTIONS.size()]), _bindingItemTypes);
- _bindinglistDataType = new TabularType("Exchange Bindings", "Exchange Bindings for " + getName(),
- _bindingDataType, TABULAR_UNIQUE_INDEX.toArray(new String[TABULAR_UNIQUE_INDEX.size()]));
- }
-
- public ManagedObject getParentObject()
- {
- return _exchange.getVirtualHost().getManagedObject();
- }
-
- public T getExchange()
- {
- return _exchange;
- }
-
-
- public String getObjectInstanceName()
- {
- return ObjectName.quote(_exchange.getName());
- }
-
- public String getName()
- {
- return _exchange.getName();
- }
-
- public String getExchangeType()
- {
- return _exchange.getTypeShortString().toString();
- }
-
- public Integer getTicketNo()
- {
- return _exchange._ticket;
- }
-
- public boolean isDurable()
- {
- return _exchange._durable;
- }
-
- public boolean isAutoDelete()
- {
- return _exchange._autoDelete;
- }
-
- // Added exchangetype in the object name lets maangement apps to do any customization required
- public ObjectName getObjectName() throws MalformedObjectNameException
- {
- String objNameString = super.getObjectName().toString();
- objNameString = objNameString + ",ExchangeType=" + getExchangeType();
- return new ObjectName(objNameString);
- }
-
- protected ManagedObjectRegistry getManagedObjectRegistry()
- {
- return ApplicationRegistry.getInstance().getManagedObjectRegistry();
- }
-
- public void createNewBinding(String queueName, String binding) throws JMException
- {
- VirtualHost vhost = getExchange().getVirtualHost();
- AMQQueue queue = vhost.getQueueRegistry().getQueue(new AMQShortString(queueName));
- if (queue == null)
- {
- throw new JMException("Queue \"" + queueName + "\" is not registered with the virtualhost.");
- }
-
- CurrentActor.set(new ManagementActor(_logActor.getRootMessageLogger()));
- try
- {
- vhost.getBindingFactory().addBinding(binding,queue,getExchange(),null);
- }
- catch (AMQException ex)
- {
- JMException jme = new JMException(ex.toString());
- throw new MBeanException(jme, "Error creating new binding " + binding);
- }
- CurrentActor.remove();
- }
-
- /**
- * Removes a queue binding from the exchange.
- *
- * @see BindingFactory#removeBinding(String, AMQQueue, Exchange, Map)
- */
- public void removeBinding(String queueName, String binding) throws JMException
- {
- VirtualHost vhost = getExchange().getVirtualHost();
- AMQQueue queue = vhost.getQueueRegistry().getQueue(new AMQShortString(queueName));
- if (queue == null)
- {
- throw new JMException("Queue \"" + queueName + "\" is not registered with the virtualhost.");
- }
-
- CurrentActor.set(new ManagementActor(_logActor.getRootMessageLogger()));
- try
- {
- vhost.getBindingFactory().removeBinding(binding, queue, _exchange, Collections.<String, Object>emptyMap());
- }
- catch (AMQException ex)
- {
- JMException jme = new JMException(ex.toString());
- throw new MBeanException(jme, "Error removing binding " + binding);
- }
- CurrentActor.remove();
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/DefaultExchangeFactory.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/DefaultExchangeFactory.java
deleted file mode 100644
index 7837a9bc38..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/exchange/DefaultExchangeFactory.java
+++ /dev/null
@@ -1,146 +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 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;
-
-public class DefaultExchangeFactory implements ExchangeFactory
-{
- private static final Logger _logger = Logger.getLogger(DefaultExchangeFactory.class);
-
- private Map<AMQShortString, ExchangeType<? extends Exchange>> _exchangeClassMap = new HashMap<AMQShortString, ExchangeType<? extends Exchange>>();
- private final VirtualHost _host;
-
- public DefaultExchangeFactory(VirtualHost host)
- {
- _host = host;
- registerExchangeType(DirectExchange.TYPE);
- registerExchangeType(TopicExchange.TYPE);
- registerExchangeType(HeadersExchange.TYPE);
- registerExchangeType(FanoutExchange.TYPE);
- registerExchangeType(ManagementExchange.TYPE);
- }
-
- public void registerExchangeType(ExchangeType<? extends Exchange> type)
- {
- _exchangeClassMap.put(type.getName(), type);
- }
-
- public Collection<ExchangeType<? extends Exchange>> getRegisteredTypes()
- {
- return _exchangeClassMap.values();
- }
-
- public Collection<ExchangeType<? extends Exchange>> getPublicCreatableTypes()
- {
- Collection<ExchangeType<? extends Exchange>> publicTypes =
- new ArrayList<ExchangeType<? extends Exchange>>();
- publicTypes.addAll(_exchangeClassMap.values());
-
- //Remove the ManagementExchange type if present, as these
- //are private and cannot be created by external means
- publicTypes.remove(ManagementExchange.TYPE);
-
- return publicTypes;
- }
-
-
-
- public Exchange createExchange(String exchange, String type, boolean durable, boolean autoDelete)
- throws AMQException
- {
- return createExchange(new AMQShortString(exchange), new AMQShortString(type), durable, autoDelete, 0);
- }
-
- public Exchange createExchange(AMQShortString exchange, AMQShortString type, boolean durable, boolean autoDelete,
- int ticket)
- throws AMQException
- {
- // Check access
- if (!_host.getSecurityManager().authoriseCreateExchange(autoDelete, durable, exchange, null, null, null, type))
- {
- String description = "Permission denied: exchange-name '" + exchange.asString() + "'";
- throw new AMQSecurityException(description);
- }
-
- ExchangeType<? extends Exchange> exchType = _exchangeClassMap.get(type);
- if (exchType == null)
- {
- throw new AMQUnknownExchangeType("Unknown exchange type: " + type,null);
- }
-
- Exchange e = exchType.newInstance(_host, exchange, durable, ticket, autoDelete);
- return e;
- }
-
- public void initialise(VirtualHostConfiguration hostConfig)
- {
-
- if (hostConfig == null)
- {
- return;
- }
-
- for(Object className : hostConfig.getCustomExchanges())
- {
- try
- {
- ExchangeType<?> exchangeType = ApplicationRegistry.getInstance().getPluginManager().getExchanges().get(String.valueOf(className));
- if (exchangeType == null)
- {
- _logger.error("No such custom exchange class found: \""+String.valueOf(className)+"\"");
- return;
- }
- Class<? extends ExchangeType> exchangeTypeClass = exchangeType.getClass();
- ExchangeType<? extends ExchangeType> type = exchangeTypeClass.newInstance();
- registerExchangeType(type);
- }
- catch (ClassCastException classCastEx)
- {
- _logger.error("No custom exchange class: \""+String.valueOf(className)+"\" cannot be registered as it does not extend class \""+ExchangeType.class+"\"");
- }
- catch (IllegalAccessException e)
- {
- _logger.error("Cannot create custom exchange class: \""+String.valueOf(className)+"\"",e);
- }
- catch (InstantiationException e)
- {
- _logger.error("Cannot create custom exchange class: \""+String.valueOf(className)+"\"",e);
- }
- }
-
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/DefaultExchangeRegistry.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/DefaultExchangeRegistry.java
deleted file mode 100644
index 0e7459498a..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/exchange/DefaultExchangeRegistry.java
+++ /dev/null
@@ -1,164 +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 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.framing.AMQShortString;
-import org.apache.qpid.server.queue.IncomingMessage;
-import org.apache.qpid.server.store.DurableConfigurationStore;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-
-public class DefaultExchangeRegistry implements ExchangeRegistry
-{
- private static final Logger _log = Logger.getLogger(DefaultExchangeRegistry.class);
-
- /**
- * Maps from exchange name to exchange instance
- */
- private ConcurrentMap<AMQShortString, Exchange> _exchangeMap = new ConcurrentHashMap<AMQShortString, Exchange>();
- private ConcurrentMap<String, Exchange> _exchangeMapStr = new ConcurrentHashMap<String, Exchange>();
-
- private Exchange _defaultExchange;
- private VirtualHost _host;
-
- public DefaultExchangeRegistry(VirtualHost host)
- {
- //create 'standard' exchanges:
- _host = host;
-
- }
-
- public void initialise() throws AMQException
- {
- new ExchangeInitialiser().initialise(_host.getExchangeFactory(), this, getDurableConfigurationStore());
- }
-
-
-
- public DurableConfigurationStore getDurableConfigurationStore()
- {
- return _host.getDurableConfigurationStore();
- }
-
- public void registerExchange(Exchange exchange) throws AMQException
- {
- _exchangeMap.put(exchange.getNameShortString(), exchange);
- _exchangeMapStr.put(exchange.getNameShortString().toString(), exchange);
- }
-
- public void setDefaultExchange(Exchange exchange)
- {
- _defaultExchange = exchange;
- }
-
- public Exchange getDefaultExchange()
- {
- return _defaultExchange;
- }
-
- public Collection<AMQShortString> getExchangeNames()
- {
- return _exchangeMap.keySet();
- }
-
- public void unregisterExchange(AMQShortString name, boolean inUse) throws AMQException
- {
- // Check access
- if (!_host.getSecurityManager().authoriseDelete(_exchangeMap.get(name)))
- {
- throw new AMQSecurityException();
- }
-
- // TODO: check inUse argument
-
- Exchange e = _exchangeMap.remove(name);
- _exchangeMapStr.remove(name.toString());
- if (e != null)
- {
- if (e.isDurable())
- {
- getDurableConfigurationStore().removeExchange(e);
- }
- e.close();
- }
- else
- {
- throw new AMQException("Unknown exchange " + name);
- }
- }
-
- public void unregisterExchange(String name, boolean inUse) throws AMQException
- {
- unregisterExchange(new AMQShortString(name), inUse);
- }
-
- public Exchange getExchange(AMQShortString name)
- {
- if ((name == null) || name.length() == 0)
- {
- return getDefaultExchange();
- }
- else
- {
- return _exchangeMap.get(name);
- }
-
- }
-
- public Exchange getExchange(String name)
- {
- if ((name == null) || name.length() == 0)
- {
- return getDefaultExchange();
- }
- else
- {
- return _exchangeMapStr.get(name);
- }
- }
-
-
- /**
- * 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/java/broker/src/main/java/org/apache/qpid/server/exchange/DirectExchange.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/DirectExchange.java
deleted file mode 100644
index cb0d8ecf8f..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/exchange/DirectExchange.java
+++ /dev/null
@@ -1,216 +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.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.InboundMessage;
-import org.apache.qpid.server.queue.AMQQueue;
-import org.apache.qpid.server.queue.BaseQueue;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-
-import javax.management.JMException;
-import java.util.ArrayList;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.CopyOnWriteArraySet;
-
-public class DirectExchange extends AbstractExchange
-{
- private static final Logger _logger = Logger.getLogger(DirectExchange.class);
-
- private final ConcurrentHashMap<String, CopyOnWriteArraySet<Binding>> _bindingsByKey =
- new ConcurrentHashMap<String, CopyOnWriteArraySet<Binding>>();
-
- public static final ExchangeType<DirectExchange> TYPE = new ExchangeType<DirectExchange>()
- {
-
- public AMQShortString getName()
- {
- return ExchangeDefaults.DIRECT_EXCHANGE_CLASS;
- }
-
- public Class<DirectExchange> getExchangeClass()
- {
- return DirectExchange.class;
- }
-
- public DirectExchange newInstance(VirtualHost host,
- AMQShortString name,
- boolean durable,
- int ticket,
- boolean autoDelete) throws AMQException
- {
- DirectExchange exch = new DirectExchange();
- exch.initialise(host,name,durable,ticket,autoDelete);
- return exch;
- }
-
- public AMQShortString getDefaultExchangeName()
- {
- return ExchangeDefaults.DIRECT_EXCHANGE_NAME;
- }
- };
-
-
- public DirectExchange()
- {
- super(TYPE);
- }
-
- protected AbstractExchangeMBean createMBean() throws JMException
- {
- return new DirectExchangeMBean(this);
- }
-
- public Logger getLogger()
- {
- return _logger;
- }
-
-
- public ArrayList<? extends BaseQueue> doRoute(InboundMessage payload)
- {
-
- final String routingKey = payload.getRoutingKey();
-
- CopyOnWriteArraySet<Binding> bindings = _bindingsByKey.get(routingKey == null ? "" : routingKey);
-
- if(bindings != null)
- {
- final ArrayList<BaseQueue> queues = new ArrayList<BaseQueue>(bindings.size());
-
- for(Binding binding : bindings)
- {
- queues.add(binding.getQueue());
- binding.incrementMatches();
- }
-
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Publishing message to queue " + queues);
- }
-
- return queues;
- }
- else
- {
- return new ArrayList<BaseQueue>(0);
- }
-
-
-
- }
-
- public boolean isBound(AMQShortString routingKey, FieldTable arguments, AMQQueue queue)
- {
- return isBound(routingKey,queue);
- }
-
- public boolean isBound(AMQShortString routingKey, AMQQueue queue)
- {
- String bindingKey = (routingKey == null) ? "" : routingKey.toString();
- CopyOnWriteArraySet<Binding> bindings = _bindingsByKey.get(bindingKey);
- if(bindings != null)
- {
- for(Binding binding : bindings)
- {
- if(binding.getQueue().equals(queue))
- {
- return true;
- }
- }
- }
- return false;
-
- }
-
- public boolean isBound(AMQShortString routingKey)
- {
- String bindingKey = (routingKey == null) ? "" : routingKey.toString();
- CopyOnWriteArraySet<Binding> bindings = _bindingsByKey.get(bindingKey);
- return bindings != null && !bindings.isEmpty();
- }
-
- public boolean isBound(AMQQueue queue)
- {
-
- for (CopyOnWriteArraySet<Binding> bindings : _bindingsByKey.values())
- {
- for(Binding binding : bindings)
- {
- if(binding.getQueue().equals(queue))
- {
- return true;
- }
- }
- }
- return false;
- }
-
- public boolean hasBindings()
- {
- return !getBindings().isEmpty();
- }
-
- protected void onBind(final Binding binding)
- {
- String bindingKey = binding.getBindingKey();
- AMQQueue queue = binding.getQueue();
- AMQShortString routingKey = AMQShortString.valueOf(bindingKey);
-
- assert queue != null;
- assert routingKey != null;
-
- CopyOnWriteArraySet<Binding> bindings = _bindingsByKey.get(bindingKey);
-
- if(bindings == null)
- {
- bindings = new CopyOnWriteArraySet<Binding>();
- CopyOnWriteArraySet<Binding> newBindings;
- if((newBindings = _bindingsByKey.putIfAbsent(bindingKey, bindings)) != null)
- {
- bindings = newBindings;
- }
- }
-
- bindings.add(binding);
-
- }
-
- protected void onUnbind(final Binding binding)
- {
- assert binding != null;
-
- CopyOnWriteArraySet<Binding> bindings = _bindingsByKey.get(binding.getBindingKey());
- if(bindings != null)
- {
- bindings.remove(binding);
- }
-
- }
-
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/DirectExchangeMBean.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/DirectExchangeMBean.java
deleted file mode 100644
index 94fc44d9c7..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/exchange/DirectExchangeMBean.java
+++ /dev/null
@@ -1,81 +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.management.common.mbeans.annotations.MBeanDescription;
-import org.apache.qpid.management.common.mbeans.annotations.MBeanConstructor;
-import org.apache.qpid.server.binding.Binding;
-
-import javax.management.JMException;
-import javax.management.openmbean.*;
-import java.util.List;
-import java.util.Map;
-import java.util.ArrayList;
-import java.util.HashMap;
-
-/**
- * MBean class implementing the management interfaces.
- */
-@MBeanDescription("Management Bean for Direct Exchange")
-final class DirectExchangeMBean extends AbstractExchangeMBean<DirectExchange>
-{
- @MBeanConstructor("Creates an MBean for AMQ direct exchange")
- public DirectExchangeMBean(final DirectExchange exchange) throws JMException
- {
- super(exchange);
-
- init();
- }
-
- public TabularData bindings() throws OpenDataException
- {
- TabularDataSupport bindingList = new TabularDataSupport(_bindinglistDataType);
-
- Map<String, List<String>> bindingMap = new HashMap<String, List<String>>();
-
- for (Binding binding : getExchange().getBindings())
- {
- String key = binding.getBindingKey();
- List<String> queueList = bindingMap.get(key);
- if(queueList == null)
- {
- queueList = new ArrayList<String>();
- bindingMap.put(key, queueList);
- }
- queueList.add(binding.getQueue().getNameShortString().toString());
-
- }
-
- for(Map.Entry<String, List<String>> entry : bindingMap.entrySet())
- {
- Object[] bindingItemValues = {entry.getKey(), entry.getValue().toArray(new String[0])};
- CompositeData bindingData = new CompositeDataSupport(_bindingDataType,
- COMPOSITE_ITEM_NAMES.toArray(new String[COMPOSITE_ITEM_NAMES.size()]),
- bindingItemValues);
- bindingList.put(bindingData);
- }
-
- return bindingList;
- }
-
-
-
-}// End of MBean class
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/Exchange.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/Exchange.java
deleted file mode 100644
index 356a7f89b9..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/exchange/Exchange.java
+++ /dev/null
@@ -1,145 +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.AMQInternalException;
-import org.apache.qpid.AMQSecurityException;
-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.message.InboundMessage;
-import org.apache.qpid.server.binding.BindingFactory;
-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.List;
-import java.util.Collection;
-import java.util.concurrent.CopyOnWriteArrayList;
-
-public interface Exchange extends ExchangeReferrer, ExchangeConfig
-{
-
- public interface BindingListener
- {
- void bindingAdded(Exchange exchange, Binding binding);
- void bindingRemoved(Exchange exchange, Binding binding);
- }
-
- AMQShortString getNameShortString();
-
- AMQShortString getTypeShortString();
-
- void initialise(VirtualHost host, AMQShortString name, boolean durable, int ticket, boolean autoDelete)
- throws AMQException, JMException;
-
- boolean isDurable();
-
- /**
- * @return true if the exchange will be deleted after all queues have been detached
- */
- boolean isAutoDelete();
-
- int getTicket();
-
- void close() throws AMQException;
-
-
- ArrayList<? extends BaseQueue> route(InboundMessage message);
-
-
- /**
- * Determines whether a message would be isBound to a particular queue using a specific routing key and arguments
- * @param routingKey
- * @param arguments
- * @param queue
- * @return
- * @throws AMQException
- */
- boolean isBound(AMQShortString routingKey, FieldTable arguments, AMQQueue queue);
-
- /**
- * Determines whether a message would be isBound to a particular queue using a specific routing key
- * @param routingKey
- * @param queue
- * @return
- * @throws AMQException
- */
- boolean isBound(AMQShortString routingKey, AMQQueue queue);
-
- /**
- * Determines whether a message is routing to any queue using a specific _routing key
- * @param routingKey
- * @return
- * @throws AMQException
- */
- boolean isBound(AMQShortString routingKey);
-
- boolean isBound(AMQQueue queue);
-
- /**
- * Returns true if this exchange has at least one binding associated with it.
- * @return
- * @throws AMQException
- */
- boolean hasBindings();
-
-
- boolean isBound(String bindingKey, AMQQueue queue);
-
- boolean isBound(String bindingKey);
-
- void addCloseTask(Task task);
-
- void removeCloseTask(Task task);
-
-
- Exchange getAlternateExchange();
-
- void setAlternateExchange(Exchange exchange);
-
- void removeReference(ExchangeReferrer exchange);
-
- void addReference(ExchangeReferrer exchange);
-
- boolean hasReferrers();
-
- void addBinding(Binding binding);
-
- void removeBinding(Binding binding);
-
- Collection<Binding> getBindings();
-
- public void addBindingListener(BindingListener listener);
-
- public void removeBindingListener(BindingListener listener);
-
-
- public static interface Task
- {
- public void onClose(Exchange exchange) throws AMQSecurityException, AMQInternalException;
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeFactory.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeFactory.java
deleted file mode 100644
index 92795487e4..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeFactory.java
+++ /dev/null
@@ -1,43 +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 java.util.Collection;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.server.configuration.VirtualHostConfiguration;
-
-
-public interface ExchangeFactory
-{
- Exchange createExchange(AMQShortString exchange, AMQShortString type, boolean durable, boolean autoDelete,
- int ticket)
- throws AMQException;
-
- void initialise(VirtualHostConfiguration hostConfig);
-
- Collection<ExchangeType<? extends Exchange>> getRegisteredTypes();
-
- Collection<ExchangeType<? extends Exchange>> getPublicCreatableTypes();
-
- Exchange createExchange(String exchange, String type, boolean durable, boolean autoDelete) throws AMQException;
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeInUseException.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeInUseException.java
deleted file mode 100644
index c77f114428..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeInUseException.java
+++ /dev/null
@@ -1,45 +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;
-
-/**
- * ExchangeInUseRegistry indicates that an exchange cannot be unregistered because it is currently being used.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Represents failure to unregister exchange that is in use.
- * </table>
- *
- * @todo Not an AMQP exception as no status code.
- *
- * @todo This exception is not used. However, it is part of the ExchangeRegistry interface, and looks like code is
- * going to need to be added to throw/deal with this. Alternatively ExchangeResitries may be able to handle the
- * issue internally.
- */
-public class ExchangeInUseException extends AMQException
-{
- public ExchangeInUseException(String exchangeName)
- {
- super("Exchange " + exchangeName + " is currently in use");
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeInitialiser.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeInitialiser.java
deleted file mode 100644
index 4dfcce7bbe..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeInitialiser.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.exchange;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.exchange.ExchangeDefaults;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.server.store.DurableConfigurationStore;
-
-public class ExchangeInitialiser
-{
- public void initialise(ExchangeFactory factory, ExchangeRegistry registry, DurableConfigurationStore store) throws AMQException{
- for (ExchangeType<? extends Exchange> type : factory.getRegisteredTypes())
- {
- define (registry, factory, type.getDefaultExchangeName(), type.getName(), store);
- }
-
- define(registry, factory, ExchangeDefaults.DEFAULT_EXCHANGE_NAME, ExchangeDefaults.DIRECT_EXCHANGE_CLASS, store);
- registry.setDefaultExchange(registry.getExchange(ExchangeDefaults.DEFAULT_EXCHANGE_NAME));
- }
-
- private void define(ExchangeRegistry r, ExchangeFactory f,
- AMQShortString name, AMQShortString type, DurableConfigurationStore store) throws AMQException
- {
- if(r.getExchange(name)== null)
- {
- Exchange exchange = f.createExchange(name, type, true, false, 0);
- r.registerExchange(exchange);
-
- if(exchange.isDurable())
- {
- store.createExchange(exchange);
- }
- }
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeReferrer.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeReferrer.java
deleted file mode 100755
index e41d63d97d..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeReferrer.java
+++ /dev/null
@@ -1,26 +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;
-
-public interface ExchangeReferrer
-{
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeRegistry.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeRegistry.java
deleted file mode 100644
index e34ef29d9b..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeRegistry.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.exchange;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.AMQShortString;
-
-import java.util.Collection;
-
-
-public interface ExchangeRegistry extends MessageRouter
-{
- void registerExchange(Exchange exchange) throws AMQException;
-
- /**
- * Unregister an exchange
- * @param name name of the exchange to delete
- * @param inUse if true, do NOT delete the exchange if it is in use (has queues bound to it)
- * @throws ExchangeInUseException when the exchange cannot be deleted because it is in use
- * @throws AMQException
- */
- void unregisterExchange(AMQShortString name, boolean inUse) throws ExchangeInUseException, AMQException;
-
- Exchange getExchange(AMQShortString name);
-
- void setDefaultExchange(Exchange exchange);
-
- Exchange getDefaultExchange();
-
- Collection<AMQShortString> getExchangeNames();
-
- void initialise() throws AMQException;
-
- Exchange getExchange(String exchangeName);
-
- void unregisterExchange(String exchange, boolean ifUnused) throws ExchangeInUseException, AMQException;;
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeType.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeType.java
deleted file mode 100644
index 0b55caa2f1..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeType.java
+++ /dev/null
@@ -1,35 +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.framing.AMQShortString;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-
-
-public interface ExchangeType<T extends Exchange>
-{
- public AMQShortString getName();
- public Class<T> getExchangeClass();
- public T newInstance(VirtualHost host, AMQShortString name,
- boolean durable, int ticket, boolean autoDelete) throws AMQException;
- public AMQShortString getDefaultExchangeName();
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/FanoutExchange.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/FanoutExchange.java
deleted file mode 100644
index bd75f7bc51..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/exchange/FanoutExchange.java
+++ /dev/null
@@ -1,206 +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.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.InboundMessage;
-import org.apache.qpid.server.queue.AMQQueue;
-import org.apache.qpid.server.queue.BaseQueue;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-
-import javax.management.JMException;
-import java.util.ArrayList;
-import java.util.concurrent.ConcurrentHashMap;
-
-public class FanoutExchange extends AbstractExchange
-{
- private static final Logger _logger = Logger.getLogger(FanoutExchange.class);
-
- private static final Integer ONE = Integer.valueOf(1);
-
- /**
- * Maps from queue name to queue instances
- */
- private final ConcurrentHashMap<AMQQueue,Integer> _queues = new ConcurrentHashMap<AMQQueue,Integer>();
-
- protected AbstractExchangeMBean createMBean() throws JMException
- {
- return new FanoutExchangeMBean(this);
- }
-
- public Logger getLogger()
- {
- return _logger;
- }
-
- public static final ExchangeType<FanoutExchange> TYPE = new ExchangeType<FanoutExchange>()
- {
-
- public AMQShortString getName()
- {
- return ExchangeDefaults.FANOUT_EXCHANGE_CLASS;
- }
-
- public Class<FanoutExchange> getExchangeClass()
- {
- return FanoutExchange.class;
- }
-
- public FanoutExchange newInstance(VirtualHost host,
- AMQShortString name,
- boolean durable,
- int ticket,
- boolean autoDelete) throws AMQException
- {
- FanoutExchange exch = new FanoutExchange();
- exch.initialise(host, name, durable, ticket, autoDelete);
- return exch;
- }
-
- public AMQShortString getDefaultExchangeName()
- {
- return ExchangeDefaults.FANOUT_EXCHANGE_NAME;
- }
- };
-
- public FanoutExchange()
- {
- super(TYPE);
- }
-
- public ArrayList<BaseQueue> doRoute(InboundMessage payload)
- {
-
-
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Publishing message to queue " + _queues);
- }
-
- for(Binding b : getBindings())
- {
- b.incrementMatches();
- }
-
- return new ArrayList<BaseQueue>(_queues.keySet());
-
- }
-
- public boolean isBound(AMQShortString routingKey, FieldTable arguments, AMQQueue queue)
- {
- return isBound(routingKey, queue);
- }
-
- public boolean isBound(AMQShortString routingKey, AMQQueue queue)
- {
- return _queues.contains(queue);
- }
-
- public boolean isBound(AMQShortString routingKey)
- {
-
- return (_queues != null) && !_queues.isEmpty();
- }
-
- public boolean isBound(AMQQueue queue)
- {
-
- return _queues.contains(queue);
- }
-
- public boolean hasBindings()
- {
- return !_queues.isEmpty();
- }
-
- protected void onBind(final Binding binding)
- {
- AMQQueue queue = binding.getQueue();
- assert queue != null;
-
- Integer oldVal;
-
- if((oldVal = _queues.putIfAbsent(queue, ONE)) != null)
- {
- Integer newVal = oldVal+1;
- while(!_queues.replace(queue, oldVal, newVal))
- {
- oldVal = _queues.get(queue);
- if(oldVal == null)
- {
- oldVal = _queues.putIfAbsent(queue, ONE);
- if(oldVal == null)
- {
- break;
- }
- }
- newVal = oldVal + 1;
- }
- }
-
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Binding queue " + queue
- + " with routing key " + new AMQShortString(binding.getBindingKey()) + " to exchange " + this);
- }
- }
-
- protected void onUnbind(final Binding binding)
- {
- AMQQueue queue = binding.getQueue();
- Integer oldValue = _queues.get(queue);
-
- boolean done = false;
-
- while(!(done || oldValue == null))
- {
- while(!(done || oldValue == null) && oldValue.intValue() == 1)
- {
- if(!_queues.remove(queue, oldValue))
- {
- oldValue = _queues.get(queue);
- }
- else
- {
- done = true;
- }
- }
- while(!(done || oldValue == null) && oldValue.intValue() != 1)
- {
- Integer newValue = oldValue - 1;
- if(!_queues.replace(queue, oldValue, newValue))
- {
- oldValue = _queues.get(queue);
- }
- else
- {
- done = true;
- }
- }
- }
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/FanoutExchangeMBean.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/FanoutExchangeMBean.java
deleted file mode 100644
index 2c85b7f787..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/exchange/FanoutExchangeMBean.java
+++ /dev/null
@@ -1,70 +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.management.common.mbeans.annotations.MBeanDescription;
-import org.apache.qpid.management.common.mbeans.annotations.MBeanConstructor;
-import org.apache.qpid.server.binding.Binding;
-
-import javax.management.JMException;
-import javax.management.openmbean.*;
-import java.util.ArrayList;
-
-/**
- * MBean class implementing the management interfaces.
- */
-@MBeanDescription("Management Bean for Fanout Exchange")
-final class FanoutExchangeMBean extends AbstractExchangeMBean<FanoutExchange>
-{
- private static final String BINDING_KEY_SUBSTITUTE = "*";
-
- @MBeanConstructor("Creates an MBean for AMQ fanout exchange")
- public FanoutExchangeMBean(final FanoutExchange exchange) throws JMException
- {
- super(exchange);
- init();
- }
-
- public TabularData bindings() throws OpenDataException
- {
-
- TabularDataSupport bindingList = new TabularDataSupport(_bindinglistDataType);
-
-
- ArrayList<String> queueNames = new ArrayList<String>();
-
- for (Binding binding : getExchange().getBindings())
- {
- String queueName = binding.getQueue().getNameShortString().toString();
- queueNames.add(queueName);
- }
-
- Object[] bindingItemValues = {BINDING_KEY_SUBSTITUTE, queueNames.toArray(new String[0])};
- CompositeData bindingData = new CompositeDataSupport(_bindingDataType,
- COMPOSITE_ITEM_NAMES.toArray(new String[COMPOSITE_ITEM_NAMES.size()]),
- bindingItemValues);
- bindingList.put(bindingData);
-
- return bindingList;
- }
-
-
-} // End of MBean class
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/HeadersBinding.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/HeadersBinding.java
deleted file mode 100644
index f58a6513a9..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/exchange/HeadersBinding.java
+++ /dev/null
@@ -1,260 +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 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;
-
-/**
- * Defines binding and matching based on a set of headers.
- */
-class HeadersBinding
-{
- private static final Logger _logger = Logger.getLogger(HeadersBinding.class);
-
- private final FieldTable _mappings;
- private final Binding _binding;
- private final Set<String> required = new HashSet<String>();
- private final Map<String,Object> matches = new HashMap<String,Object>();
- private boolean matchAny;
-
- /**
- * Creates a header binding for a set of mappings. Those mappings whose value is
- * null or the empty string are assumed only to be required headers, with
- * no constraint on the value. Those with a non-null value are assumed to
- * define a required match of value.
- *
- * @param binding the binding to create a header binding using
- */
- public HeadersBinding(Binding binding)
- {
- _binding = binding;
- if(_binding !=null)
- {
- _mappings = FieldTable.convertToFieldTable(_binding.getArguments());
- initMappings();
- }
- else
- {
- _mappings = null;
- }
- }
-
- private void initMappings()
- {
- _mappings.processOverElements(new FieldTable.FieldTableElementProcessor()
- {
-
- public boolean processElement(String propertyName, AMQTypedValue value)
- {
- 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;
- }
-
- public Object getResult()
- {
- return null;
- }
- });
- }
-
- protected FieldTable getMappings()
- {
- return _mappings;
- }
-
- public Binding getBinding()
- {
- return _binding;
- }
-
- /**
- * Checks whether the supplied headers match the requirements of this binding
- * @param headers the headers to check
- * @return true if the headers define any required keys and match any required
- * values
- */
- public boolean matches(AMQMessageHeader headers)
- {
- if(headers == null)
- {
- return required.isEmpty() && matches.isEmpty();
- }
- else
- {
- return matchAny ? or(headers) : and(headers);
- }
- }
-
- private boolean and(AMQMessageHeader headers)
- {
- if(headers.containsHeaders(required))
- {
- for(Map.Entry<String, Object> e : matches.entrySet())
- {
- if(!e.getValue().equals(headers.getHeader(e.getKey())))
- {
- return false;
- }
- }
- return true;
- }
- else
- {
- return false;
- }
- }
-
-
- private boolean or(final AMQMessageHeader headers)
- {
- if(required.isEmpty())
- {
- return matches.isEmpty() || passesMatchesOr(headers);
- }
- else
- {
- if(!passesRequiredOr(headers))
- {
- return !matches.isEmpty() && passesMatchesOr(headers);
- }
- else
- {
- return true;
- }
-
- }
- }
-
- private boolean passesMatchesOr(AMQMessageHeader headers)
- {
- for(Map.Entry<String,Object> entry : matches.entrySet())
- {
- if(headers.containsHeader(entry.getKey())
- && ((entry.getValue() == null && headers.getHeader(entry.getKey()) == null)
- || (entry.getValue().equals(headers.getHeader(entry.getKey())))))
- {
- return true;
- }
- }
- return false;
- }
-
- private boolean passesRequiredOr(AMQMessageHeader headers)
- {
- for(String name : required)
- {
- if(headers.containsHeader(name))
- {
- return true;
- }
- }
- return false;
- }
-
- private void processSpecial(String key, Object value)
- {
- if("X-match".equalsIgnoreCase(key))
- {
- matchAny = isAny(value);
- }
- else
- {
- _logger.warn("Ignoring special header: " + key);
- }
- }
-
- private boolean isAny(Object value)
- {
- if(value instanceof String)
- {
- 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
- }
-
- static boolean isSpecial(Object key)
- {
- return key instanceof String && isSpecial((String) key);
- }
-
- static boolean isSpecial(String key)
- {
- return key.startsWith("X-") || key.startsWith("x-");
- }
-
- @Override
- public boolean equals(final Object o)
- {
- if (this == o)
- {
- return true;
- }
-
- if (o == null)
- {
- return false;
- }
-
- if (!(o instanceof HeadersBinding))
- {
- return false;
- }
-
- final HeadersBinding hb = (HeadersBinding) o;
-
- if(_binding == null)
- {
- if(hb.getBinding() != null)
- {
- return false;
- }
- }
- else if (!_binding.equals(hb.getBinding()))
- {
- return false;
- }
-
- return true;
- }
-} \ No newline at end of file
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/HeadersExchange.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/HeadersExchange.java
deleted file mode 100644
index f9cbfeb78b..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/exchange/HeadersExchange.java
+++ /dev/null
@@ -1,260 +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.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.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.CopyOnWriteArraySet;
-
-/**
- * An exchange that binds queues based on a set of required headers and header values
- * and routes messages to these queues by matching the headers of the message against
- * those with which the queues were bound.
- * <p/>
- * <pre>
- * The Headers Exchange
- *
- * Routes messages according to the value/presence of fields in the message header table.
- * (Basic and JMS content has a content header field called "headers" that is a table of
- * message header fields).
- *
- * class = "headers"
- * routing key is not used
- *
- * Has the following binding arguments:
- *
- * the X-match field - if "all", does an AND match (used for GRM), if "any", does an OR match.
- * other fields prefixed with "X-" are ignored (and generate a console warning message).
- * a field with no value or empty value indicates a match on presence only.
- * a field with a value indicates match on field presence and specific value.
- *
- * Standard instances:
- *
- * amq.match - pub/sub on field content/value
- * </pre>
- */
-public class HeadersExchange extends AbstractExchange
-{
-
- private static final Logger _logger = Logger.getLogger(HeadersExchange.class);
-
- private final ConcurrentHashMap<String, CopyOnWriteArraySet<Binding>> _bindingsByKey =
- new ConcurrentHashMap<String, CopyOnWriteArraySet<Binding>>();
-
- private final CopyOnWriteArrayList<HeadersBinding> _bindingHeaderMatchers =
- new CopyOnWriteArrayList<HeadersBinding>();
-
-
- public static final ExchangeType<HeadersExchange> TYPE = new ExchangeType<HeadersExchange>()
- {
-
- public AMQShortString getName()
- {
- return ExchangeDefaults.HEADERS_EXCHANGE_CLASS;
- }
-
- public Class<HeadersExchange> getExchangeClass()
- {
- return HeadersExchange.class;
- }
-
- public HeadersExchange newInstance(VirtualHost host, AMQShortString name, boolean durable, int ticket,
- boolean autoDelete) throws AMQException
- {
- HeadersExchange exch = new HeadersExchange();
-
- exch.initialise(host, name, durable, ticket, autoDelete);
- return exch;
- }
-
- public AMQShortString getDefaultExchangeName()
- {
-
- return ExchangeDefaults.HEADERS_EXCHANGE_NAME;
- }
- };
-
- public HeadersExchange()
- {
- super(TYPE);
- }
-
-
-
- public ArrayList<BaseQueue> doRoute(InboundMessage payload)
- {
- AMQMessageHeader header = payload.getMessageHeader();
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Exchange " + getNameShortString() + ": routing message with headers " + header);
- }
-
- LinkedHashSet<BaseQueue> queues = new LinkedHashSet<BaseQueue>();
-
- for (HeadersBinding hb : _bindingHeaderMatchers)
- {
- if (hb.matches(header))
- {
- Binding b = hb.getBinding();
-
- b.incrementMatches();
-
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Exchange " + getNameShortString() + ": delivering message with headers " +
- header + " to " + b.getQueue().getNameShortString());
- }
- queues.add(b.getQueue());
- }
- }
-
- return new ArrayList<BaseQueue>(queues);
- }
-
- public boolean isBound(AMQShortString routingKey, FieldTable arguments, AMQQueue queue)
- {
- //fixme isBound here should take the arguements in to consideration.
- return isBound(routingKey, queue);
- }
-
- public boolean isBound(AMQShortString routingKey, AMQQueue queue)
- {
- String bindingKey = (routingKey == null) ? "" : routingKey.toString();
- CopyOnWriteArraySet<Binding> bindings = _bindingsByKey.get(bindingKey);
-
- if(bindings != null)
- {
- for(Binding binding : bindings)
- {
- if(binding.getQueue().equals(queue))
- {
- return true;
- }
- }
- }
-
- return false;
- }
-
- public boolean isBound(AMQShortString routingKey)
- {
- String bindingKey = (routingKey == null) ? "" : routingKey.toString();
- CopyOnWriteArraySet<Binding> bindings = _bindingsByKey.get(bindingKey);
- return bindings != null && !bindings.isEmpty();
- }
-
- public boolean isBound(AMQQueue queue)
- {
- for (CopyOnWriteArraySet<Binding> bindings : _bindingsByKey.values())
- {
- for(Binding binding : bindings)
- {
- if(binding.getQueue().equals(queue))
- {
- return true;
- }
- }
- }
-
- return false;
- }
-
- public boolean hasBindings()
- {
- return !getBindings().isEmpty();
- }
-
- protected AbstractExchangeMBean createMBean() throws JMException
- {
- return new HeadersExchangeMBean(this);
- }
-
- public Logger getLogger()
- {
- return _logger;
- }
-
- protected void onBind(final Binding binding)
- {
- String bindingKey = binding.getBindingKey();
- AMQQueue queue = binding.getQueue();
- AMQShortString routingKey = AMQShortString.valueOf(bindingKey);
- Map<String,Object> args = binding.getArguments();
-
- assert queue != null;
- assert routingKey != null;
-
- CopyOnWriteArraySet<Binding> bindings = _bindingsByKey.get(bindingKey);
-
- if(bindings == null)
- {
- bindings = new CopyOnWriteArraySet<Binding>();
- CopyOnWriteArraySet<Binding> newBindings;
- if((newBindings = _bindingsByKey.putIfAbsent(bindingKey, bindings)) != null)
- {
- bindings = newBindings;
- }
- }
-
- if(_logger.isDebugEnabled())
- {
- _logger.debug("Exchange " + getNameShortString() + ": Binding " + queue.getNameShortString() +
- " with binding key '" +bindingKey + "' and args: " + args);
- }
-
- _bindingHeaderMatchers.add(new HeadersBinding(binding));
- bindings.add(binding);
-
- }
-
- protected void onUnbind(final Binding binding)
- {
- assert binding != null;
-
- CopyOnWriteArraySet<Binding> bindings = _bindingsByKey.get(binding.getBindingKey());
- if(bindings != null)
- {
- bindings.remove(binding);
- }
-
- if(_logger.isDebugEnabled())
- {
- _logger.debug("Removing Binding: " + _bindingHeaderMatchers.remove(new HeadersBinding(binding)));
- }
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/HeadersExchangeMBean.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/HeadersExchangeMBean.java
deleted file mode 100644
index 66c9b5b552..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/exchange/HeadersExchangeMBean.java
+++ /dev/null
@@ -1,98 +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.management.common.mbeans.annotations.MBeanDescription;
-import org.apache.qpid.management.common.mbeans.annotations.MBeanConstructor;
-import org.apache.qpid.server.binding.Binding;
-
-import javax.management.JMException;
-import javax.management.openmbean.*;
-import java.util.List;
-import java.util.ArrayList;
-import java.util.Map;
-
-/**
- * HeadersExchangeMBean class implements the management interface for the
- * Header Exchanges.
- */
-@MBeanDescription("Management Bean for Headers Exchange")
-final class HeadersExchangeMBean extends AbstractExchangeMBean<HeadersExchange>
-{
-
- @MBeanConstructor("Creates an MBean for AMQ Headers exchange")
- public HeadersExchangeMBean(final HeadersExchange headersExchange) throws JMException
- {
- super(headersExchange);
- init();
- }
-
- /**
- * initialises the OpenType objects.
- */
- 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()]));
- }
-
- public TabularData bindings() throws OpenDataException
- {
- TabularDataSupport bindingList = new TabularDataSupport(_bindinglistDataType);
- int count = 1;
- for (Binding binding : getExchange().getBindings())
- {
-
- String queueName = binding.getQueue().getNameShortString().toString();
-
-
- Map<String,Object> headerMappings = binding.getArguments();
- final List<String> mappingList = new ArrayList<String>();
-
- if(headerMappings != null)
- {
- for(Map.Entry<String,Object> entry : headerMappings.entrySet())
- {
-
- mappingList.add(entry.getKey() + "=" + entry.getValue());
- }
- }
-
-
- Object[] bindingItemValues = {count++, queueName, mappingList.toArray(new String[0])};
- CompositeData bindingData = new CompositeDataSupport(_bindingDataType,
- HEADERS_COMPOSITE_ITEM_NAMES.toArray(new String[HEADERS_COMPOSITE_ITEM_NAMES.size()]), bindingItemValues);
- bindingList.put(bindingData);
- }
-
- return bindingList;
- }
-
-
-} // End of MBean class
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/MessageRouter.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/MessageRouter.java
deleted file mode 100644
index 025a8014aa..0000000000
--- a/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/java/broker/src/main/java/org/apache/qpid/server/exchange/TopicExchange.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/TopicExchange.java
deleted file mode 100644
index e523eb24fb..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/exchange/TopicExchange.java
+++ /dev/null
@@ -1,369 +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.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.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.filter.JMSSelectorFilter;
-import org.apache.qpid.server.message.InboundMessage;
-
-import javax.management.JMException;
-import java.util.*;
-import java.util.concurrent.ConcurrentHashMap;
-import java.lang.ref.WeakReference;
-
-public class TopicExchange extends AbstractExchange
-{
-
- public static final ExchangeType<TopicExchange> TYPE = new ExchangeType<TopicExchange>()
- {
-
- public AMQShortString getName()
- {
- return ExchangeDefaults.TOPIC_EXCHANGE_CLASS;
- }
-
- public Class<TopicExchange> getExchangeClass()
- {
- return TopicExchange.class;
- }
-
- public TopicExchange newInstance(VirtualHost host,
- AMQShortString name,
- boolean durable,
- int ticket,
- boolean autoDelete) throws AMQException
- {
- TopicExchange exch = new TopicExchange();
- exch.initialise(host, name, durable, ticket, autoDelete);
- return exch;
- }
-
- public AMQShortString getDefaultExchangeName()
- {
- return ExchangeDefaults.TOPIC_EXCHANGE_NAME;
- }
- };
-
-
- private static final Logger _logger = Logger.getLogger(TopicExchange.class);
-
-
-
- private final TopicParser _parser = new TopicParser();
-
- private final Map<AMQShortString, TopicExchangeResult> _topicExchangeResults =
- new ConcurrentHashMap<AMQShortString, TopicExchangeResult>();
-
- private final Map<Binding, FieldTable> _bindings = new HashMap<Binding, FieldTable>();
-
- private final Map<String, WeakReference<JMSSelectorFilter>> _selectorCache = new WeakHashMap<String, WeakReference<JMSSelectorFilter>>();
-
- public TopicExchange()
- {
- super(TYPE);
- }
-
- protected synchronized void registerQueue(final Binding binding) throws AMQInvalidArgumentException
- {
- AMQShortString rKey = new AMQShortString(binding.getBindingKey()) ;
- AMQQueue queue = binding.getQueue();
- FieldTable args = FieldTable.convertToFieldTable(binding.getArguments());
-
- assert queue != null;
- assert rKey != null;
-
- _logger.debug("Registering queue " + queue.getNameShortString() + " with routing key " + rKey);
-
-
- AMQShortString routingKey = TopicNormalizer.normalize(rKey);
-
- if(_bindings.containsKey(binding))
- {
- FieldTable oldArgs = _bindings.get(binding);
- TopicExchangeResult result = _topicExchangeResults.get(routingKey);
-
- if(argumentsContainSelector(args))
- {
- if(argumentsContainSelector(oldArgs))
- {
- result.replaceQueueFilter(queue,createSelectorFilter(oldArgs), createSelectorFilter(args));
- }
- else
- {
- result.addFilteredQueue(queue,createSelectorFilter(args));
- result.removeUnfilteredQueue(queue);
- }
- }
- else
- {
- if(argumentsContainSelector(oldArgs))
- {
- result.addUnfilteredQueue(queue);
- result.removeFilteredQueue(queue, createSelectorFilter(oldArgs));
- }
- else
- {
- // TODO - fix control flow
- return;
- }
- }
-
- result.addBinding(binding);
-
- }
- else
- {
-
- TopicExchangeResult result = _topicExchangeResults.get(routingKey);
- if(result == null)
- {
- result = new TopicExchangeResult();
- if(argumentsContainSelector(args))
- {
- result.addFilteredQueue(queue, createSelectorFilter(args));
- }
- else
- {
- result.addUnfilteredQueue(queue);
- }
- _parser.addBinding(routingKey, result);
- _topicExchangeResults.put(routingKey,result);
- }
- else
- {
- if(argumentsContainSelector(args))
- {
- result.addFilteredQueue(queue, createSelectorFilter(args));
- }
- else
- {
- result.addUnfilteredQueue(queue);
- }
- }
-
- result.addBinding(binding);
- _bindings.put(binding, args);
- }
-
-
- }
-
- private JMSSelectorFilter createSelectorFilter(final FieldTable args) throws AMQInvalidArgumentException
- {
-
- final String selectorString = args.getString(AMQPFilterTypes.JMS_SELECTOR.getValue());
- WeakReference<JMSSelectorFilter> selectorRef = _selectorCache.get(selectorString);
- JMSSelectorFilter selector = null;
-
- if(selectorRef == null || (selector = selectorRef.get())==null)
- {
- selector = new JMSSelectorFilter(selectorString);
- _selectorCache.put(selectorString, new WeakReference<JMSSelectorFilter>(selector));
- }
- return selector;
- }
-
- private static boolean argumentsContainSelector(final FieldTable args)
- {
- return args != null && args.containsKey(AMQPFilterTypes.JMS_SELECTOR.getValue()) && args.getString(AMQPFilterTypes.JMS_SELECTOR.getValue()).trim().length() != 0;
- }
-
- public ArrayList<BaseQueue> doRoute(InboundMessage payload)
- {
-
- final AMQShortString routingKey = payload.getRoutingKey() == null
- ? AMQShortString.EMPTY_STRING
- : new AMQShortString(payload.getRoutingKey());
-
- // The copy here is unfortunate, but not too bad relevant to the amount of
- // things created and copied in getMatchedQueues
- ArrayList<BaseQueue> queues = new ArrayList<BaseQueue>();
- queues.addAll(getMatchedQueues(payload, routingKey));
-
- if(queues == null || queues.isEmpty())
- {
- _logger.info("Message routing key: " + payload.getRoutingKey() + " No routes.");
- }
-
- return queues;
-
- }
-
- public boolean isBound(AMQShortString routingKey, FieldTable arguments, AMQQueue queue)
- {
- Binding binding = new Binding(null, routingKey.toString(), queue, this, FieldTable.convertToMap(arguments));
-
- if (arguments == null)
- {
- return _bindings.containsKey(binding);
- }
- else
- {
- FieldTable o = _bindings.get(binding);
- if (o != null)
- {
- return o.equals(arguments);
- }
- else
- {
- return false;
- }
-
- }
- }
-
- public boolean isBound(AMQShortString routingKey, AMQQueue queue)
- {
- return isBound(routingKey, null, queue);
- }
-
- public boolean isBound(AMQShortString routingKey)
- {
- for(Binding b : _bindings.keySet())
- {
- if(b.getBindingKey().equals(routingKey.toString()))
- {
- return true;
- }
- }
-
- return false;
- }
-
- public boolean isBound(AMQQueue queue)
- {
- for(Binding b : _bindings.keySet())
- {
- if(b.getQueue().equals(queue))
- {
- return true;
- }
- }
-
- return false;
- }
-
- public boolean hasBindings()
- {
- return !_bindings.isEmpty();
- }
-
- private boolean deregisterQueue(final Binding binding)
- {
- if(_bindings.containsKey(binding))
- {
- FieldTable bindingArgs = _bindings.remove(binding);
- AMQShortString bindingKey = TopicNormalizer.normalize(new AMQShortString(binding.getBindingKey()));
- TopicExchangeResult result = _topicExchangeResults.get(bindingKey);
-
- result.removeBinding(binding);
-
- if(argumentsContainSelector(bindingArgs))
- {
- try
- {
- result.removeFilteredQueue(binding.getQueue(), createSelectorFilter(bindingArgs));
- }
- catch (AMQInvalidArgumentException e)
- {
- return false;
- }
- }
- else
- {
- result.removeUnfilteredQueue(binding.getQueue());
- }
- return true;
- }
- else
- {
- return false;
- }
- }
-
- protected AbstractExchangeMBean createMBean() throws JMException
- {
- return new TopicExchangeMBean(this);
- }
-
- public Logger getLogger()
- {
- return _logger;
- }
-
- private Collection<AMQQueue> getMatchedQueues(InboundMessage message, AMQShortString routingKey)
- {
-
- Collection<TopicMatcherResult> results = _parser.parse(routingKey);
- if(results.isEmpty())
- {
- return Collections.EMPTY_SET;
- }
- else
- {
- Collection<AMQQueue> queues = results.size() == 1 ? null : new HashSet<AMQQueue>();
- for(TopicMatcherResult result : results)
- {
- TopicExchangeResult res = (TopicExchangeResult)result;
-
- for(Binding b : res.getBindings())
- {
- b.incrementMatches();
- }
-
- queues = res.processMessage(message, queues);
- }
- return queues;
- }
-
-
- }
-
- protected void onBind(final Binding binding)
- {
- try
- {
- registerQueue(binding);
- }
- catch (AMQInvalidArgumentException e)
- {
- throw new RuntimeException(e);
- }
- }
-
- protected void onUnbind(final Binding binding)
- {
- deregisterQueue(binding);
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/TopicExchangeMBean.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/TopicExchangeMBean.java
deleted file mode 100644
index 620c3ce140..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/exchange/TopicExchangeMBean.java
+++ /dev/null
@@ -1,77 +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.management.common.mbeans.annotations.MBeanDescription;
-import org.apache.qpid.management.common.mbeans.annotations.MBeanConstructor;
-import org.apache.qpid.server.binding.Binding;
-
-import javax.management.JMException;
-import javax.management.openmbean.*;
-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")
-final class TopicExchangeMBean extends AbstractExchangeMBean<TopicExchange>
-{
- private TopicExchange _topicExchange;
-
- @MBeanConstructor("Creates an MBean for AMQ topic exchange")
- public TopicExchangeMBean(final TopicExchange topicExchange) throws JMException
- {
- super(topicExchange);
- init();
- }
-
- /** returns exchange bindings in tabular form */
- public TabularData bindings() throws OpenDataException
- {
- TabularDataSupport bindingList = new TabularDataSupport(_bindinglistDataType);
- Map<String, List<String>> bindingData = new HashMap<String, List<String>>();
- for (Binding binding : getExchange().getBindings())
- {
- String key = binding.getBindingKey();
- List<String> queueNames = bindingData.get(key);
- if(queueNames == null)
- {
- queueNames = new ArrayList<String>();
- bindingData.put(key, queueNames);
- }
- queueNames.add(binding.getQueue().getNameShortString().toString());
-
- }
- for(Map.Entry<String, List<String>> entry : bindingData.entrySet())
- {
- Object[] bindingItemValues = {entry.getKey(), entry.getValue().toArray(new String[entry.getValue().size()]) };
- CompositeData bindingCompositeData =
- new CompositeDataSupport(_bindingDataType,
- COMPOSITE_ITEM_NAMES.toArray(new String[COMPOSITE_ITEM_NAMES.size()]),
- bindingItemValues);
- bindingList.put(bindingCompositeData);
- }
-
- return bindingList;
- }
-
-} // End of MBean class
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/headers/HeaderKey.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/headers/HeaderKey.java
deleted file mode 100644
index 8fdb91cbef..0000000000
--- a/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/java/broker/src/main/java/org/apache/qpid/server/exchange/headers/HeaderKeyDictionary.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/headers/HeaderKeyDictionary.java
deleted file mode 100644
index 7be99a88c9..0000000000
--- a/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<AMQShortString, HeaderKey> _dictionary = new HashMap<AMQShortString, HeaderKey>();
-
-
- 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/java/broker/src/main/java/org/apache/qpid/server/exchange/headers/HeaderMatcherResult.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/headers/HeaderMatcherResult.java
deleted file mode 100644
index 518064bb29..0000000000
--- a/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/java/broker/src/main/java/org/apache/qpid/server/exchange/headers/HeadersMatcherDFAState.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/headers/HeadersMatcherDFAState.java
deleted file mode 100644
index 9da93d483a..0000000000
--- a/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<HeaderMatcherResult> _results;
- private final Map<HeaderKey, Map<AMQTypedValue,HeadersMatcherDFAState>> _nextStateMap;
- private final HeaderKeyDictionary _dictionary;
-
- public HeadersMatcherDFAState(Map<HeaderKey, Map<AMQTypedValue,HeadersMatcherDFAState>> nextStateMap,
- Collection<HeaderMatcherResult> results,
- HeaderKeyDictionary dictionary)
- {
- _nextStateMap = nextStateMap;
- _results = results;
- _dictionary = dictionary;
- }
-
-
- public Collection<HeaderMatcherResult> match(final FieldTable table)
- {
- return match(table.iterator());
- }
-
-
-
- public Collection<HeaderMatcherResult> match(Iterator<Map.Entry<AMQShortString,AMQTypedValue>> fieldTableIterator)
- {
-
- if(_nextStateMap.isEmpty())
- {
- return _results;
- }
-
- while(fieldTableIterator.hasNext())
- {
-
- Map.Entry<AMQShortString, AMQTypedValue> fieldTableEntry = fieldTableIterator.next();
- HeaderKey key = _dictionary.get(fieldTableEntry.getKey());
- if(key != HeaderKey.UNKNOWN)
- {
- Map<AMQTypedValue, HeadersMatcherDFAState> 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<Set<HeadersMatcherDFAState>, HeadersMatcherDFAState> newStateMap= new HashMap<Set<HeadersMatcherDFAState>, HeadersMatcherDFAState>();
-
- Collection<HeaderMatcherResult> results;
-
- if(_results.isEmpty())
- {
- results = otherStateMachine._results;
- }
- else if(otherStateMachine._results.isEmpty())
- {
- results = _results;
- }
- else
- {
- results = new HashSet<HeaderMatcherResult>(_results);
- results.addAll(otherStateMachine._results);
- }
-
-
- final Map<HeaderKey, Map<AMQTypedValue, HeadersMatcherDFAState>> newNextStateMap = new HashMap<HeaderKey, Map<AMQTypedValue, HeadersMatcherDFAState>>();
-
- HeadersMatcherDFAState newState = new HeadersMatcherDFAState(newNextStateMap, results, _dictionary);
-
-
- Set<HeadersMatcherDFAState> oldStates = new HashSet<HeadersMatcherDFAState>();
- oldStates.add(this);
- oldStates.add(otherStateMachine);
-
- newStateMap.put(oldStates, newState);
-
- mergeStateMachines(oldStates, newNextStateMap, newStateMap);
-
- return newState;
-
-
- }
-
- private void mergeStateMachines(final Set<HeadersMatcherDFAState> oldStates,
- final Map<HeaderKey, Map<AMQTypedValue, HeadersMatcherDFAState>> newNextStateMap,
- final Map<Set<HeadersMatcherDFAState>, HeadersMatcherDFAState> newStateMap)
- {
- Map<HeaderKey, Map<AMQTypedValue, Set<HeadersMatcherDFAState>>> nfaMap = new HashMap<HeaderKey, Map<AMQTypedValue, Set<HeadersMatcherDFAState>>>();
-
- Set<HeaderKey> distinctKeys = new HashSet<HeaderKey>();
-
- for(HeadersMatcherDFAState state : oldStates)
- {
- Map<HeaderKey, Map<AMQTypedValue, HeadersMatcherDFAState>> map = state._nextStateMap;
-
- for(Map.Entry<HeaderKey, Map<AMQTypedValue, HeadersMatcherDFAState>> entry : map.entrySet())
- {
- Map<AMQTypedValue, Set<HeadersMatcherDFAState>> valueToStatesMap = nfaMap.get(entry.getKey());
-
- if(valueToStatesMap == null)
- {
- valueToStatesMap = new HashMap<AMQTypedValue, Set<HeadersMatcherDFAState>>();
- nfaMap.put(entry.getKey(), valueToStatesMap);
- }
-
- for(Map.Entry<AMQTypedValue, HeadersMatcherDFAState> valueToStateEntry : entry.getValue().entrySet())
- {
- Set<HeadersMatcherDFAState> states = valueToStatesMap.get(valueToStateEntry.getKey());
- if(states == null)
- {
- states = new HashSet<HeadersMatcherDFAState>();
- valueToStatesMap.put(valueToStateEntry.getKey(),states);
- }
- states.add(valueToStateEntry.getValue());
- }
-
- distinctKeys.add(entry.getKey());
- }
- }
-
- Map<HeaderKey, Set<HeadersMatcherDFAState>> anyValueStates = new HashMap<HeaderKey, Set<HeadersMatcherDFAState>>();
-
- for(HeaderKey distinctKey : distinctKeys)
- {
- Map<AMQTypedValue, Set<HeadersMatcherDFAState>> valueToStateMap = nfaMap.get(distinctKey);
- if(valueToStateMap != null)
- {
- Set<HeadersMatcherDFAState> 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<HeaderKey,Map<AMQTypedValue,Set<HeadersMatcherDFAState>>> entry : nfaMap.entrySet())
- {
- Map<AMQTypedValue, Set<HeadersMatcherDFAState>> valueToStatesMap = entry.getValue();
- for(Map.Entry<AMQTypedValue, Set<HeadersMatcherDFAState>> valueToStates : valueToStatesMap.entrySet())
- {
- if(valueToStates.getKey() != null)
- {
-
-
- Set<HeadersMatcherDFAState> 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<AMQTypedValue, Set<HeadersMatcherDFAState>> valueToStatesMap = nfaMap.get(distinctKey);
- for(HeadersMatcherDFAState oldState : oldStates)
- {
- if(!oldState._nextStateMap.containsKey(distinctKey))
- {
- for(Set<HeadersMatcherDFAState> endStates : valueToStatesMap.values())
- {
- endStates.add(oldState);
- }
- }
- }
- }
-
-
-
-
- for(Map.Entry<HeaderKey,Map<AMQTypedValue,Set<HeadersMatcherDFAState>>> transitionClass : nfaMap.entrySet())
- {
- Map<AMQTypedValue, HeadersMatcherDFAState> valueToDFAState = newNextStateMap.get(transitionClass.getKey());
- if(valueToDFAState == null)
- {
- valueToDFAState = new HashMap<AMQTypedValue, HeadersMatcherDFAState>();
- newNextStateMap.put(transitionClass.getKey(), valueToDFAState);
- }
-
- for(Map.Entry<AMQTypedValue,Set<HeadersMatcherDFAState>> transition : transitionClass.getValue().entrySet())
- {
- Set<HeadersMatcherDFAState> 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<HeaderMatcherResult> results;
-
- Set<Collection<HeaderMatcherResult>> resultSets = new HashSet<Collection<HeaderMatcherResult>>();
- 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<HeaderMatcherResult>();
- for(Collection<HeaderMatcherResult> oldResult : resultSets)
- {
- results.addAll(oldResult);
- }
- }
-
- final Map<HeaderKey, Map<AMQTypedValue, HeadersMatcherDFAState>> nextStateMap = new HashMap<HeaderKey, Map<AMQTypedValue, HeadersMatcherDFAState>>();
-
- nextState = new HeadersMatcherDFAState(nextStateMap, results, _dictionary);
- newStateMap.put(destinations, nextState);
-
- mergeStateMachines(
- destinations,
- nextStateMap,
- newStateMap);
-
-
- }
-
-
- }
- valueToDFAState.put(transition.getKey(),nextState);
- }
- }
-
-
-
- final ArrayList<HeaderKey> removeKeyList = new ArrayList<HeaderKey>();
-
- for(Map.Entry<HeaderKey,Map<AMQTypedValue,HeadersMatcherDFAState>> entry : _nextStateMap.entrySet())
- {
- final ArrayList<AMQTypedValue> removeValueList = new ArrayList<AMQTypedValue>();
-
- for(Map.Entry<AMQTypedValue,HeadersMatcherDFAState> 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/java/broker/src/main/java/org/apache/qpid/server/exchange/headers/HeadersParser.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/headers/HeadersParser.java
deleted file mode 100644
index 0e3a3894fe..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/exchange/headers/HeadersParser.java
+++ /dev/null
@@ -1,441 +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<HeaderKey, Map<AMQTypedValue, HeadersMatcherDFAState>> nextStateMap =
- new HashMap<HeaderKey, Map<AMQTypedValue, HeadersMatcherDFAState>>();
-
- Set<AMQShortString> seenKeys = new HashSet<AMQShortString>();
-
- Iterator<Map.Entry<AMQShortString, AMQTypedValue>> tableIterator = bindingArguments.iterator();
-
- while(tableIterator.hasNext())
- {
- final Map.Entry<AMQShortString, AMQTypedValue> 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<AMQTypedValue, HeadersMatcherDFAState> 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<AMQShortString> seenKeys = new HashSet<AMQShortString>();
- List<KeyValuePair> requiredTerms = new ArrayList<KeyValuePair>(bindingArguments.size());
-
- Iterator<Map.Entry<AMQShortString, AMQTypedValue>> tableIterator = bindingArguments.iterator();
-
-
-
- while(tableIterator.hasNext())
- {
- final Map.Entry<AMQShortString, AMQTypedValue> 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<Set<KeyValuePair>, HeadersMatcherDFAState> notSeenTermsToStateMap =
- new HashMap<Set<KeyValuePair>, 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<KeyValuePair> stateSet = new HashSet<KeyValuePair>();
- for(int posIndex = 0; posIndex < pos.length; posIndex++)
- {
- stateSet.add(requiredTerms.get(pos[posIndex]));
- }
-
- final Map<HeaderKey, Map<AMQTypedValue,HeadersMatcherDFAState>> nextStateMap =
- new HashMap<HeaderKey, Map<AMQTypedValue,HeadersMatcherDFAState>>();
-
-
- for(int posIndex = 0; posIndex < pos.length; posIndex++)
- {
- KeyValuePair nextTerm = requiredTerms.get(pos[posIndex]);
- HashSet<KeyValuePair> nextStateSet =
- new HashSet<KeyValuePair>(stateSet);
- nextStateSet.remove(nextTerm);
-
- Map<AMQTypedValue, HeadersMatcherDFAState> valueToStateMap =
- new HashMap<AMQTypedValue, HeadersMatcherDFAState>();
- 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<KeyValuePair>(requiredTerms));
-
-
-
- }
-
- public static void main(String[] args) throws AMQFrameDecodingException
- {
-
- FieldTable bindingTable = new FieldTable();
-
- bindingTable.setString(new AMQShortString("x-match"),"all");
- bindingTable.setInteger("a",1);
- bindingTable.setVoid(new AMQShortString("b"));
- bindingTable.setString("c","");
- bindingTable.setInteger("d",4);
- bindingTable.setInteger("e",1);
-
-
-
- FieldTable bindingTable2 = new FieldTable();
- bindingTable2.setString(new AMQShortString("x-match"),"all");
- bindingTable2.setInteger("a",1);
- bindingTable2.setVoid(new AMQShortString("b"));
- bindingTable2.setString("c","");
- bindingTable2.setInteger("d",4);
- bindingTable2.setInteger("e",1);
- bindingTable2.setInteger("f",1);
-
-
- FieldTable table = new FieldTable();
- table.setInteger("a",1);
- table.setInteger("b",2);
- table.setString("c","");
- table.setInteger("d",4);
- table.setInteger("e",1);
- table.setInteger("f",1);
- table.setInteger("h",1);
- table.setInteger("i",1);
- table.setInteger("j",1);
- table.setInteger("k",1);
- table.setInteger("l",1);
-
- org.apache.mina.common.ByteBuffer buffer = org.apache.mina.common.ByteBuffer.allocate( (int) table.getEncodedSize());
- EncodingUtils.writeFieldTableBytes(buffer, table);
- buffer.flip();
-
- FieldTable table2 = EncodingUtils.readFieldTable(buffer);
-
-
-
- FieldTable bindingTable3 = new FieldTable();
- bindingTable3.setString(new AMQShortString("x-match"),"any");
- bindingTable3.setInteger("a",1);
- bindingTable3.setInteger("b",3);
-
-
- FieldTable bindingTable4 = new FieldTable();
- bindingTable4.setString(new AMQShortString("x-match"),"any");
- bindingTable4.setVoid(new AMQShortString("a"));
-
-
- FieldTable bindingTable5 = new FieldTable();
- bindingTable5.setString(new AMQShortString("x-match"),"all");
- bindingTable5.setString(new AMQShortString("h"),"hello");
-
- for(int i = 0; i < 100; i++)
- {
- printMatches(new FieldTable[] {bindingTable5} , table2);
- }
-
-
-
- }
-
-
-
- private static void printMatches(final FieldTable[] bindingKeys, final FieldTable routingKey)
- {
- HeadersMatcherDFAState sm = null;
- Map<HeaderMatcherResult, String> resultMap = new HashMap<HeaderMatcherResult, String>();
-
- HeadersParser parser = new HeadersParser();
-
- for(int i = 0; i < bindingKeys.length; i++)
- {
- HeaderMatcherResult r = new HeaderMatcherResult();
- resultMap.put(r, bindingKeys[i].toString());
-
-
- if(i==0)
- {
- sm = parser.createStateMachine(bindingKeys[i], r);
- }
- else
- {
- sm = sm.mergeStateMachines(parser.createStateMachine(bindingKeys[i], r));
- }
- }
-
- Collection<HeaderMatcherResult> results = null;
- long beforeTime = System.currentTimeMillis();
- for(int i = 0; i < 1000000; i++)
- {
- routingKey.size();
-
- assert sm != null;
- results = sm.match(routingKey);
-
- }
- long elapsed = System.currentTimeMillis() - beforeTime;
- System.out.println("1000000 Iterations took: " + elapsed);
- Collection<String> resultStrings = new ArrayList<String>();
-
- assert results != null;
- for(HeaderMatcherResult result : results)
- {
- resultStrings.add(resultMap.get(result));
- }
-
- final ArrayList<String> nonMatches = new ArrayList<String>();
- for(FieldTable key : bindingKeys)
- {
- nonMatches.add(key.toString());
- }
- nonMatches.removeAll(resultStrings);
- System.out.println("\""+routingKey+"\" matched with " + resultStrings + " DID NOT MATCH with " + nonMatches);
-
-
- }
-
-
- 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/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicExchangeResult.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicExchangeResult.java
deleted file mode 100644
index 41dc0d749a..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicExchangeResult.java
+++ /dev/null
@@ -1,201 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.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 java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.CopyOnWriteArrayList;
-
-public final class TopicExchangeResult implements TopicMatcherResult
-{
- private final List<Binding> _bindings = new CopyOnWriteArrayList<Binding>();
- private final Map<AMQQueue, Integer> _unfilteredQueues = new ConcurrentHashMap<AMQQueue, Integer>();
- private final ConcurrentHashMap<AMQQueue, Map<MessageFilter,Integer>> _filteredQueues = new ConcurrentHashMap<AMQQueue, Map<MessageFilter, Integer>>();
-
- public void addUnfilteredQueue(AMQQueue queue)
- {
- Integer instances = _unfilteredQueues.get(queue);
- if(instances == null)
- {
- _unfilteredQueues.put(queue, 1);
- }
- else
- {
- _unfilteredQueues.put(queue, instances + 1);
- }
- }
-
- public void removeUnfilteredQueue(AMQQueue queue)
- {
- Integer instances = _unfilteredQueues.get(queue);
- if(instances == 1)
- {
- _unfilteredQueues.remove(queue);
- }
- else
- {
- _unfilteredQueues.put(queue,instances - 1);
- }
-
- }
-
- public Collection<AMQQueue> getUnfilteredQueues()
- {
- return _unfilteredQueues.keySet();
- }
-
- public void addBinding(Binding binding)
- {
- _bindings.add(binding);
- }
-
- public void removeBinding(Binding binding)
- {
- _bindings.remove(binding);
- }
-
- public List<Binding> getBindings()
- {
- return new ArrayList<Binding>(_bindings);
- }
-
- public void addFilteredQueue(AMQQueue queue, MessageFilter filter)
- {
- Map<MessageFilter,Integer> filters = _filteredQueues.get(queue);
- if(filters == null)
- {
- filters = new ConcurrentHashMap<MessageFilter,Integer>();
- _filteredQueues.put(queue, filters);
- }
- Integer instances = filters.get(filter);
- if(instances == null)
- {
- filters.put(filter,1);
- }
- else
- {
- filters.put(filter, instances + 1);
- }
-
- }
-
- public void removeFilteredQueue(AMQQueue queue, MessageFilter filter)
- {
- Map<MessageFilter,Integer> filters = _filteredQueues.get(queue);
- if(filters != null)
- {
- Integer instances = filters.get(filter);
- if(instances != null)
- {
- if(instances == 1)
- {
- filters.remove(filter);
- if(filters.isEmpty())
- {
- _filteredQueues.remove(queue);
- }
- }
- else
- {
- filters.put(filter, instances - 1);
- }
- }
-
- }
-
- }
-
- public void replaceQueueFilter(AMQQueue queue,
- MessageFilter oldFilter,
- MessageFilter newFilter)
- {
- Map<MessageFilter,Integer> filters = _filteredQueues.get(queue);
- Map<MessageFilter,Integer> newFilters = new ConcurrentHashMap<MessageFilter,Integer>(filters);
- Integer oldFilterInstances = filters.get(oldFilter);
- if(oldFilterInstances == 1)
- {
- newFilters.remove(oldFilter);
- }
- else
- {
- newFilters.put(oldFilter, oldFilterInstances-1);
- }
- Integer newFilterInstances = filters.get(newFilter);
- if(newFilterInstances == null)
- {
- newFilters.put(newFilter, 1);
- }
- else
- {
- newFilters.put(newFilter, newFilterInstances+1);
- }
- _filteredQueues.put(queue,newFilters);
- }
-
- public Collection<AMQQueue> processMessage(InboundMessage msg, Collection<AMQQueue> queues)
- {
- if(queues == null)
- {
- if(_filteredQueues.isEmpty())
- {
- return new ArrayList<AMQQueue>(_unfilteredQueues.keySet());
- }
- else
- {
- queues = new HashSet<AMQQueue>();
- }
- }
- else if(!(queues instanceof Set))
- {
- queues = new HashSet<AMQQueue>(queues);
- }
-
- queues.addAll(_unfilteredQueues.keySet());
- if(!_filteredQueues.isEmpty())
- {
- for(Map.Entry<AMQQueue, Map<MessageFilter, Integer>> entry : _filteredQueues.entrySet())
- {
- if(!queues.contains(entry.getKey()))
- {
- for(MessageFilter filter : entry.getValue().keySet())
- {
- if(filter.matches(msg))
- {
- queues.add(entry.getKey());
- }
- }
- }
- }
- }
- return queues;
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicMatcherDFAState.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicMatcherDFAState.java
deleted file mode 100644
index 36076cf75b..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicMatcherDFAState.java
+++ /dev/null
@@ -1,295 +0,0 @@
-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.concurrent.atomic.AtomicInteger;
-
-/*
-*
-* 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 TopicMatcherDFAState
-{
- private static final AtomicInteger stateId = new AtomicInteger();
-
- private final int _id = stateId.incrementAndGet();
-
- private final Collection<TopicMatcherResult> _results;
- private final Map<TopicWord, TopicMatcherDFAState> _nextStateMap;
- private static final byte TOPIC_DELIMITTER = (byte)'.';
-
-
- public TopicMatcherDFAState(Map<TopicWord, TopicMatcherDFAState> nextStateMap,
- Collection<TopicMatcherResult> results )
- {
- _nextStateMap = nextStateMap;
- _results = results;
- }
-
-
- public TopicMatcherDFAState nextState(TopicWord word)
- {
- final TopicMatcherDFAState nextState = _nextStateMap.get(word);
- return nextState == null ? _nextStateMap.get(TopicWord.ANY_WORD) : nextState;
- }
-
- public Collection<TopicMatcherResult> terminate()
- {
- return _results;
- }
-
-
- public Collection<TopicMatcherResult> parse(TopicWordDictionary dictionary, AMQShortString routingKey)
- {
- return parse(dictionary, routingKey.tokenize(TOPIC_DELIMITTER));
- }
-
- private Collection<TopicMatcherResult> parse(final TopicWordDictionary dictionary,
- final AMQShortStringTokenizer tokens)
- {
- if(!tokens.hasMoreTokens())
- {
- return _results;
- }
- TopicWord word = dictionary.getWord(tokens.nextToken());
- TopicMatcherDFAState nextState = _nextStateMap.get(word);
- if(nextState == null && word != TopicWord.ANY_WORD)
- {
- nextState = _nextStateMap.get(TopicWord.ANY_WORD);
- }
- if(nextState == null)
- {
- return Collections.EMPTY_SET;
- }
- // Shortcut if we are at a looping terminal state
- if((nextState == this) && (_nextStateMap.size() == 1) && _nextStateMap.containsKey(TopicWord.ANY_WORD))
- {
- return _results;
- }
-
- return nextState.parse(dictionary, tokens);
-
- }
-
-
- public TopicMatcherDFAState mergeStateMachines(TopicMatcherDFAState otherStateMachine)
- {
- Map<Set<TopicMatcherDFAState>, TopicMatcherDFAState> newStateMap= new HashMap<Set<TopicMatcherDFAState>, TopicMatcherDFAState>();
-
- Collection<TopicMatcherResult> results;
-
- if(_results.isEmpty())
- {
- results = otherStateMachine._results;
- }
- else if(otherStateMachine._results.isEmpty())
- {
- results = _results;
- }
- else
- {
- results = new HashSet<TopicMatcherResult>(_results);
- results.addAll(otherStateMachine._results);
- }
-
-
- final Map<TopicWord, TopicMatcherDFAState> newNextStateMap = new HashMap<TopicWord, TopicMatcherDFAState>();
-
- TopicMatcherDFAState newState = new TopicMatcherDFAState(newNextStateMap, results);
-
-
- Set<TopicMatcherDFAState> oldStates = new HashSet<TopicMatcherDFAState>();
- oldStates.add(this);
- oldStates.add(otherStateMachine);
-
- newStateMap.put(oldStates, newState);
-
- mergeStateMachines(oldStates, newNextStateMap, newStateMap);
-
- return newState;
-
- }
-
- private static void mergeStateMachines(
- final Set<TopicMatcherDFAState> oldStates,
- final Map<TopicWord, TopicMatcherDFAState> newNextStateMap,
- final Map<Set<TopicMatcherDFAState>, TopicMatcherDFAState> newStateMap)
- {
- Map<TopicWord, Set<TopicMatcherDFAState>> nfaMap = new HashMap<TopicWord, Set<TopicMatcherDFAState>>();
-
- for(TopicMatcherDFAState state : oldStates)
- {
- Map<TopicWord, TopicMatcherDFAState> map = state._nextStateMap;
- for(Map.Entry<TopicWord, TopicMatcherDFAState> entry : map.entrySet())
- {
- Set<TopicMatcherDFAState> states = nfaMap.get(entry.getKey());
- if(states == null)
- {
- states = new HashSet<TopicMatcherDFAState>();
- nfaMap.put(entry.getKey(), states);
- }
- states.add(entry.getValue());
- }
- }
-
- Set<TopicMatcherDFAState> anyWordStates = nfaMap.get(TopicWord.ANY_WORD);
-
- for(Map.Entry<TopicWord, Set<TopicMatcherDFAState>> transition : nfaMap.entrySet())
- {
- Set<TopicMatcherDFAState> destinations = transition.getValue();
-
- if(anyWordStates != null)
- {
- destinations.addAll(anyWordStates);
- }
-
- TopicMatcherDFAState nextState = newStateMap.get(destinations);
- if(nextState == null)
- {
-
- if(destinations.size() == 1)
- {
- nextState = destinations.iterator().next();
- newStateMap.put(destinations, nextState);
- }
- else
- {
- Collection<TopicMatcherResult> results;
-
- Set<Collection<TopicMatcherResult>> resultSets = new HashSet<Collection<TopicMatcherResult>>();
- for(TopicMatcherDFAState 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<TopicMatcherResult>();
- for(Collection<TopicMatcherResult> oldResult : resultSets)
- {
- results.addAll(oldResult);
- }
- }
-
- final Map<TopicWord, TopicMatcherDFAState> nextStateMap = new HashMap<TopicWord, TopicMatcherDFAState>();
-
- nextState = new TopicMatcherDFAState(nextStateMap, results);
- newStateMap.put(destinations, nextState);
-
- mergeStateMachines(
- destinations,
- nextStateMap,
- newStateMap);
-
-
- }
-
-
- }
- newNextStateMap.put(transition.getKey(),nextState);
- }
-
- // Remove redundant transitions where defined tokenWord has same action as ANY_WORD
- TopicMatcherDFAState anyWordState = newNextStateMap.get(TopicWord.ANY_WORD);
- if(anyWordState != null)
- {
- List<TopicWord> removeList = new ArrayList<TopicWord>();
- for(Map.Entry<TopicWord,TopicMatcherDFAState> entry : newNextStateMap.entrySet())
- {
- if(entry.getValue() == anyWordState && entry.getKey() != TopicWord.ANY_WORD)
- {
- removeList.add(entry.getKey());
- }
- }
- for(TopicWord removeKey : removeList)
- {
- newNextStateMap.remove(removeKey);
- }
- }
-
-
-
- }
-
-
- public String toString()
- {
- StringBuilder transitions = new StringBuilder();
- for(Map.Entry<TopicWord, TopicMatcherDFAState> entry : _nextStateMap.entrySet())
- {
- transitions.append("[ ");
- transitions.append(entry.getKey());
- transitions.append("\t ->\t ");
- transitions.append(entry.getValue()._id);
- transitions.append(" ]\n");
- }
-
-
- return "[ State " + _id + " ]\n" + transitions + "\n";
-
- }
-
- public String reachableStates()
- {
- StringBuilder result = new StringBuilder("Start state: " + _id + "\n");
-
- SortedSet<TopicMatcherDFAState> reachableStates =
- new TreeSet<TopicMatcherDFAState>(new Comparator<TopicMatcherDFAState>()
- {
- public int compare(final TopicMatcherDFAState o1, final TopicMatcherDFAState o2)
- {
- return o1._id - o2._id;
- }
- });
- reachableStates.add(this);
-
- int count;
-
- do
- {
- count = reachableStates.size();
- Collection<TopicMatcherDFAState> originalStates = new ArrayList<TopicMatcherDFAState>(reachableStates);
- for(TopicMatcherDFAState state : originalStates)
- {
- reachableStates.addAll(state._nextStateMap.values());
- }
- }
- while(reachableStates.size() != count);
-
-
-
- for(TopicMatcherDFAState state : reachableStates)
- {
- result.append(state.toString());
- }
-
- return result.toString();
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicMatcherResult.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicMatcherResult.java
deleted file mode 100644
index 71d30adfac..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicMatcherResult.java
+++ /dev/null
@@ -1,25 +0,0 @@
-package org.apache.qpid.server.exchange.topic;
-
-/*
-*
-* 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 interface TopicMatcherResult
-{
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicNormalizer.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicNormalizer.java
deleted file mode 100644
index 7e7cb6c0ae..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicNormalizer.java
+++ /dev/null
@@ -1,96 +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.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;
-
-public class TopicNormalizer
-{
- private static final byte TOPIC_SEPARATOR = (byte)'.';
- private static final byte HASH_BYTE = (byte)'#';
- private static final byte STAR_BYTE = (byte)'*';
-
- private static final AMQShortString TOPIC_SEPARATOR_AS_SHORTSTRING = new AMQShortString(".");
- private static final AMQShortString AMQP_STAR_TOKEN = new AMQShortString("*");
- private static final AMQShortString AMQP_HASH_TOKEN = new AMQShortString("#");
-
- public static AMQShortString normalize(AMQShortString routingKey)
- {
- if(routingKey == null)
- {
- return AMQShortString.EMPTY_STRING;
- }
- else if(!(routingKey.contains(HASH_BYTE) || routingKey.contains(STAR_BYTE)))
- {
- return routingKey;
- }
- else
- {
- AMQShortStringTokenizer routingTokens = routingKey.tokenize(TOPIC_SEPARATOR);
-
- List<AMQShortString> subscriptionList = new ArrayList<AMQShortString>();
-
- while (routingTokens.hasMoreTokens())
- {
- subscriptionList.add(routingTokens.nextToken());
- }
-
- int size = subscriptionList.size();
-
- for (int index = 0; index < size; index++)
- {
- // if there are more levels
- if ((index + 1) < size)
- {
- if (subscriptionList.get(index).equals(AMQP_HASH_TOKEN))
- {
- if (subscriptionList.get(index + 1).equals(AMQP_HASH_TOKEN))
- {
- // we don't need #.# delete this one
- subscriptionList.remove(index);
- size--;
- // redo this normalisation
- index--;
- }
-
- if (subscriptionList.get(index + 1).equals(AMQP_STAR_TOKEN))
- {
- // we don't want #.* swap to *.#
- // remove it and put it in at index + 1
- subscriptionList.add(index + 1, subscriptionList.remove(index));
- }
- }
- } // if we have more levels
- }
-
-
-
- AMQShortString normalizedString = AMQShortString.join(subscriptionList, TOPIC_SEPARATOR_AS_SHORTSTRING);
-
- return normalizedString;
- }
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicParser.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicParser.java
deleted file mode 100644
index 3e9facf412..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicParser.java
+++ /dev/null
@@ -1,613 +0,0 @@
-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.concurrent.atomic.AtomicReference;
-import java.io.IOException;
-
-/*
-*
-* 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 TopicParser
-{
- private static final byte TOPIC_DELIMITER = (byte)'.';
-
- private final TopicWordDictionary _dictionary = new TopicWordDictionary();
- private final AtomicReference<TopicMatcherDFAState> _stateMachine = new AtomicReference<TopicMatcherDFAState>();
-
- private static class Position
- {
- private final TopicWord _word;
- private final boolean _selfTransition;
- private final int _position;
- private final boolean _endState;
- private boolean _followedByAnyLoop;
-
-
- public Position(final int position, final TopicWord word, final boolean selfTransition, final boolean endState)
- {
- _position = position;
- _word = word;
- _selfTransition = selfTransition;
- _endState = endState;
- }
-
-
- }
-
- private static final Position ERROR_POSITION = new Position(Integer.MAX_VALUE,null, true, false);
-
- private static class SimpleState
- {
- Set<Position> _positions;
- Map<TopicWord, SimpleState> _nextState;
- }
-
-
- public void addBinding(AMQShortString bindingKey, TopicMatcherResult result)
- {
-
- TopicMatcherDFAState startingStateMachine;
- TopicMatcherDFAState newStateMachine;
-
- do
- {
- startingStateMachine = _stateMachine.get();
- if(startingStateMachine == null)
- {
- newStateMachine = createStateMachine(bindingKey, result);
- }
- else
- {
- newStateMachine = startingStateMachine.mergeStateMachines(createStateMachine(bindingKey, result));
- }
-
- }
- while(!_stateMachine.compareAndSet(startingStateMachine,newStateMachine));
-
- }
-
- public Collection<TopicMatcherResult> parse(AMQShortString routingKey)
- {
- TopicMatcherDFAState stateMachine = _stateMachine.get();
- if(stateMachine == null)
- {
- return Collections.EMPTY_SET;
- }
- else
- {
- return stateMachine.parse(_dictionary,routingKey);
- }
- }
-
-
- TopicMatcherDFAState createStateMachine(AMQShortString bindingKey, TopicMatcherResult result)
- {
- List<TopicWord> wordList = createTopicWordList(bindingKey);
- int wildCards = 0;
- for(TopicWord word : wordList)
- {
- if(word == TopicWord.WILDCARD_WORD)
- {
- wildCards++;
- }
- }
- if(wildCards == 0)
- {
- TopicMatcherDFAState[] states = new TopicMatcherDFAState[wordList.size()+1];
- states[states.length-1] = new TopicMatcherDFAState(Collections.EMPTY_MAP, Collections.singleton(result));
- for(int i = states.length-2; i >= 0; i--)
- {
- states[i] = new TopicMatcherDFAState(Collections.singletonMap(wordList.get(i),states[i+1]),Collections.EMPTY_SET);
-
- }
- return states[0];
- }
- else if(wildCards == wordList.size())
- {
- Map<TopicWord,TopicMatcherDFAState> stateMap = new HashMap<TopicWord,TopicMatcherDFAState>();
- TopicMatcherDFAState state = new TopicMatcherDFAState(stateMap, Collections.singleton(result));
- stateMap.put(TopicWord.ANY_WORD, state);
- return state;
- }
-
-
- int positionCount = wordList.size() - wildCards;
-
- Position[] positions = new Position[positionCount+1];
-
- int lastWord;
-
- if(wordList.get(wordList.size()-1)== TopicWord.WILDCARD_WORD)
- {
- lastWord = wordList.size()-1;
- positions[positionCount] = new Position(positionCount, TopicWord.ANY_WORD, true, true);
- }
- else
- {
- lastWord = wordList.size();
- positions[positionCount] = new Position(positionCount, TopicWord.ANY_WORD, false, true);
- }
-
-
- int pos = 0;
- int wordPos = 0;
-
-
- while(wordPos < lastWord)
- {
- TopicWord word = wordList.get(wordPos++);
-
- if(word == TopicWord.WILDCARD_WORD)
- {
- int nextWordPos = wordPos++;
- word = wordList.get(nextWordPos);
-
- positions[pos] = new Position(pos++,word,true,false);
- }
- else
- {
- positions[pos] = new Position(pos++,word,false,false);
- }
-
- }
-
-
- for(int p = 0; p<positionCount; p++)
- {
- boolean followedByWildcards = true;
-
- int n = p;
- while(followedByWildcards && n<(positionCount+1))
- {
-
- if(positions[n]._selfTransition)
- {
- break;
- }
- else if(positions[n]._word!=TopicWord.ANY_WORD)
- {
- followedByWildcards = false;
- }
- n++;
- }
-
-
- positions[p]._followedByAnyLoop = followedByWildcards && (n!= positionCount+1);
- }
-
-
- // from each position you transition to a set of other positions.
- // we approach this by examining steps of increasing length - so we
- // look how far we can go from the start position in 1 word, 2 words, etc...
-
- Map<Set<Position>,SimpleState> stateMap = new HashMap<Set<Position>,SimpleState>();
-
-
- SimpleState state = new SimpleState();
- state._positions = Collections.singleton( positions[0] );
- stateMap.put(state._positions, state);
-
- calculateNextStates(state, stateMap, positions);
-
- SimpleState[] simpleStates = stateMap.values().toArray(new SimpleState[stateMap.size()]);
- HashMap<TopicWord, TopicMatcherDFAState>[] dfaStateMaps = new HashMap[simpleStates.length];
- Map<SimpleState, TopicMatcherDFAState> simple2DFAMap = new HashMap<SimpleState, TopicMatcherDFAState>();
-
- for(int i = 0; i < simpleStates.length; i++)
- {
-
- Collection<TopicMatcherResult> results;
- boolean endState = false;
-
- for(Position p : simpleStates[i]._positions)
- {
- if(p._endState)
- {
- endState = true;
- break;
- }
- }
-
- if(endState)
- {
- results = Collections.singleton(result);
- }
- else
- {
- results = Collections.EMPTY_SET;
- }
-
- dfaStateMaps[i] = new HashMap<TopicWord, TopicMatcherDFAState>();
- simple2DFAMap.put(simpleStates[i], new TopicMatcherDFAState(dfaStateMaps[i],results));
-
- }
- for(int i = 0; i < simpleStates.length; i++)
- {
- SimpleState simpleState = simpleStates[i];
-
- Map<TopicWord, SimpleState> nextSimpleStateMap = simpleState._nextState;
- for(Map.Entry<TopicWord, SimpleState> stateMapEntry : nextSimpleStateMap.entrySet())
- {
- dfaStateMaps[i].put(stateMapEntry.getKey(), simple2DFAMap.get(stateMapEntry.getValue()));
- }
-
- }
-
- return simple2DFAMap.get(state);
-
- }
-
-
-
- private void calculateNextStates(final SimpleState state,
- final Map<Set<Position>, SimpleState> stateMap,
- final Position[] positions)
- {
- Map<TopicWord, Set<Position>> transitions = new HashMap<TopicWord,Set<Position>>();
-
- for(Position pos : state._positions)
- {
- if(pos._selfTransition)
- {
- Set<Position> dest = transitions.get(TopicWord.ANY_WORD);
- if(dest == null)
- {
- dest = new HashSet<Position>();
- transitions.put(TopicWord.ANY_WORD,dest);
- }
- dest.add(pos);
- }
-
- final int nextPos = pos._position + 1;
- Position nextPosition = nextPos == positions.length ? ERROR_POSITION : positions[nextPos];
-
- Set<Position> dest = transitions.get(pos._word);
- if(dest == null)
- {
- dest = new HashSet<Position>();
- transitions.put(pos._word,dest);
- }
- dest.add(nextPosition);
-
- }
-
- Set<Position> anyWordTransitions = transitions.get(TopicWord.ANY_WORD);
- if(anyWordTransitions != null)
- {
- for(Set<Position> dest : transitions.values())
- {
- dest.addAll(anyWordTransitions);
- }
- }
-
- state._nextState = new HashMap<TopicWord, SimpleState>();
-
- for(Map.Entry<TopicWord,Set<Position>> dest : transitions.entrySet())
- {
-
- if(dest.getValue().size()>1)
- {
- dest.getValue().remove(ERROR_POSITION);
- }
- Position loopingTerminal = null;
- for(Position destPos : dest.getValue())
- {
- if(destPos._selfTransition && destPos._endState)
- {
- loopingTerminal = destPos;
- break;
- }
- }
-
- if(loopingTerminal!=null)
- {
- dest.setValue(Collections.singleton(loopingTerminal));
- }
- else
- {
- Position anyLoop = null;
- for(Position destPos : dest.getValue())
- {
- if(destPos._followedByAnyLoop)
- {
- if(anyLoop == null || anyLoop._position<destPos._position)
- {
- anyLoop = destPos;
- }
- }
- }
- if(anyLoop != null)
- {
- Collection<Position> removals = new ArrayList<Position>();
- for(Position destPos : dest.getValue())
- {
- if(destPos._position < anyLoop._position)
- {
- removals.add(destPos);
- }
- }
- dest.getValue().removeAll(removals);
- }
- }
-
- SimpleState stateForEntry = stateMap.get(dest.getValue());
- if(stateForEntry == null)
- {
- stateForEntry = new SimpleState();
- stateForEntry._positions = dest.getValue();
- stateMap.put(dest.getValue(),stateForEntry);
- calculateNextStates(stateForEntry,
- stateMap,
- positions);
- }
- state._nextState.put(dest.getKey(),stateForEntry);
-
-
-
- }
-
- // remove redundant transitions
- SimpleState anyWordState = state._nextState.get(TopicWord.ANY_WORD);
- if(anyWordState != null)
- {
- List<TopicWord> removeList = new ArrayList<TopicWord>();
- for(Map.Entry<TopicWord,SimpleState> entry : state._nextState.entrySet())
- {
- if(entry.getValue() == anyWordState && entry.getKey() != TopicWord.ANY_WORD)
- {
- removeList.add(entry.getKey());
- }
- }
- for(TopicWord removeKey : removeList)
- {
- state._nextState.remove(removeKey);
- }
- }
-
-
- }
-
- private List<TopicWord> createTopicWordList(final AMQShortString bindingKey)
- {
- AMQShortStringTokenizer tokens = bindingKey.tokenize(TOPIC_DELIMITER);
- TopicWord previousWord = null;
-
- List<TopicWord> wordList = new ArrayList<TopicWord>();
-
- while(tokens.hasMoreTokens())
- {
- TopicWord nextWord = _dictionary.getOrCreateWord(tokens.nextToken());
- if(previousWord == TopicWord.WILDCARD_WORD)
- {
-
- if(nextWord == TopicWord.WILDCARD_WORD)
- {
- // consecutive wildcards can be merged
- // i.e. subsequent wildcards can be discarded
- continue;
- }
- else if(nextWord == TopicWord.ANY_WORD)
- {
- // wildcard and anyword can be reordered to always put anyword first
- wordList.set(wordList.size()-1,TopicWord.ANY_WORD);
- nextWord = TopicWord.WILDCARD_WORD;
- }
- }
- wordList.add(nextWord);
- previousWord = nextWord;
-
- }
- return wordList;
- }
-
-
- 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<TopicMatcherResult, String> resultMap = new HashMap<TopicMatcherResult, String>();
-
- 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<TopicMatcherResult> results = sm.parse(parser._dictionary, routingKeyShortString);
- Collection<String> resultStrings = new ArrayList<String>();
-
- for(TopicMatcherResult result : results)
- {
- resultStrings.add(resultMap.get(result));
- }
-
- final ArrayList<String> nonMatches = new ArrayList<String>(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/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicWord.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicWord.java
deleted file mode 100644
index f14d70f8a1..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicWord.java
+++ /dev/null
@@ -1,54 +0,0 @@
-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
-* 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 final class TopicWord
-{
- public static final TopicWord ANY_WORD = new TopicWord("*");
- public static final TopicWord WILDCARD_WORD = new TopicWord("#");
- private String _word;
-
- public TopicWord()
- {
-
- }
-
- public TopicWord(String s)
- {
- _word = s;
- }
-
- public TopicWord(final AMQShortString name)
- {
- _word = name.toString();
- }
-
- public String toString()
- {
- return _word;
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicWordDictionary.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicWordDictionary.java
deleted file mode 100644
index 65a0cd3107..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicWordDictionary.java
+++ /dev/null
@@ -1,63 +0,0 @@
-package org.apache.qpid.server.exchange.topic;
-
-import org.apache.qpid.framing.AMQShortString;
-
-import java.util.concurrent.ConcurrentHashMap;
-
-/*
-*
-* 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 TopicWordDictionary
-{
- private final ConcurrentHashMap<AMQShortString,TopicWord> _dictionary =
- new ConcurrentHashMap<AMQShortString,TopicWord>();
-
-
-
- public TopicWordDictionary()
- {
- _dictionary.put(new AMQShortString("*"), TopicWord.ANY_WORD);
- _dictionary.put(new AMQShortString("#"), TopicWord.WILDCARD_WORD);
- }
-
-
-
-
- public TopicWord getOrCreateWord(AMQShortString name)
- {
- TopicWord word = _dictionary.putIfAbsent(name, new TopicWord(name));
- if(word == null)
- {
- word = _dictionary.get(name);
- }
- return word;
- }
-
-
- public TopicWord getWord(AMQShortString name)
- {
- TopicWord word = _dictionary.get(name);
- if(word == null)
- {
- word = TopicWord.ANY_WORD;
- }
- return word;
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/federation/Bridge.java b/java/broker/src/main/java/org/apache/qpid/server/federation/Bridge.java
deleted file mode 100644
index fbc5387daf..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/federation/Bridge.java
+++ /dev/null
@@ -1,823 +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.federation;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.server.binding.Binding;
-import org.apache.qpid.server.configuration.BridgeConfig;
-import org.apache.qpid.server.configuration.BridgeConfigType;
-import org.apache.qpid.server.configuration.ConfiguredObject;
-import org.apache.qpid.server.exchange.Exchange;
-import org.apache.qpid.server.exchange.ExchangeRegistry;
-import org.apache.qpid.server.flow.FlowCreditManager_0_10;
-import org.apache.qpid.server.flow.WindowCreditManager;
-import org.apache.qpid.server.message.MessageMetaData_0_10;
-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.BaseQueue;
-import org.apache.qpid.server.queue.QueueRegistry;
-import org.apache.qpid.server.store.MessageStore;
-import org.apache.qpid.server.store.StoredMessage;
-import org.apache.qpid.server.subscription.Subscription_0_10;
-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.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.Session;
-import org.apache.qpid.transport.SessionException;
-import org.apache.qpid.transport.SessionListener;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.UUID;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-
-public class Bridge implements BridgeConfig
-{
- private final boolean _durable;
- private final boolean _dynamic;
- private final boolean _queueBridge;
- private final boolean _localSource;
- private final String _source;
- private final String _destination;
- private final String _key;
- private final String _tag;
- private final String _excludes;
- private final BrokerLink _link;
- private UUID _id;
- private long _createTime = System.currentTimeMillis();
-
- private Session _session;
-
- private BridgeImpl _delegate;
-
- private final int _bridgeNo;
- private AutoCommitTransaction _transaction;
-
- public Bridge(final BrokerLink brokerLink,
- final int bridgeNo,
- final boolean durable,
- final boolean dynamic,
- final boolean srcIsQueue,
- final boolean srcIsLocal,
- final String src,
- final String dest,
- final String key,
- final String tag,
- final String excludes)
- {
- _link = brokerLink;
- _bridgeNo = bridgeNo;
- _durable = durable;
- _dynamic = dynamic;
- _queueBridge = srcIsQueue;
- _localSource = srcIsLocal;
- _source = src;
- _destination = dest;
- _key = key;
- _tag = tag;
- _excludes = excludes;
- _id = brokerLink.getConfigStore().createId();
-
- _transaction = new AutoCommitTransaction(getVirtualHost().getMessageStore());
-
- if(dynamic)
- {
- if(srcIsLocal)
- {
- // TODO
- }
- else
- {
- if(srcIsQueue)
- {
- // TODO
- }
- else
- {
- _delegate = new DynamicExchangeBridge();
- }
- }
- }
- else
- {
- if(srcIsLocal)
- {
- if(srcIsQueue)
- {
- _delegate = new StaticQueuePushBridge();
- }
- else
- {
- _delegate = new StaticExchangePushBridge();
- }
- }
- else
- {
- if(srcIsQueue)
- {
- _delegate = new StaticQueuePullBridge();
- }
- else
- {
- _delegate = new StaticExchangePullBridge();
- }
- }
- }
- }
-
- public UUID getId()
- {
- return _id;
- }
-
- public BridgeConfigType getConfigType()
- {
- return BridgeConfigType.getInstance();
- }
-
- public ConfiguredObject getParent()
- {
- return getLink();
- }
-
- public boolean isDurable()
- {
- return _durable;
- }
-
- public boolean isDynamic()
- {
- return _dynamic;
- }
-
- public boolean isQueueBridge()
- {
- return _queueBridge;
- }
-
- public boolean isLocalSource()
- {
- return _localSource;
- }
-
- public String getSource()
- {
- return _source;
- }
-
- public String getDestination()
- {
- return _destination;
- }
-
- public String getKey()
- {
- return _key;
- }
-
- public String getTag()
- {
- return _tag;
- }
-
- public String getExcludes()
- {
- return _excludes;
- }
-
- public BrokerLink getLink()
- {
- return _link;
- }
-
- public Integer getChannelId()
- {
- return (_session == null) ? 0 : _session.getChannel();
- }
-
- public int getAckBatching()
- {
- return 0;
- }
-
- public long getCreateTime()
- {
- return _createTime;
- }
-
- @Override
- public boolean equals(final Object o)
- {
- if (this == o)
- {
- return true;
- }
- if (o == null || getClass() != o.getClass())
- {
- return false;
- }
-
- final Bridge bridge = (Bridge) o;
-
- if (_durable != bridge._durable)
- {
- return false;
- }
- if (_dynamic != bridge._dynamic)
- {
- return false;
- }
- if (_localSource != bridge._localSource)
- {
- return false;
- }
- if (_queueBridge != bridge._queueBridge)
- {
- return false;
- }
- if (_destination != null ? !_destination.equals(bridge._destination) : bridge._destination != null)
- {
- return false;
- }
- if (_excludes != null ? !_excludes.equals(bridge._excludes) : bridge._excludes != null)
- {
- return false;
- }
- if (_key != null ? !_key.equals(bridge._key) : bridge._key != null)
- {
- return false;
- }
- if (_source != null ? !_source.equals(bridge._source) : bridge._source != null)
- {
- return false;
- }
- if (_tag != null ? !_tag.equals(bridge._tag) : bridge._tag != null)
- {
- return false;
- }
-
- return true;
- }
-
- @Override
- public int hashCode()
- {
- int result = (_durable ? 1 : 0);
- result = 31 * result + (_dynamic ? 1 : 0);
- result = 31 * result + (_queueBridge ? 1 : 0);
- result = 31 * result + (_localSource ? 1 : 0);
- result = 31 * result + (_source != null ? _source.hashCode() : 0);
- result = 31 * result + (_destination != null ? _destination.hashCode() : 0);
- result = 31 * result + (_key != null ? _key.hashCode() : 0);
- result = 31 * result + (_tag != null ? _tag.hashCode() : 0);
- result = 31 * result + (_excludes != null ? _excludes.hashCode() : 0);
- return result;
- }
-
- public void setSession(final Session session)
- {
- _session = session;
- _delegate.setSession(session);
- }
-
- private long getMessageWindowSize()
- {
- return 10l;
- }
-
-
- VirtualHost getVirtualHost()
- {
- return _link.getVirtualHost();
- }
-
- public void close()
- {
- // TODO
- _delegate.close();
- _session = null;
- }
-
-
- private interface BridgeImpl
- {
- void setSession(Session session);
-
- void close();
- }
-
- private abstract class AbstractPullBridge implements BridgeImpl, SessionListener
- {
- public final void setSession(final Session session)
- {
- session.setSessionListener(this);
- onSession();
-
- }
-
- abstract void onSession();
-
-
-
- public void message(final Session ssn, final MessageTransfer xfr)
- {
- ExchangeRegistry exchangeRegistry = getVirtualHost().getExchangeRegistry();
-
- Exchange exchange = exchangeRegistry.getExchange(_destination);
-
- // TODO - deal with exchange not existing
-
- DeliveryProperties delvProps = null;
- if(xfr.getHeader() != null && (delvProps = xfr.getHeader().get(DeliveryProperties.class)) != null && delvProps.hasTtl() && !delvProps.hasExpiration())
- {
- delvProps.setExpiration(System.currentTimeMillis() + delvProps.getTtl());
- }
-
- MessageMetaData_0_10 messageMetaData = new MessageMetaData_0_10(xfr);
- final MessageStore store = getVirtualHost().getMessageStore();
- StoredMessage<MessageMetaData_0_10> storeMessage = store.addMessage(messageMetaData);
- storeMessage.addContent(0,xfr.getBody());
- storeMessage.flushToStore();
- MessageTransferMessage message = new MessageTransferMessage(storeMessage, ((ServerSession)_session).getReference());
-
- ArrayList<? extends BaseQueue> queues = exchange.route(message);
-
-
-
- if(queues != null && queues.size() != 0)
- {
- enqueue(message, queues);
- }
- else
- {
- if(delvProps == null || !delvProps.hasDiscardUnroutable() || !delvProps.getDiscardUnroutable())
- {
- if(xfr.getAcceptMode() == MessageAcceptMode.EXPLICIT)
- {
- RangeSet rejects = new RangeSet();
- rejects.add(xfr.getId());
- MessageReject reject = new MessageReject(rejects, MessageRejectCode.UNROUTABLE, "Unroutable");
- ssn.invoke(reject);
- }
- else
- {
- Exchange alternate = exchange.getAlternateExchange();
- if(alternate != null)
- {
- queues = alternate.route(message);
- if(queues != null && queues.size() != 0)
- {
- enqueue(message, queues);
- }
- else
- {
- //TODO - log the message discard
- }
- }
- else
- {
- //TODO - log the message discard
- }
-
-
- }
- }
-
-
- }
-
- ssn.processed(xfr);
-
- }
-
-
- private void enqueue(final ServerMessage message, final ArrayList<? extends BaseQueue> queues)
- {
- _transaction.enqueue(queues,message, new ServerTransaction.Action()
- {
-
- BaseQueue[] _queues = queues.toArray(new BaseQueue[queues.size()]);
-
- public void postCommit()
- {
- for(int i = 0; i < _queues.length; i++)
- {
- try
- {
- _queues[i].enqueue(message);
- }
- catch (AMQException e)
- {
- // TODO
-
- throw new RuntimeException(e);
- }
- }
- }
-
- public void onRollback()
- {
- // NO-OP
- }
- });
-
- }
-
- public void exception(final Session session, final SessionException exception)
- {
- // TODO - Handle exceptions
- }
-
- public void closed(final Session session)
- {
- // TODO - handle close
- }
-
- public void opened(final Session session)
- {
- // this method never called
- }
-
- public void resumed(final Session session)
- {
- // will never resume these sessions
- }
-
-
-
- }
-
- private final class StaticExchangePullBridge extends AbstractPullBridge
- {
- private final String _tmpQueueName = "bridge_queue_" + _bridgeNo + "_" + _link.getFederationTag();;
-
- public void onSession()
- {
-
- final HashMap<String, Object> options = new HashMap<String, Object>();
- options.put("qpid.trace.exclude", _link.getFederationTag());
- options.put("qpid.trace.id",_link.getRemoteFederationTag());
- _session.queueDeclare(_tmpQueueName,null, options, Option.AUTO_DELETE, Option.EXCLUSIVE);
- _session.sync();
- // todo check exception
- final Map<String,Object> bindingArgs = new HashMap<String,Object>();
- _session.exchangeBind(_tmpQueueName, _source, _key, bindingArgs);
- _session.sync();
- // todo check exception
-
- final Map<String,Object> subscribeOptions = Collections.EMPTY_MAP;
- final String subName = String.valueOf(_bridgeNo);
- _session.messageSubscribe(_tmpQueueName,
- subName,MessageAcceptMode.NONE,MessageAcquireMode.PRE_ACQUIRED,null,0l, subscribeOptions);
- _session.sync();
- // todo check exception
-
- _session.messageSetFlowMode(subName,MessageFlowMode.WINDOW);
- _session.messageFlow(subName, MessageCreditUnit.MESSAGE, getMessageWindowSize());
- _session.messageFlow(subName, MessageCreditUnit.BYTE, 0xFFFFFFFF);
-
- }
-
- public void close()
- {
- // TODO
- }
- }
-
- private final class StaticQueuePullBridge extends AbstractPullBridge
- {
-
- public void onSession()
- {
-
- final Map<String,Object> subscribeOptions = Collections.EMPTY_MAP;
- final String subName = String.valueOf(_bridgeNo);
- _session.messageSubscribe(_source,
- subName,MessageAcceptMode.NONE,MessageAcquireMode.PRE_ACQUIRED,null,0l, subscribeOptions);
- _session.sync();
- // todo check exception
-
- _session.messageSetFlowMode(subName,MessageFlowMode.WINDOW);
- _session.messageFlow(subName, MessageCreditUnit.MESSAGE, getMessageWindowSize());
- _session.messageFlow(subName, MessageCreditUnit.BYTE, 0xFFFFFFFF);
-
- }
-
- public void close()
- {
- // TODO
- }
- }
-
- private final class DynamicExchangeBridge extends AbstractPullBridge implements Exchange.BindingListener
- {
- private final String _tmpQueueName = "bridge_queue_" + _bridgeNo + "_" + _link.getFederationTag();
-
- private final ConcurrentMap<Binding,Binding> _bindings = new ConcurrentHashMap<Binding,Binding>();
-
-
- void onSession()
- {
-
-
- final HashMap<String, Object> options = new HashMap<String, Object>();
- options.put("qpid.trace.exclude", _link.getFederationTag());
- options.put("qpid.trace.id",_link.getRemoteFederationTag());
- _session.queueDeclare(_tmpQueueName,null, options, Option.AUTO_DELETE, Option.EXCLUSIVE);
- _session.sync();
- // todo - check exception
-
- final Map<String,Object> subscribeOptions = Collections.EMPTY_MAP;
- final String subName = String.valueOf(_bridgeNo);
- _session.messageSubscribe(_tmpQueueName,
- subName,MessageAcceptMode.NONE,MessageAcquireMode.PRE_ACQUIRED,null,0l, subscribeOptions);
- _session.sync();
- // todo check exception
- _session.messageSetFlowMode(subName,MessageFlowMode.WINDOW);
- _session.messageFlow(subName, MessageCreditUnit.MESSAGE, getMessageWindowSize());
- _session.messageFlow(subName, MessageCreditUnit.BYTE, 0xFFFFFFFF);
- _session.sync();
- // todo check exception
-
-
- ExchangeRegistry exchangeRegistry = getVirtualHost().getExchangeRegistry();
-
- Exchange exchange = exchangeRegistry.getExchange(_destination);
-
- // TODO - check null
-
- exchange.addBindingListener(this);
-
- Collection<Binding> bindings = exchange.getBindings();
- for(Binding binding : bindings)
- {
- propogateBinding(binding);
- }
-
- }
-
- private void propogateBinding(final Binding binding)
- {
- if(_bindings.putIfAbsent(binding,binding)== null)
- {
- Map<String,Object> arguments = new HashMap<String,Object>(binding.getArguments());
-
- if(arguments.get("qpid.fed.origin") == null)
- {
- arguments.put("qpid.fed.op","");
- arguments.put("qpid.fed.origin",_link.getFederationTag());
- arguments.put("qpid.fed.tags",_link.getFederationTag());
- }
- else
- {
- String tags = (String) arguments.get("qpid.fed.tags");
- if(tags == null)
- {
- tags = _link.getFederationTag();
- }
- else
- {
- if(Arrays.asList(tags.split(",")).contains(_link.getFederationTag()))
- {
- return;
- }
- tags += "," + _link.getFederationTag();
- }
- arguments.put("qpid.fed.tags", tags);
- }
-
- _session.exchangeBind(_tmpQueueName, _source, binding.getBindingKey(), arguments);
- _session.sync();
- // TODO - check exception?
-
- }
- }
-
- private void propogateBindingRemoval(final Binding binding)
- {
- if(_bindings.remove(binding) != null)
- {
- // TODO - this is wrong!!!!
- _session.exchangeUnbind(_tmpQueueName, _source, binding.getBindingKey());
- }
- }
-
-
- public void bindingAdded(final Exchange exchange, final Binding binding)
- {
- propogateBinding(binding);
- }
-
- public void bindingRemoved(final Exchange exchange, final Binding binding)
- {
- propogateBindingRemoval(binding);
- }
-
- public void close()
- {
- // TODO
- }
- }
-
- private class StaticExchangePushBridge implements BridgeImpl, SessionListener
- {
- private final String _tmpQueueName = "bridge_queue_" + _bridgeNo + "_" + _link.getFederationTag();
- private AMQQueue _queue;
-
- public void setSession(final Session session)
- {
- assert session instanceof ServerSession;
-
- session.setSessionListener(this);
-
- ExchangeRegistry exchangeRegistry = getVirtualHost().getExchangeRegistry();
-
- Exchange exchange = exchangeRegistry.getExchange(_source);
-
- // TODO - Check null
-
- final HashMap<String, Object> options = new HashMap<String, Object>();
- options.put("qpid.trace.exclude", _link.getFederationTag());
- options.put("qpid.trace.id",_link.getRemoteFederationTag());
-
- try
- {
- _queue = AMQQueueFactory.createAMQQueueImpl(_tmpQueueName,
- isDurable(),
- _link.getFederationTag(),
- false,
- false,
- getVirtualHost(),
- options);
- }
- catch (AMQException e)
- {
- // TODO
- throw new RuntimeException(e);
- }
-
- FlowCreditManager_0_10 creditManager = new WindowCreditManager(0xFFFFFFFF,getMessageWindowSize());
-
- //TODO Handle the passing of non-null Filters and Arguments here
-
- Subscription_0_10 sub = new Subscription_0_10((ServerSession)session,
- _destination,
- MessageAcceptMode.NONE,
- MessageAcquireMode.PRE_ACQUIRED,
- MessageFlowMode.WINDOW,
- creditManager, null,null);
-
- ((ServerSession)session).register(_destination, sub);
-
- try
- {
- _queue.registerSubscription(sub, true);
- getVirtualHost().getBindingFactory().addBinding(_key, _queue, exchange, Collections.<String, Object>emptyMap());
- }
- catch (AMQException e)
- {
- // TODO
- throw new RuntimeException(e);
- }
- }
-
- public void close()
- {
- // TODO
- }
-
- public void opened(final Session session)
- {
- // this method never called
- }
-
- public void resumed(final Session session)
- {
- // this session will never be resumed
- }
-
- public void message(final Session ssn, final MessageTransfer xfr)
- {
- // messages should not be sent ... should probably log error
- }
-
- public void exception(final Session session, final SessionException exception)
- {
- // TODO
- }
-
- public void closed(final Session session)
- {
- // TODO
- }
- }
-
- private class StaticQueuePushBridge implements BridgeImpl, SessionListener
- {
- private AMQQueue _queue;
-
- public void setSession(final Session session)
- {
- assert session instanceof ServerSession;
-
- session.setSessionListener(this);
-
- QueueRegistry queueRegistry = getVirtualHost().getQueueRegistry();
-
- _queue = queueRegistry.getQueue(_source);
-
- // TODO - null check
-
- FlowCreditManager_0_10 creditManager = new WindowCreditManager(0xFFFFFFFF,getMessageWindowSize());
-
- //TODO Handle the passing of non-null Filters and Arguments here
-
- Subscription_0_10 sub = new Subscription_0_10((ServerSession)session,
- _destination,
- MessageAcceptMode.NONE,
- MessageAcquireMode.PRE_ACQUIRED,
- MessageFlowMode.WINDOW,
- creditManager, null,null);
-
- ((ServerSession)session).register(_destination, sub);
-
- try
- {
- _queue.registerSubscription(sub, false);
- }
- catch (AMQException e)
- {
- // TODO
- throw new RuntimeException(e);
- }
-
- }
-
- public void close()
- {
- // TODO
- }
-
- public void opened(final Session session)
- {
- // never called
- }
-
- public void resumed(final Session session)
- {
- // session will not resume
- }
-
- public void message(final Session ssn, final MessageTransfer xfr)
- {
- // should never be called ... should probably log error
- }
-
- public void exception(final Session session, final SessionException exception)
- {
- // TODO
- }
-
- public void closed(final Session session)
- {
- // TODO
- }
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/federation/BrokerLink.java b/java/broker/src/main/java/org/apache/qpid/server/federation/BrokerLink.java
deleted file mode 100644
index fa2fb9ead1..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/federation/BrokerLink.java
+++ /dev/null
@@ -1,512 +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.federation;
-
-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.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.Binary;
-import org.apache.qpid.transport.Connection;
-import org.apache.qpid.transport.ConnectionException;
-import org.apache.qpid.transport.ConnectionListener;
-import org.apache.qpid.transport.Session;
-import org.apache.qpid.transport.SessionDelegate;
-import org.apache.qpid.transport.TransportException;
-
-import java.util.Map;
-import java.util.UUID;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentLinkedQueue;
-import java.util.concurrent.ScheduledThreadPoolExecutor;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.concurrent.atomic.AtomicReference;
-import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
-
-public class BrokerLink implements LinkConfig, ConnectionListener
-{
-
- private static final int CORE_POOL_SIZE = 4;
-
- private static final ScheduledThreadPoolExecutor _threadPool =
- new ScheduledThreadPoolExecutor(CORE_POOL_SIZE);
-
-
- private final String _transport;
- private final String _host;
- private final int _port;
- private final String _remoteVhost;
- private final boolean _durable;
- private final String _authMechanism;
- private final String _username;
- private final String _password;
- private final VirtualHost _virtualHost;
- private UUID _id;
- private AtomicBoolean _closing = new AtomicBoolean();
- private final long _createTime = System.currentTimeMillis();
- private Connection _qpidConnection;
- private AtomicReference<Thread> _executor = new AtomicReference<Thread>();
- private AtomicInteger _bridgeId = new AtomicInteger();
-
- private final ConcurrentHashMap<Bridge,Bridge> _bridges = new ConcurrentHashMap<Bridge,Bridge>();
- private final ConcurrentHashMap<Bridge,Bridge> _activeBridges = new ConcurrentHashMap<Bridge,Bridge>();
- private final ConcurrentLinkedQueue<Bridge> _pendingBridges = new ConcurrentLinkedQueue<Bridge>();
- private String _remoteFederationTag;
-
- private ConnectionConfig _connectionConfig;
- private ConnectionException _exception;
- private String _lastErrorMessage;
- private int _retryDelay = 1;
- private final Runnable _makeConnectionTask = new Runnable()
- {
- public void run()
- {
- doMakeConnection();
- }
- };;
- ;
-
- public static enum State
- {
- OPERATIONAL,
- DOWN,
- ESTABLISHING,
- DELETED
- }
-
-
- private volatile State _state = State.DOWN;
-
- private static final AtomicReferenceFieldUpdater<BrokerLink, State> _stateUpdater =
- AtomicReferenceFieldUpdater.newUpdater(BrokerLink.class, State.class, "_state");
-
- private class ConnectionConfigAdapter implements ConnectionConfig
- {
- private long _adapterCreateTime = System.currentTimeMillis();
- private UUID _id = BrokerLink.this.getConfigStore().createId();
-
- public VirtualHost getVirtualHost()
- {
- return BrokerLink.this.getVirtualHost();
- }
-
- public String getAddress()
- {
- return _host+":"+_port;
- }
-
- public Boolean isIncoming()
- {
- return false;
- }
-
- public Boolean isSystemConnection()
- {
- return true;
- }
-
- public Boolean isFederationLink()
- {
- return true;
- }
-
- public String getAuthId()
- {
- return _username;
- }
-
- public String getRemoteProcessName()
- {
- return null;
- }
-
- public Integer getRemotePID()
- {
- return null;
- }
-
- public Integer getRemoteParentPID()
- {
- return null;
- }
-
- public ConfigStore getConfigStore()
- {
- return getVirtualHost().getConfigStore();
- }
-
- public UUID getId()
- {
- return _id;
- }
-
- public ConnectionConfigType getConfigType()
- {
- return ConnectionConfigType.getInstance();
- }
-
- public ConfiguredObject getParent()
- {
- return getVirtualHost();
- }
-
- public boolean isDurable()
- {
- return false;
- }
-
- public long getCreateTime()
- {
- return _adapterCreateTime;
- }
-
- public Boolean isShadow()
- {
- return false;
- }
-
- public void mgmtClose()
- {
- _connectionConfig.mgmtClose();
- }
- }
-
- private class SessionFactory implements Connection.SessionFactory
- {
-
- public Session newSession(final Connection conn, final Binary name, final long expiry)
- {
- return new ServerSession(conn, new SessionDelegate(), name, expiry, _connectionConfig);
- }
- };
-
-
- public BrokerLink(final VirtualHost virtualHost,
- final String transport,
- final String host,
- final int port,
- final String remoteVhost,
- final boolean durable,
- final String authMechanism, final String username, final String password)
- {
- _virtualHost = virtualHost;
- _transport = transport;
- _host = host;
- _port = port;
- _remoteVhost = remoteVhost;
- _durable = durable;
- _authMechanism = authMechanism;
- _username = username;
- _password = password;
- _id = virtualHost.getConfigStore().createId();
- _qpidConnection = new Connection();
- _connectionConfig = new ConnectionConfigAdapter();
- _qpidConnection.addConnectionListener(this);
-
-
- makeConnection();
- }
-
- private final boolean updateState(State expected, State newState)
- {
- return _stateUpdater.compareAndSet(this,expected,newState);
- }
-
- private void makeConnection()
- {
- _threadPool.execute(_makeConnectionTask);
- }
-
-
-
- private void doMakeConnection()
- {
- if(updateState(State.DOWN, State.ESTABLISHING))
- {
- try
- {
- _qpidConnection.connect(_host, _port, _remoteVhost, _username, _password, "ssl".equals(_transport), _authMechanism);
-
- final Map<String,Object> serverProps = _qpidConnection.getServerProperties();
- _remoteFederationTag = (String) serverProps.get("qpid.federation_tag");
- if(_remoteFederationTag == null)
- {
- _remoteFederationTag = UUID.fromString(_transport+":"+_host+":"+_port).toString();
- }
- _qpidConnection.setSessionFactory(new SessionFactory());
- _qpidConnection.setAuthorizationID(_username == null ? "" : _username);
-
- updateState(State.ESTABLISHING, State.OPERATIONAL);
-
- _retryDelay = 1;
-
- for(Bridge bridge : _bridges.values())
- {
- if(_state != State.OPERATIONAL)
- {
- break;
- }
- addBridge(bridge);
- }
-
-
- }
- catch (TransportException e)
- {
- _lastErrorMessage = e.getMessage();
- if(_retryDelay < 60)
- {
- _retryDelay <<= 1;
- }
-
- updateState(State.ESTABLISHING, State.DOWN);
- _activeBridges.clear();
- scheduleConnectionRetry();
- }
- }
- }
-
- private void scheduleConnectionRetry()
- {
- if(_state != State.DELETED)
- {
- _threadPool.schedule(_makeConnectionTask, _retryDelay, TimeUnit.SECONDS);
- }
- }
-
- public VirtualHost getVirtualHost()
- {
- return _virtualHost;
- }
-
- public String getTransport()
- {
- return _transport;
- }
-
- public String getHost()
- {
- return _host;
- }
-
- public int getPort()
- {
- return _port;
- }
-
- public String getRemoteVhost()
- {
- return _remoteVhost;
- }
-
- public UUID getId()
- {
- return _id;
- }
-
- public LinkConfigType getConfigType()
- {
- return LinkConfigType.getInstance();
- }
-
- public ConfiguredObject getParent()
- {
- return getVirtualHost();
- }
-
- public boolean isDurable()
- {
- return _durable;
- }
-
- public String getAuthMechanism()
- {
- return _authMechanism;
- }
-
- public String getUsername()
- {
- return _username;
- }
-
- public String getPassword()
- {
- return _password;
- }
-
- @Override
- public boolean equals(final Object o)
- {
- if (this == o)
- {
- return true;
- }
- if (o == null || getClass() != o.getClass())
- {
- return false;
- }
-
- final BrokerLink that = (BrokerLink) o;
-
- if (_port != that._port)
- {
- return false;
- }
- if (_host != null ? !_host.equals(that._host) : that._host != null)
- {
- return false;
- }
- if (_remoteVhost != null ? !_remoteVhost.equals(that._remoteVhost) : that._remoteVhost != null)
- {
- return false;
- }
- if (_transport != null ? !_transport.equals(that._transport) : that._transport != null)
- {
- return false;
- }
-
- return true;
- }
-
- @Override
- public int hashCode()
- {
- int result = _transport != null ? _transport.hashCode() : 0;
- result = 31 * result + (_host != null ? _host.hashCode() : 0);
- result = 31 * result + _port;
- result = 31 * result + (_remoteVhost != null ? _remoteVhost.hashCode() : 0);
- return result;
- }
-
- public void close()
- {
- if(_closing.compareAndSet(false,true))
- {
- // TODO - close connection
- for(Bridge bridge : _bridges.values())
- {
- bridge.close();
- }
- _bridges.clear();
-
- _virtualHost.removeBrokerConnection(this);
- }
- }
-
- public long getCreateTime()
- {
- return _createTime;
- }
-
- public void createBridge(final boolean durable,
- final boolean dynamic,
- final boolean srcIsQueue,
- final boolean srcIsLocal,
- final String src,
- final String dest,
- final String key,
- final String tag,
- final String excludes)
- {
- if(!_closing.get())
- {
- Bridge bridge = new Bridge(this, _bridgeId.incrementAndGet(), durable,dynamic,srcIsQueue,srcIsLocal,src,dest,key,tag,excludes);
- if(_bridges.putIfAbsent(bridge, bridge) == null)
- {
-
- addBridge(bridge);
- }
- }
-
-
- }
-
- private void addBridge(final Bridge bridge)
- {
- getConfigStore().addConfiguredObject(bridge);
-
- if(_state == State.OPERATIONAL && (_activeBridges.putIfAbsent(bridge,bridge) == null))
- {
-
-
- Session session = _qpidConnection.createSession("Bridge("
- + (bridge.isDurable() ? "durable" : "transient")
- + "," + (bridge.isDynamic() ? "dynamic" : "static")
- + "," + (bridge.isQueueBridge() ? "queue" : "exchange")
- + "," + (bridge.isLocalSource() ? "local-src" : "remote-src")
- + ",[Source: '" + bridge.getSource() + "']"
- + ",[Destination: '" + bridge.getDestination() + "']"
- + ",[Key: '" + bridge.getKey() + "']"
- + ",[Tag: '" + bridge.getTag() + "']"
- + ".[Excludes: '" + bridge.getExcludes() + "'])");
- bridge.setSession(session);
-
-
- if(_closing.get())
- {
- bridge.close();
- }
- }
-
- }
-
- public void opened(final Connection connection)
- {
- // this method not called
- }
-
- public void exception(final Connection connection, final ConnectionException exception)
- {
- _exception = exception;
- _lastErrorMessage = exception.getMessage();
-
- }
-
- public void closed(final Connection connection)
- {
- State currentState = _state;
- if(currentState != State.DOWN && currentState != State.DELETED && updateState(currentState, State.DOWN))
- {
- scheduleConnectionRetry();
- }
- }
-
- public ConfigStore getConfigStore()
- {
- return getVirtualHost().getConfigStore();
- }
-
- public String getFederationTag()
- {
- return getVirtualHost().getFederationTag();
- }
-
- public String getRemoteFederationTag()
- {
- return _remoteFederationTag;
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/ArithmeticExpression.java b/java/broker/src/main/java/org/apache/qpid/server/filter/ArithmeticExpression.java
deleted file mode 100644
index 221d23ef0d..0000000000
--- a/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 <http://www.activemq.org/site/home.html>
-//
-
-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/java/broker/src/main/java/org/apache/qpid/server/filter/BinaryExpression.java b/java/broker/src/main/java/org/apache/qpid/server/filter/BinaryExpression.java
deleted file mode 100644
index 024257bea9..0000000000
--- a/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 <http://www.activemq.org/site/home.html>
-//
-
-/**
- * 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/java/broker/src/main/java/org/apache/qpid/server/filter/BooleanExpression.java b/java/broker/src/main/java/org/apache/qpid/server/filter/BooleanExpression.java
deleted file mode 100644
index 06e8664470..0000000000
--- a/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 <http://www.activemq.org/site/home.html>
-//
-
-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/java/broker/src/main/java/org/apache/qpid/server/filter/ComparisonExpression.java b/java/broker/src/main/java/org/apache/qpid/server/filter/ComparisonExpression.java
deleted file mode 100644
index aad9d41174..0000000000
--- a/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 <http://www.activemq.org/site/home.html>
-//
-
-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<Character> REGEXP_CONTROL_CHARS = new HashSet<Character>();
-
- 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/java/broker/src/main/java/org/apache/qpid/server/filter/ConstantExpression.java b/java/broker/src/main/java/org/apache/qpid/server/filter/ConstantExpression.java
deleted file mode 100644
index 5cc9ca8ef2..0000000000
--- a/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 <http://www.activemq.org/site/home.html>
-//
-
-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/java/broker/src/main/java/org/apache/qpid/server/filter/Expression.java b/java/broker/src/main/java/org/apache/qpid/server/filter/Expression.java
deleted file mode 100644
index 97e9915271..0000000000
--- a/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 <http://www.activemq.org/site/home.html>
-//
-
-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/java/broker/src/main/java/org/apache/qpid/server/filter/FilterManager.java b/java/broker/src/main/java/org/apache/qpid/server/filter/FilterManager.java
deleted file mode 100644
index b5e282038b..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/filter/FilterManager.java
+++ /dev/null
@@ -1,37 +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 <http://www.activemq.org/site/home.html>
-//
-
-import org.apache.qpid.server.queue.Filterable;
-
-public interface FilterManager
-{
- void add(MessageFilter filter);
-
- void remove(MessageFilter filter);
-
- boolean allAllow(Filterable msg);
-
- boolean hasFilters();
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/FilterManagerFactory.java b/java/broker/src/main/java/org/apache/qpid/server/filter/FilterManagerFactory.java
deleted file mode 100644
index dac517150a..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/filter/FilterManagerFactory.java
+++ /dev/null
@@ -1,75 +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 java.util.Map;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.common.AMQPFilterTypes;
-import org.apache.qpid.framing.FieldTable;
-import org.apache.log4j.Logger;
-
-
-public class FilterManagerFactory
-{
-
- private final static Logger _logger = Logger.getLogger(FilterManagerFactory.class);
-
- //fixme move to a common class so it can be refered to from client code.
-
- public static FilterManager createManager(FieldTable filters) throws AMQException
- {
- FilterManager manager = null;
-
- if (filters != null)
- {
-
-
-
- if(filters.containsKey(AMQPFilterTypes.JMS_SELECTOR.getValue()))
- {
- String selector = filters.getString(AMQPFilterTypes.JMS_SELECTOR.getValue());
-
- if (selector != null && !selector.equals(""))
- {
- manager = new SimpleFilterManager();
- manager.add(new JMSSelectorFilter(selector));
- }
-
- }
-
-
- }
- else
- {
- _logger.debug("No Filters found.");
- }
-
-
- return manager;
-
- }
-
- public static FilterManager createManager(Map<String,Object> map) throws AMQException
- {
- return createManager(FieldTable.convertToFieldTable(map));
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/JMSSelectorFilter.java b/java/broker/src/main/java/org/apache/qpid/server/filter/JMSSelectorFilter.java
deleted file mode 100644
index f32de03841..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/filter/JMSSelectorFilter.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.server.filter;
-
-import org.apache.log4j.Logger;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.AMQInvalidArgumentException;
-import org.apache.qpid.server.filter.jms.selector.SelectorParser;
-import org.apache.qpid.server.queue.Filterable;
-
-
-public class JMSSelectorFilter implements MessageFilter
-{
- private final static Logger _logger = org.apache.log4j.Logger.getLogger(JMSSelectorFilter.class);
-
- private String _selector;
- private BooleanExpression _matcher;
-
- public JMSSelectorFilter(String selector) throws AMQInvalidArgumentException
- {
- _selector = selector;
- _matcher = new SelectorParser().parse(selector);
- }
-
- public boolean matches(Filterable message)
- {
- boolean match = _matcher.matches(message);
- if(_logger.isDebugEnabled())
- {
- _logger.debug(message + " match(" + match + ") selector(" + System.identityHashCode(_selector) + "):" + _selector);
- }
- return match;
- }
-
- public String getSelector()
- {
- return _selector;
- }
-
- @Override
- public String toString()
- {
- return "JMSSelector("+_selector+")";
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/LogicExpression.java b/java/broker/src/main/java/org/apache/qpid/server/filter/LogicExpression.java
deleted file mode 100644
index fdba184da4..0000000000
--- a/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 <http://www.activemq.org/site/home.html>
-//
-
-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/java/broker/src/main/java/org/apache/qpid/server/filter/MessageFilter.java b/java/broker/src/main/java/org/apache/qpid/server/filter/MessageFilter.java
deleted file mode 100644
index f5416af09a..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/filter/MessageFilter.java
+++ /dev/null
@@ -1,28 +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.server.queue.Filterable;
-
-public interface MessageFilter
-{
- boolean matches(Filterable message);
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/NoConsumerFilter.java b/java/broker/src/main/java/org/apache/qpid/server/filter/NoConsumerFilter.java
deleted file mode 100644
index 65ddf19fc4..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/filter/NoConsumerFilter.java
+++ /dev/null
@@ -1,48 +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.log4j.Logger;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.server.queue.Filterable;
-
-public class NoConsumerFilter implements MessageFilter
-{
- private final static Logger _logger = org.apache.log4j.Logger.getLogger(NoConsumerFilter.class);
-
-
- public NoConsumerFilter() throws AMQException
- {
- _logger.info("Created NoConsumerFilter");
- }
-
- public boolean matches(Filterable message)
- {
- return true;
- }
-
- @Override
- public String toString()
- {
- return "NoConsumer";
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/PropertyExpression.java b/java/broker/src/main/java/org/apache/qpid/server/filter/PropertyExpression.java
deleted file mode 100644
index 11fdeae2b1..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/filter/PropertyExpression.java
+++ /dev/null
@@ -1,235 +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 <http://www.activemq.org/site/home.html>
-//
-
-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 final int NON_PERSISTENT = 1;
- private static final int PERSISTENT = 2;
- private static final int DEFAULT_PRIORITY = 4;
-
- private static final Logger _logger = org.apache.log4j.Logger.getLogger(PropertyExpression.class);
-
- private static final HashMap<String, Expression> JMS_PROPERTY_EXPRESSIONS = new HashMap<String, Expression>();
-
- {
- 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)
- {
- int mode = message.isPersistent() ? PERSISTENT : NON_PERSISTENT;
- if (_logger.isDebugEnabled())
- {
- _logger.debug("JMSDeliveryMode is :" + mode);
- }
-
- return mode;
- }
- }
-
- 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/java/broker/src/main/java/org/apache/qpid/server/filter/SimpleFilterManager.java b/java/broker/src/main/java/org/apache/qpid/server/filter/SimpleFilterManager.java
deleted file mode 100644
index c563569cb4..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/filter/SimpleFilterManager.java
+++ /dev/null
@@ -1,94 +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 java.util.concurrent.ConcurrentLinkedQueue;
-
-import org.apache.log4j.Logger;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.server.queue.Filterable;
-
-public class SimpleFilterManager implements FilterManager
-{
- private final Logger _logger = Logger.getLogger(SimpleFilterManager.class);
-
- private final ConcurrentLinkedQueue<MessageFilter> _filters;
- private String _toString = "";
-
- public SimpleFilterManager()
- {
- _logger.debug("Creating SimpleFilterManager");
- _filters = new ConcurrentLinkedQueue<MessageFilter>();
- }
-
- public void add(MessageFilter filter)
- {
- _filters.add(filter);
- updateStringValue();
- }
-
- public void remove(MessageFilter filter)
- {
- _filters.remove(filter);
- updateStringValue();
- }
-
- public boolean allAllow(Filterable msg)
- {
- for (MessageFilter filter : _filters)
- {
- if (!filter.matches(msg))
- {
- return false;
- }
- }
- return true;
- }
-
- public boolean hasFilters()
- {
- return !_filters.isEmpty();
- }
-
-
- @Override
- public String toString()
- {
- return _toString;
- }
-
- private void updateStringValue()
- {
- StringBuilder toString = new StringBuilder();
- for (MessageFilter filter : _filters)
- {
- toString.append(filter.toString());
- toString.append(",");
- }
-
- if (_filters.size() > 0)
- {
- //Remove the last ','
- toString.deleteCharAt(toString.length()-1);
- }
- _toString = toString.toString();
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/UnaryExpression.java b/java/broker/src/main/java/org/apache/qpid/server/filter/UnaryExpression.java
deleted file mode 100644
index 557af95001..0000000000
--- a/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 <http://www.activemq.org/site/home.html>
-//
-
-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<E extends Exception> 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<E extends Exception> 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/java/broker/src/main/java/org/apache/qpid/server/filter/XPathExpression.java b/java/broker/src/main/java/org/apache/qpid/server/filter/XPathExpression.java
deleted file mode 100644
index aa35cb5a76..0000000000
--- a/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 <http://www.activemq.org/site/home.html>
-//
-
-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/java/broker/src/main/java/org/apache/qpid/server/filter/XQueryExpression.java b/java/broker/src/main/java/org/apache/qpid/server/filter/XQueryExpression.java
deleted file mode 100644
index ae22f17413..0000000000
--- a/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 <http://www.activemq.org/site/home.html>
-//
-
-/**
- * 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/java/broker/src/main/java/org/apache/qpid/server/filter/XalanXPathEvaluator.java b/java/broker/src/main/java/org/apache/qpid/server/filter/XalanXPathEvaluator.java
deleted file mode 100644
index f83eb63ac5..0000000000
--- a/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 <http://www.activemq.org/site/home.html>
-//
-
-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/java/broker/src/main/java/org/apache/qpid/server/flow/AbstractFlowCreditManager.java b/java/broker/src/main/java/org/apache/qpid/server/flow/AbstractFlowCreditManager.java
deleted file mode 100644
index cfe5aedd61..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/flow/AbstractFlowCreditManager.java
+++ /dev/null
@@ -1,71 +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.flow;
-
-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 Set<FlowCreditManagerListener> _listeners = new HashSet<FlowCreditManagerListener>();
-
- public final void addStateListener(FlowCreditManagerListener listener)
- {
- synchronized(_listeners)
- {
- _listeners.add(listener);
- }
- }
-
- public final boolean removeListener(FlowCreditManagerListener listener)
- {
- synchronized(_listeners)
- {
- return _listeners.remove(listener);
- }
- }
-
- private void notifyListeners(final boolean suspended)
- {
- synchronized(_listeners)
- {
- for(FlowCreditManagerListener listener : _listeners)
- {
- listener.creditStateChanged(!suspended);
- }
- }
- }
-
- protected final void setSuspended(final boolean suspended)
- {
- if(_suspended.compareAndSet(!suspended, suspended))
- {
- notifyListeners(suspended);
- }
- }
-
- protected final void notifyIncreaseBytesCredit()
- {
- notifyListeners(false);
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/flow/BytesOnlyCreditManager.java b/java/broker/src/main/java/org/apache/qpid/server/flow/BytesOnlyCreditManager.java
deleted file mode 100644
index c5f2d1e808..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/flow/BytesOnlyCreditManager.java
+++ /dev/null
@@ -1,89 +0,0 @@
-package org.apache.qpid.server.flow;
-
-import org.apache.qpid.server.message.ServerMessage;
-
-import java.util.concurrent.atomic.AtomicLong;
-
-/*
-*
-* 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 BytesOnlyCreditManager extends AbstractFlowCreditManager
-{
- private final AtomicLong _bytesCredit;
-
- public BytesOnlyCreditManager(long initialCredit)
- {
- _bytesCredit = new AtomicLong(initialCredit);
- }
-
- public long getMessageCredit()
- {
- return -1L;
- }
-
- public long getBytesCredit()
- {
- return _bytesCredit.get();
- }
-
- public void restoreCredit(long messageCredit, long bytesCredit)
- {
- _bytesCredit.addAndGet(bytesCredit);
- setSuspended(false);
- }
-
- public void removeAllCredit()
- {
- _bytesCredit.set(0L);
- }
-
- public boolean hasCredit()
- {
- return _bytesCredit.get() > 0L;
- }
-
- public boolean useCreditForMessage(ServerMessage msg)
- {
- final long msgSize = msg.getSize();
- if(hasCredit())
- {
- if(_bytesCredit.addAndGet(-msgSize) >= 0)
- {
- return true;
- }
- else
- {
- _bytesCredit.addAndGet(msgSize);
- setSuspended(true);
- return false;
- }
- }
- else
- {
- return false;
- }
-
- }
-
- public void setBytesCredit(long bytesCredit)
- {
- _bytesCredit.set( bytesCredit );
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/flow/CreditCreditManager.java b/java/broker/src/main/java/org/apache/qpid/server/flow/CreditCreditManager.java
deleted file mode 100644
index b47f986155..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/flow/CreditCreditManager.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.server.flow;
-
-import org.apache.qpid.server.message.ServerMessage;
-
-public class CreditCreditManager extends AbstractFlowCreditManager implements FlowCreditManager_0_10
-{
- private volatile long _bytesCredit;
- private volatile long _messageCredit;
-
-
- public CreditCreditManager()
- {
- this(0L, 0L);
- }
-
- public CreditCreditManager(long bytesCredit, long messageCredit)
- {
- _bytesCredit = bytesCredit;
- _messageCredit = messageCredit;
- setSuspended(!hasCredit());
-
- }
-
-
- public synchronized void setCreditLimits(final long bytesCredit, final long messageCredit)
- {
- _bytesCredit = bytesCredit;
- _messageCredit = messageCredit;
-
- setSuspended(!hasCredit());
-
- }
-
-
- public long getMessageCredit()
- {
- return _messageCredit == -1L
- ? Long.MAX_VALUE
- : _messageCredit;
- }
-
- public long getBytesCredit()
- {
- return _bytesCredit == -1L
- ? Long.MAX_VALUE
- : _bytesCredit;
- }
-
- public synchronized void restoreCredit(final long messageCredit, final long bytesCredit)
- {
- /*_bytesCredit = 0l;
- _messageCredit = 0l;
- setSuspended(true);*/
- }
-
-
- public synchronized void addCredit(final long messageCredit, final long bytesCredit)
- {
- boolean notifyIncrease = true;
- if(_messageCredit >= 0L && messageCredit > 0L)
- {
- notifyIncrease = _messageCredit != 0L;
- _messageCredit += messageCredit;
- }
-
-
-
- if(_bytesCredit >= 0L && bytesCredit > 0L)
- {
- notifyIncrease = notifyIncrease && bytesCredit>0;
- _bytesCredit += bytesCredit;
-
-
-
- if(notifyIncrease)
- {
- notifyIncreaseBytesCredit();
- }
- }
-
-
-
- setSuspended(!hasCredit());
-
- }
-
- public void clearCredit()
- {
- _bytesCredit = 0l;
- _messageCredit = 0l;
- setSuspended(true);
- }
-
-
- public synchronized boolean hasCredit()
- {
- // Note !=, if credit is < 0 that indicates infinite credit
- return (_bytesCredit != 0L && _messageCredit != 0L);
- }
-
- public synchronized boolean useCreditForMessage(final ServerMessage msg)
- {
- if(_messageCredit >= 0L)
- {
- if(_messageCredit > 0)
- {
- if(_bytesCredit < 0L)
- {
- _messageCredit--;
-
- return true;
- }
- else if(msg.getSize() <= _bytesCredit)
- {
- _messageCredit--;
- _bytesCredit -= msg.getSize();
-
- return true;
- }
- else
- {
- //setSuspended(true);
- return false;
- }
- }
- else
- {
- setSuspended(true);
- return false;
- }
- }
- else if(_bytesCredit >= 0L)
- {
- if(msg.getSize() <= _bytesCredit)
- {
- _bytesCredit -= msg.getSize();
-
- return true;
- }
- else
- {
- //setSuspended(true);
- return false;
- }
-
- }
- else
- {
- return true;
- }
-
- }
-
- public synchronized void stop()
- {
- if(_bytesCredit > 0)
- {
- _bytesCredit = 0;
- }
- if(_messageCredit > 0)
- {
- _messageCredit = 0;
- }
-
- }
-
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/flow/FlowCreditManager.java b/java/broker/src/main/java/org/apache/qpid/server/flow/FlowCreditManager.java
deleted file mode 100644
index bec51d361d..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/flow/FlowCreditManager.java
+++ /dev/null
@@ -1,46 +0,0 @@
-package org.apache.qpid.server.flow;
-
-import org.apache.qpid.server.message.ServerMessage;
-
-/*
-*
-* 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 interface FlowCreditManager
-{
- long getMessageCredit();
-
- long getBytesCredit();
-
- public static interface FlowCreditManagerListener
- {
- void creditStateChanged(boolean hasCredit);
- }
-
- void addStateListener(FlowCreditManagerListener listener);
-
- boolean removeListener(FlowCreditManagerListener listener);
-
- public void restoreCredit(long messageCredit, long bytesCredit);
-
- public boolean hasCredit();
-
- public boolean useCreditForMessage(ServerMessage msg);
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/flow/FlowCreditManager_0_10.java b/java/broker/src/main/java/org/apache/qpid/server/flow/FlowCreditManager_0_10.java
deleted file mode 100755
index 48c336c0b1..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/flow/FlowCreditManager_0_10.java
+++ /dev/null
@@ -1,28 +0,0 @@
-package org.apache.qpid.server.flow;
-
-/*
- *
- * 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 interface FlowCreditManager_0_10 extends FlowCreditManager
-{
- public void addCredit(long count, long bytes);
-
- void clearCredit();
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/flow/LimitlessCreditManager.java b/java/broker/src/main/java/org/apache/qpid/server/flow/LimitlessCreditManager.java
deleted file mode 100644
index 901b71fd1f..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/flow/LimitlessCreditManager.java
+++ /dev/null
@@ -1,54 +0,0 @@
-package org.apache.qpid.server.flow;
-
-import org.apache.qpid.server.message.ServerMessage;
-
-/*
-*
-* 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 LimitlessCreditManager extends AbstractFlowCreditManager implements FlowCreditManager
-{
- public long getMessageCredit()
- {
- return -1L;
- }
-
- public long getBytesCredit()
- {
- return -1L;
- }
-
- public void restoreCredit(long messageCredit, long bytesCredit)
- {
- }
-
- public void removeAllCredit()
- {
- }
-
- public boolean hasCredit()
- {
- return true;
- }
-
- public boolean useCreditForMessage(ServerMessage msg)
- {
- return true;
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/flow/MessageAndBytesCreditManager.java b/java/broker/src/main/java/org/apache/qpid/server/flow/MessageAndBytesCreditManager.java
deleted file mode 100644
index 19a9ac1d23..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/flow/MessageAndBytesCreditManager.java
+++ /dev/null
@@ -1,92 +0,0 @@
-package org.apache.qpid.server.flow;
-
-import org.apache.qpid.server.message.ServerMessage;
-
-/*
-*
-* 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 MessageAndBytesCreditManager extends AbstractFlowCreditManager implements FlowCreditManager
-{
- private long _messageCredit;
- private long _bytesCredit;
-
- public MessageAndBytesCreditManager(final long messageCredit, final long bytesCredit)
- {
- _messageCredit = messageCredit;
- _bytesCredit = bytesCredit;
- }
-
- public synchronized long getMessageCredit()
- {
- return _messageCredit;
- }
-
- public synchronized long getBytesCredit()
- {
- return _bytesCredit;
- }
-
- public synchronized void restoreCredit(long messageCredit, long bytesCredit)
- {
- _messageCredit += messageCredit;
- _bytesCredit += bytesCredit;
- setSuspended(hasCredit());
- }
-
- public synchronized void removeAllCredit()
- {
- _messageCredit = 0L;
- _bytesCredit = 0L;
- setSuspended(true);
- }
-
- public synchronized boolean hasCredit()
- {
- return (_messageCredit > 0L) && ( _bytesCredit > 0L );
- }
-
- public synchronized boolean useCreditForMessage(ServerMessage msg)
- {
- if(_messageCredit == 0L)
- {
- setSuspended(true);
- return false;
- }
- else
- {
- final long msgSize = msg.getSize();
- if(msgSize > _bytesCredit)
- {
- setSuspended(true);
- return false;
- }
- _messageCredit--;
- _bytesCredit -= msgSize;
- setSuspended(false);
- return true;
- }
-
- }
-
- public synchronized void setBytesCredit(long bytesCredit)
- {
- _bytesCredit = bytesCredit;
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/flow/MessageOnlyCreditManager.java b/java/broker/src/main/java/org/apache/qpid/server/flow/MessageOnlyCreditManager.java
deleted file mode 100644
index a386f66b11..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/flow/MessageOnlyCreditManager.java
+++ /dev/null
@@ -1,88 +0,0 @@
-package org.apache.qpid.server.flow;
-
-import org.apache.qpid.server.message.ServerMessage;
-
-import java.util.concurrent.atomic.AtomicLong;
-
-/*
-*
-* 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 MessageOnlyCreditManager extends AbstractFlowCreditManager implements FlowCreditManager
-{
- private final AtomicLong _messageCredit;
-
- public MessageOnlyCreditManager(final long initialCredit)
- {
- _messageCredit = new AtomicLong(initialCredit);
- }
-
- public long getMessageCredit()
- {
- return _messageCredit.get();
- }
-
- public long getBytesCredit()
- {
- return -1L;
- }
-
- public void restoreCredit(long messageCredit, long bytesCredit)
- {
- _messageCredit.addAndGet(messageCredit);
- setSuspended(false);
-
- }
-
- public void removeAllCredit()
- {
- setSuspended(true);
- _messageCredit.set(0L);
- }
-
- public boolean hasCredit()
- {
- return _messageCredit.get() > 0L;
- }
-
- public boolean useCreditForMessage(ServerMessage msg)
- {
- if(hasCredit())
- {
- if(_messageCredit.addAndGet(-1L) >= 0)
- {
- setSuspended(false);
- return true;
- }
- else
- {
- _messageCredit.addAndGet(1L);
- setSuspended(true);
- return false;
- }
- }
- else
- {
- setSuspended(true);
- return false;
- }
-
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/flow/Pre0_10CreditManager.java b/java/broker/src/main/java/org/apache/qpid/server/flow/Pre0_10CreditManager.java
deleted file mode 100644
index 026804439c..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/flow/Pre0_10CreditManager.java
+++ /dev/null
@@ -1,195 +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.flow;
-
-import org.apache.qpid.server.message.ServerMessage;
-
-public class Pre0_10CreditManager extends AbstractFlowCreditManager implements FlowCreditManager
-{
-
- private volatile long _bytesCreditLimit;
- private volatile long _messageCreditLimit;
-
- private volatile long _bytesCredit;
- private volatile long _messageCredit;
-
- public Pre0_10CreditManager(long bytesCreditLimit, long messageCreditLimit)
- {
- _bytesCreditLimit = bytesCreditLimit;
- _messageCreditLimit = messageCreditLimit;
- _bytesCredit = bytesCreditLimit;
- _messageCredit = messageCreditLimit;
- }
-
-
- public synchronized void setCreditLimits(final long bytesCreditLimit, final long messageCreditLimit)
- {
- long bytesCreditChange = bytesCreditLimit - _bytesCreditLimit;
- long messageCreditChange = messageCreditLimit - _messageCreditLimit;
-
-
-
- if(bytesCreditChange != 0L)
- {
- if(bytesCreditLimit == 0L)
- {
- _bytesCredit = 0;
- }
- else
- {
- _bytesCredit += bytesCreditChange;
- }
- }
-
-
- if(messageCreditChange != 0L)
- {
- if(messageCreditLimit == 0L)
- {
- _messageCredit = 0;
- }
- else
- {
- _messageCredit += messageCreditChange;
- }
- }
-
-
- _bytesCreditLimit = bytesCreditLimit;
- _messageCreditLimit = messageCreditLimit;
-
- setSuspended(!hasCredit());
-
- }
-
-
- public long getMessageCredit()
- {
- return _messageCredit;
- }
-
- public long getBytesCredit()
- {
- return _bytesCredit;
- }
-
- public synchronized void restoreCredit(final long messageCredit, final long bytesCredit)
- {
- final long messageCreditLimit = _messageCreditLimit;
- boolean notifyIncrease = true;
- if(messageCreditLimit != 0L)
- {
- notifyIncrease = (_messageCredit != 0);
- long newCredit = _messageCredit + messageCredit;
- _messageCredit = newCredit > messageCreditLimit ? messageCreditLimit : newCredit;
- }
-
-
- final long bytesCreditLimit = _bytesCreditLimit;
- if(bytesCreditLimit != 0L)
- {
- long newCredit = _bytesCredit + bytesCredit;
- _bytesCredit = newCredit > bytesCreditLimit ? bytesCreditLimit : newCredit;
- if(notifyIncrease && bytesCredit>0)
- {
- notifyIncreaseBytesCredit();
- }
- }
-
-
-
- setSuspended(!hasCredit());
-
- }
-
- public synchronized void removeAllCredit()
- {
- _bytesCredit = 0L;
- _messageCredit = 0L;
- setSuspended(!hasCredit());
- }
-
- public synchronized boolean hasCredit()
- {
- return (_bytesCreditLimit == 0L || _bytesCredit > 0)
- && (_messageCreditLimit == 0L || _messageCredit > 0);
- }
-
- public synchronized boolean useCreditForMessage(final ServerMessage msg)
- {
- if(_messageCreditLimit != 0L)
- {
- if(_messageCredit != 0L)
- {
- if(_bytesCreditLimit == 0L)
- {
- _messageCredit--;
-
- return true;
- }
- else
- {
- if((_bytesCredit >= msg.getSize()) || (_bytesCredit == _bytesCreditLimit))
- {
- _messageCredit--;
- _bytesCredit -= msg.getSize();
-
- return true;
- }
- else
- {
- //setSuspended(true);
- return false;
- }
- }
- }
- else
- {
- setSuspended(true);
- return false;
- }
- }
- else
- {
- if(_bytesCreditLimit == 0L)
- {
-
- return true;
- }
- else
- {
- if((_bytesCredit >= msg.getSize()) || (_bytesCredit == _bytesCreditLimit))
- {
- _bytesCredit -= msg.getSize();
-
- return true;
- }
- else
- {
- //setSuspended(true);
- return false;
- }
- }
-
- }
-
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/flow/WindowCreditManager.java b/java/broker/src/main/java/org/apache/qpid/server/flow/WindowCreditManager.java
deleted file mode 100644
index 10f578551a..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/flow/WindowCreditManager.java
+++ /dev/null
@@ -1,213 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.flow;
-
-import org.apache.qpid.server.message.ServerMessage;
-
-public class WindowCreditManager extends AbstractFlowCreditManager implements FlowCreditManager_0_10
-{
- private volatile long _bytesCreditLimit;
- private volatile long _messageCreditLimit;
-
- private volatile long _bytesUsed;
- private volatile long _messageUsed;
-
- public WindowCreditManager()
- {
- this(0L, 0L);
- }
-
- public WindowCreditManager(long bytesCreditLimit, long messageCreditLimit)
- {
- _bytesCreditLimit = bytesCreditLimit;
- _messageCreditLimit = messageCreditLimit;
- setSuspended(!hasCredit());
-
- }
-
-
- public synchronized void setCreditLimits(final long bytesCreditLimit, final long messageCreditLimit)
- {
- _bytesCreditLimit = bytesCreditLimit;
- _messageCreditLimit = messageCreditLimit;
-
- setSuspended(!hasCredit());
-
- }
-
-
- public long getMessageCredit()
- {
- return _messageCreditLimit == -1L
- ? Long.MAX_VALUE
- : _messageUsed < _messageCreditLimit ? _messageCreditLimit - _messageUsed : 0L;
- }
-
- public long getBytesCredit()
- {
- return _bytesCreditLimit == -1L
- ? Long.MAX_VALUE
- : _bytesUsed < _bytesCreditLimit ? _bytesCreditLimit - _bytesUsed : 0L;
- }
-
- public synchronized void restoreCredit(final long messageCredit, final long bytesCredit)
- {
- boolean notifyIncrease = true;
- if(_messageCreditLimit > 0L)
- {
- notifyIncrease = (_messageUsed != _messageCreditLimit);
- _messageUsed -= messageCredit;
-
- //TODO log warning
- if(_messageUsed < 0L)
- {
- _messageUsed = 0;
- }
- }
-
-
-
- if(_bytesCreditLimit > 0L)
- {
- notifyIncrease = notifyIncrease && bytesCredit>0;
- _bytesUsed -= bytesCredit;
-
- //TODO log warning
- if(_bytesUsed < 0L)
- {
- _bytesUsed = 0;
- }
-
- if(notifyIncrease)
- {
- notifyIncreaseBytesCredit();
- }
- }
-
-
-
- setSuspended(!hasCredit());
-
- }
-
-
-
- public synchronized boolean hasCredit()
- {
- return (_bytesCreditLimit < 0L || _bytesCreditLimit > _bytesUsed)
- && (_messageCreditLimit < 0L || _messageCreditLimit > _messageUsed);
- }
-
- public synchronized boolean useCreditForMessage(final ServerMessage msg)
- {
- if(_messageCreditLimit >= 0L)
- {
- if(_messageUsed < _messageCreditLimit)
- {
- if(_bytesCreditLimit < 0L)
- {
- _messageUsed++;
-
- return true;
- }
- else if(_bytesUsed + msg.getSize() <= _bytesCreditLimit)
- {
- _messageUsed++;
- _bytesUsed += msg.getSize();
-
- return true;
- }
- else
- {
- //setSuspended(true);
- return false;
- }
- }
- else
- {
- setSuspended(true);
- return false;
- }
- }
- else if(_bytesCreditLimit >= 0L)
- {
- if(_bytesUsed + msg.getSize() <= _bytesCreditLimit)
- {
- _bytesUsed += msg.getSize();
-
- return true;
- }
- else
- {
- //setSuspended(true);
- return false;
- }
-
- }
- else
- {
- return true;
- }
-
- }
-
- public void stop()
- {
- if(_bytesCreditLimit > 0)
- {
- _bytesCreditLimit = 0;
- }
- if(_messageCreditLimit > 0)
- {
- _messageCreditLimit = 0;
- }
-
- }
-
- public synchronized void addCredit(long count, long bytes)
- {
- if(bytes > 0)
- {
- _bytesCreditLimit += bytes;
- }
- else if(bytes == -1)
- {
- _bytesCreditLimit = -1;
- }
-
-
- if(count > 0)
- {
- _messageCreditLimit += count;
- }
- else if(count == -1)
- {
- _messageCreditLimit = -1;
- }
- }
-
- public void clearCredit()
- {
- _bytesCreditLimit = 0l;
- _messageCreditLimit = 0l;
- setSuspended(true);
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/AccessRequestHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/AccessRequestHandler.java
deleted file mode 100644
index d587ef0c16..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/AccessRequestHandler.java
+++ /dev/null
@@ -1,77 +0,0 @@
-package org.apache.qpid.server.handler;
-/*
- *
- * 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.framing.*;
-import org.apache.qpid.framing.amqp_8_0.MethodRegistry_8_0;
-import org.apache.qpid.framing.amqp_0_9.MethodRegistry_0_9;
-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;
-
-/**
- * @author Apache Software Foundation
- *
- *
- */
-public class AccessRequestHandler implements StateAwareMethodListener<AccessRequestBody>
-{
- private static final AccessRequestHandler _instance = new AccessRequestHandler();
-
-
- public static AccessRequestHandler getInstance()
- {
- return _instance;
- }
-
- private AccessRequestHandler()
- {
- }
-
- public void methodReceived(AMQStateManager stateManager, AccessRequestBody body, int channelId) throws AMQException
- {
- AMQProtocolSession session = stateManager.getProtocolSession();
-
- MethodRegistry methodRegistry = session.getMethodRegistry();
-
- // We don't implement access control class, but to keep clients happy that expect it
- // always use the "0" ticket.
- AccessRequestOkBody response;
- if(methodRegistry instanceof MethodRegistry_0_9)
- {
- response = ((MethodRegistry_0_9)methodRegistry).createAccessRequestOkBody(0);
- }
- else if(methodRegistry instanceof MethodRegistry_8_0)
- {
- response = ((MethodRegistry_8_0)methodRegistry).createAccessRequestOkBody(0);
- }
- else
- {
- throw new AMQException(AMQConstant.COMMAND_INVALID, "AccessRequest not present in AMQP versions other than 0-8, 0-9");
- }
-
-
- session.writeFrame(response.generateFrame(channelId));
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/BasicAckMethodHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/BasicAckMethodHandler.java
deleted file mode 100644
index f90e7c3dff..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/BasicAckMethodHandler.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.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;
-import org.apache.qpid.server.state.StateAwareMethodListener;
-
-public class BasicAckMethodHandler implements StateAwareMethodListener<BasicAckBody>
-{
- private static final Logger _log = Logger.getLogger(BasicAckMethodHandler.class);
-
- private static final BasicAckMethodHandler _instance = new BasicAckMethodHandler();
-
- public static BasicAckMethodHandler getInstance()
- {
- return _instance;
- }
-
- private BasicAckMethodHandler()
- {
- }
-
- public void methodReceived(AMQStateManager stateManager, BasicAckBody body, int channelId) throws AMQException
- {
- AMQProtocolSession protocolSession = stateManager.getProtocolSession();
-
-
- if (_log.isDebugEnabled())
- {
- _log.debug("Ack(Tag:" + body.getDeliveryTag() + ":Mult:" + body.getMultiple() + ") received on channel " + channelId);
- }
-
- final AMQChannel channel = protocolSession.getChannel(channelId);
-
- if (channel == null)
- {
- throw body.getChannelNotFoundException(channelId);
- }
-
- // this method throws an AMQException if the delivery tag is not known
- channel.acknowledgeMessage(body.getDeliveryTag(), body.getMultiple());
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/BasicCancelMethodHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/BasicCancelMethodHandler.java
deleted file mode 100644
index 29054f55c1..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/BasicCancelMethodHandler.java
+++ /dev/null
@@ -1,74 +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.handler;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.BasicCancelBody;
-import org.apache.qpid.framing.BasicCancelOkBody;
-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;
-import org.apache.qpid.server.state.StateAwareMethodListener;
-import org.apache.log4j.Logger;
-
-public class BasicCancelMethodHandler implements StateAwareMethodListener<BasicCancelBody>
-{
- private static final Logger _log = Logger.getLogger(BasicCancelMethodHandler.class);
-
- private static final BasicCancelMethodHandler _instance = new BasicCancelMethodHandler();
-
- public static BasicCancelMethodHandler getInstance()
- {
- return _instance;
- }
-
- private BasicCancelMethodHandler()
- {
- }
-
- public void methodReceived(AMQStateManager stateManager, BasicCancelBody body, int channelId) throws AMQException
- {
- AMQProtocolSession session = stateManager.getProtocolSession();
-
- final AMQChannel channel = session.getChannel(channelId);
-
-
- if (channel == null)
- {
- throw body.getChannelNotFoundException(channelId);
- }
-
- if (_log.isDebugEnabled())
- {
- _log.debug("BasicCancel: for:" + body.getConsumerTag() +
- " nowait:" + body.getNowait());
- }
-
- channel.unsubscribeConsumer(body.getConsumerTag());
- if (!body.getNowait())
- {
- MethodRegistry methodRegistry = session.getMethodRegistry();
- BasicCancelOkBody cancelOkBody = methodRegistry.createBasicCancelOkBody(body.getConsumerTag());
- session.writeFrame(cancelOkBody.generateFrame(channelId));
- }
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/BasicConsumeMethodHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/BasicConsumeMethodHandler.java
deleted file mode 100644
index a5999711bc..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/BasicConsumeMethodHandler.java
+++ /dev/null
@@ -1,173 +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.handler;
-
-import org.apache.log4j.Logger;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.*;
-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.AMQQueue;
-import org.apache.qpid.server.state.AMQStateManager;
-import org.apache.qpid.server.state.StateAwareMethodListener;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-
-public class BasicConsumeMethodHandler implements StateAwareMethodListener<BasicConsumeBody>
-{
- private static final Logger _logger = Logger.getLogger(BasicConsumeMethodHandler.class);
-
- private static final BasicConsumeMethodHandler _instance = new BasicConsumeMethodHandler();
-
- public static BasicConsumeMethodHandler getInstance()
- {
- return _instance;
- }
-
- private BasicConsumeMethodHandler()
- {
- }
-
- public void methodReceived(AMQStateManager stateManager, BasicConsumeBody body, int channelId) throws AMQException
- {
- AMQProtocolSession protocolConnection = stateManager.getProtocolSession();
-
- AMQChannel channel = protocolConnection.getChannel(channelId);
-
- VirtualHost vHost = protocolConnection.getVirtualHost();
-
- if (channel == null)
- {
- throw body.getChannelNotFoundException(channelId);
- }
- else
- {
- if (_logger.isDebugEnabled())
- {
- _logger.debug("BasicConsume: from '" + body.getQueue() +
- "' for:" + body.getConsumerTag() +
- " nowait:" + body.getNowait() +
- " args:" + body.getArguments());
- }
-
- AMQQueue queue = body.getQueue() == null ? channel.getDefaultQueue() : vHost.getQueueRegistry().getQueue(body.getQueue().intern());
-
- if (queue == null)
- {
- if (_logger.isDebugEnabled())
- {
- _logger.debug("No queue for '" + body.getQueue() + "'");
- }
- if (body.getQueue() != null)
- {
- String msg = "No such queue, '" + body.getQueue() + "'";
- throw body.getChannelException(AMQConstant.NOT_FOUND, msg);
- }
- else
- {
- String msg = "No queue name provided, no default queue defined.";
- throw body.getConnectionException(AMQConstant.NOT_ALLOWED, msg);
- }
- }
- else
- {
- final AMQShortString consumerTagName;
-
- if (queue.isExclusive() && !queue.isDurable())
- {
- AMQSessionModel session = queue.getExclusiveOwningSession();
- if (session == null || session.getConnectionModel() != protocolConnection)
- {
- throw body.getConnectionException(AMQConstant.NOT_ALLOWED,
- "Queue " + queue.getNameShortString() + " is exclusive, but not created on this Connection.");
- }
- }
-
- if (body.getConsumerTag() != null)
- {
- consumerTagName = body.getConsumerTag().intern();
- }
- else
- {
- consumerTagName = null;
- }
-
- try
- {
- if(consumerTagName == null || channel.getSubscription(consumerTagName) == null)
- {
-
- AMQShortString consumerTag = channel.subscribeToQueue(consumerTagName, queue, !body.getNoAck(),
- body.getArguments(), body.getNoLocal(), body.getExclusive());
- if (!body.getNowait())
- {
- MethodRegistry methodRegistry = protocolConnection.getMethodRegistry();
- AMQMethodBody responseBody = methodRegistry.createBasicConsumeOkBody(consumerTag);
- protocolConnection.writeFrame(responseBody.generateFrame(channelId));
-
- }
- }
- else
- {
- AMQShortString msg = new AMQShortString("Non-unique consumer tag, '" + body.getConsumerTag() + "'");
-
- MethodRegistry methodRegistry = protocolConnection.getMethodRegistry();
- AMQMethodBody responseBody = methodRegistry.createConnectionCloseBody(AMQConstant.NOT_ALLOWED.getCode(), // replyCode
- msg, // replytext
- body.getClazz(),
- body.getMethod());
- protocolConnection.writeFrame(responseBody.generateFrame(0));
- }
-
- }
- catch (org.apache.qpid.AMQInvalidArgumentException ise)
- {
- _logger.debug("Closing connection due to invalid selector");
-
- MethodRegistry methodRegistry = protocolConnection.getMethodRegistry();
- AMQMethodBody responseBody = methodRegistry.createChannelCloseBody(AMQConstant.INVALID_ARGUMENT.getCode(),
- new AMQShortString(ise.getMessage()),
- body.getClazz(),
- body.getMethod());
- protocolConnection.writeFrame(responseBody.generateFrame(channelId));
-
-
- }
- catch (AMQQueue.ExistingExclusiveSubscription e)
- {
- throw body.getChannelException(AMQConstant.ACCESS_REFUSED,
- "Cannot subscribe to queue "
- + queue.getNameShortString()
- + " as it already has an existing exclusive consumer");
- }
- catch (AMQQueue.ExistingSubscriptionPreventsExclusive e)
- {
- throw body.getChannelException(AMQConstant.ACCESS_REFUSED,
- "Cannot subscribe to queue "
- + queue.getNameShortString()
- + " exclusively as it already has a consumer");
- }
-
- }
- }
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/BasicGetMethodHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/BasicGetMethodHandler.java
deleted file mode 100644
index 790027f293..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/BasicGetMethodHandler.java
+++ /dev/null
@@ -1,206 +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.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.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.virtualhost.VirtualHost;
-
-public class BasicGetMethodHandler implements StateAwareMethodListener<BasicGetBody>
-{
- private static final Logger _log = Logger.getLogger(BasicGetMethodHandler.class);
-
- private static final BasicGetMethodHandler _instance = new BasicGetMethodHandler();
-
- public static BasicGetMethodHandler getInstance()
- {
- return _instance;
- }
-
- private BasicGetMethodHandler()
- {
- }
-
- public void methodReceived(AMQStateManager stateManager, BasicGetBody body, int channelId) throws AMQException
- {
- AMQProtocolSession protocolConnection = stateManager.getProtocolSession();
-
-
- VirtualHost vHost = protocolConnection.getVirtualHost();
-
- AMQChannel channel = protocolConnection.getChannel(channelId);
- if (channel == null)
- {
- throw body.getChannelNotFoundException(channelId);
- }
- else
- {
- AMQQueue queue = body.getQueue() == null ? channel.getDefaultQueue() : vHost.getQueueRegistry().getQueue(body.getQueue());
- if (queue == null)
- {
- _log.info("No queue for '" + body.getQueue() + "'");
- if(body.getQueue()!=null)
- {
- throw body.getConnectionException(AMQConstant.NOT_FOUND,
- "No such queue, '" + body.getQueue()+ "'");
- }
- else
- {
- throw body.getConnectionException(AMQConstant.NOT_ALLOWED,
- "No queue name provided, no default queue defined.");
- }
- }
- else
- {
- if (queue.isExclusive())
- {
- AMQSessionModel session = queue.getExclusiveOwningSession();
- if (session == null || session.getConnectionModel() != protocolConnection)
- {
- throw body.getConnectionException(AMQConstant.NOT_ALLOWED,
- "Queue is exclusive, but not created on this Connection.");
- }
- }
-
- if (!performGet(queue,protocolConnection, channel, !body.getNoAck()))
- {
- MethodRegistry methodRegistry = protocolConnection.getMethodRegistry();
- // TODO - set clusterId
- BasicGetEmptyBody responseBody = methodRegistry.createBasicGetEmptyBody(null);
-
-
- protocolConnection.writeFrame(responseBody.generateFrame(channelId));
- }
- }
- }
- }
-
- public static boolean performGet(final AMQQueue queue,
- final AMQProtocolSession session,
- final AMQChannel channel,
- final boolean acks)
- throws AMQException
- {
-
- final FlowCreditManager singleMessageCredit = new MessageOnlyCreditManager(1L);
-
- final ClientDeliveryMethod getDeliveryMethod = new ClientDeliveryMethod()
- {
-
- int _msg;
-
- public void deliverToClient(final Subscription sub, final QueueEntry entry, final long deliveryTag)
- throws AMQException
- {
- singleMessageCredit.useCreditForMessage(entry.getMessage());
- if(entry.getMessage() instanceof AMQMessage)
- {
- session.getProtocolOutputConverter().writeGetOk(entry, channel.getChannelId(),
- deliveryTag, queue.getMessageCount());
- }
- else
- {
- //TODO Convert AMQP 0-10 message
- throw new AMQException(AMQConstant.NOT_IMPLEMENTED, "Not implemented conversion of 0-10 message", null);
- }
-
- }
- };
- final RecordDeliveryMethod getRecordMethod = new RecordDeliveryMethod()
- {
-
- public void recordMessageDelivery(final Subscription sub, final QueueEntry entry, final long deliveryTag)
- {
- channel.addUnacknowledgedMessage(entry, deliveryTag, null);
- }
- };
-
- Subscription sub;
- if(acks)
- {
- sub = SubscriptionFactoryImpl.INSTANCE.createSubscription(channel, session, null, acks, null, false, singleMessageCredit, getDeliveryMethod, getRecordMethod);
- }
- else
- {
- sub = new GetNoAckSubscription(channel,
- session,
- null,
- null,
- false,
- singleMessageCredit,
- getDeliveryMethod,
- getRecordMethod);
- }
-
- queue.registerSubscription(sub,false);
- queue.flushSubscription(sub);
- queue.unregisterSubscription(sub);
- return(!singleMessageCredit.hasCredit());
-
-
- }
-
- public static final class GetNoAckSubscription extends SubscriptionImpl.NoAckSubscription
- {
- public GetNoAckSubscription(AMQChannel channel, AMQProtocolSession protocolSession,
- AMQShortString consumerTag, FieldTable filters,
- boolean noLocal, FlowCreditManager creditManager,
- ClientDeliveryMethod deliveryMethod,
- RecordDeliveryMethod recordMethod)
- throws AMQException
- {
- super(channel, protocolSession, consumerTag, filters, noLocal, creditManager, deliveryMethod, recordMethod);
- }
-
- public boolean isTransient()
- {
- return true;
- }
-
- public boolean wouldSuspend(QueueEntry msg)
- {
- return !getCreditManager().useCreditForMessage(msg.getMessage());
- }
-
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/BasicPublishMethodHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/BasicPublishMethodHandler.java
deleted file mode 100644
index 8f23b1c4d4..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/BasicPublishMethodHandler.java
+++ /dev/null
@@ -1,96 +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.handler;
-
-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.BasicPublishBody;
-import org.apache.qpid.framing.abstraction.MessagePublishInfo;
-import org.apache.qpid.protocol.AMQConstant;
-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.state.AMQStateManager;
-import org.apache.qpid.server.state.StateAwareMethodListener;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-
-public class BasicPublishMethodHandler implements StateAwareMethodListener<BasicPublishBody>
-{
- private static final Logger _logger = Logger.getLogger(BasicPublishMethodHandler.class);
-
- private static final BasicPublishMethodHandler _instance = new BasicPublishMethodHandler();
-
-
- public static BasicPublishMethodHandler getInstance()
- {
- return _instance;
- }
-
- private BasicPublishMethodHandler()
- {
- }
-
- public void methodReceived(AMQStateManager stateManager, BasicPublishBody body, int channelId) throws AMQException
- {
- AMQProtocolSession session = stateManager.getProtocolSession();
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Publish received on channel " + channelId);
- }
-
- AMQShortString exchangeName = body.getExchange();
- // TODO: check the delivery tag field details - is it unique across the broker or per subscriber?
- if (exchangeName == null)
- {
- exchangeName = ExchangeDefaults.DEFAULT_EXCHANGE_NAME;
- }
-
- VirtualHost vHost = session.getVirtualHost();
- Exchange exch = vHost.getExchangeRegistry().getExchange(exchangeName);
- // if the exchange does not exist we raise a channel exception
- if (exch == null)
- {
- throw body.getChannelException(AMQConstant.NOT_FOUND, "Unknown exchange name");
- }
- else
- {
- // The partially populated BasicDeliver frame plus the received route body
- // is stored in the channel. Once the final body frame has been received
- // it is routed to the exchange.
- AMQChannel channel = session.getChannel(channelId);
-
- if (channel == null)
- {
- throw body.getChannelNotFoundException(channelId);
- }
-
- MessagePublishInfo info = session.getMethodRegistry().getProtocolVersionMethodConverter().convertToInfo(body);
- info.setExchange(exchangeName);
- channel.setPublishFrame(info, exch);
- }
- }
-
-}
-
-
-
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/BasicQosHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/BasicQosHandler.java
deleted file mode 100644
index dd3281c65f..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/BasicQosHandler.java
+++ /dev/null
@@ -1,58 +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.handler;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.BasicQosBody;
-import org.apache.qpid.framing.MethodRegistry;
-import org.apache.qpid.framing.AMQMethodBody;
-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<BasicQosBody>
-{
- private static final BasicQosHandler _instance = new BasicQosHandler();
-
- public static BasicQosHandler getInstance()
- {
- return _instance;
- }
-
- public void methodReceived(AMQStateManager stateManager, BasicQosBody body, int channelId) throws AMQException
- {
- AMQProtocolSession session = stateManager.getProtocolSession();
- AMQChannel channel = session.getChannel(channelId);
- if (channel == null)
- {
- throw body.getChannelNotFoundException(channelId);
- }
-
- channel.setCredit(body.getPrefetchSize(), body.getPrefetchCount());
-
-
- MethodRegistry methodRegistry = session.getMethodRegistry();
- AMQMethodBody responseBody = methodRegistry.createBasicQosOkBody();
- session.writeFrame(responseBody.generateFrame(channelId));
-
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/BasicRecoverMethodHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/BasicRecoverMethodHandler.java
deleted file mode 100644
index c7842cd643..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/BasicRecoverMethodHandler.java
+++ /dev/null
@@ -1,73 +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.handler;
-
-import org.apache.log4j.Logger;
-import org.apache.qpid.AMQException;
-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;
-import org.apache.qpid.server.state.StateAwareMethodListener;
-
-public class BasicRecoverMethodHandler implements StateAwareMethodListener<BasicRecoverBody>
-{
- private static final Logger _logger = Logger.getLogger(BasicRecoverMethodHandler.class);
-
- private static final BasicRecoverMethodHandler _instance = new BasicRecoverMethodHandler();
-
- public static BasicRecoverMethodHandler getInstance()
- {
- return _instance;
- }
-
- public void methodReceived(AMQStateManager stateManager, BasicRecoverBody body, int channelId) throws AMQException
- {
- AMQProtocolSession session = stateManager.getProtocolSession();
-
- _logger.debug("Recover received on protocol session " + session + " and channel " + channelId);
- AMQChannel channel = session.getChannel(channelId);
-
-
- if (channel == null)
- {
- throw body.getChannelNotFoundException(channelId);
- }
-
- channel.resend(body.getRequeue());
-
- // Qpid 0-8 hacks a synchronous -ok onto recover.
- // In Qpid 0-9 we create a separate sync-recover, sync-recover-ok pair to be "more" compliant
- if(session.getProtocolVersion().equals(ProtocolVersion.v8_0))
- {
- MethodRegistry_8_0 methodRegistry = (MethodRegistry_8_0) session.getMethodRegistry();
- AMQMethodBody recoverOk = methodRegistry.createBasicRecoverOkBody();
- session.writeFrame(recoverOk.generateFrame(channelId));
-
- }
-
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/BasicRecoverSyncMethodHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/BasicRecoverSyncMethodHandler.java
deleted file mode 100644
index f9feada6fe..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/BasicRecoverSyncMethodHandler.java
+++ /dev/null
@@ -1,83 +0,0 @@
-package org.apache.qpid.server.handler;
-/*
- *
- * 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.log4j.Logger;
-
-import org.apache.qpid.framing.BasicRecoverBody;
-import org.apache.qpid.framing.ProtocolVersion;
-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.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.server.AMQChannel;
-import org.apache.qpid.AMQException;
-
-public class BasicRecoverSyncMethodHandler implements StateAwareMethodListener<BasicRecoverSyncBody>
-{
- private static final Logger _logger = Logger.getLogger(BasicRecoverSyncMethodHandler.class);
-
- private static final BasicRecoverSyncMethodHandler _instance = new BasicRecoverSyncMethodHandler();
-
- public static BasicRecoverSyncMethodHandler getInstance()
- {
- return _instance;
- }
-
- public void methodReceived(AMQStateManager stateManager, BasicRecoverSyncBody body, int channelId) throws AMQException
- {
- AMQProtocolSession session = stateManager.getProtocolSession();
-
- _logger.debug("Recover received on protocol session " + session + " and channel " + channelId);
- AMQChannel channel = session.getChannel(channelId);
-
-
- if (channel == null)
- {
- throw body.getChannelNotFoundException(channelId);
- }
-
- channel.resend(body.getRequeue());
-
- // Qpid 0-8 hacks a synchronous -ok onto recover.
- // In Qpid 0-9 we create a separate sync-recover, sync-recover-ok pair to be "more" compliant
- if(session.getProtocolVersion().equals(ProtocolVersion.v0_9))
- {
- MethodRegistry_0_9 methodRegistry = (MethodRegistry_0_9) session.getMethodRegistry();
- AMQMethodBody recoverOk = methodRegistry.createBasicRecoverSyncOkBody();
- session.writeFrame(recoverOk.generateFrame(channelId));
-
- }
- else if(session.getProtocolVersion().equals(ProtocolVersion.v0_91))
- {
- MethodRegistry_0_91 methodRegistry = (MethodRegistry_0_91) session.getMethodRegistry();
- AMQMethodBody recoverOk = methodRegistry.createBasicRecoverSyncOkBody();
- session.writeFrame(recoverOk.generateFrame(channelId));
-
- }
-
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/BasicRejectMethodHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/BasicRejectMethodHandler.java
deleted file mode 100644
index 62dd76f832..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/BasicRejectMethodHandler.java
+++ /dev/null
@@ -1,125 +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.handler;
-
-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.state.AMQStateManager;
-import org.apache.qpid.server.state.StateAwareMethodListener;
-import org.apache.log4j.Logger;
-
-public class BasicRejectMethodHandler implements StateAwareMethodListener<BasicRejectBody>
-{
- private static final Logger _logger = Logger.getLogger(BasicRejectMethodHandler.class);
-
- private static BasicRejectMethodHandler _instance = new BasicRejectMethodHandler();
-
- public static BasicRejectMethodHandler getInstance()
- {
- return _instance;
- }
-
- private BasicRejectMethodHandler()
- {
- }
-
- public void methodReceived(AMQStateManager stateManager, BasicRejectBody body, int channelId) throws AMQException
- {
- AMQProtocolSession session = stateManager.getProtocolSession();
-
- AMQChannel channel = session.getChannel(channelId);
-
- if (channel == null)
- {
- throw body.getChannelNotFoundException(channelId);
- }
-
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Rejecting:" + body.getDeliveryTag() +
- ": Requeue:" + body.getRequeue() +
- //": Resend:" + evt.getMethod().resend +
- " on channel:" + channel.debugIdentity());
- }
-
- long deliveryTag = body.getDeliveryTag();
-
- QueueEntry message = channel.getUnacknowledgedMessageMap().get(deliveryTag);
-
- if (message == null)
- {
- _logger.warn("Dropping reject request as message is null for tag:" + deliveryTag);
-// throw evt.getMethod().getChannelException(AMQConstant.NOT_FOUND, "Delivery Tag(" + deliveryTag + ")not known");
- }
- else
- {
- if (message.isQueueDeleted())
- {
- _logger.warn("Message's Queue as already been purged, unable to Reject. " +
- "Dropping message should use Dead Letter Queue");
- message = channel.getUnacknowledgedMessageMap().remove(deliveryTag);
- if(message != null)
- {
- message.discard();
- }
- //sendtoDeadLetterQueue(msg)
- return;
- }
-
- if (message.getMessage() == null)
- {
- _logger.warn("Message as already been purged, unable to Reject.");
- return;
- }
-
-
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Rejecting: DT:" + deliveryTag + "-" + message.getMessage() +
- ": Requeue:" + body.getRequeue() +
- //": Resend:" + evt.getMethod().resend +
- " on channel:" + channel.debugIdentity());
- }
-
- // If we haven't requested message to be resent to this consumer then reject it from ever getting it.
- //if (!evt.getMethod().resend)
- {
- message.reject();
- }
-
- if (body.getRequeue())
- {
- channel.requeue(deliveryTag);
- }
- else
- {
- _logger.warn("Dropping message as requeue not required and there is no dead letter queue");
- message = channel.getUnacknowledgedMessageMap().remove(deliveryTag);
- //sendtoDeadLetterQueue(AMQMessage message)
-// message.queue = channel.getDefaultDeadLetterQueue();
-// channel.requeue(deliveryTag);
- }
- }
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelCloseHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelCloseHandler.java
deleted file mode 100644
index 9133cce6b7..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelCloseHandler.java
+++ /dev/null
@@ -1,77 +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.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.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<ChannelCloseBody>
-{
- private static final Logger _logger = Logger.getLogger(ChannelCloseHandler.class);
-
- private static ChannelCloseHandler _instance = new ChannelCloseHandler();
-
- public static ChannelCloseHandler getInstance()
- {
- return _instance;
- }
-
- private ChannelCloseHandler()
- {
- }
-
- public void methodReceived(AMQStateManager stateManager, ChannelCloseBody body, int channelId) throws AMQException
- {
- AMQProtocolSession session = stateManager.getProtocolSession();
-
- if (_logger.isInfoEnabled())
- {
- _logger.info("Received channel close for id " + channelId + " citing class " + body.getClassId() +
- " and method " + body.getMethodId());
- }
-
-
- AMQChannel channel = session.getChannel(channelId);
-
- if (channel == null)
- {
- throw body.getConnectionException(AMQConstant.CHANNEL_ERROR, "Trying to close unknown channel");
- }
-
- session.closeChannel(channelId);
- // Client requested closure so we don't wait for ok we send it
- stateManager.getProtocolSession().closeChannelOk(channelId);
-
- MethodRegistry methodRegistry = session.getMethodRegistry();
- ChannelCloseOkBody responseBody = methodRegistry.createChannelCloseOkBody();
- session.writeFrame(responseBody.generateFrame(channelId));
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelCloseOkHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelCloseOkHandler.java
deleted file mode 100644
index a857490e7e..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelCloseOkHandler.java
+++ /dev/null
@@ -1,53 +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.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;
-
-public class ChannelCloseOkHandler implements StateAwareMethodListener<ChannelCloseOkBody>
-{
- private static final Logger _logger = Logger.getLogger(ChannelCloseOkHandler.class);
-
- private static ChannelCloseOkHandler _instance = new ChannelCloseOkHandler();
-
- public static ChannelCloseOkHandler getInstance()
- {
- return _instance;
- }
-
- private ChannelCloseOkHandler()
- {
- }
-
- public void methodReceived(AMQStateManager stateManager, ChannelCloseOkBody body, int channelId) throws AMQException
- {
-
- _logger.info("Received channel-close-ok for channel-id " + channelId);
-
- // Let the Protocol Session know the channel is now closed.
- stateManager.getProtocolSession().closeChannelOk(channelId);
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelFlowHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelFlowHandler.java
deleted file mode 100644
index 696ca8a63b..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelFlowHandler.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.
- *
- */
-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.server.AMQChannel;
-import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.server.state.AMQStateManager;
-import org.apache.qpid.server.state.StateAwareMethodListener;
-
-public class ChannelFlowHandler implements StateAwareMethodListener<ChannelFlowBody>
-{
- private static final Logger _logger = Logger.getLogger(ChannelFlowHandler.class);
-
- private static ChannelFlowHandler _instance = new ChannelFlowHandler();
-
- public static ChannelFlowHandler getInstance()
- {
- return _instance;
- }
-
- private ChannelFlowHandler()
- {
- }
-
- public void methodReceived(AMQStateManager stateManager, ChannelFlowBody body, int channelId) throws AMQException
- {
- AMQProtocolSession session = stateManager.getProtocolSession();
-
-
- AMQChannel channel = session.getChannel(channelId);
-
- if (channel == null)
- {
- throw body.getChannelNotFoundException(channelId);
- }
-
- channel.setSuspended(!body.getActive());
- _logger.debug("Channel.Flow for channel " + channelId + ", active=" + body.getActive());
-
- MethodRegistry methodRegistry = session.getMethodRegistry();
- AMQMethodBody responseBody = methodRegistry.createChannelFlowOkBody(body.getActive());
- session.writeFrame(responseBody.generateFrame(channelId));
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelOpenHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelOpenHandler.java
deleted file mode 100644
index 6d874ee971..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelOpenHandler.java
+++ /dev/null
@@ -1,141 +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.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;
-import org.apache.qpid.framing.MethodRegistry;
-import org.apache.qpid.framing.ProtocolVersion;
-import org.apache.qpid.framing.amqp_0_9.MethodRegistry_0_9;
-import org.apache.qpid.framing.amqp_0_91.MethodRegistry_0_91;
-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.protocol.AMQProtocolSession;
-import org.apache.qpid.server.state.AMQStateManager;
-import org.apache.qpid.server.state.StateAwareMethodListener;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-
-public class ChannelOpenHandler implements StateAwareMethodListener<ChannelOpenBody>
-{
- private static final Logger _logger = Logger.getLogger(ChannelOpenHandler.class);
-
- private static ChannelOpenHandler _instance = new ChannelOpenHandler();
-
- public static ChannelOpenHandler getInstance()
- {
- return _instance;
- }
-
- private ChannelOpenHandler()
- {
- }
-
- public void methodReceived(AMQStateManager stateManager, ChannelOpenBody body, int channelId) throws AMQException
- {
- AMQProtocolSession session = stateManager.getProtocolSession();
- VirtualHost virtualHost = session.getVirtualHost();
-
- // Protect the broker against out of order frame request.
- if (virtualHost == null)
- {
- throw new AMQException(AMQConstant.COMMAND_INVALID, "Virtualhost has not yet been set. ConnectionOpen has not been called.", null);
- }
- _logger.info("Connecting to: " + virtualHost.getName());
-
- final AMQChannel channel = new AMQChannel(session,channelId, virtualHost.getMessageStore());
-
- session.addChannel(channel);
-
- ChannelOpenOkBody response;
-
- ProtocolVersion pv = session.getProtocolVersion();
-
- if(pv.equals(ProtocolVersion.v8_0))
- {
- MethodRegistry_8_0 methodRegistry = (MethodRegistry_8_0) MethodRegistry.getMethodRegistry(ProtocolVersion.v8_0);
- response = methodRegistry.createChannelOpenOkBody();
-
- }
- else if(pv.equals(ProtocolVersion.v0_9))
- {
- MethodRegistry_0_9 methodRegistry = (MethodRegistry_0_9) MethodRegistry.getMethodRegistry(ProtocolVersion.v0_9);
- UUID uuid = UUID.randomUUID();
- ByteArrayOutputStream output = new ByteArrayOutputStream();
- DataOutputStream dataOut = new DataOutputStream(output);
- try
- {
- dataOut.writeLong(uuid.getMostSignificantBits());
- dataOut.writeLong(uuid.getLeastSignificantBits());
- dataOut.flush();
- dataOut.close();
- }
- catch (IOException e)
- {
- // This *really* shouldn't happen as we're not doing any I/O
- throw new RuntimeException("I/O exception when writing to byte array", e);
- }
-
- // should really associate this channelId to the session
- byte[] channelName = output.toByteArray();
-
- response = methodRegistry.createChannelOpenOkBody(channelName);
- }
- else if(pv.equals(ProtocolVersion.v0_91))
- {
- MethodRegistry_0_91 methodRegistry = (MethodRegistry_0_91) MethodRegistry.getMethodRegistry(ProtocolVersion.v0_91);
- UUID uuid = UUID.randomUUID();
- ByteArrayOutputStream output = new ByteArrayOutputStream();
- DataOutputStream dataOut = new DataOutputStream(output);
- try
- {
- dataOut.writeLong(uuid.getMostSignificantBits());
- dataOut.writeLong(uuid.getLeastSignificantBits());
- dataOut.flush();
- dataOut.close();
- }
- catch (IOException e)
- {
- // This *really* shouldn't happen as we're not doing any I/O
- throw new RuntimeException("I/O exception when writing to byte array", e);
- }
-
- // should really associate this channelId to the session
- byte[] channelName = output.toByteArray();
-
- response = methodRegistry.createChannelOpenOkBody(channelName);
- }
- else
- {
- throw new AMQException(AMQConstant.INTERNAL_ERROR, "Got channel open for protocol version not catered for: " + pv, null);
- }
-
-
- session.writeFrame(response.generateFrame(channelId));
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionCloseMethodHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionCloseMethodHandler.java
deleted file mode 100644
index dade5d5f54..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionCloseMethodHandler.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.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;
-
-public class ConnectionCloseMethodHandler implements StateAwareMethodListener<ConnectionCloseBody>
-{
- private static final Logger _logger = Logger.getLogger(ConnectionCloseMethodHandler.class);
-
- private static ConnectionCloseMethodHandler _instance = new ConnectionCloseMethodHandler();
-
- public static ConnectionCloseMethodHandler getInstance()
- {
- return _instance;
- }
-
- private ConnectionCloseMethodHandler()
- {
- }
-
- public void methodReceived(AMQStateManager stateManager, ConnectionCloseBody body, int channelId) throws AMQException
- {
- AMQProtocolSession session = stateManager.getProtocolSession();
-
- if (_logger.isInfoEnabled())
- {
- _logger.info("ConnectionClose received with reply code/reply text " + body.getReplyCode() + "/" +
- body.getReplyText() + " for " + session);
- }
- try
- {
- session.closeSession();
- }
- catch (Exception e)
- {
- _logger.error("Error closing protocol session: " + e, e);
- }
-
- MethodRegistry methodRegistry = session.getMethodRegistry();
- ConnectionCloseOkBody responseBody = methodRegistry.createConnectionCloseOkBody();
- session.writeFrame(responseBody.generateFrame(channelId));
-
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionCloseOkMethodHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionCloseOkMethodHandler.java
deleted file mode 100644
index bc6e5ab403..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionCloseOkMethodHandler.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.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;
-import org.apache.qpid.server.state.StateAwareMethodListener;
-
-public class ConnectionCloseOkMethodHandler implements StateAwareMethodListener<ConnectionCloseOkBody>
-{
- private static final Logger _logger = Logger.getLogger(ConnectionCloseOkMethodHandler.class);
-
- private static ConnectionCloseOkMethodHandler _instance = new ConnectionCloseOkMethodHandler();
-
- public static ConnectionCloseOkMethodHandler getInstance()
- {
- return _instance;
- }
-
- private ConnectionCloseOkMethodHandler()
- {
- }
-
- public void methodReceived(AMQStateManager stateManager, ConnectionCloseOkBody body, int channelId) throws AMQException
- {
- AMQProtocolSession session = stateManager.getProtocolSession();
- //todo should this not do more than just log the method?
- _logger.info("Received Connection-close-ok");
-
- try
- {
- stateManager.changeState(AMQState.CONNECTION_CLOSED);
- session.closeSession();
- }
- catch (Exception e)
- {
- _logger.error("Error closing protocol session: " + e, e);
- }
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionOpenMethodHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionOpenMethodHandler.java
deleted file mode 100644
index 9a79467526..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionOpenMethodHandler.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.handler;
-
-import org.apache.log4j.Logger;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.AMQMethodBody;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.ConnectionOpenBody;
-import org.apache.qpid.framing.MethodRegistry;
-import org.apache.qpid.protocol.AMQConstant;
-import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.server.state.AMQState;
-import org.apache.qpid.server.state.AMQStateManager;
-import org.apache.qpid.server.state.StateAwareMethodListener;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-
-public class ConnectionOpenMethodHandler implements StateAwareMethodListener<ConnectionOpenBody>
-{
- private static final Logger _logger = Logger.getLogger(ConnectionOpenMethodHandler.class);
-
- private static ConnectionOpenMethodHandler _instance = new ConnectionOpenMethodHandler();
-
- public static ConnectionOpenMethodHandler getInstance()
- {
- return _instance;
- }
-
- private ConnectionOpenMethodHandler()
- {
- }
-
- private static AMQShortString generateClientID()
- {
- return new AMQShortString(Long.toString(System.currentTimeMillis()));
- }
-
- public void methodReceived(AMQStateManager stateManager, ConnectionOpenBody body, int channelId) throws AMQException
- {
- AMQProtocolSession session = stateManager.getProtocolSession();
-
- //ignore leading '/'
- String virtualHostName;
- if ((body.getVirtualHost() != null) && body.getVirtualHost().charAt(0) == '/')
- {
- virtualHostName = new StringBuilder(body.getVirtualHost().subSequence(1, body.getVirtualHost().length())).toString();
- }
- else
- {
- virtualHostName = body.getVirtualHost() == null ? null : String.valueOf(body.getVirtualHost());
- }
-
- VirtualHost virtualHost = stateManager.getVirtualHostRegistry().getVirtualHost(virtualHostName);
-
- if (virtualHost == null)
- {
- throw body.getConnectionException(AMQConstant.NOT_FOUND, "Unknown virtual host: '" + virtualHostName + "'");
- }
- else
- {
- // Check virtualhost access
- if (!virtualHost.getSecurityManager().accessVirtualhost(virtualHostName, session.getRemoteAddress()))
- {
- throw body.getConnectionException(AMQConstant.ACCESS_REFUSED, "Permission denied: '" + virtualHost.getName() + "'");
- }
-
- session.setVirtualHost(virtualHost);
-
- // See Spec (0.8.2). Section 3.1.2 Virtual Hosts
- if (session.getContextKey() == null)
- {
- session.setContextKey(generateClientID());
- }
-
- MethodRegistry methodRegistry = session.getMethodRegistry();
- AMQMethodBody responseBody = methodRegistry.createConnectionOpenOkBody(body.getVirtualHost());
-
- stateManager.changeState(AMQState.CONNECTION_OPEN);
-
- session.writeFrame(responseBody.generateFrame(channelId));
- }
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionSecureOkMethodHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionSecureOkMethodHandler.java
deleted file mode 100644
index d4b79134a2..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionSecureOkMethodHandler.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.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;
-import org.apache.qpid.framing.ConnectionSecureOkBody;
-import org.apache.qpid.framing.ConnectionTuneBody;
-import org.apache.qpid.framing.MethodRegistry;
-import org.apache.qpid.protocol.AMQConstant;
-import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-import org.apache.qpid.server.security.auth.AuthenticationResult;
-import org.apache.qpid.server.security.auth.manager.AuthenticationManager;
-import org.apache.qpid.server.security.auth.sasl.UsernamePrincipal;
-import org.apache.qpid.server.state.AMQState;
-import org.apache.qpid.server.state.AMQStateManager;
-import org.apache.qpid.server.state.StateAwareMethodListener;
-
-public class ConnectionSecureOkMethodHandler implements StateAwareMethodListener<ConnectionSecureOkBody>
-{
- private static final Logger _logger = Logger.getLogger(ConnectionSecureOkMethodHandler.class);
-
- private static ConnectionSecureOkMethodHandler _instance = new ConnectionSecureOkMethodHandler();
-
- public static ConnectionSecureOkMethodHandler getInstance()
- {
- return _instance;
- }
-
- private ConnectionSecureOkMethodHandler()
- {
- }
-
- public void methodReceived(AMQStateManager stateManager, ConnectionSecureOkBody body, int channelId) throws AMQException
- {
- AMQProtocolSession session = stateManager.getProtocolSession();
-
- AuthenticationManager authMgr = ApplicationRegistry.getInstance().getAuthenticationManager();
-
- SaslServer ss = session.getSaslServer();
- if (ss == null)
- {
- throw new AMQException("No SASL context set up in session");
- }
- MethodRegistry methodRegistry = session.getMethodRegistry();
- AuthenticationResult authResult = authMgr.authenticate(ss, body.getResponse());
- switch (authResult.status)
- {
- case ERROR:
- Exception cause = authResult.getCause();
-
- _logger.info("Authentication failed:" + (cause == null ? "" : cause.getMessage()));
-
- // This should be abstracted
- stateManager.changeState(AMQState.CONNECTION_CLOSING);
-
- ConnectionCloseBody connectionCloseBody =
- methodRegistry.createConnectionCloseBody(AMQConstant.NOT_ALLOWED.getCode(),
- AMQConstant.NOT_ALLOWED.getName(),
- body.getClazz(),
- body.getMethod());
-
- session.writeFrame(connectionCloseBody.generateFrame(0));
- disposeSaslServer(session);
- break;
- case SUCCESS:
- _logger.info("Connected as: " + ss.getAuthorizationID());
- stateManager.changeState(AMQState.CONNECTION_NOT_TUNED);
-
- ConnectionTuneBody tuneBody =
- methodRegistry.createConnectionTuneBody(ApplicationRegistry.getInstance().getConfiguration().getMaxChannelCount(),
- ConnectionStartOkMethodHandler.getConfiguredFrameSize(),
- ApplicationRegistry.getInstance().getConfiguration().getHeartBeatDelay());
- session.writeFrame(tuneBody.generateFrame(0));
- session.setAuthorizedID(new UsernamePrincipal(ss.getAuthorizationID()));
- disposeSaslServer(session);
- break;
- case CONTINUE:
- stateManager.changeState(AMQState.CONNECTION_NOT_AUTH);
-
- ConnectionSecureBody secureBody = methodRegistry.createConnectionSecureBody(authResult.challenge);
- session.writeFrame(secureBody.generateFrame(0));
- }
- }
-
- private void disposeSaslServer(AMQProtocolSession ps)
- {
- SaslServer ss = ps.getSaslServer();
- if (ss != null)
- {
- ps.setSaslServer(null);
- try
- {
- ss.dispose();
- }
- catch (SaslException e)
- {
- _logger.error("Error disposing of Sasl server: " + e);
- }
- }
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionStartOkMethodHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionStartOkMethodHandler.java
deleted file mode 100644
index 4442f969c4..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionStartOkMethodHandler.java
+++ /dev/null
@@ -1,162 +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.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;
-import org.apache.qpid.framing.ConnectionStartOkBody;
-import org.apache.qpid.framing.ConnectionTuneBody;
-import org.apache.qpid.framing.MethodRegistry;
-import org.apache.qpid.protocol.AMQConstant;
-import org.apache.qpid.server.configuration.ServerConfiguration;
-import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-import org.apache.qpid.server.security.auth.AuthenticationResult;
-import org.apache.qpid.server.security.auth.manager.AuthenticationManager;
-import org.apache.qpid.server.security.auth.sasl.UsernamePrincipal;
-import org.apache.qpid.server.state.AMQState;
-import org.apache.qpid.server.state.AMQStateManager;
-import org.apache.qpid.server.state.StateAwareMethodListener;
-
-
-public class ConnectionStartOkMethodHandler implements StateAwareMethodListener<ConnectionStartOkBody>
-{
- private static final Logger _logger = Logger.getLogger(ConnectionStartOkMethodHandler.class);
-
- private static ConnectionStartOkMethodHandler _instance = new ConnectionStartOkMethodHandler();
-
- public static ConnectionStartOkMethodHandler getInstance()
- {
- return _instance;
- }
-
- private ConnectionStartOkMethodHandler()
- {
- }
-
- public void methodReceived(AMQStateManager stateManager, ConnectionStartOkBody body, int channelId) throws AMQException
- {
- AMQProtocolSession session = stateManager.getProtocolSession();
-
- _logger.info("SASL Mechanism selected: " + body.getMechanism());
- _logger.info("Locale selected: " + body.getLocale());
-
- AuthenticationManager authMgr = ApplicationRegistry.getInstance().getAuthenticationManager();
-
- SaslServer ss = null;
- try
- {
- ss = authMgr.createSaslServer(String.valueOf(body.getMechanism()), session.getLocalFQDN());
-
- if (ss == null)
- {
- throw body.getConnectionException(AMQConstant.RESOURCE_ERROR, "Unable to create SASL Server:" + body.getMechanism());
- }
-
- session.setSaslServer(ss);
-
- AuthenticationResult authResult = authMgr.authenticate(ss, body.getResponse());
-
- //save clientProperties
- if (session.getClientProperties() == null)
- {
- session.setClientProperties(body.getClientProperties());
- }
-
- MethodRegistry methodRegistry = session.getMethodRegistry();
-
- switch (authResult.status)
- {
- case ERROR:
- Exception cause = authResult.getCause();
-
- _logger.info("Authentication failed:" + (cause == null ? "" : cause.getMessage()));
-
- stateManager.changeState(AMQState.CONNECTION_CLOSING);
-
- ConnectionCloseBody closeBody =
- methodRegistry.createConnectionCloseBody(AMQConstant.NOT_ALLOWED.getCode(), // replyCode
- AMQConstant.NOT_ALLOWED.getName(),
- body.getClazz(),
- body.getMethod());
-
- session.writeFrame(closeBody.generateFrame(0));
- disposeSaslServer(session);
- break;
-
- case SUCCESS:
- _logger.info("Connected as: " + ss.getAuthorizationID());
- session.setAuthorizedID(new UsernamePrincipal(ss.getAuthorizationID()));
-
- stateManager.changeState(AMQState.CONNECTION_NOT_TUNED);
-
- ConnectionTuneBody tuneBody = methodRegistry.createConnectionTuneBody(ApplicationRegistry.getInstance().getConfiguration().getMaxChannelCount(),
- getConfiguredFrameSize(),
- ApplicationRegistry.getInstance().getConfiguration().getHeartBeatDelay());
- session.writeFrame(tuneBody.generateFrame(0));
- break;
- case CONTINUE:
- stateManager.changeState(AMQState.CONNECTION_NOT_AUTH);
-
- ConnectionSecureBody secureBody = methodRegistry.createConnectionSecureBody(authResult.challenge);
- session.writeFrame(secureBody.generateFrame(0));
- }
- }
- catch (SaslException e)
- {
- disposeSaslServer(session);
- throw new AMQException("SASL error: " + e, e);
- }
- }
-
- private void disposeSaslServer(AMQProtocolSession ps)
- {
- SaslServer ss = ps.getSaslServer();
- if (ss != null)
- {
- ps.setSaslServer(null);
- try
- {
- ss.dispose();
- }
- catch (SaslException e)
- {
- _logger.error("Error disposing of Sasl server: " + e);
- }
- }
- }
-
- static int getConfiguredFrameSize()
- {
- final ServerConfiguration config = ApplicationRegistry.getInstance().getConfiguration();
- final int framesize = config.getFrameSize();
- _logger.info("Framesize set to " + framesize);
- return framesize;
- }
-}
-
-
-
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionTuneOkMethodHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionTuneOkMethodHandler.java
deleted file mode 100644
index 1da2760639..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionTuneOkMethodHandler.java
+++ /dev/null
@@ -1,58 +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.handler;
-
-import org.apache.log4j.Logger;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.ConnectionTuneOkBody;
-import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.server.state.AMQState;
-import org.apache.qpid.server.state.AMQStateManager;
-import org.apache.qpid.server.state.StateAwareMethodListener;
-
-public class ConnectionTuneOkMethodHandler implements StateAwareMethodListener<ConnectionTuneOkBody>
-{
- private static final Logger _logger = Logger.getLogger(ConnectionTuneOkMethodHandler.class);
-
- private static ConnectionTuneOkMethodHandler _instance = new ConnectionTuneOkMethodHandler();
-
- public static ConnectionTuneOkMethodHandler getInstance()
- {
- return _instance;
- }
-
- public void methodReceived(AMQStateManager stateManager, ConnectionTuneOkBody body, int channelId) throws AMQException
- {
- AMQProtocolSession session = stateManager.getProtocolSession();
-
- if (_logger.isDebugEnabled())
- {
- _logger.debug(body);
- }
- stateManager.changeState(AMQState.CONNECTION_NOT_OPENED);
- session.initHeartbeats(body.getHeartbeat());
- session.setMaxFrameSize(body.getFrameMax());
-
- long maxChannelNumber = body.getChannelMax();
- //0 means no implied limit, except that forced by protocol limitations (0xFFFF)
- session.setMaximumNumberOfChannels( maxChannelNumber == 0 ? 0xFFFFL : maxChannelNumber);
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/ExchangeBoundHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/ExchangeBoundHandler.java
deleted file mode 100644
index ccd42204d9..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/ExchangeBoundHandler.java
+++ /dev/null
@@ -1,178 +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.handler;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.*;
-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.state.AMQStateManager;
-import org.apache.qpid.server.state.StateAwareMethodListener;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-
-/**
- * @author Apache Software Foundation
- *
- *
- */
-public class ExchangeBoundHandler implements StateAwareMethodListener<ExchangeBoundBody>
-{
- private static final ExchangeBoundHandler _instance = new ExchangeBoundHandler();
-
- public static final int OK = 0;
-
- public static final int EXCHANGE_NOT_FOUND = 1;
-
- public static final int QUEUE_NOT_FOUND = 2;
-
- public static final int NO_BINDINGS = 3;
-
- public static final int QUEUE_NOT_BOUND = 4;
-
- public static final int NO_QUEUE_BOUND_WITH_RK = 5;
-
- public static final int SPECIFIC_QUEUE_NOT_BOUND_WITH_RK = 6;
-
- public static ExchangeBoundHandler getInstance()
- {
- return _instance;
- }
-
- private ExchangeBoundHandler()
- {
- }
-
- public void methodReceived(AMQStateManager stateManager, ExchangeBoundBody body, int channelId) throws AMQException
- {
- AMQProtocolSession session = stateManager.getProtocolSession();
-
- VirtualHost virtualHost = session.getVirtualHost();
- QueueRegistry queueRegistry = virtualHost.getQueueRegistry();
- MethodRegistry methodRegistry = session.getMethodRegistry();
-
-
-
-
- AMQShortString exchangeName = body.getExchange();
- AMQShortString queueName = body.getQueue();
- AMQShortString routingKey = body.getRoutingKey();
- if (exchangeName == null)
- {
- throw new AMQException("Exchange exchange must not be null");
- }
- Exchange exchange = virtualHost.getExchangeRegistry().getExchange(exchangeName);
- ExchangeBoundOkBody response;
- if (exchange == null)
- {
-
-
- response = methodRegistry.createExchangeBoundOkBody(EXCHANGE_NOT_FOUND,
- new AMQShortString("Exchange " + exchangeName + " not found"));
- }
- else if (routingKey == null)
- {
- if (queueName == null)
- {
- if (exchange.hasBindings())
- {
- response = methodRegistry.createExchangeBoundOkBody(OK, null);
- }
- else
- {
-
- response = methodRegistry.createExchangeBoundOkBody(NO_BINDINGS, // replyCode
- null); // replyText
- }
- }
- else
- {
-
- AMQQueue queue = queueRegistry.getQueue(queueName);
- if (queue == null)
- {
-
- response = methodRegistry.createExchangeBoundOkBody(QUEUE_NOT_FOUND, // replyCode
- new AMQShortString("Queue " + queueName + " not found")); // replyText
- }
- else
- {
- if (exchange.isBound(queue))
- {
-
- response = methodRegistry.createExchangeBoundOkBody(OK, // replyCode
- null); // replyText
- }
- else
- {
-
- response = methodRegistry.createExchangeBoundOkBody(QUEUE_NOT_BOUND, // replyCode
- new AMQShortString("Queue " + queueName + " not bound to exchange " + exchangeName)); // replyText
- }
- }
- }
- }
- else if (queueName != null)
- {
- AMQQueue queue = queueRegistry.getQueue(queueName);
- if (queue == null)
- {
-
- response = methodRegistry.createExchangeBoundOkBody(QUEUE_NOT_FOUND, // replyCode
- new AMQShortString("Queue " + queueName + " not found")); // replyText
- }
- else
- {
- if (exchange.isBound(body.getRoutingKey(), queue))
- {
-
- response = methodRegistry.createExchangeBoundOkBody(OK, // replyCode
- null); // replyText
- }
- else
- {
-
- response = methodRegistry.createExchangeBoundOkBody(SPECIFIC_QUEUE_NOT_BOUND_WITH_RK, // replyCode
- new AMQShortString("Queue " + queueName + " not bound with routing key " +
- body.getRoutingKey() + " to exchange " + exchangeName)); // replyText
- }
- }
- }
- else
- {
- if (exchange.isBound(body.getRoutingKey()))
- {
-
- response = methodRegistry.createExchangeBoundOkBody(OK, // replyCode
- null); // replyText
- }
- else
- {
-
- response = methodRegistry.createExchangeBoundOkBody(NO_QUEUE_BOUND_WITH_RK, // replyCode
- new AMQShortString("No queue bound with routing key " + body.getRoutingKey() +
- " to exchange " + exchangeName)); // replyText
- }
- }
- session.writeFrame(response.generateFrame(channelId));
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/ExchangeDeclareHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/ExchangeDeclareHandler.java
deleted file mode 100644
index 98a0d33487..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/ExchangeDeclareHandler.java
+++ /dev/null
@@ -1,108 +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.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.protocol.AMQConstant;
-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.protocol.AMQProtocolSession;
-import org.apache.qpid.server.state.AMQStateManager;
-import org.apache.qpid.server.state.StateAwareMethodListener;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-
-public class ExchangeDeclareHandler implements StateAwareMethodListener<ExchangeDeclareBody>
-{
- private static final Logger _logger = Logger.getLogger(ExchangeDeclareHandler.class);
-
- private static final ExchangeDeclareHandler _instance = new ExchangeDeclareHandler();
-
- public static ExchangeDeclareHandler getInstance()
- {
- return _instance;
- }
-
- private ExchangeDeclareHandler()
- {
- }
-
- public void methodReceived(AMQStateManager stateManager, ExchangeDeclareBody body, int channelId) throws AMQException
- {
- AMQProtocolSession session = stateManager.getProtocolSession();
- VirtualHost virtualHost = session.getVirtualHost();
- ExchangeRegistry exchangeRegistry = virtualHost.getExchangeRegistry();
- ExchangeFactory exchangeFactory = virtualHost.getExchangeFactory();
-
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Request to declare exchange of type " + body.getType() + " with name " + body.getExchange());
- }
-
- synchronized(exchangeRegistry)
- {
- Exchange exchange = exchangeRegistry.getExchange(body.getExchange());
-
- if (exchange == null)
- {
- if(body.getPassive() && ((body.getType() == null) || body.getType().length() ==0))
- {
- throw body.getChannelException(AMQConstant.NOT_FOUND, "Unknown exchange: " + body.getExchange());
- }
- else
- {
- try
- {
- exchange = exchangeFactory.createExchange(body.getExchange() == null ? null : body.getExchange().intern(),
- body.getType() == null ? null : body.getType().intern(),
- body.getDurable(),
- body.getPassive(), body.getTicket());
- exchangeRegistry.registerExchange(exchange);
-
- if (exchange.isDurable())
- {
- virtualHost.getDurableConfigurationStore().createExchange(exchange);
- }
- }
- catch(AMQUnknownExchangeType e)
- {
- throw body.getConnectionException(AMQConstant.COMMAND_INVALID, "Unknown exchange: " + body.getExchange(),e);
- }
- }
- }
- else if (!exchange.getTypeShortString().equals(body.getType()))
- {
-
- throw new AMQConnectionException(AMQConstant.NOT_ALLOWED, "Attempt to redeclare exchange: " + body.getExchange() + " of type " + exchange.getTypeShortString() + " to " + body.getType() +".",body.getClazz(), body.getMethod(),body.getMajor(),body.getMinor(),null);
- }
- }
- if(!body.getNowait())
- {
- MethodRegistry methodRegistry = session.getMethodRegistry();
- AMQMethodBody responseBody = methodRegistry.createExchangeDeclareOkBody();
- session.writeFrame(responseBody.generateFrame(channelId));
- }
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/ExchangeDeleteHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/ExchangeDeleteHandler.java
deleted file mode 100644
index 586aaf9336..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/ExchangeDeleteHandler.java
+++ /dev/null
@@ -1,71 +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.handler;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.ExchangeDeleteBody;
-import org.apache.qpid.framing.ExchangeDeleteOkBody;
-import org.apache.qpid.protocol.AMQConstant;
-import org.apache.qpid.server.exchange.ExchangeInUseException;
-import org.apache.qpid.server.exchange.ExchangeRegistry;
-import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.server.state.AMQStateManager;
-import org.apache.qpid.server.state.StateAwareMethodListener;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-
-public class ExchangeDeleteHandler implements StateAwareMethodListener<ExchangeDeleteBody>
-{
- private static final ExchangeDeleteHandler _instance = new ExchangeDeleteHandler();
-
- public static ExchangeDeleteHandler getInstance()
- {
- return _instance;
- }
-
- private ExchangeDeleteHandler()
- {
- }
-
- public void methodReceived(AMQStateManager stateManager, ExchangeDeleteBody body, int channelId) throws AMQException
- {
- AMQProtocolSession session = stateManager.getProtocolSession();
- VirtualHost virtualHost = session.getVirtualHost();
- ExchangeRegistry exchangeRegistry = virtualHost.getExchangeRegistry();
-
- try
- {
- if(exchangeRegistry.getExchange(body.getExchange()) == null)
- {
- throw body.getChannelException(AMQConstant.NOT_FOUND, "No such exchange: " + body.getExchange());
- }
- exchangeRegistry.unregisterExchange(body.getExchange(), body.getIfUnused());
-
- ExchangeDeleteOkBody responseBody = session.getMethodRegistry().createExchangeDeleteOkBody();
-
- session.writeFrame(responseBody.generateFrame(channelId));
- }
- catch (ExchangeInUseException e)
- {
- throw body.getChannelException(AMQConstant.IN_USE, "Exchange in use");
- // TODO: sort out consistent channel close mechanism that does all clean up etc.
- }
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/OnCurrentThreadExecutor.java b/java/broker/src/main/java/org/apache/qpid/server/handler/OnCurrentThreadExecutor.java
deleted file mode 100644
index ac516b6133..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/OnCurrentThreadExecutor.java
+++ /dev/null
@@ -1,34 +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.handler;
-
-import java.util.concurrent.Executor;
-
-/**
- * An executor that executes the task on the current thread.
- */
-public class OnCurrentThreadExecutor implements Executor
-{
- public void execute(Runnable command)
- {
- command.run();
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/QueueBindHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/QueueBindHandler.java
deleted file mode 100644
index 0eb69e4b16..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/QueueBindHandler.java
+++ /dev/null
@@ -1,159 +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.handler;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.AMQMethodBody;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.FieldTable;
-import org.apache.qpid.framing.MethodRegistry;
-import org.apache.qpid.framing.QueueBindBody;
-import org.apache.qpid.protocol.AMQConstant;
-import org.apache.qpid.server.AMQChannel;
-import org.apache.qpid.server.binding.Binding;
-import org.apache.qpid.server.exchange.Exchange;
-import org.apache.qpid.server.exchange.ExchangeRegistry;
-import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.server.protocol.AMQSessionModel;
-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 java.util.Map;
-
-public class QueueBindHandler implements StateAwareMethodListener<QueueBindBody>
-{
- private static final Logger _log = Logger.getLogger(QueueBindHandler.class);
-
- private static final QueueBindHandler _instance = new QueueBindHandler();
-
- public static QueueBindHandler getInstance()
- {
- return _instance;
- }
-
- private QueueBindHandler()
- {
- }
-
- public void methodReceived(AMQStateManager stateManager, QueueBindBody body, int channelId) throws AMQException
- {
- AMQProtocolSession protocolConnection = stateManager.getProtocolSession();
- VirtualHost virtualHost = protocolConnection.getVirtualHost();
- ExchangeRegistry exchangeRegistry = virtualHost.getExchangeRegistry();
- QueueRegistry queueRegistry = virtualHost.getQueueRegistry();
-
- final AMQQueue queue;
- final AMQShortString routingKey;
-
- if (body.getQueue() == null)
- {
- AMQChannel channel = protocolConnection.getChannel(channelId);
-
- if (channel == null)
- {
- throw body.getChannelNotFoundException(channelId);
- }
-
- queue = channel.getDefaultQueue();
-
- if (queue == null)
- {
- throw body.getChannelException(AMQConstant.NOT_FOUND, "No default queue defined on channel and queue was null");
- }
-
- if (body.getRoutingKey() == null)
- {
- routingKey = queue.getNameShortString();
- }
- else
- {
- routingKey = body.getRoutingKey().intern();
- }
- }
- else
- {
- queue = queueRegistry.getQueue(body.getQueue());
- routingKey = body.getRoutingKey() == null ? AMQShortString.EMPTY_STRING : body.getRoutingKey().intern();
- }
-
- if (queue == null)
- {
- throw body.getChannelException(AMQConstant.NOT_FOUND, "Queue " + body.getQueue() + " does not exist.");
- }
- final Exchange exch = exchangeRegistry.getExchange(body.getExchange());
- if (exch == null)
- {
- throw body.getChannelException(AMQConstant.NOT_FOUND, "Exchange " + body.getExchange() + " does not exist.");
- }
-
-
- try
- {
- if (queue.isExclusive() && !queue.isDurable())
- {
- AMQSessionModel session = queue.getExclusiveOwningSession();
- if (session == null || session.getConnectionModel() != protocolConnection)
- {
- throw body.getConnectionException(AMQConstant.NOT_ALLOWED,
- "Queue " + queue.getNameShortString() + " is exclusive, but not created on this Connection.");
- }
- }
-
- if (!exch.isBound(routingKey, body.getArguments(), queue))
- {
- String bindingKey = String.valueOf(routingKey);
- Map<String,Object> arguments = FieldTable.convertToMap(body.getArguments());
-
- if(!virtualHost.getBindingFactory().addBinding(bindingKey, queue, exch, arguments))
- {
- Binding oldBinding = virtualHost.getBindingFactory().getBinding(bindingKey, queue, exch, arguments);
-
- Map<String, Object> oldArgs = oldBinding.getArguments();
- if((oldArgs == null && !arguments.isEmpty()) || (oldArgs != null && !oldArgs.equals(arguments)))
- {
- virtualHost.getBindingFactory().replaceBinding(bindingKey, queue, exch, arguments);
- }
- }
- }
- }
- catch (AMQException e)
- {
- throw body.getChannelException(AMQConstant.CHANNEL_ERROR, e.toString());
- }
-
- if (_log.isInfoEnabled())
- {
- _log.info("Binding queue " + queue + " to exchange " + exch + " with routing key " + routingKey);
- }
- if (!body.getNowait())
- {
- MethodRegistry methodRegistry = protocolConnection.getMethodRegistry();
- AMQMethodBody responseBody = methodRegistry.createQueueBindOkBody();
- protocolConnection.writeFrame(responseBody.generateFrame(channelId));
-
- }
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/QueueDeclareHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/QueueDeclareHandler.java
deleted file mode 100644
index 8939cfa334..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/QueueDeclareHandler.java
+++ /dev/null
@@ -1,254 +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.handler;
-
-import java.util.UUID;
-import java.util.Collections;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import org.apache.log4j.Logger;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.MethodRegistry;
-import org.apache.qpid.framing.QueueDeclareBody;
-import org.apache.qpid.framing.QueueDeclareOkBody;
-import org.apache.qpid.protocol.AMQConstant;
-import org.apache.qpid.server.AMQChannel;
-import org.apache.qpid.server.exchange.Exchange;
-import org.apache.qpid.server.exchange.ExchangeRegistry;
-import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.server.protocol.AMQSessionModel;
-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.state.AMQStateManager;
-import org.apache.qpid.server.state.StateAwareMethodListener;
-import org.apache.qpid.server.store.DurableConfigurationStore;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-
-public class QueueDeclareHandler implements StateAwareMethodListener<QueueDeclareBody>
-{
- private static final Logger _logger = Logger.getLogger(QueueDeclareHandler.class);
-
- private static final QueueDeclareHandler _instance = new QueueDeclareHandler();
-
- public static QueueDeclareHandler getInstance()
- {
- return _instance;
- }
-
- public boolean autoRegister = ApplicationRegistry.getInstance().getConfiguration().getQueueAutoRegister();
-
- private final AtomicInteger _counter = new AtomicInteger();
-
- public void methodReceived(AMQStateManager stateManager, QueueDeclareBody body, int channelId) throws AMQException
- {
- final AMQProtocolSession protocolConnection = stateManager.getProtocolSession();
- final AMQSessionModel session = protocolConnection.getChannel(channelId);
- VirtualHost virtualHost = protocolConnection.getVirtualHost();
- ExchangeRegistry exchangeRegistry = virtualHost.getExchangeRegistry();
- QueueRegistry queueRegistry = virtualHost.getQueueRegistry();
- DurableConfigurationStore store = virtualHost.getDurableConfigurationStore();
-
- final AMQShortString queueName;
-
- // if we aren't given a queue name, we create one which we return to the client
- if ((body.getQueue() == null) || (body.getQueue().length() == 0))
- {
- queueName = createName();
- }
- else
- {
- queueName = body.getQueue().intern();
- }
-
- AMQQueue queue;
-
- //TODO: do we need to check that the queue already exists with exactly the same "configuration"?
-
- synchronized (queueRegistry)
- {
- queue = queueRegistry.getQueue(queueName);
-
- AMQSessionModel owningSession = null;
-
- if (queue != null)
- {
- owningSession = queue.getExclusiveOwningSession();
- }
-
- if (queue == null)
- {
- if (body.getPassive())
- {
- String msg = "Queue: " + queueName + " not found on VirtualHost(" + virtualHost + ").";
- throw body.getChannelException(AMQConstant.NOT_FOUND, msg);
- }
- else
- {
- queue = createQueue(queueName, body, virtualHost, protocolConnection);
- queue.setPrincipalHolder(protocolConnection);
- if (queue.isDurable() && !queue.isAutoDelete())
- {
- store.createQueue(queue, body.getArguments());
- }
- if(body.getAutoDelete())
- {
- queue.setDeleteOnNoConsumers(true);
- }
- queueRegistry.registerQueue(queue);
- if (body.getExclusive())
- {
- queue.setExclusiveOwningSession(protocolConnection.getChannel(channelId));
- queue.setPrincipalHolder(protocolConnection);
-
- if(!body.getDurable())
- {
- final AMQQueue q = queue;
- final AMQProtocolSession.Task sessionCloseTask = new AMQProtocolSession.Task()
- {
- public void doTask(AMQProtocolSession session) throws AMQException
- {
- q.setExclusiveOwningSession(null);
- }
- };
- protocolConnection.addSessionCloseTask(sessionCloseTask);
- queue.addQueueDeleteTask(new AMQQueue.Task() {
- public void doTask(AMQQueue queue) throws AMQException
- {
- protocolConnection.removeSessionCloseTask(sessionCloseTask);
- }
- });
- }
- }
- if (autoRegister)
- {
- Exchange defaultExchange = exchangeRegistry.getDefaultExchange();
-
- virtualHost.getBindingFactory().addBinding(String.valueOf(queueName), queue, defaultExchange, Collections.EMPTY_MAP);
- _logger.info("Queue " + queueName + " bound to default exchange(" + defaultExchange.getNameShortString() + ")");
- }
- }
- }
- else if (queue.isExclusive() && !queue.isDurable() && (owningSession == null || owningSession.getConnectionModel() != protocolConnection))
- {
- throw body.getConnectionException(AMQConstant.NOT_ALLOWED,
- "Queue " + queue.getNameShortString() + " is exclusive, but not created on this Connection.");
- }
- else if(!body.getPassive() && ((queue.isExclusive()) != body.getExclusive()))
- {
-
- throw body.getChannelException(AMQConstant.ALREADY_EXISTS,
- "Cannot re-declare queue '" + queue.getNameShortString() + "' with different exclusivity (was: "
- + queue.isExclusive() + " requested " + body.getExclusive() + ")");
- }
- else if (!body.getPassive() && body.getExclusive() && !(queue.isDurable() ? String.valueOf(queue.getOwner()).equals(session.getClientID()) : (owningSession == null || owningSession.getConnectionModel() == protocolConnection)))
- {
- throw body.getChannelException(AMQConstant.ALREADY_EXISTS, "Cannot declare queue('" + queueName + "'), "
- + "as exclusive queue with same name "
- + "declared on another client ID('"
- + queue.getOwner() + "') your clientID('" + session.getClientID() + "')");
-
- }
- else if(!body.getPassive() && queue.isAutoDelete() != body.getAutoDelete())
- {
- throw body.getChannelException(AMQConstant.ALREADY_EXISTS,
- "Cannot re-declare queue '" + queue.getNameShortString() + "' with different auto-delete (was: "
- + queue.isAutoDelete() + " requested " + body.getAutoDelete() + ")");
- }
- else if(!body.getPassive() && queue.isDurable() != body.getDurable())
- {
- throw body.getChannelException(AMQConstant.ALREADY_EXISTS,
- "Cannot re-declare queue '" + queue.getNameShortString() + "' with different durability (was: "
- + queue.isDurable() + " requested " + body.getDurable() + ")");
- }
-
-
- AMQChannel channel = protocolConnection.getChannel(channelId);
-
- if (channel == null)
- {
- throw body.getChannelNotFoundException(channelId);
- }
-
- //set this as the default queue on the channel:
- channel.setDefaultQueue(queue);
- }
-
- if (!body.getNowait())
- {
- MethodRegistry methodRegistry = protocolConnection.getMethodRegistry();
- QueueDeclareOkBody responseBody =
- methodRegistry.createQueueDeclareOkBody(queueName,
- queue.getMessageCount(),
- queue.getConsumerCount());
- protocolConnection.writeFrame(responseBody.generateFrame(channelId));
-
- _logger.info("Queue " + queueName + " declared successfully");
- }
- }
-
- protected AMQShortString createName()
- {
- return new AMQShortString("tmp_" + UUID.randomUUID());
- }
-
- protected AMQQueue createQueue(final AMQShortString queueName,
- QueueDeclareBody body,
- VirtualHost virtualHost,
- final AMQProtocolSession session)
- throws AMQException
- {
- final QueueRegistry registry = virtualHost.getQueueRegistry();
- AMQShortString owner = body.getExclusive() ? session.getContextKey() : null;
-
- final AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(queueName, body.getDurable(), owner, body.getAutoDelete(),
- body.getExclusive(),virtualHost, body.getArguments());
-
- if (body.getExclusive() && !body.getDurable())
- {
- final AMQProtocolSession.Task deleteQueueTask =
- new AMQProtocolSession.Task()
- {
- public void doTask(AMQProtocolSession session) throws AMQException
- {
- if (registry.getQueue(queueName) == queue)
- {
- queue.delete();
- }
- }
- };
-
- session.addSessionCloseTask(deleteQueueTask);
-
- queue.addQueueDeleteTask(new AMQQueue.Task()
- {
- public void doTask(AMQQueue queue)
- {
- session.removeSessionCloseTask(deleteQueueTask);
- }
- });
- }
-
- return queue;
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/QueueDeleteHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/QueueDeleteHandler.java
deleted file mode 100644
index da52268e52..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/QueueDeleteHandler.java
+++ /dev/null
@@ -1,125 +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.handler;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.QueueDeleteBody;
-import org.apache.qpid.framing.QueueDeleteOkBody;
-import org.apache.qpid.framing.MethodRegistry;
-import org.apache.qpid.protocol.AMQConstant;
-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.state.AMQStateManager;
-import org.apache.qpid.server.state.StateAwareMethodListener;
-import org.apache.qpid.server.store.DurableConfigurationStore;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-import org.apache.qpid.server.AMQChannel;
-
-public class QueueDeleteHandler implements StateAwareMethodListener<QueueDeleteBody>
-{
- private static final QueueDeleteHandler _instance = new QueueDeleteHandler();
-
- public static QueueDeleteHandler getInstance()
- {
- return _instance;
- }
-
- private final boolean _failIfNotFound;
-
- public QueueDeleteHandler()
- {
- this(true);
- }
-
- public QueueDeleteHandler(boolean failIfNotFound)
- {
- _failIfNotFound = failIfNotFound;
-
- }
-
- public void methodReceived(AMQStateManager stateManager, QueueDeleteBody body, int channelId) throws AMQException
- {
- AMQProtocolSession protocolConnection = stateManager.getProtocolSession();
- VirtualHost virtualHost = protocolConnection.getVirtualHost();
- QueueRegistry queueRegistry = virtualHost.getQueueRegistry();
- DurableConfigurationStore store = virtualHost.getDurableConfigurationStore();
-
- AMQQueue queue;
- if (body.getQueue() == null)
- {
- AMQChannel channel = protocolConnection.getChannel(channelId);
-
- if (channel == null)
- {
- throw body.getChannelNotFoundException(channelId);
- }
-
- //get the default queue on the channel:
- queue = channel.getDefaultQueue();
- }
- else
- {
- queue = queueRegistry.getQueue(body.getQueue());
- }
-
- if (queue == null)
- {
- if (_failIfNotFound)
- {
- throw body.getChannelException(AMQConstant.NOT_FOUND, "Queue " + body.getQueue() + " does not exist.");
- }
- }
- else
- {
- if (body.getIfEmpty() && !queue.isEmpty())
- {
- throw body.getChannelException(AMQConstant.IN_USE, "Queue: " + body.getQueue() + " is not empty.");
- }
- else if (body.getIfUnused() && !queue.isUnused())
- {
- // TODO - Error code
- throw body.getChannelException(AMQConstant.IN_USE, "Queue: " + body.getQueue() + " is still used.");
- }
- else
- {
- AMQSessionModel session = queue.getExclusiveOwningSession();
- if (queue.isExclusive() && !queue.isDurable() && (session == null || session.getConnectionModel() != protocolConnection))
- {
- throw body.getConnectionException(AMQConstant.NOT_ALLOWED,
- "Queue " + queue.getNameShortString() + " is exclusive, but not created on this Connection.");
- }
-
- int purged = queue.delete();
-
- if (queue.isDurable())
- {
- store.removeQueue(queue);
- }
-
- MethodRegistry methodRegistry = protocolConnection.getMethodRegistry();
- QueueDeleteOkBody responseBody = methodRegistry.createQueueDeleteOkBody(purged);
- protocolConnection.writeFrame(responseBody.generateFrame(channelId));
- }
- }
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/QueuePurgeHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/QueuePurgeHandler.java
deleted file mode 100644
index 759eec0129..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/QueuePurgeHandler.java
+++ /dev/null
@@ -1,123 +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.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.protocol.AMQConstant;
-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.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<QueuePurgeBody>
-{
- private static final QueuePurgeHandler _instance = new QueuePurgeHandler();
-
- public static QueuePurgeHandler getInstance()
- {
- return _instance;
- }
-
- private final boolean _failIfNotFound;
-
- public QueuePurgeHandler()
- {
- this(true);
- }
-
- public QueuePurgeHandler(boolean failIfNotFound)
- {
- _failIfNotFound = failIfNotFound;
- }
-
- public void methodReceived(AMQStateManager stateManager, QueuePurgeBody body, int channelId) throws AMQException
- {
- AMQProtocolSession protocolConnection = stateManager.getProtocolSession();
- VirtualHost virtualHost = protocolConnection.getVirtualHost();
- QueueRegistry queueRegistry = virtualHost.getQueueRegistry();
-
- AMQChannel channel = protocolConnection.getChannel(channelId);
-
-
- AMQQueue queue;
- if(body.getQueue() == null)
- {
-
- if (channel == null)
- {
- throw body.getChannelNotFoundException(channelId);
- }
-
- //get the default queue on the channel:
- queue = channel.getDefaultQueue();
-
- if(queue == null)
- {
- if(_failIfNotFound)
- {
- throw body.getConnectionException(AMQConstant.NOT_ALLOWED,"No queue specified.");
- }
- }
- }
- else
- {
- queue = queueRegistry.getQueue(body.getQueue());
- }
-
- if(queue == null)
- {
- if(_failIfNotFound)
- {
- throw body.getChannelException(AMQConstant.NOT_FOUND, "Queue " + body.getQueue() + " does not exist.");
- }
- }
- else
- {
- AMQSessionModel session = queue.getExclusiveOwningSession();
-
- if (queue.isExclusive() && (session == null || session.getConnectionModel() != protocolConnection))
- {
- throw body.getConnectionException(AMQConstant.NOT_ALLOWED,
- "Queue is exclusive, but not created on this Connection.");
- }
-
- long purged = queue.clearQueue();
-
-
- if(!body.getNowait())
- {
-
- MethodRegistry methodRegistry = protocolConnection.getMethodRegistry();
- AMQMethodBody responseBody = methodRegistry.createQueuePurgeOkBody(purged);
- protocolConnection.writeFrame(responseBody.generateFrame(channelId));
-
- }
- }
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/QueueUnbindHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/QueueUnbindHandler.java
deleted file mode 100644
index 8391a4b184..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/QueueUnbindHandler.java
+++ /dev/null
@@ -1,123 +0,0 @@
-package org.apache.qpid.server.handler;
-/*
- *
- * 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.log4j.Logger;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.AMQMethodBody;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.FieldTable;
-import org.apache.qpid.framing.QueueUnbindBody;
-import org.apache.qpid.framing.amqp_0_9.MethodRegistry_0_9;
-import org.apache.qpid.protocol.AMQConstant;
-import org.apache.qpid.server.AMQChannel;
-import org.apache.qpid.server.exchange.Exchange;
-import org.apache.qpid.server.exchange.ExchangeRegistry;
-import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.server.queue.AMQQueue;
-import org.apache.qpid.server.queue.QueueRegistry;
-import org.apache.qpid.server.state.AMQStateManager;
-import org.apache.qpid.server.state.StateAwareMethodListener;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-
-public class QueueUnbindHandler implements StateAwareMethodListener<QueueUnbindBody>
-{
- private static final Logger _log = Logger.getLogger(QueueUnbindHandler.class);
-
- private static final QueueUnbindHandler _instance = new QueueUnbindHandler();
-
- public static QueueUnbindHandler getInstance()
- {
- return _instance;
- }
-
- private QueueUnbindHandler()
- {
- }
-
- public void methodReceived(AMQStateManager stateManager, QueueUnbindBody body, int channelId) throws AMQException
- {
- AMQProtocolSession session = stateManager.getProtocolSession();
- VirtualHost virtualHost = session.getVirtualHost();
- ExchangeRegistry exchangeRegistry = virtualHost.getExchangeRegistry();
- QueueRegistry queueRegistry = virtualHost.getQueueRegistry();
-
-
- final AMQQueue queue;
- final AMQShortString routingKey;
-
- if (body.getQueue() == null)
- {
- AMQChannel channel = session.getChannel(channelId);
-
- if (channel == null)
- {
- throw body.getChannelNotFoundException(channelId);
- }
-
- queue = channel.getDefaultQueue();
-
- if (queue == null)
- {
- throw body.getChannelException(AMQConstant.NOT_FOUND, "No default queue defined on channel and queue was null");
- }
-
- routingKey = body.getRoutingKey() == null ? null : body.getRoutingKey().intern();
-
- }
- else
- {
- queue = queueRegistry.getQueue(body.getQueue());
- routingKey = body.getRoutingKey() == null ? null : body.getRoutingKey().intern();
- }
-
- if (queue == null)
- {
- throw body.getChannelException(AMQConstant.NOT_FOUND, "Queue " + body.getQueue() + " does not exist.");
- }
- final Exchange exch = exchangeRegistry.getExchange(body.getExchange());
- if (exch == null)
- {
- throw body.getChannelException(AMQConstant.NOT_FOUND, "Exchange " + body.getExchange() + " does not exist.");
- }
-
- if(virtualHost.getBindingFactory().getBinding(String.valueOf(routingKey), queue, exch, FieldTable.convertToMap(body.getArguments())) == null)
- {
- throw body.getChannelException(AMQConstant.NOT_FOUND,"No such binding");
- }
- else
- {
- virtualHost.getBindingFactory().removeBinding(String.valueOf(routingKey), queue, exch, FieldTable.convertToMap(body.getArguments()));
- }
-
-
- if (_log.isInfoEnabled())
- {
- _log.info("Binding queue " + queue + " to exchange " + exch + " with routing key " + routingKey);
- }
-
- MethodRegistry_0_9 methodRegistry = (MethodRegistry_0_9) session.getMethodRegistry();
- AMQMethodBody responseBody = methodRegistry.createQueueUnbindOkBody();
- session.writeFrame(responseBody.generateFrame(channelId));
-
-
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/ServerMethodDispatcherImpl.java b/java/broker/src/main/java/org/apache/qpid/server/handler/ServerMethodDispatcherImpl.java
deleted file mode 100644
index e290afcde3..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/ServerMethodDispatcherImpl.java
+++ /dev/null
@@ -1,574 +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.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;
-
-public class ServerMethodDispatcherImpl implements MethodDispatcher
-{
- private final AMQStateManager _stateManager;
-
- private static interface DispatcherFactory
- {
- public MethodDispatcher createMethodDispatcher(AMQStateManager stateManager);
- }
-
- private static final Map<ProtocolVersion, DispatcherFactory> _dispatcherFactories =
- new HashMap<ProtocolVersion, DispatcherFactory>();
-
-
- static
- {
- _dispatcherFactories.put(ProtocolVersion.v8_0,
- new DispatcherFactory()
- {
- public MethodDispatcher createMethodDispatcher(AMQStateManager stateManager)
- {
- return new ServerMethodDispatcherImpl_8_0(stateManager);
- }
- });
-
- _dispatcherFactories.put(ProtocolVersion.v0_9,
- new DispatcherFactory()
- {
- public MethodDispatcher createMethodDispatcher(AMQStateManager stateManager)
- {
- return new ServerMethodDispatcherImpl_0_9(stateManager);
- }
- });
- _dispatcherFactories.put(ProtocolVersion.v0_91,
- new DispatcherFactory()
- {
- public MethodDispatcher createMethodDispatcher(AMQStateManager stateManager)
- {
- return new ServerMethodDispatcherImpl_0_91(stateManager);
- }
- });
-
- }
-
-
- private static final AccessRequestHandler _accessRequestHandler = AccessRequestHandler.getInstance();
- private static final ChannelCloseHandler _channelCloseHandler = ChannelCloseHandler.getInstance();
- private static final ChannelOpenHandler _channelOpenHandler = ChannelOpenHandler.getInstance();
- private static final ChannelCloseOkHandler _channelCloseOkHandler = ChannelCloseOkHandler.getInstance();
- private static final ConnectionCloseMethodHandler _connectionCloseMethodHandler = ConnectionCloseMethodHandler.getInstance();
- private static final ConnectionCloseOkMethodHandler _connectionCloseOkMethodHandler = ConnectionCloseOkMethodHandler.getInstance();
- private static final ConnectionOpenMethodHandler _connectionOpenMethodHandler = ConnectionOpenMethodHandler.getInstance();
- private static final ConnectionTuneOkMethodHandler _connectionTuneOkMethodHandler = ConnectionTuneOkMethodHandler.getInstance();
- private static final ConnectionSecureOkMethodHandler _connectionSecureOkMethodHandler = ConnectionSecureOkMethodHandler.getInstance();
- private static final ConnectionStartOkMethodHandler _connectionStartOkMethodHandler = ConnectionStartOkMethodHandler.getInstance();
- private static final ExchangeDeclareHandler _exchangeDeclareHandler = ExchangeDeclareHandler.getInstance();
- private static final ExchangeDeleteHandler _exchangeDeleteHandler = ExchangeDeleteHandler.getInstance();
- private static final ExchangeBoundHandler _exchangeBoundHandler = ExchangeBoundHandler.getInstance();
- private static final BasicAckMethodHandler _basicAckMethodHandler = BasicAckMethodHandler.getInstance();
- private static final BasicRecoverMethodHandler _basicRecoverMethodHandler = BasicRecoverMethodHandler.getInstance();
- private static final BasicConsumeMethodHandler _basicConsumeMethodHandler = BasicConsumeMethodHandler.getInstance();
- private static final BasicGetMethodHandler _basicGetMethodHandler = BasicGetMethodHandler.getInstance();
- private static final BasicCancelMethodHandler _basicCancelMethodHandler = BasicCancelMethodHandler.getInstance();
- private static final BasicPublishMethodHandler _basicPublishMethodHandler = BasicPublishMethodHandler.getInstance();
- private static final BasicQosHandler _basicQosHandler = BasicQosHandler.getInstance();
- private static final QueueBindHandler _queueBindHandler = QueueBindHandler.getInstance();
- private static final QueueDeclareHandler _queueDeclareHandler = QueueDeclareHandler.getInstance();
- private static final QueueDeleteHandler _queueDeleteHandler = QueueDeleteHandler.getInstance();
- private static final QueuePurgeHandler _queuePurgeHandler = QueuePurgeHandler.getInstance();
- private static final ChannelFlowHandler _channelFlowHandler = ChannelFlowHandler.getInstance();
- private static final TxSelectHandler _txSelectHandler = TxSelectHandler.getInstance();
- private static final TxCommitHandler _txCommitHandler = TxCommitHandler.getInstance();
- private static final TxRollbackHandler _txRollbackHandler = TxRollbackHandler.getInstance();
- private static final BasicRejectMethodHandler _basicRejectMethodHandler = BasicRejectMethodHandler.getInstance();
-
-
-
- public static MethodDispatcher createMethodDispatcher(AMQStateManager stateManager, ProtocolVersion protocolVersion)
- {
- return _dispatcherFactories.get(protocolVersion).createMethodDispatcher(stateManager);
- }
-
-
- public ServerMethodDispatcherImpl(AMQStateManager stateManager)
- {
- _stateManager = stateManager;
- }
-
-
- protected AMQStateManager getStateManager()
- {
- return _stateManager;
- }
-
-
-
- public boolean dispatchAccessRequest(AccessRequestBody body, int channelId) throws AMQException
- {
- _accessRequestHandler.methodReceived(_stateManager, body, channelId);
- return true;
- }
-
- public boolean dispatchBasicAck(BasicAckBody body, int channelId) throws AMQException
- {
- _basicAckMethodHandler.methodReceived(_stateManager, body, channelId);
- return true;
- }
-
- public boolean dispatchBasicCancel(BasicCancelBody body, int channelId) throws AMQException
- {
- _basicCancelMethodHandler.methodReceived(_stateManager, body, channelId);
- return true;
- }
-
- public boolean dispatchBasicConsume(BasicConsumeBody body, int channelId) throws AMQException
- {
- _basicConsumeMethodHandler.methodReceived(_stateManager, body, channelId);
- return true;
- }
-
- public boolean dispatchBasicGet(BasicGetBody body, int channelId) throws AMQException
- {
- _basicGetMethodHandler.methodReceived(_stateManager, body, channelId);
- return true;
- }
-
- public boolean dispatchBasicPublish(BasicPublishBody body, int channelId) throws AMQException
- {
- _basicPublishMethodHandler.methodReceived(_stateManager, body, channelId);
- return true;
- }
-
- public boolean dispatchBasicQos(BasicQosBody body, int channelId) throws AMQException
- {
- _basicQosHandler.methodReceived(_stateManager, body, channelId);
- return true;
- }
-
- public boolean dispatchBasicRecover(BasicRecoverBody body, int channelId) throws AMQException
- {
- _basicRecoverMethodHandler.methodReceived(_stateManager, body, channelId);
- return true;
- }
-
- public boolean dispatchBasicReject(BasicRejectBody body, int channelId) throws AMQException
- {
- _basicRejectMethodHandler.methodReceived(_stateManager, body, channelId);
- return true;
- }
-
- public boolean dispatchChannelOpen(ChannelOpenBody body, int channelId) throws AMQException
- {
- _channelOpenHandler.methodReceived(_stateManager, body, channelId);
- return true;
- }
-
-
- public boolean dispatchAccessRequestOk(AccessRequestOkBody body, int channelId) throws AMQException
- {
- throw new UnexpectedMethodException(body);
- }
-
- public boolean dispatchBasicCancelOk(BasicCancelOkBody body, int channelId) throws AMQException
- {
- throw new UnexpectedMethodException(body);
- }
-
- public boolean dispatchBasicConsumeOk(BasicConsumeOkBody body, int channelId) throws AMQException
- {
- throw new UnexpectedMethodException(body);
- }
-
- public boolean dispatchBasicDeliver(BasicDeliverBody body, int channelId) throws AMQException
- {
- throw new UnexpectedMethodException(body);
- }
-
- public boolean dispatchBasicGetEmpty(BasicGetEmptyBody body, int channelId) throws AMQException
- {
- throw new UnexpectedMethodException(body);
- }
-
- public boolean dispatchBasicGetOk(BasicGetOkBody body, int channelId) throws AMQException
- {
- throw new UnexpectedMethodException(body);
- }
-
- public boolean dispatchBasicQosOk(BasicQosOkBody body, int channelId) throws AMQException
- {
- throw new UnexpectedMethodException(body);
- }
-
- public boolean dispatchBasicReturn(BasicReturnBody body, int channelId) throws AMQException
- {
- throw new UnexpectedMethodException(body);
- }
-
- public boolean dispatchChannelClose(ChannelCloseBody body, int channelId) throws AMQException
- {
- _channelCloseHandler.methodReceived(_stateManager, body, channelId);
- return true;
- }
-
-
- public boolean dispatchChannelCloseOk(ChannelCloseOkBody body, int channelId) throws AMQException
- {
- _channelCloseOkHandler.methodReceived(_stateManager, body, channelId);
- return true;
- }
-
-
- public boolean dispatchChannelFlow(ChannelFlowBody body, int channelId) throws AMQException
- {
- _channelFlowHandler.methodReceived(_stateManager, body, channelId);
- return true;
- }
-
- public boolean dispatchChannelFlowOk(ChannelFlowOkBody body, int channelId) throws AMQException
- {
- throw new UnexpectedMethodException(body);
- }
-
- public boolean dispatchChannelOpenOk(ChannelOpenOkBody body, int channelId) throws AMQException
- {
- throw new UnexpectedMethodException(body);
- }
-
-
- public boolean dispatchConnectionOpen(ConnectionOpenBody body, int channelId) throws AMQException
- {
- _connectionOpenMethodHandler.methodReceived(_stateManager, body, channelId);
- return true;
- }
-
-
- public boolean dispatchConnectionClose(ConnectionCloseBody body, int channelId) throws AMQException
- {
- _connectionCloseMethodHandler.methodReceived(_stateManager, body, channelId);
- return true;
- }
-
-
- public boolean dispatchConnectionCloseOk(ConnectionCloseOkBody body, int channelId) throws AMQException
- {
- _connectionCloseOkMethodHandler.methodReceived(_stateManager, body, channelId);
- return true;
- }
-
- public boolean dispatchConnectionOpenOk(ConnectionOpenOkBody body, int channelId) throws AMQException
- {
- throw new UnexpectedMethodException(body);
- }
-
- public boolean dispatchConnectionRedirect(ConnectionRedirectBody body, int channelId) throws AMQException
- {
- throw new UnexpectedMethodException(body);
- }
-
- public boolean dispatchConnectionSecure(ConnectionSecureBody body, int channelId) throws AMQException
- {
- throw new UnexpectedMethodException(body);
- }
-
- public boolean dispatchConnectionStart(ConnectionStartBody body, int channelId) throws AMQException
- {
- throw new UnexpectedMethodException(body);
- }
-
- public boolean dispatchConnectionTune(ConnectionTuneBody body, int channelId) throws AMQException
- {
- throw new UnexpectedMethodException(body);
- }
-
- public boolean dispatchDtxSelectOk(DtxSelectOkBody body, int channelId) throws AMQException
- {
- throw new UnexpectedMethodException(body);
- }
-
- public boolean dispatchDtxStartOk(DtxStartOkBody body, int channelId) throws AMQException
- {
- throw new UnexpectedMethodException(body);
- }
-
- public boolean dispatchExchangeBoundOk(ExchangeBoundOkBody body, int channelId) throws AMQException
- {
- throw new UnexpectedMethodException(body);
- }
-
- public boolean dispatchExchangeDeclareOk(ExchangeDeclareOkBody body, int channelId) throws AMQException
- {
- throw new UnexpectedMethodException(body);
- }
-
- public boolean dispatchExchangeDeleteOk(ExchangeDeleteOkBody body, int channelId) throws AMQException
- {
- throw new UnexpectedMethodException(body);
- }
-
- public boolean dispatchFileCancelOk(FileCancelOkBody body, int channelId) throws AMQException
- {
- throw new UnexpectedMethodException(body);
- }
-
- public boolean dispatchFileConsumeOk(FileConsumeOkBody body, int channelId) throws AMQException
- {
- throw new UnexpectedMethodException(body);
- }
-
- public boolean dispatchFileDeliver(FileDeliverBody body, int channelId) throws AMQException
- {
- throw new UnexpectedMethodException(body);
- }
-
- public boolean dispatchFileOpen(FileOpenBody body, int channelId) throws AMQException
- {
- throw new UnexpectedMethodException(body);
- }
-
- public boolean dispatchFileOpenOk(FileOpenOkBody body, int channelId) throws AMQException
- {
- throw new UnexpectedMethodException(body);
- }
-
- public boolean dispatchFileQosOk(FileQosOkBody body, int channelId) throws AMQException
- {
- throw new UnexpectedMethodException(body);
- }
-
- public boolean dispatchFileReturn(FileReturnBody body, int channelId) throws AMQException
- {
- throw new UnexpectedMethodException(body);
- }
-
- public boolean dispatchFileStage(FileStageBody body, int channelId) throws AMQException
- {
- throw new UnexpectedMethodException(body);
- }
-
- public boolean dispatchQueueBindOk(QueueBindOkBody body, int channelId) throws AMQException
- {
- throw new UnexpectedMethodException(body);
- }
-
- public boolean dispatchQueueDeclareOk(QueueDeclareOkBody body, int channelId) throws AMQException
- {
- throw new UnexpectedMethodException(body);
- }
-
- public boolean dispatchQueueDeleteOk(QueueDeleteOkBody body, int channelId) throws AMQException
- {
- throw new UnexpectedMethodException(body);
- }
-
- public boolean dispatchQueuePurgeOk(QueuePurgeOkBody body, int channelId) throws AMQException
- {
- throw new UnexpectedMethodException(body);
- }
-
- public boolean dispatchStreamCancelOk(StreamCancelOkBody body, int channelId) throws AMQException
- {
- throw new UnexpectedMethodException(body);
- }
-
- public boolean dispatchStreamConsumeOk(StreamConsumeOkBody body, int channelId) throws AMQException
- {
- throw new UnexpectedMethodException(body);
- }
-
- public boolean dispatchStreamDeliver(StreamDeliverBody body, int channelId) throws AMQException
- {
- throw new UnexpectedMethodException(body);
- }
-
- public boolean dispatchStreamQosOk(StreamQosOkBody body, int channelId) throws AMQException
- {
- throw new UnexpectedMethodException(body);
- }
-
- public boolean dispatchStreamReturn(StreamReturnBody body, int channelId) throws AMQException
- {
- throw new UnexpectedMethodException(body);
- }
-
- public boolean dispatchTxCommitOk(TxCommitOkBody body, int channelId) throws AMQException
- {
- throw new UnexpectedMethodException(body);
- }
-
- public boolean dispatchTxRollbackOk(TxRollbackOkBody body, int channelId) throws AMQException
- {
- throw new UnexpectedMethodException(body);
- }
-
- public boolean dispatchTxSelectOk(TxSelectOkBody body, int channelId) throws AMQException
- {
- throw new UnexpectedMethodException(body);
- }
-
-
- public boolean dispatchConnectionSecureOk(ConnectionSecureOkBody body, int channelId) throws AMQException
- {
- _connectionSecureOkMethodHandler.methodReceived(_stateManager, body, channelId);
- return true;
- }
-
- public boolean dispatchConnectionStartOk(ConnectionStartOkBody body, int channelId) throws AMQException
- {
- _connectionStartOkMethodHandler.methodReceived(_stateManager, body, channelId);
- return true;
- }
-
- public boolean dispatchConnectionTuneOk(ConnectionTuneOkBody body, int channelId) throws AMQException
- {
- _connectionTuneOkMethodHandler.methodReceived(_stateManager, body, channelId);
- return true;
- }
-
- public boolean dispatchDtxSelect(DtxSelectBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchDtxStart(DtxStartBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchExchangeBound(ExchangeBoundBody body, int channelId) throws AMQException
- {
- _exchangeBoundHandler.methodReceived(_stateManager, body, channelId);
- return true;
- }
-
- public boolean dispatchExchangeDeclare(ExchangeDeclareBody body, int channelId) throws AMQException
- {
- _exchangeDeclareHandler.methodReceived(_stateManager, body, channelId);
- return true;
- }
-
- public boolean dispatchExchangeDelete(ExchangeDeleteBody body, int channelId) throws AMQException
- {
- _exchangeDeleteHandler.methodReceived(_stateManager, body, channelId);
- return true;
- }
-
- public boolean dispatchFileAck(FileAckBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchFileCancel(FileCancelBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchFileConsume(FileConsumeBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchFilePublish(FilePublishBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchFileQos(FileQosBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchFileReject(FileRejectBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchQueueBind(QueueBindBody body, int channelId) throws AMQException
- {
- _queueBindHandler.methodReceived(_stateManager, body, channelId);
- return true;
- }
-
- public boolean dispatchQueueDeclare(QueueDeclareBody body, int channelId) throws AMQException
- {
- _queueDeclareHandler.methodReceived(_stateManager, body, channelId);
- return true;
- }
-
- public boolean dispatchQueueDelete(QueueDeleteBody body, int channelId) throws AMQException
- {
- _queueDeleteHandler.methodReceived(_stateManager, body, channelId);
- return true;
- }
-
- public boolean dispatchQueuePurge(QueuePurgeBody body, int channelId) throws AMQException
- {
- _queuePurgeHandler.methodReceived(_stateManager, body, channelId);
- return true;
- }
-
- public boolean dispatchStreamCancel(StreamCancelBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchStreamConsume(StreamConsumeBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchStreamPublish(StreamPublishBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchStreamQos(StreamQosBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchTunnelRequest(TunnelRequestBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchTxCommit(TxCommitBody body, int channelId) throws AMQException
- {
- _txCommitHandler.methodReceived(_stateManager, body, channelId);
- return true;
- }
-
- public boolean dispatchTxRollback(TxRollbackBody body, int channelId) throws AMQException
- {
- _txRollbackHandler.methodReceived(_stateManager, body, channelId);
- return true;
- }
-
- public boolean dispatchTxSelect(TxSelectBody body, int channelId) throws AMQException
- {
- _txSelectHandler.methodReceived(_stateManager, body, channelId);
- return true;
- }
-
-
-
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/ServerMethodDispatcherImpl_0_9.java b/java/broker/src/main/java/org/apache/qpid/server/handler/ServerMethodDispatcherImpl_0_9.java
deleted file mode 100644
index 8b1dca77ba..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/ServerMethodDispatcherImpl_0_9.java
+++ /dev/null
@@ -1,164 +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.handler;
-
-
-import org.apache.qpid.framing.amqp_0_9.MethodDispatcher_0_9;
-import org.apache.qpid.framing.*;
-import org.apache.qpid.server.state.AMQStateManager;
-import org.apache.qpid.AMQException;
-
-
-
-public class ServerMethodDispatcherImpl_0_9
- extends ServerMethodDispatcherImpl
- implements MethodDispatcher_0_9
-
-{
-
- private static final BasicRecoverSyncMethodHandler _basicRecoverSyncMethodHandler =
- BasicRecoverSyncMethodHandler.getInstance();
- private static final QueueUnbindHandler _queueUnbindHandler =
- QueueUnbindHandler.getInstance();
-
-
- public ServerMethodDispatcherImpl_0_9(AMQStateManager stateManager)
- {
- super(stateManager);
- }
-
- public boolean dispatchBasicRecoverSync(BasicRecoverSyncBody body, int channelId) throws AMQException
- {
- _basicRecoverSyncMethodHandler.methodReceived(getStateManager(), body, channelId);
- return true;
- }
-
- public boolean dispatchBasicRecoverSyncOk(BasicRecoverSyncOkBody body, int channelId) throws AMQException
- {
- throw new UnexpectedMethodException(body);
- }
-
- public boolean dispatchChannelOk(ChannelOkBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchChannelPing(ChannelPingBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchChannelPong(ChannelPongBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchChannelResume(ChannelResumeBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageAppend(MessageAppendBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageCancel(MessageCancelBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageCheckpoint(MessageCheckpointBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageClose(MessageCloseBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageConsume(MessageConsumeBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageEmpty(MessageEmptyBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageGet(MessageGetBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageOffset(MessageOffsetBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageOk(MessageOkBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageOpen(MessageOpenBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageQos(MessageQosBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageRecover(MessageRecoverBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageReject(MessageRejectBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageResume(MessageResumeBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageTransfer(MessageTransferBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchQueueUnbindOk(QueueUnbindOkBody body, int channelId) throws AMQException
- {
- throw new UnexpectedMethodException(body);
- }
-
- public boolean dispatchQueueUnbind(QueueUnbindBody body, int channelId) throws AMQException
- {
- _queueUnbindHandler.methodReceived(getStateManager(),body,channelId);
- return true;
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/ServerMethodDispatcherImpl_0_91.java b/java/broker/src/main/java/org/apache/qpid/server/handler/ServerMethodDispatcherImpl_0_91.java
deleted file mode 100644
index 32cd4c4e9f..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/ServerMethodDispatcherImpl_0_91.java
+++ /dev/null
@@ -1,168 +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.handler;
-
-
-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
- extends ServerMethodDispatcherImpl
- implements MethodDispatcher_0_91
-
-{
-
- private static final BasicRecoverSyncMethodHandler _basicRecoverSyncMethodHandler =
- BasicRecoverSyncMethodHandler.getInstance();
- private static final QueueUnbindHandler _queueUnbindHandler =
- QueueUnbindHandler.getInstance();
-
-
- public ServerMethodDispatcherImpl_0_91(AMQStateManager stateManager)
- {
- super(stateManager);
- }
-
- public boolean dispatchBasicRecoverSync(BasicRecoverSyncBody body, int channelId) throws AMQException
- {
- _basicRecoverSyncMethodHandler.methodReceived(getStateManager(), body, channelId);
- return true;
- }
-
- public boolean dispatchBasicRecoverSyncOk(BasicRecoverSyncOkBody body, int channelId) throws AMQException
- {
- throw new UnexpectedMethodException(body);
- }
-
- public boolean dispatchChannelOk(ChannelOkBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchChannelPing(ChannelPingBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchChannelPong(ChannelPongBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchChannelResume(ChannelResumeBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageAppend(MessageAppendBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageCancel(MessageCancelBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageCheckpoint(MessageCheckpointBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageClose(MessageCloseBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageConsume(MessageConsumeBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageEmpty(MessageEmptyBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageGet(MessageGetBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageOffset(MessageOffsetBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageOk(MessageOkBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageOpen(MessageOpenBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageQos(MessageQosBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageRecover(MessageRecoverBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageReject(MessageRejectBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageResume(MessageResumeBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageTransfer(MessageTransferBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchBasicRecoverOk(BasicRecoverOkBody body, int channelId) throws AMQException
- {
- return false; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean dispatchQueueUnbindOk(QueueUnbindOkBody body, int channelId) throws AMQException
- {
- throw new UnexpectedMethodException(body);
- }
-
- public boolean dispatchQueueUnbind(QueueUnbindBody body, int channelId) throws AMQException
- {
- _queueUnbindHandler.methodReceived(getStateManager(),body,channelId);
- return true;
- }
-} \ No newline at end of file
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/ServerMethodDispatcherImpl_8_0.java b/java/broker/src/main/java/org/apache/qpid/server/handler/ServerMethodDispatcherImpl_8_0.java
deleted file mode 100644
index d599ca3d4e..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/ServerMethodDispatcherImpl_8_0.java
+++ /dev/null
@@ -1,86 +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.handler;
-
-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
- implements MethodDispatcher_8_0
-{
- public ServerMethodDispatcherImpl_8_0(AMQStateManager stateManager)
- {
- super(stateManager);
- }
-
- public boolean dispatchBasicRecoverOk(BasicRecoverOkBody body, int channelId) throws AMQException
- {
- throw new UnexpectedMethodException(body);
- }
-
- public boolean dispatchChannelAlert(ChannelAlertBody body, int channelId) throws AMQException
- {
- throw new UnexpectedMethodException(body);
- }
-
- public boolean dispatchTestContent(TestContentBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchTestContentOk(TestContentOkBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchTestInteger(TestIntegerBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchTestIntegerOk(TestIntegerOkBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchTestString(TestStringBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchTestStringOk(TestStringOkBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchTestTable(TestTableBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchTestTableOk(TestTableOkBody body, int channelId) throws AMQException
- {
- return false;
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/TxCommitHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/TxCommitHandler.java
deleted file mode 100644
index abd2bccc8d..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/TxCommitHandler.java
+++ /dev/null
@@ -1,76 +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.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.server.AMQChannel;
-import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.server.state.AMQStateManager;
-import org.apache.qpid.server.state.StateAwareMethodListener;
-
-public class TxCommitHandler implements StateAwareMethodListener<TxCommitBody>
-{
- private static final Logger _log = Logger.getLogger(TxCommitHandler.class);
-
- private static TxCommitHandler _instance = new TxCommitHandler();
-
- public static TxCommitHandler getInstance()
- {
- return _instance;
- }
-
- private TxCommitHandler()
- {
- }
-
- public void methodReceived(AMQStateManager stateManager, TxCommitBody body, int channelId) throws AMQException
- {
- AMQProtocolSession session = stateManager.getProtocolSession();
-
- try
- {
- if (_log.isDebugEnabled())
- {
- _log.debug("Commit received on channel " + channelId);
- }
- AMQChannel channel = session.getChannel(channelId);
-
- if (channel == null)
- {
- throw body.getChannelNotFoundException(channelId);
- }
- channel.commit();
-
- MethodRegistry methodRegistry = session.getMethodRegistry();
- AMQMethodBody responseBody = methodRegistry.createTxCommitOkBody();
- session.writeFrame(responseBody.generateFrame(channelId));
-
- }
- catch (AMQException e)
- {
- throw body.getChannelException(e.getErrorCode(), "Failed to commit: " + e.getMessage());
- }
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/TxRollbackHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/TxRollbackHandler.java
deleted file mode 100644
index 4643dee0a3..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/TxRollbackHandler.java
+++ /dev/null
@@ -1,82 +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.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.server.AMQChannel;
-import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.server.state.AMQStateManager;
-import org.apache.qpid.server.state.StateAwareMethodListener;
-
-public class TxRollbackHandler implements StateAwareMethodListener<TxRollbackBody>
-{
- private static TxRollbackHandler _instance = new TxRollbackHandler();
-
- public static TxRollbackHandler getInstance()
- {
- return _instance;
- }
-
- private TxRollbackHandler()
- {
- }
-
- public void methodReceived(AMQStateManager stateManager, TxRollbackBody body, final int channelId) throws AMQException
- {
- final AMQProtocolSession session = stateManager.getProtocolSession();
-
- try
- {
- AMQChannel channel = session.getChannel(channelId);
-
- if (channel == null)
- {
- throw body.getChannelNotFoundException(channelId);
- }
-
-
-
- final MethodRegistry methodRegistry = session.getMethodRegistry();
- final AMQMethodBody responseBody = methodRegistry.createTxRollbackOkBody();
-
- Runnable task = new Runnable()
- {
-
- public void run()
- {
- session.writeFrame(responseBody.generateFrame(channelId));
- }
- };
-
- channel.rollback(task);
-
- }
- catch (AMQException e)
- {
- throw body.getChannelException(e.getErrorCode(), "Failed to rollback: " + e.getMessage());
- }
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/TxSelectHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/TxSelectHandler.java
deleted file mode 100644
index 308f5b73cf..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/TxSelectHandler.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.server.handler;
-
-import org.apache.qpid.AMQException;
-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.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<TxSelectBody>
-{
- private static TxSelectHandler _instance = new TxSelectHandler();
-
- public static TxSelectHandler getInstance()
- {
- return _instance;
- }
-
- private TxSelectHandler()
- {
- }
-
- public void methodReceived(AMQStateManager stateManager, TxSelectBody body, int channelId) throws AMQException
- {
- AMQProtocolSession session = stateManager.getProtocolSession();
-
- AMQChannel channel = session.getChannel(channelId);
-
- if (channel == null)
- {
- throw body.getChannelNotFoundException(channelId);
- }
-
- channel.setLocalTransactional();
-
- MethodRegistry methodRegistry = session.getMethodRegistry();
- TxSelectOkBody responseBody = methodRegistry.createTxSelectOkBody();
- session.writeFrame(responseBody.generateFrame(channelId));
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/UnexpectedMethodException.java b/java/broker/src/main/java/org/apache/qpid/server/handler/UnexpectedMethodException.java
deleted file mode 100644
index 3526fdcae5..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/UnexpectedMethodException.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.handler;
-
-
-import org.apache.qpid.framing.AMQMethodBody;
-import org.apache.qpid.AMQException;
-
-public class UnexpectedMethodException extends AMQException
-{
-
- private static final long serialVersionUID = -255921574946294892L;
-
- public UnexpectedMethodException(AMQMethodBody body)
- {
- super("Unexpected method recevied: " + body.getClass().getName());
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/information/management/ServerInformationMBean.java b/java/broker/src/main/java/org/apache/qpid/server/information/management/ServerInformationMBean.java
deleted file mode 100644
index 5e6a143d52..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/information/management/ServerInformationMBean.java
+++ /dev/null
@@ -1,146 +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.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;
-import org.apache.qpid.server.management.AMQManagedObject;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-
-import javax.management.JMException;
-
-/** MBean class for the ServerInformationMBean. */
-@MBeanDescription("Server Information Interface")
-public class ServerInformationMBean extends AMQManagedObject implements ServerInformation
-{
- private String buildVersion;
- private String productVersion;
- private ApplicationRegistry registry;
-
- public ServerInformationMBean(ApplicationRegistry applicationRegistry) throws JMException
- {
- super(ServerInformation.class, ServerInformation.TYPE);
-
- registry = applicationRegistry;
- buildVersion = QpidProperties.getBuildVersion();
- productVersion = QpidProperties.getReleaseVersion();
- }
-
- public String getObjectInstanceName()
- {
- return ServerInformation.TYPE;
- }
-
- public Integer getManagementApiMajorVersion() throws IOException
- {
- return QPID_JMX_API_MAJOR_VERSION;
- }
-
- public Integer getManagementApiMinorVersion() throws IOException
- {
- return QPID_JMX_API_MINOR_VERSION;
- }
-
- public String getBuildVersion() throws IOException
- {
- return buildVersion;
- }
-
- public String getProductVersion() throws IOException
- {
- return productVersion;
- }
-
-
- public void resetStatistics() throws Exception
- {
- registry.resetStatistics();
- }
-
- public double getPeakMessageDeliveryRate()
- {
- return registry.getMessageDeliveryStatistics().getPeak();
- }
-
- public double getPeakDataDeliveryRate()
- {
- return registry.getDataDeliveryStatistics().getPeak();
- }
-
- public double getMessageDeliveryRate()
- {
- return registry.getMessageDeliveryStatistics().getRate();
- }
-
- public double getDataDeliveryRate()
- {
- return registry.getDataDeliveryStatistics().getRate();
- }
-
- public long getTotalMessagesDelivered()
- {
- return registry.getMessageDeliveryStatistics().getTotal();
- }
-
- public long getTotalDataDelivered()
- {
- return registry.getDataDeliveryStatistics().getTotal();
- }
-
- public double getPeakMessageReceiptRate()
- {
- return registry.getMessageReceiptStatistics().getPeak();
- }
-
- public double getPeakDataReceiptRate()
- {
- return registry.getDataReceiptStatistics().getPeak();
- }
-
- public double getMessageReceiptRate()
- {
- return registry.getMessageReceiptStatistics().getRate();
- }
-
- public double getDataReceiptRate()
- {
- return registry.getDataReceiptStatistics().getRate();
- }
-
- public long getTotalMessagesReceived()
- {
- return registry.getMessageReceiptStatistics().getTotal();
- }
-
- public long getTotalDataReceived()
- {
- return registry.getDataReceiptStatistics().getTotal();
- }
-
- public boolean isStatisticsEnabled()
- {
- return registry.isStatisticsEnabled();
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/logging/AbstractRootMessageLogger.java b/java/broker/src/main/java/org/apache/qpid/server/logging/AbstractRootMessageLogger.java
deleted file mode 100644
index 545f2adea2..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/logging/AbstractRootMessageLogger.java
+++ /dev/null
@@ -1,59 +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.logging;
-
-import org.apache.qpid.server.configuration.ServerConfiguration;
-
-public abstract class AbstractRootMessageLogger implements RootMessageLogger
-{
- public static final String DEFAULT_LOG_HIERARCHY_PREFIX = "qpid.message.";
-
- private boolean _enabled = true;
-
- public AbstractRootMessageLogger()
- {
-
- }
-
- public AbstractRootMessageLogger(ServerConfiguration config)
- {
- _enabled = config.getStatusUpdatesEnabled();
- }
-
- public boolean isEnabled()
- {
- return _enabled;
- }
-
- public boolean isMessageEnabled(LogActor actor, LogSubject subject, String logHierarchy)
- {
- return _enabled;
- }
-
- public boolean isMessageEnabled(LogActor actor, String logHierarchy)
- {
- return _enabled;
- }
-
- public abstract void rawMessage(String message, String logHierarchy);
-
- public abstract void rawMessage(String message, Throwable throwable, String logHierarchy);
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/logging/CompositeStartupMessageLogger.java b/java/broker/src/main/java/org/apache/qpid/server/logging/CompositeStartupMessageLogger.java
deleted file mode 100644
index e0a51b3a3e..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/logging/CompositeStartupMessageLogger.java
+++ /dev/null
@@ -1,51 +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.logging;
-
-public class CompositeStartupMessageLogger extends AbstractRootMessageLogger
-{
- private RootMessageLogger[] _loggers;
-
- public CompositeStartupMessageLogger(RootMessageLogger[] loggers)
- {
- super();
- _loggers = loggers;
- }
-
- @Override
- public void rawMessage(String message, String logHierarchy)
- {
- for(RootMessageLogger l : _loggers)
- {
- l.rawMessage(message, logHierarchy);
- }
- }
-
- @Override
- public void rawMessage(String message, Throwable throwable, String logHierarchy)
- {
- for(RootMessageLogger l : _loggers)
- {
- l.rawMessage(message, throwable, logHierarchy);
- }
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/logging/Log4jMessageLogger.java b/java/broker/src/main/java/org/apache/qpid/server/logging/Log4jMessageLogger.java
deleted file mode 100644
index a0285ebfc4..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/logging/Log4jMessageLogger.java
+++ /dev/null
@@ -1,74 +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.logging;
-
-import org.apache.log4j.Level;
-import org.apache.log4j.Logger;
-import org.apache.qpid.server.configuration.ServerConfiguration;
-
-public class Log4jMessageLogger extends AbstractRootMessageLogger
-{
- public static final Level LEVEL = Level.toLevel("INFO");
-
- public Log4jMessageLogger()
- {
- super();
- }
-
- public Log4jMessageLogger(ServerConfiguration config)
- {
- super(config);
- }
-
- @Override
- public boolean isMessageEnabled(LogActor actor, LogSubject subject, String logHierarchy)
- {
- return isMessageEnabled(actor, logHierarchy);
- }
-
- @Override
- public boolean isMessageEnabled(LogActor actor, String logHierarchy)
- {
- if(isEnabled())
- {
- Logger logger = Logger.getLogger(logHierarchy);
- return logger.isEnabledFor(LEVEL);
- }
- else
- {
- return false;
- }
- }
-
- @Override
- public void rawMessage(String message, String logHierarchy)
- {
- rawMessage(message, null, logHierarchy);
- }
-
- @Override
- public void rawMessage(String message, Throwable throwable, String logHierarchy)
- {
- Logger logger = Logger.getLogger(logHierarchy);
-
- logger.log(LEVEL, message, throwable);
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/logging/LogActor.java b/java/broker/src/main/java/org/apache/qpid/server/logging/LogActor.java
deleted file mode 100644
index 18f03c2716..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/logging/LogActor.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.
- *
- *
- */
-package org.apache.qpid.server.logging;
-
-/**
- * LogActor the entity that is stored as in a ThreadLocal and used to perform logging.
- *
- * The actor is responsible for formatting its display name for the log entry.
- *
- * The actor performs the requested logging.
- */
-public interface LogActor
-{
- /**
- * Logs the specified LogMessage about the LogSubject
- *
- * Currently logging has a global setting however this will later be revised and
- * as such the LogActor will need to take into consideration any new configuration
- * as a means of enabling the logging of LogActors and LogSubjects.
- *
- * @param subject The subject that is being logged
- * @param message The message to log
- */
- public void message(LogSubject subject, LogMessage message);
-
- /**
- * Logs the specified LogMessage against this actor
- *
- * Currently logging has a global setting however this will later be revised and
- * as such the LogActor will need to take into consideration any new configuration
- * as a means of enabling the logging of LogActors and LogSubjects.
- *
- * @param message The message to log
- */
- public void message(LogMessage message);
-
- /**
- *
- * @return the RootMessageLogger that is currently in use by this LogActor.
- */
- RootMessageLogger getRootMessageLogger();
-
- /**
- *
- * @return the String representing this LogActor
- */
- public String getLogMessage();
-} \ No newline at end of file
diff --git a/java/broker/src/main/java/org/apache/qpid/server/logging/LogMessage.java b/java/broker/src/main/java/org/apache/qpid/server/logging/LogMessage.java
deleted file mode 100644
index fa18435fab..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/logging/LogMessage.java
+++ /dev/null
@@ -1,26 +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.logging;
-
-public interface LogMessage
-{
- String getLogHierarchy();
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/logging/LogSubject.java b/java/broker/src/main/java/org/apache/qpid/server/logging/LogSubject.java
deleted file mode 100644
index 09a277e520..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/logging/LogSubject.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.logging;
-
-/**
- * Each LogSubject that wishes to be logged will implement this to provide their
- * own display representation.
- *
- */
-public interface LogSubject
-{
- /**
- * Provides the log message as as String.
- *
- * @returns String the display representation of this LogSubject
- */
- public String toLogString();
-} \ No newline at end of file
diff --git a/java/broker/src/main/java/org/apache/qpid/server/logging/NullRootMessageLogger.java b/java/broker/src/main/java/org/apache/qpid/server/logging/NullRootMessageLogger.java
deleted file mode 100644
index db8b24e90e..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/logging/NullRootMessageLogger.java
+++ /dev/null
@@ -1,47 +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.logging;
-
-public class NullRootMessageLogger extends AbstractRootMessageLogger
-{
-
- @Override
- public boolean isMessageEnabled(LogActor actor, LogSubject subject, String logHeirarchy)
- {
- return false;
- }
-
- @Override
- public boolean isMessageEnabled(LogActor actor, String logHierarchy)
- {
- return false;
- }
-
- public void rawMessage(String message, String logHierarchy)
- {
- // drop message
- }
-
- public void rawMessage(String message, Throwable throwable, String logHierarchy)
- {
- // drop message
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/logging/RootMessageLogger.java b/java/broker/src/main/java/org/apache/qpid/server/logging/RootMessageLogger.java
deleted file mode 100644
index 1431dd1da9..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/logging/RootMessageLogger.java
+++ /dev/null
@@ -1,75 +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.logging;
-
-/**
- * The RootMessageLogger is used by the LogActors to query if
- * logging is enabled for the requested message and to provide the actual
- * message that should be logged.
- */
-public interface RootMessageLogger
-{
- /**
- * Determine whether the MessageLogger is enabled
- *
- * @return boolean true if enabled.
- */
- boolean isEnabled();
-
- /**
- * Determine if the LogSubject and the LogActor should be
- * generating log messages.
- * @param actor The actor requesting the logging
- * @param subject The subject of this log request
- * @param logHierarchy The log hierarchy for this request
- *
- * @return boolean true if the message should be logged.
- */
- boolean isMessageEnabled(LogActor actor, LogSubject subject, String logHierarchy);
-
- /**
- * Determine if the LogActor should be generating log messages.
- *
- * @param actor The actor requesting the logging
- * @param logHierarchy The log hierarchy for this request
- *
- * @return boolean true if the message should be logged.
- */
- boolean isMessageEnabled(LogActor actor, String logHierarchy);
-
- /**
- * Log the raw message to the configured logger.
- *
- * @param message The message to log
- * @param logHierarchy The log hierarchy for this request
- */
- public void rawMessage(String message, String logHierarchy);
-
- /**
- * Log the raw message to the configured logger.
- * Along with a formated stack trace from the Throwable.
- *
- * @param message The message to log
- * @param throwable Optional Throwable that should provide stact trace
- * @param logHierarchy The log hierarchy for this request
- */
- void rawMessage(String message, Throwable throwable, String logHierarchy);
-} \ No newline at end of file
diff --git a/java/broker/src/main/java/org/apache/qpid/server/logging/SystemOutMessageLogger.java b/java/broker/src/main/java/org/apache/qpid/server/logging/SystemOutMessageLogger.java
deleted file mode 100644
index b384b3fde3..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/logging/SystemOutMessageLogger.java
+++ /dev/null
@@ -1,51 +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.logging;
-
-
-public class SystemOutMessageLogger extends AbstractRootMessageLogger
-{
- @Override
- public boolean isMessageEnabled(LogActor actor, LogSubject subject, String logHeirarchy)
- {
- return true;
- }
-
- @Override
- public boolean isMessageEnabled(LogActor actor, String logHierarchy)
- {
- return true;
- }
-
- public void rawMessage(String message, String logHierarchy)
- {
- rawMessage(message, null, logHierarchy);
- }
-
- public void rawMessage(String message, Throwable throwable, String logHierarchy)
- {
- System.out.println(message);
- if (throwable != null)
- {
- throwable.printStackTrace(System.out);
- }
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/logging/actors/AMQPChannelActor.java b/java/broker/src/main/java/org/apache/qpid/server/logging/actors/AMQPChannelActor.java
deleted file mode 100644
index 9c7ffcc5f8..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/logging/actors/AMQPChannelActor.java
+++ /dev/null
@@ -1,64 +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.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
- * associated Channel.
- *
- * <p/>
- * This is responsible for correctly formatting the LogActor String in the log
- * <p/>
- * [con:1(user@127.0.0.1/)/ch:1]
- * <p/>
- * To do this it requires access to the IO Layers as well as a Channel
- */
-public class AMQPChannelActor extends AbstractActor
-{
- private final ChannelLogSubject _logString;
-
- /**
- * Create a new ChannelActor
- *
- * @param channel The Channel for this LogActor
- * @param rootLogger The root Logger that this LogActor should use
- */
- public AMQPChannelActor(AMQChannel channel, RootMessageLogger rootLogger)
- {
- super(rootLogger);
-
-
- _logString = new ChannelLogSubject(channel);
- }
-
- public String getLogMessage()
- {
- return _logString.toLogString();
- }
-}
-
diff --git a/java/broker/src/main/java/org/apache/qpid/server/logging/actors/AMQPConnectionActor.java b/java/broker/src/main/java/org/apache/qpid/server/logging/actors/AMQPConnectionActor.java
deleted file mode 100644
index 1b4bc91bc1..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/logging/actors/AMQPConnectionActor.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- *
- */
-package org.apache.qpid.server.logging.actors;
-
-import org.apache.qpid.server.logging.RootMessageLogger;
-import org.apache.qpid.server.logging.subjects.ConnectionLogSubject;
-import org.apache.qpid.server.protocol.AMQProtocolSession;
-
-
-
-/**
- * An AMQPConnectionActor represtents a connectionthrough the AMQP port.
- * <p/>
- * This is responsible for correctly formatting the LogActor String in the log
- * <p/>
- * [ con:1(user@127.0.0.1/) ]
- * <p/>
- * To do this it requires access to the IO Layers.
- */
-public class AMQPConnectionActor extends AbstractActor
-{
- private ConnectionLogSubject _logSubject;
-
- public AMQPConnectionActor(AMQProtocolSession session, RootMessageLogger rootLogger)
- {
- super(rootLogger);
-
- _logSubject = new ConnectionLogSubject(session);
- }
-
- public String getLogMessage()
- {
- return _logSubject.toLogString();
- }
-}
-
diff --git a/java/broker/src/main/java/org/apache/qpid/server/logging/actors/AbstractActor.java b/java/broker/src/main/java/org/apache/qpid/server/logging/actors/AbstractActor.java
deleted file mode 100644
index e0bf180cc4..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/logging/actors/AbstractActor.java
+++ /dev/null
@@ -1,71 +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.logging.actors;
-
-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;
-
-public abstract class AbstractActor implements LogActor
-{
- public final String _msgPrefix = System.getProperty("qpid.logging.prefix","");
-
- protected RootMessageLogger _rootLogger;
-
- public AbstractActor(RootMessageLogger rootLogger)
- {
- if(rootLogger == null)
- {
- throw new NullPointerException("RootMessageLogger cannot be null");
- }
- _rootLogger = rootLogger;
- }
-
- public void message(LogSubject subject, LogMessage message)
- {
- if (_rootLogger.isMessageEnabled(this, subject, message.getLogHierarchy()))
- {
- _rootLogger.rawMessage(_msgPrefix + getLogMessage() + subject.toLogString() + message, message.getLogHierarchy());
- }
- }
-
- public void message(LogMessage message)
- {
- if (_rootLogger.isMessageEnabled(this, message.getLogHierarchy()))
- {
- _rootLogger.rawMessage(_msgPrefix + getLogMessage() + message, message.getLogHierarchy());
- }
- }
-
- public RootMessageLogger getRootMessageLogger()
- {
- return _rootLogger;
- }
-
- public String toString()
- {
- return getLogMessage();
- }
-
- abstract public String getLogMessage();
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/logging/actors/BrokerActor.java b/java/broker/src/main/java/org/apache/qpid/server/logging/actors/BrokerActor.java
deleted file mode 100644
index 9e77452228..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/logging/actors/BrokerActor.java
+++ /dev/null
@@ -1,53 +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.logging.actors;
-
-import org.apache.qpid.server.logging.RootMessageLogger;
-
-public class BrokerActor extends AbstractActor
-{
- private final String _logString;
-
- /**
- * Create a new BrokerActor
- *
- * @param logger
- */
- public BrokerActor(RootMessageLogger logger)
- {
- super(logger);
-
- _logString = "[Broker] ";
- }
-
- public BrokerActor(String name, RootMessageLogger logger)
- {
- super(logger);
-
- _logString = "[Broker(" + name + ")] ";
- }
-
- public String getLogMessage()
- {
- return _logString;
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/logging/actors/CurrentActor.java b/java/broker/src/main/java/org/apache/qpid/server/logging/actors/CurrentActor.java
deleted file mode 100644
index 2ebbfeb734..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/logging/actors/CurrentActor.java
+++ /dev/null
@@ -1,125 +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.logging.actors;
-
-import org.apache.qpid.server.logging.LogActor;
-
-import java.util.EmptyStackException;
-import java.util.Stack;
-
-/**
- * The CurrentActor is a ThreadLocal wrapper that allows threads in the broker
- * to retrieve an actor to perform logging. This approach is used so for two
- * reasons:
- * 1) We do not have to pass a logging actor around the system
- * 2) We can set new actors at the point we have enough information. i.e.
- * - Set a low level ConnectionActor when processing bytes from the wire.
- * - Set a ChannelActor when we are processing the frame
- * - Set a SubscriptionActor when we are handling the subscription.
- * <p/>
- * The code performing the logging need not worry about what type of actor is
- * currently set so can perform its logging. The resulting log entry though will
- * contain customised details from the the currently set Actor.
- * <p/>
- * The Actor model also allows the pre-creation of fixed messages so the
- * performance impact of the additional logging data is minimised.
- * <p/>
- * This class does not perform any checks to ensure that there is an Actor set
- * when calling remove or get. As a result the application developer must ensure
- * that they have called set before they attempt to use the actor via get or
- * remove the set actor.
- * <p/>
- * The checking of the return via get should not be done as the logging is
- * desired. It is preferable to cause the NullPointerException to highlight the
- * programming error rather than miss a log message.
- * <p/>
- * The same is true for the remove. A NPE will occur if no set has been called
- * highlighting the programming error.
- */
-public class CurrentActor
-{
- /** The ThreadLocal variable with initialiser */
- private static final ThreadLocal<Stack<LogActor>> _currentActor = new ThreadLocal<Stack<LogActor>>()
- {
- // Initialise the CurrentActor to be an empty List
- protected Stack<LogActor> initialValue()
- {
- return new Stack<LogActor>();
- }
- };
-
- private static LogActor _defaultActor;
-
- /**
- * Set a new {@link LogActor} to be the Current Actor
- * <p/>
- * This pushes the Actor in to the LIFO Queue
- *
- * @param actor The new LogActor
- */
- public static void set(LogActor actor)
- {
- Stack<LogActor> stack = _currentActor.get();
- stack.push(actor);
- }
-
- /**
- * Remove all {@link LogActor}s
- */
- public static void removeAll()
- {
- Stack<LogActor> stack = _currentActor.get();
- stack.clear();
- }
-
- /**
- * Remove the current {@link LogActor}.
- * <p/>
- * Calling remove without calling set will result in an EmptyStackException.
- */
- public static void remove()
- {
- Stack<LogActor> stack = _currentActor.get();
- stack.pop();
- }
-
- /**
- * Return the current head of the list of {@link LogActor}s.
- *
- * @return Current LogActor
- */
- public static LogActor get()
- {
- try
- {
- return _currentActor.get().peek();
- }
- catch (EmptyStackException ese)
- {
- return _defaultActor;
- }
- }
-
- public static void setDefault(LogActor defaultActor)
- {
- _defaultActor = defaultActor;
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/logging/actors/GenericActor.java b/java/broker/src/main/java/org/apache/qpid/server/logging/actors/GenericActor.java
deleted file mode 100644
index 9afc76ce78..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/logging/actors/GenericActor.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.qpid.server.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
-{
-
- private static RootMessageLogger _defaultMessageLogger;
-
- private LogSubject _logSubject;
-
- public static RootMessageLogger getDefaultMessageLogger()
- {
- return _defaultMessageLogger;
- }
-
- public static void setDefaultMessageLogger(RootMessageLogger defaultMessageLogger)
- {
- _defaultMessageLogger = defaultMessageLogger;
- }
-
- public GenericActor(LogSubject logSubject, RootMessageLogger rootLogger)
- {
- super(rootLogger);
- _logSubject = logSubject;
- }
-
- public String getLogMessage()
- {
- return _logSubject.toLogString();
- }
-
- public static LogActor getInstance(final String logMessage, RootMessageLogger rootLogger)
- {
- return new GenericActor(new LogSubject()
- {
- public String toLogString()
- {
- return logMessage;
- }
-
- }, rootLogger);
- }
-
- public static LogActor getInstance(final String subjectMessage)
- {
- return new GenericActor(new LogSubject()
- {
- public String toLogString()
- {
- return "[" + subjectMessage + "] ";
- }
-
- }, _defaultMessageLogger);
- }
-
- public static LogActor getInstance(LogSubject logSubject)
- {
- return new GenericActor(logSubject, _defaultMessageLogger);
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/logging/actors/ManagementActor.java b/java/broker/src/main/java/org/apache/qpid/server/logging/actors/ManagementActor.java
deleted file mode 100644
index 2825fa1b75..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/logging/actors/ManagementActor.java
+++ /dev/null
@@ -1,114 +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.logging.actors;
-
-import org.apache.qpid.server.logging.LogMessage;
-import org.apache.qpid.server.logging.LogSubject;
-import org.apache.qpid.server.logging.RootMessageLogger;
-
-import java.text.MessageFormat;
-
-/**
- * NOTE: This actor is not thread safe.
- *
- * Sharing of a ManagementActor instance between threads may result in an
- * incorrect actor value being logged.
- *
- * This is due to the fact that calls to message will dynamically query the
- * thread name and use that to set the log format during each message() call.
- *
- * This is currently not an issue as each MBean operation creates a new Actor
- * that is unique for each operation.
- */
-public class ManagementActor extends AbstractActor
-{
- String _lastThreadName = null;
-
- /**
- * LOG FORMAT for the ManagementActor,
- * Uses a MessageFormat call to insert the requried values according to
- * these indicies:
- *
- * 0 - Connection ID
- * 1 - User ID
- * 2 - IP
- */
- public static final String MANAGEMENT_FORMAT = "mng:{0}({1})";
-
- /**
- * The logString to be used for logging
- */
- private String _logString;
-
- /** @param rootLogger The RootLogger to use for this Actor */
- public ManagementActor(RootMessageLogger rootLogger)
- {
- super(rootLogger);
- }
-
- private void updateLogString()
- {
- String currentName = Thread.currentThread().getName();
-
- String actor;
- // Record the last thread name so we don't have to recreate the log string
- if (!currentName.equals(_lastThreadName))
- {
- _lastThreadName = currentName;
-
- // Management Thread names have this format.
- //RMI TCP Connection(2)-169.24.29.116
- // This is true for both LocalAPI and JMX Connections
- // However to be defensive lets test.
-
- String[] split = currentName.split("\\(");
- if (split.length == 2)
- {
- String connectionID = split[1].split("\\)")[0];
- String ip = currentName.split("-")[1];
-
- actor = MessageFormat.format(MANAGEMENT_FORMAT,
- connectionID,
- ip);
- }
- else
- {
- // This is a precautionary path as it is not expected to occur
- // however rather than adjusting the thread name of the two
- // tests that will use this it is safer all round to do this.
- // it is also currently used by tests :
- // AMQBrokerManagerMBeanTest
- // ExchangeMBeanTest
- actor = currentName;
- }
-
- _logString = "[" + actor + "] ";
-
- }
- }
-
- public String getLogMessage()
- {
- updateLogString();
- return _logString;
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/logging/actors/QueueActor.java b/java/broker/src/main/java/org/apache/qpid/server/logging/actors/QueueActor.java
deleted file mode 100644
index 3364365b61..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/logging/actors/QueueActor.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.logging.actors;
-
-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.
- */
-public class QueueActor extends AbstractActor
-{
- private QueueLogSubject _logSubject;
-
- /**
- * Create an QueueLogSubject that Logs in the following format.
- *
- * @param queue The queue that this Actor is working for
- * @param rootLogger the Root logger to use.
- */
- public QueueActor(AMQQueue queue, RootMessageLogger rootLogger)
- {
- super(rootLogger);
-
- _logSubject = new QueueLogSubject(queue);
- }
-
- public String getLogMessage()
- {
- return _logSubject.toLogString();
- }
-}
-
diff --git a/java/broker/src/main/java/org/apache/qpid/server/logging/actors/SubscriptionActor.java b/java/broker/src/main/java/org/apache/qpid/server/logging/actors/SubscriptionActor.java
deleted file mode 100644
index a2dbf2f6ee..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/logging/actors/SubscriptionActor.java
+++ /dev/null
@@ -1,46 +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.logging.actors;
-
-import org.apache.qpid.server.logging.RootMessageLogger;
-import org.apache.qpid.server.logging.subjects.SubscriptionLogSubject;
-import org.apache.qpid.server.subscription.Subscription;
-
-/**
- * The subscription actor provides formatted logging for actions that are
- * performed by the subsciption. Such as STATE changes.
- */
-public class SubscriptionActor extends AbstractActor
-{
- private SubscriptionLogSubject _logSubject;
-
- public SubscriptionActor(RootMessageLogger logger, Subscription subscription)
- {
- super(logger);
-
- _logSubject = new SubscriptionLogSubject(subscription);
- }
-
- public String getLogMessage()
- {
- return _logSubject.toLogString();
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/logging/management/LoggingManagementMBean.java b/java/broker/src/main/java/org/apache/qpid/server/logging/management/LoggingManagementMBean.java
deleted file mode 100644
index a823fb7cb1..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/logging/management/LoggingManagementMBean.java
+++ /dev/null
@@ -1,825 +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.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.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 javax.management.JMException;
-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 javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.transform.OutputKeys;
-import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerException;
-import javax.xml.transform.TransformerFactory;
-import javax.xml.transform.dom.DOMSource;
-import javax.xml.transform.stream.StreamResult;
-
-
-/** MBean class for BrokerLoggingManagerMBean. It implements all the management features exposed for managing logging. */
-@MBeanDescription("Logging Management Interface")
-public class LoggingManagementMBean extends AMQManagedObject implements LoggingManagement
-{
-
- private static final Logger _logger = Logger.getLogger(LoggingManagementMBean.class);
- private String _log4jConfigFileName;
- private int _log4jLogWatchInterval;
- private static final String INHERITED = "INHERITED";
- private static final String[] LEVELS = new String[]{Level.ALL.toString(), Level.TRACE.toString(),
- Level.DEBUG.toString(), Level.INFO.toString(),
- Level.WARN.toString(), Level.ERROR.toString(),
- Level.FATAL.toString(),Level.OFF.toString(),
- INHERITED};
- static TabularType _loggerLevelTabularType;
- static CompositeType _loggerLevelCompositeType;
-
- static
- {
- try
- {
- OpenType[] loggerLevelItemTypes = new OpenType[]{SimpleType.STRING, SimpleType.STRING};
-
- _loggerLevelCompositeType = new CompositeType("LoggerLevelList", "Logger Level Data",
- COMPOSITE_ITEM_NAMES.toArray(new String[COMPOSITE_ITEM_NAMES.size()]),
- COMPOSITE_ITEM_DESCRIPTIONS.toArray(new String[COMPOSITE_ITEM_DESCRIPTIONS.size()]),
- loggerLevelItemTypes);
-
- _loggerLevelTabularType = new TabularType("LoggerLevel", "List of loggers with levels",
- _loggerLevelCompositeType,
- TABULAR_UNIQUE_INDEX.toArray(new String[TABULAR_UNIQUE_INDEX.size()]));
- }
- catch (OpenDataException e)
- {
- _logger.error("Tabular data setup for viewing logger levels was incorrect.");
- _loggerLevelTabularType = null;
- }
- }
-
- public LoggingManagementMBean(String log4jConfigFileName, int log4jLogWatchInterval) throws JMException
- {
- super(LoggingManagement.class, LoggingManagement.TYPE);
- _log4jConfigFileName = log4jConfigFileName;
- _log4jLogWatchInterval = log4jLogWatchInterval;
- }
-
- public String getObjectInstanceName()
- {
- return LoggingManagement.TYPE;
- }
-
- public Integer getLog4jLogWatchInterval()
- {
- return _log4jLogWatchInterval;
- }
-
- public String[] getAvailableLoggerLevels()
- {
- return LEVELS;
- }
- @SuppressWarnings("unchecked")
- public synchronized boolean setRuntimeLoggerLevel(String logger, String level)
- {
- //check specified level is valid
- Level newLevel;
- try
- {
- newLevel = getLevel(level);
- }
- catch (Exception e)
- {
- return false;
- }
-
- //check specified logger exists
- Enumeration loggers = LogManager.getCurrentLoggers();
- Boolean loggerExists = false;
-
- while(loggers.hasMoreElements())
- {
- Logger log = (Logger) loggers.nextElement();
- if (log.getName().equals(logger))
- {
- loggerExists = true;
- break;
- }
- }
-
- if(!loggerExists)
- {
- return false;
- }
-
- //set the logger to the new level
- _logger.info("Setting level to " + level + " for logger: " + logger);
-
- Logger log = Logger.getLogger(logger);
- log.setLevel(newLevel);
-
- return true;
- }
-
- @SuppressWarnings("unchecked")
- public synchronized TabularData viewEffectiveRuntimeLoggerLevels()
- {
- if (_loggerLevelTabularType == null)
- {
- _logger.warn("TabluarData type not set up correctly");
- return null;
- }
-
- _logger.info("Getting levels for currently active log4j loggers");
-
- Enumeration loggers = LogManager.getCurrentLoggers();
-
- TabularData loggerLevelList = new TabularDataSupport(_loggerLevelTabularType);
-
- Logger logger;
- String loggerName;
- String level;
-
- try
- {
- while(loggers.hasMoreElements()){
- logger = (Logger) loggers.nextElement();
-
- loggerName = logger.getName();
- level = logger.getEffectiveLevel().toString();
-
- Object[] itemData = {loggerName, level};
- CompositeData loggerData = new CompositeDataSupport(_loggerLevelCompositeType,
- COMPOSITE_ITEM_NAMES.toArray(new String[COMPOSITE_ITEM_NAMES.size()]), itemData);
- loggerLevelList.put(loggerData);
- }
- }
- catch (OpenDataException e)
- {
- _logger.warn("Unable to create logger level list due to :" + e);
- return null;
- }
-
- return loggerLevelList;
-
- }
-
- public synchronized String getRuntimeRootLoggerLevel()
- {
- Logger rootLogger = Logger.getRootLogger();
-
- return rootLogger.getLevel().toString();
- }
-
- public synchronized boolean setRuntimeRootLoggerLevel(String level)
- {
- Level newLevel;
- try
- {
- newLevel = getLevel(level);
- }
- catch (Exception e)
- {
- return false;
- }
-
- if(newLevel == null)
- {
- //A null Level reference implies inheritance. Setting the runtime RootLogger
- //to null is catastrophic (and prevented by Log4J at startup and runtime anyway).
- return false;
- }
-
- _logger.info("Setting RootLogger level to " + level);
-
- Logger log = Logger.getRootLogger();
- log.setLevel(newLevel);
-
- return true;
- }
-
- //method to convert from a string to a log4j Level, throws exception if the given value is invalid
- private Level getLevel(String level) throws Exception
- {
- if("null".equalsIgnoreCase(level) || INHERITED.equalsIgnoreCase(level))
- {
- //the string "null" or "inherited" signals to inherit from a parent logger,
- //using a null Level reference for the logger.
- return null;
- }
-
- Level newLevel = Level.toLevel(level);
-
- //above Level.toLevel call returns a DEBUG Level if the request fails. Check the result.
- if (newLevel.equals(Level.DEBUG) && !(level.equalsIgnoreCase("debug")))
- {
- //received DEBUG but we did not ask for it, the Level request failed.
- throw new Exception("Invalid level name");
- }
-
- return newLevel;
- }
-
- //method to parse the XML configuration file, validating it in the process, and returning a DOM Document of the content.
- private static synchronized Document parseConfigFile(String fileName) throws IOException
- {
- try
- {
- LOCK.lock();
-
- //check file was specified, exists, and is readable
- if(fileName == null)
- {
- _logger.warn("Provided log4j XML configuration filename is null");
- throw new IOException("Provided log4j XML configuration filename is null");
- }
-
- File configFile = new File(fileName);
-
- if (!configFile.exists())
- {
- _logger.warn("The log4j XML configuration file could not be found: " + fileName);
- throw new IOException("The log4j XML configuration file could not be found");
- }
- else if (!configFile.canRead())
- {
- _logger.warn("The log4j XML configuration file is not readable: " + fileName);
- throw new IOException("The log4j XML configuration file is not readable");
- }
-
- //parse it
- DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
- DocumentBuilder docBuilder;
- Document doc;
-
- ErrorHandler errHandler = new QpidLog4JSaxErrorHandler();
- try
- {
- docFactory.setValidating(true);
- docBuilder = docFactory.newDocumentBuilder();
- docBuilder.setErrorHandler(errHandler);
- docBuilder.setEntityResolver(new Log4jEntityResolver());
- doc = docBuilder.parse(fileName);
- }
- catch (ParserConfigurationException e)
- {
- _logger.warn("Unable to parse the log4j XML file due to possible configuration error: " + e);
- //recommended that MBeans should use java.* and javax.* exceptions only
- throw new IOException("Unable to parse the log4j XML file due to possible configuration error: " + e.getMessage());
- }
- catch (SAXException e)
- {
- _logger.warn("The specified log4j XML file is invalid: " + e);
- //recommended that MBeans should use standard java.* and javax.* exceptions only
- throw new IOException("The specified log4j XML file is invalid: " + e.getMessage());
- }
- catch (IOException e)
- {
- _logger.warn("Unable to parse the specified log4j XML file" + e);
- throw new IOException("Unable to parse the specified log4j XML file: " + e.getMessage());
- }
-
- return doc;
- }
- finally
- {
- LOCK.unlock();
- }
- }
-
-
- private static synchronized boolean writeUpdatedConfigFile(String log4jConfigFileName, Document doc) throws IOException
- {
- try
- {
- LOCK.lock();
-
- File log4jConfigFile = new File(log4jConfigFileName);
-
- if (!log4jConfigFile.canWrite())
- {
- _logger.warn("Specified log4j XML configuration file is not writable: " + log4jConfigFile);
- throw new IOException("Specified log4j XML configuration file is not writable");
- }
-
- Transformer transformer = null;
- try
- {
- transformer = TransformerFactory.newInstance().newTransformer();
- }
- catch (Exception e)
- {
- _logger.warn("Could not create an XML transformer: " +e);
- return false;
- }
-
- transformer.setOutputProperty(OutputKeys.INDENT, "yes");
- transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "log4j.dtd");
- DOMSource source = new DOMSource(doc);
-
- File tmp;
- Random r = new Random();
- do
- {
- tmp = new File(log4jConfigFile.getPath() + r.nextInt() + ".tmp");
- }
- while(tmp.exists());
-
- tmp.deleteOnExit();
-
- try
- {
- StreamResult result = new StreamResult(tmp);
- transformer.transform(source, result);
- }
- catch (TransformerException e)
- {
- _logger.warn("Could not transform the XML into new file: " +e);
- throw new IOException("Could not transform the XML into new file: " +e);
- }
-
- // Swap temp file in to replace existing configuration file.
- File old = new File(log4jConfigFile.getAbsoluteFile() + ".old");
- if (old.exists())
- {
- old.delete();
- }
-
- if(!log4jConfigFile.renameTo(old))
- {
- //unable to rename the existing file to the backup name
- _logger.error("Could not backup the existing log4j XML file");
- throw new IOException("Could not backup the existing log4j XML file");
- }
-
- if(!tmp.renameTo(log4jConfigFile))
- {
- //failed to rename the new file to the required filename
-
- if(!old.renameTo(log4jConfigFile))
- {
- //unable to return the backup to required filename
- _logger.error("Could not rename the new log4j configuration file into place, and unable to restore original file");
- throw new IOException("Could not rename the new log4j configuration file into place, and unable to restore original file");
- }
-
- _logger.error("Could not rename the new log4j configuration file into place");
- throw new IOException("Could not rename the new log4j configuration file into place");
- }
-
- return true;
- }
- finally
- {
- LOCK.unlock();
- }
- }
-
-
- /* The log4j XML configuration file DTD defines three possible element
- * combinations for specifying optional logger+level settings.
- * Must account for the following:
- *
- * <category name="x"> <priority value="y"/> </category> OR
- * <category name="x"> <level value="y"/> </category> OR
- * <logger name="x"> <level value="y"/> </logger>
- *
- * Noting also that the level/priority child element is optional too,
- * and not the only possible child element.
- */
-
- public static synchronized Map<String,String> retrieveConfigFileLoggersLevels(String fileName) throws IOException
- {
- try
- {
- LOCK.lock();
-
- Document doc = parseConfigFile(fileName);
-
- HashMap<String,String> loggerLevelList = new HashMap<String,String>();
-
- //retrieve the 'category' element nodes
- NodeList categoryElements = doc.getElementsByTagName("category");
-
- String categoryName;
- String priority = null;
-
- for (int i = 0; i < categoryElements.getLength(); i++)
- {
- Element categoryElement = (Element) categoryElements.item(i);
- categoryName = categoryElement.getAttribute("name");
-
- //retrieve the category's mandatory 'priority' or 'level' element's value.
- //It may not be the only child node, so request by tag name.
- NodeList priorityElements = categoryElement.getElementsByTagName("priority");
- NodeList levelElements = categoryElement.getElementsByTagName("level");
-
- if (priorityElements.getLength() != 0)
- {
- Element priorityElement = (Element) priorityElements.item(0);
- priority = priorityElement.getAttribute("value");
- }
- else if (levelElements.getLength() != 0)
- {
- Element levelElement = (Element) levelElements.item(0);
- priority = levelElement.getAttribute("value");
- }
- else
- {
- //there is no exiting priority or level to view, move onto next category/logger
- continue;
- }
-
- loggerLevelList.put(categoryName, priority);
- }
-
- //retrieve the 'logger' element nodes
- NodeList loggerElements = doc.getElementsByTagName("logger");
-
- String loggerName;
- String level;
-
- for (int i = 0; i < loggerElements.getLength(); i++)
- {
- Element loggerElement = (Element) loggerElements.item(i);
- loggerName = loggerElement.getAttribute("name");
-
- //retrieve the logger's mandatory 'level' element's value
- //It may not be the only child node, so request by tag name.
- NodeList levelElements = loggerElement.getElementsByTagName("level");
-
- Element levelElement = (Element) levelElements.item(0);
- level = levelElement.getAttribute("value");
-
- loggerLevelList.put(loggerName, level);
- }
-
- return loggerLevelList;
- }
- finally
- {
- LOCK.unlock();
- }
- }
-
- public synchronized TabularData viewConfigFileLoggerLevels() throws IOException
- {
- try
- {
- LOCK.lock();
-
- if (_loggerLevelTabularType == null)
- {
- _logger.warn("TabluarData type not set up correctly");
- return null;
- }
-
- _logger.info("Getting logger levels from log4j configuration file");
-
- TabularData loggerLevelList = new TabularDataSupport(_loggerLevelTabularType);
-
- Map<String,String> levels = retrieveConfigFileLoggersLevels(_log4jConfigFileName);
-
- for (Map.Entry<String,String> entry : levels.entrySet())
- {
- String loggerName = entry.getKey();
- String level = entry.getValue();
-
- try
- {
- Object[] itemData = {loggerName, level.toUpperCase()};
- CompositeData loggerData = new CompositeDataSupport(_loggerLevelCompositeType,
- COMPOSITE_ITEM_NAMES.toArray(new String[COMPOSITE_ITEM_NAMES.size()]), itemData);
- loggerLevelList.put(loggerData);
- }
- catch (OpenDataException e)
- {
- _logger.warn("Unable to create logger level list due to :" + e);
- return null;
- }
- }
-
- return loggerLevelList;
- }
- finally
- {
- LOCK.unlock();
- }
- }
-
- public synchronized boolean setConfigFileLoggerLevel(String logger, String level) throws IOException
- {
- try
- {
- LOCK.lock();
-
- //check that the specified level is a valid log4j Level
- try
- {
- getLevel(level);
- }
- catch (Exception e)
- {
- //it isnt a valid level
- return false;
- }
-
- _logger.info("Setting level to " + level + " for logger '" + logger
- + "' in log4j xml configuration file: " + _log4jConfigFileName);
-
- Document doc = parseConfigFile(_log4jConfigFileName);
-
- //retrieve the 'category' and 'logger' element nodes
- NodeList categoryElements = doc.getElementsByTagName("category");
- NodeList loggerElements = doc.getElementsByTagName("logger");
-
- //collect them into a single elements list
- List<Element> logElements = new ArrayList<Element>();
-
- for (int i = 0; i < categoryElements.getLength(); i++)
- {
- logElements.add((Element) categoryElements.item(i));
- }
- for (int i = 0; i < loggerElements.getLength(); i++)
- {
- logElements.add((Element) loggerElements.item(i));
- }
-
- //try to locate the specified logger/category in the elements retrieved
- Element logElement = null;
- for (Element e : logElements)
- {
- if (e.getAttribute("name").equals(logger))
- {
- logElement = e;
- break;
- }
- }
-
- if (logElement == null)
- {
- //no loggers/categories with given name found, does not exist to update
- _logger.warn("Specified logger does not exist in the configuration file: " +logger);
- return false;
- }
-
- //retrieve the optional 'priority' or 'level' sub-element value.
- //It may not be the only child node, so request by tag name.
- NodeList priorityElements = logElement.getElementsByTagName("priority");
- NodeList levelElements = logElement.getElementsByTagName("level");
-
- Element levelElement = null;
- if (priorityElements.getLength() != 0)
- {
- levelElement = (Element) priorityElements.item(0);
- }
- else if (levelElements.getLength() != 0)
- {
- levelElement = (Element) levelElements.item(0);
- }
- else
- {
- //there is no exiting priority or level element to update
- return false;
- }
-
- //update the element with the new level/priority
- levelElement.setAttribute("value", level.toLowerCase());
-
- //output the new file
- return writeUpdatedConfigFile(_log4jConfigFileName, doc);
- }
- finally
- {
- LOCK.unlock();
- }
- }
-
-
- /* The log4j XML configuration file DTD defines 2 possible element
- * combinations for specifying the optional root logger level settings
- * Must account for the following:
- *
- * <root> <priority value="y"/> </root> OR
- * <root> <level value="y"/> </root>
- *
- * Noting also that the level/priority child element is optional too,
- * and not the only possible child element.
- */
-
- public static synchronized String retrieveConfigFileRootLoggerLevel(String fileName) throws IOException
- {
- try
- {
- LOCK.lock();
-
- Document doc = parseConfigFile(fileName);
-
- //retrieve the optional 'root' element node
- NodeList rootElements = doc.getElementsByTagName("root");
-
- if (rootElements.getLength() == 0)
- {
- //there is no root logger definition
- return "N/A";
- }
-
- Element rootElement = (Element) rootElements.item(0);
-
- //retrieve the optional 'priority' or 'level' element value.
- //It may not be the only child node, so request by tag name.
- NodeList priorityElements = rootElement.getElementsByTagName("priority");
- NodeList levelElements = rootElement.getElementsByTagName("level");
- String priority = null;
-
- if (priorityElements.getLength() != 0)
- {
- Element priorityElement = (Element) priorityElements.item(0);
- priority = priorityElement.getAttribute("value");
- }
- else if(levelElements.getLength() != 0)
- {
- Element levelElement = (Element) levelElements.item(0);
- priority = levelElement.getAttribute("value");
- }
-
- if(priority != null)
- {
- return priority;
- }
- else
- {
- return "N/A";
- }
- }
- finally
- {
- LOCK.unlock();
- }
- }
-
- public synchronized String getConfigFileRootLoggerLevel() throws IOException
- {
- return retrieveConfigFileRootLoggerLevel(_log4jConfigFileName).toUpperCase();
- }
-
- public synchronized boolean setConfigFileRootLoggerLevel(String level) throws IOException
- {
- try
- {
- LOCK.lock();
-
- //check that the specified level is a valid log4j Level
- try
- {
- Level newLevel = getLevel(level);
- if(newLevel == null)
- {
- //A null Level reference implies inheritance. Setting the config file RootLogger
- //to "null" or "inherited" just ensures it defaults to DEBUG at startup as Log4J
- //prevents this catastrophic situation at startup and runtime anyway.
- return false;
- }
- }
- catch (Exception e)
- {
- //it isnt a valid level
- return false;
- }
-
- _logger.info("Setting level to " + level + " for the Root logger in " +
- "log4j xml configuration file: " + _log4jConfigFileName);
-
- Document doc = parseConfigFile(_log4jConfigFileName);
-
- //retrieve the optional 'root' element node
- NodeList rootElements = doc.getElementsByTagName("root");
-
- if (rootElements.getLength() == 0)
- {
- return false;
- }
-
- Element rootElement = (Element) rootElements.item(0);
-
- //retrieve the optional 'priority' or 'level' sub-element value.
- //It may not be the only child node, so request by tag name.
- NodeList priorityElements = rootElement.getElementsByTagName("priority");
- NodeList levelElements = rootElement.getElementsByTagName("level");
-
- Element levelElement = null;
- if (priorityElements.getLength() != 0)
- {
- levelElement = (Element) priorityElements.item(0);
- }
- else if (levelElements.getLength() != 0)
- {
- levelElement = (Element) levelElements.item(0);
- }
- else
- {
- //there is no exiting priority/level to update
- return false;
- }
-
- //update the element with the new level/priority
- levelElement.setAttribute("value", level);
-
- //output the new file
- return writeUpdatedConfigFile(_log4jConfigFileName, doc);
- }
- finally
- {
- LOCK.unlock();
- }
- }
-
- public synchronized void reloadConfigFile() throws IOException
- {
- try
- {
- LOCK.lock();
-
- QpidLog4JConfigurator.configure(_log4jConfigFileName);
- _logger.info("Applied log4j configuration from: " + _log4jConfigFileName);
- }
- catch (IllegalLoggerLevelException e)
- {
- _logger.warn("The log4j configuration reload request was aborted: " + e);
- //recommended that MBeans should use standard java.* and javax.* exceptions only
- throw new IOException("The log4j configuration reload request was aborted: " + e.getMessage());
- }
- catch (ParserConfigurationException e)
- {
- _logger.warn("The log4j configuration reload request was aborted: " + e);
- throw new IOException("The log4j configuration reload request was aborted: " + e.getMessage());
- }
- catch (SAXException e)
- {
- _logger.warn("The log4j configuration reload request was aborted: " + e);
- //recommended that MBeans should use standard java.* and javax.* exceptions only
- throw new IOException("The log4j configuration reload request was aborted: " + e.getMessage());
- }
- catch (IOException e)
- {
- _logger.warn("The log4j configuration reload request was aborted: " + e);
- throw new IOException("The log4j configuration reload request was aborted: " + e.getMessage());
- }
- finally
- {
- LOCK.unlock();
- }
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/logging/messages/Binding_logmessages.properties b/java/broker/src/main/java/org/apache/qpid/server/logging/messages/Binding_logmessages.properties
deleted file mode 100644
index 808ec7918f..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/logging/messages/Binding_logmessages.properties
+++ /dev/null
@@ -1,22 +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.
-#
-# Default File used for all non-defined locales.
-#
-CREATED = BND-1001 : Create[ : Arguments : {0}]
-DELETED = BND-1002 : Deleted
diff --git a/java/broker/src/main/java/org/apache/qpid/server/logging/messages/Broker_logmessages.properties b/java/broker/src/main/java/org/apache/qpid/server/logging/messages/Broker_logmessages.properties
deleted file mode 100644
index 5d1e85fe41..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/logging/messages/Broker_logmessages.properties
+++ /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.
-#
-# Default File used for all non-defined locales.
-
-# 0 - Version
-# 1 = Build
-STARTUP = BRK-1001 : Startup : Version: {0} Build: {1}
-# 0 - Transport
-# 1 - Port
-LISTENING = BRK-1002 : Starting : Listening on {0} port {1,number,#}
-# 0 - Transport
-# 1 - Port
-SHUTTING_DOWN = BRK-1003 : Shuting down : {0} port {1,number,#}
-READY = BRK-1004 : Qpid Broker Ready
-STOPPED = BRK-1005 : Stopped
-# 0 - path
-CONFIG = BRK-1006 : Using configuration : {0}
-# 0 - path
-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
diff --git a/java/broker/src/main/java/org/apache/qpid/server/logging/messages/Channel_logmessages.properties b/java/broker/src/main/java/org/apache/qpid/server/logging/messages/Channel_logmessages.properties
deleted file mode 100644
index ed8c0d0ce9..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/logging/messages/Channel_logmessages.properties
+++ /dev/null
@@ -1,34 +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.
-#
-# Default File used for all non-defined locales.
-
-CREATE = CHN-1001 : Create
-# 0 - flow
-FLOW = CHN-1002 : Flow {0}
-CLOSE = CHN-1003 : Close
-# 0 - bytes allowed in prefetch
-# 1 - number of messagse.
-PREFETCH_SIZE = CHN-1004 : Prefetch Size (bytes) {0,number} : Count {1,number}
-# 0 - queue causing flow control
-FLOW_ENFORCED = CHN-1005 : Flow Control Enforced (Queue {0})
-FLOW_REMOVED = CHN-1006 : Flow Control Removed
-# Channel Transactions
-# 0 - time in milliseconds
-OPEN_TXN = CHN-1007 : Open Transaction : {0,number} ms
-IDLE_TXN = CHN-1008 : Idle Transaction : {0,number} ms
diff --git a/java/broker/src/main/java/org/apache/qpid/server/logging/messages/ConfigStore_logmessages.properties b/java/broker/src/main/java/org/apache/qpid/server/logging/messages/ConfigStore_logmessages.properties
deleted file mode 100644
index 3bc5074777..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/logging/messages/ConfigStore_logmessages.properties
+++ /dev/null
@@ -1,27 +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.
-#
-# Default File used for all non-defined locales.
-
-# 0 - name
-CREATED = CFG-1001 : Created : {0}
-# 0 - path
-STORE_LOCATION = CFG-1002 : Store location : {0}
-CLOSE = CFG-1003 : Closed
-RECOVERY_START = CFG-1004 : Recovery Start
-RECOVERY_COMPLETE = CFG-1005 : Recovery Complete
diff --git a/java/broker/src/main/java/org/apache/qpid/server/logging/messages/Connection_logmessages.properties b/java/broker/src/main/java/org/apache/qpid/server/logging/messages/Connection_logmessages.properties
deleted file mode 100644
index 81ae6f3bd0..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/logging/messages/Connection_logmessages.properties
+++ /dev/null
@@ -1,24 +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.
-#
-# Default File used for all non-defined locales.
-
-# 0 - Client id
-# 1 - Protocol Version
-OPEN = CON-1001 : Open[ : Client ID : {0}][ : Protocol Version : {1}]
-CLOSE = CON-1002 : Close \ No newline at end of file
diff --git a/java/broker/src/main/java/org/apache/qpid/server/logging/messages/Exchange_logmessages.properties b/java/broker/src/main/java/org/apache/qpid/server/logging/messages/Exchange_logmessages.properties
deleted file mode 100644
index b9890d9f27..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/logging/messages/Exchange_logmessages.properties
+++ /dev/null
@@ -1,24 +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.
-#
-# Default File used for all non-defined locales.
-
-# 0 - type
-# 1 - name
-CREATED = EXH-1001 : Create :[ Durable] Type: {0} Name: {1}
-DELETED = EXH-1002 : Deleted \ No newline at end of file
diff --git a/java/broker/src/main/java/org/apache/qpid/server/logging/messages/ManagementConsole_logmessages.properties b/java/broker/src/main/java/org/apache/qpid/server/logging/messages/ManagementConsole_logmessages.properties
deleted file mode 100644
index ab77476da2..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/logging/messages/ManagementConsole_logmessages.properties
+++ /dev/null
@@ -1,33 +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.
-#
-# Default File used for all non-defined locales.
-#
-STARTUP = MNG-1001 : Startup
-# 0 - Service
-# 1 - Port
-LISTENING = MNG-1002 : Starting : {0} : Listening on port {1,number,#}
-# 0 - Service
-# 1 - Port
-SHUTTING_DOWN = MNG-1003 : Shutting down : {0} : port {1,number,#}
-READY = MNG-1004 : Ready[ : Using the platform JMX Agent]
-STOPPED = MNG-1005 : Stopped
-# 0 - Path
-SSL_KEYSTORE = MNG-1006 : Using SSL Keystore : {0}
-OPEN = MNG-1007 : Open : User {0}
-CLOSE = MNG-1008 : Close \ No newline at end of file
diff --git a/java/broker/src/main/java/org/apache/qpid/server/logging/messages/MessageStore_logmessages.properties b/java/broker/src/main/java/org/apache/qpid/server/logging/messages/MessageStore_logmessages.properties
deleted file mode 100644
index a2cedeb22a..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/logging/messages/MessageStore_logmessages.properties
+++ /dev/null
@@ -1,28 +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.
-#
-# Default File used for all non-defined locales.
-#
-# 0 - name
-CREATED = MST-1001 : Created : {0}
-# 0 - path
-STORE_LOCATION = MST-1002 : Store location : {0}
-CLOSED = MST-1003 : Closed
-RECOVERY_START = MST-1004 : Recovery Start
-RECOVERED = MST-1005 : Recovered {0,number} messages
-RECOVERY_COMPLETE = MST-1006 : Recovery Complete \ No newline at end of file
diff --git a/java/broker/src/main/java/org/apache/qpid/server/logging/messages/Queue_logmessages.properties b/java/broker/src/main/java/org/apache/qpid/server/logging/messages/Queue_logmessages.properties
deleted file mode 100644
index 538bf994ea..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/logging/messages/Queue_logmessages.properties
+++ /dev/null
@@ -1,26 +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.
-#
-# Default File used for all non-defined locales.
-#
-# 0 - owner
-# 1 - priority
-CREATED = QUE-1001 : Create :[ Owner: {0}][ AutoDelete][ Durable][ Transient][ Priority: {1,number,#}]
-DELETED = QUE-1002 : Deleted
-OVERFULL = QUE-1003 : Overfull : Size : {0,number} bytes, Capacity : {1,number}
-UNDERFULL = QUE-1004 : Underfull : Size : {0,number} bytes, Resume Capacity : {1,number}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/logging/messages/Subscription_logmessages.properties b/java/broker/src/main/java/org/apache/qpid/server/logging/messages/Subscription_logmessages.properties
deleted file mode 100644
index ef5f885b50..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/logging/messages/Subscription_logmessages.properties
+++ /dev/null
@@ -1,24 +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.
-#
-# Default File used for all non-defined locales.
-#
-CREATE = SUB-1001 : Create[ : Durable][ : Arguments : {0}]
-CLOSE = SUB-1002 : Close
-# 0 - The current subscription state
-STATE = SUB-1003 : State : {0} \ No newline at end of file
diff --git a/java/broker/src/main/java/org/apache/qpid/server/logging/messages/TransactionLog_logmessages.properties b/java/broker/src/main/java/org/apache/qpid/server/logging/messages/TransactionLog_logmessages.properties
deleted file mode 100644
index fadc2e2098..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/logging/messages/TransactionLog_logmessages.properties
+++ /dev/null
@@ -1,33 +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.
-#
-# Default File used for all non-defined locales.
-#
-#
-# 0 - name
-CREATED = TXN-1001 : Created : {0}
-# 0 - path
-STORE_LOCATION = TXN-1002 : Store location : {0}
-CLOSED = TXN-1003 : Closed
-# 0 - queue name
-RECOVERY_START = TXN-1004 : Recovery Start[ : {0}]
-# 0 - count
-# 1 - queue count
-RECOVERED = TXN-1005 : Recovered {0,number} messages for queue {1}
-# 0 - queue name
-RECOVERY_COMPLETE = TXN-1006 : Recovery Complete[ : {0}]
diff --git a/java/broker/src/main/java/org/apache/qpid/server/logging/messages/VirtualHost_logmessages.properties b/java/broker/src/main/java/org/apache/qpid/server/logging/messages/VirtualHost_logmessages.properties
deleted file mode 100644
index 3e640c7929..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/logging/messages/VirtualHost_logmessages.properties
+++ /dev/null
@@ -1,26 +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.
-#
-# Default File used for all non-defined locales.
-#
-# 0 - name
-CREATED = VHT-1001 : Created : {0}
-CLOSED = VHT-1002 : Closed
-
-STATS_DATA = VHT-1003 : {0} : {1,choice,0#delivered|1#received} : {2,number,#.###} kB/s peak : {3,number,#} bytes total
-STATS_MSGS = VHT-1004 : {0} : {1,choice,0#delivered|1#received} : {2,number,#.###} msg/s peak : {3,number,#} msgs total` \ No newline at end of file
diff --git a/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/AbstractLogSubject.java b/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/AbstractLogSubject.java
deleted file mode 100644
index 779db01601..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/AbstractLogSubject.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.server.logging.subjects;
-
-import org.apache.qpid.server.logging.LogSubject;
-
-import java.text.MessageFormat;
-
-/**
- * The LogSubjects all have a similar requriement to format their output and
- * provide the String value.
- *
- * This Abstract LogSubject provides this basic functionality, allowing the
- * actual LogSubjects to provide their formating and data.
- */
-public abstract class AbstractLogSubject implements LogSubject
-{
- /**
- * The logString that will be returned via toLogString
- */
- protected String _logString;
-
- /**
- * Set the toString logging of this LogSubject. Based on a format provided
- * by format and the var args.
- * @param format The Message to format
- * @param args The values to put in to the message.
- */
- protected void setLogStringWithFormat(String format, Object... args)
- {
- _logString = "[" + MessageFormat.format(format, args) + "] ";
- }
-
- /**
- * toLogString is how the Logging infrastructure will get the text for this
- * LogSubject
- *
- * @return String representing this LogSubject
- */
- public String toLogString()
- {
- return _logString;
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/BindingLogSubject.java b/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/BindingLogSubject.java
deleted file mode 100644
index 088b59ae68..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/BindingLogSubject.java
+++ /dev/null
@@ -1,49 +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.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
-{
-
- /**
- * Create a BindingLogSubject that Logs in the following format.
- *
- * [ vh(/)/ex(amq.direct)/qu(testQueue)/bd(testQueue) ]
- *
- * @param routingKey
- * @param exchange
- * @param queue
- */
- public BindingLogSubject(String routingKey, Exchange exchange,
- AMQQueue queue)
- {
- setLogStringWithFormat(BINDING_FORMAT, queue.getVirtualHost().getName(),
- exchange.getTypeShortString(),
- exchange.getNameShortString(),
- queue.getNameShortString(),
- routingKey);
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/ChannelLogSubject.java b/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/ChannelLogSubject.java
deleted file mode 100644
index f28873940b..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/ChannelLogSubject.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.server.logging.subjects;
-
-import org.apache.qpid.server.AMQChannel;
-import org.apache.qpid.server.protocol.AMQProtocolSession;
-import static org.apache.qpid.server.logging.subjects.LogSubjectFormat.CHANNEL_FORMAT;
-
-public class ChannelLogSubject extends AbstractLogSubject
-{
-
- public ChannelLogSubject(AMQChannel channel)
- {
- AMQProtocolSession session = channel.getProtocolSession();
-
- /**
- * LOG FORMAT used by the AMQPConnectorActor follows
- * ChannelLogSubject.CHANNEL_FORMAT :
- * con:{0}({1}@{2}/{3})/ch:{4}
- *
- * Uses a MessageFormat call to insert the required values according to
- * these indices:
- *
- * 0 - Connection ID
- * 1 - User ID
- * 2 - IP
- * 3 - Virtualhost
- * 4 - Channel ID
- */
- setLogStringWithFormat(CHANNEL_FORMAT,
- session.getSessionID(),
- session.getPrincipal().getName(),
- session.getRemoteAddress(),
- session.getVirtualHost().getName(),
- channel.getChannelId());
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/ConnectionLogSubject.java b/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/ConnectionLogSubject.java
deleted file mode 100644
index a697029d24..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/ConnectionLogSubject.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.server.logging.subjects;
-
-import org.apache.qpid.server.protocol.AMQProtocolSession;
-
-import java.text.MessageFormat;
-
-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;
-
-/** The Connection LogSubject */
-public class ConnectionLogSubject extends AbstractLogSubject
-{
-
- public ConnectionLogSubject(AMQProtocolSession session)
- {
- _session = session;
- }
-
- // The Session this Actor is representing
- private AMQProtocolSession _session;
-
- // Used to stop re-creating the _logString when we reach our final format
- private boolean _upToDate = false;
-
- /**
- * Update the LogString as the Connection process proceeds.
- *
- * When the Session has an authorized ID add that to the string.
- *
- * When the Session then gains a Vhost add that to the string, at this point
- * we can set upToDate = true as the _logString will not need to be updated
- * from this point onwards.
- */
- private void updateLogString()
- {
- if (!_upToDate)
- {
- if (_session.getPrincipal() != null)
- {
- if (_session.getVirtualHost() != null)
- {
- /**
- * LOG FORMAT used by the AMQPConnectorActor follows
- * ConnectionLogSubject.CONNECTION_FORMAT :
- * con:{0}({1}@{2}/{3})
- *
- * Uses a MessageFormat call to insert the required values
- * according to these indices:
- *
- * 0 - Connection ID 1 - User ID 2 - IP 3 - Virtualhost
- */
- _logString = "[" + MessageFormat.format(CONNECTION_FORMAT,
- _session.getSessionID(),
- _session.getPrincipal().getName(),
- _session.getRemoteAddress(),
- _session.getVirtualHost().getName())
- + "] ";
-
- _upToDate = true;
- }
- else
- {
- _logString = "[" + MessageFormat.format(USER_FORMAT,
- _session.getSessionID(),
- _session.getPrincipal().getName(),
- _session.getRemoteAddress())
- + "] ";
-
- }
- }
- else
- {
- _logString = "[" + MessageFormat.format(SOCKET_FORMAT,
- _session.getSessionID(),
- _session.getRemoteAddress())
- + "] ";
- }
- }
- }
-
- public String toLogString()
- {
- updateLogString();
- return super.toLogString();
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/ExchangeLogSubject.java b/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/ExchangeLogSubject.java
deleted file mode 100644
index 6ab44a92b9..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/ExchangeLogSubject.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.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
-{
-
- /** Create an ExchangeLogSubject that Logs in the following format. */
- public ExchangeLogSubject(Exchange exchange, VirtualHost vhost)
- {
- setLogStringWithFormat(EXCHANGE_FORMAT, vhost.getName(),
- exchange.getTypeShortString(), exchange.getNameShortString());
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/LogSubjectFormat.java b/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/LogSubjectFormat.java
deleted file mode 100644
index ff2bb90140..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/LogSubjectFormat.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.server.logging.subjects;
-
-/**
- * LogSubjectFormat class contains a list of formatting string
- * that can be statically imported where needed.
- * The formatting strings are to be used via a MessageFormat call
- * to insert the required values at the corresponding place holder
- * indices.
- *
- */
-
-public class LogSubjectFormat
-{
-
- /**
- * LOG FORMAT for the Subscription Log Subject
- * 0 - Subscription ID
- */
- public static final String SUBSCRIPTION_FORMAT = "sub:{0}";
-
- /**
- * LOG FORMAT for Connection Log Subject - SOCKET format
- * 0 - Connection ID
- * 1 - Remote Address
- */
- public static final String SOCKET_FORMAT = "con:{0}({1})";
-
- /**
- * LOG FORMAT for Connection Log Subject - USER format
- * 0 - Connection ID
- * 1 - User ID
- * 2 - IP
- */
- public static final String USER_FORMAT = "con:{0}({1}@{2})";
-
- /**
- * LOG FORMAT for the Connection Log Subject - CON format
- * 0 - Connection ID
- * 1 - User ID
- * 2 - IP
- * 3 - Virtualhost
- */
- public static final String CONNECTION_FORMAT = "con:{0}({1}@{2}/{3})";
-
- /**
- * LOG FORMAT for the Channel LogSubject
- * 0 - Connection ID
- * 1 - User ID
- * 2 - IP
- * 3 - Virtualhost
- * 4 - Channel ID
- */
- public static final String CHANNEL_FORMAT = CONNECTION_FORMAT + "/ch:{4}";
-
- /**
- * LOG FORMAT for the Exchange LogSubject,
- * 0 - Virtualhost Name
- * 1 - Exchange Type
- * 2 - Exchange Name
- */
- public static final String EXCHANGE_FORMAT = "vh(/{0})/ex({1}/{2})";
-
- /**
- * LOG FORMAT for a Binding LogSubject
- * 0 - Virtualhost Name
- * 1 - Exchange Type
- * 2 - Exchange Name
- * 3 - Queue Name
- * 4 - Binding RoutingKey
- */
- public static final String BINDING_FORMAT = "vh(/{0})/ex({1}/{2})/qu({3})/rk({4})";
-
- /**
- * LOG FORMAT for the MessagesStore LogSubject
- * 0 - Virtualhost Name
- * 1 - Message Store Type
- */
- public static final String STORE_FORMAT = "vh(/{0})/ms({1})";
-
- /**
- * LOG FORMAT for the Queue LogSubject,
- * 0 - Virtualhost name
- * 1 - queue name
- */
- public static final String QUEUE_FORMAT = "vh(/{0})/qu({1})";
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/MessageStoreLogSubject.java b/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/MessageStoreLogSubject.java
deleted file mode 100644
index 3fce13bcb5..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/MessageStoreLogSubject.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.logging.subjects;
-
-import org.apache.qpid.server.virtualhost.VirtualHost;
-import org.apache.qpid.server.store.MessageStore;
-import static org.apache.qpid.server.logging.subjects.LogSubjectFormat.STORE_FORMAT;
-
-public class MessageStoreLogSubject extends AbstractLogSubject
-{
-
- /** Create an ExchangeLogSubject that Logs in the following format. */
- public MessageStoreLogSubject(VirtualHost vhost, MessageStore store)
- {
- setLogStringWithFormat(STORE_FORMAT, vhost.getName(),
- store.getClass().getSimpleName());
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/QueueLogSubject.java b/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/QueueLogSubject.java
deleted file mode 100644
index bfe12f1a60..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/QueueLogSubject.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.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
-{
-
- /** Create an QueueLogSubject that Logs in the following format. */
- public QueueLogSubject(AMQQueue queue)
- {
- setLogStringWithFormat(QUEUE_FORMAT,
- queue.getVirtualHost().getName(),
- queue.getName());
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/SubscriptionLogSubject.java b/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/SubscriptionLogSubject.java
deleted file mode 100644
index 8b57647046..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/SubscriptionLogSubject.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.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;
-
-public class SubscriptionLogSubject extends AbstractLogSubject
-{
-
- /**
- * Create an QueueLogSubject that Logs in the following format.
- *
- * @param subscription
- */
- public SubscriptionLogSubject(Subscription subscription)
- {
- // Delegate the formating of the Queue to the QueueLogSubject. So final
- // log string format is:
- // [ sub:<id>(vh(<vhost>)/qu(<queue>)) ]
-
- String queueString = new QueueLogSubject(subscription.getQueue()).toLogString();
-
- _logString = "[" + 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/java/broker/src/main/java/org/apache/qpid/server/management/AMQManagedObject.java b/java/broker/src/main/java/org/apache/qpid/server/management/AMQManagedObject.java
deleted file mode 100644
index c4ffcd26bf..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/management/AMQManagedObject.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.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 javax.management.ListenerNotFoundException;
-import javax.management.MBeanInfo;
-import javax.management.MBeanNotificationInfo;
-import javax.management.NotCompliantMBeanException;
-import javax.management.NotificationBroadcaster;
-import javax.management.NotificationBroadcasterSupport;
-import javax.management.NotificationFilter;
-import javax.management.NotificationListener;
-
-/**
- * This class provides additinal feature of Notification Broadcaster to the
- * DefaultManagedObject.
- * @author Bhupendra Bhardwaj
- * @version 0.1
- */
-public abstract class AMQManagedObject extends DefaultManagedObject
- implements NotificationBroadcaster
-{
- /**
- * broadcaster support class
- */
- protected NotificationBroadcasterSupport _broadcaster = new NotificationBroadcasterSupport();
-
- /**
- * sequence number for notifications
- */
- protected long _notificationSequenceNumber = 0;
-
- protected MBeanInfo _mbeanInfo;
-
- protected LogActor _logActor;
-
- protected AMQManagedObject(Class<?> managementInterface, String typeName)
- throws NotCompliantMBeanException
- {
- super(managementInterface, typeName);
- // CurrentActor will be defined as these objects are created during
- // broker startup.
- _logActor = new ManagementActor(CurrentActor.get().getRootMessageLogger());
- buildMBeanInfo();
- }
-
- @Override
- public MBeanInfo getMBeanInfo()
- {
- return _mbeanInfo;
- }
-
- private void buildMBeanInfo() throws NotCompliantMBeanException
- {
- _mbeanInfo = new MBeanInfo(this.getClass().getName(),
- MBeanIntrospector.getMBeanDescription(this.getClass()),
- MBeanIntrospector.getMBeanAttributesInfo(getManagementInterface()),
- MBeanIntrospector.getMBeanConstructorsInfo(this.getClass()),
- MBeanIntrospector.getMBeanOperationsInfo(getManagementInterface()),
- this.getNotificationInfo());
- }
-
-
-
- // notification broadcaster implementation
-
- public void addNotificationListener(NotificationListener listener,
- NotificationFilter filter,
- Object handback)
- {
- _broadcaster.addNotificationListener(listener, filter, handback);
- }
-
- public void removeNotificationListener(NotificationListener listener)
- throws ListenerNotFoundException
- {
- _broadcaster.removeNotificationListener(listener);
- }
-
- public MBeanNotificationInfo[] getNotificationInfo()
- {
- return null;
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/management/DefaultManagedObject.java b/java/broker/src/main/java/org/apache/qpid/server/management/DefaultManagedObject.java
deleted file mode 100644
index 7924964fdf..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/management/DefaultManagedObject.java
+++ /dev/null
@@ -1,156 +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.management;
-
-import javax.management.JMException;
-import javax.management.MalformedObjectNameException;
-import javax.management.NotCompliantMBeanException;
-import javax.management.ObjectName;
-import javax.management.StandardMBean;
-
-import org.apache.qpid.AMQException;
-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.
- *
- */
-public abstract class DefaultManagedObject extends StandardMBean implements ManagedObject
-{
- private Class<?> _managementInterface;
-
- private String _typeName;
-
- protected DefaultManagedObject(Class<?> managementInterface, String typeName)
- throws NotCompliantMBeanException
- {
- super(managementInterface);
- _managementInterface = managementInterface;
- _typeName = typeName;
- }
-
- public String getType()
- {
- return _typeName;
- }
-
- public Class<?> getManagementInterface()
- {
- return _managementInterface;
- }
-
- public ManagedObject getParentObject()
- {
- return null;
- }
-
- public void register() throws JMException
- {
- getManagedObjectRegistry().registerObject(this);
- }
-
- protected ManagedObjectRegistry getManagedObjectRegistry()
- {
- return ApplicationRegistry.getInstance().getManagedObjectRegistry();
- }
-
- public void unregister() throws AMQException
- {
- try
- {
- getManagedObjectRegistry().unregisterObject(this);
- }
- catch (JMException e)
- {
- throw new AMQException("Error unregistering managed object: " + this + ": " + e, e);
- }
- }
-
- public String toString()
- {
- return getObjectInstanceName() + "[" + getType() + "]";
- }
-
-
- /**
- * Created the ObjectName as per the JMX Specs
- * @return ObjectName
- * @throws MalformedObjectNameException
- */
- public ObjectName getObjectName() throws MalformedObjectNameException
- {
- String name = getObjectInstanceName();
- StringBuffer objectName = new StringBuffer(ManagedObject.DOMAIN);
-
- objectName.append(":type=");
- objectName.append(getHierarchicalType(this));
-
- objectName.append(",");
- objectName.append(getHierarchicalName(this));
- objectName.append("name=").append(name);
-
- return new ObjectName(objectName.toString());
- }
-
- protected ObjectName getObjectNameForSingleInstanceMBean() throws MalformedObjectNameException
- {
- StringBuffer objectName = new StringBuffer(ManagedObject.DOMAIN);
-
- objectName.append(":type=");
- objectName.append(getHierarchicalType(this));
-
- String hierarchyName = getHierarchicalName(this);
- if (hierarchyName != null)
- {
- objectName.append(",");
- objectName.append(hierarchyName.substring(0, hierarchyName.lastIndexOf(",")));
- }
-
- return new ObjectName(objectName.toString());
- }
-
- protected String getHierarchicalType(ManagedObject obj)
- {
- if (obj.getParentObject() != null)
- {
- String parentType = getHierarchicalType(obj.getParentObject()).toString();
- return parentType + "." + obj.getType();
- }
- else
- return obj.getType();
- }
-
- protected String getHierarchicalName(ManagedObject obj)
- {
- if (obj.getParentObject() != null)
- {
- String parentName = obj.getParentObject().getType() + "=" +
- obj.getParentObject().getObjectInstanceName() + ","+
- getHierarchicalName(obj.getParentObject());
-
- return parentName;
- }
- else
- return "";
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/management/JMXManagedObjectRegistry.java b/java/broker/src/main/java/org/apache/qpid/server/management/JMXManagedObjectRegistry.java
deleted file mode 100644
index 0334a856c1..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/management/JMXManagedObjectRegistry.java
+++ /dev/null
@@ -1,447 +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.management;
-
-import org.apache.commons.configuration.ConfigurationException;
-import org.apache.log4j.Logger;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-import org.apache.qpid.server.registry.IApplicationRegistry;
-import org.apache.qpid.server.security.auth.database.PrincipalDatabase;
-import org.apache.qpid.server.security.auth.rmi.RMIPasswordAuthenticator;
-import org.apache.qpid.server.logging.actors.CurrentActor;
-import org.apache.qpid.server.logging.messages.ManagementConsoleMessages;
-
-import javax.management.JMException;
-import javax.management.MBeanServer;
-import javax.management.MBeanServerFactory;
-import javax.management.ObjectName;
-import javax.management.NotificationListener;
-import javax.management.NotificationFilterSupport;
-import javax.management.remote.JMXConnectorServer;
-import javax.management.remote.JMXServiceURL;
-import javax.management.remote.MBeanServerForwarder;
-import javax.management.remote.JMXConnectionNotification;
-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 java.io.File;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.lang.management.ManagementFactory;
-import java.lang.reflect.Proxy;
-import java.net.InetAddress;
-import java.net.ServerSocket;
-import java.net.Socket;
-import java.net.UnknownHostException;
-import java.rmi.AlreadyBoundException;
-import java.rmi.NoSuchObjectException;
-import java.rmi.NotBoundException;
-import java.rmi.registry.LocateRegistry;
-import java.rmi.registry.Registry;
-import java.rmi.server.RMIClientSocketFactory;
-import java.rmi.server.RMIServerSocketFactory;
-import java.rmi.server.UnicastRemoteObject;
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * 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.
- */
-public class JMXManagedObjectRegistry implements ManagedObjectRegistry
-{
- private static final Logger _log = Logger.getLogger(JMXManagedObjectRegistry.class);
-
- public static final String MANAGEMENT_PORT_CONFIG_PATH = "management.jmxport";
- public static final int MANAGEMENT_PORT_DEFAULT = 8999;
- public static final int PORT_EXPORT_OFFSET = 100;
-
- private final MBeanServer _mbeanServer;
- private JMXConnectorServer _cs;
- private Registry _rmiRegistry;
- private boolean _useCustomSocketFactory;
-
- public JMXManagedObjectRegistry() throws AMQException
- {
- _log.info("Initialising managed object registry using platform MBean server");
- IApplicationRegistry appRegistry = ApplicationRegistry.getInstance();
-
- // Retrieve the config parameters
- _useCustomSocketFactory = appRegistry.getConfiguration().getUseCustomRMISocketFactory();
- boolean platformServer = appRegistry.getConfiguration().getPlatformMbeanserver();
-
- _mbeanServer =
- platformServer ? ManagementFactory.getPlatformMBeanServer()
- : MBeanServerFactory.createMBeanServer(ManagedObject.DOMAIN);
- }
-
-
- public void start() throws IOException, ConfigurationException
- {
-
- CurrentActor.get().message(ManagementConsoleMessages.STARTUP());
-
- //check if system properties are set to use the JVM's out-of-the-box JMXAgent
- if (areOutOfTheBoxJMXOptionsSet())
- {
- CurrentActor.get().message(ManagementConsoleMessages.READY(true));
- return;
- }
-
- IApplicationRegistry appRegistry = ApplicationRegistry.getInstance();
- int port = appRegistry.getConfiguration().getJMXManagementPort();
-
- //retrieve the Principal Database assigned to JMX authentication duties
- String jmxDatabaseName = appRegistry.getConfiguration().getJMXPrincipalDatabase();
- Map<String, PrincipalDatabase> map = appRegistry.getDatabaseManager().getDatabases();
- PrincipalDatabase db = map.get(jmxDatabaseName);
-
- HashMap<String,Object> env = new HashMap<String,Object>();
-
- //Socket factories for the RMIConnectorServer, either default or SLL depending on configuration
- RMIClientSocketFactory csf;
- RMIServerSocketFactory ssf;
-
- //check ssl enabled option in config, default to true if option is not set
- boolean sslEnabled = appRegistry.getConfiguration().getManagementSSLEnabled();
-
- if (sslEnabled)
- {
- //set the SSL related system properties used by the SSL RMI socket factories to the values
- //given in the configuration file, unless command line settings have already been specified
- String keyStorePath;
-
- if(System.getProperty("javax.net.ssl.keyStore") != null)
- {
- keyStorePath = System.getProperty("javax.net.ssl.keyStore");
- }
- else
- {
- keyStorePath = appRegistry.getConfiguration().getManagementKeyStorePath();
- }
-
- //check the keystore path value is valid
- if (keyStorePath == null)
- {
- throw new ConfigurationException("JMX management SSL keystore path not defined, " +
- "unable to start SSL protected JMX ConnectorServer");
- }
- else
- {
- //ensure the system property is set
- System.setProperty("javax.net.ssl.keyStore", keyStorePath);
-
- //check the file is usable
- File ksf = new File(keyStorePath);
-
- 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.");
- }
- if (!ksf.canRead())
- {
- throw new FileNotFoundException("Cannot read JMX management SSL keystore file: "
- + ksf + ". Check permissions.");
- }
-
- CurrentActor.get().message(ManagementConsoleMessages.SSL_KEYSTORE(ksf.getAbsolutePath()));
- }
-
- //check the key store password is set
- if (System.getProperty("javax.net.ssl.keyStorePassword") == null)
- {
-
- if (appRegistry.getConfiguration().getManagementKeyStorePassword() == null)
- {
- throw new ConfigurationException("JMX management SSL keystore password not defined, " +
- "unable to start requested SSL protected JMX server");
- }
- else
- {
- System.setProperty("javax.net.ssl.keyStorePassword",
- appRegistry.getConfiguration().getManagementKeyStorePassword());
- }
- }
-
- //create the SSL RMI socket factories
- csf = new SslRMIClientSocketFactory();
- ssf = new SslRMIServerSocketFactory();
- }
- else
- {
- //Do not specify any specific RMI socket factories, resulting in use of the defaults.
- csf = null;
- ssf = null;
- }
-
- //add a JMXAuthenticator implementation the env map to authenticate the RMI based JMX connector server
- RMIPasswordAuthenticator rmipa = new RMIPasswordAuthenticator();
- rmipa.setPrincipalDatabase(db);
- env.put(JMXConnectorServer.AUTHENTICATOR, rmipa);
-
- /*
- * Start a RMI registry on the management port, to hold the JMX RMI ConnectorServer stub.
- * Using custom socket factory to prevent anyone (including us unfortunately) binding to the registry using RMI.
- * As a result, only binds made using the object reference will succeed, thus securing it from external change.
- */
- System.setProperty("java.rmi.server.randomIDs", "true");
- if(_useCustomSocketFactory)
- {
- _rmiRegistry = LocateRegistry.createRegistry(port, null, new CustomRMIServerSocketFactory());
- }
- else
- {
- _rmiRegistry = LocateRegistry.createRegistry(port, null, null);
- }
-
- CurrentActor.get().message(ManagementConsoleMessages.LISTENING("RMI Registry", port));
-
- /*
- * We must now create the RMI ConnectorServer manually, as the JMX Factory methods use RMI calls
- * to bind the ConnectorServer to the registry, which will now fail as for security we have
- * locked it from any RMI based modifications, including our own. Instead, we will manually bind
- * the RMIConnectorServer stub to the registry using its object reference, which will still succeed.
- *
- * The registry is exported on the defined management port 'port'. We will export the RMIConnectorServer
- * on 'port +1'. Use of these two well-defined ports will ease any navigation through firewall's.
- */
- final RMIServerImpl rmiConnectorServerStub = new RMIJRMPServerImpl(port+PORT_EXPORT_OFFSET, csf, ssf, env);
- String localHost;
- try
- {
- localHost = InetAddress.getLocalHost().getHostName();
- }
- catch(UnknownHostException ex)
- {
- localHost="127.0.0.1";
- }
- final String hostname = localHost;
- final JMXServiceURL externalUrl = new JMXServiceURL(
- "service:jmx:rmi://"+hostname+":"+(port+PORT_EXPORT_OFFSET)+"/jndi/rmi://"+hostname+":"+port+"/jmxrmi");
-
- final JMXServiceURL internalUrl = new JMXServiceURL("rmi", hostname, port+PORT_EXPORT_OFFSET);
- _cs = new RMIConnectorServer(internalUrl, env, rmiConnectorServerStub, _mbeanServer)
- {
- @Override
- public synchronized void start() throws IOException
- {
- try
- {
- //manually bind the connector server to the registry at key 'jmxrmi', like the out-of-the-box agent
- _rmiRegistry.bind("jmxrmi", rmiConnectorServerStub);
- }
- catch (AlreadyBoundException abe)
- {
- //key was already in use. shouldnt happen here as its a new registry, unbindable by normal means.
-
- //IOExceptions are the only checked type throwable by the method, wrap and rethrow
- IOException ioe = new IOException(abe.getMessage());
- ioe.initCause(abe);
- throw ioe;
- }
-
- //now do the normal tasks
- super.start();
- }
-
- @Override
- public synchronized void stop() throws IOException
- {
- try
- {
- if (_rmiRegistry != null)
- {
- _rmiRegistry.unbind("jmxrmi");
- }
- }
- catch (NotBoundException nbe)
- {
- //ignore
- }
-
- //now do the normal tasks
- super.stop();
- }
-
- @Override
- public JMXServiceURL getAddress()
- {
- //must return our pre-crafted url that includes the full details, inc JNDI details
- return externalUrl;
- }
-
- };
-
-
- //Add the custom invoker as an MBeanServerForwarder, and start the RMIConnectorServer.
- MBeanServerForwarder mbsf = MBeanInvocationHandlerImpl.newProxyInstance();
- _cs.setMBeanServerForwarder(mbsf);
-
- NotificationFilterSupport filter = new NotificationFilterSupport();
- filter.enableType(JMXConnectionNotification.OPENED);
- filter.enableType(JMXConnectionNotification.CLOSED);
- filter.enableType(JMXConnectionNotification.FAILED);
- // Get the handler that is used by the above MBInvocationHandler Proxy.
- // which is the MBeanInvocationHandlerImpl and so also a NotificationListener
- _cs.addNotificationListener((NotificationListener) Proxy.getInvocationHandler(mbsf), filter, null);
-
- _cs.start();
-
- String connectorServer = (sslEnabled ? "SSL " : "") + "JMX RMIConnectorServer";
- CurrentActor.get().message(ManagementConsoleMessages.LISTENING(connectorServer, port + PORT_EXPORT_OFFSET));
-
- CurrentActor.get().message(ManagementConsoleMessages.READY(false));
- }
-
- /*
- * Custom RMIServerSocketFactory class, used to prevent updates to the RMI registry.
- * Supplied to the registry at creation, this will prevent RMI-based operations on the
- * registry such as attempting to bind a new object, thereby securing it from tampering.
- * This is accomplished by always returning null when attempting to determine the address
- * of the caller, thus ensuring the registry will refuse the attempt. Calls to bind etc
- * made using the object reference will not be affected and continue to operate normally.
- */
-
- private static class CustomRMIServerSocketFactory implements RMIServerSocketFactory
- {
-
- public ServerSocket createServerSocket(int port) throws IOException
- {
- return new NoLocalAddressServerSocket(port);
- }
-
- private static class NoLocalAddressServerSocket extends ServerSocket
- {
- NoLocalAddressServerSocket(int port) throws IOException
- {
- super(port);
- }
-
- @Override
- public Socket accept() throws IOException
- {
- Socket s = new NoLocalAddressSocket();
- super.implAccept(s);
- return s;
- }
- }
-
- private static class NoLocalAddressSocket extends Socket
- {
- @Override
- public InetAddress getInetAddress()
- {
- return null;
- }
- }
- }
-
-
- public void registerObject(ManagedObject managedObject) throws JMException
- {
- _mbeanServer.registerMBean(managedObject, managedObject.getObjectName());
- }
-
- public void unregisterObject(ManagedObject managedObject) throws JMException
- {
- _mbeanServer.unregisterMBean(managedObject.getObjectName());
- }
-
- // checks if the system properties are set which enable the JVM's out-of-the-box JMXAgent.
- private boolean areOutOfTheBoxJMXOptionsSet()
- {
- if (System.getProperty("com.sun.management.jmxremote") != null)
- {
- return true;
- }
-
- if (System.getProperty("com.sun.management.jmxremote.port") != null)
- {
- return true;
- }
-
- return false;
- }
-
- //Stops the JMXConnectorServer and RMIRegistry, then unregisters any remaining MBeans from the MBeanServer
- public void close()
- {
- if (_cs != null)
- {
- // Stopping the JMX ConnectorServer
- try
- {
- CurrentActor.get().message(ManagementConsoleMessages.SHUTTING_DOWN("JMX RMIConnectorServer", _cs.getAddress().getPort()));
- _cs.stop();
- }
- catch (IOException e)
- {
- _log.error("Exception while closing the JMX ConnectorServer: " + e.getMessage());
- }
- }
-
- if (_rmiRegistry != null)
- {
- // Stopping the RMI registry
- CurrentActor.get().message(ManagementConsoleMessages.SHUTTING_DOWN("RMI Registry", _cs.getAddress().getPort() - PORT_EXPORT_OFFSET));
- try
- {
- UnicastRemoteObject.unexportObject(_rmiRegistry, false);
- }
- catch (NoSuchObjectException e)
- {
- _log.error("Exception while closing the RMI Registry: " + e.getMessage());
- }
- }
-
- //ObjectName query to gather all Qpid related MBeans
- ObjectName mbeanNameQuery = null;
- try
- {
- mbeanNameQuery = new ObjectName(ManagedObject.DOMAIN + ":*");
- }
- catch (Exception e1)
- {
- _log.warn("Unable to generate MBean ObjectName query for close operation");
- }
-
- for (ObjectName name : _mbeanServer.queryNames(mbeanNameQuery, null))
- {
- try
- {
- _mbeanServer.unregisterMBean(name);
- }
- catch (JMException e)
- {
- _log.error("Exception unregistering MBean '"+ name +"': " + e.getMessage());
- }
- }
-
- CurrentActor.get().message(ManagementConsoleMessages.STOPPED());
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/management/MBeanIntrospector.java b/java/broker/src/main/java/org/apache/qpid/server/management/MBeanIntrospector.java
deleted file mode 100644
index 17a6851abc..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/management/MBeanIntrospector.java
+++ /dev/null
@@ -1,396 +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.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 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;
-
-/**
- * This class is a utility class to introspect the MBean class and the management
- * interface class for various purposes.
- * @author Bhupendra Bhardwaj
- * @version 0.1
- */
-class MBeanIntrospector {
-
- private static final String _defaultAttributeDescription = "Management attribute";
- private static final String _defaultOerationDescription = "Management operation";
- private static final String _defaultConstructorDescription = "MBean constructor";
- private static final String _defaultMbeanDescription = "Management interface of the MBean";
-
- /**
- * Introspects the management interface class for MBean attributes.
- * @param interfaceClass
- * @return MBeanAttributeInfo[]
- * @throws NotCompliantMBeanException
- */
- static MBeanAttributeInfo[] getMBeanAttributesInfo(Class interfaceClass)
- throws NotCompliantMBeanException
- {
- List<MBeanAttributeInfo> attributesList = new ArrayList<MBeanAttributeInfo>();
-
- /**
- * Using reflection, all methods of the managemetn interface will be analysed,
- * and MBeanInfo will be created.
- */
- for (Method method : interfaceClass.getMethods())
- {
- String name = method.getName();
- Class<?> resultType = method.getReturnType();
- MBeanAttributeInfo attributeInfo = null;
-
- if (isAttributeGetterMethod(method))
- {
- String desc = getAttributeDescription(method);
- attributeInfo = new MBeanAttributeInfo(name.substring(3),
- resultType.getName(),
- desc,
- true,
- false,
- false);
- int index = getIndexIfAlreadyExists(attributeInfo, attributesList);
- if (index == -1)
- {
- attributesList.add(attributeInfo);
- }
- else
- {
- attributeInfo = new MBeanAttributeInfo(name.substring(3),
- resultType.getName(),
- desc,
- true,
- true,
- false);
- attributesList.set(index, attributeInfo);
- }
- }
- else if (isAttributeSetterMethod(method))
- {
- String desc = getAttributeDescription(method);
- attributeInfo = new MBeanAttributeInfo(name.substring(3),
- method.getParameterTypes()[0].getName(),
- desc,
- false,
- true,
- false);
- int index = getIndexIfAlreadyExists(attributeInfo, attributesList);
- if (index == -1)
- {
- attributesList.add(attributeInfo);
- }
- else
- {
- attributeInfo = new MBeanAttributeInfo(name.substring(3),
- method.getParameterTypes()[0].getName(),
- desc,
- true,
- true,
- false);
- attributesList.set(index, attributeInfo);
- }
- }
- else if (isAttributeBoolean(method))
- {
- attributeInfo = new MBeanAttributeInfo(name.substring(2),
- resultType.getName(),
- getAttributeDescription(method),
- true,
- false,
- true);
- attributesList.add(attributeInfo);
- }
- }
-
- return attributesList.toArray(new MBeanAttributeInfo[0]);
- }
-
- /**
- * Introspects the management interface class for management operations.
- * @param interfaceClass
- * @return MBeanOperationInfo[]
- */
- static MBeanOperationInfo[] getMBeanOperationsInfo(Class interfaceClass)
- {
- List<MBeanOperationInfo> operationsList = new ArrayList<MBeanOperationInfo>();
-
- for (Method method : interfaceClass.getMethods())
- {
- if (!isAttributeGetterMethod(method) &&
- !isAttributeSetterMethod(method) &&
- !isAttributeBoolean(method))
- {
- operationsList.add(getOperationInfo(method));
- }
- }
-
- return operationsList.toArray(new MBeanOperationInfo[0]);
- }
-
- /**
- * Checks if the method is an attribute getter method.
- * @param method
- * @return true if the method is an attribute getter method.
- */
- private static boolean isAttributeGetterMethod(Method method)
- {
- if (!(method.getName().equals("get")) &&
- method.getName().startsWith("get") &&
- method.getParameterTypes().length == 0 &&
- !method.getReturnType().equals(void.class))
- {
- return true;
- }
-
- return false;
- }
-
- /**
- * Checks if the method is an attribute setter method.
- * @param method
- * @return true if the method is an attribute setter method.
- */
- private static boolean isAttributeSetterMethod(Method method)
- {
- if (!(method.getName().equals("set")) &&
- method.getName().startsWith("set") &&
- method.getParameterTypes().length == 1 &&
- method.getReturnType().equals(void.class))
- {
- return true;
- }
-
- return false;
- }
-
- /**
- * Checks if the attribute is a boolean and the method is a isX kind og method.
- * @param method
- * @return true if the method is an attribute isX type of method
- */
- private static boolean isAttributeBoolean(Method method)
- {
- if (!(method.getName().equals("is")) &&
- method.getName().startsWith("is") &&
- method.getParameterTypes().length == 0 &&
- method.getReturnType().equals(boolean.class))
- {
- return true;
- }
-
- return false;
- }
-
- /**
- * Helper method to retrieve the attribute index from the list of attributes.
- * @param attribute
- * @param list
- * @return attribute index no. -1 if attribtue doesn't exist
- * @throws NotCompliantMBeanException
- */
- private static int getIndexIfAlreadyExists(MBeanAttributeInfo attribute,
- List<MBeanAttributeInfo> list)
- throws NotCompliantMBeanException
- {
- String exceptionMsg = "Conflicting attribute methods for attribute " + attribute.getName();
-
- for (MBeanAttributeInfo memberAttribute : list)
- {
- if (attribute.getName().equals(memberAttribute.getName()))
- {
- if (!attribute.getType().equals(memberAttribute.getType()))
- {
- throw new NotCompliantMBeanException(exceptionMsg);
- }
- if (attribute.isReadable() && memberAttribute.isReadable())
- {
- if (attribute.isIs() != memberAttribute.isIs())
- {
- throw new NotCompliantMBeanException(exceptionMsg);
- }
- }
-
- return list.indexOf(memberAttribute);
- }
- }
-
- return -1;
- }
-
- /**
- * Retrieves the attribute description from annotation
- * @param attributeMethod
- * @return attribute description
- */
- private static String getAttributeDescription(Method attributeMethod)
- {
- MBeanAttribute anno = attributeMethod.getAnnotation(MBeanAttribute.class);
- if (anno != null)
- {
- return anno.description();
- }
- return _defaultAttributeDescription;
- }
-
- /**
- * Introspects the method to retrieve the operation information.
- * @param operation
- * @return MBeanOperationInfo
- */
- private static MBeanOperationInfo getOperationInfo(Method operation)
- {
- MBeanOperationInfo operationInfo = null;
- Class<?> returnType = operation.getReturnType();
-
- MBeanParameterInfo[] paramsInfo = getParametersInfo(operation.getParameterAnnotations(),
- operation.getParameterTypes());
-
- String operationDesc = _defaultOerationDescription;
- int impact = MBeanOperationInfo.UNKNOWN;
-
- if (operation.getAnnotation(MBeanOperation.class) != null)
- {
- operationDesc = operation.getAnnotation(MBeanOperation.class).description();
- impact = operation.getAnnotation(MBeanOperation.class).impact();
- }
- operationInfo = new MBeanOperationInfo(operation.getName(),
- operationDesc,
- paramsInfo,
- returnType.getName(),
- impact);
-
- return operationInfo;
- }
-
- /**
- * Constructs the parameter info.
- * @param paramsAnno
- * @param paramTypes
- * @return MBeanParameterInfo[]
- */
- private static MBeanParameterInfo[] getParametersInfo(Annotation[][] paramsAnno,
- Class<?>[] paramTypes)
- {
- int noOfParams = paramsAnno.length;
-
- MBeanParameterInfo[] paramsInfo = new MBeanParameterInfo[noOfParams];
-
- for (int i = 0; i < noOfParams; i++)
- {
- MBeanParameterInfo paramInfo = null;
- String type = paramTypes[i].getName();
- for (Annotation anno : paramsAnno[i])
- {
- String name,desc;
- if (MBeanOperationParameter.class.isInstance(anno))
- {
- name = MBeanOperationParameter.class.cast(anno).name();
- desc = MBeanOperationParameter.class.cast(anno).description();
- paramInfo = new MBeanParameterInfo(name, type, desc);
- }
- }
-
-
- if (paramInfo == null)
- {
- paramInfo = new MBeanParameterInfo("p " + (i + 1), type, "parameter " + (i + 1));
- }
- if (paramInfo != null)
- paramsInfo[i] = paramInfo;
- }
-
- return paramsInfo;
- }
-
- /**
- * Introspects the MBean class for constructors
- * @param implClass
- * @return MBeanConstructorInfo[]
- */
- static MBeanConstructorInfo[] getMBeanConstructorsInfo(Class implClass)
- {
- List<MBeanConstructorInfo> constructors = new ArrayList<MBeanConstructorInfo>();
-
- 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]);
- }
-
- /**
- * Retrieves the constructor info from given constructor.
- * @param cons
- * @return MBeanConstructorInfo
- */
- private static MBeanConstructorInfo getMBeanConstructorInfo(Constructor cons)
- {
- String desc = _defaultConstructorDescription;
- Annotation anno = cons.getAnnotation(MBeanConstructor.class);
- if (anno != null && MBeanConstructor.class.isInstance(anno))
- {
- desc = MBeanConstructor.class.cast(anno).value();
- if(desc == null)
- {
- desc = _defaultConstructorDescription;
- }
- }
-
- //MBeanParameterInfo[] paramsInfo = getParametersInfo(cons.getParameterAnnotations(),
- // cons.getParameterTypes());
-
- return new MBeanConstructorInfo(cons.getName(), desc, null);
- }
-
- /**
- * Retrieves the description from the annotations of given class
- * @param annotatedClass
- * @return class description
- */
- static String getMBeanDescription(Class annotatedClass)
- {
- Annotation anno = annotatedClass.getAnnotation(MBeanDescription.class);
- if (anno != null && MBeanDescription.class.isInstance(anno))
- {
- return MBeanDescription.class.cast(anno).value();
- }
- return _defaultMbeanDescription;
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/management/MBeanInvocationHandlerImpl.java b/java/broker/src/main/java/org/apache/qpid/server/management/MBeanInvocationHandlerImpl.java
deleted file mode 100644
index 380f51e308..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/management/MBeanInvocationHandlerImpl.java
+++ /dev/null
@@ -1,329 +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.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.security.Principal;
-import java.util.Properties;
-import java.util.Set;
-
-import javax.management.Attribute;
-import javax.management.JMException;
-import javax.management.MBeanInfo;
-import javax.management.MBeanOperationInfo;
-import javax.management.MBeanServer;
-import javax.management.Notification;
-import javax.management.NotificationListener;
-import javax.management.ObjectName;
-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.CurrentActor;
-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.security.SecurityManager;
-import org.apache.qpid.server.security.access.Operation;
-
-/**
- * This class can be used by the JMXConnectorServer as an InvocationHandler for the mbean operations. This implements
- * the logic for allowing the users to invoke MBean operations and implements the restrictions for readOnly, readWrite
- * and admin users.
- */
-public class MBeanInvocationHandlerImpl implements InvocationHandler, NotificationListener
-{
- private static final Logger _logger = Logger.getLogger(MBeanInvocationHandlerImpl.class);
-
- public final static String ADMIN = "admin";
- public final static String READWRITE = "readwrite";
- public final static String READONLY = "readonly";
- private final static String DELEGATE = "JMImplementation:type=MBeanServerDelegate";
- private MBeanServer _mbs;
- private static Properties _userRoles = new Properties();
- private static ManagementActor _logActor;
-
- public static MBeanServerForwarder newProxyInstance()
- {
- final InvocationHandler handler = new MBeanInvocationHandlerImpl();
- final Class<?>[] interfaces = new Class[] { MBeanServerForwarder.class };
-
-
- _logActor = new ManagementActor(ApplicationRegistry.getInstance().getRootMessageLogger());
-
- Object proxy = Proxy.newProxyInstance(MBeanServerForwarder.class.getClassLoader(), interfaces, handler);
- return MBeanServerForwarder.class.cast(proxy);
- }
-
- public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
- {
- final String methodName = getMethodName(method, args);
-
- if (methodName.equals("getMBeanServer"))
- {
- return _mbs;
- }
-
- if (methodName.equals("setMBeanServer"))
- {
- if (args[0] == null)
- {
- throw new IllegalArgumentException("Null MBeanServer");
- }
- if (_mbs != null)
- {
- throw new IllegalArgumentException("MBeanServer object already initialized");
- }
- _mbs = (MBeanServer) args[0];
- return null;
- }
-
- // Retrieve Subject from current AccessControlContext
- AccessControlContext acc = AccessController.getContext();
- Subject subject = Subject.getSubject(acc);
-
- try
- {
- // Allow operations performed locally on behalf of the connector server itself
- if (subject == null)
- {
- return method.invoke(_mbs, args);
- }
-
- if (args == null || DELEGATE.equals(args[0]))
- {
- return method.invoke(_mbs, args);
- }
-
- // Restrict access to "createMBean" and "unregisterMBean" to any user
- if (methodName.equals("createMBean") || methodName.equals("unregisterMBean"))
- {
- _logger.debug("User trying to create or unregister an MBean");
- throw new SecurityException("Access denied: " + methodName);
- }
-
- // Allow querying available object names
- if (methodName.equals("queryNames"))
- {
- return method.invoke(_mbs, args);
- }
-
- // Retrieve JMXPrincipal from Subject
- Set<JMXPrincipal> principals = subject.getPrincipals(JMXPrincipal.class);
- if (principals == null || principals.isEmpty())
- {
- throw new SecurityException("Access denied: no principal");
- }
-
- // Save the principal
- Principal principal = principals.iterator().next();
- SecurityManager.setThreadPrincipal(principal);
-
- // Get the component, type and impact, which may be null
- String type = getType(method, args);
- String vhost = getVirtualHost(method, args);
- int impact = getImpact(method, args);
-
- // Get the security manager for the virtual host (if set)
- SecurityManager security;
- if (vhost == null)
- {
- security = ApplicationRegistry.getInstance().getSecurityManager();
- }
- else
- {
- security = ApplicationRegistry.getInstance().getVirtualHostRegistry().getVirtualHost(vhost).getSecurityManager();
- }
-
- if (isAccessMethod(methodName) || impact == MBeanOperationInfo.INFO)
- {
- // Check for read-only method invocation permission
- if (!security.authoriseMethod(Operation.ACCESS, type, methodName))
- {
- throw new SecurityException("Permission denied: Access " + methodName);
- }
- }
- else if (isUpdateMethod(methodName))
- {
- // Check for setting properties permission
- if (!security.authoriseMethod(Operation.UPDATE, type, methodName))
- {
- throw new SecurityException("Permission denied: Update " + methodName);
- }
- }
- else
- {
- // Check for invoking/executing method action/operation permission
- if (!security.authoriseMethod(Operation.EXECUTE, type, methodName))
- {
- throw new SecurityException("Permission denied: Execute " + methodName);
- }
- }
-
- // Actually invoke the method
- return method.invoke(_mbs, args);
- }
- catch (InvocationTargetException e)
- {
- throw e.getTargetException();
- }
- }
-
- private String getType(Method method, Object[] args)
- {
- if (args[0] instanceof ObjectName)
- {
- ObjectName object = (ObjectName) args[0];
- String type = object.getKeyProperty("type");
-
- return type;
- }
- return null;
- }
-
- private String getVirtualHost(Method method, Object[] args)
- {
- if (args[0] instanceof ObjectName)
- {
- ObjectName object = (ObjectName) args[0];
- String vhost = object.getKeyProperty("VirtualHost");
-
- if(vhost != null)
- {
- try
- {
- //if the name is quoted in the ObjectName, unquote it
- vhost = ObjectName.unquote(vhost);
- }
- catch(IllegalArgumentException e)
- {
- //ignore, this just means the name is not quoted
- //and can be left unchanged
- }
- }
-
- return vhost;
- }
- return null;
- }
-
- private String getMethodName(Method method, Object[] args)
- {
- String methodName = method.getName();
-
- // if arguments are set, try and work out real method name
- if (args != null && args.length >= 1 && args[0] instanceof ObjectName)
- {
- if (methodName.equals("getAttribute"))
- {
- methodName = "get" + (String) args[1];
- }
- else if (methodName.equals("setAttribute"))
- {
- methodName = "set" + ((Attribute) args[1]).getName();
- }
- else if (methodName.equals("invoke"))
- {
- methodName = (String) args[1];
- }
- }
-
- return methodName;
- }
-
- private int getImpact(Method method, Object[] args)
- {
- //handle invocation of other methods on mbeans
- if ((args[0] instanceof ObjectName) && (method.getName().equals("invoke")))
- {
- //get invoked method name
- String mbeanMethod = (args.length > 1) ? (String) args[1] : null;
- if (mbeanMethod == null)
- {
- return -1;
- }
-
- try
- {
- //Get the impact attribute
- MBeanInfo mbeanInfo = _mbs.getMBeanInfo((ObjectName) args[0]);
- if (mbeanInfo != null)
- {
- MBeanOperationInfo[] opInfos = mbeanInfo.getOperations();
- for (MBeanOperationInfo opInfo : opInfos)
- {
- if (opInfo.getName().equals(mbeanMethod))
- {
- return opInfo.getImpact();
- }
- }
- }
- }
- catch (JMException ex)
- {
- ex.printStackTrace();
- }
- }
-
- return -1;
- }
-
- private boolean isAccessMethod(String methodName)
- {
- //handle standard get/query/is methods from MBeanServer
- return (methodName.startsWith("query") || methodName.startsWith("get") || methodName.startsWith("is"));
- }
-
-
- private boolean isUpdateMethod(String methodName)
- {
- //handle standard set methods from MBeanServer
- return methodName.startsWith("set");
- }
-
- public void handleNotification(Notification notification, Object handback)
- {
- assert notification instanceof JMXConnectionNotification;
-
- // only RMI Connections are serviced here, Local API atta
- // rmi://169.24.29.116 guest 3
- String[] connectionData = ((JMXConnectionNotification) notification).getConnectionId().split(" ");
- String user = connectionData[1];
-
- if (notification.getType().equals(JMXConnectionNotification.OPENED))
- {
- _logActor.message(ManagementConsoleMessages.OPEN(user));
- }
- else if (notification.getType().equals(JMXConnectionNotification.CLOSED) ||
- notification.getType().equals(JMXConnectionNotification.FAILED))
- {
- _logActor.message(ManagementConsoleMessages.CLOSE());
- }
- }
-}
-
diff --git a/java/broker/src/main/java/org/apache/qpid/server/management/Managable.java b/java/broker/src/main/java/org/apache/qpid/server/management/Managable.java
deleted file mode 100644
index 166a2a376d..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/management/Managable.java
+++ /dev/null
@@ -1,34 +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.management;
-
-/**
- * Any object that can return a related MBean should implement this interface.
- *
- * This enables other classes to get the managed object, which in turn is useful when
- * constructing relationships between managed objects without having to maintain
- * separate data structures containing MBeans.
- *
- */
-public interface Managable
-{
- ManagedObject getManagedObject();
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/management/ManagedObject.java b/java/broker/src/main/java/org/apache/qpid/server/management/ManagedObject.java
deleted file mode 100644
index de14785fb0..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/management/ManagedObject.java
+++ /dev/null
@@ -1,59 +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.management;
-
-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.
- */
-public interface ManagedObject
-{
- static final String DOMAIN = "org.apache.qpid";
-
- /**
- * @return the name that uniquely identifies this object instance. It must be
- * unique only among objects of this type at this level in the hierarchy so
- * the uniqueness should not be too difficult to ensure.
- */
- String getObjectInstanceName();
-
- String getType();
-
- Class<?> getManagementInterface();
-
- ManagedObject getParentObject();
-
- void register() throws AMQException, JMException;
-
- void unregister() throws AMQException;
-
- /**
- * Returns the ObjectName required for the mbeanserver registration.
- * @return ObjectName
- * @throws MalformedObjectNameException
- */
- ObjectName getObjectName() throws MalformedObjectNameException;
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/management/ManagedObjectRegistry.java b/java/broker/src/main/java/org/apache/qpid/server/management/ManagedObjectRegistry.java
deleted file mode 100644
index fda80ad0dd..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/management/ManagedObjectRegistry.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.management;
-
-import javax.management.JMException;
-
-import org.apache.commons.configuration.ConfigurationException;
-import org.apache.qpid.common.Closeable;
-
-import java.rmi.RemoteException;
-import java.io.IOException;
-
-/**
- * Handles the registration (and unregistration and so on) of managed objects.
- *
- * Managed objects are responsible for exposting attributes, operations and notifications. They will expose
- * these outside the JVM therefore it is important not to use implementation objects directly as managed objects.
- * Instead, creating inner classes and exposing those is an effective way of exposing internal state in a
- * controlled way.
- *
- * Although we do not explictly use them while targetting Java 5, the enhanced MXBean approach in Java 6 will
- * be the obvious choice for managed objects.
- *
- */
-public interface ManagedObjectRegistry extends Closeable
-{
- void start() throws IOException, ConfigurationException;
-
- void registerObject(ManagedObject managedObject) throws JMException;
-
- void unregisterObject(ManagedObject managedObject) throws JMException;
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/management/NoopManagedObjectRegistry.java b/java/broker/src/main/java/org/apache/qpid/server/management/NoopManagedObjectRegistry.java
deleted file mode 100644
index a048e75b2e..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/management/NoopManagedObjectRegistry.java
+++ /dev/null
@@ -1,60 +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.management;
-
-import javax.management.JMException;
-
-import org.apache.log4j.Logger;
-
-import java.rmi.RemoteException;
-
-/**
- * This managed object registry does not actually register MBeans. This can be used in tests when management is
- * not required or when management has been disabled.
- *
- */
-public class NoopManagedObjectRegistry implements ManagedObjectRegistry
-{
- private static final Logger _log = Logger.getLogger(NoopManagedObjectRegistry.class);
-
- public NoopManagedObjectRegistry()
- {
- _log.info("Management is disabled");
- }
-
- public void start()
- {
- //no-op
- }
-
- public void registerObject(ManagedObject managedObject) throws JMException
- {
- }
-
- public void unregisterObject(ManagedObject managedObject) throws JMException
- {
- }
-
- public void close()
- {
-
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/message/AMQMessage.java b/java/broker/src/main/java/org/apache/qpid/server/message/AMQMessage.java
deleted file mode 100644
index e0c181a5fc..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/message/AMQMessage.java
+++ /dev/null
@@ -1,346 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.message;
-
-import org.apache.log4j.Logger;
-import org.apache.qpid.AMQException;
-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 java.util.concurrent.atomic.AtomicInteger;
-import java.lang.ref.WeakReference;
-import java.nio.ByteBuffer;
-
-/**
- * A deliverable message.
- */
-public class AMQMessage implements ServerMessage
-{
- /** Used for debugging purposes. */
- private static final Logger _log = Logger.getLogger(AMQMessage.class);
-
- private final AtomicInteger _referenceCount = new AtomicInteger(0);
-
- /** Flag to indicate that this message requires 'immediate' delivery. */
-
- private static final byte IMMEDIATE = 0x01;
-
- /**
- * Flag to indicate whether this message has been delivered to a consumer. Used in implementing return functionality
- * for messages published with the 'immediate' flag.
- */
-
- private static final byte DELIVERED_TO_CONSUMER = 0x02;
-
- private byte _flags = 0;
-
- private long _expiration;
-
- private final long _size;
-
- private Object _sessionIdentifier;
- private static final byte IMMEDIATE_AND_DELIVERED = (byte) (IMMEDIATE | DELIVERED_TO_CONSUMER);
-
- private final StoredMessage<MessageMetaData> _handle;
-
- WeakReference<AMQChannel> _channelRef;
-
-
- public AMQMessage(StoredMessage<MessageMetaData> handle)
- {
- this(handle, null);
- }
-
- public AMQMessage(StoredMessage<MessageMetaData> handle, WeakReference<AMQChannel> channelRef)
- {
- _handle = handle;
- final MessageMetaData metaData = handle.getMetaData();
- _size = metaData.getContentSize();
- final MessagePublishInfo messagePublishInfo = metaData.getMessagePublishInfo();
-
- if(messagePublishInfo.isImmediate())
- {
- _flags |= IMMEDIATE;
- }
-
- _channelRef = channelRef;
- }
-
-
- public String debugIdentity()
- {
- return "(HC:" + System.identityHashCode(this) + " ID:" + getMessageId() + " Ref:" + _referenceCount.get() + ")";
- }
-
- public void setExpiration(final long expiration)
- {
-
- _expiration = expiration;
-
- }
-
- public boolean isReferenced()
- {
- return _referenceCount.get() > 0;
- }
-
- public MessageMetaData getMessageMetaData()
- {
- return _handle.getMetaData();
- }
-
- public ContentHeaderBody getContentHeaderBody() throws AMQException
- {
- return getMessageMetaData().getContentHeaderBody();
- }
-
-
-
- public Long getMessageId()
- {
- return _handle.getMessageNumber();
- }
-
- /**
- * Creates a long-lived reference to this message, and increments the count of such references, as an atomic
- * operation.
- */
- public AMQMessage takeReference()
- {
- incrementReference(); // _referenceCount.incrementAndGet();
-
- return this;
- }
-
- public boolean incrementReference()
- {
- return incrementReference(1);
- }
-
- /* Threadsafe. Increment the reference count on the message. */
- public boolean incrementReference(int count)
- {
-
- if(_referenceCount.addAndGet(count) <= 0)
- {
- _referenceCount.addAndGet(-count);
- return false;
- }
- else
- {
- return true;
- }
-
- }
-
- /**
- * Threadsafe. This will decrement the reference count and when it reaches zero will remove the message from the
- * message store.
- *
- *
- * @throws org.apache.qpid.server.queue.MessageCleanupException when an attempt was made to remove the message from the message store and that
- * failed
- */
- public void decrementReference()
- {
- int count = _referenceCount.decrementAndGet();
-
- // note that the operation of decrementing the reference count and then removing the message does not
- // have to be atomic since the ref count starts at 1 and the exchange itself decrements that after
- // the message has been passed to all queues. i.e. we are
- // not relying on the all the increments having taken place before the delivery manager decrements.
- if (count == 0)
- {
- // set the reference count way below 0 so that we can detect that the message has been deleted
- // this is to guard against the message being spontaneously recreated (from the mgmt console)
- // by copying from other queues at the same time as it is being removed.
- _referenceCount.set(Integer.MIN_VALUE/2);
-
- // must check if the handle is null since there may be cases where we decide to throw away a message
- // and the handle has not yet been constructed
- if (_handle != null)
- {
- _handle.remove();
-
- }
- }
- else
- {
- if (count < 0)
- {
- throw new RuntimeException("Reference count for message id " + debugIdentity()
- + " has gone below 0.");
- }
- }
- }
-
-
- /**
- * Called selectors to determin if the message has already been sent
- *
- * @return _deliveredToConsumer
- */
- public boolean getDeliveredToConsumer()
- {
- return (_flags & DELIVERED_TO_CONSUMER) != 0;
- }
-
- public String getRoutingKey()
- {
- // TODO
- return null;
- }
-
- public AMQMessageHeader getMessageHeader()
- {
- return getMessageMetaData().getMessageHeader();
- }
-
- public boolean isPersistent()
- {
- return getMessageMetaData().isPersistent();
- }
-
- /**
- * Called to enforce the 'immediate' flag.
- *
- * @returns true if the message is marked for immediate delivery but has not been marked as delivered
- * to a consumer
- */
- public boolean immediateAndNotDelivered()
- {
-
- return (_flags & IMMEDIATE_AND_DELIVERED) == IMMEDIATE;
-
- }
-
- public MessagePublishInfo getMessagePublishInfo() throws AMQException
- {
- return getMessageMetaData().getMessagePublishInfo();
- }
-
- public long getArrivalTime()
- {
- return getMessageMetaData().getArrivalTime();
- }
-
- /**
- * Checks to see if the message has expired. If it has the message is dequeued.
- *
- * @param queue The queue to check the expiration against. (Currently not used)
- *
- * @return true if the message has expire
- *
- * @throws AMQException
- */
- public boolean expired(AMQQueue queue) throws AMQException
- {
-
- if (_expiration != 0L)
- {
- long now = System.currentTimeMillis();
-
- return (now > _expiration);
- }
-
- return false;
- }
-
- /**
- * Called when this message is delivered to a consumer. (used to implement the 'immediate' flag functionality).
- * And for selector efficiency.
- */
- public void setDeliveredToConsumer()
- {
- _flags |= DELIVERED_TO_CONSUMER;
- }
-
- public long getSize()
- {
- return _size;
-
- }
-
- public boolean isImmediate()
- {
- return (_flags & IMMEDIATE) == IMMEDIATE;
- }
-
- public long getExpiration()
- {
- return _expiration;
- }
-
- public MessageReference newReference()
- {
- return new AMQMessageReference(this);
- }
-
- public Long getMessageNumber()
- {
- return getMessageId();
- }
-
-
- public Object getPublisherIdentifier()
- {
- //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;
-
- }
-
- public void setClientIdentifier(final Object sessionIdentifier)
- {
- _sessionIdentifier = sessionIdentifier;
- }
-
-
- public String toString()
- {
- // return "Message[" + debugIdentity() + "]: " + _messageId + "; ref count: " + _referenceCount + "; taken : " +
- // _taken + " by :" + _takenBySubcription;
-
- return "Message[" + debugIdentity() + "]: " + getMessageId() + "; ref count: " + _referenceCount;
- }
-
- public int getContent(ByteBuffer buf, int offset)
- {
- return _handle.getContent(offset, buf);
- }
-
- public StoredMessage<MessageMetaData> getStoredMessage()
- {
- return _handle;
- }
-
- public SessionConfig getSessionConfig()
- {
- return _channelRef == null ? null : ((SessionConfig) _channelRef.get());
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/message/AMQMessageHeader.java b/java/broker/src/main/java/org/apache/qpid/server/message/AMQMessageHeader.java
deleted file mode 100644
index faac14f8a7..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/message/AMQMessageHeader.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.message;
-
-import java.util.Set;
-
-public interface AMQMessageHeader
-{
- String getCorrelationId();
-
- long getExpiration();
-
- String getMessageId();
-
- String getMimeType();
-
- String getEncoding();
-
- byte getPriority();
-
- long getTimestamp();
-
- String getType();
-
- String getReplyTo();
-
- String getReplyToExchange();
- String getReplyToRoutingKey();
-
-
- Object getHeader(String name);
-
- boolean containsHeaders(Set<String> names);
-
- boolean containsHeader(String name);
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/message/AMQMessageReference.java b/java/broker/src/main/java/org/apache/qpid/server/message/AMQMessageReference.java
deleted file mode 100644
index 940caaefe4..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/message/AMQMessageReference.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.message;
-
-import org.apache.qpid.server.message.AMQMessage;
-import org.apache.qpid.server.queue.MessageCleanupException;
-
-public class AMQMessageReference extends MessageReference<AMQMessage>
-{
-
-
- public AMQMessageReference(AMQMessage message)
- {
- super(message);
- }
-
- protected void onReference(AMQMessage message)
- {
- message.incrementReference();
- }
-
- protected void onRelease(AMQMessage message)
- {
- message.decrementReference();
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/message/ContentHeaderBodyAdapter.java b/java/broker/src/main/java/org/apache/qpid/server/message/ContentHeaderBodyAdapter.java
deleted file mode 100644
index 84a1642578..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/message/ContentHeaderBodyAdapter.java
+++ /dev/null
@@ -1,127 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.message;
-
-import org.apache.qpid.framing.ContentHeaderBody;
-import org.apache.qpid.framing.BasicContentHeaderProperties;
-import org.apache.qpid.framing.FieldTable;
-
-import java.util.Set;
-
-public class ContentHeaderBodyAdapter implements AMQMessageHeader
-{
- private final ContentHeaderBody _contentHeaderBody;
-
- public ContentHeaderBodyAdapter(ContentHeaderBody contentHeaderBody)
- {
- _contentHeaderBody = contentHeaderBody;
- }
-
- private BasicContentHeaderProperties getProperties()
- {
- return (BasicContentHeaderProperties) _contentHeaderBody.getProperties();
- }
-
- public String getCorrelationId()
- {
- return getProperties().getCorrelationIdAsString();
- }
-
- public long getExpiration()
- {
- return getProperties().getExpiration();
- }
-
- public String getMessageId()
- {
- return getProperties().getMessageIdAsString();
- }
-
- public String getMimeType()
- {
- return getProperties().getContentTypeAsString();
- }
-
- public String getEncoding()
- {
- return getProperties().getEncodingAsString();
- }
-
- public byte getPriority()
- {
- return getProperties().getPriority();
- }
-
- public long getTimestamp()
- {
- return getProperties().getTimestamp();
- }
-
- public String getType()
- {
- return getProperties().getTypeAsString();
- }
-
- public String getReplyTo()
- {
- return getProperties().getReplyToAsString();
- }
-
- public String getReplyToExchange()
- {
- // TODO
- return getReplyTo();
- }
-
- public String getReplyToRoutingKey()
- {
- // TODO
- return getReplyTo();
-
- }
-
- public Object getHeader(String name)
- {
- FieldTable ft = getProperties().getHeaders();
- return ft.get(name);
- }
-
- public boolean containsHeaders(Set<String> names)
- {
- FieldTable ft = getProperties().getHeaders();
- for(String name : names)
- {
- if(!ft.containsKey(name))
- {
- return false;
- }
- }
- return true;
- }
-
- public boolean containsHeader(String name)
- {
- FieldTable ft = getProperties().getHeaders();
- return ft.containsKey(name);
- }
-
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/message/EnqueableMessage.java b/java/broker/src/main/java/org/apache/qpid/server/message/EnqueableMessage.java
deleted file mode 100755
index c32f80fc5b..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/message/EnqueableMessage.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-*
-* Licensed to the Apache Software Foundation (ASF) under one
-* or more contributor license agreements. See the NOTICE file
-* distributed with this work for additional information
-* regarding copyright ownership. The ASF licenses this file
-* to you under the Apache License, Version 2.0 (the
-* "License"); you may not use this file except in compliance
-* with the License. You may obtain a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing,
-* software distributed under the License is distributed on an
-* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-* KIND, either express or implied. See the License for the
-* specific language governing permissions and limitations
-* under the License.
-*
-*/
-package org.apache.qpid.server.message;
-
-public interface EnqueableMessage
-{
- Long getMessageNumber();
- boolean isPersistent();
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/message/InboundMessage.java b/java/broker/src/main/java/org/apache/qpid/server/message/InboundMessage.java
deleted file mode 100644
index 1b3fdb1870..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/message/InboundMessage.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.message;
-
-
-import org.apache.qpid.server.queue.Filterable;
-
-public interface InboundMessage extends Filterable
-{
- String getRoutingKey();
-
- AMQMessageHeader getMessageHeader();
-
- boolean isPersistent();
-
- boolean isRedelivered();
-
- long getSize();
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/message/MessageContentSource.java b/java/broker/src/main/java/org/apache/qpid/server/message/MessageContentSource.java
deleted file mode 100755
index 08a09c4a85..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/message/MessageContentSource.java
+++ /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.
- *
- */
-
-package org.apache.qpid.server.message;
-
-import java.nio.ByteBuffer;
-
-public interface MessageContentSource
-{
- public int getContent(ByteBuffer buf, int offset);
-
- long getSize();
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/message/MessageMetaData.java b/java/broker/src/main/java/org/apache/qpid/server/message/MessageMetaData.java
deleted file mode 100644
index 66cb7ed83b..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/message/MessageMetaData.java
+++ /dev/null
@@ -1,320 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.message;
-
-import org.apache.qpid.framing.ContentHeaderBody;
-import org.apache.qpid.framing.BasicContentHeaderProperties;
-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 java.nio.ByteBuffer;
-import java.util.Set;
-
-/**
- * Encapsulates a publish body and a content header. In the context of the message store these are treated as a
- * single unit.
- */
-public class MessageMetaData implements StorableMessageMetaData
-{
- private MessagePublishInfo _messagePublishInfo;
-
- private ContentHeaderBody _contentHeaderBody;
-
- private int _contentChunkCount;
-
- private long _arrivalTime;
- private static final byte MANDATORY_FLAG = 1;
- private static final byte IMMEDIATE_FLAG = 2;
- public static final MessageMetaDataType.Factory<MessageMetaData> FACTORY = new MetaDataFactory();
-
- public MessageMetaData(MessagePublishInfo publishBody, ContentHeaderBody contentHeaderBody, int contentChunkCount)
- {
- this(publishBody,contentHeaderBody, contentChunkCount, System.currentTimeMillis());
- }
-
- public MessageMetaData(MessagePublishInfo publishBody, ContentHeaderBody contentHeaderBody, int contentChunkCount, long arrivalTime)
- {
- _contentHeaderBody = contentHeaderBody;
- _messagePublishInfo = publishBody;
- _contentChunkCount = contentChunkCount;
- _arrivalTime = arrivalTime;
- }
-
- public int getContentChunkCount()
- {
- return _contentChunkCount;
- }
-
- public void setContentChunkCount(int contentChunkCount)
- {
- _contentChunkCount = contentChunkCount;
- }
-
- public ContentHeaderBody getContentHeaderBody()
- {
- return _contentHeaderBody;
- }
-
- public void setContentHeaderBody(ContentHeaderBody contentHeaderBody)
- {
- _contentHeaderBody = contentHeaderBody;
- }
-
- public MessagePublishInfo getMessagePublishInfo()
- {
- return _messagePublishInfo;
- }
-
- public void setMessagePublishInfo(MessagePublishInfo messagePublishInfo)
- {
- _messagePublishInfo = messagePublishInfo;
- }
-
- public long getArrivalTime()
- {
- return _arrivalTime;
- }
-
- public void setArrivalTime(long arrivalTime)
- {
- _arrivalTime = arrivalTime;
- }
-
- public MessageMetaDataType getType()
- {
- return MessageMetaDataType.META_DATA_0_8;
- }
-
- public int getStorableSize()
- {
- int size = _contentHeaderBody.getSize();
- size += 4;
- size += EncodingUtils.encodedShortStringLength(_messagePublishInfo.getExchange());
- size += EncodingUtils.encodedShortStringLength(_messagePublishInfo.getRoutingKey());
- size += 1; // flags for immediate/mandatory
- size += EncodingUtils.encodedLongLength();
-
- return size;
- }
-
- public int writeToBuffer(int offset, ByteBuffer dest)
- {
- ByteBuffer src = ByteBuffer.allocate((int)getStorableSize());
-
- org.apache.mina.common.ByteBuffer minaSrc = org.apache.mina.common.ByteBuffer.wrap(src);
- EncodingUtils.writeInteger(minaSrc, _contentHeaderBody.getSize());
- _contentHeaderBody.writePayload(minaSrc);
- EncodingUtils.writeShortStringBytes(minaSrc, _messagePublishInfo.getExchange());
- EncodingUtils.writeShortStringBytes(minaSrc, _messagePublishInfo.getRoutingKey());
- byte flags = 0;
- if(_messagePublishInfo.isMandatory())
- {
- flags |= MANDATORY_FLAG;
- }
- if(_messagePublishInfo.isImmediate())
- {
- flags |= IMMEDIATE_FLAG;
- }
- EncodingUtils.writeByte(minaSrc, flags);
- EncodingUtils.writeLong(minaSrc,_arrivalTime);
- src.position(minaSrc.position());
- src.flip();
- src.position(offset);
- src = src.slice();
- if(dest.remaining() < src.limit())
- {
- src.limit(dest.remaining());
- }
- dest.put(src);
-
-
- return src.limit();
- }
-
- public int getContentSize()
- {
- return (int) _contentHeaderBody.bodySize;
- }
-
- public boolean isPersistent()
- {
- BasicContentHeaderProperties properties = (BasicContentHeaderProperties) (_contentHeaderBody.getProperties());
- return properties.getDeliveryMode() == BasicContentHeaderProperties.PERSISTENT;
- }
-
- private static class MetaDataFactory implements MessageMetaDataType.Factory
- {
-
-
- public MessageMetaData createMetaData(ByteBuffer buf)
- {
- try
- {
- org.apache.mina.common.ByteBuffer minaSrc = org.apache.mina.common.ByteBuffer.wrap(buf);
- int size = EncodingUtils.readInteger(minaSrc);
- ContentHeaderBody chb = ContentHeaderBody.createFromBuffer(minaSrc, size);
- final AMQShortString exchange = EncodingUtils.readAMQShortString(minaSrc);
- final AMQShortString routingKey = EncodingUtils.readAMQShortString(minaSrc);
-
- final byte flags = EncodingUtils.readByte(minaSrc);
- long arrivalTime = EncodingUtils.readLong(minaSrc);
-
- MessagePublishInfo publishBody =
- new MessagePublishInfo()
- {
-
- public AMQShortString getExchange()
- {
- return exchange;
- }
-
- public void setExchange(AMQShortString exchange)
- {
- }
-
- public boolean isImmediate()
- {
- return (flags & IMMEDIATE_FLAG) != 0;
- }
-
- public boolean isMandatory()
- {
- return (flags & MANDATORY_FLAG) != 0;
- }
-
- public AMQShortString getRoutingKey()
- {
- return routingKey;
- }
- };
- return new MessageMetaData(publishBody, chb, 0, arrivalTime);
- }
- catch (AMQException e)
- {
- throw new RuntimeException(e);
- }
-
- }
- };
-
- public AMQMessageHeader getMessageHeader()
- {
- return new MessageHeaderAdapter();
- }
-
- private final class MessageHeaderAdapter implements AMQMessageHeader
- {
- private BasicContentHeaderProperties getProperties()
- {
- return (BasicContentHeaderProperties) getContentHeaderBody().getProperties();
- }
-
- public String getCorrelationId()
- {
- return getProperties().getCorrelationIdAsString();
- }
-
- public long getExpiration()
- {
- return getProperties().getExpiration();
- }
-
- public String getMessageId()
- {
- return getProperties().getMessageIdAsString();
- }
-
- public String getMimeType()
- {
- return getProperties().getContentTypeAsString();
- }
-
- public String getEncoding()
- {
- return getProperties().getEncodingAsString();
- }
-
- public byte getPriority()
- {
- return getProperties().getPriority();
- }
-
- public long getTimestamp()
- {
- return getProperties().getTimestamp();
- }
-
- public String getType()
- {
- return getProperties().getTypeAsString();
- }
-
- public String getReplyTo()
- {
- return getProperties().getReplyToAsString();
- }
-
- public String getReplyToExchange()
- {
- // TODO
- return getReplyTo();
- }
-
- public String getReplyToRoutingKey()
- {
- // TODO
- return getReplyTo();
- }
-
- public Object getHeader(String name)
- {
- FieldTable ft = getProperties().getHeaders();
- return ft.get(name);
- }
-
- public boolean containsHeaders(Set<String> names)
- {
- FieldTable ft = getProperties().getHeaders();
- for(String name : names)
- {
- if(!ft.containsKey(name))
- {
- return false;
- }
- }
- return true;
- }
-
- public boolean containsHeader(String name)
- {
- FieldTable ft = getProperties().getHeaders();
- return ft.containsKey(name);
- }
-
-
-
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/message/MessageMetaData_0_10.java b/java/broker/src/main/java/org/apache/qpid/server/message/MessageMetaData_0_10.java
deleted file mode 100755
index cf8ae2166c..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/message/MessageMetaData_0_10.java
+++ /dev/null
@@ -1,242 +0,0 @@
-/*
-*
-* Licensed to the Apache Software Foundation (ASF) under one
-* or more contributor license agreements. See the NOTICE file
-* distributed with this work for additional information
-* regarding copyright ownership. The ASF licenses this file
-* to you under the Apache License, Version 2.0 (the
-* "License"); you may not use this file except in compliance
-* with the License. You may obtain a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing,
-* software distributed under the License is distributed on an
-* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-* KIND, either express or implied. See the License for the
-* specific language governing permissions and limitations
-* under the License.
-*
-*/
-package org.apache.qpid.server.message;
-
-import org.apache.qpid.server.store.StorableMessageMetaData;
-import org.apache.qpid.server.store.MessageMetaDataType;
-import org.apache.qpid.transport.MessageTransfer;
-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.Struct;
-import org.apache.qpid.transport.codec.BBEncoder;
-import org.apache.qpid.transport.codec.BBDecoder;
-
-import java.nio.ByteBuffer;
-import java.lang.ref.SoftReference;
-
-public class MessageMetaData_0_10 implements StorableMessageMetaData
-{
- private Header _header;
- private DeliveryProperties _deliveryProps;
- private MessageProperties _messageProps;
- private MessageTransferHeader _messageHeader;
- private long _arrivalTime;
- private int _bodySize;
- private volatile SoftReference<ByteBuffer> _body;
-
- private static final int ENCODER_SIZE = 1 << 16;
-
- public static final MessageMetaDataType.Factory<MessageMetaData_0_10> FACTORY = new MetaDataFactory();
-
- private volatile ByteBuffer _encoded;
-
-
- public MessageMetaData_0_10(MessageTransfer xfr)
- {
- this(xfr.getHeader(), xfr.getBodySize(), xfr.getBody(), System.currentTimeMillis());
- }
-
- private MessageMetaData_0_10(Header header, int bodySize, long arrivalTime)
- {
- this(header, bodySize, null, arrivalTime);
- }
-
- private MessageMetaData_0_10(Header header, int bodySize, ByteBuffer xfrBody, long arrivalTime)
- {
- _header = header;
- if(_header != null)
- {
- _deliveryProps = _header.get(DeliveryProperties.class);
- _messageProps = _header.get(MessageProperties.class);
- }
- else
- {
- _deliveryProps = null;
- _messageProps = null;
- }
- _messageHeader = new MessageTransferHeader(_deliveryProps, _messageProps);
- _arrivalTime = arrivalTime;
- _bodySize = bodySize;
-
-
-
- if(xfrBody == null)
- {
- _body = null;
- }
- else
- {
- ByteBuffer body = ByteBuffer.allocate(_bodySize);
- body.put(xfrBody);
- body.flip();
- _body = new SoftReference<ByteBuffer>(body);
- }
-
-
- }
-
-
-
- public MessageMetaDataType getType()
- {
- return MessageMetaDataType.META_DATA_0_10;
- }
-
- public int getStorableSize()
- {
- ByteBuffer buf = _encoded;
-
- if(buf == null)
- {
- buf = encodeAsBuffer();
- _encoded = buf;
- }
-
- //TODO -- need to add stuff
- return buf.limit();
- }
-
- private ByteBuffer encodeAsBuffer()
- {
- BBEncoder encoder = new BBEncoder(ENCODER_SIZE);
-
- encoder.writeInt64(_arrivalTime);
- encoder.writeInt32(_bodySize);
- Struct[] headers = _header == null ? new Struct[0] : _header.getStructs();
- encoder.writeInt32(headers.length);
-
-
- for(Struct header : headers)
- {
- encoder.writeStruct32(header);
-
- }
-
- ByteBuffer buf = encoder.buffer();
- return buf;
- }
-
- public int writeToBuffer(int offsetInMetaData, ByteBuffer dest)
- {
- ByteBuffer buf = _encoded;
-
- if(buf == null)
- {
- buf = encodeAsBuffer();
- _encoded = buf;
- }
-
- buf = buf.duplicate();
-
- buf.position(offsetInMetaData);
-
- if(dest.remaining() < buf.limit())
- {
- buf.limit(dest.remaining());
- }
- dest.put(buf);
- return buf.limit();
- }
-
- public int getContentSize()
- {
- return _bodySize;
- }
-
- public boolean isPersistent()
- {
- return _deliveryProps == null ? false : _deliveryProps.getDeliveryMode() == MessageDeliveryMode.PERSISTENT;
- }
-
- public String getRoutingKey()
- {
- return _deliveryProps == null ? null : _deliveryProps.getRoutingKey();
- }
-
- public AMQMessageHeader getMessageHeader()
- {
- return _messageHeader;
- }
-
- public long getSize()
- {
-
- return _bodySize;
- }
-
- public boolean isImmediate()
- {
- return _deliveryProps != null && _deliveryProps.getImmediate();
- }
-
- public long getExpiration()
- {
- return _deliveryProps == null ? 0L : _deliveryProps.getExpiration();
- }
-
- public long getArrivalTime()
- {
- return _arrivalTime;
- }
-
- public Header getHeader()
- {
- return _header;
- }
-
- public ByteBuffer getBody()
- {
- ByteBuffer body = _body == null ? null : _body.get();
- return body;
- }
-
- public void setBody(ByteBuffer body)
- {
- _body = new SoftReference<ByteBuffer>(body);
- }
-
- private static class MetaDataFactory implements MessageMetaDataType.Factory<MessageMetaData_0_10>
- {
- public MessageMetaData_0_10 createMetaData(ByteBuffer buf)
- {
- BBDecoder decoder = new BBDecoder();
- decoder.init(buf);
-
- long arrivalTime = decoder.readInt64();
- int bodySize = decoder.readInt32();
- int headerCount = decoder.readInt32();
-
- Struct[] headers = new Struct[headerCount];
-
- for(int i = 0 ; i < headerCount; i++)
- {
- headers[i] = decoder.readStruct32();
- }
-
- Header header = new Header(headers);
-
- return new MessageMetaData_0_10(header, bodySize, arrivalTime);
-
- }
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/message/MessageReference.java b/java/broker/src/main/java/org/apache/qpid/server/message/MessageReference.java
deleted file mode 100644
index 399f8f9327..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/message/MessageReference.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.message;
-
-import java.util.concurrent.atomic.AtomicBoolean;
-
-public abstract class MessageReference<M extends ServerMessage>
-{
-
- private final AtomicBoolean _released = new AtomicBoolean(false);
-
- private volatile M _message;
-
- public MessageReference(M message)
- {
- _message = message;
- onReference(message);
- }
-
- abstract protected void onReference(M message);
-
- abstract protected void onRelease(M message);
-
- public M getMessage()
- {
- return _message;
- }
-
- public void release()
- {
- if(!_released.getAndSet(true))
- {
- if(_message != null)
- {
- onRelease(_message);
- }
- }
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/message/MessageTransferHeader.java b/java/broker/src/main/java/org/apache/qpid/server/message/MessageTransferHeader.java
deleted file mode 100644
index 31cf223428..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/message/MessageTransferHeader.java
+++ /dev/null
@@ -1,153 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.message;
-
-import org.apache.qpid.transport.DeliveryProperties;
-import org.apache.qpid.transport.MessageProperties;
-import org.apache.qpid.transport.MessageDeliveryPriority;
-
-import java.util.Set;
-import java.util.Map;
-import java.util.UUID;
-
-class MessageTransferHeader implements AMQMessageHeader
-{
-
-
- public static final String JMS_TYPE = "x-jms-type";
-
- private final DeliveryProperties _deliveryProps;
- private final MessageProperties _messageProps;
-
- public MessageTransferHeader(DeliveryProperties deliveryProps, MessageProperties messageProps)
- {
- _deliveryProps = deliveryProps;
- _messageProps = messageProps;
- }
-
- public String getCorrelationId()
- {
- if (_messageProps != null && _messageProps.getCorrelationId() != null)
- {
- return new String(_messageProps.getCorrelationId());
- }
- else
- {
- return null;
- }
- }
-
- public long getExpiration()
- {
- return _deliveryProps == null ? 0L : _deliveryProps.getExpiration();
- }
-
- public String getMessageId()
- {
- UUID id = _messageProps == null ? null : _messageProps.getMessageId();
-
- return id == null ? null : String.valueOf(id);
- }
-
- public String getMimeType()
- {
- return _messageProps == null ? null : _messageProps.getContentType();
- }
-
- public String getEncoding()
- {
- return _messageProps == null ? null : _messageProps.getContentEncoding();
- }
-
- public byte getPriority()
- {
- MessageDeliveryPriority priority = _deliveryProps == null
- ? MessageDeliveryPriority.MEDIUM
- : _deliveryProps.getPriority();
- return (byte) priority.getValue();
- }
-
- public long getTimestamp()
- {
- return _deliveryProps == null ? 0L : _deliveryProps.getTimestamp();
- }
-
- public String getType()
- {
- Object type = getHeader(JMS_TYPE);
- return type instanceof String ? (String) type : null;
- }
-
- public String getReplyTo()
- {
- if (_messageProps != null && _messageProps.getReplyTo() != null)
- {
- return _messageProps.getReplyTo().toString();
- }
- else
- {
- return null;
- }
- }
-
- public String getReplyToExchange()
- {
- if (_messageProps != null && _messageProps.getReplyTo() != null)
- {
- return _messageProps.getReplyTo().getExchange();
- }
- else
- {
- return null;
- }
- }
-
- public String getReplyToRoutingKey()
- {
- if (_messageProps != null && _messageProps.getReplyTo() != null)
- {
- return _messageProps.getReplyTo().getRoutingKey();
- }
- else
- {
- return null;
- }
- }
-
- public Object getHeader(String name)
- {
- Map<String, Object> appHeaders = _messageProps == null ? null : _messageProps.getApplicationHeaders();
- return appHeaders == null ? null : appHeaders.get(name);
- }
-
- public boolean containsHeaders(Set<String> names)
- {
- Map<String, Object> appHeaders = _messageProps == null ? null : _messageProps.getApplicationHeaders();
- return appHeaders != null && appHeaders.keySet().containsAll(names);
-
- }
-
- public boolean containsHeader(String name)
- {
- Map<String, Object> appHeaders = _messageProps == null ? null : _messageProps.getApplicationHeaders();
- return appHeaders != null && appHeaders.containsKey(name);
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/message/MessageTransferMessage.java b/java/broker/src/main/java/org/apache/qpid/server/message/MessageTransferMessage.java
deleted file mode 100644
index 08006435f8..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/message/MessageTransferMessage.java
+++ /dev/null
@@ -1,149 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.message;
-
-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 java.nio.ByteBuffer;
-import java.lang.ref.WeakReference;
-
-
-public class MessageTransferMessage implements InboundMessage, ServerMessage
-{
-
-
- private StoredMessage<MessageMetaData_0_10> _storeMessage;
-
-
- private WeakReference<Session> _sessionRef;
-
- public MessageTransferMessage(StoredMessage<MessageMetaData_0_10> storeMessage, WeakReference<Session> sessionRef)
- {
-
- _storeMessage = storeMessage;
- _sessionRef = sessionRef;
- }
-
- private MessageMetaData_0_10 getMetaData()
- {
- return _storeMessage.getMetaData();
- }
-
- public String getRoutingKey()
- {
- return getMetaData().getRoutingKey();
-
- }
-
- public AMQMessageHeader getMessageHeader()
- {
- return getMetaData().getMessageHeader();
- }
-
- public boolean isPersistent()
- {
- return getMetaData().isPersistent();
- }
-
-
- public boolean isRedelivered()
- {
- // The *Message* is never redelivered, only queue entries are... this is here so that filters
- // can run against the message on entry to an exchange
- return false;
- }
-
- public long getSize()
- {
-
- return getMetaData().getSize();
- }
-
- public boolean isImmediate()
- {
- return getMetaData().isImmediate();
- }
-
- public long getExpiration()
- {
- return getMetaData().getExpiration();
- }
-
- public MessageReference newReference()
- {
- return new TransferMessageReference(this);
- }
-
- public Long getMessageNumber()
- {
- return _storeMessage.getMessageNumber();
- }
-
- public long getArrivalTime()
- {
- return getMetaData().getArrivalTime();
- }
-
- public int getContent(ByteBuffer buf, int offset)
- {
- return _storeMessage.getContent(offset, buf);
- }
-
- public Header getHeader()
- {
- return getMetaData().getHeader();
- }
-
- public ByteBuffer getBody()
- {
- ByteBuffer body = getMetaData().getBody();
- if(body == null && getSize() != 0l)
- {
- final int size = (int) getSize();
- int pos = 0;
- body = ByteBuffer.allocate(size);
-
- while(pos < size)
- {
- pos += getContent(body, pos);
- }
-
- body.flip();
-
- getMetaData().setBody(body.duplicate());
- }
- return body;
- }
-
- public Session getSession()
- {
- return _sessionRef == null ? null : _sessionRef.get();
- }
-
- public SessionConfig getSessionConfig()
- {
- return _sessionRef == null ? null : (ServerSession) _sessionRef.get();
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/message/ServerMessage.java b/java/broker/src/main/java/org/apache/qpid/server/message/ServerMessage.java
deleted file mode 100644
index 2f2d39115f..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/message/ServerMessage.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.message;
-
-import java.nio.ByteBuffer;
-
-import org.apache.qpid.server.configuration.SessionConfig;
-
-public interface ServerMessage extends EnqueableMessage, MessageContentSource
-{
- String getRoutingKey();
-
- AMQMessageHeader getMessageHeader();
-
- boolean isPersistent();
-
- long getSize();
-
- boolean isImmediate();
-
- long getExpiration();
-
- MessageReference newReference();
-
- Long getMessageNumber();
-
- long getArrivalTime();
-
- public int getContent(ByteBuffer buf, int offset);
-
- SessionConfig getSessionConfig();
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/message/TransferMessageReference.java b/java/broker/src/main/java/org/apache/qpid/server/message/TransferMessageReference.java
deleted file mode 100644
index ed189c49c4..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/message/TransferMessageReference.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.message;
-
-public class TransferMessageReference extends MessageReference<MessageTransferMessage>
-{
- public TransferMessageReference(MessageTransferMessage message)
- {
- super(message);
- }
-
- protected void onReference(MessageTransferMessage message)
- {
-
- }
-
- protected void onRelease(MessageTransferMessage message)
- {
-
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/output/HeaderPropertiesConverter.java b/java/broker/src/main/java/org/apache/qpid/server/output/HeaderPropertiesConverter.java
deleted file mode 100755
index aded3f3d2a..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/output/HeaderPropertiesConverter.java
+++ /dev/null
@@ -1,124 +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.output;
-
-import org.apache.qpid.server.message.MessageTransferMessage;
-import org.apache.qpid.framing.BasicContentHeaderProperties;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.FieldTable;
-import org.apache.qpid.transport.Header;
-import org.apache.qpid.transport.DeliveryProperties;
-import org.apache.qpid.transport.MessageProperties;
-import org.apache.qpid.transport.MessageDeliveryMode;
-import org.apache.qpid.AMQPInvalidClassException;
-
-import java.util.Map;
-
-public class HeaderPropertiesConverter
-{
-
- public static BasicContentHeaderProperties convert(MessageTransferMessage messageTransferMessage)
- {
- BasicContentHeaderProperties props = new BasicContentHeaderProperties();
-
- Header header = messageTransferMessage.getHeader();
- DeliveryProperties deliveryProps = header.get(DeliveryProperties.class);
- MessageProperties messageProps = header.get(MessageProperties.class);
-
- if(deliveryProps != null)
- {
- if(deliveryProps.hasDeliveryMode())
- {
- props.setDeliveryMode((byte)(deliveryProps.getDeliveryMode() == MessageDeliveryMode.PERSISTENT ? BasicContentHeaderProperties.PERSISTENT : BasicContentHeaderProperties.NON_PERSISTENT));
- }
- if(deliveryProps.hasExpiration())
- {
- props.setExpiration(deliveryProps.getExpiration());
- }
- if(deliveryProps.hasPriority())
- {
- props.setPriority((byte)deliveryProps.getPriority().getValue());
- }
- if(deliveryProps.hasTimestamp())
- {
- props.setTimestamp(deliveryProps.getTimestamp());
- }
- }
- if(messageProps != null)
- {
- if(messageProps.hasAppId())
- {
- props.setAppId(new AMQShortString(messageProps.getAppId()));
- }
- if(messageProps.hasContentType())
- {
- props.setContentType(messageProps.getContentType());
- }
- if(messageProps.hasCorrelationId())
- {
- props.setCorrelationId(new AMQShortString(messageProps.getCorrelationId()));
- }
- if(messageProps.hasContentEncoding())
- {
- props.setEncoding(messageProps.getContentEncoding());
- }
- if(messageProps.hasMessageId())
- {
- props.setMessageId(messageProps.getMessageId().toString());
- }
-
- // TODO Reply-to
-
- if(messageProps.hasUserId())
- {
- props.setUserId(new AMQShortString(messageProps.getUserId()));
- }
-
- if(messageProps.hasApplicationHeaders())
- {
- Map<String, Object> appHeaders = messageProps.getApplicationHeaders();
- FieldTable ft = new FieldTable();
- for(Map.Entry<String, Object> entry : appHeaders.entrySet())
- {
- try
- {
- ft.put(new AMQShortString(entry.getKey()), entry.getValue());
- }
- catch(AMQPInvalidClassException e)
- {
- // TODO
- // log here, but ignore - just can;t convert
- }
- }
- props.setHeaders(ft);
-
- }
- }
-
-
-
-
-
-
-
- return props;
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/output/ProtocolOutputConverter.java b/java/broker/src/main/java/org/apache/qpid/server/output/ProtocolOutputConverter.java
deleted file mode 100644
index 5300bad613..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/output/ProtocolOutputConverter.java
+++ /dev/null
@@ -1,60 +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;
-
-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.framing.AMQDataBlock;
-import org.apache.qpid.framing.ContentHeaderBody;
-import org.apache.qpid.framing.abstraction.MessagePublishInfo;
-import org.apache.qpid.AMQException;
-
-public interface ProtocolOutputConverter
-{
- void confirmConsumerAutoClose(int channelId, AMQShortString consumerTag);
-
- interface Factory
- {
- ProtocolOutputConverter newInstance(AMQProtocolSession session);
- }
-
- void writeDeliver(QueueEntry entry, int channelId, long deliveryTag, AMQShortString consumerTag)
- throws AMQException;
-
- void writeGetOk(QueueEntry message, int channelId, long deliveryTag, int queueSize) throws AMQException;
-
- byte getProtocolMinorVersion();
-
- byte getProtocolMajorVersion();
-
- void writeReturn(MessagePublishInfo messagePublishInfo, ContentHeaderBody header, MessageContentSource msgContent, int channelId, int replyCode, AMQShortString replyText)
- throws AMQException;
-
- void writeFrame(AMQDataBlock block);
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/output/ProtocolOutputConverterRegistry.java b/java/broker/src/main/java/org/apache/qpid/server/output/ProtocolOutputConverterRegistry.java
deleted file mode 100644
index dbefeb61f2..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/output/ProtocolOutputConverterRegistry.java
+++ /dev/null
@@ -1,61 +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;
-
-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;
-
-public class ProtocolOutputConverterRegistry
-{
-
- private static final Map<ProtocolVersion, Factory> _registry =
- new HashMap<ProtocolVersion, Factory>();
-
-
- 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());
- }
-
- private static void register(ProtocolVersion version, Factory converter)
- {
-
- _registry.put(version,converter);
- }
-
-
- public static ProtocolOutputConverter getConverter(AMQProtocolSession session)
- {
- return _registry.get(session.getProtocolVersion()).newInstance(session);
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/output/amqp0_8/ProtocolOutputConverterImpl.java b/java/broker/src/main/java/org/apache/qpid/server/output/amqp0_8/ProtocolOutputConverterImpl.java
deleted file mode 100644
index 2cebec373e..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/output/amqp0_8/ProtocolOutputConverterImpl.java
+++ /dev/null
@@ -1,273 +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.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.amqp_8_0.BasicGetBodyImpl;
-import org.apache.qpid.framing.abstraction.MessagePublishInfo;
-import org.apache.qpid.framing.abstraction.ProtocolVersionMethodConverter;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.transport.DeliveryProperties;
-
-import java.nio.ByteBuffer;
-
-public class ProtocolOutputConverterImpl implements ProtocolOutputConverter
-{
-
- private static final MethodRegistry METHOD_REGISTRY = MethodRegistry.getMethodRegistry(ProtocolVersion.v8_0);
-
- private static final ProtocolVersionMethodConverter PROTOCOL_CONVERTER =
- METHOD_REGISTRY.getProtocolVersionMethodConverter();
-
- 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
- {
- AMQDataBlock deliver = createEncodedDeliverFrame(entry, channelId, deliveryTag, consumerTag);
- writeMessageDelivery(entry.getMessage(), getContentHeaderBody(entry), channelId, deliver);
- }
-
- 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);
- ContentHeaderBody chb = new ContentHeaderBody(props, BasicGetBodyImpl.CLASS_ID);
- chb.bodySize = message.getSize();
- return chb;
- }
- }
-
-
- public void writeGetOk(QueueEntry entry, int channelId, long deliveryTag, int queueSize) throws AMQException
- {
- AMQDataBlock deliver = createEncodedGetOkFrame(entry, channelId, deliveryTag, queueSize);
- writeMessageDelivery(entry.getMessage(), getContentHeaderBody(entry), channelId, deliver);
- }
-
- private void writeMessageDelivery(MessageContentSource message, ContentHeaderBody chb, int channelId, AMQDataBlock deliver)
- throws AMQException
- {
-
-
- AMQDataBlock contentHeader = ContentHeaderBody.createAMQFrame(channelId, chb);
-
-
- final int bodySize = (int) message.getSize();
- if(bodySize == 0)
- {
- SmallCompositeAMQDataBlock compositeBlock = new SmallCompositeAMQDataBlock(deliver,
- contentHeader);
- writeFrame(compositeBlock);
- }
- else
- {
- int maxBodySize = (int) getProtocolSession().getMaxFrameSize() - AMQFrame.getFrameOverhead();
-
- final int capacity = bodySize > maxBodySize ? maxBodySize : bodySize;
- ByteBuffer buf = ByteBuffer.allocate(capacity);
-
- int writtenSize = 0;
-
- writtenSize += message.getContent(buf, writtenSize);
- buf.flip();
- AMQDataBlock firstContentBody = new AMQFrame(channelId, PROTOCOL_CONVERTER.convertToBody(buf));
- AMQDataBlock[] blocks = new AMQDataBlock[]{deliver, contentHeader, firstContentBody};
- CompositeAMQDataBlock compositeBlock = new CompositeAMQDataBlock(blocks);
- writeFrame(compositeBlock);
-
- while(writtenSize < bodySize)
- {
- buf = java.nio.ByteBuffer.allocate(capacity);
- writtenSize += message.getContent(buf, writtenSize);
- buf.flip();
- writeFrame(new AMQFrame(channelId, PROTOCOL_CONVERTER.convertToBody(buf)));
- }
-
- }
- }
-
-
- private AMQDataBlock createEncodedDeliverFrame(QueueEntry entry, int channelId, long deliveryTag, 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().get(DeliveryProperties.class);
- 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();
-
-
- BasicDeliverBody deliverBody =
- METHOD_REGISTRY.createBasicDeliverBody(consumerTag,
- deliveryTag,
- isRedelivered,
- exchangeName,
- routingKey);
-
- AMQFrame deliverFrame = deliverBody.generateFrame(channelId);
-
-
- return deliverFrame;
- }
-
- private AMQDataBlock createEncodedGetOkFrame(QueueEntry entry, int channelId, 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().get(DeliveryProperties.class);
- 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);
- AMQFrame getOkFrame = getOkBody.generateFrame(channelId);
-
- return getOkFrame;
- }
-
- public byte getProtocolMinorVersion()
- {
- return getProtocolSession().getProtocolMinorVersion();
- }
-
- public byte getProtocolMajorVersion()
- {
- return getProtocolSession().getProtocolMajorVersion();
- }
-
- private AMQDataBlock createEncodedReturnFrame(MessagePublishInfo messagePublishInfo, int channelId, int replyCode, AMQShortString replyText) throws AMQException
- {
- BasicReturnBody basicReturnBody =
- METHOD_REGISTRY.createBasicReturnBody(replyCode,
- replyText,
- messagePublishInfo.getExchange(),
- messagePublishInfo.getRoutingKey());
- AMQFrame returnFrame = basicReturnBody.generateFrame(channelId);
-
- return returnFrame;
- }
-
- public void writeReturn(MessagePublishInfo messagePublishInfo,
- ContentHeaderBody header,
- MessageContentSource content,
- int channelId,
- int replyCode,
- AMQShortString replyText)
- throws AMQException
- {
-
- AMQDataBlock returnFrame = createEncodedReturnFrame(messagePublishInfo, channelId, replyCode, replyText);
-
- writeMessageDelivery(content, 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));
-
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/output/amqp0_9/ProtocolOutputConverterImpl.java b/java/broker/src/main/java/org/apache/qpid/server/output/amqp0_9/ProtocolOutputConverterImpl.java
deleted file mode 100644
index 319b5cc7bd..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/output/amqp0_9/ProtocolOutputConverterImpl.java
+++ /dev/null
@@ -1,383 +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.mina.common.ByteBuffer;
-
-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.framing.abstraction.ProtocolVersionMethodConverter;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.transport.DeliveryProperties;
-import org.apache.qpid.protocol.AMQVersionAwareProtocolSession;
-
-public class ProtocolOutputConverterImpl implements ProtocolOutputConverter
-{
- private static final MethodRegistry METHOD_REGISTRY = MethodRegistry.getMethodRegistry(ProtocolVersion.v0_9);
- private static final ProtocolVersionMethodConverter
- PROTOCOL_CONVERTER = METHOD_REGISTRY.getProtocolVersionMethodConverter();
-
-
- 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);
- 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();
-
-
- final int capacity = bodySize > maxBodySize ? maxBodySize : bodySize;
- java.nio.ByteBuffer buf = java.nio.ByteBuffer.allocate(capacity);
-
- int writtenSize = 0;
-
-
- writtenSize += message.getContent(buf, writtenSize);
- buf.flip();
- AMQBody firstContentBody = PROTOCOL_CONVERTER.convertToBody(buf);
-
- CompositeAMQBodyBlock
- compositeBlock = new CompositeAMQBodyBlock(channelId, deliverBody, contentHeaderBody, firstContentBody);
- writeFrame(compositeBlock);
-
- while(writtenSize < bodySize)
- {
- buf = java.nio.ByteBuffer.allocate(capacity);
-
- writtenSize += message.getContent(buf, writtenSize);
- buf.flip();
- writeFrame(new AMQFrame(channelId, PROTOCOL_CONVERTER.convertToBody(buf)));
- }
- }
- }
-
- 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().get(DeliveryProperties.class);
- 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(ByteBuffer buffer)
- {
- 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().get(DeliveryProperties.class);
- 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(ByteBuffer buffer)
- {
- 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(ByteBuffer buffer)
- {
- AMQFrame.writeFrames(buffer, _channel, _methodBody, _headerBody);
- }
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/output/amqp0_9_1/ProtocolOutputConverterImpl.java b/java/broker/src/main/java/org/apache/qpid/server/output/amqp0_9_1/ProtocolOutputConverterImpl.java
deleted file mode 100644
index cffbe445ee..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/output/amqp0_9_1/ProtocolOutputConverterImpl.java
+++ /dev/null
@@ -1,383 +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.mina.common.ByteBuffer;
-
-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.framing.abstraction.ProtocolVersionMethodConverter;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.transport.DeliveryProperties;
-import org.apache.qpid.protocol.AMQVersionAwareProtocolSession;
-
-public class ProtocolOutputConverterImpl implements ProtocolOutputConverter
-{
- private static final MethodRegistry METHOD_REGISTRY = MethodRegistry.getMethodRegistry(ProtocolVersion.v0_91);
- private static final ProtocolVersionMethodConverter
- PROTOCOL_CONVERTER = METHOD_REGISTRY.getProtocolVersionMethodConverter();
-
-
- 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);
- 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();
-
-
- final int capacity = bodySize > maxBodySize ? maxBodySize : bodySize;
- java.nio.ByteBuffer buf = java.nio.ByteBuffer.allocate(capacity);
-
- int writtenSize = 0;
-
-
- writtenSize += message.getContent(buf, writtenSize);
- buf.flip();
- AMQBody firstContentBody = PROTOCOL_CONVERTER.convertToBody(buf);
-
- CompositeAMQBodyBlock
- compositeBlock = new CompositeAMQBodyBlock(channelId, deliverBody, contentHeaderBody, firstContentBody);
- writeFrame(compositeBlock);
-
- while(writtenSize < bodySize)
- {
- buf = java.nio.ByteBuffer.allocate(capacity);
-
- writtenSize += message.getContent(buf, writtenSize);
- buf.flip();
- writeFrame(new AMQFrame(channelId, PROTOCOL_CONVERTER.convertToBody(buf)));
- }
- }
- }
-
- 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().get(DeliveryProperties.class);
- 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(ByteBuffer buffer)
- {
- 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().get(DeliveryProperties.class);
- 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(ByteBuffer buffer)
- {
- 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(ByteBuffer buffer)
- {
- AMQFrame.writeFrames(buffer, _channel, _methodBody, _headerBody);
- }
- }
-
-} \ No newline at end of file
diff --git a/java/broker/src/main/java/org/apache/qpid/server/plugins/Activator.java b/java/broker/src/main/java/org/apache/qpid/server/plugins/Activator.java
deleted file mode 100644
index df72e87fd8..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/plugins/Activator.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.qpid.server.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;
-
-public class Activator implements BundleActivator
-{
- private static final Logger _logger = Logger.getLogger(Activator.class);
-
- private BundleContext _context = null;
-
- public void start(BundleContext ctx) throws Exception
- {
- _context = ctx;
- _logger.info("Registering bundle: " + _context.getBundle().getSymbolicName());
- ctx.registerService(ServerConfiguration.class.getName(), ApplicationRegistry.getInstance().getConfiguration(), null);
- }
-
- public void stop(BundleContext ctx) throws Exception
- {
- _logger.info("Stopping bundle: " + _context.getBundle().getSymbolicName());
- _context = null;
- }
-
- public BundleContext getContext()
- {
- return _context;
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/plugins/Plugin.java b/java/broker/src/main/java/org/apache/qpid/server/plugins/Plugin.java
deleted file mode 100644
index e7f9983fff..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/plugins/Plugin.java
+++ /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.
- */
-package org.apache.qpid.server.plugins;
-
-import org.apache.commons.configuration.ConfigurationException;
-import org.apache.qpid.server.configuration.plugins.ConfigurationPlugin;
-
-public interface Plugin
-{
-
- /**
- * Provide Configuration to this plugin
- */
- public void configure(ConfigurationPlugin config);
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/plugins/PluginFactory.java b/java/broker/src/main/java/org/apache/qpid/server/plugins/PluginFactory.java
deleted file mode 100644
index bbf3e74a30..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/plugins/PluginFactory.java
+++ /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.
- */
-package org.apache.qpid.server.plugins;
-
-import org.apache.commons.configuration.ConfigurationException;
-import org.apache.qpid.server.configuration.plugins.ConfigurationPlugin;
-
-public interface PluginFactory<P extends Plugin>
-{
- public Class<P> getPluginClass();
-
- public String getPluginName();
-
- public P newInstance(ConfigurationPlugin config) throws ConfigurationException;
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/plugins/PluginManager.java b/java/broker/src/main/java/org/apache/qpid/server/plugins/PluginManager.java
deleted file mode 100644
index 4e8d64a136..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/plugins/PluginManager.java
+++ /dev/null
@@ -1,342 +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.plugins;
-
-import static org.apache.felix.framework.util.FelixConstants.*;
-import static org.apache.felix.main.AutoProcessor.*;
-
-import java.io.File;
-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 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.apache.qpid.common.Closeable;
-import org.apache.qpid.server.configuration.TopicConfiguration;
-import org.apache.qpid.server.configuration.plugins.SlowConsumerDetectionConfiguration.SlowConsumerDetectionConfigurationFactory;
-import org.apache.qpid.server.configuration.plugins.SlowConsumerDetectionPolicyConfiguration.SlowConsumerDetectionPolicyConfigurationFactory;
-import org.apache.qpid.server.configuration.plugins.SlowConsumerDetectionQueueConfiguration.SlowConsumerDetectionQueueConfigurationFactory;
-import org.apache.qpid.server.configuration.plugins.ConfigurationPluginFactory;
-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.virtualhost.plugins.VirtualHostPluginFactory;
-import org.apache.qpid.server.virtualhost.plugins.SlowConsumerDetection;
-import org.apache.qpid.server.virtualhost.plugins.policies.TopicDeletePolicy;
-import org.apache.qpid.slowconsumerdetection.policies.SlowConsumerPolicyPluginFactory;
-import org.osgi.framework.BundleActivator;
-import org.osgi.framework.BundleException;
-import org.osgi.framework.launch.Framework;
-import org.osgi.util.tracker.ServiceTracker;
-
-/**
- * Provides access to pluggable elements, such as exchanges
- */
-@SuppressWarnings("unchecked")
-public class PluginManager implements Closeable
-{
- private static final Logger _logger = Logger.getLogger(PluginManager.class);
-
- private static final int FELIX_STOP_TIMEOUT = 30000;
- private static final String QPID_VER_SUFFIX = "version=0.11,";
-
- private Framework _felix;
-
- private ServiceTracker _exchangeTracker = null;
- private ServiceTracker _securityTracker = null;
- private ServiceTracker _configTracker = null;
- private ServiceTracker _virtualHostTracker = null;
- private ServiceTracker _policyTracker = null;
-
- private Activator _activator;
-
- private Map<String, SecurityPluginFactory> _securityPlugins = new HashMap<String, SecurityPluginFactory>();
- private Map<List<String>, ConfigurationPluginFactory> _configPlugins = new IdentityHashMap<List<String>, ConfigurationPluginFactory>();
- private Map<String, VirtualHostPluginFactory> _vhostPlugins = new HashMap<String, VirtualHostPluginFactory>();
- private Map<String, SlowConsumerPolicyPluginFactory> _policyPlugins = new HashMap<String, SlowConsumerPolicyPluginFactory>();
-
- public PluginManager(String pluginPath, String cachePath) throws Exception
- {
- // 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))
- {
- _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(),
- new SlowConsumerDetectionQueueConfigurationFactory()))
- {
- _configPlugins.put(configFactory.getParentPaths(), configFactory);
- }
- for (SlowConsumerPolicyPluginFactory pluginFactory : Arrays.asList(
- new TopicDeletePolicy.TopicDeletePolicyFactory()))
- {
- _policyPlugins.put(pluginFactory.getPluginName(), pluginFactory);
- }
- for (VirtualHostPluginFactory pluginFactory : Arrays.asList(
- new SlowConsumerDetection.SlowConsumerFactory()))
- {
- _vhostPlugins.put(pluginFactory.getClass().getName(), pluginFactory);
- }
-
- // Check the plugin directory path is set and exist
- if (pluginPath == null)
- {
- return;
- }
- File pluginDir = new File(pluginPath);
- if (!pluginDir.exists())
- {
- return;
- }
-
- // Setup OSGi configuration propery map
- StringMap configMap = new StringMap(false);
-
- // Add the bundle provided service interface package and the core OSGi
- // packages to be exported from the class path via the system bundle.
- configMap.put(FRAMEWORK_SYSTEMPACKAGES,
- "org.osgi.framework; version=1.3.0," +
- "org.osgi.service.packageadmin; version=1.2.0," +
- "org.osgi.service.startlevel; version=1.0.0," +
- "org.osgi.service.url; version=1.0.0," +
- "org.osgi.util.tracker; version=1.0.0," +
- "org.apache.qpid.junit.extensions.util; " + QPID_VER_SUFFIX +
- "org.apache.qpid; " + QPID_VER_SUFFIX +
- "org.apache.qpid.common; " + QPID_VER_SUFFIX +
- "org.apache.qpid.exchange; " + QPID_VER_SUFFIX +
- "org.apache.qpid.framing; " + QPID_VER_SUFFIX +
- "org.apache.qpid.management.common.mbeans.annotations; " + QPID_VER_SUFFIX +
- "org.apache.qpid.protocol; " + QPID_VER_SUFFIX +
- "org.apache.qpid.server.binding; " + QPID_VER_SUFFIX +
- "org.apache.qpid.server.configuration; " + QPID_VER_SUFFIX +
- "org.apache.qpid.server.configuration.plugins; " + QPID_VER_SUFFIX +
- "org.apache.qpid.server.configuration.management; " + QPID_VER_SUFFIX +
- "org.apache.qpid.server.exchange; " + QPID_VER_SUFFIX +
- "org.apache.qpid.server.logging; " + QPID_VER_SUFFIX +
- "org.apache.qpid.server.logging.actors; " + QPID_VER_SUFFIX +
- "org.apache.qpid.server.logging.subjects; " + QPID_VER_SUFFIX +
- "org.apache.qpid.server.management; " + QPID_VER_SUFFIX +
- "org.apache.qpid.server.persistent; " + QPID_VER_SUFFIX +
- "org.apache.qpid.server.plugins; " + QPID_VER_SUFFIX +
- "org.apache.qpid.server.protocol; " + QPID_VER_SUFFIX +
- "org.apache.qpid.server.queue; " + QPID_VER_SUFFIX +
- "org.apache.qpid.server.registry; " + QPID_VER_SUFFIX +
- "org.apache.qpid.server.security; " + QPID_VER_SUFFIX +
- "org.apache.qpid.server.security.access; " + QPID_VER_SUFFIX +
- "org.apache.qpid.server.security.access.plugins; " + QPID_VER_SUFFIX +
- "org.apache.qpid.server.virtualhost; " + QPID_VER_SUFFIX +
- "org.apache.qpid.server.virtualhost.plugins; " + QPID_VER_SUFFIX +
- "org.apache.qpid.util; " + QPID_VER_SUFFIX +
- "org.apache.commons.configuration; version=1.0.0," +
- "org.apache.commons.lang; version=1.0.0," +
- "org.apache.commons.lang.builder; version=1.0.0," +
- "org.apache.commons.logging; version=1.0.0," +
- "org.apache.log4j; version=1.2.12," +
- "javax.management.openmbean; version=1.0.0," +
- "javax.management; version=1.0.0"
- );
-
- // No automatic shutdown hook
- configMap.put("felix.shutdown.hook", "false");
-
- // Add system activator
- List<BundleActivator> activators = new ArrayList<BundleActivator>();
- _activator = new Activator();
- activators.add(_activator);
- configMap.put(SYSTEMBUNDLE_ACTIVATORS_PROP, activators);
-
- if (cachePath != null)
- {
- File cacheDir = new File(cachePath);
- if (!cacheDir.exists() && cacheDir.canWrite())
- {
- _logger.info("Creating plugin cache directory: " + cachePath);
- cacheDir.mkdir();
- }
-
- // Set plugin cache directory and empty it
- _logger.info("Cache bundles in directory " + cachePath);
- configMap.put(FRAMEWORK_STORAGE, cachePath);
- }
- configMap.put(FRAMEWORK_STORAGE_CLEAN, FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT);
-
- // Set directory with plugins to auto-deploy
- _logger.info("Auto deploying bundles from directory " + pluginPath);
- configMap.put(AUTO_DEPLOY_DIR_PROPERY, pluginPath);
- configMap.put(AUTO_DEPLOY_ACTION_PROPERY, AUTO_DEPLOY_INSTALL_VALUE + "," + AUTO_DEPLOY_START_VALUE);
-
- // Start plugin manager and trackers
- _felix = new Felix(configMap);
- try
- {
- _logger.info("Starting plugin manager...");
- _felix.init();
- process(configMap, _felix.getBundleContext());
- _felix.start();
- _logger.info("Started plugin manager");
- }
- catch (BundleException e)
- {
- throw new ConfigurationException("Could not start plugin manager: " + e.getMessage(), e);
- }
-
- // TODO save trackers in a map, keyed by class name
-
- _exchangeTracker = new ServiceTracker(_activator.getContext(), ExchangeType.class.getName(), null);
- _exchangeTracker.open();
-
- _securityTracker = new ServiceTracker(_activator.getContext(), SecurityPluginFactory.class.getName(), null);
- _securityTracker.open();
-
- _configTracker = new ServiceTracker(_activator.getContext(), ConfigurationPluginFactory.class.getName(), null);
- _configTracker.open();
-
- _virtualHostTracker = new ServiceTracker(_activator.getContext(), VirtualHostPluginFactory.class.getName(), null);
- _virtualHostTracker.open();
-
- _policyTracker = new ServiceTracker(_activator.getContext(), SlowConsumerPolicyPluginFactory.class.getName(), null);
- _policyTracker.open();
-
- _logger.info("Opened service trackers");
- }
-
- private static <T> Map<String, T> getServices(ServiceTracker tracker)
- {
- Map<String, T> services = new HashMap<String, T>();
-
- if ((tracker != null) && (tracker.getServices() != null))
- {
- for (Object service : tracker.getServices())
- {
- if (service instanceof PluginFactory<?>)
- {
- services.put(((PluginFactory<?>) service).getPluginName(), (T) service);
- }
- else
- {
- services.put(service.getClass().getName(), (T) service);
- }
- }
- }
-
- return services;
- }
-
- public static <T> Map<String, T> getServices(ServiceTracker tracker, Map<String, T> plugins)
- {
- Map<String, T> services = getServices(tracker);
- services.putAll(plugins);
- return services;
- }
-
- public Map<List<String>, ConfigurationPluginFactory> getConfigurationPlugins()
- {
- Map<List<String>, ConfigurationPluginFactory> services = new IdentityHashMap<List<String>, ConfigurationPluginFactory>();
-
- if (_configTracker != null && _configTracker.getServices() != null)
- {
- for (Object service : _configTracker.getServices())
- {
- ConfigurationPluginFactory factory = (ConfigurationPluginFactory) service;
- services.put(factory.getParentPaths(), factory);
- }
- }
-
- services.putAll(_configPlugins);
-
- return services;
- }
-
- public Map<String, VirtualHostPluginFactory> getVirtualHostPlugins()
- {
- return getServices(_virtualHostTracker, _vhostPlugins);
- }
-
- public Map<String, SlowConsumerPolicyPluginFactory> getSlowConsumerPlugins()
- {
- return getServices(_policyTracker, _policyPlugins);
- }
-
- public Map<String, ExchangeType<?>> getExchanges()
- {
- return getServices(_exchangeTracker);
- }
-
- public Map<String, SecurityPluginFactory> getSecurityPlugins()
- {
- return getServices(_securityTracker, _securityPlugins);
- }
-
- public void close()
- {
- if (_felix != null)
- {
- try
- {
- // Close all bundle trackers
- _exchangeTracker.close();
- _securityTracker.close();
- _configTracker.close();
- _virtualHostTracker.close();
- _policyTracker.close();
- }
- finally
- {
- _logger.info("Stopping plugin manager");
- try
- {
- // FIXME should be stopAndWait() but hangs VM, need upgrade in felix
- _felix.stop();
- }
- catch (BundleException e)
- {
- // Ignore
- }
-
- try
- {
- _felix.waitForStop(FELIX_STOP_TIMEOUT);
- }
- catch (InterruptedException e)
- {
- // Ignore
- }
- _logger.info("Stopped plugin manager");
- }
- }
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQConnectionModel.java b/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQConnectionModel.java
deleted file mode 100644
index 061ebf50cd..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQConnectionModel.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.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;
-
-public interface AMQConnectionModel extends StatisticsGatherer
-{
- /**
- * get a unique id for this connection.
- *
- * @return a {@link UUID} representing the connection
- */
- public UUID getId();
-
- /**
- * Close the underlying Connection
- *
- * @param cause
- * @param message
- * @throws org.apache.qpid.AMQException
- */
- public void close(AMQConstant cause, String message) throws AMQException;
-
- /**
- * Close the given requested Session
- *
- * @param session
- * @param cause
- * @param message
- * @throws org.apache.qpid.AMQException
- */
- public void closeSession(AMQSessionModel session, AMQConstant cause, String message) throws AMQException;
-
- public long getConnectionId();
-
- /**
- * Get a list of all sessions using this connection.
- *
- * @return a list of {@link AMQSessionModel}s
- */
- public List<AMQSessionModel> getSessionModels();
-
- /**
- * Return a {@link LogSubject} for the connection.
- */
- public LogSubject getLogSubject();
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQNoMethodHandlerException.java b/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQNoMethodHandlerException.java
deleted file mode 100644
index a7599a3e0d..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQNoMethodHandlerException.java
+++ /dev/null
@@ -1,46 +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.protocol;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.AMQMethodBody;
-import org.apache.qpid.protocol.AMQMethodEvent;
-
-/**
- * AMQNoMethodHandlerException represents the case where no method handler exists to handle an AQMP method.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Represents failure to handle an AMQP method.
- * </table>
- *
- * @todo Not an AMQP exception as no status code.
- *
- * @todo Missing method handler. Unlikely to ever happen, and if it does its a coding error. Consider replacing with a
- * Runtime.
- */
-public class AMQNoMethodHandlerException extends AMQException
-{
- public AMQNoMethodHandlerException(AMQMethodEvent<AMQMethodBody> evt)
- {
- super("AMQMethodEvent " + evt + " was not processed by any listener on Broker.");
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolEngine.java b/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolEngine.java
deleted file mode 100644
index 449f698c48..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolEngine.java
+++ /dev/null
@@ -1,1361 +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.protocol;
-
-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;
-import java.util.concurrent.atomic.AtomicLong;
-
-import javax.management.JMException;
-import javax.security.sasl.SaslServer;
-
-import org.apache.log4j.Logger;
-import org.apache.mina.transport.vmpipe.VmPipeAddress;
-import org.apache.qpid.AMQChannelException;
-import org.apache.qpid.AMQConnectionException;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.AMQSecurityException;
-import org.apache.qpid.codec.AMQCodecFactory;
-import org.apache.qpid.codec.AMQDecoder;
-import org.apache.qpid.common.ClientProperties;
-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.AMQProtocolHeaderException;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.ChannelCloseBody;
-import org.apache.qpid.framing.ChannelCloseOkBody;
-import org.apache.qpid.framing.ConnectionCloseBody;
-import org.apache.qpid.framing.ContentBody;
-import org.apache.qpid.framing.ContentHeaderBody;
-import org.apache.qpid.framing.FieldTable;
-import org.apache.qpid.framing.HeartbeatBody;
-import org.apache.qpid.framing.MethodDispatcher;
-import org.apache.qpid.framing.MethodRegistry;
-import org.apache.qpid.framing.ProtocolInitiation;
-import org.apache.qpid.framing.ProtocolVersion;
-import org.apache.qpid.pool.Job;
-import org.apache.qpid.pool.ReferenceCountingExecutorService;
-import org.apache.qpid.protocol.AMQConstant;
-import org.apache.qpid.protocol.AMQMethodEvent;
-import org.apache.qpid.protocol.AMQMethodListener;
-import org.apache.qpid.protocol.ProtocolEngine;
-import org.apache.qpid.server.AMQChannel;
-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.handler.ServerMethodDispatcherImpl;
-import org.apache.qpid.server.logging.LogActor;
-import org.apache.qpid.server.logging.LogSubject;
-import org.apache.qpid.server.logging.actors.AMQPConnectionActor;
-import org.apache.qpid.server.logging.actors.CurrentActor;
-import org.apache.qpid.server.logging.actors.ManagementActor;
-import org.apache.qpid.server.logging.messages.ConnectionMessages;
-import org.apache.qpid.server.logging.subjects.ConnectionLogSubject;
-import org.apache.qpid.server.management.Managable;
-import org.apache.qpid.server.management.ManagedObject;
-import org.apache.qpid.server.output.ProtocolOutputConverter;
-import org.apache.qpid.server.output.ProtocolOutputConverterRegistry;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-import org.apache.qpid.server.state.AMQState;
-import org.apache.qpid.server.state.AMQStateManager;
-import org.apache.qpid.server.stats.StatisticsCounter;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-import org.apache.qpid.server.virtualhost.VirtualHostRegistry;
-import org.apache.qpid.transport.NetworkDriver;
-import org.apache.qpid.transport.Sender;
-
-public class AMQProtocolEngine implements ProtocolEngine, Managable, AMQProtocolSession, ConnectionConfig
-{
- private static final Logger _logger = Logger.getLogger(AMQProtocolEngine.class);
-
- private static final String CLIENT_PROPERTIES_INSTANCE = ClientProperties.instance.toString();
-
- private static final AtomicLong idGenerator = new AtomicLong(0);
-
- // to save boxing the channelId and looking up in a map... cache in an array the low numbered
- // channels. This value must be of the form 2^x - 1.
- private static final int CHANNEL_CACHE_SIZE = 0xff;
-
- private AMQShortString _contextKey;
-
- private AMQShortString _clientVersion = null;
-
- private VirtualHost _virtualHost;
-
- private final Map<Integer, AMQChannel> _channelMap = new HashMap<Integer, AMQChannel>();
-
- private final AMQChannel[] _cachedChannels = new AMQChannel[CHANNEL_CACHE_SIZE + 1];
-
- private final CopyOnWriteArraySet<AMQMethodListener> _frameListeners = new CopyOnWriteArraySet<AMQMethodListener>();
-
- private final AMQStateManager _stateManager;
-
- private AMQCodecFactory _codecFactory;
-
- private AMQProtocolSessionMBean _managedObject;
-
- private SaslServer _saslServer;
-
- private Object _lastReceived;
-
- private Object _lastSent;
-
- protected volatile boolean _closed;
-
- // maximum number of channels this session should have
- private long _maxNoOfChannels = ApplicationRegistry.getInstance().getConfiguration().getMaxChannelCount();
-
- /* AMQP Version for this session */
- private ProtocolVersion _protocolVersion = ProtocolVersion.getLatestSupportedVersion();
-
- private FieldTable _clientProperties;
- private final List<Task> _taskList = new CopyOnWriteArrayList<Task>();
-
- private Map<Integer, Long> _closingChannelsList = new ConcurrentHashMap<Integer, Long>();
- private ProtocolOutputConverter _protocolOutputConverter;
- private Principal _authorizedID;
- private MethodDispatcher _dispatcher;
- private ProtocolSessionIdentifier _sessionIdentifier;
-
- // Create a simple ID that increments for ever new Session
- private final long _sessionID = idGenerator.getAndIncrement();
-
- private AMQPConnectionActor _actor;
- private LogSubject _logSubject;
-
- private NetworkDriver _networkDriver;
-
- private long _lastIoTime;
-
- private long _writtenBytes;
- private long _readBytes;
-
- private Job _readJob;
- private Job _writeJob;
-
- private ReferenceCountingExecutorService _poolReference = ReferenceCountingExecutorService.getInstance();
- private long _maxFrameSize;
- private final AtomicBoolean _closing = new AtomicBoolean(false);
- private final UUID _id;
- private final ConfigStore _configStore;
- private long _createTime = System.currentTimeMillis();
-
- private ApplicationRegistry _registry;
- private boolean _statisticsEnabled = false;
- private StatisticsCounter _messagesDelivered, _dataDelivered, _messagesReceived, _dataReceived;
-
- public ManagedObject getManagedObject()
- {
- return _managedObject;
- }
-
- public AMQProtocolEngine(VirtualHostRegistry virtualHostRegistry, NetworkDriver driver)
- {
- _stateManager = new AMQStateManager(virtualHostRegistry, this);
- _networkDriver = driver;
-
- _codecFactory = new AMQCodecFactory(true, this);
- _poolReference.acquireExecutorService();
- _readJob = new Job(_poolReference, Job.MAX_JOB_EVENTS, true);
- _writeJob = new Job(_poolReference, Job.MAX_JOB_EVENTS, false);
-
- _actor = new AMQPConnectionActor(this, virtualHostRegistry.getApplicationRegistry().getRootMessageLogger());
-
- _logSubject = new ConnectionLogSubject(this);
-
- _configStore = virtualHostRegistry.getConfigStore();
- _id = _configStore.createId();
-
- _actor.message(ConnectionMessages.OPEN(null, null, false, false));
-
- _registry = virtualHostRegistry.getApplicationRegistry();
- initialiseStatistics();
- }
-
- private AMQProtocolSessionMBean createMBean() throws JMException
- {
- return new AMQProtocolSessionMBean(this);
- }
-
- public long getSessionID()
- {
- return _sessionID;
- }
-
- public LogActor getLogActor()
- {
- return _actor;
- }
-
- public void setMaxFrameSize(long frameMax)
- {
- _maxFrameSize = frameMax;
- }
-
- public long getMaxFrameSize()
- {
- return _maxFrameSize;
- }
-
- public boolean isClosing()
- {
- return _closing.get();
- }
-
- public void received(final ByteBuffer msg)
- {
- _lastIoTime = System.currentTimeMillis();
- try
- {
- final ArrayList<AMQDataBlock> dataBlocks = _codecFactory.getDecoder().decodeBuffer(msg);
- Job.fireAsynchEvent(_poolReference.getPool(), _readJob, new Runnable()
- {
- public void run()
- {
- // Decode buffer
-
- for (AMQDataBlock dataBlock : dataBlocks)
- {
- try
- {
- dataBlockReceived(dataBlock);
- }
- catch (Exception e)
- {
- _logger.error("Unexpected exception when processing datablock", e);
- closeProtocolSession();
- }
- }
- }
- });
- }
- catch (Exception e)
- {
- _logger.error("Unexpected exception when processing datablock", e);
- closeProtocolSession();
- }
- }
-
- public void dataBlockReceived(AMQDataBlock message) throws Exception
- {
- _lastReceived = message;
- if (message instanceof ProtocolInitiation)
- {
- protocolInitiationReceived((ProtocolInitiation) message);
-
- }
- else if (message instanceof AMQFrame)
- {
- AMQFrame frame = (AMQFrame) message;
- frameReceived(frame);
-
- }
- else
- {
- throw new AMQException("Unknown message type: " + message.getClass().getName() + ": " + message);
- }
- }
-
- private void frameReceived(AMQFrame frame) throws AMQException
- {
- int channelId = frame.getChannel();
- AMQBody body = frame.getBodyFrame();
-
- //Look up the Channel's Actor and set that as the current actor
- // If that is not available then we can use the ConnectionActor
- // that is associated with this AMQMPSession.
- LogActor channelActor = null;
- if (_channelMap.get(channelId) != null)
- {
- channelActor = _channelMap.get(channelId).getLogActor();
- }
- CurrentActor.set(channelActor == null ? _actor : channelActor);
-
- try
- {
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Frame Received: " + frame);
- }
-
- // Check that this channel is not closing
- if (channelAwaitingClosure(channelId))
- {
- if ((frame.getBodyFrame() instanceof ChannelCloseOkBody))
- {
- if (_logger.isInfoEnabled())
- {
- _logger.info("Channel[" + channelId + "] awaiting closure - processing close-ok");
- }
- }
- else
- {
- // The channel has been told to close, we don't process any more frames until
- // it's closed.
- return;
- }
- }
-
- try
- {
- body.handle(channelId, this);
- }
- catch (AMQException e)
- {
- closeChannel(channelId);
- throw e;
- }
- }
- finally
- {
- CurrentActor.remove();
- }
- }
-
- private void protocolInitiationReceived(ProtocolInitiation pi)
- {
- // this ensures the codec never checks for a PI message again
- ((AMQDecoder) _codecFactory.getDecoder()).setExpectProtocolInitiation(false);
- try
- {
- // Log incomming protocol negotiation request
- _actor.message(ConnectionMessages.OPEN(null, pi._protocolMajor + "-" + pi._protocolMinor, false, true));
-
- ProtocolVersion pv = pi.checkVersion(); // Fails if not correct
-
- // This sets the protocol version (and hence framing classes) for this session.
- setProtocolVersion(pv);
-
- String mechanisms = ApplicationRegistry.getInstance().getAuthenticationManager().getMechanisms();
-
- String locales = "en_US";
-
- AMQMethodBody responseBody = getMethodRegistry().createConnectionStartBody((short) getProtocolMajorVersion(),
- (short) pv.getActualMinorVersion(),
- null,
- mechanisms.getBytes(),
- locales.getBytes());
- _networkDriver.send(responseBody.generateFrame(0).toNioByteBuffer());
-
- }
- catch (AMQException e)
- {
- _logger.info("Received unsupported protocol initiation for protocol version: " + getProtocolVersion());
-
- _networkDriver.send(new ProtocolInitiation(ProtocolVersion.getLatestSupportedVersion()).toNioByteBuffer());
- }
- }
-
- public void methodFrameReceived(int channelId, AMQMethodBody methodBody)
- {
- final AMQMethodEvent<AMQMethodBody> evt = new AMQMethodEvent<AMQMethodBody>(channelId, methodBody);
-
- try
- {
- try
- {
- boolean wasAnyoneInterested = _stateManager.methodReceived(evt);
-
- if (!_frameListeners.isEmpty())
- {
- for (AMQMethodListener listener : _frameListeners)
- {
- wasAnyoneInterested = listener.methodReceived(evt) || wasAnyoneInterested;
- }
- }
-
- if (!wasAnyoneInterested)
- {
- throw new AMQNoMethodHandlerException(evt);
- }
- }
- catch (AMQChannelException e)
- {
- if (getChannel(channelId) != null)
- {
- if (_logger.isInfoEnabled())
- {
- _logger.info("Closing channel due to: " + e.getMessage());
- }
-
- writeFrame(e.getCloseFrame(channelId));
- closeChannel(channelId);
- }
- else
- {
- if (_logger.isDebugEnabled())
- {
- _logger.debug("ChannelException occured on non-existent channel:" + e.getMessage());
- }
-
- if (_logger.isInfoEnabled())
- {
- _logger.info("Closing connection due to: " + e.getMessage());
- }
-
- AMQConnectionException ce =
- evt.getMethod().getConnectionException(AMQConstant.CHANNEL_ERROR,
- AMQConstant.CHANNEL_ERROR.getName().toString());
-
- _logger.info(e.getMessage() + " whilst processing:" + methodBody);
- closeConnection(channelId, ce, false);
- }
- }
- catch (AMQConnectionException e)
- {
- _logger.info(e.getMessage() + " whilst processing:" + methodBody);
- closeConnection(channelId, e, false);
- }
- catch (AMQSecurityException e)
- {
- AMQConnectionException ce = evt.getMethod().getConnectionException(AMQConstant.ACCESS_REFUSED, e.getMessage());
- _logger.info(e.getMessage() + " whilst processing:" + methodBody);
- closeConnection(channelId, ce, false);
- }
- }
- catch (Exception e)
- {
- for (AMQMethodListener listener : _frameListeners)
- {
- listener.error(e);
- }
-
- _logger.error("Unexpected exception while processing frame. Closing connection.", e);
-
- closeProtocolSession();
- }
- }
-
- public void contentHeaderReceived(int channelId, ContentHeaderBody body) throws AMQException
- {
-
- AMQChannel channel = getAndAssertChannel(channelId);
-
- channel.publishContentHeader(body);
-
- }
-
- public void contentBodyReceived(int channelId, ContentBody body) throws AMQException
- {
- AMQChannel channel = getAndAssertChannel(channelId);
-
- channel.publishContentBody(body);
- }
-
- public void heartbeatBodyReceived(int channelId, HeartbeatBody body)
- {
- // NO - OP
- }
-
- /**
- * Convenience method that writes a frame to the protocol session. Equivalent to calling
- * getProtocolSession().write().
- *
- * @param frame the frame to write
- */
- public void writeFrame(AMQDataBlock frame)
- {
- _lastSent = frame;
- final ByteBuffer buf = frame.toNioByteBuffer();
- _lastIoTime = System.currentTimeMillis();
- _writtenBytes += buf.remaining();
- Job.fireAsynchEvent(_poolReference.getPool(), _writeJob, new Runnable()
- {
- public void run()
- {
- _networkDriver.send(buf);
- }
- });
- }
-
- public AMQShortString getContextKey()
- {
- return _contextKey;
- }
-
- public void setContextKey(AMQShortString contextKey)
- {
- _contextKey = contextKey;
- }
-
- public List<AMQChannel> getChannels()
- {
- return new ArrayList<AMQChannel>(_channelMap.values());
- }
-
- public AMQChannel getAndAssertChannel(int channelId) throws AMQException
- {
- AMQChannel channel = getChannel(channelId);
- if (channel == null)
- {
- throw new AMQException(AMQConstant.NOT_FOUND, "Channel not found with id:" + channelId);
- }
-
- return channel;
- }
-
- public AMQChannel getChannel(int channelId)
- {
- final AMQChannel channel =
- ((channelId & CHANNEL_CACHE_SIZE) == channelId) ? _cachedChannels[channelId] : _channelMap.get(channelId);
- if ((channel == null) || channel.isClosing())
- {
- return null;
- }
- else
- {
- return channel;
- }
- }
-
- public boolean channelAwaitingClosure(int channelId)
- {
- return !_closingChannelsList.isEmpty() && _closingChannelsList.containsKey(channelId);
- }
-
- public void addChannel(AMQChannel channel) throws AMQException
- {
- if (_closed)
- {
- throw new AMQException("Session is closed");
- }
-
- final int channelId = channel.getChannelId();
-
- if (_closingChannelsList.containsKey(channelId))
- {
- throw new AMQException("Session is marked awaiting channel close");
- }
-
- if (_channelMap.size() == _maxNoOfChannels)
- {
- String errorMessage =
- toString() + ": maximum number of channels has been reached (" + _maxNoOfChannels
- + "); can't create channel";
- _logger.error(errorMessage);
- throw new AMQException(AMQConstant.NOT_ALLOWED, errorMessage);
- }
- else
- {
- _channelMap.put(channel.getChannelId(), channel);
- }
-
- if (((channelId & CHANNEL_CACHE_SIZE) == channelId))
- {
- _cachedChannels[channelId] = channel;
- }
-
- checkForNotification();
- }
-
- private void checkForNotification()
- {
- int channelsCount = _channelMap.size();
- if (_managedObject != null && channelsCount >= _maxNoOfChannels)
- {
- _managedObject.notifyClients("Channel count (" + channelsCount + ") has reached the threshold value");
- }
- }
-
- public Long getMaximumNumberOfChannels()
- {
- return _maxNoOfChannels;
- }
-
- public void setMaximumNumberOfChannels(Long value)
- {
- _maxNoOfChannels = value;
- }
-
- public void commitTransactions(AMQChannel channel) throws AMQException
- {
- if ((channel != null) && channel.isTransactional())
- {
- channel.commit();
- }
- }
-
- public void rollbackTransactions(AMQChannel channel) throws AMQException
- {
- if ((channel != null) && channel.isTransactional())
- {
- channel.rollback();
- }
- }
-
- /**
- * Close a specific channel. This will remove any resources used by the channel, including: <ul><li>any queue
- * subscriptions (this may in turn remove queues if they are auto delete</li> </ul>
- *
- * @param channelId id of the channel to close
- *
- * @throws AMQException if an error occurs closing the channel
- * @throws IllegalArgumentException if the channel id is not valid
- */
- public void closeChannel(int channelId) throws AMQException
- {
- final AMQChannel channel = getChannel(channelId);
- if (channel == null)
- {
- throw new IllegalArgumentException("Unknown channel id");
- }
- else
- {
- try
- {
- channel.close();
- markChannelAwaitingCloseOk(channelId);
- }
- finally
- {
- removeChannel(channelId);
- }
- }
- }
-
- public void closeChannelOk(int channelId)
- {
- // todo QPID-847 - This is called from two lcoations ChannelCloseHandler and ChannelCloseOkHandler.
- // When it is the CC_OK_Handler then it makes sence to remove the channel else we will leak memory.
- // We do it from the Close Handler as we are sending the OK back to the client.
- // While this is AMQP spec compliant. The Java client in the event of an IllegalArgumentException
- // will send a close-ok.. Where we should call removeChannel.
- // 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);
- }
-
- private void markChannelAwaitingCloseOk(int channelId)
- {
- _closingChannelsList.put(channelId, System.currentTimeMillis());
- }
-
- /**
- * In our current implementation this is used by the clustering code.
- *
- * @param channelId The channel to remove
- */
- public void removeChannel(int channelId)
- {
- _channelMap.remove(channelId);
- if ((channelId & CHANNEL_CACHE_SIZE) == channelId)
- {
- _cachedChannels[channelId] = null;
- }
- }
-
- /**
- * Initialise heartbeats on the session.
- *
- * @param delay delay in seconds (not ms)
- */
- public void initHeartbeats(int delay)
- {
- if (delay > 0)
- {
- _networkDriver.setMaxWriteIdle(delay);
- _networkDriver.setMaxReadIdle((int) (ApplicationRegistry.getInstance().getConfiguration().getHeartBeatTimeout() * delay));
- }
- }
-
- /**
- * Closes all channels that were opened by this protocol session. This frees up all resources used by the channel.
- *
- * @throws AMQException if an error occurs while closing any channel
- */
- private void closeAllChannels() throws AMQException
- {
- for (AMQChannel channel : _channelMap.values())
- {
- channel.close();
- }
-
- _channelMap.clear();
- for (int i = 0; i <= CHANNEL_CACHE_SIZE; i++)
- {
- _cachedChannels[i] = null;
- }
- }
-
- /** This must be called when the session is _closed in order to free up any resources managed by the session. */
- public void closeSession() throws AMQException
- {
- if(_closing.compareAndSet(false,true))
- {
- // REMOVE THIS SHOULD NOT BE HERE.
- if (CurrentActor.get() == null)
- {
- CurrentActor.set(_actor);
- }
- if (!_closed)
- {
- if (_virtualHost != null)
- {
- _virtualHost.getConnectionRegistry().deregisterConnection(this);
- }
-
- closeAllChannels();
-
- getConfigStore().removeConfiguredObject(this);
-
- if (_managedObject != null)
- {
- _managedObject.unregister();
- // Ensure we only do this once.
- _managedObject = null;
- }
-
- for (Task task : _taskList)
- {
- task.doTask(this);
- }
-
- synchronized(this)
- {
- _closed = true;
- notifyAll();
- }
- _poolReference.releaseExecutorService();
- CurrentActor.get().message(_logSubject, ConnectionMessages.CLOSE());
- }
- }
- else
- {
- synchronized(this)
- {
- while(!_closed)
- {
- try
- {
- wait(1000);
- }
- catch (InterruptedException e)
- {
-
- }
- }
- }
- }
- }
-
- public void closeConnection(int channelId, AMQConnectionException e, boolean closeProtocolSession) throws AMQException
- {
- if (_logger.isInfoEnabled())
- {
- _logger.info("Closing connection due to: " + e);
- }
-
- markChannelAwaitingCloseOk(channelId);
- closeSession();
- _stateManager.changeState(AMQState.CONNECTION_CLOSING);
- writeFrame(e.getCloseFrame(channelId));
-
- if (closeProtocolSession)
- {
- closeProtocolSession();
- }
- }
-
- public void closeProtocolSession()
- {
- _networkDriver.close();
- try
- {
- _stateManager.changeState(AMQState.CONNECTION_CLOSED);
- }
- catch (AMQException e)
- {
- _logger.info(e.getMessage());
- }
- }
-
- public String toString()
- {
- return getRemoteAddress() + "(" + (getAuthorizedID() == null ? "?" : getAuthorizedID().getName() + ")");
- }
-
- public String dump()
- {
- return this + " last_sent=" + _lastSent + " last_received=" + _lastReceived;
- }
-
- /** @return an object that can be used to identity */
- public Object getKey()
- {
- return getRemoteAddress();
- }
-
- /**
- * Get the fully qualified domain name of the local address to which this session is bound. Since some servers may
- * be bound to multiple addresses this could vary depending on the acceptor this session was created from.
- *
- * @return a String FQDN
- */
- public String getLocalFQDN()
- {
- SocketAddress address = _networkDriver.getLocalAddress();
- // we use the vmpipe address in some tests hence the need for this rather ugly test. The host
- // information is used by SASL primary.
- if (address instanceof InetSocketAddress)
- {
- return ((InetSocketAddress) address).getHostName();
- }
- else if (address instanceof VmPipeAddress)
- {
- return "vmpipe:" + ((VmPipeAddress) address).getPort();
- }
- else
- {
- throw new IllegalArgumentException("Unsupported socket address class: " + address);
- }
- }
-
- public SaslServer getSaslServer()
- {
- return _saslServer;
- }
-
- public void setSaslServer(SaslServer saslServer)
- {
- _saslServer = saslServer;
- }
-
- public FieldTable getClientProperties()
- {
- return _clientProperties;
- }
-
- public void setClientProperties(FieldTable clientProperties)
- {
- _clientProperties = clientProperties;
- if (_clientProperties != null)
- {
- if (_clientProperties.getString(CLIENT_PROPERTIES_INSTANCE) != null)
- {
- String clientID = _clientProperties.getString(CLIENT_PROPERTIES_INSTANCE);
- 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()));
- }
- }
- _sessionIdentifier = new ProtocolSessionIdentifier(this);
- }
-
- private void setProtocolVersion(ProtocolVersion pv)
- {
- _protocolVersion = pv;
-
- _protocolOutputConverter = ProtocolOutputConverterRegistry.getConverter(this);
- _dispatcher = ServerMethodDispatcherImpl.createMethodDispatcher(_stateManager, _protocolVersion);
- }
-
- public byte getProtocolMajorVersion()
- {
- return _protocolVersion.getMajorVersion();
- }
-
- public ProtocolVersion getProtocolVersion()
- {
- return _protocolVersion;
- }
-
- public byte getProtocolMinorVersion()
- {
- return _protocolVersion.getMinorVersion();
- }
-
- public boolean isProtocolVersion(byte major, byte minor)
- {
- return (getProtocolMajorVersion() == major) && (getProtocolMinorVersion() == minor);
- }
-
- public MethodRegistry getRegistry()
- {
- return getMethodRegistry();
- }
-
- public Object getClientIdentifier()
- {
- return (_networkDriver != null) ? _networkDriver.getRemoteAddress() : null;
- }
-
- public VirtualHost getVirtualHost()
- {
- return _virtualHost;
- }
-
- public void setVirtualHost(VirtualHost virtualHost) throws AMQException
- {
- _virtualHost = virtualHost;
-
- _virtualHost.getConnectionRegistry().registerConnection(this);
-
- _configStore.addConfiguredObject(this);
-
- try
- {
- _managedObject = createMBean();
- _managedObject.register();
- }
- catch (JMException e)
- {
- _logger.error(e);
- }
- }
-
- public void addSessionCloseTask(Task task)
- {
- _taskList.add(task);
- }
-
- public void removeSessionCloseTask(Task task)
- {
- _taskList.remove(task);
- }
-
- public ProtocolOutputConverter getProtocolOutputConverter()
- {
- return _protocolOutputConverter;
- }
-
- public void setAuthorizedID(Principal authorizedID)
- {
- _authorizedID = authorizedID;
- }
-
- public Principal getAuthorizedID()
- {
- return _authorizedID;
- }
-
- public Principal getPrincipal()
- {
- return _authorizedID;
- }
-
- public SocketAddress getRemoteAddress()
- {
- return _networkDriver.getRemoteAddress();
- }
-
- public SocketAddress getLocalAddress()
- {
- return _networkDriver.getLocalAddress();
- }
-
- public MethodRegistry getMethodRegistry()
- {
- return MethodRegistry.getMethodRegistry(getProtocolVersion());
- }
-
- public MethodDispatcher getMethodDispatcher()
- {
- return _dispatcher;
- }
-
- public void closed()
- {
- try
- {
- closeSession();
- }
- catch (AMQException e)
- {
- _logger.error("Could not close protocol engine", e);
- }
- }
-
- public void readerIdle()
- {
- // Nothing
- }
-
- public void setNetworkDriver(NetworkDriver driver)
- {
- _networkDriver = driver;
- }
-
- public void writerIdle()
- {
- _networkDriver.send(HeartbeatBody.FRAME.toNioByteBuffer());
- }
-
- public void exception(Throwable throwable)
- {
- if (throwable instanceof AMQProtocolHeaderException)
- {
- writeFrame(new ProtocolInitiation(ProtocolVersion.getLatestSupportedVersion()));
- _networkDriver.close();
-
- _logger.error("Error in protocol initiation " + this + ":" + getRemoteAddress() + " :" + throwable.getMessage(), throwable);
- }
- else if (throwable instanceof IOException)
- {
- _logger.error("IOException caught in" + this + ", session closed implictly: " + throwable);
- }
- else
- {
- _logger.error("Exception caught in" + this + ", closing session explictly: " + throwable, throwable);
-
-
- MethodRegistry methodRegistry = MethodRegistry.getMethodRegistry(getProtocolVersion());
- ConnectionCloseBody closeBody = methodRegistry.createConnectionCloseBody(200,new AMQShortString(throwable.getMessage()),0,0);
-
- writeFrame(closeBody.generateFrame(0));
-
- _networkDriver.close();
- }
- }
-
- public void init()
- {
- // Do nothing
- }
-
- public void setSender(Sender<ByteBuffer> sender)
- {
- // Do nothing
- }
-
- public long getReadBytes()
- {
- return _readBytes;
- }
-
- public long getWrittenBytes()
- {
- return _writtenBytes;
- }
-
- public long getLastIoTime()
- {
- return _lastIoTime;
- }
-
- public ProtocolSessionIdentifier getSessionIdentifier()
- {
- return _sessionIdentifier;
- }
-
- public String getClientVersion()
- {
- return (_clientVersion == null) ? null : _clientVersion.toString();
- }
-
- public Boolean isIncoming()
- {
- return true;
- }
-
- public Boolean isSystemConnection()
- {
- return false;
- }
-
- public Boolean isFederationLink()
- {
- return false;
- }
-
- public String getAuthId()
- {
- return getAuthorizedID().getName();
- }
-
- public Integer getRemotePID()
- {
- return null;
- }
-
- public String getRemoteProcessName()
- {
- return null;
- }
-
- public Integer getRemoteParentPID()
- {
- return null;
- }
-
- public ConfigStore getConfigStore()
- {
- return _configStore;
- }
-
- public ConnectionConfigType getConfigType()
- {
- return ConnectionConfigType.getInstance();
- }
-
- public ConfiguredObject getParent()
- {
- return getVirtualHost();
- }
-
- public boolean isDurable()
- {
- return false;
- }
-
- public UUID getId()
- {
- return _id;
- }
-
- public long getConnectionId()
- {
- return getSessionID();
- }
-
- public String getAddress()
- {
- return String.valueOf(getRemoteAddress());
- }
-
- public long getCreateTime()
- {
- return _createTime;
- }
-
- public Boolean isShadow()
- {
- return false;
- }
-
- public void mgmtClose()
- {
- MethodRegistry methodRegistry = getMethodRegistry();
- ConnectionCloseBody responseBody =
- methodRegistry.createConnectionCloseBody(
- AMQConstant.REPLY_SUCCESS.getCode(),
- new AMQShortString("The connection was closed using the broker's management interface."),
- 0,0);
-
- // This seems ugly but because we use closeConnection in both normal
- // broker operation and as part of the management interface it cannot
- // be avoided. The Current Actor will be null when this method is
- // called via the QMF management interface. As such we need to set one.
- boolean removeActor = false;
- if (CurrentActor.get() == null)
- {
- removeActor = true;
- CurrentActor.set(new ManagementActor(_actor.getRootMessageLogger()));
- }
-
- try
- {
- writeFrame(responseBody.generateFrame(0));
-
- try
- {
-
- closeSession();
- }
- catch (AMQException ex)
- {
- throw new RuntimeException(ex);
- }
- }
- finally
- {
- if (removeActor)
- {
- CurrentActor.remove();
- }
- }
- }
-
- public void mgmtCloseChannel(int channelId)
- {
- MethodRegistry methodRegistry = getMethodRegistry();
- ChannelCloseBody responseBody =
- methodRegistry.createChannelCloseBody(
- AMQConstant.REPLY_SUCCESS.getCode(),
- new AMQShortString("The channel was closed using the broker's management interface."),
- 0,0);
-
- // This seems ugly but because we use AMQChannel.close() in both normal
- // broker operation and as part of the management interface it cannot
- // be avoided. The Current Actor will be null when this method is
- // called via the QMF management interface. As such we need to set one.
- boolean removeActor = false;
- if (CurrentActor.get() == null)
- {
- removeActor = true;
- CurrentActor.set(new ManagementActor(_actor.getRootMessageLogger()));
- }
-
- try
- {
- writeFrame(responseBody.generateFrame(channelId));
-
- try
- {
- closeChannel(channelId);
- }
- catch (AMQException ex)
- {
- throw new RuntimeException(ex);
- }
- }
- finally
- {
- if (removeActor)
- {
- CurrentActor.remove();
- }
- }
- }
-
- public String getClientID()
- {
- return getContextKey().toString();
- }
-
- public void closeSession(AMQSessionModel session, AMQConstant cause, String message) throws AMQException
- {
- closeChannel((Integer)session.getID());
-
- MethodRegistry methodRegistry = getMethodRegistry();
- ChannelCloseBody responseBody =
- methodRegistry.createChannelCloseBody(
- cause.getCode(),
- new AMQShortString(message),
- 0,0);
-
- writeFrame(responseBody.generateFrame((Integer)session.getID()));
- }
-
- public void close(AMQConstant cause, String message) throws AMQException
- {
- closeConnection(0, new AMQConnectionException(cause, message, 0, 0,
- getProtocolOutputConverter().getProtocolMajorVersion(),
- getProtocolOutputConverter().getProtocolMinorVersion(),
- (Throwable) null), true);
- }
-
- public List<AMQSessionModel> getSessionModels()
- {
- List<AMQSessionModel> sessions = new ArrayList<AMQSessionModel>();
- for (AMQChannel channel : getChannels())
- {
- sessions.add((AMQSessionModel) channel);
- }
- return sessions;
- }
-
- public LogSubject getLogSubject()
- {
- return _logSubject;
- }
-
- public void registerMessageDelivered(long messageSize)
- {
- if (isStatisticsEnabled())
- {
- _messagesDelivered.registerEvent(1L);
- _dataDelivered.registerEvent(messageSize);
- }
- _virtualHost.registerMessageDelivered(messageSize);
- }
-
- public void registerMessageReceived(long messageSize, long timestamp)
- {
- if (isStatisticsEnabled())
- {
- _messagesReceived.registerEvent(1L, timestamp);
- _dataReceived.registerEvent(messageSize, timestamp);
- }
- _virtualHost.registerMessageReceived(messageSize, timestamp);
- }
-
- public StatisticsCounter getMessageReceiptStatistics()
- {
- return _messagesReceived;
- }
-
- public StatisticsCounter getDataReceiptStatistics()
- {
- return _dataReceived;
- }
-
- public StatisticsCounter getMessageDeliveryStatistics()
- {
- return _messagesDelivered;
- }
-
- public StatisticsCounter getDataDeliveryStatistics()
- {
- return _dataDelivered;
- }
-
- public void resetStatistics()
- {
- _messagesDelivered.reset();
- _dataDelivered.reset();
- _messagesReceived.reset();
- _dataReceived.reset();
- }
-
- public void initialiseStatistics()
- {
- setStatisticsEnabled(!StatisticsCounter.DISABLE_STATISTICS &&
- _registry.getConfiguration().isStatisticsGenerationConnectionsEnabled());
-
- _messagesDelivered = new StatisticsCounter("messages-delivered-" + getSessionID());
- _dataDelivered = new StatisticsCounter("data-delivered-" + getSessionID());
- _messagesReceived = new StatisticsCounter("messages-received-" + getSessionID());
- _dataReceived = new StatisticsCounter("data-received-" + getSessionID());
- }
-
- public boolean isStatisticsEnabled()
- {
- return _statisticsEnabled;
- }
-
- public void setStatisticsEnabled(boolean enabled)
- {
- _statisticsEnabled = enabled;
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolEngineFactory.java b/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolEngineFactory.java
deleted file mode 100644
index 0e4444725e..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolEngineFactory.java
+++ /dev/null
@@ -1,50 +0,0 @@
-package org.apache.qpid.server.protocol;
-/*
- *
- * 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.protocol.ProtocolEngine;
-import org.apache.qpid.protocol.ProtocolEngineFactory;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-import org.apache.qpid.server.virtualhost.VirtualHostRegistry;
-import org.apache.qpid.transport.NetworkDriver;
-
-public class AMQProtocolEngineFactory implements ProtocolEngineFactory
-{
- private VirtualHostRegistry _vhosts;
-
- public AMQProtocolEngineFactory()
- {
- this(1);
- }
-
- public AMQProtocolEngineFactory(Integer port)
- {
- _vhosts = ApplicationRegistry.getInstance(port).getVirtualHostRegistry();
- }
-
-
- public ProtocolEngine newProtocolEngine(NetworkDriver networkDriver)
- {
- return new AMQProtocolEngine(_vhosts, networkDriver);
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolSession.java b/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolSession.java
deleted file mode 100644
index c64ed4ad5a..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolSession.java
+++ /dev/null
@@ -1,235 +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.protocol;
-
-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.protocol.AMQVersionAwareProtocolSession;
-import org.apache.qpid.server.AMQChannel;
-import org.apache.qpid.server.security.PrincipalHolder;
-import org.apache.qpid.server.logging.LogActor;
-import org.apache.qpid.server.output.ProtocolOutputConverter;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-
-import java.security.Principal;
-import java.util.List;
-
-
-public interface AMQProtocolSession extends AMQVersionAwareProtocolSession, PrincipalHolder, AMQConnectionModel
-{
- long getSessionID();
-
- LogActor getLogActor();
-
- void setMaxFrameSize(long frameMax);
-
- long getMaxFrameSize();
-
- boolean isClosing();
-
- 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;
- }
-
- /**
- * Called when a protocol data block is received
- *
- * @param message the data block that has been received
- *
- * @throws Exception if processing the datablock fails
- */
- void dataBlockReceived(AMQDataBlock message) throws Exception;
-
- /**
- * Get the context key associated with this session. Context key is described in the AMQ protocol specification (RFC
- * 6).
- *
- * @return the context key
- */
- AMQShortString getContextKey();
-
- /**
- * Set the context key associated with this session. Context key is described in the AMQ protocol specification (RFC
- * 6).
- *
- * @param contextKey the context key
- */
- void setContextKey(AMQShortString contextKey);
-
- /**
- * Get the channel for this session associated with the specified id. A channel id is unique per connection (i.e.
- * per session).
- *
- * @param channelId the channel id which must be valid
- *
- * @return null if no channel exists, the channel otherwise
- */
- AMQChannel getChannel(int channelId);
-
- /**
- * Associate a channel with this session.
- *
- * @param channel the channel to associate with this session. It is an error to associate the same channel with more
- * than one session but this is not validated.
- */
- void addChannel(AMQChannel channel) throws AMQException;
-
- /**
- * Close a specific channel. This will remove any resources used by the channel, including: <ul><li>any queue
- * subscriptions (this may in turn remove queues if they are auto delete</li> </ul>
- *
- * @param channelId id of the channel to close
- *
- * @throws org.apache.qpid.AMQException if an error occurs closing the channel
- * @throws IllegalArgumentException if the channel id is not valid
- */
- void closeChannel(int channelId) throws AMQException;
-
- /**
- * Markes the specific channel as closed. This will release the lock for that channel id so a new channel can be
- * created on that id.
- *
- * @param channelId id of the channel to close
- */
- void closeChannelOk(int channelId);
-
- /**
- * Check to see if this chanel is closing
- *
- * @param channelId id to check
- * @return boolean with state of channel awaiting closure
- */
- boolean channelAwaitingClosure(int channelId);
-
- /**
- * Remove a channel from the session but do not close it.
- *
- * @param channelId
- */
- void removeChannel(int channelId);
-
- /**
- * Initialise heartbeats on the session.
- *
- * @param delay delay in seconds (not ms)
- */
- void initHeartbeats(int delay);
-
- /** This must be called when the session is _closed in order to free up any resources managed by the session. */
- void closeSession() throws AMQException;
-
- /** This must be called to close the session in order to free up any resources managed by the session. */
- void closeConnection(int channelId, AMQConnectionException e, boolean closeProtocolSession) throws AMQException;
-
-
- /** @return a key that uniquely identifies this session */
- Object getKey();
-
- /**
- * Get the fully qualified domain name of the local address to which this session is bound. Since some servers may
- * be bound to multiple addresses this could vary depending on the acceptor this session was created from.
- *
- * @return a String FQDN
- */
- String getLocalFQDN();
-
- /** @return the sasl server that can perform authentication for this session. */
- SaslServer getSaslServer();
-
- /**
- * Set the sasl server that is to perform authentication for this session.
- *
- * @param saslServer
- */
- void setSaslServer(SaslServer saslServer);
-
-
- FieldTable getClientProperties();
-
- void setClientProperties(FieldTable clientProperties);
-
- Object getClientIdentifier();
-
- VirtualHost getVirtualHost();
-
- void setVirtualHost(VirtualHost virtualHost) throws AMQException;
-
- void addSessionCloseTask(Task task);
-
- void removeSessionCloseTask(Task task);
-
- public ProtocolOutputConverter getProtocolOutputConverter();
-
- void setAuthorizedID(Principal authorizedID);
-
- public java.net.SocketAddress getRemoteAddress();
-
- public MethodRegistry getMethodRegistry();
-
- public MethodDispatcher getMethodDispatcher();
-
- public ProtocolSessionIdentifier getSessionIdentifier();
-
- String getClientVersion();
-
- long getLastIoTime();
-
- long getWrittenBytes();
-
- Long getMaximumNumberOfChannels();
-
- void setMaximumNumberOfChannels(Long value);
-
- void commitTransactions(AMQChannel channel) throws AMQException;
-
- void rollbackTransactions(AMQChannel channel) throws AMQException;
-
- List<AMQChannel> getChannels();
-
- void mgmtCloseChannel(int channelId);
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolSessionMBean.java b/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolSessionMBean.java
deleted file mode 100644
index fcac78fafa..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolSessionMBean.java
+++ /dev/null
@@ -1,417 +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.
- *
- */
-/*
- *
- * Copyright (c) 2006 The Apache Software Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-package org.apache.qpid.server.protocol;
-
-import java.util.Date;
-import java.util.List;
-
-import javax.management.JMException;
-import javax.management.MBeanException;
-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.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 org.apache.qpid.AMQException;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.ConnectionCloseBody;
-import org.apache.qpid.framing.MethodRegistry;
-import org.apache.qpid.management.common.mbeans.ManagedConnection;
-import org.apache.qpid.management.common.mbeans.annotations.MBeanConstructor;
-import org.apache.qpid.management.common.mbeans.annotations.MBeanDescription;
-import org.apache.qpid.protocol.AMQConstant;
-import org.apache.qpid.server.AMQChannel;
-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;
-
-/**
- * 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.
- */
-@MBeanDescription("Management Bean for an AMQ Broker Connection")
-public class AMQProtocolSessionMBean extends AMQManagedObject implements ManagedConnection
-{
- private AMQProtocolSession _protocolSession = null;
- private String _name = null;
-
- // openmbean data types for representing the channel attributes
-
- private static final OpenType[] _channelAttributeTypes =
- { SimpleType.INTEGER, SimpleType.BOOLEAN, SimpleType.STRING, SimpleType.INTEGER, SimpleType.BOOLEAN };
- private static CompositeType _channelType = null; // represents the data type for channel data
- private static TabularType _channelsType = null; // Data type for list of channels type
- private static final AMQShortString BROKER_MANAGEMENT_CONSOLE_HAS_CLOSED_THE_CONNECTION =
- new AMQShortString("Broker Management Console has closed the connection.");
-
- @MBeanConstructor("Creates an MBean exposing an AMQ Broker Connection")
- public AMQProtocolSessionMBean(AMQProtocolSession amqProtocolSession) throws NotCompliantMBeanException, OpenDataException
- {
- super(ManagedConnection.class, ManagedConnection.TYPE);
- _protocolSession = amqProtocolSession;
- String remote = getRemoteAddress();
- _name = "anonymous".equals(remote) ? (remote + hashCode()) : remote;
- init();
- }
-
- static
- {
- try
- {
- init();
- }
- catch (JMException ex)
- {
- // This is not expected to ever occur.
- throw new RuntimeException("Got JMException in static initializer.", ex);
- }
- }
-
- /**
- * initialises the openmbean data types
- */
- private static void init() throws OpenDataException
- {
- _channelType =
- new CompositeType("Channel", "Channel Details", COMPOSITE_ITEM_NAMES_DESC.toArray(new String[COMPOSITE_ITEM_NAMES_DESC.size()]),
- COMPOSITE_ITEM_NAMES_DESC.toArray(new String[COMPOSITE_ITEM_NAMES_DESC.size()]), _channelAttributeTypes);
- _channelsType = new TabularType("Channels", "Channels", _channelType, TABULAR_UNIQUE_INDEX.toArray(new String[TABULAR_UNIQUE_INDEX.size()]));
- }
-
- public String getClientId()
- {
- return String.valueOf(_protocolSession.getContextKey());
- }
-
- public String getAuthorizedId()
- {
- return (_protocolSession.getPrincipal() != null ) ? _protocolSession.getPrincipal().getName() : null;
- }
-
- public String getVersion()
- {
- return (_protocolSession.getClientVersion() == null) ? null : _protocolSession.getClientVersion().toString();
- }
-
- public Date getLastIoTime()
- {
- return new Date(_protocolSession.getLastIoTime());
- }
-
- public String getRemoteAddress()
- {
- return _protocolSession.getRemoteAddress().toString();
- }
-
- public ManagedObject getParentObject()
- {
- return _protocolSession.getVirtualHost().getManagedObject();
- }
-
- public Long getWrittenBytes()
- {
- return _protocolSession.getWrittenBytes();
- }
-
- public Long getReadBytes()
- {
- return _protocolSession.getWrittenBytes();
- }
-
- public Long getMaximumNumberOfChannels()
- {
- return _protocolSession.getMaximumNumberOfChannels();
- }
-
- public void setMaximumNumberOfChannels(Long value)
- {
- _protocolSession.setMaximumNumberOfChannels(value);
- }
-
- public String getObjectInstanceName()
- {
- return ObjectName.quote(_name);
- }
-
- /**
- * commits transactions for a transactional channel
- *
- * @param channelId
- * @throws JMException if channel with given id doesn't exist or if commit fails
- */
- public void commitTransactions(int channelId) throws JMException
- {
- CurrentActor.set(new ManagementActor(_logActor.getRootMessageLogger()));
- try
- {
- AMQChannel channel = _protocolSession.getChannel(channelId);
- if (channel == null)
- {
- throw new JMException("The channel (channel Id = " + channelId + ") does not exist");
- }
-
- _protocolSession.commitTransactions(channel);
- }
- catch (AMQException ex)
- {
- throw new MBeanException(ex, ex.toString());
- }
- finally
- {
- CurrentActor.remove();
- }
- }
-
- /**
- * rollsback the transactions for a transactional channel
- *
- * @param channelId
- * @throws JMException if channel with given id doesn't exist or if rollback fails
- */
- public void rollbackTransactions(int channelId) throws JMException
- {
- CurrentActor.set(new ManagementActor(_logActor.getRootMessageLogger()));
- try
- {
- AMQChannel channel = _protocolSession.getChannel(channelId);
- if (channel == null)
- {
- throw new JMException("The channel (channel Id = " + channelId + ") does not exist");
- }
-
- _protocolSession.rollbackTransactions(channel);
- }
- catch (AMQException ex)
- {
- throw new MBeanException(ex, ex.toString());
- }
- finally
- {
- CurrentActor.remove();
- }
- }
-
- /**
- * Creates the list of channels in tabular form from the _channelMap.
- *
- * @return list of channels in tabular form.
- * @throws OpenDataException
- */
- public TabularData channels() throws OpenDataException
- {
- TabularDataSupport channelsList = new TabularDataSupport(_channelsType);
- List<AMQChannel> list = _protocolSession.getChannels();
-
- for (AMQChannel channel : list)
- {
- Object[] itemValues =
- {
- channel.getChannelId(), channel.isTransactional(),
- (channel.getDefaultQueue() != null) ? channel.getDefaultQueue().getNameShortString().asString() : null,
- channel.getUnacknowledgedMessageMap().size(), channel.getBlocking()
- };
-
- CompositeData channelData = new CompositeDataSupport(_channelType,
- COMPOSITE_ITEM_NAMES_DESC.toArray(new String[COMPOSITE_ITEM_NAMES_DESC.size()]), itemValues);
- channelsList.put(channelData);
- }
-
- return channelsList;
- }
-
- /**
- * closes the connection. The administrator can use this management operation to close connection to free up
- * resources.
- * @throws JMException
- */
- public void closeConnection() throws JMException
- {
-
- MethodRegistry methodRegistry = _protocolSession.getMethodRegistry();
- ConnectionCloseBody responseBody =
- methodRegistry.createConnectionCloseBody(AMQConstant.REPLY_SUCCESS.getCode(),
- // replyCode
- BROKER_MANAGEMENT_CONSOLE_HAS_CLOSED_THE_CONNECTION,
- // replyText,
- 0,
- 0);
-
- // This seems ugly but because we use closeConnection in both normal
- // broker operation and as part of the management interface it cannot
- // be avoided. The Current Actor will be null when this method is
- // called via the Management interface. This is because we allow the
- // Local API connection with JConsole. If we did not allow that option
- // then the CurrentActor could be set in our JMX Proxy object.
- // As it is we need to set the CurrentActor on all MBean methods
- // Ideally we would not have a single method that can be called from
- // two contexts.
- boolean removeActor = false;
- if (CurrentActor.get() == null)
- {
- removeActor = true;
- CurrentActor.set(new ManagementActor(_logActor.getRootMessageLogger()));
- }
-
- try
- {
- _protocolSession.writeFrame(responseBody.generateFrame(0));
-
- try
- {
-
- _protocolSession.closeSession();
- }
- catch (AMQException ex)
- {
- throw new MBeanException(ex, ex.toString());
- }
- }
- finally
- {
- if (removeActor)
- {
- CurrentActor.remove();
- }
- }
- }
-
- @Override
- public MBeanNotificationInfo[] getNotificationInfo()
- {
- String[] notificationTypes = new String[] { MonitorNotification.THRESHOLD_VALUE_EXCEEDED };
- String name = MonitorNotification.class.getName();
- String description = "Channel count has reached threshold value";
- MBeanNotificationInfo info1 = new MBeanNotificationInfo(notificationTypes, name, description);
-
- return new MBeanNotificationInfo[] { info1 };
- }
-
- public void notifyClients(String notificationMsg)
- {
- Notification n =
- new Notification(MonitorNotification.THRESHOLD_VALUE_EXCEEDED, this, ++_notificationSequenceNumber,
- System.currentTimeMillis(), notificationMsg);
- _broadcaster.sendNotification(n);
- }
-
- public void resetStatistics() throws Exception
- {
- _protocolSession.resetStatistics();
- }
-
- public double getPeakMessageDeliveryRate()
- {
- return _protocolSession.getMessageDeliveryStatistics().getPeak();
- }
-
- public double getPeakDataDeliveryRate()
- {
- return _protocolSession.getDataDeliveryStatistics().getPeak();
- }
-
- public double getMessageDeliveryRate()
- {
- return _protocolSession.getMessageDeliveryStatistics().getRate();
- }
-
- public double getDataDeliveryRate()
- {
- return _protocolSession.getDataDeliveryStatistics().getRate();
- }
-
- public long getTotalMessagesDelivered()
- {
- return _protocolSession.getMessageDeliveryStatistics().getTotal();
- }
-
- public long getTotalDataDelivered()
- {
- return _protocolSession.getDataDeliveryStatistics().getTotal();
- }
-
- public double getPeakMessageReceiptRate()
- {
- return _protocolSession.getMessageReceiptStatistics().getPeak();
- }
-
- public double getPeakDataReceiptRate()
- {
- return _protocolSession.getDataReceiptStatistics().getPeak();
- }
-
- public double getMessageReceiptRate()
- {
- return _protocolSession.getMessageReceiptStatistics().getRate();
- }
-
- public double getDataReceiptRate()
- {
- return _protocolSession.getDataReceiptStatistics().getRate();
- }
-
- public long getTotalMessagesReceived()
- {
- return _protocolSession.getMessageReceiptStatistics().getTotal();
- }
-
- public long getTotalDataReceived()
- {
- return _protocolSession.getDataReceiptStatistics().getTotal();
- }
-
- public boolean isStatisticsEnabled()
- {
- return _protocolSession.isStatisticsEnabled();
- }
-
- public void setStatisticsEnabled(boolean enabled)
- {
- _protocolSession.setStatisticsEnabled(enabled);
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQSessionModel.java b/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQSessionModel.java
deleted file mode 100644
index bc63403a86..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQSessionModel.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.protocol;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.server.logging.LogSubject;
-
-public interface AMQSessionModel
-{
- public Object getID();
-
- public AMQConnectionModel getConnectionModel();
-
- public String getClientID();
-
- public void close() throws AMQException;
-
- public LogSubject getLogSubject();
-
- /**
- * This method is called from the housekeeping thread to check the status of
- * transactions on this session and react appropriately.
- *
- * If a transaction is open for too long or idle for too long then a warning
- * is logged or the connection is closed, depending on the configuration. An open
- * transaction is one that has recent activity. The transaction age is counted
- * from the time the transaction was started. An idle transaction is one that
- * has had no activity, such as publishing or acknowledgeing messages.
- *
- * @param openWarn time in milliseconds before alerting on open transaction
- * @param openClose time in milliseconds before closing connection with open transaction
- * @param idleWarn time in milliseconds before alerting on idle transaction
- * @param idleClose time in milliseconds before closing connection with idle transaction
- */
- public void checkTransactionStatus(long openWarn, long openClose, long idleWarn, long idleClose) throws AMQException;
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/protocol/MultiVersionProtocolEngine.java b/java/broker/src/main/java/org/apache/qpid/server/protocol/MultiVersionProtocolEngine.java
deleted file mode 100755
index eb957ee33c..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/protocol/MultiVersionProtocolEngine.java
+++ /dev/null
@@ -1,425 +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.protocol;
-
-
-import org.apache.log4j.Logger;
-import org.apache.qpid.protocol.ProtocolEngine;
-import org.apache.qpid.server.protocol.MultiVersionProtocolEngineFactory.VERSION;
-import org.apache.qpid.server.registry.IApplicationRegistry;
-import org.apache.qpid.server.transport.ServerConnection;
-import org.apache.qpid.transport.ConnectionDelegate;
-import org.apache.qpid.transport.NetworkDriver;
-
-import java.net.SocketAddress;
-import java.nio.ByteBuffer;
-import java.util.Set;
-
-public class MultiVersionProtocolEngine implements ProtocolEngine
-{
- private static final Logger _logger = Logger.getLogger(MultiVersionProtocolEngine.class);
-
-
-
- private NetworkDriver _networkDriver;
- private Set<VERSION> _supported;
- private String _fqdn;
- private IApplicationRegistry _appRegistry;
-
- private volatile ProtocolEngine _delegate = new SelfDelegateProtocolEngine();
-
- public MultiVersionProtocolEngine(IApplicationRegistry appRegistry,
- String fqdn,
- Set<VERSION> supported, NetworkDriver networkDriver)
- {
- _appRegistry = appRegistry;
- _fqdn = fqdn;
- _supported = supported;
- _networkDriver = networkDriver;
- }
-
- public void setNetworkDriver(NetworkDriver driver)
- {
- _delegate.setNetworkDriver(driver);
- }
-
- public SocketAddress getRemoteAddress()
- {
- return _delegate.getRemoteAddress();
- }
-
- public SocketAddress getLocalAddress()
- {
- return _delegate.getLocalAddress();
- }
-
- public long getWrittenBytes()
- {
- return _delegate.getWrittenBytes();
- }
-
- public long getReadBytes()
- {
- return _delegate.getReadBytes();
- }
-
- public void closed()
- {
- _delegate.closed();
- }
-
- public void writerIdle()
- {
- _delegate.writerIdle();
- }
-
- public void readerIdle()
- {
- _delegate.readerIdle();
- }
-
- public void received(ByteBuffer msg)
- {
- _delegate.received(msg);
- }
-
- public void exception(Throwable t)
- {
- _delegate.exception(t);
- }
-
- private static final int MINIMUM_REQUIRED_HEADER_BYTES = 8;
-
- private static final byte[] AMQP_0_8_HEADER =
- new byte[] { (byte) 'A',
- (byte) 'M',
- (byte) 'Q',
- (byte) 'P',
- (byte) 1,
- (byte) 1,
- (byte) 8,
- (byte) 0
- };
-
- private static final byte[] AMQP_0_9_HEADER =
- new byte[] { (byte) 'A',
- (byte) 'M',
- (byte) 'Q',
- (byte) 'P',
- (byte) 1,
- (byte) 1,
- (byte) 0,
- (byte) 9
- };
-
-private static final byte[] AMQP_0_9_1_HEADER =
- new byte[] { (byte) 'A',
- (byte) 'M',
- (byte) 'Q',
- (byte) 'P',
- (byte) 0,
- (byte) 0,
- (byte) 9,
- (byte) 1
- };
-
-
- private static final byte[] AMQP_0_10_HEADER =
- new byte[] { (byte) 'A',
- (byte) 'M',
- (byte) 'Q',
- (byte) 'P',
- (byte) 1,
- (byte) 1,
- (byte) 0,
- (byte) 10
- };
-
- private static interface DelegateCreator
- {
- VERSION getVersion();
- byte[] getHeaderIdentifier();
- ProtocolEngine getProtocolEngine();
- }
-
- private DelegateCreator creator_0_8 = new DelegateCreator()
- {
-
- public VERSION getVersion()
- {
- return VERSION.v0_8;
- }
-
- public byte[] getHeaderIdentifier()
- {
- return AMQP_0_8_HEADER;
- }
-
- public ProtocolEngine getProtocolEngine()
- {
- return new AMQProtocolEngine(_appRegistry.getVirtualHostRegistry(), _networkDriver);
- }
- };
-
- private DelegateCreator creator_0_9 = new DelegateCreator()
- {
-
- public VERSION getVersion()
- {
- return VERSION.v0_9;
- }
-
-
- public byte[] getHeaderIdentifier()
- {
- return AMQP_0_9_HEADER;
- }
-
- public ProtocolEngine getProtocolEngine()
- {
- return new AMQProtocolEngine(_appRegistry.getVirtualHostRegistry(), _networkDriver);
- }
- };
-
- private DelegateCreator creator_0_9_1 = new DelegateCreator()
- {
-
- public VERSION getVersion()
- {
- return VERSION.v0_9_1;
- }
-
-
- public byte[] getHeaderIdentifier()
- {
- return AMQP_0_9_1_HEADER;
- }
-
- public ProtocolEngine getProtocolEngine()
- {
- return new AMQProtocolEngine(_appRegistry.getVirtualHostRegistry(), _networkDriver);
- }
- };
-
-
- private DelegateCreator creator_0_10 = new DelegateCreator()
- {
-
- public VERSION getVersion()
- {
- return VERSION.v0_10;
- }
-
-
- public byte[] getHeaderIdentifier()
- {
- return AMQP_0_10_HEADER;
- }
-
- public ProtocolEngine getProtocolEngine()
- {
- final ConnectionDelegate connDelegate =
- new org.apache.qpid.server.transport.ServerConnectionDelegate(_appRegistry, _fqdn);
-
- ServerConnection conn = new ServerConnection();
- conn.setConnectionDelegate(connDelegate);
-
- return new ProtocolEngine_0_10( conn, _networkDriver, _appRegistry);
- }
- };
-
- private final DelegateCreator[] _creators =
- new DelegateCreator[] { creator_0_8, creator_0_9, creator_0_9_1, creator_0_10 };
-
-
- private class ClosedDelegateProtocolEngine implements ProtocolEngine
- {
- public void setNetworkDriver(NetworkDriver driver)
- {
- _networkDriver = driver;
- }
-
- public SocketAddress getRemoteAddress()
- {
- return _networkDriver.getRemoteAddress();
- }
-
- public SocketAddress getLocalAddress()
- {
- return _networkDriver.getLocalAddress();
- }
-
- public long getWrittenBytes()
- {
- return 0;
- }
-
- public long getReadBytes()
- {
- return 0;
- }
-
- public void received(ByteBuffer msg)
- {
- _logger.error("Error processing incoming data, could not negotiate a common protocol");
- }
-
- public void exception(Throwable t)
- {
- _logger.error("Error establishing session", t);
- }
-
- public void closed()
- {
-
- }
-
- public void writerIdle()
- {
-
- }
-
- public void readerIdle()
- {
-
- }
- }
-
- private class SelfDelegateProtocolEngine implements ProtocolEngine
- {
-
- private final ByteBuffer _header = ByteBuffer.allocate(MINIMUM_REQUIRED_HEADER_BYTES);
-
- public void setNetworkDriver(NetworkDriver driver)
- {
- _networkDriver = driver;
- }
-
- public SocketAddress getRemoteAddress()
- {
- return _networkDriver.getRemoteAddress();
- }
-
- public SocketAddress getLocalAddress()
- {
- return _networkDriver.getLocalAddress();
- }
-
- public long getWrittenBytes()
- {
- return 0;
- }
-
- public long getReadBytes()
- {
- return 0;
- }
-
- public void received(ByteBuffer msg)
- {
- ByteBuffer msgheader = msg.duplicate();
- if(_header.remaining() > msgheader.limit())
- {
- msg.position(msg.limit());
- }
- else
- {
- msgheader.limit(_header.remaining());
- msg.position(_header.remaining());
- }
-
- _header.put(msgheader);
-
- if(!_header.hasRemaining())
- {
- _header.flip();
- byte[] headerBytes = new byte[MINIMUM_REQUIRED_HEADER_BYTES];
- _header.get(headerBytes);
-
-
- ProtocolEngine newDelegate = null;
- byte[] newestSupported = null;
-
- for(int i = 0; newDelegate == null && i < _creators.length; i++)
- {
-
- if(_supported.contains(_creators[i].getVersion()))
- {
- newestSupported = _creators[i].getHeaderIdentifier();
- byte[] compareBytes = _creators[i].getHeaderIdentifier();
- boolean equal = true;
- for(int j = 0; equal && j<compareBytes.length; j++)
- {
- equal = headerBytes[j] == compareBytes[j];
- }
- if(equal)
- {
- newDelegate = _creators[i].getProtocolEngine();
- }
- }
- }
-
- // If no delegate is found then send back the most recent support protocol version id
- if(newDelegate == null)
- {
- _networkDriver.send(ByteBuffer.wrap(newestSupported));
-
- _delegate = new ClosedDelegateProtocolEngine();
- }
- else
- {
- newDelegate.setNetworkDriver(_networkDriver);
-
- _delegate = newDelegate;
-
- _header.flip();
- _delegate.received(_header);
- if(msg.hasRemaining())
- {
- _delegate.received(msg);
- }
- }
-
- }
-
- }
-
- public void exception(Throwable t)
- {
- _logger.error("Error establishing session", t);
- }
-
- public void closed()
- {
-
- }
-
- public void writerIdle()
- {
-
- }
-
- public void readerIdle()
- {
-
- }
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/protocol/MultiVersionProtocolEngineFactory.java b/java/broker/src/main/java/org/apache/qpid/server/protocol/MultiVersionProtocolEngineFactory.java
deleted file mode 100755
index 75358c42d9..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/protocol/MultiVersionProtocolEngineFactory.java
+++ /dev/null
@@ -1,75 +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.protocol;
-
-import org.apache.qpid.protocol.ProtocolEngineFactory;
-import org.apache.qpid.protocol.ProtocolEngine;
-import org.apache.qpid.transport.NetworkDriver;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-import org.apache.qpid.server.registry.IApplicationRegistry;
-
-import java.util.Set;
-import java.util.Arrays;
-import java.util.HashSet;
-
-public class MultiVersionProtocolEngineFactory implements ProtocolEngineFactory
-{
- ;
-
-
- public enum VERSION { v0_8, v0_9, v0_9_1, v0_10 };
-
- private static final Set<VERSION> ALL_VERSIONS = new HashSet<VERSION>(Arrays.asList(VERSION.values()));
-
- private final IApplicationRegistry _appRegistry;
- private final String _fqdn;
- private final Set<VERSION> _supported;
-
-
- public MultiVersionProtocolEngineFactory()
- {
- this(1, "localhost", ALL_VERSIONS);
- }
-
- public MultiVersionProtocolEngineFactory(String fqdn, Set<VERSION> versions)
- {
- this(1, fqdn, versions);
- }
-
-
- public MultiVersionProtocolEngineFactory(String fqdn)
- {
- this(1, fqdn, ALL_VERSIONS);
- }
-
- public MultiVersionProtocolEngineFactory(int instance, String fqdn, Set<VERSION> supportedVersions)
- {
- _appRegistry = ApplicationRegistry.getInstance(instance);
- _fqdn = fqdn;
- _supported = supportedVersions;
- }
-
-
- public ProtocolEngine newProtocolEngine(NetworkDriver networkDriver)
- {
- return new MultiVersionProtocolEngine(_appRegistry, _fqdn, _supported, networkDriver);
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/protocol/ProtocolEngine_0_10.java b/java/broker/src/main/java/org/apache/qpid/server/protocol/ProtocolEngine_0_10.java
deleted file mode 100755
index 30d506a89b..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/protocol/ProtocolEngine_0_10.java
+++ /dev/null
@@ -1,201 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.protocol;
-
-import org.apache.qpid.protocol.ProtocolEngine;
-import org.apache.qpid.transport.NetworkDriver;
-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.server.configuration.*;
-import org.apache.qpid.server.transport.ServerConnection;
-import org.apache.qpid.server.logging.actors.CurrentActor;
-import org.apache.qpid.server.logging.messages.ConnectionMessages;
-import org.apache.qpid.server.registry.IApplicationRegistry;
-
-import java.net.SocketAddress;
-import java.util.UUID;
-
-public class ProtocolEngine_0_10 extends InputHandler implements ProtocolEngine, ConnectionConfig
-{
- public static final int MAX_FRAME_SIZE = 64 * 1024 - 1;
-
- private NetworkDriver _networkDriver;
- private long _readBytes;
- private long _writtenBytes;
- private ServerConnection _connection;
- private final UUID _id;
- private final IApplicationRegistry _appRegistry;
- private long _createTime = System.currentTimeMillis();
-
- public ProtocolEngine_0_10(ServerConnection conn,
- NetworkDriver networkDriver,
- final IApplicationRegistry appRegistry)
- {
- super(new Assembler(conn));
- _connection = conn;
- _connection.setConnectionConfig(this);
- _networkDriver = networkDriver;
- _id = appRegistry.getConfigStore().createId();
- _appRegistry = appRegistry;
-
- // FIXME Two log messages to maintain compatinbility with earlier protocol versions
- _connection.getLogActor().message(ConnectionMessages.OPEN(null, null, false, false));
- _connection.getLogActor().message(ConnectionMessages.OPEN(null, "0-10", false, true));
- }
-
- public void setNetworkDriver(NetworkDriver driver)
- {
- _networkDriver = driver;
- Disassembler dis = new Disassembler(driver, MAX_FRAME_SIZE);
- _connection.setSender(dis);
- _connection.onOpen(new Runnable()
- {
- public void run()
- {
- getConfigStore().addConfiguredObject(ProtocolEngine_0_10.this);
- }
- });
-
- }
-
- public SocketAddress getRemoteAddress()
- {
- return _networkDriver.getRemoteAddress();
- }
-
- public SocketAddress getLocalAddress()
- {
- return _networkDriver.getLocalAddress();
- }
-
- public long getReadBytes()
- {
- return _readBytes;
- }
-
- public long getWrittenBytes()
- {
- return _writtenBytes;
- }
-
- public void writerIdle()
- {
- //Todo
- }
-
- public void readerIdle()
- {
- //Todo
- }
-
- public VirtualHostConfig getVirtualHost()
- {
- return _connection.getVirtualHost();
- }
-
- public String getAddress()
- {
- return getRemoteAddress().toString();
- }
-
- public Boolean isIncoming()
- {
- return true;
- }
-
- public Boolean isSystemConnection()
- {
- return false;
- }
-
- public Boolean isFederationLink()
- {
- return false;
- }
-
- public String getAuthId()
- {
- return _connection.getAuthorizationID();
- }
-
- public String getRemoteProcessName()
- {
- return null;
- }
-
- public Integer getRemotePID()
- {
- return null;
- }
-
- public Integer getRemoteParentPID()
- {
- return null;
- }
-
- public ConfigStore getConfigStore()
- {
- return _appRegistry.getConfigStore();
- }
-
- public UUID getId()
- {
- return _id;
- }
-
- public ConnectionConfigType getConfigType()
- {
- return ConnectionConfigType.getInstance();
- }
-
- public ConfiguredObject getParent()
- {
- return getVirtualHost();
- }
-
- public boolean isDurable()
- {
- return false;
- }
-
- @Override
- public void closed()
- {
- super.closed();
- getConfigStore().removeConfiguredObject(this);
- }
-
- public long getCreateTime()
- {
- return _createTime;
- }
-
- public Boolean isShadow()
- {
- return false;
- }
-
- public void mgmtClose()
- {
- _connection.mgmtClose();
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/AMQPriorityQueue.java b/java/broker/src/main/java/org/apache/qpid/server/queue/AMQPriorityQueue.java
deleted file mode 100644
index b6e97e08fb..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/queue/AMQPriorityQueue.java
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
-*
-* Licensed to the Apache Software Foundation (ASF) under one
-* or more contributor license agreements. See the NOTICE file
-* distributed with this work for additional information
-* regarding copyright ownership. The ASF licenses this file
-* to you under the Apache License, Version 2.0 (the
-* "License"); you may not use this file except in compliance
-* with the License. You may obtain a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing,
-* software distributed under the License is distributed on an
-* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-* KIND, either express or implied. See the License for the
-* specific language governing permissions and limitations
-* under the License.
-*
-*/
-package org.apache.qpid.server.queue;
-
-import org.apache.qpid.framing.AMQShortString;
-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 class AMQPriorityQueue extends SimpleAMQQueue
-{
- protected AMQPriorityQueue(final AMQShortString name,
- final boolean durable,
- final AMQShortString owner,
- final boolean autoDelete,
- boolean exclusive,
- final VirtualHost virtualHost,
- int priorities, Map<String, Object> arguments)
- {
- super(name, durable, owner, autoDelete, exclusive, virtualHost,new PriorityQueueList.Factory(priorities), arguments);
- }
-
- public AMQPriorityQueue(String queueName,
- boolean durable,
- String owner,
- boolean autoDelete,
- boolean exclusive, VirtualHost virtualHost, int priorities, Map<String,Object> arguments)
- {
- this(queueName == null ? null : new AMQShortString(queueName), durable, owner == null ? null : new AMQShortString(owner),
- autoDelete, exclusive,virtualHost, priorities, arguments);
- }
-
- public int getPriorities()
- {
- return ((PriorityQueueList) _entries).getPriorities();
- }
-
- @Override
- protected void checkSubscriptionsNotAheadOfDelivery(final QueueEntry entry)
- {
- // check that all subscriptions are not in advance of the entry
- SubscriptionList.SubscriptionNodeIterator subIter = _subscriptionList.iterator();
- while(subIter.advance() && !entry.isAcquired())
- {
- final Subscription subscription = subIter.getNode().getSubscription();
- if(!subscription.isClosed())
- {
- QueueContext context = (QueueContext) subscription.getQueueContext();
- if(context != null)
- {
- QueueEntry subnode = context._lastSeenEntry;
- QueueEntry released = context._releasedEntry;
- while(subnode != null && entry.compareTo(subnode) < 0 && !entry.isAcquired() && (released == null || released.compareTo(entry) < 0))
- {
- if(QueueContext._releasedUpdater.compareAndSet(context,released,entry))
- {
- break;
- }
- else
- {
- subnode = context._lastSeenEntry;
- released = context._releasedEntry;
- }
- }
- }
- }
-
- }
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/AMQQueue.java b/java/broker/src/main/java/org/apache/qpid/server/queue/AMQQueue.java
deleted file mode 100644
index 9b9de8333b..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/queue/AMQQueue.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.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.exchange.Exchange;
-import org.apache.qpid.server.exchange.ExchangeReferrer;
-import org.apache.qpid.server.management.Managable;
-import org.apache.qpid.server.management.ManagedObject;
-import org.apache.qpid.server.security.PrincipalHolder;
-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;
-import java.util.Map;
-import java.util.Set;
-
-public interface AMQQueue extends Managable, Comparable<AMQQueue>, ExchangeReferrer, TransactionLogResource, BaseQueue,
- QueueConfig
-{
- boolean getDeleteOnNoConsumers();
-
- void setDeleteOnNoConsumers(boolean b);
-
- void addBinding(Binding binding);
-
- void removeBinding(Binding binding);
-
- List<Binding> getBindings();
-
- int getBindingCount();
-
- LogSubject getLogSubject();
-
- public interface Context
- {
- QueueEntry getLastSeenEntry();
- }
-
- void setNoLocal(boolean b);
-
- boolean isAutoDelete();
-
- AMQShortString getOwner();
- PrincipalHolder getPrincipalHolder();
- void setPrincipalHolder(PrincipalHolder principalHolder);
-
- void setExclusiveOwningSession(AMQSessionModel owner);
- AMQSessionModel getExclusiveOwningSession();
-
- VirtualHost getVirtualHost();
-
- void registerSubscription(final Subscription subscription, final boolean exclusive) throws AMQException;
-
- void unregisterSubscription(final Subscription subscription) throws AMQException;
-
-
- int getConsumerCount();
-
- int getActiveConsumerCount();
-
- boolean hasExclusiveSubscriber();
-
- boolean isUnused();
-
- boolean isEmpty();
-
- int getMessageCount();
-
- int getUndeliveredMessageCount();
-
-
- long getQueueDepth();
-
- long getReceivedMessageCount();
-
- long getOldestMessageArrivalTime();
-
- boolean isDeleted();
-
- int delete() throws AMQException;
-
- void requeue(QueueEntry entry);
-
- void dequeue(QueueEntry entry, Subscription sub);
-
- void decrementUnackedMsgCount();
-
- boolean resend(final QueueEntry entry, final Subscription subscription) throws AMQException;
-
- void addQueueDeleteTask(final Task task);
- void removeQueueDeleteTask(final Task task);
-
-
-
- List<QueueEntry> getMessagesOnTheQueue();
-
- List<QueueEntry> getMessagesOnTheQueue(long fromMessageId, long toMessageId);
-
- List<Long> getMessagesOnTheQueue(int num);
-
- List<Long> getMessagesOnTheQueue(int num, int offest);
-
- QueueEntry getMessageOnTheQueue(long messageId);
-
- /**
- * Returns a list of QueEntries from a given range of queue positions, eg messages 5 to 10 on the queue.
- *
- * The 'queue position' index starts from 1. Using 0 in 'from' will be ignored and continue from 1.
- * Using 0 in the 'to' field will return an empty list regardless of the 'from' value.
- * @param fromPosition
- * @param toPosition
- * @return
- */
- public List<QueueEntry> getMessagesRangeOnTheQueue(final long fromPosition, final long toPosition);
-
-
- void moveMessagesToAnotherQueue(long fromMessageId, long toMessageId, String queueName,
- ServerTransaction transaction);
-
- void copyMessagesToAnotherQueue(long fromMessageId, long toMessageId, String queueName, ServerTransaction transaction);
-
- void removeMessagesFromQueue(long fromMessageId, long toMessageId);
-
-
-
- long getMaximumMessageSize();
-
- void setMaximumMessageSize(long value);
-
-
- long getMaximumMessageCount();
-
- void setMaximumMessageCount(long value);
-
-
- long getMaximumQueueDepth();
-
- void setMaximumQueueDepth(long value);
-
-
- long getMaximumMessageAge();
-
- void setMaximumMessageAge(final long maximumMessageAge);
-
-
- long getMinimumAlertRepeatGap();
-
- void setMinimumAlertRepeatGap(long value);
-
-
- long getCapacity();
-
- void setCapacity(long capacity);
-
-
- long getFlowResumeCapacity();
-
- void setFlowResumeCapacity(long flowResumeCapacity);
-
- boolean isOverfull();
-
- void deleteMessageFromTop();
-
- long clearQueue() throws AMQException;
-
- /**
- * Checks the status of messages on the queue, purging expired ones, firing age related alerts etc.
- * @throws AMQException
- */
- void checkMessageStatus() throws AMQException;
-
- Set<NotificationCheck> getNotificationChecks();
-
- void flushSubscription(final Subscription sub) throws AMQException;
-
- void deliverAsync(final Subscription sub);
-
- void deliverAsync();
-
- void stop();
-
- boolean isExclusive();
-
- Exchange getAlternateExchange();
-
- void setAlternateExchange(Exchange exchange);
-
- Map<String, Object> getArguments();
-
- void checkCapacity(AMQChannel channel);
-
- /**
- * ExistingExclusiveSubscription signals a failure to create a subscription, because an exclusive subscription
- * already exists.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Represent failure to create a subscription, because an exclusive subscription already exists.
- * </table>
- *
- * @todo Not an AMQP exception as no status code.
- *
- * @todo Move to top level, used outside this class.
- */
- static final class ExistingExclusiveSubscription extends AMQException
- {
-
- public ExistingExclusiveSubscription()
- {
- super("");
- }
- }
-
- /**
- * ExistingSubscriptionPreventsExclusive signals a failure to create an exclusize subscription, as a subscription
- * already exists.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Represent failure to create an exclusize subscription, as a subscription already exists.
- * </table>
- *
- * @todo Not an AMQP exception as no status code.
- *
- * @todo Move to top level, used outside this class.
- */
- static final class ExistingSubscriptionPreventsExclusive extends AMQException
- {
- public ExistingSubscriptionPreventsExclusive()
- {
- super("");
- }
- }
-
- static interface Task
- {
- public void doTask(AMQQueue queue) throws AMQException;
- }
-
- void configure(ConfigurationPlugin config);
-
- ConfigurationPlugin getConfiguration();
-
- ManagedObject getManagedObject();
-
- void setExclusive(boolean exclusive) throws AMQException;
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/AMQQueueFactory.java b/java/broker/src/main/java/org/apache/qpid/server/queue/AMQQueueFactory.java
deleted file mode 100644
index bee55118ba..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/queue/AMQQueueFactory.java
+++ /dev/null
@@ -1,253 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.queue;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.AMQSecurityException;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.FieldTable;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-import org.apache.qpid.server.configuration.QueueConfiguration;
-
-import java.util.Map;
-import java.util.HashMap;
-
-public class AMQQueueFactory
-{
- public static final AMQShortString X_QPID_PRIORITIES = new AMQShortString("x-qpid-priorities");
- public static final String QPID_LVQ_KEY = "qpid.LVQ_key";
- public static final String QPID_LAST_VALUE_QUEUE = "qpid.last_value_queue";
- public static final String QPID_LAST_VALUE_QUEUE_KEY = "qpid.last_value_queue_key";
-
- private abstract static class QueueProperty
- {
-
- private final AMQShortString _argumentName;
-
-
- public QueueProperty(String argumentName)
- {
- _argumentName = new AMQShortString(argumentName);
- }
-
- public AMQShortString getArgumentName()
- {
- return _argumentName;
- }
-
-
- public abstract void setPropertyValue(AMQQueue queue, Object value);
-
- }
-
- private abstract static class QueueLongProperty extends QueueProperty
- {
-
- public QueueLongProperty(String argumentName)
- {
- super(argumentName);
- }
-
- public void setPropertyValue(AMQQueue queue, Object value)
- {
- if(value instanceof Number)
- {
- setPropertyValue(queue, ((Number)value).longValue());
- }
-
- }
-
- abstract void setPropertyValue(AMQQueue queue, long value);
-
-
- }
-
- private static final QueueProperty[] DECLAREABLE_PROPERTIES = {
- new QueueLongProperty("x-qpid-maximum-message-age")
- {
- public void setPropertyValue(AMQQueue queue, long value)
- {
- queue.setMaximumMessageAge(value);
- }
- },
- new QueueLongProperty("x-qpid-maximum-message-size")
- {
- public void setPropertyValue(AMQQueue queue, long value)
- {
- queue.setMaximumMessageSize(value);
- }
- },
- new QueueLongProperty("x-qpid-maximum-message-count")
- {
- public void setPropertyValue(AMQQueue queue, long value)
- {
- queue.setMaximumMessageCount(value);
- }
- },
- new QueueLongProperty("x-qpid-minimum-alert-repeat-gap")
- {
- public void setPropertyValue(AMQQueue queue, long value)
- {
- queue.setMinimumAlertRepeatGap(value);
- }
- },
- new QueueLongProperty("x-qpid-capacity")
- {
- public void setPropertyValue(AMQQueue queue, long value)
- {
- queue.setCapacity(value);
- }
- },
- new QueueLongProperty("x-qpid-flow-resume-capacity")
- {
- public void setPropertyValue(AMQQueue queue, long value)
- {
- queue.setFlowResumeCapacity(value);
- }
- }
-
- };
-
-
- /** @see #createAMQQueueImpl(String, boolean, String, boolean, boolean, VirtualHost, Map) */
- public static AMQQueue createAMQQueueImpl(AMQShortString name,
- boolean durable,
- AMQShortString owner,
- boolean autoDelete,
- boolean exclusive,
- VirtualHost virtualHost, final FieldTable arguments) throws AMQException
- {
- return createAMQQueueImpl(name == null ? null : name.toString(),
- durable,
- owner == null ? null : owner.toString(),
- autoDelete,
- exclusive,
- virtualHost, FieldTable.convertToMap(arguments));
- }
-
-
- public static AMQQueue createAMQQueueImpl(String queueName,
- boolean durable,
- String owner,
- boolean autoDelete,
- boolean exclusive,
- VirtualHost virtualHost, Map<String, Object> arguments) throws AMQSecurityException
- {
- // Access check
- if (!virtualHost.getSecurityManager().authoriseCreateQueue(autoDelete, durable, exclusive, null, null, new AMQShortString(queueName), owner))
- {
- String description = "Permission denied: queue-name '" + queueName + "'";
- throw new AMQSecurityException(description);
- }
-
- int priorities = 1;
- String conflationKey = null;
- if(arguments != null)
- {
- if(arguments.containsKey(QPID_LAST_VALUE_QUEUE) || arguments.containsKey(QPID_LAST_VALUE_QUEUE_KEY))
- {
- conflationKey = (String) arguments.get(QPID_LAST_VALUE_QUEUE_KEY);
- if(conflationKey == null)
- {
- conflationKey = QPID_LVQ_KEY;
- }
- }
- else if(arguments.containsKey(X_QPID_PRIORITIES.toString()))
- {
- Object prioritiesObj = arguments.get(X_QPID_PRIORITIES.toString());
- if(prioritiesObj instanceof Number)
- {
- priorities = ((Number)prioritiesObj).intValue();
- }
- }
- }
-
- AMQQueue q;
- if(conflationKey != null)
- {
- q = new ConflationQueue(queueName, durable, owner, autoDelete, exclusive, virtualHost, arguments, conflationKey);
- }
- else if(priorities > 1)
- {
- q = new AMQPriorityQueue(queueName, durable, owner, autoDelete, exclusive, virtualHost, priorities, arguments);
- }
- else
- {
- q = new SimpleAMQQueue(queueName, durable, owner, autoDelete, exclusive, virtualHost, arguments);
- }
-
- //Register the new queue
- virtualHost.getQueueRegistry().registerQueue(q);
- q.configure(virtualHost.getConfiguration().getQueueConfiguration(queueName));
-
- if(arguments != null)
- {
- for(QueueProperty p : DECLAREABLE_PROPERTIES)
- {
- if(arguments.containsKey(p.getArgumentName().toString()))
- {
- p.setPropertyValue(q, arguments.get(p.getArgumentName().toString()));
- }
- }
- }
-
- return q;
-
- }
-
-
- public static AMQQueue createAMQQueueImpl(QueueConfiguration config, VirtualHost host) throws AMQException
- {
- String queueName = config.getName();
-
- boolean durable = config.getDurable();
- boolean autodelete = config.getAutoDelete();
- boolean exclusive = config.getExclusive();
- String owner = config.getOwner();
- Map<String,Object> arguments = null;
- if(config.isLVQ() || config.getLVQKey() != null)
- {
-
- arguments = new HashMap<String,Object>();
- arguments.put(QPID_LAST_VALUE_QUEUE, 1);
- arguments.put(QPID_LAST_VALUE_QUEUE_KEY, config.getLVQKey() == null ? QPID_LVQ_KEY : config.getLVQKey());
- }
- else
- {
- boolean priority = config.getPriority();
- int priorities = config.getPriorities();
- if(priority || priorities > 0)
- {
- arguments = new HashMap<String,Object>();
- if (priorities < 0)
- {
- priorities = 10;
- }
- arguments.put("x-qpid-priorities", priorities);
- }
- }
-
- AMQQueue q = createAMQQueueImpl(queueName, durable, owner, autodelete, exclusive, host, arguments);
- q.configure(config);
- return q;
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/AMQQueueMBean.java b/java/broker/src/main/java/org/apache/qpid/server/queue/AMQQueueMBean.java
deleted file mode 100644
index c8eb118b11..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/queue/AMQQueueMBean.java
+++ /dev/null
@@ -1,647 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.queue;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.BasicContentHeaderProperties;
-import org.apache.qpid.framing.ContentHeaderBody;
-import org.apache.qpid.management.common.mbeans.ManagedQueue;
-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;
-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.MessageTransferMessage;
-import org.apache.qpid.server.txn.ServerTransaction;
-import org.apache.qpid.server.txn.LocalTransaction;
-import org.apache.qpid.transport.MessageProperties;
-
-import javax.management.JMException;
-import javax.management.MBeanException;
-import javax.management.MBeanNotificationInfo;
-import javax.management.Notification;
-import javax.management.ObjectName;
-import javax.management.OperationsException;
-import javax.management.monitor.MonitorNotification;
-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.text.SimpleDateFormat;
-import java.util.*;
-
-/**
- * AMQQueueMBean is the management bean for an {@link AMQQueue}.
- *
- * <p/><tablse id="crc"><caption>CRC Caption</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * </table>
- */
-@MBeanDescription("Management Interface for AMQQueue")
-public class AMQQueueMBean extends AMQManagedObject implements ManagedQueue, QueueNotificationListener
-{
- /** Used for debugging purposes. */
- private static final Logger _logger = Logger.getLogger(AMQQueueMBean.class);
-
- private static final SimpleDateFormat _dateFormat = new SimpleDateFormat("MM-dd-yy HH:mm:ss.SSS z");
-
- private AMQQueue _queue = null;
- private String _queueName = null;
- // OpenMBean data types for viewMessages method
-
- private static OpenType[] _msgAttributeTypes = new OpenType[5]; // AMQ message attribute types.
- private static CompositeType _messageDataType = null; // Composite type for representing AMQ Message data.
- private static TabularType _messagelistDataType = null; // Datatype for representing AMQ messages list.
-
- // OpenMBean data types for viewMessageContent method
- private static CompositeType _msgContentType = null;
- private static OpenType[] _msgContentAttributeTypes = new OpenType[4];
-
- private final long[] _lastNotificationTimes = new long[NotificationCheck.values().length];
- private Notification _lastNotification = null;
-
-
-
-
- @MBeanConstructor("Creates an MBean exposing an AMQQueue")
- public AMQQueueMBean(AMQQueue queue) throws JMException
- {
- super(ManagedQueue.class, ManagedQueue.TYPE);
- _queue = queue;
- _queueName = queue.getName();
- }
-
- public ManagedObject getParentObject()
- {
- return _queue.getVirtualHost().getManagedObject();
- }
-
- static
- {
- try
- {
- init();
- }
- catch (JMException ex)
- {
- // This is not expected to ever occur.
- throw new RuntimeException("Got JMException in static initializer.", ex);
- }
- }
-
- /**
- * initialises the openmbean data types
- */
- private static void init() throws OpenDataException
- {
- _msgContentAttributeTypes[0] = SimpleType.LONG; // For message id
- _msgContentAttributeTypes[1] = SimpleType.STRING; // For MimeType
- _msgContentAttributeTypes[2] = SimpleType.STRING; // For Encoding
- _msgContentAttributeTypes[3] = new ArrayType(1, SimpleType.BYTE); // For message content
- _msgContentType = new CompositeType("Message Content", "AMQ Message Content",
- VIEW_MSG_CONTENT_COMPOSITE_ITEM_NAMES_DESC.toArray(new String[VIEW_MSG_CONTENT_COMPOSITE_ITEM_NAMES_DESC.size()]),
- VIEW_MSG_CONTENT_COMPOSITE_ITEM_NAMES_DESC.toArray(new String[VIEW_MSG_CONTENT_COMPOSITE_ITEM_NAMES_DESC.size()]),
- _msgContentAttributeTypes);
-
- _msgAttributeTypes[0] = SimpleType.LONG; // For message id
- _msgAttributeTypes[1] = new ArrayType(1, SimpleType.STRING); // For header attributes
- _msgAttributeTypes[2] = SimpleType.LONG; // For size
- _msgAttributeTypes[3] = SimpleType.BOOLEAN; // For redelivered
- _msgAttributeTypes[4] = SimpleType.LONG; // For queue position
-
- _messageDataType = new CompositeType("Message", "AMQ Message",
- VIEW_MSGS_COMPOSITE_ITEM_NAMES_DESC.toArray(new String[VIEW_MSGS_COMPOSITE_ITEM_NAMES_DESC.size()]),
- VIEW_MSGS_COMPOSITE_ITEM_NAMES_DESC.toArray(new String[VIEW_MSGS_COMPOSITE_ITEM_NAMES_DESC.size()]), _msgAttributeTypes);
- _messagelistDataType = new TabularType("Messages", "List of messages", _messageDataType,
- VIEW_MSGS_TABULAR_UNIQUE_INDEX.toArray(new String[VIEW_MSGS_TABULAR_UNIQUE_INDEX.size()]));
- }
-
- public String getObjectInstanceName()
- {
- return ObjectName.quote(_queueName);
- }
-
- public String getName()
- {
- return _queueName;
- }
-
- public boolean isDurable()
- {
- return _queue.isDurable();
- }
-
- public String getOwner()
- {
- return String.valueOf(_queue.getOwner());
- }
-
- public boolean isAutoDelete()
- {
- return _queue.isAutoDelete();
- }
-
- public Integer getMessageCount()
- {
- return _queue.getMessageCount();
- }
-
- public Long getMaximumMessageSize()
- {
- return _queue.getMaximumMessageSize();
- }
-
- public Long getMaximumMessageAge()
- {
- return _queue.getMaximumMessageAge();
- }
-
- public void setMaximumMessageAge(Long maximumMessageAge)
- {
- _queue.setMaximumMessageAge(maximumMessageAge);
- }
-
- public void setMaximumMessageSize(Long value)
- {
- _queue.setMaximumMessageSize(value);
- }
-
- public Integer getConsumerCount()
- {
- return _queue.getConsumerCount();
- }
-
- public Integer getActiveConsumerCount()
- {
- return _queue.getActiveConsumerCount();
- }
-
- public Long getReceivedMessageCount()
- {
- return _queue.getReceivedMessageCount();
- }
-
- public Long getMaximumMessageCount()
- {
- return _queue.getMaximumMessageCount();
- }
-
- public void setMaximumMessageCount(Long value)
- {
- _queue.setMaximumMessageCount(value);
- }
-
- /**
- * returns the maximum total size of messages(bytes) in the queue.
- */
- public Long getMaximumQueueDepth()
- {
- return _queue.getMaximumQueueDepth();
- }
-
- public void setMaximumQueueDepth(Long value)
- {
- _queue.setMaximumQueueDepth(value);
- }
-
- /**
- * returns the total size of messages(bytes) in the queue.
- */
- public Long getQueueDepth() throws JMException
- {
- return _queue.getQueueDepth();
- }
-
- public Long getCapacity()
- {
- return _queue.getCapacity();
- }
-
- public void setCapacity(Long capacity) throws IllegalArgumentException
- {
- if( _queue.getFlowResumeCapacity() > capacity )
- {
- throw new IllegalArgumentException("Capacity must not be less than FlowResumeCapacity");
- }
-
- _queue.setCapacity(capacity);
- }
-
- public Long getFlowResumeCapacity()
- {
- return _queue.getFlowResumeCapacity();
- }
-
- public void setFlowResumeCapacity(Long flowResumeCapacity) throws IllegalArgumentException
- {
- if( _queue.getCapacity() < flowResumeCapacity )
- {
- throw new IllegalArgumentException("FlowResumeCapacity must not exceed Capacity");
- }
-
- _queue.setFlowResumeCapacity(flowResumeCapacity);
- }
-
- public boolean isFlowOverfull()
- {
- return _queue.isOverfull();
- }
-
- public boolean isExclusive()
- {
- return _queue.isExclusive();
- }
-
- public void setExclusive(boolean exclusive) throws JMException
- {
- try
- {
- _queue.setExclusive(exclusive);
- }
- catch (AMQException e)
- {
- throw new JMException(e.toString());
- }
- }
-
- /**
- * Checks if there is any notification to be send to the listeners
- */
- public void checkForNotification(ServerMessage msg) throws AMQException
- {
-
- final Set<NotificationCheck> notificationChecks = _queue.getNotificationChecks();
-
- if(!notificationChecks.isEmpty())
- {
- final long currentTime = System.currentTimeMillis();
- final long thresholdTime = currentTime - _queue.getMinimumAlertRepeatGap();
-
- for (NotificationCheck check : notificationChecks)
- {
- if (check.isMessageSpecific() || (_lastNotificationTimes[check.ordinal()] < thresholdTime))
- {
- if (check.notifyIfNecessary(msg, _queue, this))
- {
- _lastNotificationTimes[check.ordinal()] = currentTime;
- }
- }
- }
- }
-
- }
-
- /**
- * Sends the notification to the listeners
- */
- 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);
- notificationMsg = notification.name() + " " + notificationMsg;
-
- _lastNotification =
- new Notification(MonitorNotification.THRESHOLD_VALUE_EXCEEDED, this, ++_notificationSequenceNumber,
- System.currentTimeMillis(), notificationMsg);
-
- _broadcaster.sendNotification(_lastNotification);
- }
-
- public Notification getLastNotification()
- {
- return _lastNotification;
- }
-
- /**
- * @see AMQQueue#deleteMessageFromTop
- */
- public void deleteMessageFromTop() throws JMException
- {
- _queue.deleteMessageFromTop();
- }
-
- /**
- * Clears the queue of non-acquired messages
- *
- * @return the number of messages deleted
- * @see AMQQueue#clearQueue
- */
- public Long clearQueue() throws JMException
- {
- try
- {
- return _queue.clearQueue();
- }
- catch (AMQException ex)
- {
- throw new MBeanException(ex, "Error clearing queue " + _queueName);
- }
- }
-
- /**
- * returns message content as byte array and related attributes for the given message id.
- */
- public CompositeData viewMessageContent(long msgId) throws JMException
- {
- QueueEntry entry = _queue.getMessageOnTheQueue(msgId);
-
- if (entry == null)
- {
- throw new OperationsException("AMQMessage with message id = " + msgId + " is not in the " + _queueName);
- }
-
- ServerMessage serverMsg = entry.getMessage();
- final int bodySize = (int) serverMsg.getSize();
-
-
- List<Byte> msgContent = new ArrayList<Byte>();
-
- java.nio.ByteBuffer buf = java.nio.ByteBuffer.allocate(bodySize);
- int position = 0;
-
- while(position < bodySize)
- {
- position += serverMsg.getContent(buf, position);
- buf.flip();
- for(int i = 0; i < buf.limit(); i++)
- {
- msgContent.add(buf.get(i));
- }
- buf.clear();
- }
-
- AMQMessageHeader header = serverMsg.getMessageHeader();
-
- String mimeType = null, encoding = null;
- if (header != null)
- {
- mimeType = header.getMimeType();
-
- encoding = header.getEncoding();
- }
-
-
- Object[] itemValues = { msgId, mimeType, encoding, msgContent.toArray(new Byte[0]) };
-
- return new CompositeDataSupport(_msgContentType,
- VIEW_MSG_CONTENT_COMPOSITE_ITEM_NAMES_DESC.toArray(
- new String[VIEW_MSG_CONTENT_COMPOSITE_ITEM_NAMES_DESC.size()]), itemValues);
-
- }
-
- /**
- * Returns the header contents of the messages stored in this queue in tabular form.
- * Deprecated as of Qpid JMX API 1.3
- */
- @Deprecated
- public TabularData viewMessages(int beginIndex, int endIndex) throws JMException
- {
- return viewMessages((long)beginIndex,(long)endIndex);
- }
-
-
- /**
- * Returns the header contents of the messages stored in this queue in tabular form.
- * @param startPosition The queue position of the first message to be viewed
- * @param endPosition The queue position of the last message to be viewed
- */
- public TabularData viewMessages(long startPosition, long endPosition) throws JMException
- {
- if ((startPosition > endPosition) || (startPosition < 1))
- {
- throw new OperationsException("From Index = " + startPosition + ", To Index = " + endPosition
- + "\n\"From Index\" should be greater than 0 and less than \"To Index\"");
- }
-
- if ((endPosition - startPosition) > Integer.MAX_VALUE)
- {
- throw new OperationsException("Specified MessageID interval is too large. Intervals must be less than 2^31 in size");
- }
-
- List<QueueEntry> list = _queue.getMessagesRangeOnTheQueue(startPosition,endPosition);
- TabularDataSupport _messageList = new TabularDataSupport(_messagelistDataType);
-
- try
- {
- // Create the tabular list of message header contents
- int size = list.size();
-
- for (int i = 0; i < size ; i++)
- {
- long position = startPosition + i;
- final QueueEntry queueEntry = list.get(i);
- ServerMessage serverMsg = queueEntry.getMessage();
-
- String[] headerAttributes = null;
- Object[] itemValues = null;
-
- if(serverMsg instanceof AMQMessage)
- {
- AMQMessage msg = (AMQMessage) serverMsg;
- ContentHeaderBody headerBody = msg.getContentHeaderBody();
- // Create header attributes list
- headerAttributes = getMessageHeaderProperties(headerBody);
- itemValues = new Object[]{msg.getMessageId(), headerAttributes, headerBody.bodySize, queueEntry.isRedelivered(), position};
- }
- else if(serverMsg instanceof MessageTransferMessage)
- {
- // We have a 0-10 message
- MessageTransferMessage msg = (MessageTransferMessage) serverMsg;
-
- // Create header attributes list
- headerAttributes = getMessageTransferMessageHeaderProps(msg);
- itemValues = new Object[]{msg.getMessageNumber(), headerAttributes, msg.getSize(), queueEntry.isRedelivered(), position};
- }
- else
- {
- //unknown message
- headerAttributes = new String[]{"N/A"};
- itemValues = new Object[]{serverMsg.getMessageNumber(), headerAttributes, serverMsg.getSize(), queueEntry.isRedelivered(), position};
- }
-
- CompositeData messageData = new CompositeDataSupport(_messageDataType,
- VIEW_MSGS_COMPOSITE_ITEM_NAMES_DESC.toArray(new String[VIEW_MSGS_COMPOSITE_ITEM_NAMES_DESC.size()]), itemValues);
- _messageList.put(messageData);
- }
- }
- catch (AMQException e)
- {
- JMException jme = new JMException("Error creating message contents: " + e);
- jme.initCause(e);
- throw jme;
- }
-
- return _messageList;
- }
-
- private String[] getMessageHeaderProperties(ContentHeaderBody headerBody)
- {
- List<String> list = new ArrayList<String>();
- BasicContentHeaderProperties headerProperties = (BasicContentHeaderProperties) headerBody.getProperties();
- list.add("reply-to = " + headerProperties.getReplyToAsString());
- list.add("propertyFlags = " + headerProperties.getPropertyFlags());
- list.add("ApplicationID = " + headerProperties.getAppIdAsString());
- list.add("ClusterID = " + headerProperties.getClusterIdAsString());
- list.add("UserId = " + headerProperties.getUserIdAsString());
- list.add("JMSMessageID = " + headerProperties.getMessageIdAsString());
- list.add("JMSCorrelationID = " + headerProperties.getCorrelationIdAsString());
-
- int delMode = headerProperties.getDeliveryMode();
- list.add("JMSDeliveryMode = " +
- ((delMode == BasicContentHeaderProperties.PERSISTENT) ? "Persistent" : "Non_Persistent"));
-
- list.add("JMSPriority = " + headerProperties.getPriority());
- list.add("JMSType = " + headerProperties.getType());
-
- long longDate = headerProperties.getExpiration();
- String strDate = (longDate != 0) ? _dateFormat.format(new Date(longDate)) : null;
- list.add("JMSExpiration = " + strDate);
-
- longDate = headerProperties.getTimestamp();
- strDate = (longDate != 0) ? _dateFormat.format(new Date(longDate)) : null;
- list.add("JMSTimestamp = " + strDate);
-
- return list.toArray(new String[list.size()]);
- }
-
- private String[] getMessageTransferMessageHeaderProps(MessageTransferMessage msg)
- {
- List<String> list = new ArrayList<String>();
-
- AMQMessageHeader header = msg.getMessageHeader();
- MessageProperties msgProps = msg.getHeader().get(MessageProperties.class);
-
- String appID = null;
- String userID = null;
-
- if(msgProps != null)
- {
- appID = msgProps.getAppId() == null ? "null" : new String(msgProps.getAppId());
- userID = msgProps.getUserId() == null ? "null" : new String(msgProps.getUserId());
- }
-
- list.add("reply-to = " + header.getReplyTo());
- list.add("propertyFlags = "); //TODO
- list.add("ApplicationID = " + appID);
- list.add("ClusterID = "); //TODO
- list.add("UserId = " + userID);
- list.add("JMSMessageID = " + header.getMessageId());
- list.add("JMSCorrelationID = " + header.getCorrelationId());
- list.add("JMSDeliveryMode = " + (msg.isPersistent() ? "Persistent" : "Non_Persistent"));
- list.add("JMSPriority = " + header.getPriority());
- list.add("JMSType = " + header.getType());
-
- long longDate = header.getExpiration();
- String strDate = (longDate != 0) ? _dateFormat.format(new Date(longDate)) : null;
- list.add("JMSExpiration = " + strDate);
-
- longDate = header.getTimestamp();
- strDate = (longDate != 0) ? _dateFormat.format(new Date(longDate)) : null;
- list.add("JMSTimestamp = " + strDate);
-
- return list.toArray(new String[list.size()]);
- }
-
- /**
- * @see ManagedQueue#moveMessages
- * @param fromMessageId
- * @param toMessageId
- * @param toQueueName
- * @throws JMException
- */
- public void moveMessages(long fromMessageId, long toMessageId, String toQueueName) throws JMException
- {
- if ((fromMessageId > toMessageId) || (fromMessageId < 1))
- {
- throw new OperationsException("\"From MessageId\" should be greater than 0 and less than \"To MessageId\"");
- }
-
- ServerTransaction txn = new LocalTransaction(_queue.getVirtualHost().getTransactionLog());
- _queue.moveMessagesToAnotherQueue(fromMessageId, toMessageId, toQueueName, txn);
- txn.commit();
- }
-
- /**
- * @see ManagedQueue#deleteMessages
- * @param fromMessageId
- * @param toMessageId
- * @throws JMException
- */
- public void deleteMessages(long fromMessageId, long toMessageId) throws JMException
- {
- if ((fromMessageId > toMessageId) || (fromMessageId < 1))
- {
- throw new OperationsException("\"From MessageId\" should be greater than 0 and less than \"To MessageId\"");
- }
-
- _queue.removeMessagesFromQueue(fromMessageId, toMessageId);
- }
-
- /**
- * @see ManagedQueue#copyMessages
- * @param fromMessageId
- * @param toMessageId
- * @param toQueueName
- * @throws JMException
- */
- public void copyMessages(long fromMessageId, long toMessageId, String toQueueName) throws JMException
- {
- if ((fromMessageId > toMessageId) || (fromMessageId < 1))
- {
- throw new OperationsException("\"From MessageId\" should be greater than 0 and less than \"To MessageId\"");
- }
-
- ServerTransaction txn = new LocalTransaction(_queue.getVirtualHost().getTransactionLog());
-
- _queue.copyMessagesToAnotherQueue(fromMessageId, toMessageId, toQueueName, txn);
-
- txn.commit();
-
-
- }
-
- /**
- * returns Notifications sent by this MBean.
- */
- @Override
- public MBeanNotificationInfo[] getNotificationInfo()
- {
- String[] notificationTypes = new String[] { MonitorNotification.THRESHOLD_VALUE_EXCEEDED };
- String name = MonitorNotification.class.getName();
- String description = "Either Message count or Queue depth or Message size has reached threshold high value";
- MBeanNotificationInfo info1 = new MBeanNotificationInfo(notificationTypes, name, description);
-
- return new MBeanNotificationInfo[] { info1 };
- }
-
-} // End of AMQQueueMBean class
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/BaseQueue.java b/java/broker/src/main/java/org/apache/qpid/server/queue/BaseQueue.java
deleted file mode 100644
index 05e0efd9a6..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/queue/BaseQueue.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.qpid.server.queue;
-
-import org.apache.qpid.server.message.ServerMessage;
-import org.apache.qpid.server.store.TransactionLogResource;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.AMQShortString;
-
-public interface BaseQueue extends TransactionLogResource
-{
- public static interface PostEnqueueAction
- {
- public void onEnqueue(QueueEntry entry);
- }
-
- void enqueue(ServerMessage message) throws AMQException;
- void enqueue(ServerMessage message, PostEnqueueAction action) throws AMQException;
-
- boolean isDurable();
-
- AMQShortString getNameShortString();
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/ConflationQueue.java b/java/broker/src/main/java/org/apache/qpid/server/queue/ConflationQueue.java
deleted file mode 100644
index b5293f51be..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/queue/ConflationQueue.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.qpid.server.queue;
-
-import org.apache.qpid.server.virtualhost.VirtualHost;
-
-import java.util.Map;
-
-public class ConflationQueue extends SimpleAMQQueue
-{
- protected ConflationQueue(String name,
- boolean durable,
- String owner,
- boolean autoDelete,
- boolean exclusive,
- VirtualHost virtualHost,
- Map<String, Object> args,
- String conflationKey)
- {
- super(name, durable, owner, autoDelete, exclusive, virtualHost, new ConflationQueueList.Factory(conflationKey), args);
- }
-
- public String getConflationKey()
- {
- return ((ConflationQueueList) _entries).getConflationKey();
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/ConflationQueueList.java b/java/broker/src/main/java/org/apache/qpid/server/queue/ConflationQueueList.java
deleted file mode 100644
index 2c1883e763..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/queue/ConflationQueueList.java
+++ /dev/null
@@ -1,167 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.qpid.server.queue;
-
-import java.util.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;
-
-public class ConflationQueueList extends SimpleQueueEntryList
-{
-
- private final String _conflationKey;
- private final ConcurrentHashMap<Object, AtomicReference<QueueEntry>> _latestValuesMap =
- new ConcurrentHashMap<Object, AtomicReference<QueueEntry>>();
-
- public ConflationQueueList(AMQQueue queue, String conflationKey)
- {
- super(queue);
- _conflationKey = conflationKey;
- }
-
- public String getConflationKey()
- {
- return _conflationKey;
- }
-
- @Override
- protected ConflationQueueEntry createQueueEntry(ServerMessage message)
- {
- return new ConflationQueueEntry(this, message);
- }
-
-
- @Override
- public QueueEntry add(final ServerMessage message)
- {
- ConflationQueueEntry entry = (ConflationQueueEntry) (super.add(message));
- AtomicReference<QueueEntry> latestValueReference = null;
-
- Object value = message.getMessageHeader().getHeader(_conflationKey);
- if(value != null)
- {
- latestValueReference = _latestValuesMap.get(value);
- if(latestValueReference == null)
- {
- _latestValuesMap.putIfAbsent(value, new AtomicReference<QueueEntry>(entry));
- latestValueReference = _latestValuesMap.get(value);
- }
- QueueEntry oldEntry;
-
- do
- {
- oldEntry = latestValueReference.get();
- }
- while(oldEntry.compareTo(entry) < 0 && !latestValueReference.compareAndSet(oldEntry, entry));
-
- if(oldEntry.compareTo(entry) < 0)
- {
- // We replaced some other entry to become the newest value
- if(oldEntry.acquire())
- {
- discardEntry(oldEntry);
- }
- }
- else if (oldEntry.compareTo(entry) > 0)
- {
- // A newer entry came along
- discardEntry(entry);
-
- }
- }
-
- entry.setLatestValueReference(latestValueReference);
- return entry;
- }
-
- private void discardEntry(final QueueEntry entry)
- {
- if(entry.acquire())
- {
- ServerTransaction txn = new AutoCommitTransaction(getQueue().getVirtualHost().getTransactionLog());
- txn.dequeue(entry.getQueue(),entry.getMessage(),
- new ServerTransaction.Action()
- {
- public void postCommit()
- {
- entry.discard();
- }
-
- public void onRollback()
- {
-
- }
- });
- }
- }
-
- private final class ConflationQueueEntry extends QueueEntryImpl
- {
-
-
- private AtomicReference<QueueEntry> _latestValueReference;
-
- public ConflationQueueEntry(SimpleQueueEntryList queueEntryList, ServerMessage message)
- {
- super(queueEntryList, message);
- }
-
-
- public void release()
- {
- super.release();
-
- if(_latestValueReference != null)
- {
- if(_latestValueReference.get() != this)
- {
- discardEntry(this);
- }
- }
-
- }
-
- public void setLatestValueReference(final AtomicReference<QueueEntry> latestValueReference)
- {
- _latestValueReference = latestValueReference;
- }
- }
-
- static class Factory implements QueueEntryListFactory
- {
- private final String _conflationKey;
-
- Factory(String conflationKey)
- {
- _conflationKey = conflationKey;
- }
-
- public QueueEntryList createQueueEntryList(AMQQueue queue)
- {
- return new ConflationQueueList(queue, _conflationKey);
- }
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/DefaultQueueRegistry.java b/java/broker/src/main/java/org/apache/qpid/server/queue/DefaultQueueRegistry.java
deleted file mode 100644
index d76487073d..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/queue/DefaultQueueRegistry.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.queue;
-
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-
-import java.util.Collection;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-
-public class DefaultQueueRegistry implements QueueRegistry
-{
- private ConcurrentMap<AMQShortString, AMQQueue> _queueMap = new ConcurrentHashMap<AMQShortString, AMQQueue>();
-
- private final VirtualHost _virtualHost;
-
- public DefaultQueueRegistry(VirtualHost virtualHost)
- {
- _virtualHost = virtualHost;
- }
-
- public VirtualHost getVirtualHost()
- {
- return _virtualHost;
- }
-
- public void registerQueue(AMQQueue queue)
- {
- _queueMap.put(queue.getNameShortString(), queue);
- }
-
- public void unregisterQueue(AMQShortString name)
- {
- _queueMap.remove(name);
- }
-
- public AMQQueue getQueue(AMQShortString name)
- {
- return _queueMap.get(name);
- }
-
- public Collection<AMQShortString> getQueueNames()
- {
- return _queueMap.keySet();
- }
-
- public Collection<AMQQueue> getQueues()
- {
- return _queueMap.values();
- }
-
- public AMQQueue getQueue(String queue)
- {
- return getQueue(new AMQShortString(queue));
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/FailedDequeueException.java b/java/broker/src/main/java/org/apache/qpid/server/queue/FailedDequeueException.java
deleted file mode 100644
index 6466e81dd2..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/queue/FailedDequeueException.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.queue;
-
-import org.apache.qpid.AMQException;
-
-/**
- * Signals that the dequeue of a message from a queue failed.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Indicates the a message could not be dequeued from a queue.
- * <tr><td>
- * </table>
- *
- * @todo Not an AMQP exception as no status code.
- *
- * @todo Happens as a consequence of a message store failure, or reference counting error. Both of which migh become
- * runtime exceptions, as unrecoverable conditions? In which case this one might be dropped too.
- */
-public class FailedDequeueException extends AMQException
-{
- public FailedDequeueException(String queue)
- {
- super("Failed to dequeue message from " + queue);
- }
-
- public FailedDequeueException(String queue, AMQException e)
- {
- super("Failed to dequeue message from " + queue, e);
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/Filterable.java b/java/broker/src/main/java/org/apache/qpid/server/queue/Filterable.java
deleted file mode 100644
index eaa3992e98..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/queue/Filterable.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
-*
-* Licensed to the Apache Software Foundation (ASF) under one
-* or more contributor license agreements. See the NOTICE file
-* distributed with this work for additional information
-* regarding copyright ownership. The ASF licenses this file
-* to you under the Apache License, Version 2.0 (the
-* "License"); you may not use this file except in compliance
-* with the License. You may obtain a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing,
-* software distributed under the License is distributed on an
-* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-* KIND, either express or implied. See the License for the
-* specific language governing permissions and limitations
-* under the License.
-*
-*/
-package org.apache.qpid.server.queue;
-
-import org.apache.qpid.framing.ContentHeaderBody;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.server.message.AMQMessageHeader;
-
-public interface Filterable
-{
- AMQMessageHeader getMessageHeader();
-
- boolean isPersistent();
-
- boolean isRedelivered();
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/InboundMessageAdapter.java b/java/broker/src/main/java/org/apache/qpid/server/queue/InboundMessageAdapter.java
deleted file mode 100755
index 77da08d8c4..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/queue/InboundMessageAdapter.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.qpid.server.queue;
-
-import org.apache.qpid.server.message.InboundMessage;
-import org.apache.qpid.server.message.AMQMessageHeader;
-
-class InboundMessageAdapter implements InboundMessage
-{
-
- private QueueEntry _entry;
-
- InboundMessageAdapter()
- {
- }
-
- InboundMessageAdapter(QueueEntry entry)
- {
- _entry = entry;
- }
-
- public void setEntry(QueueEntry entry)
- {
- _entry = entry;
- }
-
-
- public String getRoutingKey()
- {
- return _entry.getMessage().getRoutingKey();
- }
-
- public AMQMessageHeader getMessageHeader()
- {
- return _entry.getMessageHeader();
- }
-
- public boolean isPersistent()
- {
- return _entry.isPersistent();
- }
-
- public boolean isRedelivered()
- {
- return _entry.isRedelivered();
- }
-
- public long getSize()
- {
- return _entry.getSize();
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/IncomingMessage.java b/java/broker/src/main/java/org/apache/qpid/server/queue/IncomingMessage.java
deleted file mode 100644
index 3e3288404f..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/queue/IncomingMessage.java
+++ /dev/null
@@ -1,300 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.queue;
-
-import org.apache.qpid.framing.abstraction.MessagePublishInfo;
-import org.apache.qpid.framing.abstraction.ContentChunk;
-import org.apache.qpid.framing.ContentHeaderBody;
-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.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.MessageContentSource;
-import org.apache.qpid.server.message.MessageMetaData;
-import org.apache.qpid.AMQException;
-import org.apache.log4j.Logger;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.nio.ByteBuffer;
-
-public class IncomingMessage implements Filterable, InboundMessage, EnqueableMessage, MessageContentSource
-{
-
- /** Used for debugging purposes. */
- private static final Logger _logger = Logger.getLogger(IncomingMessage.class);
-
- private static final boolean SYNCHED_CLOCKS =
- ApplicationRegistry.getInstance().getConfiguration().getSynchedClocks();
-
- private final MessagePublishInfo _messagePublishInfo;
- private ContentHeaderBody _contentHeaderBody;
-
-
- /**
- * Keeps a track of how many bytes we have received in body frames
- */
- private long _bodyLengthReceived = 0;
-
- /**
- * This is stored during routing, to know the queues to which this message should immediately be
- * delivered. It is <b>cleared after delivery has been attempted</b>. Any persistent record of destinations is done
- * by the message handle.
- */
- private ArrayList<? extends BaseQueue> _destinationQueues;
-
- private long _expiration;
-
- private Exchange _exchange;
-
-
- private int _receivedChunkCount = 0;
- private List<ContentChunk> _contentChunks = new ArrayList<ContentChunk>();
-
- // we keep both the original meta data object and the store reference to it just in case the
- // store would otherwise flow it to disk
-
- private MessageMetaData _messageMetaData;
-
- private StoredMessage<MessageMetaData> _storedMessageHandle;
-
-
- public IncomingMessage(
- final MessagePublishInfo info
- )
- {
- _messagePublishInfo = info;
- }
-
- public void setContentHeaderBody(final ContentHeaderBody contentHeaderBody) throws AMQException
- {
- _contentHeaderBody = contentHeaderBody;
- }
-
- public void setExpiration()
- {
- long expiration =
- ((BasicContentHeaderProperties) _contentHeaderBody.getProperties()).getExpiration();
- long timestamp =
- ((BasicContentHeaderProperties) _contentHeaderBody.getProperties()).getTimestamp();
-
- if (SYNCHED_CLOCKS)
- {
- _expiration = expiration;
- }
- else
- {
- // Update TTL to be in broker time.
- if (expiration != 0L)
- {
- if (timestamp != 0L)
- {
- // todo perhaps use arrival time
- long diff = (System.currentTimeMillis() - timestamp);
-
- if ((diff > 1000L) || (diff < 1000L))
- {
- _expiration = expiration + diff;
- }
- }
- }
- }
-
- }
-
- public MessageMetaData headersReceived()
- {
- _messageMetaData = new MessageMetaData(_messagePublishInfo, _contentHeaderBody, 0);
- return _messageMetaData;
- }
-
-
- public ArrayList<? extends BaseQueue> getDestinationQueues()
- {
- return _destinationQueues;
- }
-
- public int addContentBodyFrame(final ContentChunk contentChunk)
- throws AMQException
- {
- _storedMessageHandle.addContent((int)_bodyLengthReceived, contentChunk.getData().buf());
- _bodyLengthReceived += contentChunk.getSize();
- _contentChunks.add(contentChunk);
-
-
-
- return _receivedChunkCount++;
- }
-
- public boolean allContentReceived()
- {
- return (_bodyLengthReceived == getContentHeader().bodySize);
- }
-
- public AMQShortString getExchange()
- {
- return _messagePublishInfo.getExchange();
- }
-
- public String getRoutingKey()
- {
- return _messagePublishInfo.getRoutingKey() == null ? null : _messagePublishInfo.getRoutingKey().toString();
- }
-
- public String getBinding()
- {
- return _messagePublishInfo.getRoutingKey() == null ? null : _messagePublishInfo.getRoutingKey().toString();
- }
-
-
- public boolean isMandatory()
- {
- return _messagePublishInfo.isMandatory();
- }
-
-
- public boolean isImmediate()
- {
- return _messagePublishInfo.isImmediate();
- }
-
- public ContentHeaderBody getContentHeader()
- {
- return _contentHeaderBody;
- }
-
-
- public AMQMessageHeader getMessageHeader()
- {
- return _messageMetaData.getMessageHeader();
- }
-
- public boolean isPersistent()
- {
- return getContentHeader().getProperties() instanceof BasicContentHeaderProperties &&
- ((BasicContentHeaderProperties) getContentHeader().getProperties()).getDeliveryMode() ==
- BasicContentHeaderProperties.PERSISTENT;
- }
-
- public boolean isRedelivered()
- {
- return false;
- }
-
-
- public long getSize()
- {
- return getContentHeader().bodySize;
- }
-
- public Long getMessageNumber()
- {
- return _storedMessageHandle.getMessageNumber();
- }
-
- public void setExchange(final Exchange e)
- {
- _exchange = e;
- }
-
- public void route()
- {
- enqueue(_exchange.route(this));
-
- }
-
- public void enqueue(final ArrayList<? extends BaseQueue> queues)
- {
- _destinationQueues = queues;
- }
-
- public MessagePublishInfo getMessagePublishInfo()
- {
- return _messagePublishInfo;
- }
-
- public long getExpiration()
- {
- return _expiration;
- }
-
- public int getReceivedChunkCount()
- {
- return _receivedChunkCount;
- }
-
-
- public int getBodyCount() throws AMQException
- {
- return _contentChunks.size();
- }
-
- public ContentChunk getContentChunk(int index) throws IllegalArgumentException, AMQException
- {
- return _contentChunks.get(index);
- }
-
-
- public int getContent(ByteBuffer buf, int offset)
- {
- int pos = 0;
- int written = 0;
- for(ContentChunk cb : _contentChunks)
- {
- ByteBuffer data = cb.getData().buf();
- if(offset+written >= pos && offset < pos + data.limit())
- {
- ByteBuffer src = data.duplicate();
- src.position(offset+written - pos);
- src = src.slice();
-
- if(buf.remaining() < src.limit())
- {
- src.limit(buf.remaining());
- }
- int count = src.limit();
- buf.put(src);
- written += count;
- if(buf.remaining() == 0)
- {
- break;
- }
- }
- pos+=data.limit();
- }
- return written;
-
- }
-
- public void setStoredMessage(StoredMessage<MessageMetaData> storedMessageHandle)
- {
- _storedMessageHandle = storedMessageHandle;
- }
-
- public StoredMessage<MessageMetaData> getStoredMessage()
- {
- return _storedMessageHandle;
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/MessageCleanupException.java b/java/broker/src/main/java/org/apache/qpid/server/queue/MessageCleanupException.java
deleted file mode 100644
index 090096d3c3..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/queue/MessageCleanupException.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.queue;
-
-import org.apache.qpid.AMQException;
-
-/**
- * MessageCleanupException represents the failure to perform reference counting on messages correctly. This should not
- * happen, but there may be programming errors giving race conditions that cause the reference counting to go wrong.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Signals that the reference count of a message has gone below zero.
- * <tr><td> Indicates that a message store has lost a message which is still referenced.
- * </table>
- *
- * @todo Not an AMQP exception as no status code.
- *
- * @todo The race conditions leading to this error should be cleaned up, and a runtime exception used instead. If the
- * message store loses messages, then something is seriously wrong and it would be sensible to terminate the
- * broker. This may be disguising out of memory errors.
- */
-public class MessageCleanupException extends AMQException
-{
- public MessageCleanupException(long messageId, AMQException e)
- {
- super("Failed to cleanup message with id " + messageId, e);
- }
-
- public MessageCleanupException(String message)
- {
- super(message);
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/NotificationCheck.java b/java/broker/src/main/java/org/apache/qpid/server/queue/NotificationCheck.java
deleted file mode 100644
index d1fb0f3fe6..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/queue/NotificationCheck.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.server.queue;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.server.message.ServerMessage;
-
-public enum NotificationCheck
-{
-
- MESSAGE_COUNT_ALERT
- {
- boolean notifyIfNecessary(ServerMessage msg, AMQQueue queue, QueueNotificationListener listener)
- {
- int msgCount;
- final long maximumMessageCount = queue.getMaximumMessageCount();
- if (maximumMessageCount!= 0 && (msgCount = queue.getMessageCount()) >= maximumMessageCount)
- {
- listener.notifyClients(this, queue, msgCount + ": Maximum count on queue threshold ("+ maximumMessageCount +") breached.");
- return true;
- }
- return false;
- }
- },
- MESSAGE_SIZE_ALERT(true)
- {
- boolean notifyIfNecessary(ServerMessage msg, AMQQueue queue, QueueNotificationListener listener)
- {
- final long maximumMessageSize = queue.getMaximumMessageSize();
- if(maximumMessageSize != 0)
- {
- // Check for threshold message size
- long messageSize;
- messageSize = (msg == null) ? 0 : msg.getSize();
-
-
- if (messageSize >= maximumMessageSize)
- {
- listener.notifyClients(this, queue, messageSize + "b : Maximum message size threshold ("+ maximumMessageSize +") breached. [Message ID=" + msg.getMessageNumber() + "]");
- return true;
- }
- }
- return false;
- }
-
- },
- QUEUE_DEPTH_ALERT
- {
- boolean notifyIfNecessary(ServerMessage msg, AMQQueue queue, QueueNotificationListener listener)
- {
- // Check for threshold queue depth in bytes
- final long maximumQueueDepth = queue.getMaximumQueueDepth();
-
- if(maximumQueueDepth != 0)
- {
- final long queueDepth = queue.getQueueDepth();
-
- if (queueDepth >= maximumQueueDepth)
- {
- listener.notifyClients(this, queue, (queueDepth>>10) + "Kb : Maximum queue depth threshold ("+(maximumQueueDepth>>10)+"Kb) breached.");
- return true;
- }
- }
- return false;
- }
-
- },
- MESSAGE_AGE_ALERT
- {
- boolean notifyIfNecessary(ServerMessage msg, AMQQueue queue, QueueNotificationListener listener)
- {
-
- final long maxMessageAge = queue.getMaximumMessageAge();
- if(maxMessageAge != 0)
- {
- final long currentTime = System.currentTimeMillis();
- final long thresholdTime = currentTime - maxMessageAge;
- final long firstArrivalTime = queue.getOldestMessageArrivalTime();
-
- if(firstArrivalTime < thresholdTime)
- {
- long oldestAge = currentTime - firstArrivalTime;
- listener.notifyClients(this, queue, (oldestAge/1000) + "s : Maximum age on queue threshold ("+(maxMessageAge /1000)+"s) breached.");
-
- return true;
- }
- }
- return false;
-
- }
-
- }
- ;
-
- private final boolean _messageSpecific;
-
- NotificationCheck()
- {
- this(false);
- }
-
- NotificationCheck(boolean messageSpecific)
- {
- _messageSpecific = messageSpecific;
- }
-
- public boolean isMessageSpecific()
- {
- return _messageSpecific;
- }
-
- abstract boolean notifyIfNecessary(ServerMessage msg, AMQQueue queue, QueueNotificationListener listener);
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/PriorityQueueList.java b/java/broker/src/main/java/org/apache/qpid/server/queue/PriorityQueueList.java
deleted file mode 100644
index 0c6b84d2b6..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/queue/PriorityQueueList.java
+++ /dev/null
@@ -1,162 +0,0 @@
-/*
-*
-* Licensed to the Apache Software Foundation (ASF) under one
-* or more contributor license agreements. See the NOTICE file
-* distributed with this work for additional information
-* regarding copyright ownership. The ASF licenses this file
-* to you under the Apache License, Version 2.0 (the
-* "License"); you may not use this file except in compliance
-* with the License. You may obtain a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing,
-* software distributed under the License is distributed on an
-* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-* KIND, either express or implied. See the License for the
-* specific language governing permissions and limitations
-* under the License.
-*
-*/
-package org.apache.qpid.server.queue;
-
-import org.apache.qpid.framing.CommonContentHeaderProperties;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.server.message.ServerMessage;
-
-public class PriorityQueueList implements QueueEntryList
-{
- private final AMQQueue _queue;
- private final QueueEntryList[] _priorityLists;
- private final int _priorities;
- private final int _priorityOffset;
-
- public PriorityQueueList(AMQQueue queue, int priorities)
- {
- _queue = queue;
- _priorityLists = new QueueEntryList[priorities];
- _priorities = priorities;
- _priorityOffset = 5-((priorities + 1)/2);
- for(int i = 0; i < priorities; i++)
- {
- _priorityLists[i] = new SimpleQueueEntryList(queue);
- }
- }
-
- public int getPriorities()
- {
- return _priorities;
- }
-
- public AMQQueue getQueue()
- {
- return _queue;
- }
-
- public QueueEntry add(ServerMessage message)
- {
- int index = message.getMessageHeader().getPriority() - _priorityOffset;
- if(index >= _priorities)
- {
- index = _priorities-1;
- }
- else if(index < 0)
- {
- index = 0;
- }
- return _priorityLists[index].add(message);
-
- }
-
- public QueueEntry next(QueueEntry node)
- {
- QueueEntryImpl nodeImpl = (QueueEntryImpl)node;
- QueueEntry next = nodeImpl.getNext();
-
- if(next == null)
- {
- QueueEntryList nodeEntryList = nodeImpl.getQueueEntryList();
- int index;
- for(index = _priorityLists.length-1; _priorityLists[index] != nodeEntryList; index--);
-
- while(next == null && index != 0)
- {
- index--;
- next = ((QueueEntryImpl)_priorityLists[index].getHead()).getNext();
- }
-
- }
- return next;
- }
-
- private final class PriorityQueueEntryListIterator implements QueueEntryIterator
- {
- private final QueueEntryIterator[] _iterators = new QueueEntryIterator[ _priorityLists.length ];
- private QueueEntry _lastNode;
-
- PriorityQueueEntryListIterator()
- {
- for(int i = 0; i < _priorityLists.length; i++)
- {
- _iterators[i] = _priorityLists[i].iterator();
- }
- _lastNode = _iterators[_iterators.length - 1].getNode();
- }
-
-
- public boolean atTail()
- {
- for(int i = 0; i < _iterators.length; i++)
- {
- if(!_iterators[i].atTail())
- {
- return false;
- }
- }
- return true;
- }
-
- public QueueEntry getNode()
- {
- return _lastNode;
- }
-
- public boolean advance()
- {
- for(int i = _iterators.length-1; i >= 0; i--)
- {
- if(_iterators[i].advance())
- {
- _lastNode = _iterators[i].getNode();
- return true;
- }
- }
- return false;
- }
- }
-
- public QueueEntryIterator iterator()
- {
- return new PriorityQueueEntryListIterator();
- }
-
- public QueueEntry getHead()
- {
- return _priorityLists[_priorities-1].getHead();
- }
-
- static class Factory implements QueueEntryListFactory
- {
- private final int _priorities;
-
- Factory(int priorities)
- {
- _priorities = priorities;
- }
-
- public QueueEntryList createQueueEntryList(AMQQueue queue)
- {
- return new PriorityQueueList(queue, _priorities);
- }
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/QueueContext.java b/java/broker/src/main/java/org/apache/qpid/server/queue/QueueContext.java
deleted file mode 100755
index 825a85a89c..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/queue/QueueContext.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.qpid.server.queue;
-
-import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
-
-final class QueueContext implements AMQQueue.Context
-{
- volatile QueueEntry _lastSeenEntry;
- volatile QueueEntry _releasedEntry;
-
- static final AtomicReferenceFieldUpdater<QueueContext, QueueEntry>
- _lastSeenUpdater =
- AtomicReferenceFieldUpdater.newUpdater
- (QueueContext.class, QueueEntry.class, "_lastSeenEntry");
- static final AtomicReferenceFieldUpdater<QueueContext, QueueEntry>
- _releasedUpdater =
- AtomicReferenceFieldUpdater.newUpdater
- (QueueContext.class, QueueEntry.class, "_releasedEntry");
-
- public QueueContext(QueueEntry head)
- {
- _lastSeenEntry = head;
- }
-
- public QueueEntry getLastSeenEntry()
- {
- return _lastSeenEntry;
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/QueueEntry.java b/java/broker/src/main/java/org/apache/qpid/server/queue/QueueEntry.java
deleted file mode 100644
index 79ede2694e..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/queue/QueueEntry.java
+++ /dev/null
@@ -1,210 +0,0 @@
-package org.apache.qpid.server.queue;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.server.subscription.Subscription;
-import org.apache.qpid.server.message.ServerMessage;
-
-/*
-*
-* 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 interface QueueEntry extends Comparable<QueueEntry>, Filterable
-{
-
-
-
- public static enum State
- {
- AVAILABLE,
- ACQUIRED,
- EXPIRED,
- DEQUEUED,
- DELETED;
-
-
- }
-
- public static interface StateChangeListener
- {
- public void stateChanged(QueueEntry entry, State oldSate, State newState);
- }
-
- public abstract class EntryState
- {
- private EntryState()
- {
- }
-
- public abstract State getState();
- }
-
-
- public final class AvailableState extends EntryState
- {
-
- public State getState()
- {
- return State.AVAILABLE;
- }
- }
-
-
- public final class DequeuedState extends EntryState
- {
-
- public State getState()
- {
- return State.DEQUEUED;
- }
- }
-
-
- public final class DeletedState extends EntryState
- {
-
- public State getState()
- {
- return State.DELETED;
- }
- }
-
- public final class ExpiredState extends EntryState
- {
-
- public State getState()
- {
- return State.EXPIRED;
- }
- }
-
-
- public final class NonSubscriptionAcquiredState extends EntryState
- {
- public State getState()
- {
- return State.ACQUIRED;
- }
- }
-
- public final class SubscriptionAcquiredState extends EntryState
- {
- private final Subscription _subscription;
-
- public SubscriptionAcquiredState(Subscription subscription)
- {
- _subscription = subscription;
- }
-
-
- public State getState()
- {
- return State.ACQUIRED;
- }
-
- public Subscription getSubscription()
- {
- return _subscription;
- }
- }
-
- public final class SubscriptionAssignedState extends EntryState
- {
- private final Subscription _subscription;
-
- public SubscriptionAssignedState(Subscription subscription)
- {
- _subscription = subscription;
- }
-
-
- public State getState()
- {
- return State.AVAILABLE;
- }
-
- public Subscription getSubscription()
- {
- return _subscription;
- }
- }
-
-
- final static EntryState AVAILABLE_STATE = new AvailableState();
- final static EntryState DELETED_STATE = new DeletedState();
- final static EntryState DEQUEUED_STATE = new DequeuedState();
- final static EntryState EXPIRED_STATE = new ExpiredState();
- final static EntryState NON_SUBSCRIPTION_ACQUIRED_STATE = new NonSubscriptionAcquiredState();
-
-
-
-
- AMQQueue getQueue();
-
- ServerMessage getMessage();
-
- long getSize();
-
- boolean getDeliveredToConsumer();
-
- boolean expired() throws AMQException;
-
- boolean isAvailable();
-
- boolean isAcquired();
-
- boolean acquire();
- boolean acquire(Subscription sub);
-
- boolean delete();
- boolean isDeleted();
-
- boolean acquiredBySubscription();
- boolean isAcquiredBy(Subscription subscription);
-
- void release();
- boolean releaseButRetain();
-
-
- boolean immediateAndNotDelivered();
-
- void setRedelivered();
-
- boolean isRedelivered();
-
- Subscription getDeliveredSubscription();
-
- void reject();
-
- void reject(Subscription subscription);
-
- boolean isRejectedBy(Subscription subscription);
-
- void dequeue();
-
- void dispose();
-
- void discard();
-
- void routeToAlternate();
-
- boolean isQueueDeleted();
-
- void addStateChangeListener(StateChangeListener listener);
- boolean removeStateChangeListener(StateChangeListener listener);
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/QueueEntryImpl.java b/java/broker/src/main/java/org/apache/qpid/server/queue/QueueEntryImpl.java
deleted file mode 100644
index 809ba3277e..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/queue/QueueEntryImpl.java
+++ /dev/null
@@ -1,550 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.queue;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.server.exchange.Exchange;
-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.ServerTransaction;
-
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.concurrent.CopyOnWriteArraySet;
-import java.util.concurrent.atomic.AtomicLongFieldUpdater;
-import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
-
-
-public class QueueEntryImpl implements QueueEntry
-{
-
- /**
- * Used for debugging purposes.
- */
- private static final Logger _log = Logger.getLogger(QueueEntryImpl.class);
-
- private final SimpleQueueEntryList _queueEntryList;
-
- private MessageReference _message;
-
- private Set<Subscription> _rejectedBy = null;
-
- private volatile EntryState _state = AVAILABLE_STATE;
-
- private static final
- AtomicReferenceFieldUpdater<QueueEntryImpl, EntryState>
- _stateUpdater =
- AtomicReferenceFieldUpdater.newUpdater
- (QueueEntryImpl.class, EntryState.class, "_state");
-
-
- private volatile Set<StateChangeListener> _stateChangeListeners;
-
- private static final
- AtomicReferenceFieldUpdater<QueueEntryImpl, Set>
- _listenersUpdater =
- AtomicReferenceFieldUpdater.newUpdater
- (QueueEntryImpl.class, Set.class, "_stateChangeListeners");
-
-
- private static final
- AtomicLongFieldUpdater<QueueEntryImpl>
- _entryIdUpdater =
- AtomicLongFieldUpdater.newUpdater
- (QueueEntryImpl.class, "_entryId");
-
-
- private volatile long _entryId;
-
- volatile QueueEntryImpl _next;
-
- private static final int DELIVERED_TO_CONSUMER = 1;
- private static final int REDELIVERED = 2;
-
- private volatile int _deliveryState;
-
-
- QueueEntryImpl(SimpleQueueEntryList queueEntryList)
- {
- this(queueEntryList,null,Long.MIN_VALUE);
- _state = DELETED_STATE;
- }
-
-
- public QueueEntryImpl(SimpleQueueEntryList queueEntryList, ServerMessage message, final long entryId)
- {
- _queueEntryList = queueEntryList;
-
- _message = message == null ? null : message.newReference();
-
- _entryIdUpdater.set(this, entryId);
- }
-
- public QueueEntryImpl(SimpleQueueEntryList queueEntryList, ServerMessage message)
- {
- _queueEntryList = queueEntryList;
- _message = message == null ? null : message.newReference();
- }
-
- protected void setEntryId(long entryId)
- {
- _entryIdUpdater.set(this, entryId);
- }
-
- protected long getEntryId()
- {
- return _entryId;
- }
-
- public AMQQueue getQueue()
- {
- return _queueEntryList.getQueue();
- }
-
- public ServerMessage getMessage()
- {
- return _message == null ? null : _message.getMessage();
- }
-
- public long getSize()
- {
- return getMessage() == null ? 0 : getMessage().getSize();
- }
-
- public boolean getDeliveredToConsumer()
- {
- return (_deliveryState & DELIVERED_TO_CONSUMER) != 0;
- }
-
- public boolean expired() throws AMQException
- {
- ServerMessage message = getMessage();
- if(message != null)
- {
- long expiration = message.getExpiration();
- if (expiration != 0L)
- {
- long now = System.currentTimeMillis();
-
- return (now > expiration);
- }
- }
- return false;
-
- }
-
- public boolean isAvailable()
- {
- return _state == AVAILABLE_STATE;
- }
-
- public boolean isAcquired()
- {
- return _state.getState() == State.ACQUIRED;
- }
-
- public boolean acquire()
- {
- return acquire(NON_SUBSCRIPTION_ACQUIRED_STATE);
- }
-
- private boolean acquire(final EntryState state)
- {
- boolean acquired = _stateUpdater.compareAndSet(this,AVAILABLE_STATE, state);
-
- // deal with the case where the node has been assigned to a given subscription already
- // including the case that the node is assigned to a closed subscription
- if(!acquired)
- {
- if(state != NON_SUBSCRIPTION_ACQUIRED_STATE)
- {
- EntryState currentState = _state;
- if(currentState.getState() == State.AVAILABLE
- && ((currentState == AVAILABLE_STATE)
- || (((SubscriptionAcquiredState)state).getSubscription() ==
- ((SubscriptionAssignedState)currentState).getSubscription())
- || ((SubscriptionAssignedState)currentState).getSubscription().isClosed() ))
- {
- acquired = _stateUpdater.compareAndSet(this,currentState, state);
- }
- }
- }
- if(acquired && _stateChangeListeners != null)
- {
- notifyStateChange(State.AVAILABLE, State.ACQUIRED);
- }
-
- return acquired;
- }
-
- public boolean acquire(Subscription sub)
- {
- final boolean acquired = acquire(sub.getOwningState());
- if(acquired)
- {
- _deliveryState |= DELIVERED_TO_CONSUMER;
- }
- return acquired;
- }
-
- public boolean acquiredBySubscription()
- {
-
- return (_state instanceof SubscriptionAcquiredState);
- }
-
- public boolean isAcquiredBy(Subscription subscription)
- {
- EntryState state = _state;
- return state instanceof SubscriptionAcquiredState
- && ((SubscriptionAcquiredState)state).getSubscription() == subscription;
- }
-
- public void release()
- {
- EntryState state = _state;
-
- if((state.getState() == State.ACQUIRED) &&_stateUpdater.compareAndSet(this, state, AVAILABLE_STATE))
- {
- if(state instanceof SubscriptionAcquiredState)
- {
- getQueue().decrementUnackedMsgCount();
- }
-
- if(!getQueue().isDeleted())
- {
- getQueue().requeue(this);
- if(_stateChangeListeners != null)
- {
- notifyStateChange(QueueEntry.State.ACQUIRED, QueueEntry.State.AVAILABLE);
- }
-
- }
- else if(acquire())
- {
- routeToAlternate();
- }
- }
- }
-
- public boolean releaseButRetain()
- {
- EntryState state = _state;
-
- boolean stateUpdated = false;
-
- if(state instanceof SubscriptionAcquiredState)
- {
- Subscription sub = ((SubscriptionAcquiredState) state).getSubscription();
- if(_stateUpdater.compareAndSet(this, state, sub.getAssignedState()))
- {
- System.err.println("Message released (and retained)" + getMessage().getMessageNumber());
- getQueue().requeue(this);
- if(_stateChangeListeners != null)
- {
- notifyStateChange(QueueEntry.State.ACQUIRED, QueueEntry.State.AVAILABLE);
- }
- stateUpdated = true;
- }
- }
-
- return stateUpdated;
-
- }
-
- public boolean immediateAndNotDelivered()
- {
- return !getDeliveredToConsumer() && isImmediate();
- }
-
- private boolean isImmediate()
- {
- final ServerMessage message = getMessage();
- return message != null && message.isImmediate();
- }
-
- public void setRedelivered()
- {
- _deliveryState |= REDELIVERED;
- }
-
- public AMQMessageHeader getMessageHeader()
- {
- final ServerMessage message = getMessage();
- return message == null ? null : message.getMessageHeader();
- }
-
- public boolean isPersistent()
- {
- final ServerMessage message = getMessage();
- return message != null && message.isPersistent();
- }
-
- public boolean isRedelivered()
- {
- return (_deliveryState & REDELIVERED) != 0;
- }
-
- public Subscription getDeliveredSubscription()
- {
- EntryState state = _state;
- if (state instanceof SubscriptionAcquiredState)
- {
- return ((SubscriptionAcquiredState) state).getSubscription();
- }
- else
- {
- return null;
- }
-
- }
-
- public void reject()
- {
- reject(getDeliveredSubscription());
- }
-
- public void reject(Subscription subscription)
- {
- if (subscription != null)
- {
- if (_rejectedBy == null)
- {
- _rejectedBy = new HashSet<Subscription>();
- }
-
- _rejectedBy.add(subscription);
- }
- else
- {
- _log.warn("Requesting rejection by null subscriber:" + this);
- }
- }
-
- public boolean isRejectedBy(Subscription subscription)
- {
-
- if (_rejectedBy != null) // We have subscriptions that rejected this message
- {
- return _rejectedBy.contains(subscription);
- }
- else // This messasge hasn't been rejected yet.
- {
- return false;
- }
- }
-
- public void dequeue()
- {
- EntryState state = _state;
-
- if((state.getState() == State.ACQUIRED) &&_stateUpdater.compareAndSet(this, state, DEQUEUED_STATE))
- {
- Subscription s = null;
- if (state instanceof SubscriptionAcquiredState)
- {
- getQueue().decrementUnackedMsgCount();
- s = ((SubscriptionAcquiredState) state).getSubscription();
- s.onDequeue(this);
- }
-
- getQueue().dequeue(this,s);
- if(_stateChangeListeners != null)
- {
- notifyStateChange(state.getState() , QueueEntry.State.DEQUEUED);
- }
-
- }
-
- }
-
- private void notifyStateChange(final State oldState, final State newState)
- {
- for(StateChangeListener l : _stateChangeListeners)
- {
- l.stateChanged(this, oldState, newState);
- }
- }
-
- public void dispose()
- {
- if(delete())
- {
- _message.release();
- }
- }
-
- public void discard()
- {
- //if the queue is null then the message is waiting to be acked, but has been removed.
- if (getQueue() != null)
- {
- dequeue();
- }
-
- dispose();
- }
-
- public void routeToAlternate()
- {
- final AMQQueue currentQueue = getQueue();
- Exchange alternateExchange = currentQueue.getAlternateExchange();
-
- if(alternateExchange != null)
- {
- final List<? extends BaseQueue> rerouteQueues = alternateExchange.route(new InboundMessageAdapter(this));
- final ServerMessage message = getMessage();
- if(rerouteQueues != null && rerouteQueues.size() != 0)
- {
- ServerTransaction txn = new AutoCommitTransaction(getQueue().getVirtualHost().getTransactionLog());
-
- txn.enqueue(rerouteQueues, message, new ServerTransaction.Action() {
- public void postCommit()
- {
- try
- {
- for(BaseQueue queue : rerouteQueues)
- {
- queue.enqueue(message);
- }
- }
- catch (AMQException e)
- {
- throw new RuntimeException(e);
- }
- }
-
- public void onRollback()
- {
-
- }
- });
- txn.dequeue(currentQueue,message,
- new ServerTransaction.Action()
- {
- public void postCommit()
- {
- discard();
- }
-
- public void onRollback()
- {
-
- }
- });
- }
- }
- }
-
- public boolean isQueueDeleted()
- {
- return getQueue().isDeleted();
- }
-
- public void addStateChangeListener(StateChangeListener listener)
- {
- Set<StateChangeListener> listeners = _stateChangeListeners;
- if(listeners == null)
- {
- _listenersUpdater.compareAndSet(this, null, new CopyOnWriteArraySet<StateChangeListener>());
- listeners = _stateChangeListeners;
- }
-
- listeners.add(listener);
- }
-
- public boolean removeStateChangeListener(StateChangeListener listener)
- {
- Set<StateChangeListener> listeners = _stateChangeListeners;
- if(listeners != null)
- {
- return listeners.remove(listener);
- }
-
- return false;
- }
-
-
- public int compareTo(final QueueEntry o)
- {
- QueueEntryImpl other = (QueueEntryImpl)o;
- return getEntryId() > other.getEntryId() ? 1 : getEntryId() < other.getEntryId() ? -1 : 0;
- }
-
- public QueueEntryImpl getNext()
- {
-
- QueueEntryImpl next = nextNode();
- while(next != null && next.isDeleted())
- {
-
- final QueueEntryImpl newNext = next.nextNode();
- if(newNext != null)
- {
- SimpleQueueEntryList._nextUpdater.compareAndSet(this,next, newNext);
- next = nextNode();
- }
- else
- {
- next = null;
- }
-
- }
- return next;
- }
-
- QueueEntryImpl nextNode()
- {
- return _next;
- }
-
- public boolean isDeleted()
- {
- return _state == DELETED_STATE;
- }
-
- public boolean delete()
- {
- EntryState state = _state;
-
- if(state != DELETED_STATE && _stateUpdater.compareAndSet(this,state,DELETED_STATE))
- {
- _queueEntryList.advanceHead();
- return true;
- }
- else
- {
- return false;
- }
- }
-
- public QueueEntryList getQueueEntryList()
- {
- return _queueEntryList;
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/QueueEntryIterator.java b/java/broker/src/main/java/org/apache/qpid/server/queue/QueueEntryIterator.java
deleted file mode 100644
index c5c115a2d1..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/queue/QueueEntryIterator.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.
-*
-*/
-package org.apache.qpid.server.queue;
-
-public interface QueueEntryIterator
-{
- boolean atTail();
-
- QueueEntry getNode();
-
- boolean advance();
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/QueueEntryList.java b/java/broker/src/main/java/org/apache/qpid/server/queue/QueueEntryList.java
deleted file mode 100644
index b4042ce02c..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/queue/QueueEntryList.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.queue;
-
-import org.apache.qpid.server.message.ServerMessage;
-
-public interface QueueEntryList
-{
- AMQQueue getQueue();
-
- QueueEntry add(ServerMessage message);
-
- QueueEntry next(QueueEntry node);
-
- QueueEntryIterator iterator();
-
- QueueEntry getHead();
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/QueueEntryListFactory.java b/java/broker/src/main/java/org/apache/qpid/server/queue/QueueEntryListFactory.java
deleted file mode 100644
index 4dbce45f67..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/queue/QueueEntryListFactory.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
-*
-* Licensed to the Apache Software Foundation (ASF) under one
-* or more contributor license agreements. See the NOTICE file
-* distributed with this work for additional information
-* regarding copyright ownership. The ASF licenses this file
-* to you under the Apache License, Version 2.0 (the
-* "License"); you may not use this file except in compliance
-* with the License. You may obtain a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing,
-* software distributed under the License is distributed on an
-* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-* KIND, either express or implied. See the License for the
-* specific language governing permissions and limitations
-* under the License.
-*
-*/
-package org.apache.qpid.server.queue;
-
-interface QueueEntryListFactory
-{
- public QueueEntryList createQueueEntryList(AMQQueue queue);
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/QueueNotificationListener.java b/java/broker/src/main/java/org/apache/qpid/server/queue/QueueNotificationListener.java
deleted file mode 100644
index 959ca03c80..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/queue/QueueNotificationListener.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.queue;
-
-
-public interface QueueNotificationListener
-{
- void notifyClients(NotificationCheck notification, AMQQueue queue, String notificationMsg);
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/QueueRegistry.java b/java/broker/src/main/java/org/apache/qpid/server/queue/QueueRegistry.java
deleted file mode 100644
index a537e0c83f..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/queue/QueueRegistry.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.queue;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-
-import java.util.Collection;
-
-public interface QueueRegistry
-{
- VirtualHost getVirtualHost();
-
- void registerQueue(AMQQueue queue);
-
- void unregisterQueue(AMQShortString name);
-
- AMQQueue getQueue(AMQShortString name);
-
- Collection<AMQShortString> getQueueNames();
-
- Collection<AMQQueue> getQueues();
-
- AMQQueue getQueue(String queue);
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/QueueRunner.java b/java/broker/src/main/java/org/apache/qpid/server/queue/QueueRunner.java
deleted file mode 100644
index 7e1d57e205..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/queue/QueueRunner.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.queue;
-
-import org.apache.log4j.Logger;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.pool.ReadWriteRunnable;
-import org.apache.qpid.server.logging.actors.CurrentActor;
-import org.apache.qpid.server.queue.QueueRunner;
-import org.apache.qpid.server.queue.SimpleAMQQueue;
-
-/**
- * QueueRunners are Runnables used to process a queue when requiring
- * asynchronous message delivery to subscriptions, which is necessary
- * when straight-through delivery of a message to a subscription isn't
- * possible during the enqueue operation.
- */
-public class QueueRunner implements ReadWriteRunnable
-{
- private static final Logger _logger = Logger.getLogger(QueueRunner.class);
-
- private final String _name;
- private final SimpleAMQQueue _queue;
-
- public QueueRunner(SimpleAMQQueue queue, long count)
- {
- _queue = queue;
- _name = "QueueRunner-" + count + "-" + queue.getLogActor();
- }
-
- public void run()
- {
- String originalName = Thread.currentThread().getName();
- try
- {
- Thread.currentThread().setName(_name);
- CurrentActor.set(_queue.getLogActor());
-
- _queue.processQueue(this);
- }
- catch (AMQException e)
- {
- _logger.error("Exception during asynchronous delivery by " + _name, e);
- }
- finally
- {
- CurrentActor.remove();
- Thread.currentThread().setName(originalName);
- }
- }
-
- public boolean isRead()
- {
- return false;
- }
-
- public boolean isWrite()
- {
- return true;
- }
-
- public String toString()
- {
- return _name;
- }
-} \ No newline at end of file
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/SimpleAMQQueue.java b/java/broker/src/main/java/org/apache/qpid/server/queue/SimpleAMQQueue.java
deleted file mode 100644
index b02d03a1ad..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/queue/SimpleAMQQueue.java
+++ /dev/null
@@ -1,2233 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.qpid.server.queue;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.AMQSecurityException;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.pool.ReadWriteRunnable;
-import org.apache.qpid.pool.ReferenceCountingExecutorService;
-import org.apache.qpid.server.AMQChannel;
-import org.apache.qpid.server.configuration.plugins.ConfigurationPlugin;
-import org.apache.qpid.server.protocol.AMQSessionModel;
-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.QueueConfiguration;
-import org.apache.qpid.server.configuration.SessionConfig;
-import org.apache.qpid.server.exchange.Exchange;
-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.QueueActor;
-import org.apache.qpid.server.logging.messages.QueueMessages;
-import org.apache.qpid.server.logging.subjects.QueueLogSubject;
-import org.apache.qpid.server.management.ManagedObject;
-import org.apache.qpid.server.message.ServerMessage;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-import org.apache.qpid.server.security.PrincipalHolder;
-import org.apache.qpid.server.subscription.Subscription;
-import org.apache.qpid.server.subscription.SubscriptionList;
-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 javax.management.JMException;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.EnumSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.UUID;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-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 java.util.concurrent.atomic.AtomicReference;
-
-public class SimpleAMQQueue implements AMQQueue, Subscription.StateListener
-{
- private static final Logger _logger = Logger.getLogger(SimpleAMQQueue.class);
-
-
- private final VirtualHost _virtualHost;
-
- private final AMQShortString _name;
- private final String _resourceName;
-
- /** null means shared */
- private final AMQShortString _owner;
-
- private PrincipalHolder _prinicpalHolder;
-
- private boolean _exclusive = false;
- private AMQSessionModel _exclusiveOwner;
-
-
- private final boolean _durable;
-
- /** If true, this queue is deleted when the last subscriber is removed */
- private final boolean _autoDelete;
-
- private Exchange _alternateExchange;
-
- /** Used to track bindings to exchanges so that on deletion they can easily be cancelled. */
-
-
-
- protected final QueueEntryList _entries;
-
- protected final SubscriptionList _subscriptionList = new SubscriptionList(this);
-
- private final AtomicReference<SubscriptionList.SubscriptionNode> _lastSubscriptionNode = new AtomicReference<SubscriptionList.SubscriptionNode>(_subscriptionList.getHead());
-
- private volatile Subscription _exclusiveSubscriber;
-
-
-
- private final AtomicInteger _atomicQueueCount = new AtomicInteger(0);
-
- private final AtomicLong _atomicQueueSize = new AtomicLong(0L);
-
- private final AtomicInteger _activeSubscriberCount = new AtomicInteger();
-
- private final AtomicLong _totalMessagesReceived = new AtomicLong();
-
- private final AtomicLong _dequeueCount = new AtomicLong();
- private final AtomicLong _dequeueSize = new AtomicLong();
- private final AtomicLong _enqueueSize = new AtomicLong();
- private final AtomicLong _persistentMessageEnqueueSize = new AtomicLong();
- private final AtomicLong _persistentMessageDequeueSize = new AtomicLong();
- private final AtomicLong _persistentMessageEnqueueCount = new AtomicLong();
- private final AtomicLong _persistentMessageDequeueCount = new AtomicLong();
- private final AtomicInteger _counsumerCountHigh = new AtomicInteger(0);
- private final AtomicLong _msgTxnEnqueues = new AtomicLong(0);
- private final AtomicLong _byteTxnEnqueues = new AtomicLong(0);
- private final AtomicLong _msgTxnDequeues = new AtomicLong(0);
- private final AtomicLong _byteTxnDequeues = new AtomicLong(0);
- private final AtomicLong _unackedMsgCount = new AtomicLong(0);
- private final AtomicLong _unackedMsgCountHigh = new AtomicLong(0);
-
- private final AtomicInteger _bindingCountHigh = new AtomicInteger();
-
- /** max allowed size(KB) of a single message */
- public long _maximumMessageSize = ApplicationRegistry.getInstance().getConfiguration().getMaximumMessageSize();
-
- /** max allowed number of messages on a queue. */
- public long _maximumMessageCount = ApplicationRegistry.getInstance().getConfiguration().getMaximumMessageCount();
-
- /** max queue depth for the queue */
- public long _maximumQueueDepth = ApplicationRegistry.getInstance().getConfiguration().getMaximumQueueDepth();
-
- /** maximum message age before alerts occur */
- public 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 _capacity = ApplicationRegistry.getInstance().getConfiguration().getCapacity();
-
- private long _flowResumeCapacity = ApplicationRegistry.getInstance().getConfiguration().getFlowResumeCapacity();
-
- private final Set<NotificationCheck> _notificationChecks = EnumSet.noneOf(NotificationCheck.class);
-
-
- static final int MAX_ASYNC_DELIVERIES = 10;
-
-
- private final AtomicLong _stateChangeCount = new AtomicLong(Long.MIN_VALUE);
- private AtomicReference<Runnable> _asynchronousRunner = new AtomicReference<Runnable>(null);
- private final Executor _asyncDelivery;
- private AtomicInteger _deliveredMessages = new AtomicInteger();
- private AtomicBoolean _stopped = new AtomicBoolean(false);
-
- private final ConcurrentMap<AMQChannel, Boolean> _blockedChannels = new ConcurrentHashMap<AMQChannel, Boolean>();
-
- private final AtomicBoolean _deleted = new AtomicBoolean(false);
- private final List<Task> _deleteTaskList = new CopyOnWriteArrayList<Task>();
-
-
- private LogSubject _logSubject;
- private LogActor _logActor;
-
- private AMQQueueMBean _managedObject;
- private static final String SUB_FLUSH_RUNNER = "SUB_FLUSH_RUNNER";
- private boolean _nolocal;
-
- private final AtomicBoolean _overfull = new AtomicBoolean(false);
- private boolean _deleteOnNoConsumers;
- private final CopyOnWriteArrayList<Binding> _bindings = new CopyOnWriteArrayList<Binding>();
- private UUID _id;
- private final Map<String, Object> _arguments;
-
- //TODO : persist creation time
- private long _createTime = System.currentTimeMillis();
- private ConfigurationPlugin _queueConfiguration;
-
-
-
- protected SimpleAMQQueue(AMQShortString name, boolean durable, AMQShortString owner, boolean autoDelete, boolean exclusive, VirtualHost virtualHost, Map<String,Object> arguments)
- {
- this(name, durable, owner, autoDelete, exclusive, virtualHost,new SimpleQueueEntryList.Factory(), arguments);
- }
-
- public SimpleAMQQueue(String queueName, boolean durable, String owner, boolean autoDelete, boolean exclusive, VirtualHost virtualHost, Map<String, Object> arguments)
- {
- this(queueName, durable, owner, autoDelete, exclusive, virtualHost, new SimpleQueueEntryList.Factory(), arguments);
- }
-
- public SimpleAMQQueue(String queueName, boolean durable, String owner, boolean autoDelete, boolean exclusive, VirtualHost virtualHost, QueueEntryListFactory entryListFactory, Map<String, Object> arguments)
- {
- this(queueName == null ? null : new AMQShortString(queueName), durable, owner == null ? null : new AMQShortString(owner), autoDelete, exclusive, virtualHost, entryListFactory, arguments);
- }
-
- protected SimpleAMQQueue(AMQShortString name,
- boolean durable,
- AMQShortString owner,
- boolean autoDelete,
- boolean exclusive,
- VirtualHost virtualHost,
- QueueEntryListFactory entryListFactory,
- Map<String,Object> arguments)
- {
-
- if (name == null)
- {
- throw new IllegalArgumentException("Queue name must not be null");
- }
-
- if (virtualHost == null)
- {
- throw new IllegalArgumentException("Virtual Host must not be null");
- }
-
- _name = name;
- _resourceName = String.valueOf(name);
- _durable = durable;
- _owner = owner;
- _autoDelete = autoDelete;
- _exclusive = exclusive;
- _virtualHost = virtualHost;
- _entries = entryListFactory.createQueueEntryList(this);
- _arguments = arguments;
-
- _id = virtualHost.getConfigStore().createId();
-
- _asyncDelivery = ReferenceCountingExecutorService.getInstance().acquireExecutorService();
-
- _logSubject = new QueueLogSubject(this);
- _logActor = new QueueActor(this, CurrentActor.get().getRootMessageLogger());
-
- // Log the correct creation message
-
- // Extract the number of priorities for this Queue.
- // Leave it as 0 if we are a SimpleQueueEntryList
- int priorities = 0;
- if (entryListFactory instanceof PriorityQueueList.Factory)
- {
- priorities = ((PriorityQueueList)_entries).getPriorities();
- }
-
- // Log the creation of this Queue.
- // The priorities display is toggled on if we set priorities > 0
- CurrentActor.get().message(_logSubject,
- QueueMessages.CREATED(String.valueOf(_owner),
- priorities,
- _owner != null,
- autoDelete,
- durable, !durable,
- priorities > 0));
-
- getConfigStore().addConfiguredObject(this);
-
- try
- {
- _managedObject = new AMQQueueMBean(this);
- _managedObject.register();
- }
- catch (JMException e)
- {
- _logger.error("AMQQueue MBean creation has failed ", e);
- }
-
- resetNotifications();
-
- }
-
- public void resetNotifications()
- {
- // This ensure that the notification checks for the configured alerts are created.
- setMaximumMessageAge(_maximumMessageAge);
- setMaximumMessageCount(_maximumMessageCount);
- setMaximumMessageSize(_maximumMessageSize);
- setMaximumQueueDepth(_maximumQueueDepth);
- }
-
- // ------ Getters and Setters
-
- public void execute(ReadWriteRunnable runnable)
- {
- _asyncDelivery.execute(runnable);
- }
-
- public AMQShortString getNameShortString()
- {
- return _name;
- }
-
- public void setNoLocal(boolean nolocal)
- {
- _nolocal = nolocal;
- }
-
- public UUID getId()
- {
- return _id;
- }
-
- public QueueConfigType getConfigType()
- {
- return QueueConfigType.getInstance();
- }
-
- public ConfiguredObject getParent()
- {
- return getVirtualHost();
- }
-
- public boolean isDurable()
- {
- return _durable;
- }
-
- public boolean isExclusive()
- {
- return _exclusive;
- }
-
- public void setExclusive(boolean exclusive) throws AMQException
- {
- _exclusive = exclusive;
-
- if(isDurable())
- {
- getVirtualHost().getDurableConfigurationStore().updateQueue(this);
- }
- }
-
- public Exchange getAlternateExchange()
- {
- return _alternateExchange;
- }
-
- public void setAlternateExchange(Exchange exchange)
- {
- if(_alternateExchange != null)
- {
- _alternateExchange.removeReference(this);
- }
- if(exchange != null)
- {
- exchange.addReference(this);
- }
- _alternateExchange = exchange;
- }
-
- public Map<String, Object> getArguments()
- {
- return _arguments;
- }
-
- public boolean isAutoDelete()
- {
- return _autoDelete;
- }
-
- public AMQShortString getOwner()
- {
- return _owner;
- }
-
- public PrincipalHolder getPrincipalHolder()
- {
- return _prinicpalHolder;
- }
-
- public void setPrincipalHolder(PrincipalHolder prinicpalHolder)
- {
- _prinicpalHolder = prinicpalHolder;
- }
-
-
- public VirtualHost getVirtualHost()
- {
- return _virtualHost;
- }
-
- public String getName()
- {
- return getNameShortString().toString();
- }
-
- // ------ Manage Subscriptions
-
- public synchronized void registerSubscription(final Subscription subscription, final boolean exclusive)
- throws AMQSecurityException, ExistingExclusiveSubscription, ExistingSubscriptionPreventsExclusive
- {
- // Access control
- if (!getVirtualHost().getSecurityManager().authoriseConsume(this))
- {
- throw new AMQSecurityException("Permission denied");
- }
-
-
- if (hasExclusiveSubscriber())
- {
- throw new ExistingExclusiveSubscription();
- }
-
- if (exclusive && !subscription.isTransient())
- {
- if (getConsumerCount() != 0)
- {
- throw new ExistingSubscriptionPreventsExclusive();
- }
- else
- {
- _exclusiveSubscriber = subscription;
- }
- }
-
- _activeSubscriberCount.incrementAndGet();
- subscription.setStateListener(this);
- subscription.setQueueContext(new QueueContext(_entries.getHead()));
-
- if (!isDeleted())
- {
- subscription.setQueue(this, exclusive);
- if(_nolocal)
- {
- subscription.setNoLocal(_nolocal);
- }
- _subscriptionList.add(subscription);
-
- //Increment consumerCountHigh if necessary. (un)registerSubscription are both
- //synchronized methods so we don't need additional synchronization here
- if(_counsumerCountHigh.get() < getConsumerCount())
- {
- _counsumerCountHigh.incrementAndGet();
- }
-
- if (isDeleted())
- {
- subscription.queueDeleted(this);
- }
- }
- else
- {
- // TODO
- }
-
- deliverAsync(subscription);
-
- }
-
- public synchronized void unregisterSubscription(final Subscription subscription) throws AMQException
- {
- if (subscription == null)
- {
- throw new NullPointerException("subscription argument is null");
- }
-
- boolean removed = _subscriptionList.remove(subscription);
-
- if (removed)
- {
- subscription.close();
- // No longer can the queue have an exclusive consumer
- setExclusiveSubscriber(null);
- subscription.setQueueContext(null);
-
- // auto-delete queues must be deleted if there are no remaining subscribers
-
- if (_autoDelete && getDeleteOnNoConsumers() && !subscription.isTransient() && getConsumerCount() == 0 )
- {
- if (_logger.isInfoEnabled())
- {
- _logger.info("Auto-deleteing queue:" + this);
- }
-
- delete();
-
- // we need to manually fire the event to the removed subscription (which was the last one left for this
- // queue. This is because the delete method uses the subscription set which has just been cleared
- subscription.queueDeleted(this);
- }
- }
-
- }
-
- public boolean getDeleteOnNoConsumers()
- {
- return _deleteOnNoConsumers;
- }
-
- public void setDeleteOnNoConsumers(boolean b)
- {
- _deleteOnNoConsumers = b;
- }
-
- public void addBinding(final Binding binding)
- {
- _bindings.add(binding);
- int bindingCount = _bindings.size();
- int bindingCountHigh;
- while(bindingCount > (bindingCountHigh = _bindingCountHigh.get()))
- {
- if(_bindingCountHigh.compareAndSet(bindingCountHigh, bindingCount))
- {
- break;
- }
- }
-
- reconfigure();
- }
-
- private void reconfigure()
- {
- //Reconfigure the queue for to reflect this new binding.
- ConfigurationPlugin config = getVirtualHost().getConfiguration().getQueueConfiguration(this);
-
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Reconfiguring queue(" + this + ") with config:" + config + " was "+ _queueConfiguration);
- }
-
- if (config != null)
- {
- // Reconfigure with new config.
- configure(config);
- }
- }
-
- public int getBindingCountHigh()
- {
- return _bindingCountHigh.get();
- }
-
- public void removeBinding(final Binding binding)
- {
- _bindings.remove(binding);
-
- reconfigure();
- }
-
- public List<Binding> getBindings()
- {
- return Collections.unmodifiableList(_bindings);
- }
-
- public int getBindingCount()
- {
- return getBindings().size();
- }
-
- public LogSubject getLogSubject()
- {
- return _logSubject;
- }
-
- // ------ Enqueue / Dequeue
- public void enqueue(ServerMessage message) throws AMQException
- {
- enqueue(message, null);
- }
-
- public void enqueue(ServerMessage message, PostEnqueueAction action) throws AMQException
- {
- incrementTxnEnqueueStats(message);
- incrementQueueCount();
- incrementQueueSize(message);
- _totalMessagesReceived.incrementAndGet();
-
-
- QueueEntry entry;
- Subscription exclusiveSub = _exclusiveSubscriber;
-
- if (exclusiveSub != null)
- {
- exclusiveSub.getSendLock();
-
- try
- {
- entry = _entries.add(message);
-
- deliverToSubscription(exclusiveSub, entry);
- }
- finally
- {
- exclusiveSub.releaseSendLock();
- }
- }
- else
- {
- entry = _entries.add(message);
- /*
-
- iterate over subscriptions and if any is at the end of the queue and can deliver this message, then deliver the message
-
- */
- SubscriptionList.SubscriptionNode node = _lastSubscriptionNode.get();
- SubscriptionList.SubscriptionNode nextNode = node.getNext();
- if (nextNode == null)
- {
- nextNode = _subscriptionList.getHead().getNext();
- }
- while (nextNode != null)
- {
- if (_lastSubscriptionNode.compareAndSet(node, nextNode))
- {
- break;
- }
- else
- {
- node = _lastSubscriptionNode.get();
- nextNode = node.getNext();
- if (nextNode == null)
- {
- nextNode = _subscriptionList.getHead().getNext();
- }
- }
- }
-
- // always do one extra loop after we believe we've finished
- // this catches the case where we *just* miss an update
- int loops = 2;
-
- while (!(entry.isAcquired() || entry.isDeleted()) && loops != 0)
- {
- if (nextNode == null)
- {
- loops--;
- nextNode = _subscriptionList.getHead();
- }
- else
- {
- // if subscription at end, and active, offer
- Subscription sub = nextNode.getSubscription();
- deliverToSubscription(sub, entry);
- }
- nextNode = nextNode.getNext();
-
- }
- }
-
-
- if (!(entry.isAcquired() || entry.isDeleted()))
- {
- checkSubscriptionsNotAheadOfDelivery(entry);
-
- deliverAsync();
- }
-
- if(_managedObject != null)
- {
- _managedObject.checkForNotification(entry.getMessage());
- }
-
- if(action != null)
- {
- action.onEnqueue(entry);
- }
-
- }
-
- private void deliverToSubscription(final Subscription sub, final QueueEntry entry)
- throws AMQException
- {
-
- sub.getSendLock();
- try
- {
- if (subscriptionReadyAndHasInterest(sub, entry)
- && !sub.isSuspended())
- {
- if (!sub.wouldSuspend(entry))
- {
- if (sub.acquires() && !entry.acquire(sub))
- {
- // restore credit here that would have been taken away by wouldSuspend since we didn't manage
- // to acquire the entry for this subscription
- sub.onDequeue(entry);
- }
- else
- {
- deliverMessage(sub, entry);
- }
- }
- }
- }
- finally
- {
- sub.releaseSendLock();
- }
- }
-
- protected void checkSubscriptionsNotAheadOfDelivery(final QueueEntry entry)
- {
- // This method is only required for queues which mess with ordering
- // Simple Queues don't :-)
- }
-
- private void incrementQueueSize(final ServerMessage message)
- {
- long size = message.getSize();
- getAtomicQueueSize().addAndGet(size);
- _enqueueSize.addAndGet(size);
- if(message.isPersistent() && isDurable())
- {
- _persistentMessageEnqueueSize.addAndGet(size);
- _persistentMessageEnqueueCount.incrementAndGet();
- }
- }
-
- private void incrementQueueCount()
- {
- getAtomicQueueCount().incrementAndGet();
- }
-
- private void incrementTxnEnqueueStats(final ServerMessage message)
- {
- SessionConfig session = message.getSessionConfig();
-
- if(session !=null && session.isTransactional())
- {
- _msgTxnEnqueues.incrementAndGet();
- _byteTxnEnqueues.addAndGet(message.getSize());
- }
- }
-
- private void incrementTxnDequeueStats(QueueEntry entry)
- {
- _msgTxnDequeues.incrementAndGet();
- _byteTxnDequeues.addAndGet(entry.getSize());
- }
-
- private void deliverMessage(final Subscription sub, final QueueEntry entry)
- throws AMQException
- {
- setLastSeenEntry(sub, entry);
-
- _deliveredMessages.incrementAndGet();
- incrementUnackedMsgCount();
-
- sub.send(entry);
- }
-
- private boolean subscriptionReadyAndHasInterest(final Subscription sub, final QueueEntry entry) throws AMQException
- {
- return sub.hasInterest(entry) && (getNextAvailableEntry(sub) == entry);
- }
-
-
- private void setLastSeenEntry(final Subscription sub, final QueueEntry entry)
- {
- QueueContext subContext = (QueueContext) sub.getQueueContext();
- QueueEntry releasedEntry = subContext._releasedEntry;
-
- QueueContext._lastSeenUpdater.set(subContext, entry);
- if(releasedEntry == entry)
- {
- QueueContext._releasedUpdater.compareAndSet(subContext, releasedEntry, null);
- }
- }
-
- private void updateSubRequeueEntry(final Subscription sub, final QueueEntry entry)
- {
-
- QueueContext subContext = (QueueContext) sub.getQueueContext();
- if(subContext != null)
- {
- QueueEntry oldEntry;
-
- while((oldEntry = subContext._releasedEntry) == null || oldEntry.compareTo(entry) > 0)
- {
- if(QueueContext._releasedUpdater.compareAndSet(subContext, oldEntry, entry))
- {
- break;
- }
- }
- }
- }
-
- public void requeue(QueueEntry entry)
- {
-
- SubscriptionList.SubscriptionNodeIterator subscriberIter = _subscriptionList.iterator();
- // iterate over all the subscribers, and if they are in advance of this queue entry then move them backwards
- while (subscriberIter.advance() && entry.isAvailable())
- {
- Subscription sub = subscriberIter.getNode().getSubscription();
-
- // we don't make browsers send the same stuff twice
- if (sub.seesRequeues())
- {
- updateSubRequeueEntry(sub, entry);
- }
- }
-
- deliverAsync();
-
- }
-
- public void dequeue(QueueEntry entry, Subscription sub)
- {
- decrementQueueCount();
- decrementQueueSize(entry);
- if (entry.acquiredBySubscription())
- {
- _deliveredMessages.decrementAndGet();
- }
-
- if(sub != null && sub.isSessionTransactional())
- {
- incrementTxnDequeueStats(entry);
- }
-
- checkCapacity();
-
- }
-
- private void decrementQueueSize(final QueueEntry entry)
- {
- final ServerMessage message = entry.getMessage();
- long size = message.getSize();
- getAtomicQueueSize().addAndGet(-size);
- _dequeueSize.addAndGet(size);
- if(message.isPersistent() && isDurable())
- {
- _persistentMessageDequeueSize.addAndGet(size);
- _persistentMessageDequeueCount.incrementAndGet();
- }
- }
-
- void decrementQueueCount()
- {
- getAtomicQueueCount().decrementAndGet();
- _dequeueCount.incrementAndGet();
- }
-
- public boolean resend(final QueueEntry entry, final Subscription subscription) throws AMQException
- {
- /* TODO : This is wrong as the subscription may be suspended, we should instead change the state of the message
- entry to resend and move back the subscription pointer. */
-
- subscription.getSendLock();
- try
- {
- if (!subscription.isClosed())
- {
- deliverMessage(subscription, entry);
- return true;
- }
- else
- {
- return false;
- }
- }
- finally
- {
- subscription.releaseSendLock();
- }
- }
-
- public int getConsumerCount()
- {
- return _subscriptionList.size();
- }
-
- public int getConsumerCountHigh()
- {
- return _counsumerCountHigh.get();
- }
-
- public int getActiveConsumerCount()
- {
- return _activeSubscriberCount.get();
- }
-
- public boolean isUnused()
- {
- return getConsumerCount() == 0;
- }
-
- public boolean isEmpty()
- {
- return getMessageCount() == 0;
- }
-
- public int getMessageCount()
- {
- return getAtomicQueueCount().get();
- }
-
- public long getQueueDepth()
- {
- return getAtomicQueueSize().get();
- }
-
- public int getUndeliveredMessageCount()
- {
- int count = getMessageCount() - _deliveredMessages.get();
- if (count < 0)
- {
- return 0;
- }
- else
- {
- return count;
- }
- }
-
- public long getReceivedMessageCount()
- {
- return _totalMessagesReceived.get();
- }
-
- public long getOldestMessageArrivalTime()
- {
- QueueEntry entry = getOldestQueueEntry();
- return entry == null ? Long.MAX_VALUE : entry.getMessage().getArrivalTime();
- }
-
- protected QueueEntry getOldestQueueEntry()
- {
- return _entries.next(_entries.getHead());
- }
-
- public boolean isDeleted()
- {
- return _deleted.get();
- }
-
- public List<QueueEntry> getMessagesOnTheQueue()
- {
- ArrayList<QueueEntry> entryList = new ArrayList<QueueEntry>();
- QueueEntryIterator queueListIterator = _entries.iterator();
- while (queueListIterator.advance())
- {
- QueueEntry node = queueListIterator.getNode();
- if (node != null && !node.isDeleted())
- {
- entryList.add(node);
- }
- }
- return entryList;
-
- }
-
- public void stateChange(Subscription sub, Subscription.State oldState, Subscription.State newState)
- {
- if (oldState == Subscription.State.ACTIVE && newState != Subscription.State.ACTIVE)
- {
- _activeSubscriberCount.decrementAndGet();
-
- }
- else if (newState == Subscription.State.ACTIVE)
- {
- if (oldState != Subscription.State.ACTIVE)
- {
- _activeSubscriberCount.incrementAndGet();
-
- }
- deliverAsync(sub);
- }
- }
-
- public int compareTo(final AMQQueue o)
- {
- return _name.compareTo(o.getNameShortString());
- }
-
- public AtomicInteger getAtomicQueueCount()
- {
- return _atomicQueueCount;
- }
-
- public AtomicLong getAtomicQueueSize()
- {
- return _atomicQueueSize;
- }
-
- public boolean hasExclusiveSubscriber()
- {
- return _exclusiveSubscriber != null;
- }
-
- private void setExclusiveSubscriber(Subscription exclusiveSubscriber)
- {
- _exclusiveSubscriber = exclusiveSubscriber;
- }
-
- public static interface QueueEntryFilter
- {
- public boolean accept(QueueEntry entry);
-
- public boolean filterComplete();
- }
-
- public List<QueueEntry> getMessagesOnTheQueue(final long fromMessageId, final long toMessageId)
- {
- return getMessagesOnTheQueue(new QueueEntryFilter()
- {
-
- public boolean accept(QueueEntry entry)
- {
- final long messageId = entry.getMessage().getMessageNumber();
- return messageId >= fromMessageId && messageId <= toMessageId;
- }
-
- public boolean filterComplete()
- {
- return false;
- }
- });
- }
-
- public QueueEntry getMessageOnTheQueue(final long messageId)
- {
- List<QueueEntry> entries = getMessagesOnTheQueue(new QueueEntryFilter()
- {
- private boolean _complete;
-
- public boolean accept(QueueEntry entry)
- {
- _complete = entry.getMessage().getMessageNumber() == messageId;
- return _complete;
- }
-
- public boolean filterComplete()
- {
- return _complete;
- }
- });
- return entries.isEmpty() ? null : entries.get(0);
- }
-
- public List<QueueEntry> getMessagesOnTheQueue(QueueEntryFilter filter)
- {
- ArrayList<QueueEntry> entryList = new ArrayList<QueueEntry>();
- QueueEntryIterator queueListIterator = _entries.iterator();
- while (queueListIterator.advance() && !filter.filterComplete())
- {
- QueueEntry node = queueListIterator.getNode();
- if (!node.isDeleted() && filter.accept(node))
- {
- entryList.add(node);
- }
- }
- return entryList;
-
- }
-
- /**
- * Returns a list of QueEntries from a given range of queue positions, eg messages 5 to 10 on the queue.
- *
- * The 'queue position' index starts from 1. Using 0 in 'from' will be ignored and continue from 1.
- * Using 0 in the 'to' field will return an empty list regardless of the 'from' value.
- * @param fromPosition
- * @param toPosition
- * @return
- */
- public List<QueueEntry> getMessagesRangeOnTheQueue(final long fromPosition, final long toPosition)
- {
- return getMessagesOnTheQueue(new QueueEntryFilter()
- {
- private long position = 0;
-
- public boolean accept(QueueEntry entry)
- {
- position++;
- return (position >= fromPosition) && (position <= toPosition);
- }
-
- public boolean filterComplete()
- {
- return position >= toPosition;
- }
- });
-
- }
-
- public void moveMessagesToAnotherQueue(final long fromMessageId,
- final long toMessageId,
- String queueName,
- ServerTransaction txn) 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");
- }
-
- List<QueueEntry> entries = getMessagesOnTheQueue(new QueueEntryFilter()
- {
-
- public boolean accept(QueueEntry entry)
- {
- final long messageId = entry.getMessage().getMessageNumber();
- return (messageId >= fromMessageId)
- && (messageId <= toMessageId)
- && entry.acquire();
- }
-
- public boolean filterComplete()
- {
- return false;
- }
- });
-
-
-
- // 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()
- {
-
- public void postCommit()
- {
- try
- {
- toQueue.enqueue(message);
- }
- catch (AMQException e)
- {
- throw new RuntimeException(e);
- }
- }
-
- public void onRollback()
- {
- entry.release();
- }
- });
- txn.dequeue(this, message,
- new ServerTransaction.Action()
- {
-
- public void postCommit()
- {
- entry.discard();
- }
-
- public void onRollback()
- {
-
- }
- });
-
- }
-
- }
-
- public void copyMessagesToAnotherQueue(final long fromMessageId,
- final long toMessageId,
- String queueName,
- final ServerTransaction txn) 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");
- }
-
- List<QueueEntry> entries = getMessagesOnTheQueue(new QueueEntryFilter()
- {
-
- public boolean accept(QueueEntry entry)
- {
- final long messageId = entry.getMessage().getMessageNumber();
- return ((messageId >= fromMessageId)
- && (messageId <= toMessageId));
- }
-
- public boolean filterComplete()
- {
- return false;
- }
- });
-
-
- // Move the messages in on the message store.
- for (QueueEntry entry : entries)
- {
- final ServerMessage message = entry.getMessage();
-
- txn.enqueue(toQueue, message, new ServerTransaction.Action()
- {
- public void postCommit()
- {
- try
- {
- toQueue.enqueue(message);
- }
- catch (AMQException e)
- {
- throw new RuntimeException(e);
- }
- }
-
- public void onRollback()
- {
-
- }
- });
-
- }
-
- }
-
- public void removeMessagesFromQueue(long fromMessageId, long toMessageId)
- {
-
- QueueEntryIterator queueListIterator = _entries.iterator();
-
- while (queueListIterator.advance())
- {
- QueueEntry node = queueListIterator.getNode();
-
- final ServerMessage message = node.getMessage();
- if(message != null)
- {
- final long messageId = message.getMessageNumber();
-
- if ((messageId >= fromMessageId)
- && (messageId <= toMessageId)
- && !node.isDeleted()
- && node.acquire())
- {
- dequeueEntry(node);
- }
- }
- }
-
- }
-
- public void purge(final long request) throws AMQException
- {
- clear(request);
- }
-
- public long getCreateTime()
- {
- return _createTime;
- }
-
- // ------ Management functions
-
- public void deleteMessageFromTop()
- {
- QueueEntryIterator queueListIterator = _entries.iterator();
- boolean noDeletes = true;
-
- while (noDeletes && queueListIterator.advance())
- {
- QueueEntry node = queueListIterator.getNode();
- if (!node.isDeleted() && node.acquire())
- {
- dequeueEntry(node);
- noDeletes = false;
- }
-
- }
- }
-
- public long clearQueue() throws AMQException
- {
- return clear(0l);
- }
-
- private long clear(final long request) throws AMQSecurityException
- {
- //Perform ACLs
- if (!getVirtualHost().getSecurityManager().authorisePurge(this))
- {
- throw new AMQSecurityException("Permission denied: queue " + getName());
- }
-
- QueueEntryIterator queueListIterator = _entries.iterator();
- long count = 0;
-
- ServerTransaction txn = new LocalTransaction(getVirtualHost().getTransactionLog());
-
- while (queueListIterator.advance())
- {
- QueueEntry node = queueListIterator.getNode();
- if (!node.isDeleted() && node.acquire())
- {
- dequeueEntry(node, txn);
- if(++count == request)
- {
- break;
- }
- }
-
- }
-
- txn.commit();
-
- return count;
- }
-
- private void dequeueEntry(final QueueEntry node)
- {
- ServerTransaction txn = new AutoCommitTransaction(getVirtualHost().getTransactionLog());
- dequeueEntry(node, txn);
- }
-
- private void dequeueEntry(final QueueEntry node, ServerTransaction txn)
- {
- txn.dequeue(this, node.getMessage(),
- new ServerTransaction.Action()
- {
-
- public void postCommit()
- {
- node.discard();
- }
-
- public void onRollback()
- {
-
- }
- });
- }
-
- public void addQueueDeleteTask(final Task task)
- {
- _deleteTaskList.add(task);
- }
-
- public void removeQueueDeleteTask(final Task task)
- {
- _deleteTaskList.remove(task);
- }
-
- // TODO list all thrown exceptions
- public int delete() throws AMQSecurityException, AMQException
- {
- // Check access
- if (!_virtualHost.getSecurityManager().authoriseDelete(this))
- {
- throw new AMQSecurityException("Permission denied: " + getName());
- }
-
- if (!_deleted.getAndSet(true))
- {
-
- for (Binding b : getBindings())
- {
- _virtualHost.getBindingFactory().removeBinding(b);
- }
-
- SubscriptionList.SubscriptionNodeIterator subscriptionIter = _subscriptionList.iterator();
-
- while (subscriptionIter.advance())
- {
- Subscription s = subscriptionIter.getNode().getSubscription();
- if (s != null)
- {
- s.queueDeleted(this);
- }
- }
-
- _virtualHost.getQueueRegistry().unregisterQueue(_name);
- getConfigStore().removeConfiguredObject(this);
-
- List<QueueEntry> entries = getMessagesOnTheQueue(new QueueEntryFilter()
- {
-
- public boolean accept(QueueEntry entry)
- {
- return entry.acquire();
- }
-
- public boolean filterComplete()
- {
- return false;
- }
- });
-
- ServerTransaction txn = new LocalTransaction(getVirtualHost().getTransactionLog());
-
- if(_alternateExchange != null)
- {
-
- InboundMessageAdapter adapter = new InboundMessageAdapter();
- for(final QueueEntry entry : entries)
- {
- adapter.setEntry(entry);
- final List<? extends BaseQueue> rerouteQueues = _alternateExchange.route(adapter);
- final ServerMessage message = entry.getMessage();
- if(rerouteQueues != null && rerouteQueues.size() != 0)
- {
- txn.enqueue(rerouteQueues, entry.getMessage(),
- new ServerTransaction.Action()
- {
-
- public void postCommit()
- {
- try
- {
- for(BaseQueue queue : rerouteQueues)
- {
- queue.enqueue(message);
- }
- }
- catch (AMQException e)
- {
- throw new RuntimeException(e);
- }
-
- }
-
- public void onRollback()
- {
-
- }
- });
- txn.dequeue(this, entry.getMessage(),
- new ServerTransaction.Action()
- {
-
- public void postCommit()
- {
- entry.discard();
- }
-
- public void onRollback()
- {
- }
- });
- }
-
- }
-
- _alternateExchange.removeReference(this);
- }
- else
- {
- // TODO log discard
-
- for(final QueueEntry entry : entries)
- {
- final ServerMessage message = entry.getMessage();
- if(message != null)
- {
- txn.dequeue(this, message,
- new ServerTransaction.Action()
- {
-
- public void postCommit()
- {
- entry.discard();
- }
-
- public void onRollback()
- {
- }
- });
- }
- }
- }
-
- txn.commit();
-
-
- if(_managedObject!=null)
- {
- _managedObject.unregister();
- }
-
- for (Task task : _deleteTaskList)
- {
- task.doTask(this);
- }
-
- _deleteTaskList.clear();
- stop();
-
- //Log Queue Deletion
- CurrentActor.get().message(_logSubject, QueueMessages.DELETED());
-
- }
- return getMessageCount();
-
- }
-
- public void stop()
- {
- if (!_stopped.getAndSet(true))
- {
- ReferenceCountingExecutorService.getInstance().releaseExecutorService();
- }
- }
-
- public void checkCapacity(AMQChannel channel)
- {
- if(_capacity != 0l)
- {
- if(_atomicQueueSize.get() > _capacity)
- {
- _overfull.set(true);
- //Overfull log message
- _logActor.message(_logSubject, QueueMessages.OVERFULL(_atomicQueueSize.get(), _capacity));
-
- if(_blockedChannels.putIfAbsent(channel, Boolean.TRUE)==null)
- {
- channel.block(this);
- }
-
- if(_atomicQueueSize.get() <= _flowResumeCapacity)
- {
-
- //Underfull log message
- _logActor.message(_logSubject, QueueMessages.UNDERFULL(_atomicQueueSize.get(), _flowResumeCapacity));
-
- channel.unblock(this);
- _blockedChannels.remove(channel);
-
- }
-
- }
-
-
-
- }
- }
-
- private void checkCapacity()
- {
- if(_capacity != 0L)
- {
- if(_overfull.get() && _atomicQueueSize.get() <= _flowResumeCapacity)
- {
- if(_overfull.compareAndSet(true,false))
- {//Underfull log message
- _logActor.message(_logSubject, QueueMessages.UNDERFULL(_atomicQueueSize.get(), _flowResumeCapacity));
- }
-
-
- for(AMQChannel c : _blockedChannels.keySet())
- {
- c.unblock(this);
- _blockedChannels.remove(c);
- }
- }
- }
- }
-
-
- public void deliverAsync()
- {
- QueueRunner runner = new QueueRunner(this, _stateChangeCount.incrementAndGet());
-
- if (_asynchronousRunner.compareAndSet(null, runner))
- {
- _asyncDelivery.execute(runner);
- }
- }
-
- public void deliverAsync(Subscription sub)
- {
- SubFlushRunner flusher = (SubFlushRunner) sub.get(SUB_FLUSH_RUNNER);
- if(flusher == null)
- {
- flusher = new SubFlushRunner(sub);
- sub.set(SUB_FLUSH_RUNNER, flusher);
- }
- _asyncDelivery.execute(flusher);
- }
-
- public void flushSubscription(Subscription sub) throws AMQException
- {
- // Access control
- if (!getVirtualHost().getSecurityManager().authoriseConsume(this))
- {
- throw new AMQSecurityException("Permission denied: " + getName());
- }
- flushSubscription(sub, Long.MAX_VALUE);
- }
-
- public boolean flushSubscription(Subscription sub, long iterations) throws AMQException
- {
- boolean atTail = false;
-
- while (!sub.isSuspended() && !atTail && iterations != 0)
- {
- try
- {
- sub.getSendLock();
- atTail = attemptDelivery(sub);
- if (atTail && sub.isAutoClose())
- {
- unregisterSubscription(sub);
-
- sub.confirmAutoClose();
-
- }
- else if (!atTail)
- {
- iterations--;
- }
- }
- finally
- {
- sub.releaseSendLock();
- }
- }
-
- // if there's (potentially) more than one subscription the others will potentially not have been advanced to the
- // next entry they are interested in yet. This would lead to holding on to references to expired messages, etc
- // which would give us memory "leak".
-
- if (!hasExclusiveSubscriber())
- {
- advanceAllSubscriptions();
- }
- return atTail;
- }
-
- /**
- * Attempt delivery for the given subscription.
- *
- * Looks up the next node for the subscription and attempts to deliver it.
- *
- * @param sub
- * @return true if we have completed all possible deliveries for this sub.
- * @throws AMQException
- */
- private boolean attemptDelivery(Subscription sub) throws AMQException
- {
- boolean atTail = false;
-
- boolean subActive = sub.isActive() && !sub.isSuspended();
- if (subActive)
- {
-
- QueueEntry node = getNextAvailableEntry(sub);
-
- if (node != null && !(node.isAcquired() || node.isDeleted()))
- {
- if (sub.hasInterest(node))
- {
- if (!sub.wouldSuspend(node))
- {
- if (sub.acquires() && !node.acquire(sub))
- {
- sub.onDequeue(node);
- }
- else
- {
- deliverMessage(sub, node);
- }
-
- }
- else // Not enough Credit for message and wouldSuspend
- {
- //QPID-1187 - Treat the subscription as suspended for this message
- // and wait for the message to be removed to continue delivery.
- subActive = false;
- node.addStateChangeListener(new QueueEntryListener(sub));
- }
- }
-
- }
- atTail = (node == null) || (_entries.next(node) == null);
- }
- return atTail || !subActive;
- }
-
- protected void advanceAllSubscriptions() throws AMQException
- {
- SubscriptionList.SubscriptionNodeIterator subscriberIter = _subscriptionList.iterator();
- while (subscriberIter.advance())
- {
- SubscriptionList.SubscriptionNode subNode = subscriberIter.getNode();
- Subscription sub = subNode.getSubscription();
- if(sub.acquires())
- {
- getNextAvailableEntry(sub);
- }
- else
- {
- // TODO
- }
- }
- }
-
- private QueueEntry getNextAvailableEntry(final Subscription sub)
- throws AMQException
- {
- QueueContext context = (QueueContext) sub.getQueueContext();
- if(context != null)
- {
- QueueEntry lastSeen = context._lastSeenEntry;
- QueueEntry releasedNode = context._releasedEntry;
-
- QueueEntry node = (releasedNode != null && lastSeen.compareTo(releasedNode)>=0) ? releasedNode : _entries.next(lastSeen);
-
- boolean expired = false;
- while (node != null && (node.isAcquired() || node.isDeleted() || (expired = node.expired()) || !sub.hasInterest(node)))
- {
- if (expired)
- {
- expired = false;
- if (node.acquire())
- {
- dequeueEntry(node);
- }
- }
-
- if(QueueContext._lastSeenUpdater.compareAndSet(context, lastSeen, node))
- {
- QueueContext._releasedUpdater.compareAndSet(context, releasedNode, null);
- }
-
- lastSeen = context._lastSeenEntry;
- releasedNode = context._releasedEntry;
- node = (releasedNode != null && lastSeen.compareTo(releasedNode)>0) ? releasedNode : _entries.next(lastSeen);
- }
- return node;
- }
- else
- {
- return null;
- }
- }
-
-
- /**
- * Used by queue Runners to asynchronously deliver messages to consumers.
- *
- * A queue Runner is started whenever a state change occurs, e.g when a new
- * message arrives on the queue and cannot be immediately delivered to a
- * subscription (i.e. asynchronous delivery is required). Unless there are
- * SubFlushRunners operating (due to subscriptions unsuspending) which are
- * capable of accepting/delivering all messages then these messages would
- * otherwise remain on the queue.
- *
- * processQueue should be running while there are messages on the queue AND
- * there are subscriptions that can deliver them. If there are no
- * subscriptions capable of delivering the remaining messages on the queue
- * then processQueue should stop to prevent spinning.
- *
- * Since processQueue is runs in a fixed size Executor, it should not run
- * indefinitely to prevent starving other tasks of CPU (e.g jobs to process
- * incoming messages may not be able to be scheduled in the thread pool
- * because all threads are working on clearing down large queues). To solve
- * this problem, after an arbitrary number of message deliveries the
- * processQueue job stops iterating, resubmits itself to the executor, and
- * ends the current instance
- *
- * @param runner the Runner to schedule
- * @throws AMQException
- */
- public void processQueue(QueueRunner runner) throws AMQException
- {
- long stateChangeCount;
- long previousStateChangeCount = Long.MIN_VALUE;
- boolean deliveryIncomplete = true;
-
- boolean lastLoop = false;
- int iterations = MAX_ASYNC_DELIVERIES;
-
- _asynchronousRunner.compareAndSet(runner, null);
-
- // For every message enqueue/requeue the we fire deliveryAsync() which
- // increases _stateChangeCount. If _sCC changes whilst we are in our loop
- // (detected by setting previousStateChangeCount to stateChangeCount in the loop body)
- // then we will continue to run for a maximum of iterations.
- // So whilst delivery/rejection is going on a processQueue thread will be running
- while (iterations != 0 && ((previousStateChangeCount != (stateChangeCount = _stateChangeCount.get())) || deliveryIncomplete) && _asynchronousRunner.compareAndSet(null, runner))
- {
- // we want to have one extra loop after every subscription has reached the point where it cannot move
- // further, just in case the advance of one subscription in the last loop allows a different subscription to
- // move forward in the next iteration
-
- if (previousStateChangeCount != stateChangeCount)
- {
- //further asynchronous delivery is required since the
- //previous loop. keep going if iteration slicing allows.
- lastLoop = false;
- }
-
- previousStateChangeCount = stateChangeCount;
- boolean allSubscriptionsDone = true;
- boolean subscriptionDone;
-
- SubscriptionList.SubscriptionNodeIterator subscriptionIter = _subscriptionList.iterator();
- //iterate over the subscribers and try to advance their pointer
- while (subscriptionIter.advance())
- {
- Subscription sub = subscriptionIter.getNode().getSubscription();
- sub.getSendLock();
- try
- {
- //attempt delivery. returns true if no further delivery currently possible to this sub
- subscriptionDone = attemptDelivery(sub);
- if (subscriptionDone)
- {
- //close autoClose subscriptions if we are not currently intent on continuing
- if (lastLoop && sub.isAutoClose())
- {
- unregisterSubscription(sub);
-
- sub.confirmAutoClose();
- }
- }
- else
- {
- //this subscription can accept additional deliveries, so we must
- //keep going after this (if iteration slicing allows it)
- allSubscriptionsDone = false;
- lastLoop = false;
- iterations--;
- }
- }
- finally
- {
- sub.releaseSendLock();
- }
- }
-
- if(allSubscriptionsDone && lastLoop)
- {
- //We have done an extra loop already and there are again
- //again no further delivery attempts possible, only
- //keep going if state change demands it.
- deliveryIncomplete = false;
- }
- else if(allSubscriptionsDone)
- {
- //All subscriptions reported being done, but we have to do
- //an extra loop if the iterations are not exhausted and
- //there is still any work to be done
- deliveryIncomplete = _subscriptionList.size() != 0;
- lastLoop = true;
- }
- else
- {
- //some subscriptions can still accept more messages,
- //keep going if iteration count allows.
- lastLoop = false;
- deliveryIncomplete = true;
- }
-
- _asynchronousRunner.set(null);
- }
-
- // If iterations == 0 then the limiting factor was the time-slicing rather than available messages or credit
- // therefore we should schedule this runner again (unless someone beats us to it :-) ).
- if (iterations == 0 && _asynchronousRunner.compareAndSet(null, runner))
- {
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Rescheduling runner:" + runner);
- }
- _asyncDelivery.execute(runner);
- }
- }
-
- public void checkMessageStatus() throws AMQException
- {
-
- QueueEntryIterator queueListIterator = _entries.iterator();
-
- while (queueListIterator.advance())
- {
- QueueEntry node = queueListIterator.getNode();
- // Only process nodes that are not currently deleted
- if (!node.isDeleted())
- {
- // If the node has exired then aquire it
- if (node.expired() && node.acquire())
- {
- // Then dequeue it.
- dequeueEntry(node);
- }
- else
- {
- if (_managedObject != null)
- {
- // There is a chance that the node could be deleted by
- // the time the check actually occurs. So verify we
- // can actually get the message to perform the check.
- ServerMessage msg = node.getMessage();
- if (msg != null)
- {
- _managedObject.checkForNotification(msg);
- }
- }
- }
- }
- }
-
- }
-
- public long getMinimumAlertRepeatGap()
- {
- return _minimumAlertRepeatGap;
- }
-
- public void setMinimumAlertRepeatGap(long minimumAlertRepeatGap)
- {
- _minimumAlertRepeatGap = minimumAlertRepeatGap;
- }
-
- public long getMaximumMessageAge()
- {
- return _maximumMessageAge;
- }
-
- public void setMaximumMessageAge(long maximumMessageAge)
- {
- _maximumMessageAge = maximumMessageAge;
- if (maximumMessageAge == 0L)
- {
- _notificationChecks.remove(NotificationCheck.MESSAGE_AGE_ALERT);
- }
- else
- {
- _notificationChecks.add(NotificationCheck.MESSAGE_AGE_ALERT);
- }
- }
-
- public long getMaximumMessageCount()
- {
- return _maximumMessageCount;
- }
-
- public void setMaximumMessageCount(final long maximumMessageCount)
- {
- _maximumMessageCount = maximumMessageCount;
- if (maximumMessageCount == 0L)
- {
- _notificationChecks.remove(NotificationCheck.MESSAGE_COUNT_ALERT);
- }
- else
- {
- _notificationChecks.add(NotificationCheck.MESSAGE_COUNT_ALERT);
- }
-
- }
-
- public long getMaximumQueueDepth()
- {
- return _maximumQueueDepth;
- }
-
- // Sets the queue depth, the max queue size
- public void setMaximumQueueDepth(final long maximumQueueDepth)
- {
- _maximumQueueDepth = maximumQueueDepth;
- if (maximumQueueDepth == 0L)
- {
- _notificationChecks.remove(NotificationCheck.QUEUE_DEPTH_ALERT);
- }
- else
- {
- _notificationChecks.add(NotificationCheck.QUEUE_DEPTH_ALERT);
- }
-
- }
-
- public long getMaximumMessageSize()
- {
- return _maximumMessageSize;
- }
-
- public void setMaximumMessageSize(final long maximumMessageSize)
- {
- _maximumMessageSize = maximumMessageSize;
- if (maximumMessageSize == 0L)
- {
- _notificationChecks.remove(NotificationCheck.MESSAGE_SIZE_ALERT);
- }
- else
- {
- _notificationChecks.add(NotificationCheck.MESSAGE_SIZE_ALERT);
- }
- }
-
- public long getCapacity()
- {
- return _capacity;
- }
-
- public void setCapacity(long capacity)
- {
- _capacity = capacity;
- }
-
- public long getFlowResumeCapacity()
- {
- return _flowResumeCapacity;
- }
-
- public void setFlowResumeCapacity(long flowResumeCapacity)
- {
- _flowResumeCapacity = flowResumeCapacity;
-
- checkCapacity();
- }
-
- public boolean isOverfull()
- {
- return _overfull.get();
- }
-
- public Set<NotificationCheck> getNotificationChecks()
- {
- return _notificationChecks;
- }
-
- public ManagedObject getManagedObject()
- {
- return _managedObject;
- }
-
- private final class QueueEntryListener implements QueueEntry.StateChangeListener
- {
-
- private final Subscription _sub;
-
- public QueueEntryListener(final Subscription sub)
- {
- _sub = sub;
- }
-
- public boolean equals(Object o)
- {
- assert o != null;
- assert o instanceof QueueEntryListener;
- return _sub == ((QueueEntryListener) o)._sub;
- }
-
- public int hashCode()
- {
- return System.identityHashCode(_sub);
- }
-
- public void stateChanged(QueueEntry entry, QueueEntry.State oldSate, QueueEntry.State newState)
- {
- entry.removeStateChangeListener(this);
- deliverAsync(_sub);
- }
- }
-
- public List<Long> getMessagesOnTheQueue(int num)
- {
- return getMessagesOnTheQueue(num, 0);
- }
-
- public List<Long> getMessagesOnTheQueue(int num, int offset)
- {
- ArrayList<Long> ids = new ArrayList<Long>(num);
- QueueEntryIterator it = _entries.iterator();
- for (int i = 0; i < offset; i++)
- {
- it.advance();
- }
-
- for (int i = 0; i < num && !it.atTail(); i++)
- {
- it.advance();
- ids.add(it.getNode().getMessage().getMessageNumber());
- }
- return ids;
- }
-
- public AMQSessionModel getExclusiveOwningSession()
- {
- return _exclusiveOwner;
- }
-
- public void setExclusiveOwningSession(AMQSessionModel exclusiveOwner)
- {
- _exclusive = true;
- _exclusiveOwner = exclusiveOwner;
- }
-
-
- public void configure(ConfigurationPlugin config)
- {
- if (config != null)
- {
- if (config instanceof QueueConfiguration)
- {
-
- setMaximumMessageAge(((QueueConfiguration)config).getMaximumMessageAge());
- setMaximumQueueDepth(((QueueConfiguration)config).getMaximumQueueDepth());
- setMaximumMessageSize(((QueueConfiguration)config).getMaximumMessageSize());
- setMaximumMessageCount(((QueueConfiguration)config).getMaximumMessageCount());
- setMinimumAlertRepeatGap(((QueueConfiguration)config).getMinimumAlertRepeatGap());
- _capacity = ((QueueConfiguration)config).getCapacity();
- _flowResumeCapacity = ((QueueConfiguration)config).getFlowResumeCapacity();
- }
-
- _queueConfiguration = config;
-
- }
- }
-
-
- public ConfigurationPlugin getConfiguration()
- {
- return _queueConfiguration;
- }
-
- public String getResourceName()
- {
- return _resourceName;
- }
-
-
- public ConfigStore getConfigStore()
- {
- return getVirtualHost().getConfigStore();
- }
-
- public long getMessageDequeueCount()
- {
- return _dequeueCount.get();
- }
-
- public long getTotalEnqueueSize()
- {
- return _enqueueSize.get();
- }
-
- public long getTotalDequeueSize()
- {
- return _dequeueSize.get();
- }
-
- public long getByteTxnEnqueues()
- {
- return _byteTxnEnqueues.get();
- }
-
- public long getByteTxnDequeues()
- {
- return _byteTxnDequeues.get();
- }
-
- public long getMsgTxnEnqueues()
- {
- return _msgTxnEnqueues.get();
- }
-
- public long getMsgTxnDequeues()
- {
- return _msgTxnDequeues.get();
- }
-
- public long getPersistentByteEnqueues()
- {
- return _persistentMessageEnqueueSize.get();
- }
-
- public long getPersistentByteDequeues()
- {
- return _persistentMessageDequeueSize.get();
- }
-
- public long getPersistentMsgEnqueues()
- {
- return _persistentMessageEnqueueCount.get();
- }
-
- public long getPersistentMsgDequeues()
- {
- return _persistentMessageDequeueCount.get();
- }
-
-
- @Override
- public String toString()
- {
- return String.valueOf(getNameShortString());
- }
-
- public long getUnackedMessageCountHigh()
- {
- return _unackedMsgCountHigh.get();
- }
-
- public long getUnackedMessageCount()
- {
- return _unackedMsgCount.get();
- }
-
- public void decrementUnackedMsgCount()
- {
- _unackedMsgCount.decrementAndGet();
- }
-
- private void incrementUnackedMsgCount()
- {
- long unackedMsgCount = _unackedMsgCount.incrementAndGet();
-
- long unackedMsgCountHigh;
- while(unackedMsgCount > (unackedMsgCountHigh = _unackedMsgCountHigh.get()))
- {
- if(_unackedMsgCountHigh.compareAndSet(unackedMsgCountHigh, unackedMsgCount))
- {
- break;
- }
- }
- }
-
- public LogActor getLogActor()
- {
- return _logActor;
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/SimpleQueueEntryList.java b/java/broker/src/main/java/org/apache/qpid/server/queue/SimpleQueueEntryList.java
deleted file mode 100644
index b97c2c55c5..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/queue/SimpleQueueEntryList.java
+++ /dev/null
@@ -1,198 +0,0 @@
-package org.apache.qpid.server.queue;
-
-import org.apache.qpid.server.message.InboundMessage;
-import org.apache.qpid.server.message.ServerMessage;
-
-import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
-import java.util.concurrent.atomic.AtomicLong;
-
-/*
-*
-* 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 SimpleQueueEntryList implements QueueEntryList
-{
-
- private final QueueEntryImpl _head;
-
- private volatile QueueEntryImpl _tail;
-
- static final AtomicReferenceFieldUpdater<SimpleQueueEntryList, QueueEntryImpl>
- _tailUpdater =
- AtomicReferenceFieldUpdater.newUpdater
- (SimpleQueueEntryList.class, QueueEntryImpl.class, "_tail");
-
-
- private final AMQQueue _queue;
-
- static final AtomicReferenceFieldUpdater<QueueEntryImpl, QueueEntryImpl>
- _nextUpdater =
- AtomicReferenceFieldUpdater.newUpdater
- (QueueEntryImpl.class, QueueEntryImpl.class, "_next");
-
- private AtomicLong _scavenges = new AtomicLong(0L);
- private final long _scavengeCount = Integer.getInteger("qpid.queue.scavenge_count", 50);
-
-
- public SimpleQueueEntryList(AMQQueue queue)
- {
- _queue = queue;
- _head = new QueueEntryImpl(this);
- _tail = _head;
- }
-
- void advanceHead()
- {
- QueueEntryImpl next = _head.nextNode();
- QueueEntryImpl newNext = _head.getNext();
-
- if (next == newNext)
- {
- if (_scavenges.incrementAndGet() > _scavengeCount)
- {
- _scavenges.set(0L);
- scavenge();
- }
- }
- }
-
- void scavenge()
- {
- QueueEntryImpl next = _head.getNext();
-
- while (next != null)
- {
- next = next.getNext();
- }
- }
-
-
- public AMQQueue getQueue()
- {
- return _queue;
- }
-
-
- public QueueEntry add(ServerMessage message)
- {
- QueueEntryImpl node = createQueueEntry(message);
- for (;;)
- {
- QueueEntryImpl tail = _tail;
- QueueEntryImpl next = tail.nextNode();
- if (tail == _tail)
- {
- if (next == null)
- {
- node.setEntryId(tail.getEntryId()+1);
- if (_nextUpdater.compareAndSet(tail, null, node))
- {
- _tailUpdater.compareAndSet(this, tail, node);
-
- return node;
- }
- }
- else
- {
- _tailUpdater.compareAndSet(this,tail, next);
- }
- }
- }
- }
-
- protected QueueEntryImpl createQueueEntry(ServerMessage message)
- {
- return new QueueEntryImpl(this, message);
- }
-
- public QueueEntry next(QueueEntry node)
- {
- return ((QueueEntryImpl)node).getNext();
- }
-
-
- public static class QueueEntryIteratorImpl implements QueueEntryIterator
- {
-
- private QueueEntryImpl _lastNode;
-
- QueueEntryIteratorImpl(QueueEntryImpl startNode)
- {
- _lastNode = startNode;
- }
-
-
- public boolean atTail()
- {
- return _lastNode.nextNode() == null;
- }
-
- public QueueEntry getNode()
- {
-
- return _lastNode;
-
- }
-
- public boolean advance()
- {
-
- if(!atTail())
- {
- QueueEntryImpl nextNode = _lastNode.nextNode();
- while(nextNode.isDeleted() && nextNode.nextNode() != null)
- {
- nextNode = nextNode.nextNode();
- }
- _lastNode = nextNode;
- return true;
-
- }
- else
- {
- return false;
- }
-
- }
-
- }
-
-
- public QueueEntryIterator iterator()
- {
- return new QueueEntryIteratorImpl(_head);
- }
-
-
- public QueueEntry getHead()
- {
- return _head;
- }
-
- static class Factory implements QueueEntryListFactory
- {
-
- public QueueEntryList createQueueEntryList(AMQQueue queue)
- {
- return new SimpleQueueEntryList(queue);
- }
- }
-
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/SubFlushRunner.java b/java/broker/src/main/java/org/apache/qpid/server/queue/SubFlushRunner.java
deleted file mode 100755
index 46c1a6af9a..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/queue/SubFlushRunner.java
+++ /dev/null
@@ -1,96 +0,0 @@
-package org.apache.qpid.server.queue;
-/*
- *
- * 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.pool.ReadWriteRunnable;
-import org.apache.qpid.server.subscription.Subscription;
-import org.apache.qpid.server.logging.actors.CurrentActor;
-import org.apache.qpid.AMQException;
-import org.apache.log4j.Logger;
-
-
-class SubFlushRunner implements ReadWriteRunnable
-{
- private static final Logger _logger = Logger.getLogger(SubFlushRunner.class);
-
-
- private final Subscription _sub;
- private final String _name;
- private static final long ITERATIONS = SimpleAMQQueue.MAX_ASYNC_DELIVERIES;
-
- public SubFlushRunner(Subscription sub)
- {
- _sub = sub;
- _name = "SubFlushRunner-"+_sub;
- }
-
- public void run()
- {
-
- String originalName = Thread.currentThread().getName();
- try
- {
- Thread.currentThread().setName(_name);
-
- boolean complete = false;
- try
- {
- CurrentActor.set(_sub.getLogActor());
- complete = getQueue().flushSubscription(_sub, ITERATIONS);
-
- }
- catch (AMQException e)
- {
- _logger.error(e);
- }
- finally
- {
- CurrentActor.remove();
- }
- if (!complete && !_sub.isSuspended())
- {
- getQueue().execute(this);
- }
-
- }
- finally
- {
- Thread.currentThread().setName(originalName);
- }
-
- }
-
- private SimpleAMQQueue getQueue()
- {
- return (SimpleAMQQueue) _sub.getQueue();
- }
-
- public boolean isRead()
- {
- return false;
- }
-
- public boolean isWrite()
- {
- return true;
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/registry/ApplicationRegistry.java b/java/broker/src/main/java/org/apache/qpid/server/registry/ApplicationRegistry.java
deleted file mode 100644
index b6df0cc0a6..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/registry/ApplicationRegistry.java
+++ /dev/null
@@ -1,655 +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.registry;
-
-import java.net.InetSocketAddress;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Timer;
-import java.util.TimerTask;
-import java.util.UUID;
-
-import org.apache.commons.configuration.ConfigurationException;
-import org.apache.log4j.Logger;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.common.Closeable;
-import org.apache.qpid.common.QpidProperties;
-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.SystemConfig;
-import org.apache.qpid.server.configuration.SystemConfigImpl;
-import org.apache.qpid.server.configuration.VirtualHostConfiguration;
-import org.apache.qpid.server.logging.CompositeStartupMessageLogger;
-import org.apache.qpid.server.logging.Log4jMessageLogger;
-import org.apache.qpid.server.logging.RootMessageLogger;
-import org.apache.qpid.server.logging.SystemOutMessageLogger;
-import org.apache.qpid.server.logging.actors.AbstractActor;
-import org.apache.qpid.server.logging.actors.BrokerActor;
-import org.apache.qpid.server.logging.actors.CurrentActor;
-import org.apache.qpid.server.logging.messages.BrokerMessages;
-import org.apache.qpid.server.logging.messages.VirtualHostMessages;
-import org.apache.qpid.server.management.ManagedObjectRegistry;
-import org.apache.qpid.server.management.NoopManagedObjectRegistry;
-import org.apache.qpid.server.plugins.PluginManager;
-import org.apache.qpid.server.security.SecurityManager;
-import org.apache.qpid.server.security.auth.database.ConfigurationFilePrincipalDatabaseManager;
-import org.apache.qpid.server.security.auth.database.PrincipalDatabaseManager;
-import org.apache.qpid.server.security.auth.manager.AuthenticationManager;
-import org.apache.qpid.server.security.auth.manager.PrincipalDatabaseAuthenticationManager;
-import org.apache.qpid.server.stats.StatisticsCounter;
-import org.apache.qpid.server.transport.QpidAcceptor;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-import org.apache.qpid.server.virtualhost.VirtualHostImpl;
-import org.apache.qpid.server.virtualhost.VirtualHostRegistry;
-
-/**
- * An abstract application registry that provides access to configuration information and handles the
- * construction and caching of configurable objects.
- * <p/>
- * Subclasses should handle the construction of the "registered objects" such as the exchange registry.
- */
-public abstract class ApplicationRegistry implements IApplicationRegistry
-{
- protected static final Logger _logger = Logger.getLogger(ApplicationRegistry.class);
-
- private static Map<Integer, IApplicationRegistry> _instanceMap = new HashMap<Integer, IApplicationRegistry>();
-
- protected final ServerConfiguration _configuration;
-
- public static final int DEFAULT_INSTANCE = 1;
-
- protected final Map<InetSocketAddress, QpidAcceptor> _acceptors = new HashMap<InetSocketAddress, QpidAcceptor>();
-
- protected ManagedObjectRegistry _managedObjectRegistry;
-
- protected AuthenticationManager _authenticationManager;
-
- protected VirtualHostRegistry _virtualHostRegistry;
-
- protected SecurityManager _securityManager;
-
- protected PrincipalDatabaseManager _databaseManager;
-
- protected PluginManager _pluginManager;
-
- protected ConfigurationManager _configurationManager;
-
- protected RootMessageLogger _rootMessageLogger;
-
- protected CompositeStartupMessageLogger _startupMessageLogger;
-
- protected UUID _brokerId = UUID.randomUUID();
-
- protected QMFService _qmfService;
-
- private BrokerConfig _broker;
-
- private ConfigStore _configStore;
-
- protected String _registryName;
-
- private Timer _reportingTimer;
- private boolean _statisticsEnabled = false;
- private StatisticsCounter _messagesDelivered, _dataDelivered, _messagesReceived, _dataReceived;
-
- static
- {
- Runtime.getRuntime().addShutdownHook(new Thread(new ShutdownService()));
- }
-
- private static class ShutdownService implements Runnable
- {
- public void run()
- {
- removeAll();
- }
- }
-
- public static void initialise(IApplicationRegistry instance) throws Exception
- {
- initialise(instance, DEFAULT_INSTANCE);
- }
-
- @SuppressWarnings("finally")
- public static void initialise(IApplicationRegistry instance, int instanceID) throws Exception
- {
- if (instance != null)
- {
- _logger.info("Initialising Application Registry(" + instance + "):" + instanceID);
- _instanceMap.put(instanceID, instance);
-
- final ConfigStore store = ConfigStore.newInstance();
- store.setRoot(new SystemConfigImpl(store));
- instance.setConfigStore(store);
-
- BrokerConfig broker = new BrokerConfigAdapter(instance);
-
- SystemConfig system = (SystemConfig) store.getRoot();
- system.addBroker(broker);
- instance.setBroker(broker);
-
- try
- {
- instance.initialise(instanceID);
- }
- catch (Exception e)
- {
- _instanceMap.remove(instanceID);
- try
- {
- system.removeBroker(broker);
- }
- finally
- {
- throw e;
- }
- }
- }
- else
- {
- remove(instanceID);
- }
- }
-
- public ConfigStore getConfigStore()
- {
- return _configStore;
- }
-
- public void setConfigStore(final ConfigStore configStore)
- {
- _configStore = configStore;
- }
-
- public static boolean isConfigured()
- {
- return isConfigured(DEFAULT_INSTANCE);
- }
-
- public static boolean isConfigured(int instanceID)
- {
- return _instanceMap.containsKey(instanceID);
- }
-
- /** Method to cleanly shutdown the default registry running in this JVM */
- public static void remove()
- {
- remove(DEFAULT_INSTANCE);
- }
-
- /**
- * Method to cleanly shutdown specified registry running in this JVM
- *
- * @param instanceID the instance to shutdown
- */
- public static void remove(int instanceID)
- {
- try
- {
- IApplicationRegistry instance = _instanceMap.get(instanceID);
- if (instance != null)
- {
- if (_logger.isInfoEnabled())
- {
- _logger.info("Shutting down ApplicationRegistry(" + instanceID + "):" + instance);
- }
- instance.close();
- instance.getBroker().getSystem().removeBroker(instance.getBroker());
- }
- }
- catch (Exception e)
- {
- _logger.error("Error shutting down Application Registry(" + instanceID + "): " + e, e);
- }
- finally
- {
- _instanceMap.remove(instanceID);
- }
- }
-
- /** Method to cleanly shutdown all registries currently running in this JVM */
- public static void removeAll()
- {
- Object[] keys = _instanceMap.keySet().toArray();
- for (Object k : keys)
- {
- remove((Integer) k);
- }
- }
-
- protected ApplicationRegistry(ServerConfiguration configuration)
- {
- _configuration = configuration;
- }
-
- public void configure() throws ConfigurationException
- {
- _configurationManager = new ConfigurationManager();
-
- try
- {
- _pluginManager = new PluginManager(_configuration.getPluginDirectory(), _configuration.getCacheDirectory());
- }
- catch (Exception e)
- {
- throw new ConfigurationException(e);
- }
-
- _configuration.initialise();
- }
-
- public void initialise(int instanceID) throws Exception
- {
- //Create the RootLogger to be used during broker operation
- _rootMessageLogger = new Log4jMessageLogger(_configuration);
- _registryName = String.valueOf(instanceID);
-
- //Create the composite (log4j+SystemOut MessageLogger to be used during startup
- RootMessageLogger[] messageLoggers = {new SystemOutMessageLogger(), _rootMessageLogger};
- _startupMessageLogger = new CompositeStartupMessageLogger(messageLoggers);
-
- CurrentActor.set(new BrokerActor(_startupMessageLogger));
-
- try
- {
- configure();
-
- _qmfService = new QMFService(getConfigStore(), this);
-
- CurrentActor.get().message(BrokerMessages.STARTUP(QpidProperties.getReleaseVersion(), QpidProperties.getBuildVersion()));
-
- initialiseManagedObjectRegistry();
-
- _virtualHostRegistry = new VirtualHostRegistry(this);
-
- _securityManager = new SecurityManager(_configuration, _pluginManager);
-
- createDatabaseManager(_configuration);
-
- _authenticationManager = new PrincipalDatabaseAuthenticationManager();
-
- _databaseManager.initialiseManagement(_configuration);
-
- _managedObjectRegistry.start();
- }
- finally
- {
- CurrentActor.remove();
- }
-
- CurrentActor.set(new BrokerActor(_rootMessageLogger));
- try
- {
- initialiseVirtualHosts();
- initialiseStatistics();
- initialiseStatisticsReporting();
- }
- finally
- {
- // Startup complete, so pop the current actor
- CurrentActor.remove();
- }
- }
-
- protected void createDatabaseManager(ServerConfiguration configuration) throws Exception
- {
- _databaseManager = new ConfigurationFilePrincipalDatabaseManager(_configuration);
- }
-
- protected void initialiseVirtualHosts() throws Exception
- {
- for (String name : _configuration.getVirtualHosts())
- {
- createVirtualHost(_configuration.getVirtualHostConfig(name));
- }
- getVirtualHostRegistry().setDefaultVirtualHostName(_configuration.getDefaultVirtualHost());
- }
-
- protected void initialiseManagedObjectRegistry() throws AMQException
- {
- _managedObjectRegistry = new NoopManagedObjectRegistry();
- }
-
- public void initialiseStatisticsReporting()
- {
- long report = _configuration.getStatisticsReportingPeriod() * 1000; // convert to ms
- final boolean broker = _configuration.isStatisticsGenerationBrokerEnabled();
- final boolean virtualhost = _configuration.isStatisticsGenerationVirtualhostsEnabled();
- final boolean reset = _configuration.isStatisticsReportResetEnabled();
-
- /* add a timer task to report statistics if generation is enabled for broker or virtualhosts */
- if (report > 0L && (broker || virtualhost))
- {
- _reportingTimer = new Timer("Statistics-Reporting", true);
-
- class StatisticsReportingTask extends TimerTask
- {
- private final int DELIVERED = 0;
- private final int RECEIVED = 1;
-
- public void run()
- {
- 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();
- }
- }
-
- _reportingTimer.scheduleAtFixedRate(new StatisticsReportingTask(),
- report / 2,
- report);
- }
- }
-
- public static IApplicationRegistry getInstance()
- {
- return getInstance(DEFAULT_INSTANCE);
- }
-
- public static IApplicationRegistry getInstance(int instanceID)
- {
- synchronized (IApplicationRegistry.class)
- {
- IApplicationRegistry instance = _instanceMap.get(instanceID);
-
- if (instance == null)
- {
- throw new IllegalStateException("Application Registry (" + instanceID + ") not created");
- }
- else
- {
- return instance;
- }
- }
- }
-
- /**
- * Close non-null Closeable items and log any errors
- * @param close
- */
- private void close(Closeable close)
- {
- try
- {
- if (close != null)
- {
- close.close();
- }
- }
- catch (Throwable e)
- {
- _logger.error("Error thrown whilst closing " + close.getClass().getSimpleName(), e);
- }
- }
-
-
- public void close()
- {
- if (_logger.isInfoEnabled())
- {
- _logger.info("Shutting down ApplicationRegistry:" + this);
- }
-
- //Stop Statistics Reporting
- if (_reportingTimer != null)
- {
- _reportingTimer.cancel();
- }
-
- //Stop incoming connections
- unbind();
-
- //Shutdown virtualhosts
- close(_virtualHostRegistry);
-
-// close(_accessManager);
-//
-// close(_databaseManager);
-
- close(_authenticationManager);
-
- close(_managedObjectRegistry);
-
- close(_qmfService);
-
- close(_pluginManager);
-
- CurrentActor.get().message(BrokerMessages.STOPPED());
- }
-
- private void unbind()
- {
- synchronized (_acceptors)
- {
- for (InetSocketAddress bindAddress : _acceptors.keySet())
- {
- QpidAcceptor acceptor = _acceptors.get(bindAddress);
-
- try
- {
- acceptor.getNetworkDriver().close();
- }
- catch (Throwable e)
- {
- _logger.error("Unable to close network driver due to:" + e.getMessage());
- }
-
- CurrentActor.get().message(BrokerMessages.SHUTTING_DOWN(acceptor.toString(), bindAddress.getPort()));
- }
- }
- }
-
- public ServerConfiguration getConfiguration()
- {
- return _configuration;
- }
-
- public void addAcceptor(InetSocketAddress bindAddress, QpidAcceptor acceptor)
- {
- synchronized (_acceptors)
- {
- _acceptors.put(bindAddress, acceptor);
- }
- }
-
- public VirtualHostRegistry getVirtualHostRegistry()
- {
- return _virtualHostRegistry;
- }
-
- public SecurityManager getSecurityManager()
- {
- return _securityManager;
- }
-
- public ManagedObjectRegistry getManagedObjectRegistry()
- {
- return _managedObjectRegistry;
- }
-
- public PrincipalDatabaseManager getDatabaseManager()
- {
- return _databaseManager;
- }
-
- public AuthenticationManager getAuthenticationManager()
- {
- return _authenticationManager;
- }
-
- public PluginManager getPluginManager()
- {
- return _pluginManager;
- }
-
- public ConfigurationManager getConfigurationManager()
- {
- return _configurationManager;
- }
-
- public RootMessageLogger getRootMessageLogger()
- {
- return _rootMessageLogger;
- }
-
- public RootMessageLogger getCompositeStartupMessageLogger()
- {
- return _startupMessageLogger;
- }
-
- public UUID getBrokerId()
- {
- return _brokerId;
- }
-
- public QMFService getQMFService()
- {
- return _qmfService;
- }
-
- public BrokerConfig getBroker()
- {
- return _broker;
- }
-
- public void setBroker(final BrokerConfig broker)
- {
- _broker = broker;
- }
-
- public VirtualHost createVirtualHost(final VirtualHostConfiguration vhostConfig) throws Exception
- {
- VirtualHostImpl virtualHost = new VirtualHostImpl(this, vhostConfig);
- _virtualHostRegistry.registerVirtualHost(virtualHost);
- getBroker().addVirtualHost(virtualHost);
- return virtualHost;
- }
-
- public void registerMessageDelivered(long messageSize)
- {
- if (isStatisticsEnabled())
- {
- _messagesDelivered.registerEvent(1L);
- _dataDelivered.registerEvent(messageSize);
- }
- }
-
- public void registerMessageReceived(long messageSize, long timestamp)
- {
- if (isStatisticsEnabled())
- {
- _messagesReceived.registerEvent(1L, timestamp);
- _dataReceived.registerEvent(messageSize, timestamp);
- }
- }
-
- public StatisticsCounter getMessageReceiptStatistics()
- {
- return _messagesReceived;
- }
-
- public StatisticsCounter getDataReceiptStatistics()
- {
- return _dataReceived;
- }
-
- public StatisticsCounter getMessageDeliveryStatistics()
- {
- return _messagesDelivered;
- }
-
- public StatisticsCounter getDataDeliveryStatistics()
- {
- return _dataDelivered;
- }
-
- public void resetStatistics()
- {
- _messagesDelivered.reset();
- _dataDelivered.reset();
- _messagesReceived.reset();
- _dataReceived.reset();
-
- for (VirtualHost vhost : _virtualHostRegistry.getVirtualHosts())
- {
- vhost.resetStatistics();
- }
- }
-
- public void initialiseStatistics()
- {
- setStatisticsEnabled(!StatisticsCounter.DISABLE_STATISTICS &&
- getConfiguration().isStatisticsGenerationBrokerEnabled());
-
- _messagesDelivered = new StatisticsCounter("messages-delivered");
- _dataDelivered = new StatisticsCounter("bytes-delivered");
- _messagesReceived = new StatisticsCounter("messages-received");
- _dataReceived = new StatisticsCounter("bytes-received");
- }
-
- public boolean isStatisticsEnabled()
- {
- return _statisticsEnabled;
- }
-
- public void setStatisticsEnabled(boolean enabled)
- {
- _statisticsEnabled = enabled;
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/registry/BrokerConfigAdapter.java b/java/broker/src/main/java/org/apache/qpid/server/registry/BrokerConfigAdapter.java
deleted file mode 100644
index 4a4253153c..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/registry/BrokerConfigAdapter.java
+++ /dev/null
@@ -1,161 +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.registry;
-
-import org.apache.qpid.server.configuration.*;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-import org.apache.qpid.common.QpidProperties;
-
-import java.util.UUID;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-public class BrokerConfigAdapter implements BrokerConfig
-{
- private final IApplicationRegistry _instance;
- private SystemConfig _system;
-
- private final Map<UUID, VirtualHostConfig> _vhosts = new ConcurrentHashMap<UUID, VirtualHostConfig>();
- private final long _createTime = System.currentTimeMillis();
- private UUID _id;
- private String _federationTag;
-
- public BrokerConfigAdapter(final IApplicationRegistry instance)
- {
- _instance = instance;
- _id = instance.getConfigStore().createId();
- _federationTag = UUID.randomUUID().toString();
- }
-
- public void setSystem(final SystemConfig system)
- {
- _system = system;
- }
-
- public SystemConfig getSystem()
- {
- return _system;
- }
-
- public Integer getPort()
- {
- List ports = _instance.getConfiguration().getPorts();
- if(ports.size() > 0)
- {
- return Integer.valueOf(ports.get(0).toString());
- }
- else
- {
- return 0;
- }
- }
-
- public Integer getWorkerThreads()
- {
- return _instance.getConfiguration().getProcessors();
- }
-
- public Integer getMaxConnections()
- {
- return 0;
- }
-
- public Integer getConnectionBacklogLimit()
- {
- return 0;
- }
-
- public Long getStagingThreshold()
- {
- return 0L;
- }
-
- public Integer getManagementPublishInterval()
- {
- return 10000;
- }
-
- public String getVersion()
- {
- return QpidProperties.getReleaseVersion() + " [Build: " + QpidProperties.getBuildVersion() + "]";
- }
-
- public String getDataDirectory()
- {
- return _instance.getConfiguration().getQpidWork();
- }
-
- public void addVirtualHost(final VirtualHostConfig virtualHost)
- {
- virtualHost.setBroker(this);
- _vhosts.put(virtualHost.getId(), virtualHost);
- getConfigStore().addConfiguredObject(virtualHost);
-
- }
-
- private ConfigStore getConfigStore()
- {
- return _instance.getConfigStore();
- }
-
- public long getCreateTime()
- {
- return _createTime;
- }
-
- public void createBrokerConnection(final String transport,
- final String host,
- final int port,
- final boolean durable,
- final String authMechanism,
- final String username,
- final String password)
- {
- VirtualHost vhost = _instance.getVirtualHostRegistry().getDefaultVirtualHost();
- vhost.createBrokerConnection(transport, host, port, "", durable, authMechanism, username, password);
- }
-
- public UUID getId()
- {
- return _id;
- }
-
- public BrokerConfigType getConfigType()
- {
- return BrokerConfigType.getInstance();
- }
-
- public ConfiguredObject getParent()
- {
- return _system;
- }
-
- public boolean isDurable()
- {
- return false;
- }
-
- public String getFederationTag()
- {
- return _federationTag;
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/registry/ConfigurationFileApplicationRegistry.java b/java/broker/src/main/java/org/apache/qpid/server/registry/ConfigurationFileApplicationRegistry.java
deleted file mode 100644
index ff2a8c959b..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/registry/ConfigurationFileApplicationRegistry.java
+++ /dev/null
@@ -1,69 +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.registry;
-
-import java.io.File;
-
-import org.apache.commons.configuration.ConfigurationException;
-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;
-
-public class ConfigurationFileApplicationRegistry extends ApplicationRegistry
-{
- public ConfigurationFileApplicationRegistry(File configurationURL) throws ConfigurationException
- {
- super(new ServerConfiguration(configurationURL));
- }
-
- @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())
- {
- _managedObjectRegistry = new JMXManagedObjectRegistry();
- }
- else
- {
- _managedObjectRegistry = new NoopManagedObjectRegistry();
- }
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/registry/IApplicationRegistry.java b/java/broker/src/main/java/org/apache/qpid/server/registry/IApplicationRegistry.java
deleted file mode 100644
index 0ef55097ce..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/registry/IApplicationRegistry.java
+++ /dev/null
@@ -1,103 +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.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.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;
-import org.apache.qpid.server.security.SecurityManager;
-import org.apache.qpid.server.security.auth.database.PrincipalDatabaseManager;
-import org.apache.qpid.server.security.auth.manager.AuthenticationManager;
-import org.apache.qpid.server.stats.StatisticsGatherer;
-import org.apache.qpid.server.transport.QpidAcceptor;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-import org.apache.qpid.server.virtualhost.VirtualHostRegistry;
-
-public interface IApplicationRegistry extends StatisticsGatherer
-{
- /**
- * Initialise the application registry. All initialisation must be done in this method so that any components
- * that need access to the application registry itself for initialisation are able to use it. Attempting to
- * initialise in the constructor will lead to failures since the registry reference will not have been set.
- * @param instanceID the instanceID that we can use to identify this AR.
- */
- void initialise(int instanceID) throws Exception;
-
- /**
- * Shutdown this Registry
- */
- void close();
-
- /**
- * Get the low level configuration. For use cases where the configured object approach is not required
- * you can get the complete configuration information.
- * @return a Commons Configuration instance
- */
- ServerConfiguration getConfiguration();
-
- ManagedObjectRegistry getManagedObjectRegistry();
-
- PrincipalDatabaseManager getDatabaseManager();
-
- AuthenticationManager getAuthenticationManager();
-
- VirtualHostRegistry getVirtualHostRegistry();
-
- SecurityManager getSecurityManager();
-
- PluginManager getPluginManager();
-
- ConfigurationManager getConfigurationManager();
-
- RootMessageLogger getRootMessageLogger();
-
- /**
- * Register any acceptors for this registry
- * @param bindAddress The address that the acceptor has been bound with
- * @param acceptor The acceptor in use
- */
- void addAcceptor(InetSocketAddress bindAddress, QpidAcceptor acceptor);
-
- public UUID getBrokerId();
-
- QMFService getQMFService();
-
- void setBroker(BrokerConfig broker);
-
- BrokerConfig getBroker();
-
- VirtualHost createVirtualHost(VirtualHostConfiguration vhostConfig) throws Exception;
-
- ConfigStore getConfigStore();
-
- void setConfigStore(ConfigStore store);
-
- void initialiseStatisticsReporting();
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/AbstractPlugin.java b/java/broker/src/main/java/org/apache/qpid/server/security/AbstractPlugin.java
deleted file mode 100644
index ff80499bc2..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/AbstractPlugin.java
+++ /dev/null
@@ -1,53 +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;
-
-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;
-import org.apache.qpid.server.security.access.Operation;
-
-/**
- * This is intended as the parent for all simple plugins.
- */
-public abstract class AbstractPlugin implements SecurityPlugin
-{
- protected final Logger _logger = Logger.getLogger(getClass());
-
- protected ConfigurationPlugin _config;
-
- public Result getDefault()
- {
- return Result.ABSTAIN;
- }
-
- public abstract Result access(ObjectType object, Object instance);
-
- public abstract Result authorise(Operation operation, ObjectType object, ObjectProperties properties);
-
- public void configure(ConfigurationPlugin config)
- {
- _config = config;
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/AbstractProxyPlugin.java b/java/broker/src/main/java/org/apache/qpid/server/security/AbstractProxyPlugin.java
deleted file mode 100644
index 8b5ff6781d..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/AbstractProxyPlugin.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.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;
-
-/**
- * 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
-{
- public Result authoriseConsume(ObjectType object, ObjectProperties properties)
- {
- return getDefault();
- }
-
- public Result authorisePublish(ObjectType object, ObjectProperties properties)
- {
- return getDefault();
- }
-
- public Result authoriseCreate(ObjectType object, ObjectProperties properties)
- {
- return getDefault();
- }
-
- public Result authoriseAccess(ObjectType object, ObjectProperties properties)
- {
- return getDefault();
- }
-
- public Result authoriseBind(ObjectType object, ObjectProperties properties)
- {
- return getDefault();
- }
-
- public Result authoriseUnbind(ObjectType object, ObjectProperties properties)
- {
- return getDefault();
- }
-
- public Result authoriseDelete(ObjectType object, ObjectProperties properties)
- {
- return getDefault();
- }
-
- public Result authorisePurge(ObjectType object, ObjectProperties properties)
- {
- return getDefault();
- }
-
- public Result authoriseExecute(ObjectType object, ObjectProperties properties)
- {
- return getDefault();
- }
-
- public Result authoriseUpdate(ObjectType object, ObjectProperties properties)
- {
- return getDefault();
- }
-
- public Result accessVirtualhost(Object instance)
- {
- return getDefault();
- }
-
- @Override
- public Result access(ObjectType objectType, Object instance)
- {
- switch (objectType)
- {
- case VIRTUALHOST:
- return accessVirtualhost(instance);
- }
-
- return getDefault();
- }
-
- @Override
- public Result authorise(Operation operation, ObjectType objectType, ObjectProperties properties)
- {
- switch (operation)
- {
- case CONSUME:
- return authoriseConsume(objectType, properties);
- case PUBLISH:
- return authorisePublish(objectType, properties);
- case CREATE:
- return authoriseCreate(objectType, properties);
- case ACCESS:
- return authoriseAccess(objectType, properties);
- case BIND:
- return authoriseBind(objectType, properties);
- case UNBIND:
- return authoriseUnbind(objectType, properties);
- case DELETE:
- return authoriseDelete(objectType, properties);
- case PURGE:
- return authorisePurge(objectType, properties);
- case EXECUTE:
- return authoriseExecute(objectType, properties);
- case UPDATE:
- return authoriseUpdate(objectType, properties);
- }
-
- return getDefault();
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/PrincipalHolder.java b/java/broker/src/main/java/org/apache/qpid/server/security/PrincipalHolder.java
deleted file mode 100755
index 7e93623cab..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/PrincipalHolder.java
+++ /dev/null
@@ -1,29 +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;
-
-import java.security.Principal;
-
-public interface PrincipalHolder
-{
- /** @return a Principal that was used to authorized this session */
- Principal getPrincipal();
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/Result.java b/java/broker/src/main/java/org/apache/qpid/server/security/Result.java
deleted file mode 100644
index f79721799e..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/Result.java
+++ /dev/null
@@ -1,46 +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;
-
-/**
- * The result of a security plugin decision, normally {@link #ALLOWED} or {@link #DENIED}.
- */
-public enum Result
-{
- /**
- * The request is allowed.
- */
- ALLOWED,
-
- /**
- * The request is denied.
- */
- DENIED,
-
- /**
- * Indicates that a plugin does not handle a particular type of request.
- */
- ABSTAIN,
-
- /**
- * A plugin instance cannot make a decision on a request it is able to handle,
- * and another instance of the plugin should be checked.
- */
- DEFER;
-} \ No newline at end of file
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/SecurityManager.java b/java/broker/src/main/java/org/apache/qpid/server/security/SecurityManager.java
deleted file mode 100755
index f18c327692..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/SecurityManager.java
+++ /dev/null
@@ -1,416 +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;
-
-import static org.apache.qpid.server.security.access.ObjectType.*;
-import static org.apache.qpid.server.security.access.Operation.*;
-
-import java.net.SocketAddress;
-import java.security.Principal;
-import java.util.Arrays;
-import java.util.HashMap;
-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.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.protocol.AMQProtocolSession;
-import org.apache.qpid.server.queue.AMQQueue;
-import org.apache.qpid.server.security.access.ObjectProperties;
-import org.apache.qpid.server.security.access.Operation;
-import org.apache.qpid.server.security.auth.sasl.UsernamePrincipal;
-
-/**
- * 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 <em>OSGi</em> .jar files that export the required classes or just internal
- * objects for simpler plugins.
- *
- * @see SecurityPlugin
- */
-public class SecurityManager
-{
- private static final Logger _logger = Logger.getLogger(SecurityManager.class);
-
- /** Container for the {@link Principal} that is using to this thread. */
- private static final ThreadLocal<Principal> _principal = new ThreadLocal<Principal>();
-
- private PluginManager _pluginManager;
- private Map<String, SecurityPluginFactory> _pluginFactories = new HashMap<String, SecurityPluginFactory>();
- private Map<String, SecurityPlugin> _globalPlugins = new HashMap<String, SecurityPlugin>();
- private Map<String, SecurityPlugin> _hostPlugins = new HashMap<String, SecurityPlugin>();
-
- public static class SecurityConfiguration extends ConfigurationPlugin
- {
- public static final ConfigurationPluginFactory FACTORY = new ConfigurationPluginFactory()
- {
- public ConfigurationPlugin newInstance(String path, Configuration config) throws ConfigurationException
- {
- ConfigurationPlugin instance = new SecurityConfiguration();
- instance.setConfiguration(path, config);
- return instance;
- }
-
- public List<String> getParentPaths()
- {
- return Arrays.asList("security", "virtualhosts.virtualhost.security");
- }
- };
-
- @Override
- public String[] getElementsProcessed()
- {
- return new String[]{"security"};
- }
-
- public void validateConfiguration() throws ConfigurationException
- {
- if (_configuration.isEmpty())
- {
- throw new ConfigurationException("security section is incomplete, no elements found.");
- }
- }
- }
-
-
- public SecurityManager(SecurityManager parent) throws ConfigurationException
- {
- _pluginManager = parent._pluginManager;
- _pluginFactories = parent._pluginFactories;
-
- // our global plugins are the parent's host plugins
- _globalPlugins = parent._hostPlugins;
- }
-
- public SecurityManager(ConfigurationPlugin configuration, PluginManager manager) throws ConfigurationException
- {
- this(configuration, manager, null);
- }
-
- public SecurityManager(ConfigurationPlugin configuration, PluginManager manager, SecurityPluginFactory plugin) throws ConfigurationException
- {
- _pluginManager = manager;
- if (manager == null) // No plugin manager, no plugins
- {
- return;
- }
-
- _pluginFactories = _pluginManager.getSecurityPlugins();
- if (plugin != null)
- {
- _pluginFactories.put(plugin.getPluginName(), plugin);
- }
-
- configureHostPlugins(configuration);
- }
-
- public static Principal getThreadPrincipal()
- {
- return _principal.get();
- }
-
- public static void setThreadPrincipal(Principal principal)
- {
- _principal.set(principal);
- }
-
- public static void setThreadPrincipal(String authId)
- {
- setThreadPrincipal(new UsernamePrincipal(authId));
- }
-
- public void configureHostPlugins(ConfigurationPlugin hostConfig) throws ConfigurationException
- {
- _hostPlugins = configurePlugins(hostConfig);
- }
-
- public void configureGlobalPlugins(ConfigurationPlugin configuration) throws ConfigurationException
- {
- _globalPlugins = configurePlugins(configuration);
- }
-
- public Map<String, SecurityPlugin> configurePlugins(ConfigurationPlugin hostConfig) throws ConfigurationException
- {
- Map<String, SecurityPlugin> plugins = new HashMap<String, SecurityPlugin>();
- SecurityConfiguration securityConfig = hostConfig.getConfiguration(SecurityConfiguration.class.getName());
-
- // If we have no security Configuration then there is nothing to configure.
- if (securityConfig != null)
- {
- for (SecurityPluginFactory<?> factory : _pluginFactories.values())
- {
- SecurityPlugin plugin = factory.newInstance(securityConfig);
- if (plugin != null)
- {
- plugins.put(factory.getPluginName(), plugin);
- }
- }
- }
- return plugins;
- }
-
- public void addHostPlugin(SecurityPlugin plugin)
- {
- _hostPlugins.put(plugin.getClass().getName(), plugin);
- }
-
- public static Logger getLogger()
- {
- return _logger;
- }
-
- private abstract class AccessCheck
- {
- abstract Result allowed(SecurityPlugin plugin);
- }
-
- private boolean checkAllPlugins(AccessCheck checker)
- {
- HashMap<String, SecurityPlugin> remainingPlugins = new HashMap<String, SecurityPlugin>(_globalPlugins);
-
- for (Entry<String, SecurityPlugin> hostEntry : _hostPlugins.entrySet())
- {
- // Create set of global only plugins
- SecurityPlugin globalPlugin = remainingPlugins.get(hostEntry.getKey());
- if (globalPlugin != null)
- {
- remainingPlugins.remove(hostEntry.getKey());
- }
-
- Result host = checker.allowed(hostEntry.getValue());
-
- if (host == Result.DENIED)
- {
- // Something vetoed the access, we're done
- return false;
- }
-
- // host allow overrides global allow, so only check global on abstain or defer
- if (host != Result.ALLOWED)
- {
- if (globalPlugin == null)
- {
- if (host == Result.DEFER)
- {
- host = hostEntry.getValue().getDefault();
- }
- if (host == Result.DENIED)
- {
- return false;
- }
- }
- else
- {
- Result global = checker.allowed(globalPlugin);
- if (global == Result.DEFER)
- {
- global = globalPlugin.getDefault();
- }
- if (global == Result.ABSTAIN && host == Result.DEFER)
- {
- global = hostEntry.getValue().getDefault();
- }
- if (global == Result.DENIED)
- {
- return false;
- }
- }
- }
- }
-
- for (SecurityPlugin plugin : remainingPlugins.values())
- {
- Result remaining = checker.allowed(plugin);
- if (remaining == Result.DEFER)
- {
- remaining = plugin.getDefault();
- }
- if (remaining == Result.DENIED)
- {
- return false;
- }
- }
-
- // getting here means either allowed or abstained from all plugins
- return true;
- }
-
- public boolean authoriseBind(final Exchange exch, final AMQQueue queue, final AMQShortString routingKey)
- {
- return checkAllPlugins(new AccessCheck()
- {
- Result allowed(SecurityPlugin plugin)
- {
- return plugin.authorise(BIND, EXCHANGE, new ObjectProperties(exch, queue, routingKey));
- }
- });
- }
-
- // TODO not implemented yet, awaiting consensus
- public boolean authoriseObject(final String packageName, final String className)
- {
- return checkAllPlugins(new AccessCheck()
- {
- Result allowed(SecurityPlugin plugin)
- {
- ObjectProperties properties = new ObjectProperties();
- properties.put(ObjectProperties.Property.PACKAGE, packageName);
- properties.put(ObjectProperties.Property.CLASS, className);
- return plugin.authorise(ACCESS, OBJECT, properties);
- }
- });
- }
-
- public boolean authoriseMethod(final Operation operation, final String componentName, final String methodName)
- {
- return checkAllPlugins(new AccessCheck()
- {
- Result allowed(SecurityPlugin plugin)
- {
- ObjectProperties properties = new ObjectProperties();
- properties.setName(methodName);
- if (componentName != null)
- {
- // Only set the property if there is a component name
- properties.put(ObjectProperties.Property.COMPONENT, componentName);
- }
- return plugin.authorise(operation, METHOD, properties);
- }
- });
- }
-
- public boolean accessVirtualhost(final String vhostname, final SocketAddress remoteAddress)
- {
- return checkAllPlugins(new AccessCheck()
- {
- Result allowed(SecurityPlugin plugin)
- {
- return plugin.access(VIRTUALHOST, remoteAddress);
- }
- });
- }
-
- public boolean authoriseConsume(final AMQQueue queue)
- {
- return checkAllPlugins(new AccessCheck()
- {
- Result allowed(SecurityPlugin plugin)
- {
- return plugin.authorise(CONSUME, QUEUE, new ObjectProperties(queue));
- }
- });
- }
-
- public boolean authoriseConsume(final boolean exclusive, final boolean noAck, final boolean noLocal, final boolean nowait, final AMQQueue queue)
- {
- return checkAllPlugins(new AccessCheck()
- {
- Result allowed(SecurityPlugin plugin)
- {
- return plugin.authorise(CONSUME, QUEUE, new ObjectProperties(exclusive, noAck, noLocal, nowait, queue));
- }
- });
- }
-
- public boolean authoriseCreateExchange(final Boolean autoDelete, final Boolean durable, final AMQShortString exchangeName,
- final Boolean internal, final Boolean nowait, final Boolean passive, final AMQShortString exchangeType)
- {
- return checkAllPlugins(new AccessCheck()
- {
- Result allowed(SecurityPlugin plugin)
- {
- return plugin.authorise(CREATE, EXCHANGE, new ObjectProperties(autoDelete, durable, exchangeName,
- internal, nowait, passive, exchangeType));
- }
- });
- }
-
- public boolean authoriseCreateQueue(final Boolean autoDelete, final Boolean durable, final Boolean exclusive,
- final Boolean nowait, final Boolean passive, final AMQShortString queueName, final String owner)
- {
- return checkAllPlugins(new AccessCheck()
- {
- Result allowed(SecurityPlugin plugin)
- {
- return plugin.authorise(CREATE, QUEUE, new ObjectProperties(autoDelete, durable, exclusive, nowait, passive, queueName, owner));
- }
- });
- }
-
- public boolean authoriseDelete(final AMQQueue queue)
- {
- return checkAllPlugins(new AccessCheck()
- {
- Result allowed(SecurityPlugin plugin)
- {
- return plugin.authorise(DELETE, QUEUE, new ObjectProperties(queue));
- }
- });
- }
-
- public boolean authoriseDelete(final Exchange exchange)
- {
- return checkAllPlugins(new AccessCheck()
- {
- Result allowed(SecurityPlugin plugin)
- {
- return plugin.authorise(DELETE, EXCHANGE, new ObjectProperties(exchange.getName()));
- }
- });
- }
-
- public boolean authorisePublish(final boolean immediate, final String routingKey, final String exchangeName)
- {
- return checkAllPlugins(new AccessCheck()
- {
- Result allowed(SecurityPlugin plugin)
- {
- return plugin.authorise(PUBLISH, EXCHANGE, new ObjectProperties(exchangeName, routingKey, immediate));
- }
- });
- }
-
- public boolean authorisePurge(final AMQQueue queue)
- {
- return checkAllPlugins(new AccessCheck()
- {
- Result allowed(SecurityPlugin plugin)
- {
- return plugin.authorise(PURGE, QUEUE, new ObjectProperties(queue));
- }
- });
- }
-
- public boolean authoriseUnbind(final Exchange exch, final AMQShortString routingKey, final AMQQueue queue)
- {
- return checkAllPlugins(new AccessCheck()
- {
- Result allowed(SecurityPlugin plugin)
- {
- return plugin.authorise(UNBIND, EXCHANGE, new ObjectProperties(exch, queue, routingKey));
- }
- });
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/SecurityPlugin.java b/java/broker/src/main/java/org/apache/qpid/server/security/SecurityPlugin.java
deleted file mode 100644
index c3c06bf206..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/SecurityPlugin.java
+++ /dev/null
@@ -1,47 +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;
-
-import org.apache.qpid.server.plugins.Plugin;
-import org.apache.qpid.server.security.access.ObjectProperties;
-import org.apache.qpid.server.security.access.ObjectType;
-import org.apache.qpid.server.security.access.Operation;
-
-/**
- * The two methods, {@link #access(ObjectType, Object)} and {@link #authorise(Operation, ObjectType, ObjectProperties)},
- * return the {@link Result} of the security decision, which may be to {@link Result#ABSTAIN} if no decision is made
- * by this plugin.
- */
-public interface SecurityPlugin extends Plugin
-{
- /**
- * Default result for {@link #access(ObjectType, Object)} or {@link #authorise(Operation, ObjectType, ObjectProperties)}.
- */
- Result getDefault();
-
- /**
- * Authorise access granted to an object instance.
- */
- Result access(ObjectType objectType, Object instance);
-
- /**
- * Authorise an operation on an object defined by a set of properties.
- */
- Result authorise(Operation operation, ObjectType objectType, ObjectProperties properties);
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/SecurityPluginActivator.java b/java/broker/src/main/java/org/apache/qpid/server/security/SecurityPluginActivator.java
deleted file mode 100644
index 5ee7833c4c..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/SecurityPluginActivator.java
+++ /dev/null
@@ -1,74 +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;
-
-import org.apache.log4j.Logger;
-import org.apache.qpid.server.configuration.plugins.ConfigurationPluginFactory;
-import org.osgi.framework.BundleActivator;
-import org.osgi.framework.BundleContext;
-
-/**
- * An OSGi {@link BundleActivator} that loads a {@link SecurityPluginFactory}.
- */
-public abstract class SecurityPluginActivator implements BundleActivator
-{
- private static final Logger _logger = Logger.getLogger(SecurityPluginActivator.class);
-
- private SecurityPluginFactory _factory;
- private ConfigurationPluginFactory _config;
- private BundleContext _ctx;
- private String _bundleName;
-
- /** Implement this to return the factory this plugin activates. */
- public abstract SecurityPluginFactory getFactory();
-
- /** Implement this to return the factory this plugin activates. */
- public abstract ConfigurationPluginFactory getConfigurationFactory();
-
- /**
- * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
- */
- public void start(BundleContext ctx) throws Exception
- {
- _ctx = ctx;
- _factory = getFactory();
- _config = getConfigurationFactory();
- _bundleName = ctx.getBundle().getSymbolicName();
-
- // register the service
- _logger.info("Registering security plugin: " + _bundleName);
- _ctx.registerService(SecurityPluginFactory.class.getName(), _factory, null);
- _ctx.registerService(ConfigurationPluginFactory.class.getName(), _config, null);
- }
-
- /**
- * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
- */
- public void stop(BundleContext context) throws Exception
- {
- _logger.info("Stopping security plugin: " + _bundleName);
-
- // null object references
- _factory = null;
- _config = null;
- _ctx = null;
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/SecurityPluginFactory.java b/java/broker/src/main/java/org/apache/qpid/server/security/SecurityPluginFactory.java
deleted file mode 100644
index fe81cba282..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/SecurityPluginFactory.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.
- *
- */
-package org.apache.qpid.server.security;
-
-import org.apache.qpid.server.plugins.PluginFactory;
-
-/**
- * The factory that generates instances of security plugins. Usually implemented as a static member class in the plugin itself.
- */
-public interface SecurityPluginFactory<S extends SecurityPlugin> extends PluginFactory<S>
-{
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/access/ObjectProperties.java b/java/broker/src/main/java/org/apache/qpid/server/security/access/ObjectProperties.java
deleted file mode 100644
index 70a9ea5356..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/access/ObjectProperties.java
+++ /dev/null
@@ -1,318 +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;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-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;
-
-/**
- * An set of properties for an access control v2 rule {@link ObjectType}.
- *
- * The {@link #matches(ObjectProperties)} method is intended to be used when determining precedence of rules, and
- * {@link #equals(Object)} and {@link #hashCode()} are intended for use in maps. This is due to the wildcard matching
- * described above.
- */
-public class ObjectProperties extends HashMap<ObjectProperties.Property, String>
-{
- /** serialVersionUID */
- private static final long serialVersionUID = -1356019341374170495L;
-
- public static final String STAR= "*";
-
- public static final ObjectProperties EMPTY = new ObjectProperties();
-
- public enum Property
- {
- ROUTING_KEY,
- NAME,
- QUEUE_NAME,
- OWNER,
- TYPE,
- ALTERNATE,
- IMMEDIATE,
- INTERNAL,
- NO_WAIT,
- NO_LOCAL,
- NO_ACK,
- PASSIVE,
- DURABLE,
- EXCLUSIVE,
- TEMPORARY,
- AUTO_DELETE,
- COMPONENT,
- PACKAGE,
- CLASS;
-
- public static Property parse(String text)
- {
- for (Property property : values())
- {
- if (property.getName().equalsIgnoreCase(text))
- {
- return property;
- }
- }
- throw new IllegalArgumentException("Not a valid property: " + text);
- }
-
- public String getName()
- {
- return StringUtils.remove(name(), '_').toLowerCase();
- }
-
- public static List<String> getPropertyNames()
- {
- List<String> properties = new ArrayList<String>();
- for (Property property : values())
- {
- properties.add(property.getName());
- }
- return properties;
- }
- }
-
- public static List<String> getAllPropertyNames()
- {
- List<String> properties = new ArrayList<String>();
- for (Property property : Property.values())
- {
- properties.add(StringUtils.remove(property.name(), '_').toLowerCase());
- }
- return properties;
- }
-
- public ObjectProperties()
- {
- super();
- }
-
- public ObjectProperties(ObjectProperties copy)
- {
- super();
-
- putAll(copy);
- }
-
- public ObjectProperties(String name)
- {
- super();
-
- setName(name);
- }
-
-
- public ObjectProperties(AMQShortString name)
- {
- super();
-
- setName(name);
- }
-
- public ObjectProperties(AMQQueue queue)
- {
- super();
-
- setName(queue.getName());
-
- put(Property.AUTO_DELETE, queue.isAutoDelete());
- put(Property.TEMPORARY, queue.isAutoDelete());
- put(Property.DURABLE, queue.isDurable());
- put(Property.EXCLUSIVE, queue.isExclusive());
- if (queue.getAlternateExchange() != null)
- {
- put(Property.ALTERNATE, queue.getAlternateExchange().getName());
- }
- if (queue.getOwner() != null)
- {
- put(Property.OWNER, queue.getOwner());
- }
- else if (queue.getPrincipalHolder() != null)
- {
- put(Property.OWNER, queue.getPrincipalHolder().getPrincipal().getName());
- }
- }
-
- public ObjectProperties(Exchange exch, AMQQueue queue, AMQShortString routingKey)
- {
- this(queue);
-
- setName(exch.getName());
-
- put(Property.QUEUE_NAME, queue.getName());
- put(Property.ROUTING_KEY, routingKey);
- }
-
- public ObjectProperties(Exchange exch, AMQShortString routingKey)
- {
- this(exch.getName(), routingKey.asString());
- }
-
- public ObjectProperties(String exchangeName, String routingKey, Boolean immediate)
- {
- this(exchangeName, routingKey);
-
- put(Property.IMMEDIATE, immediate);
- }
-
- public ObjectProperties(String exchangeName, String routingKey)
- {
- super();
-
- setName(exchangeName);
-
- put(Property.ROUTING_KEY, routingKey);
- }
-
- public ObjectProperties(Boolean autoDelete, Boolean durable, AMQShortString exchangeName,
- Boolean internal, Boolean nowait, Boolean passive, AMQShortString exchangeType)
- {
- super();
-
- setName(exchangeName);
-
- put(Property.AUTO_DELETE, autoDelete);
- put(Property.TEMPORARY, autoDelete);
- put(Property.DURABLE, durable);
- put(Property.INTERNAL, internal);
- put(Property.NO_WAIT, nowait);
- put(Property.PASSIVE, passive);
- put(Property.TYPE, exchangeType);
- }
-
- public ObjectProperties(Boolean autoDelete, Boolean durable, Boolean exclusive, Boolean nowait, Boolean passive,
- AMQShortString queueName, String owner)
- {
- super();
-
- setName(queueName);
-
- put(Property.AUTO_DELETE, autoDelete);
- put(Property.TEMPORARY, autoDelete);
- put(Property.DURABLE, durable);
- put(Property.EXCLUSIVE, exclusive);
- put(Property.NO_WAIT, nowait);
- put(Property.PASSIVE, passive);
- put(Property.OWNER, owner);
- }
-
- public ObjectProperties(Boolean exclusive, Boolean noAck, Boolean noLocal, Boolean nowait, AMQQueue queue)
- {
- this(queue);
-
- put(Property.NO_LOCAL, noLocal);
- put(Property.NO_ACK, noAck);
- put(Property.EXCLUSIVE, exclusive);
- put(Property.NO_WAIT, nowait);
- }
-
- public List<String> getPropertyNames()
- {
- List<String> properties = new ArrayList<String>();
- for (Property property : keySet())
- {
- properties.add(property.getName());
- }
- return properties;
- }
-
- public Boolean isSet(Property key)
- {
- return containsKey(key) && Boolean.valueOf(get(key));
- }
-
- public String getName()
- {
- return get(Property.NAME);
- }
-
- public void setName(String name)
- {
- put(Property.NAME, name);
- }
-
- public void setName(AMQShortString name)
- {
- put(Property.NAME, name);
- }
-
- public String put(Property key, AMQShortString value)
- {
- return put(key, value == null ? "" : value.asString());
- }
-
- @Override
- public String put(Property key, String value)
- {
- return super.put(key, value == null ? "" : value.trim());
- }
-
- public void put(Property key, Boolean value)
- {
- if (value != null)
- {
- super.put(key, Boolean.toString(value));
- }
- }
-
- public boolean matches(ObjectProperties properties)
- {
- if (properties.keySet().isEmpty())
- {
- return true;
- }
-
- if (!keySet().containsAll(properties.keySet()))
- {
- return false;
- }
-
- for (Map.Entry<Property,String> entry : properties.entrySet())
- {
- Property key = entry.getKey();
- String ruleValue = entry.getValue();
-
- String thisValue = get(key);
-
- if (!valueMatches(thisValue, ruleValue))
- {
- return false;
- }
- }
-
- return true;
- }
-
- private boolean valueMatches(String thisValue, String ruleValue)
- {
- return (StringUtils.isEmpty(ruleValue)
- || StringUtils.equals(thisValue, ruleValue))
- || ruleValue.equals(STAR)
- || (ruleValue.endsWith(STAR)
- && thisValue != null
- && thisValue.length() > ruleValue.length()
- && thisValue.startsWith(ruleValue.substring(0, ruleValue.length() - 2)));
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/access/ObjectType.java b/java/broker/src/main/java/org/apache/qpid/server/security/access/ObjectType.java
deleted file mode 100644
index 7103b30283..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/access/ObjectType.java
+++ /dev/null
@@ -1,95 +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;
-
-import static org.apache.qpid.server.security.access.Operation.*;
-
-import java.util.EnumSet;
-import java.util.Set;
-
-/**
- * An enumeration of all possible object types that can form part of an access control v2 rule.
- *
- * Each object type is valid only for a certain set of {@link Operation}s, which are passed as a list to
- * the constructor, and can be checked using the {@link #isAllowed(Operation)} method.
- */
-public enum ObjectType
-{
- ALL(Operation.ALL),
- VIRTUALHOST(ACCESS),
- QUEUE(CREATE, DELETE, PURGE, CONSUME),
- TOPIC(CREATE, DELETE, PURGE, CONSUME),
- EXCHANGE(ACCESS, CREATE, DELETE, BIND, UNBIND, PUBLISH),
- LINK, // Not allowed in the Java broker
- ROUTE, // Not allowed in the Java broker
- METHOD(Operation.ALL, ACCESS, UPDATE, EXECUTE),
- OBJECT(ACCESS);
-
- private EnumSet<Operation> _actions;
-
- private ObjectType()
- {
- _actions = EnumSet.noneOf(Operation.class);
- }
-
- private ObjectType(Operation operation)
- {
- if (operation == Operation.ALL)
- {
- _actions = EnumSet.allOf(Operation.class);
- }
- else
- {
- _actions = EnumSet.of(operation);
- }
- }
-
- private ObjectType(Operation first, Operation...rest)
- {
- _actions = EnumSet.of(first, rest);
- }
-
- public Set<Operation> getActions()
- {
- return _actions;
- }
-
- public boolean isAllowed(Operation operation)
- {
- return _actions.contains(operation);
- }
-
- public static ObjectType parse(String text)
- {
- for (ObjectType object : values())
- {
- if (object.name().equalsIgnoreCase(text))
- {
- return object;
- }
- }
- throw new IllegalArgumentException("Not a valid object type: " + text);
- }
-
- public String toString()
- {
- String name = name();
- return name.charAt(0) + name.substring(1).toLowerCase();
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/access/Operation.java b/java/broker/src/main/java/org/apache/qpid/server/security/access/Operation.java
deleted file mode 100644
index 06d7f8fd0c..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/access/Operation.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.qpid.server.security.access;
-
-/**
- * An enumeration of all possible actions that can form part of an access control v2 rule.
- */
-public enum Operation
-{
- ALL,
- CONSUME,
- PUBLISH,
- CREATE,
- ACCESS,
- BIND,
- UNBIND,
- DELETE,
- PURGE,
- UPDATE,
- EXECUTE;
-
- public static Operation parse(String text)
- {
- for (Operation operation : values())
- {
- if (operation.name().equalsIgnoreCase(text))
- {
- return operation;
- }
- }
- throw new IllegalArgumentException("Not a valid operation: " + text);
- }
-
- public String toString()
- {
- String name = name();
- return name.charAt(0) + name.substring(1).toLowerCase();
- }
-} \ No newline at end of file
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/access/Permission.java b/java/broker/src/main/java/org/apache/qpid/server/security/access/Permission.java
deleted file mode 100644
index 49b3a331f9..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/access/Permission.java
+++ /dev/null
@@ -1,47 +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;
-
-import org.apache.commons.lang.StringUtils;
-
-/**
- * An enumeration of all possible permissions that can be applied to an access control v2 rule.
- */
-public enum Permission
-{
- ALLOW,
- ALLOW_LOG,
- DENY,
- DENY_LOG;
-
- public static Permission parse(String text)
- {
-
- for (Permission permission : values())
- {
- if (permission.name().equalsIgnoreCase(StringUtils.replaceChars(text, '-', '_')))
- {
- return permission;
- }
- }
- throw new IllegalArgumentException("Not a valid permission: " + text);
- }
-} \ No newline at end of file
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/access/plugins/AllowAll.java b/java/broker/src/main/java/org/apache/qpid/server/security/access/plugins/AllowAll.java
deleted file mode 100644
index db18a89231..0000000000
--- a/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<String> 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<AllowAll> FACTORY = new SecurityPluginFactory<AllowAll>()
- {
- 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<AllowAll> getPluginClass()
- {
- return AllowAll.class;
- }
- };
-
- @Override
- public Result getDefault()
- {
- return Result.ALLOWED;
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/access/plugins/BasicPlugin.java b/java/broker/src/main/java/org/apache/qpid/server/security/access/plugins/BasicPlugin.java
deleted file mode 100644
index f3161551dc..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/access/plugins/BasicPlugin.java
+++ /dev/null
@@ -1,45 +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 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.
- */
-public abstract class BasicPlugin extends AbstractPlugin
-{
- public Result access(ObjectType objectType, Object instance)
- {
- return getDefault();
- }
-
- public Result authorise(Operation operation, ObjectType objectType, ObjectProperties properties)
- {
- return getDefault();
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/access/plugins/DenyAll.java b/java/broker/src/main/java/org/apache/qpid/server/security/access/plugins/DenyAll.java
deleted file mode 100644
index 6c0fb1eaa4..0000000000
--- a/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<String> 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<DenyAll> FACTORY = new SecurityPluginFactory<DenyAll>()
- {
- 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<DenyAll> getPluginClass()
- {
- return DenyAll.class;
- }
- };
-
- @Override
- public Result getDefault()
- {
- return Result.DENIED;
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/access/plugins/LegacyAccess.java b/java/broker/src/main/java/org/apache/qpid/server/security/access/plugins/LegacyAccess.java
deleted file mode 100644
index bd99cdd1fa..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/access/plugins/LegacyAccess.java
+++ /dev/null
@@ -1,87 +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.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. */
-public class LegacyAccess extends BasicPlugin
-{
- public static class LegacyAccessConfiguration extends ConfigurationPlugin {
- public static final ConfigurationPluginFactory FACTORY = new ConfigurationPluginFactory()
- {
- public List<String> 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");
- }
-
- public ConfigurationPlugin newInstance(String path, Configuration config) throws ConfigurationException
- {
- ConfigurationPlugin instance = new LegacyAccessConfiguration();
- instance.setConfiguration(path, config);
- return instance;
- }
- };
-
- public String[] getElementsProcessed()
- {
- return new String[] { "" };
- }
- }
-
- public static final SecurityPluginFactory<LegacyAccess> FACTORY = new SecurityPluginFactory<LegacyAccess>()
- {
- public LegacyAccess newInstance(ConfigurationPlugin config) throws ConfigurationException
- {
- LegacyAccessConfiguration configuration = config.getConfiguration(LegacyAccessConfiguration.class.getName());
-
- // If there is no configuration for this plugin then don't load it.
- if (configuration == null)
- {
- return null;
- }
-
- LegacyAccess plugin = new LegacyAccess();
- plugin.configure(configuration);
- return plugin;
- }
-
- public String getPluginName()
- {
- return LegacyAccess.class.getName();
- }
-
- public Class<LegacyAccess> getPluginClass()
- {
- return LegacyAccess.class;
- }
- };
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/AuthenticationResult.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/AuthenticationResult.java
deleted file mode 100644
index 62967ef7eb..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/AuthenticationResult.java
+++ /dev/null
@@ -1,61 +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.auth;
-
-public class AuthenticationResult
-{
- public enum AuthenticationStatus
- {
- SUCCESS, CONTINUE, ERROR
- }
-
- public AuthenticationStatus status;
- public byte[] challenge;
-
- private Exception cause;
-
- public AuthenticationResult(AuthenticationStatus status)
- {
- this(null, status, null);
- }
-
- public AuthenticationResult(byte[] challenge, AuthenticationStatus status)
- {
- this(challenge, status, null);
- }
-
- public AuthenticationResult(AuthenticationStatus error, Exception cause)
- {
- this(null, error, cause);
- }
-
- public AuthenticationResult(byte[] challenge, AuthenticationStatus status, Exception cause)
- {
- this.status = status;
- this.challenge = challenge;
- this.cause = cause;
- }
-
- public Exception getCause()
- {
- return cause;
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/Base64MD5PasswordFilePrincipalDatabase.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/Base64MD5PasswordFilePrincipalDatabase.java
deleted file mode 100644
index 5a92b33e43..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/Base64MD5PasswordFilePrincipalDatabase.java
+++ /dev/null
@@ -1,567 +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.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 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.
- *
- * The file is expected to be in the form: username:password username1:password1 ... usernamen:passwordn
- *
- * where a carriage return separates each username/password pair. Passwords are assumed to be in plain text.
- */
-public class Base64MD5PasswordFilePrincipalDatabase implements PrincipalDatabase
-{
- private static final Logger _logger = Logger.getLogger(Base64MD5PasswordFilePrincipalDatabase.class);
-
- private File _passwordFile;
-
- private Pattern _regexp = Pattern.compile(":");
-
- private Map<String, AuthenticationProviderInitialiser> _saslServers;
-
- AMQUserManagementMBean _mbean;
- public static final String DEFAULT_ENCODING = "utf-8";
- private Map<String, HashedUser> _users = new HashMap<String, HashedUser>();
- private ReentrantLock _userUpdate = new ReentrantLock();
-
- public Base64MD5PasswordFilePrincipalDatabase()
- {
- _saslServers = new HashMap<String, AuthenticationProviderInitialiser>();
-
- /**
- * Create Authenticators for MD5 Password file.
- */
-
- // 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
- *
- * @param principal The principal to authenticate
- * @param password The password to check
- *
- * @return true if password is correct
- *
- * @throws AccountNotFoundException if the principal cannot be found
- */
- public boolean verifyPassword(String principal, char[] password) throws AccountNotFoundException
- {
- char[] pwd = lookupPassword(principal);
-
- if (pwd == null)
- {
- throw new AccountNotFoundException("Unable to lookup the specfied users password");
- }
-
- byte[] byteArray = new byte[password.length];
- int index = 0;
- for (char c : password)
- {
- byteArray[index++] = (byte) c;
- }
-
- byte[] MD5byteArray;
- try
- {
- MD5byteArray = HashedUser.getMD5(byteArray);
- }
- catch (Exception e1)
- {
- _logger.warn("Unable to hash password for user '" + principal + "' for comparison");
- return false;
- }
-
- char[] hashedPassword = new char[MD5byteArray.length];
-
- index = 0;
- for (byte c : MD5byteArray)
- {
- hashedPassword[index++] = (char) c;
- }
-
- 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
- {
- 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;
- }
- }
-
- 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<String, AuthenticationProviderInitialiser> getMechanisms()
- {
- return _saslServers;
- }
-
- public List<Principal> getUsers()
- {
- return new LinkedList<Principal>(_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 <b>not</b> 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)
- {
- 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();
- }
- }
-
- public void reload() throws IOException
- {
- loadPasswordFile();
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/ConfigurationFilePrincipalDatabaseManager.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/ConfigurationFilePrincipalDatabaseManager.java
deleted file mode 100644
index e9276e1b0e..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/ConfigurationFilePrincipalDatabaseManager.java
+++ /dev/null
@@ -1,194 +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.auth.database;
-
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.lang.reflect.Method;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.commons.configuration.Configuration;
-import org.apache.commons.configuration.ConfigurationException;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.configuration.PropertyUtils;
-import org.apache.qpid.configuration.PropertyException;
-import org.apache.qpid.server.configuration.ServerConfiguration;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-import org.apache.qpid.server.security.auth.database.PrincipalDatabase;
-import org.apache.qpid.server.security.auth.database.PrincipalDatabaseManager;
-import org.apache.qpid.server.security.auth.management.AMQUserManagementMBean;
-import org.apache.qpid.AMQException;
-
-import javax.management.JMException;
-
-public class ConfigurationFilePrincipalDatabaseManager implements PrincipalDatabaseManager
-{
- private static final Logger _logger = Logger.getLogger(ConfigurationFilePrincipalDatabaseManager.class);
-
- Map<String, PrincipalDatabase> _databases;
-
- public ConfigurationFilePrincipalDatabaseManager(ServerConfiguration _configuration) throws Exception
- {
- _logger.info("Initialising PrincipalDatabase authentication manager");
- _databases = initialisePrincipalDatabases(_configuration);
- }
-
- private Map<String, PrincipalDatabase> initialisePrincipalDatabases(ServerConfiguration _configuration) throws Exception
- {
- List<String> databaseNames = _configuration.getPrincipalDatabaseNames();
- List<String> databaseClasses = _configuration.getPrincipalDatabaseClass();
- Map<String, PrincipalDatabase> databases = new HashMap<String, PrincipalDatabase>();
-
- if (databaseNames.size() == 0)
- {
- _logger.warn("No Principal databases specified. Broker running with NO AUTHENTICATION");
- }
-
- for (int i = 0; i < databaseNames.size(); i++)
- {
- Object o;
- try
- {
- o = Class.forName(databaseClasses.get(i)).newInstance();
- }
- catch (Exception e)
- {
- throw new Exception("Error initialising principal database: " + e, e);
- }
-
- if (!(o instanceof PrincipalDatabase))
- {
- throw new Exception("Principal databases must implement the PrincipalDatabase interface");
- }
-
- initialisePrincipalDatabase((PrincipalDatabase) o, _configuration, i);
-
- String name = databaseNames.get(i);
- if ((name == null) || (name.length() == 0))
- {
- throw new Exception("Principal database names must have length greater than or equal to one character");
- }
-
- PrincipalDatabase pd = databases.get(name);
- if (pd != null)
- {
- throw new Exception("Duplicate principal database name not permitted");
- }
-
- _logger.info("Initialised principal database '" + name + "' successfully");
- databases.put(name, (PrincipalDatabase) o);
- }
-
- return databases;
- }
-
- private void initialisePrincipalDatabase(PrincipalDatabase principalDatabase, ServerConfiguration _configuration, int index)
- throws FileNotFoundException, ConfigurationException
- {
- List<String> argumentNames = _configuration.getPrincipalDatabaseAttributeNames(index);
- List<String> argumentValues = _configuration.getPrincipalDatabaseAttributeValues(index);
- for (int i = 0; i < argumentNames.size(); i++)
- {
- String argName = argumentNames.get(i);
- if ((argName == null) || (argName.length() == 0))
- {
- throw new ConfigurationException("Argument names must have length >= 1 character");
- }
-
- if (Character.isLowerCase(argName.charAt(0)))
- {
- argName = Character.toUpperCase(argName.charAt(0)) + argName.substring(1);
- }
-
- String methodName = "set" + argName;
- Method method = null;
- try
- {
- method = principalDatabase.getClass().getMethod(methodName, String.class);
- }
- catch (Exception e)
- {
- // do nothing.. as on error method will be null
- }
-
- if (method == null)
- {
- throw new ConfigurationException("No method " + methodName + " found in class "
- + principalDatabase.getClass()
- + " hence unable to configure principal database. The method must be public and "
- + "have a single String argument with a void return type");
- }
-
- try
- {
- method.invoke(principalDatabase, PropertyUtils.replaceProperties(argumentValues.get(i)));
- }
- catch (Exception ite)
- {
- if (ite instanceof ConfigurationException)
- {
- throw(ConfigurationException) ite;
- }
- else
- {
- throw new ConfigurationException(ite.getMessage(), ite);
- }
- }
- }
- }
-
- public Map<String, PrincipalDatabase> getDatabases()
- {
- return _databases;
- }
-
- public void initialiseManagement(ServerConfiguration config) throws ConfigurationException
- {
- try
- {
- AMQUserManagementMBean _mbean = new AMQUserManagementMBean();
-
- List<String> principalDBs = config.getManagementPrincipalDBs();
- if (principalDBs.isEmpty())
- {
- throw new ConfigurationException("No principal-database specified for jmx security");
- }
-
- String databaseName = principalDBs.get(0);
- PrincipalDatabase database = getDatabases().get(databaseName);
- if (database == null)
- {
- throw new ConfigurationException("Principal-database '" + databaseName + "' not found");
- }
-
- _mbean.setPrincipalDatabase(database);
- _mbean.register();
- }
- catch (JMException e)
- {
- _logger.warn("User management disabled as unable to create MBean:" + e);
- }
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/HashedUser.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/HashedUser.java
deleted file mode 100644
index 3690e7f92a..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/HashedUser.java
+++ /dev/null
@@ -1,169 +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.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
-{
- private static final Logger _logger = Logger.getLogger(HashedUser.class);
-
- String _name;
- char[] _password;
- byte[] _encodedPassword = null;
- private boolean _modified = false;
- private boolean _deleted = false;
-
- HashedUser(String[] data) throws UnsupportedEncodingException
- {
- if (data.length != 2)
- {
- throw new IllegalArgumentException("User Data should be length 2, username, password");
- }
-
- _name = data[0];
-
- byte[] encoded_password = data[1].getBytes(Base64MD5PasswordFilePrincipalDatabase.DEFAULT_ENCODING);
-
- Base64 b64 = new Base64();
- byte[] decoded = b64.decode(encoded_password);
-
- _encodedPassword = encoded_password;
-
- _password = new char[decoded.length];
-
- int index = 0;
- for (byte c : decoded)
- {
- _password[index++] = (char) c;
- }
- }
-
- public HashedUser(String name, char[] password) throws UnsupportedEncodingException, NoSuchAlgorithmException
- {
- _name = name;
- setPassword(password,false);
- }
-
- public static byte[] getMD5(byte[] data) throws NoSuchAlgorithmException, UnsupportedEncodingException
- {
- MessageDigest md = MessageDigest.getInstance("MD5");
-
- for (byte b : data)
- {
- md.update(b);
- }
-
- return md.digest();
- }
-
- public String getName()
- {
- return _name;
- }
-
- public String toString()
- {
- return _name;
- }
-
- char[] getPassword()
- {
- return _password;
- }
-
- void setPassword(char[] password, boolean alreadyHashed) throws UnsupportedEncodingException, NoSuchAlgorithmException
- {
- if(alreadyHashed){
- _password = password;
- }
- else
- {
- byte[] byteArray = new byte[password.length];
- int index = 0;
- for (char c : password)
- {
- byteArray[index++] = (byte) c;
- }
-
- byte[] MD5byteArray = getMD5(byteArray);
-
- _password = new char[MD5byteArray.length];
-
- index = 0;
- for (byte c : MD5byteArray)
- {
- _password[index++] = (char) c;
- }
- }
-
- _modified = true;
- _encodedPassword = null;
- }
-
- byte[] getEncodedPassword() throws EncoderException, UnsupportedEncodingException, NoSuchAlgorithmException
- {
- if (_encodedPassword == null)
- {
- encodePassword();
- }
- return _encodedPassword;
- }
-
- private void encodePassword() throws EncoderException, UnsupportedEncodingException, NoSuchAlgorithmException
- {
- byte[] byteArray = new byte[_password.length];
- int index = 0;
- for (char c : _password)
- {
- byteArray[index++] = (byte) c;
- }
- _encodedPassword = (new Base64()).encode(byteArray);
- }
-
- public boolean isModified()
- {
- return _modified;
- }
-
- public boolean isDeleted()
- {
- return _deleted;
- }
-
- public void delete()
- {
- _deleted = true;
- }
-
- public void saved()
- {
- _modified = false;
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PlainPasswordFilePrincipalDatabase.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PlainPasswordFilePrincipalDatabase.java
deleted file mode 100644
index 76ebea0321..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PlainPasswordFilePrincipalDatabase.java
+++ /dev/null
@@ -1,503 +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.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.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.
- *
- * The file is expected to be in the form: username:password username1:password1 ... usernamen:passwordn
- *
- * where a carriage return separates each username/password pair. Passwords are assumed to be in plain text.
- */
-public class PlainPasswordFilePrincipalDatabase implements PrincipalDatabase
-{
- 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<String, AuthenticationProviderInitialiser> _saslServers;
-
- private Map<String, PlainUser> _users = new HashMap<String, PlainUser>();
- private ReentrantLock _userUpdate = new ReentrantLock();
-
- public PlainPasswordFilePrincipalDatabase()
- {
- _saslServers = new HashMap<String, AuthenticationProviderInitialiser>();
-
- /**
- * Create Authenticators for Plain Password file.
- */
-
- // Accept AMQPlain incomming and compare it to the file.
- AmqPlainInitialiser amqplain = new AmqPlainInitialiser();
- amqplain.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);
- }
-
- 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();
- }
-
- /**
- * 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
- *
- * @param principal The principal to authenticate
- * @param password The plaintext password to check
- *
- * @return true if password is correct
- *
- * @throws AccountNotFoundException if the principal cannot be found
- */
- public boolean verifyPassword(String principal, char[] password) throws AccountNotFoundException
- {
-
- char[] pwd = lookupPassword(principal);
-
- if (pwd == null)
- {
- throw new AccountNotFoundException("Unable to lookup the specfied users password");
- }
-
- return compareCharArray(pwd, password);
-
- }
-
- /**
- * 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
- {
- 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();
- }
- }
-
- 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
- {
- 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;
- }
-
- public Map<String, AuthenticationProviderInitialiser> getMechanisms()
- {
- return _saslServers;
- }
-
- public List<Principal> getUsers()
- {
- return new LinkedList<Principal>(_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 <b>not</b> 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;
-
- 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;
- }
-
- 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 (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();
- }
- }
-
- public void reload() throws IOException
- {
- loadPasswordFile();
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PlainUser.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PlainUser.java
deleted file mode 100644
index 46a78a55aa..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PlainUser.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.security.auth.database;
-
-import org.apache.log4j.Logger;
-
-import java.security.Principal;
-
-public class PlainUser implements Principal
-{
- private String _name;
- private char[] _password;
- private boolean _modified = false;
- private boolean _deleted = false;
-
- PlainUser(String[] data)
- {
- if (data.length != 2)
- {
- throw new IllegalArgumentException("User Data should be length 2, username, password");
- }
-
- _name = data[0];
-
- _password = data[1].toCharArray();
-
- }
-
- public PlainUser(String name, char[] password)
- {
- _name = name;
- _password = password;
- _modified = true;
- }
-
- public String getName()
- {
- return _name;
- }
-
- public String toString()
- {
- return _name;
- }
-
- char[] getPassword()
- {
- return _password;
- }
-
- byte[] getPasswordBytes()
- {
- byte[] byteArray = new byte[_password.length];
- int index = 0;
- for (char c : _password)
- {
- byteArray[index++] = (byte) c;
- }
- return byteArray;
- }
-
- void setPassword(char[] password)
- {
- _password = password;
- _modified = true;
- }
-
- public boolean isModified()
- {
- return _modified;
- }
-
- public boolean isDeleted()
- {
- return _deleted;
- }
-
- public void delete()
- {
- _deleted = true;
- }
-
- public void saved()
- {
- _modified = false;
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PrincipalDatabase.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PrincipalDatabase.java
deleted file mode 100644
index ef37e043a6..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PrincipalDatabase.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.security.auth.database;
-
-import org.apache.qpid.server.security.auth.sasl.AuthenticationProviderInitialiser;
-
-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;
-
-/** Represents a "user database" which is really a way of storing principals (i.e. usernames) and passwords. */
-public interface PrincipalDatabase
-{
- /**
- * Set the password for a given principal in the specified callback. This is used for certain SASL providers. The
- * user database implementation should look up the password in any way it chooses and set it in the callback by
- * calling its setPassword method.
- *
- * @param principal the principal
- * @param callback the password callback that wants to receive the password
- *
- * @throws AccountNotFoundException if the account for specified principal could not be found
- * @throws IOException if there was an error looking up the principal
- */
- void setPassword(Principal principal, PasswordCallback callback)
- throws IOException, AccountNotFoundException;
-
- /**
- * Used to verify that the presented Password is correct. Currently only used by Management Console
- * @param principal The principal to authenticate
- * @param password The password to check
- * @return true if password is correct
- * @throws AccountNotFoundException if the principal cannot be found
- */
- boolean verifyPassword(String principal, char[] password)
- throws AccountNotFoundException;
-
- /**
- * Update(Change) the password for the given principal
- * @param principal Who's password is to be changed
- * @param password The new password to use
- * @return True if change was successful
- * @throws AccountNotFoundException If the given principal doesn't exist in the Database
- */
- boolean updatePassword(Principal principal, char[] password)
- throws AccountNotFoundException;
-
- /**
- * Create a new principal in the database
- * @param principal The principal to create
- * @param password The password to set for the principal
- * @return True on a successful creation
- */
- boolean createPrincipal(Principal principal, char[] password);
-
- /**
- * Delete a principal
- * @param principal The principal to delete
- * @return True on a successful creation
- * @throws AccountNotFoundException If the given principal doesn't exist in the Database
- */
- boolean deletePrincipal(Principal principal)
- throws AccountNotFoundException;
-
- /**
- * Get the principal from the database with the given username
- * @param username of the principal to lookup
- * @return The Principal object for the given username or null if not found.
- */
- Principal getUser(String username);
-
- /**
- * Reload the database to its ensure contents are up to date
- * @throws IOException If there was an error reloading the database
- */
- void reload() throws IOException;
-
- public Map<String, AuthenticationProviderInitialiser> getMechanisms();
-
-
- List<Principal> getUsers();
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PrincipalDatabaseManager.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PrincipalDatabaseManager.java
deleted file mode 100644
index f9882f8810..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PrincipalDatabaseManager.java
+++ /dev/null
@@ -1,35 +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.auth.database;
-
-import org.apache.qpid.server.configuration.ServerConfiguration;
-import org.apache.qpid.server.security.auth.database.PrincipalDatabase;
-import org.apache.commons.configuration.Configuration;
-import org.apache.commons.configuration.ConfigurationException;
-
-import java.util.Map;
-
-public interface PrincipalDatabaseManager
-{
- public Map<String, PrincipalDatabase> getDatabases();
-
- public void initialiseManagement(ServerConfiguration _configuration) throws ConfigurationException;
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PropertiesPrincipalDatabase.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PropertiesPrincipalDatabase.java
deleted file mode 100644
index ff8851306f..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PropertiesPrincipalDatabase.java
+++ /dev/null
@@ -1,169 +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.auth.database;
-
-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.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.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;
-
-public class PropertiesPrincipalDatabase implements PrincipalDatabase
-{
- private Properties _users;
-
- private Map<String, AuthenticationProviderInitialiser> _saslServers;
-
- public PropertiesPrincipalDatabase(Properties users)
- {
- _users = users;
-
- _saslServers = new HashMap<String, AuthenticationProviderInitialiser>();
-
- /**
- * Create Authenticators for Properties Principal Database.
- */
-
- // Accept MD5 incomming and use plain comparison with the file
- PlainInitialiser cram = new PlainInitialiser();
- cram.initialise(this);
- // Accept Plain incomming and hash it for comparison to the file.
- CRAMMD5Initialiser plain = new CRAMMD5Initialiser();
- plain.initialise(this, CRAMMD5Initialiser.HashDirection.INCOMMING);
-
- _saslServers.put(plain.getMechanismName(), cram);
- _saslServers.put(cram.getMechanismName(), plain);
- }
-
- public void setPassword(Principal principal, PasswordCallback callback) throws IOException, AccountNotFoundException
- {
- if (principal == null)
- {
- throw new IllegalArgumentException("principal must not be null");
- }
-
-
-
- final String pwd = _users.getProperty(principal.getName());
-
- if (pwd != null)
- {
- callback.setPassword(pwd.toCharArray());
- }
- else
- {
- throw new AccountNotFoundException("No account found for principal " + principal);
- }
- }
-
- public boolean verifyPassword(String principal, char[] password) throws AccountNotFoundException
- {
- //fixme this is not correct as toCharArray is not safe based on the type of string.
- char[] pwd = _users.getProperty(principal).toCharArray();
-
- return compareCharArray(pwd, password);
- }
-
- public boolean updatePassword(Principal principal, char[] password) throws AccountNotFoundException
- {
- return false; // updates denied
- }
-
- public boolean createPrincipal(Principal principal, char[] password)
- {
- return false; // updates denied
- }
-
- public boolean deletePrincipal(Principal principal) throws AccountNotFoundException
- {
- return false; // updates denied
- }
-
- 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;
- }
-
- private char[] convertPassword(String password) throws UnsupportedEncodingException
- {
- byte[] passwdBytes = password.getBytes("utf-8");
-
- char[] passwd = new char[passwdBytes.length];
-
- int index = 0;
-
- for (byte b : passwdBytes)
- {
- passwd[index++] = (char) b;
- }
-
- return passwd;
- }
-
-
- public Map<String, AuthenticationProviderInitialiser> getMechanisms()
- {
- return _saslServers;
- }
-
- public List<Principal> getUsers()
- {
- return new LinkedList<Principal>(); //todo
- }
-
- public Principal getUser(String username)
- {
- if (_users.getProperty(username) != null)
- {
- return new UsernamePrincipal(username);
- }
- else
- {
- return null;
- }
- }
-
- public void reload() throws IOException
- {
- //No file to update from, so do nothing.
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PropertiesPrincipalDatabaseManager.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PropertiesPrincipalDatabaseManager.java
deleted file mode 100644
index 8658101cd8..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PropertiesPrincipalDatabaseManager.java
+++ /dev/null
@@ -1,49 +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.auth.database;
-
-import org.apache.commons.configuration.ConfigurationException;
-import org.apache.qpid.server.configuration.ServerConfiguration;
-
-import java.util.Map;
-import java.util.Properties;
-import java.util.HashMap;
-
-public class PropertiesPrincipalDatabaseManager implements PrincipalDatabaseManager
-{
-
- Map<String, PrincipalDatabase> _databases = new HashMap<String, PrincipalDatabase>();
-
- public PropertiesPrincipalDatabaseManager(String name, Properties users)
- {
- _databases.put(name, new PropertiesPrincipalDatabase(users));
- }
-
- public Map<String, PrincipalDatabase> getDatabases()
- {
- return _databases;
- }
-
- public void initialiseManagement(ServerConfiguration _configuration) throws ConfigurationException
- {
- //todo
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/management/AMQUserManagementMBean.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/management/AMQUserManagementMBean.java
deleted file mode 100644
index a839315bcc..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/management/AMQUserManagementMBean.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.server.security.auth.management;
-
-import java.io.IOException;
-import java.security.Principal;
-import java.util.List;
-
-import javax.management.JMException;
-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 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;
-
-/** MBean class for AMQUserManagementMBean. It implements all the management features exposed for managing users. */
-@MBeanDescription("User Management Interface")
-public class AMQUserManagementMBean extends AMQManagedObject implements UserManagement
-{
- private static final Logger _logger = Logger.getLogger(AMQUserManagementMBean.class);
-
- private PrincipalDatabase _principalDatabase;
-
- // Setup for the TabularType
- private static final TabularType _userlistDataType; // Datatype for representing User Lists
- private static final CompositeType _userDataType; // Composite type for representing User
-
- static
- {
- OpenType[] userItemTypes = new OpenType[4]; // User item types.
- userItemTypes[0] = SimpleType.STRING; // For Username
- userItemTypes[1] = SimpleType.BOOLEAN; // For Rights - Read - No longer in use
- userItemTypes[2] = SimpleType.BOOLEAN; // For Rights - Write - No longer in use
- userItemTypes[3] = SimpleType.BOOLEAN; // For Rights - Admin - No longer is use
-
- try
- {
- _userDataType =
- new CompositeType("User", "User Data", COMPOSITE_ITEM_NAMES.toArray(new String[COMPOSITE_ITEM_NAMES.size()]),
- COMPOSITE_ITEM_DESCRIPTIONS.toArray(new String[COMPOSITE_ITEM_DESCRIPTIONS.size()]), userItemTypes);
-
- _userlistDataType = new TabularType("Users", "List of users", _userDataType, TABULAR_UNIQUE_INDEX.toArray(new String[TABULAR_UNIQUE_INDEX.size()]));
- }
- catch (OpenDataException e)
- {
- _logger.error("Tabular data setup for viewing users incorrect.", e);
- throw new ExceptionInInitializerError("Tabular data setup for viewing users incorrect");
- }
- }
-
- public AMQUserManagementMBean() throws JMException
- {
- super(UserManagement.class, UserManagement.TYPE);
- }
-
- public String getObjectInstanceName()
- {
- return UserManagement.TYPE;
- }
-
- public boolean setPassword(String username, String password)
- {
- return setPassword(username, password.toCharArray());
- }
-
- public boolean setPassword(String username, char[] password)
- {
- try
- {
- //delegate password changes to the Principal Database
- return _principalDatabase.updatePassword(new UsernamePrincipal(username), password);
- }
- catch (AccountNotFoundException e)
- {
- _logger.warn("Attempt to set password of non-existent user'" + username + "'");
- return false;
- }
- }
-
- public boolean setRights(String username, boolean read, boolean write, boolean admin)
- {
- throw new UnsupportedOperationException("Support for setting access rights no longer supported.");
- }
-
- public boolean createUser(String username, String password)
- {
- if (_principalDatabase.createPrincipal(new UsernamePrincipal(username), password.toCharArray()))
- {
- return true;
- }
-
- return false;
- }
-
- public boolean createUser(String username, String password, boolean read, boolean write, boolean admin)
- {
- if (read || write || admin)
- {
- throw new UnsupportedOperationException("Support for setting access rights to true no longer supported.");
- }
- return createUser(username, password);
- }
-
- public boolean createUser(String username, char[] password, boolean read, boolean write, boolean admin)
- {
- return createUser(username, new String(password), read, write, admin);
- }
-
- public boolean deleteUser(String username)
- {
- try
- {
- _principalDatabase.deletePrincipal(new UsernamePrincipal(username));
- }
- catch (AccountNotFoundException e)
- {
- _logger.warn("Attempt to delete user (" + username + ") that doesn't exist");
- return false;
- }
-
- return true;
- }
-
- public boolean reloadData()
- {
- try
- {
- _principalDatabase.reload();
- }
- catch (IOException e)
- {
- _logger.warn("Reload failed due to:", e);
- return false;
- }
- // Reload successful
- return true;
- }
-
-
- @MBeanOperation(name = "viewUsers", description = "All users that are currently available to the system.")
- public TabularData viewUsers()
- {
- List<Principal> users = _principalDatabase.getUsers();
-
- TabularDataSupport userList = new TabularDataSupport(_userlistDataType);
-
- try
- {
- // Create the tabular list of message header contents
- for (Principal user : users)
- {
- // Create header attributes list
-
- // Read,Write,Admin items are depcreated and we return always false.
- Object[] itemData = {user.getName(), false, false, false};
- CompositeData messageData = new CompositeDataSupport(_userDataType, COMPOSITE_ITEM_NAMES.toArray(new String[COMPOSITE_ITEM_NAMES.size()]), itemData);
- userList.put(messageData);
- }
- }
- catch (OpenDataException e)
- {
- _logger.warn("Unable to create user list due to :", e);
- return null;
- }
-
- return userList;
- }
-
- /*** Broker Methods **/
-
- /**
- * setPrincipalDatabase
- *
- * @param database set The Database to use for user lookup
- */
- public void setPrincipalDatabase(PrincipalDatabase database)
- {
- _principalDatabase = database;
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/manager/AuthenticationManager.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/manager/AuthenticationManager.java
deleted file mode 100644
index 39e1e07c57..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/manager/AuthenticationManager.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.security.auth.manager;
-
-import javax.security.sasl.SaslException;
-import javax.security.sasl.SaslServer;
-
-import org.apache.qpid.common.Closeable;
-import org.apache.qpid.server.security.auth.AuthenticationResult;
-
-/**
- * The AuthenticationManager class is the entity responsible for
- * determining the authenticity of user credentials.
- */
-public interface AuthenticationManager extends Closeable
-{
- String getMechanisms();
-
- SaslServer createSaslServer(String mechanism, String localFQDN) throws SaslException;
-
- AuthenticationResult authenticate(SaslServer server, byte[] response);
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/manager/PrincipalDatabaseAuthenticationManager.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/manager/PrincipalDatabaseAuthenticationManager.java
deleted file mode 100644
index d10ad2c170..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/manager/PrincipalDatabaseAuthenticationManager.java
+++ /dev/null
@@ -1,184 +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.auth.manager;
-
-import org.apache.log4j.Logger;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-import org.apache.qpid.server.security.auth.manager.AuthenticationManager;
-import org.apache.qpid.server.security.auth.database.PrincipalDatabase;
-import org.apache.qpid.server.security.auth.sasl.JCAProvider;
-import org.apache.qpid.server.security.auth.sasl.AuthenticationProviderInitialiser;
-import org.apache.qpid.server.security.auth.AuthenticationResult;
-
-import javax.security.auth.callback.CallbackHandler;
-import javax.security.sasl.SaslServerFactory;
-import javax.security.sasl.SaslServer;
-import javax.security.sasl.SaslException;
-import javax.security.sasl.Sasl;
-import java.util.Map;
-import java.util.HashMap;
-import java.util.TreeMap;
-import java.security.Security;
-
-/**
- * Concrete implementation of the AuthenticationManager that determines if supplied
- * user credentials match those appearing in a PrincipalDatabase.
- *
- */
-public class PrincipalDatabaseAuthenticationManager implements AuthenticationManager
-{
- private static final Logger _logger = Logger.getLogger(PrincipalDatabaseAuthenticationManager.class);
-
- /** The list of mechanisms, in the order in which they are configured (i.e. preferred order) */
- private String _mechanisms;
-
- /** Maps from the mechanism to the callback handler to use for handling those requests */
- private Map<String, CallbackHandler> _callbackHandlerMap = new HashMap<String, CallbackHandler>();
-
- /**
- * Maps from the mechanism to the properties used to initialise the server. See the method Sasl.createSaslServer for
- * details of the use of these properties. This map is populated during initialisation of each provider.
- */
- private Map<String, Map<String, ?>> _serverCreationProperties = new HashMap<String, Map<String, ?>>();
-
- /** The name for the required SASL Server mechanisms */
- public static final String PROVIDER_NAME= "AMQSASLProvider-Server";
-
- public PrincipalDatabaseAuthenticationManager()
- {
- _logger.info("Initialising PrincipalDatabase authentication manager.");
-
- Map<String, Class<? extends SaslServerFactory>> providerMap = new TreeMap<String, Class<? extends SaslServerFactory>>();
-
-
- initialiseAuthenticationMechanisms(providerMap, ApplicationRegistry.getInstance().getDatabaseManager().getDatabases());
-
- if (providerMap.size() > 0)
- {
- // Ensure we are used before the defaults
- if (Security.insertProviderAt(new JCAProvider(PROVIDER_NAME, providerMap), 1) == -1)
- {
- _logger.error("Unable to load custom SASL providers. Qpid custom SASL authenticators unavailable.");
- }
- else
- {
- _logger.info("Additional SASL providers successfully registered.");
- }
-
- }
- else
- {
- _logger.warn("No additional SASL providers registered.");
- }
- }
-
- private void initialiseAuthenticationMechanisms(Map<String, Class<? extends SaslServerFactory>> providerMap, Map<String, PrincipalDatabase> databases)
- {
- if (databases.size() > 1)
- {
- _logger.warn("More than one principle database provided currently authentication mechanism will override each other.");
- }
-
- for (Map.Entry<String, PrincipalDatabase> entry : databases.entrySet())
- {
- // fixme As the database now provide the mechanisms they support, they will ...
- // overwrite each other in the map. There should only be one database per vhost.
- // But currently we must have authentication before vhost definition.
- initialiseAuthenticationMechanisms(providerMap, entry.getValue());
- }
- }
-
- private void initialiseAuthenticationMechanisms(Map<String, Class<? extends SaslServerFactory>> providerMap, PrincipalDatabase database)
- {
- if (database == null || database.getMechanisms().size() == 0)
- {
- _logger.warn("No Database or no mechanisms to initialise authentication");
- return;
- }
-
- for (Map.Entry<String, AuthenticationProviderInitialiser> mechanism : database.getMechanisms().entrySet())
- {
- initialiseAuthenticationMechanism(mechanism.getKey(), mechanism.getValue(), providerMap);
- }
- }
-
- private void initialiseAuthenticationMechanism(String mechanism, AuthenticationProviderInitialiser initialiser,
- Map<String, Class<? extends SaslServerFactory>> providerMap)
-
- {
- if (_mechanisms == null)
- {
- _mechanisms = mechanism;
- }
- else
- {
- // simple append should be fine since the number of mechanisms is small and this is a one time initialisation
- _mechanisms = _mechanisms + " " + mechanism;
- }
- _callbackHandlerMap.put(mechanism, initialiser.getCallbackHandler());
- _serverCreationProperties.put(mechanism, initialiser.getProperties());
- Class<? extends SaslServerFactory> factory = initialiser.getServerFactoryClassForJCARegistration();
- if (factory != null)
- {
- providerMap.put(mechanism, factory);
- }
- _logger.info("Initialised " + mechanism + " SASL provider successfully");
- }
-
- public String getMechanisms()
- {
- return _mechanisms;
- }
-
- public SaslServer createSaslServer(String mechanism, String localFQDN) throws SaslException
- {
- return Sasl.createSaslServer(mechanism, "AMQP", localFQDN, _serverCreationProperties.get(mechanism),
- _callbackHandlerMap.get(mechanism));
- }
-
- public AuthenticationResult authenticate(SaslServer server, byte[] response)
- {
- try
- {
- // Process response from the client
- byte[] challenge = server.evaluateResponse(response != null ? response : new byte[0]);
-
- if (server.isComplete())
- {
- return new AuthenticationResult(challenge, AuthenticationResult.AuthenticationStatus.SUCCESS);
- }
- else
- {
- return new AuthenticationResult(challenge, AuthenticationResult.AuthenticationStatus.CONTINUE);
- }
- }
- catch (SaslException e)
- {
- return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, e);
- }
- }
-
- public void close()
- {
- _mechanisms = null;
- Security.removeProvider(PROVIDER_NAME);
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/rmi/RMIPasswordAuthenticator.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/rmi/RMIPasswordAuthenticator.java
deleted file mode 100644
index 0cbbccb3b8..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/rmi/RMIPasswordAuthenticator.java
+++ /dev/null
@@ -1,119 +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.auth.rmi;
-
-import java.util.Collections;
-
-import javax.management.remote.JMXAuthenticator;
-import javax.management.remote.JMXPrincipal;
-import javax.security.auth.Subject;
-import javax.security.auth.login.AccountNotFoundException;
-
-import org.apache.qpid.server.security.auth.database.PrincipalDatabase;
-
-public class RMIPasswordAuthenticator implements JMXAuthenticator
-{
- static final String UNABLE_TO_LOOKUP = "The broker was unable to lookup the user details";
- static final String SHOULD_BE_STRING_ARRAY = "User details should be String[]";
- static final String SHOULD_HAVE_2_ELEMENTS = "User details should have 2 elements, username, password";
- static final String SHOULD_BE_NON_NULL = "Supplied username and password should be non-null";
- static final String INVALID_CREDENTIALS = "Invalid user details supplied";
- static final String CREDENTIALS_REQUIRED = "User details are required. " +
- "Please ensure you are using an up to date management console to connect.";
-
- private PrincipalDatabase _db = null;
-
- public RMIPasswordAuthenticator()
- {
- }
-
- public void setPrincipalDatabase(PrincipalDatabase pd)
- {
- this._db = pd;
- }
-
- public Subject authenticate(Object credentials) throws SecurityException
- {
- // Verify that credential's are of type String[].
- if (!(credentials instanceof String[]))
- {
- if (credentials == null)
- {
- throw new SecurityException(CREDENTIALS_REQUIRED);
- }
- else
- {
- throw new SecurityException(SHOULD_BE_STRING_ARRAY);
- }
- }
-
- // Verify that required number of credential's.
- final String[] userCredentials = (String[]) credentials;
- if (userCredentials.length != 2)
- {
- throw new SecurityException(SHOULD_HAVE_2_ELEMENTS);
- }
-
- String username = (String) userCredentials[0];
- String password = (String) userCredentials[1];
-
- // Verify that all required credential's are actually present.
- if (username == null || password == null)
- {
- throw new SecurityException(SHOULD_BE_NON_NULL);
- }
-
- // Verify that a PD has been set.
- if (_db == null)
- {
- throw new SecurityException(UNABLE_TO_LOOKUP);
- }
-
- boolean authenticated = false;
-
- // Perform authentication
- try
- {
- if (_db.verifyPassword(username, password.toCharArray()))
- {
- authenticated = true;
- }
- }
- catch (AccountNotFoundException e)
- {
- throw new SecurityException(INVALID_CREDENTIALS); // XXX
- }
-
- if (authenticated)
- {
- //credential's check out, return the appropriate JAAS Subject
- return new Subject(true,
- Collections.singleton(new JMXPrincipal(username)),
- Collections.EMPTY_SET,
- Collections.EMPTY_SET);
- }
- else
- {
- throw new SecurityException(INVALID_CREDENTIALS);
- }
- }
-
-} \ No newline at end of file
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/AuthenticationProviderInitialiser.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/AuthenticationProviderInitialiser.java
deleted file mode 100644
index 89e545d6f5..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/AuthenticationProviderInitialiser.java
+++ /dev/null
@@ -1,76 +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.auth.sasl;
-
-import java.util.Map;
-
-import javax.security.auth.callback.CallbackHandler;
-import javax.security.sasl.SaslServerFactory;
-
-import org.apache.commons.configuration.Configuration;
-import org.apache.qpid.server.security.auth.database.PrincipalDatabase;
-
-public interface AuthenticationProviderInitialiser
-{
- /**
- * @return the mechanism's name. This will be used in the list of mechanism's advertised to the
- * client.
- */
- String getMechanismName();
-
- /**
- * Initialise the authentication provider.
- * @param baseConfigPath the path in the config file that points to any config options for this provider. Each
- * provider can have its own set of configuration options
- * @param configuration the Apache Commons Configuration instance used to configure this provider
- * @param principalDatabases the set of principal databases that are available
- * @throws Exception needs refined Exception is too broad.
- */
- void initialise(String baseConfigPath, Configuration configuration,
- Map<String, PrincipalDatabase> principalDatabases) throws Exception;
-
- /**
- * Initialise the authentication provider.
- * @param db The principal database to initialise with
- */
- void initialise(PrincipalDatabase db);
-
-
- /**
- * @return the callback handler that should be used to process authentication requests for this mechanism. This will
- * be called after initialise and will be stored by the authentication manager. The callback handler <b>must</b> be
- * fully threadsafe.
- */
- CallbackHandler getCallbackHandler();
-
- /**
- * Get the properties that must be passed in to the Sasl.createSaslServer method.
- * @return the properties, which may be null
- */
- Map<String, ?> getProperties();
-
- /**
- * Get the class that is the server factory. This is used for the JCA registration.
- * @return null if no JCA registration is required, otherwise return the class
- * that will be used in JCA registration
- */
- Class<? extends SaslServerFactory> getServerFactoryClassForJCARegistration();
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/JCAProvider.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/JCAProvider.java
deleted file mode 100644
index d6a09d8217..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/JCAProvider.java
+++ /dev/null
@@ -1,46 +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.auth.sasl;
-
-import java.security.Provider;
-import java.security.Security;
-import java.util.Map;
-
-import javax.security.sasl.SaslServerFactory;
-
-public final class JCAProvider extends Provider
-{
- public JCAProvider(String name, Map<String, Class<? extends SaslServerFactory>> providerMap)
- {
- super(name, 1.0, "A JCA provider that registers all " +
- "AMQ SASL providers that want to be registered");
- register(providerMap);
- }
-
- private void register(Map<String, Class<? extends SaslServerFactory>> providerMap)
- {
- for (Map.Entry<String, Class<? extends SaslServerFactory>> me :
- providerMap.entrySet())
- {
- put("SaslServerFactory." + me.getKey(), me.getValue().getName());
- }
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/UsernamePasswordInitialiser.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/UsernamePasswordInitialiser.java
deleted file mode 100644
index 5c13e03886..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/UsernamePasswordInitialiser.java
+++ /dev/null
@@ -1,123 +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.auth.sasl;
-
-import java.io.IOException;
-import java.security.Principal;
-import java.util.Map;
-
-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.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;
-
-public abstract class UsernamePasswordInitialiser implements AuthenticationProviderInitialiser
-{
- protected static final Logger _logger = Logger.getLogger(UsernamePasswordInitialiser.class);
-
- private ServerCallbackHandler _callbackHandler;
-
- private static class ServerCallbackHandler implements CallbackHandler
- {
- private final PrincipalDatabase _principalDatabase;
-
- protected ServerCallbackHandler(PrincipalDatabase database)
- {
- _principalDatabase = database;
- }
-
- public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException
- {
- Principal username = null;
- for (Callback callback : callbacks)
- {
- if (callback instanceof NameCallback)
- {
- username = new UsernamePrincipal(((NameCallback) callback).getDefaultName());
- }
- else if (callback instanceof PasswordCallback)
- {
- try
- {
- _principalDatabase.setPassword(username, (PasswordCallback) callback);
- }
- catch (AccountNotFoundException e)
- {
- // very annoyingly the callback handler does not throw anything more appropriate than
- // IOException
- IOException ioe = new IOException("Error looking up user " + e);
- ioe.initCause(e);
- throw ioe;
- }
- }
- else if (callback instanceof AuthorizeCallback)
- {
- ((AuthorizeCallback) callback).setAuthorized(true);
- }
- else
- {
- throw new UnsupportedCallbackException(callback);
- }
- }
- }
- }
-
- public void initialise(String baseConfigPath, Configuration configuration,
- Map<String, PrincipalDatabase> principalDatabases) throws Exception
- {
- String principalDatabaseName = configuration.getString(baseConfigPath + ".principal-database");
- PrincipalDatabase db = principalDatabases.get(principalDatabaseName);
-
- initialise(db);
- }
-
- public void initialise(PrincipalDatabase db)
- {
- if (db == null)
- {
- throw new NullPointerException("Cannot initialise with a null Principal database.");
- }
-
- _callbackHandler = new ServerCallbackHandler(db);
- }
-
- public CallbackHandler getCallbackHandler()
- {
- return _callbackHandler;
- }
-
- public Map<String, ?> getProperties()
- {
- // there are no properties required for the CRAM-MD5 implementation
- return null;
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/UsernamePrincipal.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/UsernamePrincipal.java
deleted file mode 100644
index d7c8383690..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/UsernamePrincipal.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.security.auth.sasl;
-
-import java.security.Principal;
-
-/** A principal that is just a wrapper for a simple username. */
-public class UsernamePrincipal implements Principal
-{
- private String _name;
-
- public UsernamePrincipal(String name)
- {
- _name = name;
- }
-
- public String getName()
- {
- return _name;
- }
-
- public String toString()
- {
- return _name;
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/amqplain/AmqPlainInitialiser.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/amqplain/AmqPlainInitialiser.java
deleted file mode 100644
index 7acc6322d1..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/amqplain/AmqPlainInitialiser.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.security.auth.sasl.amqplain;
-
-import javax.security.sasl.SaslServerFactory;
-
-import org.apache.qpid.server.security.auth.sasl.UsernamePasswordInitialiser;
-
-public class AmqPlainInitialiser extends UsernamePasswordInitialiser
-{
- public String getMechanismName()
- {
- return "AMQPLAIN";
- }
-
- public Class<? extends SaslServerFactory> getServerFactoryClassForJCARegistration()
- {
- return AmqPlainSaslServerFactory.class;
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/amqplain/AmqPlainSaslServer.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/amqplain/AmqPlainSaslServer.java
deleted file mode 100644
index 9f56b8521a..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/amqplain/AmqPlainSaslServer.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.server.security.auth.sasl.amqplain;
-
-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 org.apache.mina.common.ByteBuffer;
-import org.apache.qpid.framing.AMQFrameDecodingException;
-import org.apache.qpid.framing.FieldTable;
-import org.apache.qpid.framing.FieldTableFactory;
-
-public class AmqPlainSaslServer implements SaslServer
-{
- public static final String MECHANISM = "AMQPLAIN";
-
- private CallbackHandler _cbh;
-
- private String _authorizationId;
-
- private boolean _complete = false;
-
- public AmqPlainSaslServer(CallbackHandler cbh)
- {
- _cbh = cbh;
- }
-
- public String getMechanismName()
- {
- return MECHANISM;
- }
-
- public byte[] evaluateResponse(byte[] response) throws SaslException
- {
- try
- {
- final FieldTable ft = FieldTableFactory.newFieldTable(ByteBuffer.wrap(response), response.length);
- String username = (String) ft.getString("LOGIN");
- // we do not care about the prompt but it throws if null
- NameCallback nameCb = new NameCallback("prompt", username);
- // we do not care about the prompt but it throws if null
- PasswordCallback passwordCb = new PasswordCallback("prompt", false);
- // TODO: should not get pwd as a String but as a char array...
- String pwd = (String) ft.getString("PASSWORD");
- AuthorizeCallback authzCb = new AuthorizeCallback(username, username);
- Callback[] callbacks = new Callback[]{nameCb, passwordCb, authzCb};
- _cbh.handle(callbacks);
- String storedPwd = new String(passwordCb.getPassword());
- if (storedPwd.equals(pwd))
- {
- _complete = true;
- }
- if (authzCb.isAuthorized() && _complete)
- {
- _authorizationId = authzCb.getAuthenticationID();
- return null;
- }
- else
- {
- throw new SaslException("Authentication failed");
- }
- }
- catch (AMQFrameDecodingException e)
- {
- throw new SaslException("Unable to decode response: " + e, e);
- }
- catch (IOException e)
- {
- throw new SaslException("Error processing data: " + e, e);
- }
- catch (UnsupportedCallbackException e)
- {
- throw new SaslException("Unable to obtain data from callback handler: " + e, e);
- }
- }
-
- public boolean isComplete()
- {
- return _complete;
- }
-
- public String getAuthorizationID()
- {
- return _authorizationId;
- }
-
- public byte[] unwrap(byte[] incoming, int offset, int len) throws SaslException
- {
- throw new SaslException("Unsupported operation");
- }
-
- public byte[] wrap(byte[] outgoing, int offset, int len) throws SaslException
- {
- throw new SaslException("Unsupported operation");
- }
-
- public Object getNegotiatedProperty(String propName)
- {
- return null;
- }
-
- public void dispose() throws SaslException
- {
- _cbh = null;
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/amqplain/AmqPlainSaslServerFactory.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/amqplain/AmqPlainSaslServerFactory.java
deleted file mode 100644
index 17d123eb0d..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/amqplain/AmqPlainSaslServerFactory.java
+++ /dev/null
@@ -1,61 +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.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;
-
-public class AmqPlainSaslServerFactory implements SaslServerFactory
-{
- public SaslServer createSaslServer(String mechanism, String protocol, String serverName, Map props,
- CallbackHandler cbh) throws SaslException
- {
- if (AmqPlainSaslServer.MECHANISM.equals(mechanism))
- {
- return new AmqPlainSaslServer(cbh);
- }
- else
- {
- return null;
- }
- }
-
- public String[] getMechanismNames(Map props)
- {
- if (props != null &&
- (props.containsKey(Sasl.POLICY_NOPLAINTEXT) ||
- props.containsKey(Sasl.POLICY_NODICTIONARY) ||
- props.containsKey(Sasl.POLICY_NOACTIVE)))
- {
- // returned array must be non null according to interface documentation
- return new String[0];
- }
- else
- {
- return new String[]{AmqPlainSaslServer.MECHANISM};
- }
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/anonymous/AnonymousInitialiser.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/anonymous/AnonymousInitialiser.java
deleted file mode 100644
index 4a66b74783..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/anonymous/AnonymousInitialiser.java
+++ /dev/null
@@ -1,39 +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.auth.sasl.anonymous;
-
-import javax.security.sasl.SaslServerFactory;
-
-import org.apache.qpid.server.security.auth.sasl.UsernamePasswordInitialiser;
-import org.apache.qpid.server.security.auth.sasl.amqplain.AmqPlainSaslServerFactory;
-
-public class AnonymousInitialiser extends UsernamePasswordInitialiser
-{
- public String getMechanismName()
- {
- return "ANONYMOUS";
- }
-
- public Class<? extends SaslServerFactory> getServerFactoryClassForJCARegistration()
- {
- return AnonymousSaslServerFactory.class;
- }
-} \ No newline at end of file
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/anonymous/AnonymousSaslServer.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/anonymous/AnonymousSaslServer.java
deleted file mode 100644
index b4cce15d88..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/anonymous/AnonymousSaslServer.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.security.auth.sasl.anonymous;
-
-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 org.apache.mina.common.ByteBuffer;
-import org.apache.qpid.framing.AMQFrameDecodingException;
-import org.apache.qpid.framing.FieldTable;
-import org.apache.qpid.framing.FieldTableFactory;
-
-public class AnonymousSaslServer implements SaslServer
-{
- public static final String MECHANISM = "ANONYMOUS";
-
- private boolean _complete = false;
-
- public AnonymousSaslServer()
- {
- }
-
- public String getMechanismName()
- {
- return MECHANISM;
- }
-
- public byte[] evaluateResponse(byte[] response) throws SaslException
- {
- _complete = true;
- return null;
- }
-
- public boolean isComplete()
- {
- return _complete;
- }
-
- public String getAuthorizationID()
- {
- return null;
- }
-
- public byte[] unwrap(byte[] incoming, int offset, int len) throws SaslException
- {
- throw new SaslException("Unsupported operation");
- }
-
- public byte[] wrap(byte[] outgoing, int offset, int len) throws SaslException
- {
- throw new SaslException("Unsupported operation");
- }
-
- public Object getNegotiatedProperty(String propName)
- {
- return null;
- }
-
- public void dispose() throws SaslException
- {
- }
-} \ No newline at end of file
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/anonymous/AnonymousSaslServerFactory.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/anonymous/AnonymousSaslServerFactory.java
deleted file mode 100644
index 8a5ff7df2d..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/anonymous/AnonymousSaslServerFactory.java
+++ /dev/null
@@ -1,64 +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.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;
-
-public class AnonymousSaslServerFactory implements SaslServerFactory
-{
- public SaslServer createSaslServer(String mechanism, String protocol, String serverName, Map props,
- CallbackHandler cbh) throws SaslException
- {
- if (AnonymousSaslServer.MECHANISM.equals(mechanism))
- {
- return new AnonymousSaslServer();
- }
- else
- {
- return null;
- }
- }
-
- public String[] getMechanismNames(Map props)
- {
- if (props != null &&
- (props.containsKey(Sasl.POLICY_NOPLAINTEXT) ||
- props.containsKey(Sasl.POLICY_NODICTIONARY) ||
- props.containsKey(Sasl.POLICY_NOACTIVE) ||
- props.containsKey(Sasl.POLICY_NOANONYMOUS)))
- {
- // returned array must be non null according to interface documentation
- return new String[0];
- }
- else
- {
- return new String[]{AnonymousSaslServer.MECHANISM};
- }
- }
-} \ No newline at end of file
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HashedInitialiser.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HashedInitialiser.java
deleted file mode 100644
index 97f9a4e91a..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HashedInitialiser.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.security.auth.sasl.crammd5;
-
-import org.apache.qpid.server.security.auth.sasl.UsernamePasswordInitialiser;
-import org.apache.qpid.server.security.auth.database.PrincipalDatabase;
-
-import javax.security.sasl.SaslServerFactory;
-import java.util.Map;
-
-public class CRAMMD5HashedInitialiser extends UsernamePasswordInitialiser
-{
- public String getMechanismName()
- {
- return CRAMMD5HashedSaslServer.MECHANISM;
- }
-
- public Class<? extends SaslServerFactory> getServerFactoryClassForJCARegistration()
- {
- return CRAMMD5HashedServerFactory.class;
- }
-
- public void initialise(PrincipalDatabase passwordFile)
- {
- super.initialise(passwordFile);
- }
-
- public Map<String, ?> getProperties()
- {
- return null;
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HashedSaslServer.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HashedSaslServer.java
deleted file mode 100644
index f6cab084ea..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HashedSaslServer.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.security.auth.sasl.crammd5;
-
-import javax.security.sasl.SaslServer;
-import javax.security.sasl.SaslException;
-import javax.security.sasl.Sasl;
-import javax.security.sasl.SaslServerFactory;
-import javax.security.auth.callback.CallbackHandler;
-import java.util.Enumeration;
-import java.util.Map;
-
-public class CRAMMD5HashedSaslServer implements SaslServer
-{
- public static final String MECHANISM = "CRAM-MD5-HASHED";
-
- private SaslServer _realServer;
-
- public CRAMMD5HashedSaslServer(String mechanism, String protocol, String serverName, Map<String, ?> props,
- CallbackHandler cbh) throws SaslException
- {
- Enumeration factories = Sasl.getSaslServerFactories();
-
- while (factories.hasMoreElements())
- {
- SaslServerFactory factory = (SaslServerFactory) factories.nextElement();
-
- if (factory instanceof CRAMMD5HashedServerFactory)
- {
- continue;
- }
-
- String[] mechs = factory.getMechanismNames(props);
-
- for (String mech : mechs)
- {
- if (mech.equals("CRAM-MD5"))
- {
- _realServer = factory.createSaslServer("CRAM-MD5", protocol, serverName, props, cbh);
- return;
- }
- }
- }
-
- throw new RuntimeException("No default SaslServer found for mechanism:" + "CRAM-MD5");
- }
-
- public String getMechanismName()
- {
- return MECHANISM;
- }
-
- public byte[] evaluateResponse(byte[] response) throws SaslException
- {
- return _realServer.evaluateResponse(response);
- }
-
- public boolean isComplete()
- {
- return _realServer.isComplete();
- }
-
- public String getAuthorizationID()
- {
- return _realServer.getAuthorizationID();
- }
-
- public byte[] unwrap(byte[] incoming, int offset, int len) throws SaslException
- {
- return _realServer.unwrap(incoming, offset, len);
- }
-
- public byte[] wrap(byte[] outgoing, int offset, int len) throws SaslException
- {
- return _realServer.wrap(outgoing, offset, len);
- }
-
- public Object getNegotiatedProperty(String propName)
- {
- return _realServer.getNegotiatedProperty(propName);
- }
-
- public void dispose() throws SaslException
- {
- _realServer.dispose();
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HashedServerFactory.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HashedServerFactory.java
deleted file mode 100644
index 5298b5cc63..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HashedServerFactory.java
+++ /dev/null
@@ -1,61 +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.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;
-
-public class CRAMMD5HashedServerFactory implements SaslServerFactory
-{
- public SaslServer createSaslServer(String mechanism, String protocol, String serverName, Map<String, ?> props,
- CallbackHandler cbh) throws SaslException
- {
- if (mechanism.equals(CRAMMD5HashedSaslServer.MECHANISM))
- {
- return new CRAMMD5HashedSaslServer(mechanism, protocol, serverName, props, cbh);
- }
- else
- {
- return null;
- }
- }
-
- public String[] getMechanismNames(Map props)
- {
- if (props != null)
- {
- if (props.containsKey(Sasl.POLICY_NOPLAINTEXT) ||
- props.containsKey(Sasl.POLICY_NODICTIONARY) ||
- props.containsKey(Sasl.POLICY_NOACTIVE))
- {
- // returned array must be non null according to interface documentation
- return new String[0];
- }
- }
-
- return new String[]{CRAMMD5HashedSaslServer.MECHANISM};
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HexInitialiser.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HexInitialiser.java
deleted file mode 100644
index 139818735f..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HexInitialiser.java
+++ /dev/null
@@ -1,144 +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.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 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 java.io.IOException;
-
-public class CRAMMD5HexInitialiser extends UsernamePasswordInitialiser
-{
- public String getMechanismName()
- {
- return CRAMMD5HexSaslServer.MECHANISM;
- }
-
- public Class<? extends SaslServerFactory> getServerFactoryClassForJCARegistration()
- {
- return CRAMMD5HexServerFactory.class;
- }
-
- public Map<String, ?> getProperties()
- {
- return null;
- }
-
- public void initialise(PrincipalDatabase db)
- {
- super.initialise(new HexifyPrincipalDatabase(db));
-
- }
-
- private static class HexifyPrincipalDatabase implements PrincipalDatabase
- {
- private PrincipalDatabase _realPricipalDatabase;
-
- HexifyPrincipalDatabase(PrincipalDatabase db)
- {
- _realPricipalDatabase = db;
- }
-
- private char[] toHex(char[] password)
- {
- StringBuilder sb = new StringBuilder();
- for (char c : password)
- {
- //toHexString does not prepend 0 so we have to
- if (((byte) c > -1) && (byte) c < 0x10 )
- {
- sb.append(0);
- }
-
- sb.append(Integer.toHexString(c & 0xFF));
- }
-
- //Extract the hex string as char[]
- char[] hex = new char[sb.length()];
-
- sb.getChars(0, sb.length(), hex, 0);
-
- return hex;
- }
-
- public void setPassword(Principal principal, PasswordCallback callback) throws IOException, AccountNotFoundException
- {
- //Let the read DB set the password
- _realPricipalDatabase.setPassword(principal, callback);
-
- //Retrieve the setpassword
- char[] plainPassword = callback.getPassword();
-
- char[] hexPassword = toHex(plainPassword);
-
- callback.setPassword(hexPassword);
- }
-
- // Simply delegate to the real PrincipalDB
- public boolean verifyPassword(String principal, char[] password) throws AccountNotFoundException
- {
- return _realPricipalDatabase.verifyPassword(principal, password);
- }
-
- public boolean updatePassword(Principal principal, char[] password) throws AccountNotFoundException
- {
- return _realPricipalDatabase.updatePassword(principal, password);
- }
-
- public boolean createPrincipal(Principal principal, char[] password)
- {
- return _realPricipalDatabase.createPrincipal(principal, password);
- }
-
- public boolean deletePrincipal(Principal principal) throws AccountNotFoundException
- {
- return _realPricipalDatabase.deletePrincipal(principal);
- }
-
- public Principal getUser(String username)
- {
- return _realPricipalDatabase.getUser(username);
- }
-
- public Map<String, AuthenticationProviderInitialiser> getMechanisms()
- {
- return _realPricipalDatabase.getMechanisms();
- }
-
- public List<Principal> getUsers()
- {
- return _realPricipalDatabase.getUsers();
- }
-
- public void reload() throws IOException
- {
- _realPricipalDatabase.reload();
- }
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HexSaslServer.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HexSaslServer.java
deleted file mode 100644
index 192ff74bff..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HexSaslServer.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.security.auth.sasl.crammd5;
-
-import javax.security.sasl.SaslServer;
-import javax.security.sasl.SaslException;
-import javax.security.sasl.Sasl;
-import javax.security.sasl.SaslServerFactory;
-import javax.security.auth.callback.CallbackHandler;
-import java.util.Enumeration;
-import java.util.Map;
-
-public class CRAMMD5HexSaslServer implements SaslServer
-{
- public static final String MECHANISM = "CRAM-MD5-HEX";
-
- private SaslServer _realServer;
-
- public CRAMMD5HexSaslServer(String mechanism, String protocol, String serverName, Map<String, ?> props,
- CallbackHandler cbh) throws SaslException
- {
- Enumeration factories = Sasl.getSaslServerFactories();
-
- while (factories.hasMoreElements())
- {
- SaslServerFactory factory = (SaslServerFactory) factories.nextElement();
-
- if (factory instanceof CRAMMD5HexServerFactory)
- {
- continue;
- }
-
- String[] mechs = factory.getMechanismNames(props);
-
- for (String mech : mechs)
- {
- if (mech.equals("CRAM-MD5"))
- {
- _realServer = factory.createSaslServer("CRAM-MD5", protocol, serverName, props, cbh);
- return;
- }
- }
- }
-
- throw new RuntimeException("No default SaslServer found for mechanism:" + "CRAM-MD5");
- }
-
- public String getMechanismName()
- {
- return MECHANISM;
- }
-
- public byte[] evaluateResponse(byte[] response) throws SaslException
- {
- return _realServer.evaluateResponse(response);
- }
-
- public boolean isComplete()
- {
- return _realServer.isComplete();
- }
-
- public String getAuthorizationID()
- {
- return _realServer.getAuthorizationID();
- }
-
- public byte[] unwrap(byte[] incoming, int offset, int len) throws SaslException
- {
- return _realServer.unwrap(incoming, offset, len);
- }
-
- public byte[] wrap(byte[] outgoing, int offset, int len) throws SaslException
- {
- return _realServer.wrap(outgoing, offset, len);
- }
-
- public Object getNegotiatedProperty(String propName)
- {
- return _realServer.getNegotiatedProperty(propName);
- }
-
- public void dispose() throws SaslException
- {
- _realServer.dispose();
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HexServerFactory.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HexServerFactory.java
deleted file mode 100644
index ce0e19abf9..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HexServerFactory.java
+++ /dev/null
@@ -1,61 +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.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;
-
-public class CRAMMD5HexServerFactory implements SaslServerFactory
-{
- public SaslServer createSaslServer(String mechanism, String protocol, String serverName, Map<String, ?> props,
- CallbackHandler cbh) throws SaslException
- {
- if (mechanism.equals(CRAMMD5HexSaslServer.MECHANISM))
- {
- return new CRAMMD5HexSaslServer(mechanism, protocol, serverName, props, cbh);
- }
- else
- {
- return null;
- }
- }
-
- public String[] getMechanismNames(Map props)
- {
- if (props != null)
- {
- if (props.containsKey(Sasl.POLICY_NOPLAINTEXT) ||
- props.containsKey(Sasl.POLICY_NODICTIONARY) ||
- props.containsKey(Sasl.POLICY_NOACTIVE))
- {
- // returned array must be non null according to interface documentation
- return new String[0];
- }
- }
-
- return new String[]{CRAMMD5HexSaslServer.MECHANISM};
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5Initialiser.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5Initialiser.java
deleted file mode 100644
index 264832888d..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5Initialiser.java
+++ /dev/null
@@ -1,71 +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.auth.sasl.crammd5;
-
-import org.apache.qpid.server.security.auth.sasl.UsernamePasswordInitialiser;
-import org.apache.qpid.server.security.auth.database.PrincipalDatabase;
-
-import javax.security.sasl.SaslServerFactory;
-
-public class CRAMMD5Initialiser extends UsernamePasswordInitialiser
-{
- private HashDirection _hashDirection;
-
- public enum HashDirection
- {
- INCOMMING, PASSWORD_FILE
- }
-
-
- public String getMechanismName()
- {
- return "CRAM-MD5";
- }
-
- public Class<? extends SaslServerFactory> getServerFactoryClassForJCARegistration()
- {
- // since the CRAM-MD5 provider is registered as part of the JDK, we do not
- // return the factory class here since we do not need to register it ourselves.
- if (_hashDirection == HashDirection.PASSWORD_FILE)
- {
- return null;
- }
- else
- {
- //fixme we need a server that will correctly has the incomming plain text for comparison to file.
- _logger.warn("we need a server that will correctly convert the incomming plain text for comparison to file.");
- return null;
- }
- }
-
- public void initialise(PrincipalDatabase passwordFile)
- {
- initialise(passwordFile, HashDirection.PASSWORD_FILE);
- }
-
- public void initialise(PrincipalDatabase passwordFile, HashDirection direction)
- {
- super.initialise(passwordFile);
-
- _hashDirection = direction;
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/plain/PlainInitialiser.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/plain/PlainInitialiser.java
deleted file mode 100644
index 1d16cd8755..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/plain/PlainInitialiser.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.security.auth.sasl.plain;
-
-import javax.security.sasl.SaslServerFactory;
-
-import org.apache.qpid.server.security.auth.sasl.UsernamePasswordInitialiser;
-
-public class PlainInitialiser extends UsernamePasswordInitialiser
-{
- public String getMechanismName()
- {
- return "PLAIN";
- }
-
- public Class<? extends SaslServerFactory> getServerFactoryClassForJCARegistration()
- {
- return PlainSaslServerFactory.class;
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/plain/PlainPasswordCallback.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/plain/PlainPasswordCallback.java
deleted file mode 100644
index 7230e8ee53..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/plain/PlainPasswordCallback.java
+++ /dev/null
@@ -1,81 +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.auth.sasl.plain;
-
-import java.util.Arrays;
-
-import javax.security.auth.callback.PasswordCallback;
-
-/**
- * Custom PasswordCallback for use during the PLAIN authentication process.
- *
- * To be used in combination with PrincipalDatabase implementations that
- * can either set a plain text value in the parent callback, or use the
- * setAuthenticated(bool) method after observing the incoming plain text.
- *
- * isAuthenticated() should then be used to determine the final result.
- *
- */
-public class PlainPasswordCallback extends PasswordCallback
-{
- private char[] _plainPassword;
- private boolean _authenticated = false;
-
- /**
- * Constructs a new PlainPasswordCallback with the incoming plain text password.
- *
- * @throws NullPointerException if the incoming plain text is null
- */
- public PlainPasswordCallback(String prompt, boolean echoOn, String plainPassword)
- {
- super(prompt, echoOn);
-
- if(plainPassword == null)
- {
- throw new NullPointerException("Incoming plain text cannot be null");
- }
-
- _plainPassword = plainPassword.toCharArray();
- }
-
- public String getPlainPassword()
- {
- return new String(_plainPassword);
- }
-
- public void setAuthenticated(boolean authenticated)
- {
- _authenticated = authenticated;
- }
-
- /**
- * Method to determine if the incoming plain password is authenticated
- *
- * @return true if the stored password matches the incoming text, or setAuthenticated(true) has been called
- */
- public boolean isAuthenticated()
- {
- char[] storedPassword = getPassword();
-
- return Arrays.equals(_plainPassword, storedPassword) || _authenticated;
- }
-}
-
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/plain/PlainSaslServer.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/plain/PlainSaslServer.java
deleted file mode 100644
index 847a3a34ce..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/plain/PlainSaslServer.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.
- *
- */
-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;
-
-public class PlainSaslServer implements SaslServer
-{
- public static final String MECHANISM = "PLAIN";
-
- private CallbackHandler _cbh;
-
- private String _authorizationId;
-
- private boolean _complete = false;
-
- public PlainSaslServer(CallbackHandler cbh)
- {
- _cbh = cbh;
- }
-
- public String getMechanismName()
- {
- return MECHANISM;
- }
-
- public byte[] evaluateResponse(byte[] response) throws SaslException
- {
- try
- {
- 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");
- }
-
- // 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);
-
- 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)
- {
- throw new SaslException("Error processing data: " + e, e);
- }
- catch (UnsupportedCallbackException e)
- {
- throw new SaslException("Unable to obtain data from callback handler: " + e, e);
- }
- }
-
-
-
- private int findNullPosition(byte[] response, int startPosition)
- {
- int position = startPosition;
- while (position < response.length)
- {
- if (response[position] == (byte) 0)
- {
- return position;
- }
- position++;
- }
- return -1;
- }
-
- public boolean isComplete()
- {
- return _complete;
- }
-
- public String getAuthorizationID()
- {
- return _authorizationId;
- }
-
- public byte[] unwrap(byte[] incoming, int offset, int len) throws SaslException
- {
- throw new SaslException("Unsupported operation");
- }
-
- public byte[] wrap(byte[] outgoing, int offset, int len) throws SaslException
- {
- throw new SaslException("Unsupported operation");
- }
-
- public Object getNegotiatedProperty(String propName)
- {
- return null;
- }
-
- public void dispose() throws SaslException
- {
- _cbh = null;
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/plain/PlainSaslServerFactory.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/plain/PlainSaslServerFactory.java
deleted file mode 100644
index 3144bfbce6..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/plain/PlainSaslServerFactory.java
+++ /dev/null
@@ -1,61 +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.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;
-
-public class PlainSaslServerFactory implements SaslServerFactory
-{
- public SaslServer createSaslServer(String mechanism, String protocol, String serverName, Map props,
- CallbackHandler cbh) throws SaslException
- {
- if (PlainSaslServer.MECHANISM.equals(mechanism))
- {
- return new PlainSaslServer(cbh);
- }
- else
- {
- return null;
- }
- }
-
- public String[] getMechanismNames(Map props)
- {
- if (props != null &&
- (props.containsKey(Sasl.POLICY_NOPLAINTEXT) ||
- props.containsKey(Sasl.POLICY_NODICTIONARY) ||
- props.containsKey(Sasl.POLICY_NOACTIVE)))
- {
- // returned array must be non null according to interface documentation
- return new String[0];
- }
- else
- {
- return new String[]{PlainSaslServer.MECHANISM};
- }
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/state/AMQState.java b/java/broker/src/main/java/org/apache/qpid/server/state/AMQState.java
deleted file mode 100644
index f427cc7206..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/state/AMQState.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.state;
-
-/**
- * States used in the AMQ protocol. Used by the finite state machine to determine
- * valid responses.
- */
-public enum AMQState
-{
- CONNECTION_NOT_STARTED,
- CONNECTION_NOT_AUTH,
- CONNECTION_NOT_TUNED,
- CONNECTION_NOT_OPENED,
- CONNECTION_OPEN,
- CONNECTION_CLOSING,
- CONNECTION_CLOSED
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/state/AMQStateManager.java b/java/broker/src/main/java/org/apache/qpid/server/state/AMQStateManager.java
deleted file mode 100644
index 6cc5e7b019..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/state/AMQStateManager.java
+++ /dev/null
@@ -1,265 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.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.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;
-
-/**
- * The state manager is responsible for managing the state of the protocol session. <p/> For each AMQProtocolHandler
- * there is a separate state manager.
- */
-public class AMQStateManager implements AMQMethodListener
-{
- private static final Logger _logger = Logger.getLogger(AMQStateManager.class);
-
- private final VirtualHostRegistry _virtualHostRegistry;
- private final AMQProtocolSession _protocolSession;
- /** 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<AMQState, Map<Class<? extends AMQMethodBody>, StateAwareMethodListener<? extends AMQMethodBody>>> _state2HandlersMap =
- new EnumMap<AMQState, Map<Class<? extends AMQMethodBody>, StateAwareMethodListener<? extends AMQMethodBody>>>(
- AMQState.class);
- */
-
-
- private CopyOnWriteArraySet<StateListener> _stateListeners = new CopyOnWriteArraySet<StateListener>();
-
- public AMQStateManager(VirtualHostRegistry virtualHostRegistry, AMQProtocolSession protocolSession)
- {
-
- _virtualHostRegistry = virtualHostRegistry;
- _protocolSession = protocolSession;
- _currentState = AMQState.CONNECTION_NOT_STARTED;
-
- }
-
- /*
- protected void registerListeners()
- {
- Map<Class<? extends AMQMethodBody>, StateAwareMethodListener<? extends AMQMethodBody>> frame2handlerMap;
-
- frame2handlerMap = new HashMap<Class<? extends AMQMethodBody>, StateAwareMethodListener<? extends AMQMethodBody>>();
- _state2HandlersMap.put(AMQState.CONNECTION_NOT_STARTED, frame2handlerMap);
-
- frame2handlerMap = new HashMap<Class<? extends AMQMethodBody>, StateAwareMethodListener<? extends AMQMethodBody>>();
- _state2HandlersMap.put(AMQState.CONNECTION_NOT_AUTH, frame2handlerMap);
-
- frame2handlerMap = new HashMap<Class<? extends AMQMethodBody>, StateAwareMethodListener<? extends AMQMethodBody>>();
- _state2HandlersMap.put(AMQState.CONNECTION_NOT_TUNED, frame2handlerMap);
-
- frame2handlerMap = new HashMap<Class<? extends AMQMethodBody>, StateAwareMethodListener<? extends AMQMethodBody>>();
- frame2handlerMap.put(ConnectionOpenBody.class, ConnectionOpenMethodHandler.getInstance());
- _state2HandlersMap.put(AMQState.CONNECTION_NOT_OPENED, frame2handlerMap);
-
- //
- // ConnectionOpen handlers
- //
- frame2handlerMap = new HashMap<Class<? extends AMQMethodBody>, StateAwareMethodListener<? extends AMQMethodBody>>();
- 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<Class<? extends AMQMethodBody>, StateAwareMethodListener<? extends AMQMethodBody>>();
-
- _state2HandlersMap.put(AMQState.CONNECTION_CLOSING, frame2handlerMap);
-
- } */
-
- public AMQState getCurrentState()
- {
- return _currentState;
- }
-
- public void changeState(AMQState newState) throws AMQException
- {
- _logger.debug("State changing to " + newState + " from old state " + _currentState);
- final AMQState oldState = _currentState;
- _currentState = newState;
-
- for (StateListener l : _stateListeners)
- {
- l.stateChanged(oldState, newState);
- }
- }
-
- public void error(Exception e)
- {
- _logger.error("State manager received error notification[Current State:" + _currentState + "]: " + e, e);
- for (StateListener l : _stateListeners)
- {
- l.error(e);
- }
- }
-
- public <B extends AMQMethodBody> boolean methodReceived(AMQMethodEvent<B> evt) throws AMQException
- {
- MethodDispatcher dispatcher = _protocolSession.getMethodDispatcher();
-
- final int channelId = evt.getChannelId();
- B body = evt.getMethod();
-
- if(channelId != 0 && _protocolSession.getChannel(channelId)== null)
- {
-
- if(! ((body instanceof ChannelOpenBody)
- || (body instanceof ChannelCloseOkBody)
- || (body instanceof ChannelCloseBody)))
- {
- throw body.getConnectionException(AMQConstant.CHANNEL_ERROR, "channel is closed won't process:" + body);
- }
-
- }
-
- return body.execute(dispatcher, channelId);
-
- }
-
- private <B extends AMQMethodBody> void checkChannel(AMQMethodEvent<B> evt, AMQProtocolSession protocolSession)
- throws AMQException
- {
- if ((evt.getChannelId() != 0) && !(evt.getMethod() instanceof ChannelOpenBody)
- && (protocolSession.getChannel(evt.getChannelId()) == null)
- && !protocolSession.channelAwaitingClosure(evt.getChannelId()))
- {
- throw evt.getMethod().getChannelNotFoundException(evt.getChannelId());
- }
- }
-
-/*
- protected <B extends AMQMethodBody> StateAwareMethodListener<B> findStateTransitionHandler(AMQState currentState,
- B frame)
- // throws IllegalStateTransitionException
- {
- final Map<Class<? extends AMQMethodBody>, StateAwareMethodListener<? extends AMQMethodBody>> classToHandlerMap =
- _state2HandlersMap.get(currentState);
-
- final StateAwareMethodListener<B> handler =
- (classToHandlerMap == null) ? null : (StateAwareMethodListener<B>) 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");
- _stateListeners.add(listener);
- }
-
- public void removeStateListener(StateListener listener)
- {
- _stateListeners.remove(listener);
- }
-
- public VirtualHostRegistry getVirtualHostRegistry()
- {
- return _virtualHostRegistry;
- }
-
- public AMQProtocolSession getProtocolSession()
- {
- SecurityManager.setThreadPrincipal(_protocolSession.getPrincipal());
- return _protocolSession;
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/state/IllegalStateTransitionException.java b/java/broker/src/main/java/org/apache/qpid/server/state/IllegalStateTransitionException.java
deleted file mode 100644
index cec67a8a6d..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/state/IllegalStateTransitionException.java
+++ /dev/null
@@ -1,52 +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.state;
-
-import org.apache.qpid.AMQException;
-
-/**
- * @todo Not an AMQP exception as no status code.
- *
- * @todo Not used! Delete.
- */
-public class IllegalStateTransitionException extends AMQException
-{
- private AMQState _originalState;
-
- private Class _frame;
-
- public IllegalStateTransitionException(AMQState originalState, Class frame)
- {
- super("No valid state transition defined for receiving frame " + frame + " from state " + originalState);
- _originalState = originalState;
- _frame = frame;
- }
-
- public AMQState getOriginalState()
- {
- return _originalState;
- }
-
- public Class getFrameClass()
- {
- return _frame;
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/state/StateAwareMethodListener.java b/java/broker/src/main/java/org/apache/qpid/server/state/StateAwareMethodListener.java
deleted file mode 100644
index 3c11bb8a9c..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/state/StateAwareMethodListener.java
+++ /dev/null
@@ -1,35 +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.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
- * the opportunity to update state.
- *
- */
-public interface StateAwareMethodListener<B extends AMQMethodBody>
-{
- void methodReceived(AMQStateManager stateManager, B evt, int channelId) throws AMQException;
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/state/StateListener.java b/java/broker/src/main/java/org/apache/qpid/server/state/StateListener.java
deleted file mode 100644
index 00fc09867b..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/state/StateListener.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.
- *
- */
-package org.apache.qpid.server.state;
-
-import org.apache.qpid.AMQException;
-
-public interface StateListener
-{
- void stateChanged(AMQState oldState, AMQState newState) throws AMQException;
-
- void error(Throwable t);
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/stats/StatisticsCounter.java b/java/broker/src/main/java/org/apache/qpid/server/stats/StatisticsCounter.java
deleted file mode 100644
index b732121180..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/stats/StatisticsCounter.java
+++ /dev/null
@@ -1,163 +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.stats;
-
-import java.util.Date;
-import java.util.concurrent.atomic.AtomicLong;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * 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.
- */
-public class StatisticsCounter
-{
- private static final Logger _log = LoggerFactory.getLogger(StatisticsCounter.class);
-
- public static final long DEFAULT_SAMPLE_PERIOD = Long.getLong("qpid.statistics.samplePeriod", 2000L); // 2s
- public static final boolean DISABLE_STATISTICS = Boolean.getBoolean("qpid.statistics.disable");
-
- private static final String COUNTER = "counter";
- private static final AtomicLong _counterIds = new AtomicLong(0L);
-
- private long _peak = 0L;
- private long _total = 0L;
- private long _temp = 0L;
- private long _last = 0L;
- private long _rate = 0L;
-
- private long _start;
-
- private final long _period;
- private final String _name;
-
- public StatisticsCounter()
- {
- this(COUNTER);
- }
-
- public StatisticsCounter(String name)
- {
- this(name, DEFAULT_SAMPLE_PERIOD);
- }
-
- public StatisticsCounter(String name, long period)
- {
- _period = period;
- _name = name + "-" + + _counterIds.incrementAndGet();
- reset();
- }
-
- public void registerEvent()
- {
- registerEvent(1L);
- }
-
- public void registerEvent(long value)
- {
- registerEvent(value, System.currentTimeMillis());
- }
-
- public void registerEvent(long value, long timestamp)
- {
- if (DISABLE_STATISTICS)
- {
- return;
- }
-
- long thisSample = (timestamp / _period);
- synchronized (this)
- {
- if (thisSample > _last)
- {
- _last = thisSample;
- _rate = _temp;
- _temp = 0L;
- if (_rate > _peak)
- {
- _peak = _rate;
- }
- }
-
- _total += value;
- _temp += value;
- }
- }
-
- /**
- * Update the current rate and peak - may reset rate to zero if a new
- * sample period has started.
- */
- private void update()
- {
- registerEvent(0L, System.currentTimeMillis());
- }
-
- /**
- * Reset
- */
- public void reset()
- {
- _log.info("Resetting statistics for counter: " + _name);
- _peak = 0L;
- _rate = 0L;
- _total = 0L;
- _start = System.currentTimeMillis();
- _last = _start / _period;
- }
-
- public double getPeak()
- {
- update();
- return (double) _peak / ((double) _period / 1000.0d);
- }
-
- public double getRate()
- {
- update();
- return (double) _rate / ((double) _period / 1000.0d);
- }
-
- public long getTotal()
- {
- return _total;
- }
-
- public long getStart()
- {
- return _start;
- }
-
- public Date getStartTime()
- {
- return new Date(_start);
- }
-
- public String getName()
- {
- return _name;
- }
-
- public long getPeriod()
- {
- return _period;
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/stats/StatisticsGatherer.java b/java/broker/src/main/java/org/apache/qpid/server/stats/StatisticsGatherer.java
deleted file mode 100644
index 36fec4025a..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/stats/StatisticsGatherer.java
+++ /dev/null
@@ -1,118 +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.stats;
-
-/**
- * This interface is to be implemented by any broker business object that
- * wishes to gather statistics about messages delivered through it.
- *
- * These statistics are exposed using a separate JMX Mbean interface, which
- * calls these methods to retrieve the underlying {@link StatisticsCounter}s
- * and return their attributes. This interface gives a standard way for
- * parts of the broker to set up and configure statistics generation.
- * <p>
- * When creating these objects, there should be a parent/child relationship
- * between them, such that the lowest level gatherer can record staticics if
- * enabled, and pass on the notification to the parent object to allow higher
- * level aggregation. When resetting statistics, this works in the opposite
- * direction, with higher level gatherers also resetting all of their children.
- */
-public interface StatisticsGatherer
-{
- /**
- * Initialise the statistics gathering for this object.
- *
- * This method is responsible for creating any {@link StatisticsCounter}
- * objects and for determining whether statistics generation should be
- * enabled, by checking broker and system configuration.
- *
- * @see StatisticsCounter#DISABLE_STATISTICS
- */
- void initialiseStatistics();
-
- /**
- * This method is responsible for registering the receipt of a message
- * with the counters, and also for passing this notification to any parent
- * {@link StatisticsGatherer}s. If statistics generation is not enabled,
- * then this method should simple delegate to the parent gatherer.
- *
- * @param messageSize the size in bytes of the delivered message
- * @param timestamp the time the message was delivered
- */
- void registerMessageReceived(long messageSize, long timestamp);
-
- /**
- * This method is responsible for registering the delivery of a message
- * with the counters. Message delivery is recorded by the counter using
- * the current system time, as opposed to the message timestamp.
- *
- * @param messageSize the size in bytes of the delivered message
- * @see #registerMessageReceived(long, long)
- */
- void registerMessageDelivered(long messageSize);
-
- /**
- * Gives access to the {@link StatisticsCounter} that is used to count
- * delivered message statistics.
- *
- * @return the {@link StatisticsCounter} that counts delivered messages
- */
- StatisticsCounter getMessageDeliveryStatistics();
-
- /**
- * Gives access to the {@link StatisticsCounter} that is used to count
- * received message statistics.
- *
- * @return the {@link StatisticsCounter} that counts received messages
- */
- StatisticsCounter getMessageReceiptStatistics();
-
- /**
- * Gives access to the {@link StatisticsCounter} that is used to count
- * delivered message size statistics.
- *
- * @return the {@link StatisticsCounter} that counts delivered bytes
- */
- StatisticsCounter getDataDeliveryStatistics();
-
- /**
- * Gives access to the {@link StatisticsCounter} that is used to count
- * received message size statistics.
- *
- * @return the {@link StatisticsCounter} that counts received bytes
- */
- StatisticsCounter getDataReceiptStatistics();
-
- /**
- * Reset the counters for this, and any child {@link StatisticsGatherer}s.
- */
- void resetStatistics();
-
- /**
- * Check if this object has statistics generation enabled.
- *
- * @return true if statistics generation is enabled
- */
- boolean isStatisticsEnabled();
-
- /**
- * Enable or disable statistics generation for this object.
- */
- void setStatisticsEnabled(boolean enabled);
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/store/AbstractMessageStore.java b/java/broker/src/main/java/org/apache/qpid/server/store/AbstractMessageStore.java
deleted file mode 100644
index b9adaeacdf..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/store/AbstractMessageStore.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.store;
-
-import org.apache.qpid.server.virtualhost.VirtualHost;
-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;
-
-public abstract class AbstractMessageStore implements MessageStore
-{
- protected LogSubject _logSubject;
-
- public void configure(VirtualHost virtualHost) throws Exception
- {
- _logSubject = new MessageStoreLogSubject(virtualHost, this);
- CurrentActor.get().message(_logSubject, MessageStoreMessages.CREATED(this.getClass().getName()));
- }
-
- public void close() throws Exception
- {
- CurrentActor.get().message(_logSubject,MessageStoreMessages.CLOSED());
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/store/ConfigurationRecoveryHandler.java b/java/broker/src/main/java/org/apache/qpid/server/store/ConfigurationRecoveryHandler.java
deleted file mode 100755
index a883f656be..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/store/ConfigurationRecoveryHandler.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.store;
-
-import java.nio.ByteBuffer;
-import org.apache.qpid.framing.FieldTable;
-
-public interface ConfigurationRecoveryHandler
-{
- QueueRecoveryHandler begin(MessageStore store);
-
- public static interface QueueRecoveryHandler
- {
- void queue(String queueName, String owner, boolean exclusive, FieldTable arguments);
- ExchangeRecoveryHandler completeQueueRecovery();
- }
-
- public static interface ExchangeRecoveryHandler
- {
- void exchange(String exchangeName, String type, boolean autoDelete);
- BindingRecoveryHandler completeExchangeRecovery();
- }
-
- public static interface BindingRecoveryHandler
- {
- void binding(String exchangeName, String queueName, String bindingKey, ByteBuffer buf);
- void completeBindingRecovery();
- }
-
- public static interface QueueEntryRecoveryHandler
- {
- void complete();
-
- void queueEntry(String queueName, long messageId);
- }
-
-
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/store/DerbyMessageStore.java b/java/broker/src/main/java/org/apache/qpid/server/store/DerbyMessageStore.java
deleted file mode 100644
index 2e694b24ea..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/store/DerbyMessageStore.java
+++ /dev/null
@@ -1,1846 +0,0 @@
-/*
-*
-* Licensed to the Apache Software Foundation (ASF) under one
-* or more contributor license agreements. See the NOTICE file
-* distributed with this work for additional information
-* regarding copyright ownership. The ASF licenses this file
-* to you under the Apache License, Version 2.0 (the
-* "License"); you may not use this file except in compliance
-* with the License. You may obtain a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing,
-* software distributed under the License is distributed on an
-* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-* KIND, either express or implied. See the License for the
-* specific language governing permissions and limitations
-* under the License.
-*
-*/
-package org.apache.qpid.server.store;
-
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.IOException;
-import java.lang.ref.SoftReference;
-import java.nio.ByteBuffer;
-import java.sql.Blob;
-import java.sql.Connection;
-import java.sql.Driver;
-import java.sql.DriverManager;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
-import java.sql.Types;
-import java.util.ArrayList;
-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;
-import org.apache.qpid.framing.FieldTable;
-import org.apache.qpid.server.exchange.Exchange;
-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.queue.AMQQueue;
-
-/**
- * An implementation of a {@link MessageStore} that uses Apache Derby as the persistance
- * mechanism.
- *
- * TODO extract the SQL statements into a generic JDBC store
- */
-public class DerbyMessageStore implements MessageStore
-{
-
- private static final Logger _logger = Logger.getLogger(DerbyMessageStore.class);
-
- public static final String ENVIRONMENT_PATH_PROPERTY = "environment-path";
-
-
- private static final String SQL_DRIVER_NAME = "org.apache.derby.jdbc.EmbeddedDriver";
-
- private static final String DB_VERSION_TABLE_NAME = "QPID_DB_VERSION";
-
- private static final String EXCHANGE_TABLE_NAME = "QPID_EXCHANGE";
- private static final String QUEUE_TABLE_NAME = "QPID_QUEUE";
- private static final String BINDINGS_TABLE_NAME = "QPID_BINDINGS";
- private static final String QUEUE_ENTRY_TABLE_NAME = "QPID_QUEUE_ENTRY";
-
- private static final String META_DATA_TABLE_NAME = "QPID_META_DATA";
- private static final String MESSAGE_CONTENT_TABLE_NAME = "QPID_MESSAGE_CONTENT";
-
- private static final int DB_VERSION = 3;
-
-
-
- private static Class<Driver> DRIVER_CLASS;
-
- private final AtomicLong _messageId = new AtomicLong(0);
- private AtomicBoolean _closed = new AtomicBoolean(false);
-
- private String _connectionURL;
-
- private static final String TABLE_EXISTANCE_QUERY = "SELECT 1 FROM SYS.SYSTABLES WHERE TABLENAME = ?";
-
- private static final String CREATE_DB_VERSION_TABLE = "CREATE TABLE "+DB_VERSION_TABLE_NAME+" ( version int not null )";
- private static final String INSERT_INTO_DB_VERSION = "INSERT INTO "+DB_VERSION_TABLE_NAME+" ( version ) VALUES ( ? )";
-
- private static final String CREATE_EXCHANGE_TABLE = "CREATE TABLE "+EXCHANGE_TABLE_NAME+" ( name varchar(255) not null, type varchar(255) not null, autodelete SMALLINT not null, PRIMARY KEY ( name ) )";
- private static final String CREATE_QUEUE_TABLE = "CREATE TABLE "+QUEUE_TABLE_NAME+" ( name varchar(255) not null, owner varchar(255), exclusive SMALLINT not null, arguments blob, PRIMARY KEY ( name ))";
- private static final String CREATE_BINDINGS_TABLE = "CREATE TABLE "+BINDINGS_TABLE_NAME+" ( exchange_name varchar(255) not null, queue_name varchar(255) not null, binding_key varchar(255) not null, arguments blob , PRIMARY KEY ( exchange_name, queue_name, binding_key ) )";
- private static final String SELECT_FROM_QUEUE = "SELECT name, owner, exclusive, arguments FROM " + QUEUE_TABLE_NAME;
- private static final String FIND_QUEUE = "SELECT name, owner FROM " + QUEUE_TABLE_NAME + " WHERE name = ?";
- private static final String UPDATE_QUEUE_EXCLUSIVITY = "UPDATE " + QUEUE_TABLE_NAME + " SET exclusive = ? WHERE name = ?";
- private static final String SELECT_FROM_EXCHANGE = "SELECT name, type, autodelete FROM " + EXCHANGE_TABLE_NAME;
- private static final String SELECT_FROM_BINDINGS =
- "SELECT exchange_name, queue_name, binding_key, arguments FROM " + BINDINGS_TABLE_NAME + " ORDER BY exchange_name";
- private static final String FIND_BINDING =
- "SELECT * FROM " + BINDINGS_TABLE_NAME + " WHERE exchange_name = ? AND queue_name = ? AND binding_key = ? ";
- private static final String INSERT_INTO_EXCHANGE = "INSERT INTO " + EXCHANGE_TABLE_NAME + " ( name, type, autodelete ) VALUES ( ?, ?, ? )";
- private static final String DELETE_FROM_EXCHANGE = "DELETE FROM " + EXCHANGE_TABLE_NAME + " WHERE name = ?";
- private static final String FIND_EXCHANGE = "SELECT name FROM " + EXCHANGE_TABLE_NAME + " WHERE name = ?";
- private static final String INSERT_INTO_BINDINGS = "INSERT INTO " + BINDINGS_TABLE_NAME + " ( exchange_name, queue_name, binding_key, arguments ) values ( ?, ?, ?, ? )";
- private static final String DELETE_FROM_BINDINGS = "DELETE FROM " + BINDINGS_TABLE_NAME + " WHERE exchange_name = ? AND queue_name = ? AND binding_key = ?";
- private static final String INSERT_INTO_QUEUE = "INSERT INTO " + QUEUE_TABLE_NAME + " (name, owner, exclusive, arguments) VALUES (?, ?, ?, ?)";
- private static final String DELETE_FROM_QUEUE = "DELETE FROM " + QUEUE_TABLE_NAME + " WHERE name = ?";
-
- private static final String CREATE_QUEUE_ENTRY_TABLE = "CREATE TABLE "+QUEUE_ENTRY_TABLE_NAME+" ( queue_name varchar(255) not null, message_id bigint not null, PRIMARY KEY (queue_name, message_id) )";
- private static final String INSERT_INTO_QUEUE_ENTRY = "INSERT INTO " + QUEUE_ENTRY_TABLE_NAME + " (queue_name, message_id) values (?,?)";
- private static final String DELETE_FROM_QUEUE_ENTRY = "DELETE FROM " + QUEUE_ENTRY_TABLE_NAME + " WHERE queue_name = ? AND message_id =?";
- private static final String SELECT_FROM_QUEUE_ENTRY = "SELECT queue_name, message_id FROM " + QUEUE_ENTRY_TABLE_NAME + " ORDER BY queue_name, message_id";
-
-
- private static final String CREATE_META_DATA_TABLE = "CREATE TABLE "+META_DATA_TABLE_NAME+" ( message_id bigint not null, meta_data blob, PRIMARY KEY ( message_id ) )";
- private static final String CREATE_MESSAGE_CONTENT_TABLE = "CREATE TABLE "+MESSAGE_CONTENT_TABLE_NAME+" ( message_id bigint not null, offset int not null, last_byte int not null, content blob , PRIMARY KEY (message_id, offset) )";
-
- private static final String INSERT_INTO_MESSAGE_CONTENT = "INSERT INTO " + MESSAGE_CONTENT_TABLE_NAME + "( message_id, offset, last_byte, content ) values (?, ?, ?, ?)";
- private static final String SELECT_FROM_MESSAGE_CONTENT =
- "SELECT offset, content FROM " + MESSAGE_CONTENT_TABLE_NAME + " WHERE message_id = ? AND last_byte > ? AND offset < ? ORDER BY message_id, offset";
- private static final String DELETE_FROM_MESSAGE_CONTENT = "DELETE FROM " + MESSAGE_CONTENT_TABLE_NAME + " WHERE message_id = ?";
-
- private static final String INSERT_INTO_META_DATA = "INSERT INTO " + META_DATA_TABLE_NAME + "( message_id , meta_data ) values (?, ?)";;
- private static final String SELECT_FROM_META_DATA =
- "SELECT meta_data FROM " + META_DATA_TABLE_NAME + " WHERE message_id = ?";
- private static final String DELETE_FROM_META_DATA = "DELETE FROM " + META_DATA_TABLE_NAME + " WHERE message_id = ?";
- private static final String SELECT_ALL_FROM_META_DATA = "SELECT message_id, meta_data FROM " + META_DATA_TABLE_NAME;
-
- private static final String DERBY_SINGLE_DB_SHUTDOWN_CODE = "08006";
-
-
- private LogSubject _logSubject;
- private boolean _configured;
-
-
- private enum State
- {
- INITIAL,
- CONFIGURING,
- RECOVERING,
- STARTED,
- CLOSING,
- CLOSED
- }
-
- private State _state = State.INITIAL;
-
-
- public void configureConfigStore(String name,
- ConfigurationRecoveryHandler recoveryHandler,
- Configuration storeConfiguration,
- LogSubject logSubject) throws Exception
- {
- stateTransition(State.INITIAL, State.CONFIGURING);
- _logSubject = logSubject;
- CurrentActor.get().message(_logSubject, ConfigStoreMessages.CREATED(this.getClass().getName()));
-
- if(!_configured)
- {
- commonConfiguration(name, storeConfiguration, logSubject);
- _configured = true;
- }
-
- // this recovers durable exchanges, queues, and bindings
- recover(recoveryHandler);
-
-
- stateTransition(State.RECOVERING, State.STARTED);
-
- }
-
-
- public void configureMessageStore(String name,
- MessageStoreRecoveryHandler recoveryHandler,
- Configuration storeConfiguration,
- LogSubject logSubject) throws Exception
- {
- CurrentActor.get().message(_logSubject, MessageStoreMessages.CREATED(this.getClass().getName()));
-
- if(!_configured)
- {
-
- _logSubject = logSubject;
-
- commonConfiguration(name, storeConfiguration, logSubject);
- _configured = true;
- }
-
- recoverMessages(recoveryHandler);
-
- }
-
-
-
- public void configureTransactionLog(String name,
- TransactionLogRecoveryHandler recoveryHandler,
- Configuration storeConfiguration,
- LogSubject logSubject) throws Exception
- {
- CurrentActor.get().message(_logSubject, TransactionLogMessages.CREATED(this.getClass().getName()));
-
- if(!_configured)
- {
-
- _logSubject = logSubject;
-
- commonConfiguration(name, storeConfiguration, logSubject);
- _configured = true;
- }
-
- recoverQueueEntries(recoveryHandler);
-
- }
-
-
-
- private void commonConfiguration(String name, Configuration storeConfiguration, LogSubject logSubject)
- throws ClassNotFoundException, SQLException
- {
- initialiseDriver();
-
- //Update to pick up QPID_WORK and use that as the default location not just derbyDB
-
- final String databasePath = storeConfiguration.getString(ENVIRONMENT_PATH_PROPERTY, System.getProperty("QPID_WORK")
- + File.separator + "derbyDB");
-
- File environmentPath = new File(databasePath);
- if (!environmentPath.exists())
- {
- if (!environmentPath.mkdirs())
- {
- throw new IllegalArgumentException("Environment path " + environmentPath + " could not be read or created. "
- + "Ensure the path is correct and that the permissions are correct.");
- }
- }
-
- CurrentActor.get().message(_logSubject, MessageStoreMessages.STORE_LOCATION(environmentPath.getAbsolutePath()));
-
- createOrOpenDatabase(name, databasePath);
- }
-
- private static synchronized void initialiseDriver() throws ClassNotFoundException
- {
- if(DRIVER_CLASS == null)
- {
- DRIVER_CLASS = (Class<Driver>) Class.forName(SQL_DRIVER_NAME);
- }
- }
-
- private void createOrOpenDatabase(String name, final String environmentPath) throws SQLException
- {
- //FIXME this the _vhost name should not be added here, but derby wont use an empty directory as was possibly just created.
- _connectionURL = "jdbc:derby:" + environmentPath + "/" + name + ";create=true";
-
- Connection conn = newAutoCommitConnection();
-
- createVersionTable(conn);
- createExchangeTable(conn);
- createQueueTable(conn);
- createBindingsTable(conn);
- createQueueEntryTable(conn);
- createMetaDataTable(conn);
- createMessageContentTable(conn);
-
- conn.close();
- }
-
-
-
- private void createVersionTable(final Connection conn) throws SQLException
- {
- if(!tableExists(DB_VERSION_TABLE_NAME, conn))
- {
- Statement stmt = conn.createStatement();
- try
- {
- stmt.execute(CREATE_DB_VERSION_TABLE);
- }
- finally
- {
- stmt.close();
- }
-
- PreparedStatement pstmt = conn.prepareStatement(INSERT_INTO_DB_VERSION);
- try
- {
- pstmt.setInt(1, DB_VERSION);
- pstmt.execute();
- }
- finally
- {
- pstmt.close();
- }
- }
-
- }
-
-
- private void createExchangeTable(final Connection conn) throws SQLException
- {
- if(!tableExists(EXCHANGE_TABLE_NAME, conn))
- {
- Statement stmt = conn.createStatement();
- try
- {
- stmt.execute(CREATE_EXCHANGE_TABLE);
- }
- finally
- {
- stmt.close();
- }
- }
- }
-
- private void createQueueTable(final Connection conn) throws SQLException
- {
- if(!tableExists(QUEUE_TABLE_NAME, conn))
- {
- Statement stmt = conn.createStatement();
- try
- {
- stmt.execute(CREATE_QUEUE_TABLE);
- }
- finally
- {
- stmt.close();
- }
- }
- }
-
- private void createBindingsTable(final Connection conn) throws SQLException
- {
- if(!tableExists(BINDINGS_TABLE_NAME, conn))
- {
- Statement stmt = conn.createStatement();
- try
- {
- stmt.execute(CREATE_BINDINGS_TABLE);
- }
- finally
- {
- stmt.close();
- }
- }
-
- }
-
- private void createQueueEntryTable(final Connection conn) throws SQLException
- {
- if(!tableExists(QUEUE_ENTRY_TABLE_NAME, conn))
- {
- Statement stmt = conn.createStatement();
- try
- {
- stmt.execute(CREATE_QUEUE_ENTRY_TABLE);
- }
- finally
- {
- stmt.close();
- }
- }
-
- }
-
- private void createMetaDataTable(final Connection conn) throws SQLException
- {
- if(!tableExists(META_DATA_TABLE_NAME, conn))
- {
- Statement stmt = conn.createStatement();
- try
- {
- stmt.execute(CREATE_META_DATA_TABLE);
- }
- finally
- {
- stmt.close();
- }
- }
-
- }
-
-
- private void createMessageContentTable(final Connection conn) throws SQLException
- {
- if(!tableExists(MESSAGE_CONTENT_TABLE_NAME, conn))
- {
- Statement stmt = conn.createStatement();
- try
- {
- stmt.execute(CREATE_MESSAGE_CONTENT_TABLE);
- }
- finally
- {
- stmt.close();
- }
- }
-
- }
-
-
-
- private boolean tableExists(final String tableName, final Connection conn) throws SQLException
- {
- PreparedStatement stmt = conn.prepareStatement(TABLE_EXISTANCE_QUERY);
- try
- {
- stmt.setString(1, tableName);
- ResultSet rs = stmt.executeQuery();
- try
- {
- return rs.next();
- }
- finally
- {
- rs.close();
- }
- }
- finally
- {
- stmt.close();
- }
-
- }
-
- public void recover(ConfigurationRecoveryHandler recoveryHandler) throws AMQException
- {
- stateTransition(State.CONFIGURING, State.RECOVERING);
-
- CurrentActor.get().message(_logSubject,MessageStoreMessages.RECOVERY_START());
-
- try
- {
- ConfigurationRecoveryHandler.QueueRecoveryHandler qrh = recoveryHandler.begin(this);
- loadQueues(qrh);
-
- ConfigurationRecoveryHandler.ExchangeRecoveryHandler erh = qrh.completeQueueRecovery();
- List<String> exchanges = loadExchanges(erh);
- ConfigurationRecoveryHandler.BindingRecoveryHandler brh = erh.completeExchangeRecovery();
- recoverBindings(brh, exchanges);
- brh.completeBindingRecovery();
- }
- catch (SQLException e)
- {
-
- throw new AMQStoreException("Error recovering persistent state: " + e.getMessage(), e);
- }
-
-
- }
-
- private void loadQueues(ConfigurationRecoveryHandler.QueueRecoveryHandler qrh) throws SQLException
- {
- Connection conn = newAutoCommitConnection();
- try
- {
- Statement stmt = conn.createStatement();
- try
- {
- ResultSet rs = stmt.executeQuery(SELECT_FROM_QUEUE);
- try
- {
-
- while(rs.next())
- {
- String queueName = rs.getString(1);
- String owner = rs.getString(2);
- boolean exclusive = rs.getBoolean(3);
- Blob argumentsAsBlob = rs.getBlob(4);
-
- byte[] dataAsBytes = argumentsAsBlob.getBytes(1,(int) argumentsAsBlob.length());
- FieldTable arguments;
- if(dataAsBytes.length > 0)
- {
- org.apache.mina.common.ByteBuffer buffer = org.apache.mina.common.ByteBuffer.wrap(dataAsBytes);
-
- arguments = new FieldTable(buffer,buffer.limit());
- }
- else
- {
- arguments = null;
- }
-
- qrh.queue(queueName, owner, exclusive, arguments);
-
- }
-
- }
- finally
- {
- rs.close();
- }
- }
- finally
- {
- stmt.close();
- }
- }
- finally
- {
- conn.close();
- }
- }
-
-
- private List<String> loadExchanges(ConfigurationRecoveryHandler.ExchangeRecoveryHandler erh) throws SQLException
- {
-
- List<String> exchanges = new ArrayList<String>();
- Connection conn = null;
- try
- {
- conn = newAutoCommitConnection();
-
- Statement stmt = conn.createStatement();
- try
- {
- ResultSet rs = stmt.executeQuery(SELECT_FROM_EXCHANGE);
- try
- {
- while(rs.next())
- {
- String exchangeName = rs.getString(1);
- String type = rs.getString(2);
- boolean autoDelete = rs.getShort(3) != 0;
-
- exchanges.add(exchangeName);
-
- erh.exchange(exchangeName, type, autoDelete);
-
- }
- return exchanges;
- }
- finally
- {
- rs.close();
- }
- }
- finally
- {
- stmt.close();
- }
- }
- finally
- {
- if(conn != null)
- {
- conn.close();
- }
- }
-
- }
-
- private void recoverBindings(ConfigurationRecoveryHandler.BindingRecoveryHandler brh, List<String> exchanges) throws SQLException
- {
- _logger.info("Recovering bindings...");
-
- Connection conn = null;
- try
- {
- conn = newAutoCommitConnection();
-
- PreparedStatement stmt = conn.prepareStatement(SELECT_FROM_BINDINGS);
-
- try
- {
- ResultSet rs = stmt.executeQuery();
-
- try
- {
-
- while(rs.next())
- {
- String exchangeName = rs.getString(1);
- String queueName = rs.getString(2);
- String bindingKey = rs.getString(3);
- Blob arguments = rs.getBlob(4);
- java.nio.ByteBuffer buf;
-
- if(arguments != null && arguments.length() != 0)
- {
- byte[] argumentBytes = arguments.getBytes(1, (int) arguments.length());
- buf = java.nio.ByteBuffer.wrap(argumentBytes);
- }
- else
- {
- buf = null;
- }
-
- brh.binding(exchangeName, queueName, bindingKey, buf);
- }
- }
- finally
- {
- rs.close();
- }
- }
- finally
- {
- stmt.close();
- }
-
- }
- finally
- {
- if(conn != null)
- {
- conn.close();
- }
- }
- }
-
-
-
- public void close() throws Exception
- {
- CurrentActor.get().message(_logSubject,MessageStoreMessages.CLOSED());
- _closed.getAndSet(true);
-
- try
- {
- Connection conn = DriverManager.getConnection(_connectionURL + ";shutdown=true");
- // Shouldn't reach this point - shutdown=true should throw SQLException
- conn.close();
- _logger.error("Unable to shut down the store");
- }
- catch (SQLException e)
- {
- if (e.getSQLState().equalsIgnoreCase(DERBY_SINGLE_DB_SHUTDOWN_CODE))
- {
- //expected and represents a clean shutdown of this database only, do nothing.
- }
- else
- {
- _logger.error("Exception whilst shutting down the store: " + e);
- }
- }
- }
-
- public StoredMessage addMessage(StorableMessageMetaData metaData)
- {
- if(metaData.isPersistent())
- {
- return new StoredDerbyMessage(_messageId.incrementAndGet(), metaData);
- }
- else
- {
- return new StoredMemoryMessage(_messageId.incrementAndGet(), metaData);
- }
- }
-
- public StoredMessage getMessage(long messageNumber)
- {
- return null;
- }
-
- public void removeMessage(long messageId)
- {
- try
- {
- Connection conn = newConnection();
- try
- {
- PreparedStatement stmt = conn.prepareStatement(DELETE_FROM_META_DATA);
- try
- {
- stmt.setLong(1,messageId);
- int results = stmt.executeUpdate();
- stmt.close();
-
- if (results == 0)
- {
- throw new RuntimeException("Message metadata not found for message id " + messageId);
- }
-
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Deleted metadata for message " + messageId);
- }
-
- stmt = conn.prepareStatement(DELETE_FROM_MESSAGE_CONTENT);
- stmt.setLong(1,messageId);
- results = stmt.executeUpdate();
- }
- finally
- {
- stmt.close();
- }
- conn.commit();
- }
- catch(SQLException e)
- {
- try
- {
- conn.rollback();
- }
- catch(SQLException t)
- {
- // ignore - we are re-throwing underlying exception
- }
-
- throw e;
-
- }
- finally
- {
- conn.close();
- }
- }
- catch (SQLException e)
- {
- throw new RuntimeException("Error removing message with id " + messageId + " from database: " + e.getMessage(), e);
- }
-
- }
-
- public void createExchange(Exchange exchange) throws AMQStoreException
- {
- if (_state != State.RECOVERING)
- {
- try
- {
- Connection conn = newAutoCommitConnection();
-
- try
- {
-
-
- PreparedStatement stmt = conn.prepareStatement(FIND_EXCHANGE);
- try
- {
- stmt.setString(1, exchange.getNameShortString().toString());
- ResultSet rs = stmt.executeQuery();
- try
- {
-
- // If we don't have any data in the result set then we can add this exchange
- if (!rs.next())
- {
-
- PreparedStatement insertStmt = conn.prepareStatement(INSERT_INTO_EXCHANGE);
- try
- {
- insertStmt.setString(1, exchange.getName().toString());
- insertStmt.setString(2, exchange.getTypeShortString().asString());
- insertStmt.setShort(3, exchange.isAutoDelete() ? (short) 1 : (short) 0);
- insertStmt.execute();
- }
- finally
- {
- insertStmt.close();
- }
- }
- }
- finally
- {
- rs.close();
- }
- }
- finally
- {
- stmt.close();
- }
-
- }
- finally
- {
- conn.close();
- }
- }
- catch (SQLException e)
- {
- throw new AMQStoreException("Error writing Exchange with name " + exchange.getNameShortString() + " to database: " + e.getMessage(), e);
- }
- }
-
- }
-
- public void removeExchange(Exchange exchange) throws AMQStoreException
- {
-
- try
- {
- Connection conn = newAutoCommitConnection();
- try
- {
- PreparedStatement stmt = conn.prepareStatement(DELETE_FROM_EXCHANGE);
- try
- {
- stmt.setString(1, exchange.getNameShortString().toString());
- int results = stmt.executeUpdate();
- stmt.close();
- if(results == 0)
- {
- throw new AMQStoreException("Exchange " + exchange.getNameShortString() + " not found");
- }
- }
- finally
- {
- stmt.close();
- }
- }
- finally
- {
- conn.close();
- }
- }
- catch (SQLException e)
- {
- throw new AMQStoreException("Error deleting Exchange with name " + exchange.getNameShortString() + " from database: " + e.getMessage(), e);
- }
- }
-
- public void bindQueue(Exchange exchange, AMQShortString routingKey, AMQQueue queue, FieldTable args)
- throws AMQStoreException
- {
- if (_state != State.RECOVERING)
- {
- try
- {
- Connection conn = newAutoCommitConnection();
-
- try
- {
-
- PreparedStatement stmt = conn.prepareStatement(FIND_BINDING);
- try
- {
- stmt.setString(1, exchange.getNameShortString().toString() );
- stmt.setString(2, queue.getNameShortString().toString());
- stmt.setString(3, routingKey == null ? null : routingKey.toString());
-
- ResultSet rs = stmt.executeQuery();
- try
- {
- // If this binding is not already in the store then create it.
- if (!rs.next())
- {
- PreparedStatement insertStmt = conn.prepareStatement(INSERT_INTO_BINDINGS);
- try
- {
- insertStmt.setString(1, exchange.getNameShortString().toString() );
- insertStmt.setString(2, queue.getNameShortString().toString());
- 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);
- */
- byte[] bytes = args.getDataAsBytes();
- ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
- insertStmt.setBinaryStream(4, bis, bytes.length);
- }
- else
- {
- insertStmt.setNull(4, Types.BLOB);
- }
-
- insertStmt.executeUpdate();
- }
- finally
- {
- insertStmt.close();
- }
- }
- }
- finally
- {
- rs.close();
- }
- }
- finally
- {
- stmt.close();
- }
- }
- finally
- {
- conn.close();
- }
- }
- catch (SQLException e)
- {
- throw new AMQStoreException("Error writing binding for AMQQueue with name " + queue.getNameShortString() + " to exchange "
- + exchange.getNameShortString() + " to database: " + e.getMessage(), e);
- }
-
- }
-
-
- }
-
- public void unbindQueue(Exchange exchange, AMQShortString routingKey, AMQQueue queue, FieldTable args)
- throws AMQStoreException
- {
- Connection conn = null;
-
- try
- {
- conn = newAutoCommitConnection();
- // exchange_name varchar(255) not null, queue_name varchar(255) not null, binding_key varchar(255), arguments blob
- PreparedStatement stmt = conn.prepareStatement(DELETE_FROM_BINDINGS);
- stmt.setString(1, exchange.getNameShortString().toString() );
- stmt.setString(2, queue.getNameShortString().toString());
- stmt.setString(3, routingKey == null ? null : routingKey.toString());
-
- int result = stmt.executeUpdate();
- stmt.close();
-
- if(result != 1)
- {
- throw new AMQStoreException("Queue binding for queue with name " + queue.getNameShortString() + " to exchange "
- + exchange.getNameShortString() + " not found");
- }
- }
- catch (SQLException e)
- {
- throw new AMQStoreException("Error removing binding for AMQQueue with name " + queue.getNameShortString() + " to exchange "
- + exchange.getNameShortString() + " in database: " + e.getMessage(), e);
- }
- finally
- {
- if(conn != null)
- {
- try
- {
- conn.close();
- }
- catch (SQLException e)
- {
- _logger.error(e);
- }
- }
-
- }
-
-
- }
-
- public void createQueue(AMQQueue queue) throws AMQStoreException
- {
- createQueue(queue, null);
- }
-
- public void createQueue(AMQQueue queue, FieldTable arguments) throws AMQStoreException
- {
- _logger.debug("public void createQueue(AMQQueue queue = " + queue + "): called");
-
- if (_state != State.RECOVERING)
- {
- try
- {
- Connection conn = newAutoCommitConnection();
-
- PreparedStatement stmt = conn.prepareStatement(FIND_QUEUE);
- try
- {
- stmt.setString(1, queue.getNameShortString().toString());
- ResultSet rs = stmt.executeQuery();
- try
- {
-
- // If we don't have any data in the result set then we can add this queue
- if (!rs.next())
- {
- PreparedStatement insertStmt = conn.prepareStatement(INSERT_INTO_QUEUE);
-
- try
- {
- String owner = queue.getOwner() == null ? null : queue.getOwner().toString();
-
- insertStmt.setString(1, queue.getNameShortString().toString());
- insertStmt.setString(2, owner);
- insertStmt.setBoolean(3,queue.isExclusive());
-
- final byte[] underlying;
- if(arguments != null)
- {
- underlying = arguments.getDataAsBytes();
- }
- else
- {
- underlying = new byte[0];
- }
-
- ByteArrayInputStream bis = new ByteArrayInputStream(underlying);
- insertStmt.setBinaryStream(4,bis,underlying.length);
-
- insertStmt.execute();
- }
- finally
- {
- insertStmt.close();
- }
- }
- }
- finally
- {
- rs.close();
- }
- }
- finally
- {
- stmt.close();
- }
- conn.close();
-
- }
- catch (SQLException e)
- {
- throw new AMQStoreException("Error writing AMQQueue with name " + queue.getNameShortString() + " to database: " + e.getMessage(), e);
- }
- }
- }
-
- /**
- * Updates the specified queue in the persistent store, IF it is already present. If the queue
- * is not present in the store, it will not be added.
- *
- * NOTE: Currently only updates the exclusivity.
- *
- * @param queue The queue to update the entry for.
- * @throws AMQStoreException If the operation fails for any reason.
- */
- public void updateQueue(final AMQQueue queue) throws AMQStoreException
- {
- if (_state != State.RECOVERING)
- {
- try
- {
- Connection conn = newAutoCommitConnection();
-
- try
- {
- PreparedStatement stmt = conn.prepareStatement(FIND_QUEUE);
- try
- {
- stmt.setString(1, queue.getNameShortString().toString());
-
- ResultSet rs = stmt.executeQuery();
- try
- {
- if (rs.next())
- {
- PreparedStatement stmt2 = conn.prepareStatement(UPDATE_QUEUE_EXCLUSIVITY);
- try
- {
- stmt2.setBoolean(1,queue.isExclusive());
- stmt2.setString(2, queue.getNameShortString().toString());
-
- stmt2.execute();
- }
- finally
- {
- stmt2.close();
- }
- }
- }
- finally
- {
- rs.close();
- }
- }
- finally
- {
- stmt.close();
- }
- }
- finally
- {
- conn.close();
- }
- }
- catch (SQLException e)
- {
- throw new AMQStoreException("Error updating AMQQueue with name " + queue.getNameShortString() + " to database: " + e.getMessage(), e);
- }
- }
-
- }
-
- /**
- * Convenience method to create a new Connection configured for TRANSACTION_READ_COMMITED
- * isolation and with auto-commit transactions enabled.
- */
- private Connection newAutoCommitConnection() throws SQLException
- {
- final Connection connection = newConnection();
- try
- {
- connection.setAutoCommit(true);
- }
- catch (SQLException sqlEx)
- {
-
- try
- {
- connection.close();
- }
- finally
- {
- throw sqlEx;
- }
- }
-
- return connection;
- }
-
- /**
- * Convenience method to create a new Connection configured for TRANSACTION_READ_COMMITED
- * isolation and with auto-commit transactions disabled.
- */
- private Connection newConnection() throws SQLException
- {
- final Connection connection = DriverManager.getConnection(_connectionURL);
- try
- {
- connection.setAutoCommit(false);
- connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
- }
- catch (SQLException sqlEx)
- {
- try
- {
- connection.close();
- }
- finally
- {
- throw sqlEx;
- }
- }
- return connection;
- }
-
- public void removeQueue(final AMQQueue queue) throws AMQStoreException
- {
- AMQShortString name = queue.getNameShortString();
- _logger.debug("public void removeQueue(AMQShortString name = " + name + "): called");
- Connection conn = null;
-
- try
- {
- conn = newAutoCommitConnection();
- PreparedStatement stmt = conn.prepareStatement(DELETE_FROM_QUEUE);
- stmt.setString(1, name.toString());
- int results = stmt.executeUpdate();
- stmt.close();
-
- if (results == 0)
- {
- throw new AMQStoreException("Queue " + name + " not found");
- }
- }
- catch (SQLException e)
- {
- throw new AMQStoreException("Error deleting AMQQueue with name " + name + " from database: " + e.getMessage(), e);
- }
- finally
- {
- if(conn != null)
- {
- try
- {
- conn.close();
- }
- catch (SQLException e)
- {
- _logger.error(e);
- }
- }
-
- }
-
-
- }
-
- public Transaction newTransaction()
- {
- return new DerbyTransaction();
- }
-
- public void enqueueMessage(ConnectionWrapper connWrapper, final TransactionLogResource queue, Long messageId) throws AMQStoreException
- {
- String name = queue.getResourceName();
-
- Connection conn = connWrapper.getConnection();
-
-
- try
- {
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Enqueuing message " + messageId + " on queue " + name + "[Connection" + conn + "]");
- }
-
- PreparedStatement stmt = conn.prepareStatement(INSERT_INTO_QUEUE_ENTRY);
- try
- {
- stmt.setString(1,name);
- stmt.setLong(2,messageId);
- stmt.executeUpdate();
- }
- finally
- {
- stmt.close();
- }
- }
- catch (SQLException e)
- {
- _logger.error("Failed to enqueue: " + e.getMessage(), e);
- throw new AMQStoreException("Error writing enqueued message with id " + messageId + " for queue " + name
- + " to database", e);
- }
-
- }
-
- public void dequeueMessage(ConnectionWrapper connWrapper, final TransactionLogResource queue, Long messageId) throws AMQStoreException
- {
- String name = queue.getResourceName();
-
-
- Connection conn = connWrapper.getConnection();
-
-
- try
- {
- PreparedStatement stmt = conn.prepareStatement(DELETE_FROM_QUEUE_ENTRY);
- try
- {
- stmt.setString(1,name);
- stmt.setLong(2,messageId);
- int results = stmt.executeUpdate();
-
-
-
- if(results != 1)
- {
- throw new AMQStoreException("Unable to find message with id " + messageId + " on queue " + name);
- }
-
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Dequeuing message " + messageId + " on queue " + name );//+ "[Connection" + conn + "]");
- }
- }
- finally
- {
- stmt.close();
- }
- }
- catch (SQLException e)
- {
- _logger.error("Failed to dequeue: " + e.getMessage(), e);
- throw new AMQStoreException("Error deleting enqueued message with id " + messageId + " for queue " + name
- + " from database", e);
- }
-
- }
-
- private static final class ConnectionWrapper
- {
- private final Connection _connection;
-
- public ConnectionWrapper(Connection conn)
- {
- _connection = conn;
- }
-
- public Connection getConnection()
- {
- return _connection;
- }
- }
-
-
- public void commitTran(ConnectionWrapper connWrapper) throws AMQStoreException
- {
-
- try
- {
- Connection conn = connWrapper.getConnection();
- conn.commit();
-
- if (_logger.isDebugEnabled())
- {
- _logger.debug("commit tran completed");
- }
-
- conn.close();
- }
- catch (SQLException e)
- {
- throw new AMQStoreException("Error commit tx: " + e.getMessage(), e);
- }
- finally
- {
-
- }
- }
-
- public StoreFuture commitTranAsync(ConnectionWrapper connWrapper) throws AMQStoreException
- {
- commitTran(connWrapper);
- return new StoreFuture()
- {
- public boolean isComplete()
- {
- return true;
- }
-
- public void waitForCompletion()
- {
-
- }
- };
-
- }
-
- public void abortTran(ConnectionWrapper connWrapper) throws AMQStoreException
- {
- if (connWrapper == null)
- {
- throw new AMQStoreException("Fatal internal error: transactional context is empty at abortTran");
- }
-
- if (_logger.isDebugEnabled())
- {
- _logger.debug("abort tran called: " + connWrapper.getConnection());
- }
-
- try
- {
- Connection conn = connWrapper.getConnection();
- conn.rollback();
- conn.close();
- }
- catch (SQLException e)
- {
- throw new AMQStoreException("Error aborting transaction: " + e.getMessage(), e);
- }
-
- }
-
- public Long getNewMessageId()
- {
- return _messageId.incrementAndGet();
- }
-
-
- private void storeMetaData(Connection conn, long messageId, StorableMessageMetaData metaData)
- throws SQLException
- {
- if(_logger.isDebugEnabled())
- {
- _logger.debug("Adding metadata for message " +messageId);
- }
-
- PreparedStatement stmt = conn.prepareStatement(INSERT_INTO_META_DATA);
- try
- {
- stmt.setLong(1,messageId);
-
- final int bodySize = 1 + metaData.getStorableSize();
- byte[] underlying = new byte[bodySize];
- underlying[0] = (byte) metaData.getType().ordinal();
- java.nio.ByteBuffer buf = java.nio.ByteBuffer.wrap(underlying);
- buf.position(1);
- buf = buf.slice();
-
- metaData.writeToBuffer(0, buf);
- ByteArrayInputStream bis = new ByteArrayInputStream(underlying);
- try
- {
- stmt.setBinaryStream(2,bis,underlying.length);
- int result = stmt.executeUpdate();
-
- if(result == 0)
- {
- throw new RuntimeException("Unable to add meta data for message " +messageId);
- }
- }
- finally
- {
- try
- {
- bis.close();
- }
- catch (IOException e)
- {
-
- throw new SQLException(e);
- }
- }
-
- }
- finally
- {
- stmt.close();
- }
-
- }
-
-
-
-
- private void recoverMessages(MessageStoreRecoveryHandler recoveryHandler) throws SQLException
- {
- Connection conn = newAutoCommitConnection();
- try
- {
- MessageStoreRecoveryHandler.StoredMessageRecoveryHandler messageHandler = recoveryHandler.begin();
-
- Statement stmt = conn.createStatement();
- try
- {
- ResultSet rs = stmt.executeQuery(SELECT_ALL_FROM_META_DATA);
- try
- {
-
- long maxId = 0;
-
- while(rs.next())
- {
-
- long messageId = rs.getLong(1);
- Blob dataAsBlob = rs.getBlob(2);
-
- if(messageId > maxId)
- {
- maxId = messageId;
- }
-
- byte[] dataAsBytes = dataAsBlob.getBytes(1,(int) dataAsBlob.length());
- java.nio.ByteBuffer buf = java.nio.ByteBuffer.wrap(dataAsBytes);
- buf.position(1);
- buf = buf.slice();
- MessageMetaDataType type = MessageMetaDataType.values()[dataAsBytes[0]];
- StorableMessageMetaData metaData = type.getFactory().createMetaData(buf);
- StoredDerbyMessage message = new StoredDerbyMessage(messageId, metaData, false);
- messageHandler.message(message);
- }
-
- _messageId.set(maxId);
-
- messageHandler.completeMessageRecovery();
- }
- finally
- {
- rs.close();
- }
- }
- finally
- {
- stmt.close();
- }
- }
- finally
- {
- conn.close();
- }
- }
-
-
-
- private void recoverQueueEntries(TransactionLogRecoveryHandler recoveryHandler) throws SQLException
- {
- Connection conn = newAutoCommitConnection();
- try
- {
- TransactionLogRecoveryHandler.QueueEntryRecoveryHandler queueEntryHandler = recoveryHandler.begin(this);
-
- Statement stmt = conn.createStatement();
- try
- {
- ResultSet rs = stmt.executeQuery(SELECT_FROM_QUEUE_ENTRY);
- try
- {
- while(rs.next())
- {
-
- String queueName = rs.getString(1);
- long messageId = rs.getLong(2);
- queueEntryHandler.queueEntry(queueName,messageId);
- }
- }
- finally
- {
- rs.close();
- }
- }
- finally
- {
- stmt.close();
- }
-
- queueEntryHandler.completeQueueEntryRecovery();
- }
- finally
- {
- conn.close();
- }
- }
-
- StorableMessageMetaData getMetaData(long messageId) throws SQLException
- {
-
- Connection conn = newAutoCommitConnection();
- try
- {
- PreparedStatement stmt = conn.prepareStatement(SELECT_FROM_META_DATA);
- try
- {
- stmt.setLong(1,messageId);
- ResultSet rs = stmt.executeQuery();
- try
- {
-
- if(rs.next())
- {
- Blob dataAsBlob = rs.getBlob(1);
-
- byte[] dataAsBytes = dataAsBlob.getBytes(1,(int) dataAsBlob.length());
- java.nio.ByteBuffer buf = java.nio.ByteBuffer.wrap(dataAsBytes);
- buf.position(1);
- buf = buf.slice();
- MessageMetaDataType type = MessageMetaDataType.values()[dataAsBytes[0]];
- StorableMessageMetaData metaData = type.getFactory().createMetaData(buf);
-
- return metaData;
- }
- else
- {
- throw new RuntimeException("Meta data not found for message with id " + messageId);
- }
- }
- finally
- {
- rs.close();
- }
- }
- finally
- {
- stmt.close();
- }
- }
- finally
- {
- conn.close();
- }
- }
-
-
- private void addContent(Connection conn, long messageId, int offset, ByteBuffer src)
- {
- if(_logger.isDebugEnabled())
- {
- _logger.debug("Adding content chunk offset " + offset + " for message " +messageId);
- }
-
- try
- {
- src = src.slice();
-
- byte[] chunkData = new byte[src.limit()];
- src.duplicate().get(chunkData);
-
- PreparedStatement stmt = conn.prepareStatement(INSERT_INTO_MESSAGE_CONTENT);
- stmt.setLong(1,messageId);
- stmt.setInt(2, offset);
- 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);
- */
- ByteArrayInputStream bis = new ByteArrayInputStream(chunkData);
- stmt.setBinaryStream(4, bis, chunkData.length);
- stmt.executeUpdate();
- stmt.close();
- }
- catch (SQLException e)
- {
- if(conn != null)
- {
- try
- {
- conn.close();
- }
- catch (SQLException e1)
- {
-
- }
- }
-
- throw new RuntimeException("Error adding content chunk offset " + offset + " for message " + messageId + ": " + e.getMessage(), e);
- }
-
- }
-
-
- public int getContent(long messageId, int offset, ByteBuffer dst)
- {
- Connection conn = null;
-
-
- try
- {
- conn = newAutoCommitConnection();
-
- PreparedStatement stmt = conn.prepareStatement(SELECT_FROM_MESSAGE_CONTENT);
- stmt.setLong(1,messageId);
- stmt.setInt(2, offset);
- stmt.setInt(3, offset+dst.remaining());
- ResultSet rs = stmt.executeQuery();
-
- int written = 0;
-
- while(rs.next())
- {
- int offsetInMessage = rs.getInt(1);
- Blob dataAsBlob = rs.getBlob(2);
-
- final int size = (int) dataAsBlob.length();
- byte[] dataAsBytes = dataAsBlob.getBytes(1, size);
-
- int posInArray = offset + written - offsetInMessage;
- int count = size - posInArray;
- if(count > dst.remaining())
- {
- count = dst.remaining();
- }
- dst.put(dataAsBytes,posInArray,count);
- written+=count;
-
- if(dst.remaining() == 0)
- {
- break;
- }
- }
-
- stmt.close();
- conn.close();
- return written;
-
- }
- catch (SQLException e)
- {
- if(conn != null)
- {
- try
- {
- conn.close();
- }
- catch (SQLException e1)
- {
-
- }
- }
-
- throw new RuntimeException("Error retrieving content from offset " + offset + " for message " + messageId + ": " + e.getMessage(), e);
- }
-
-
-
- }
-
- public boolean isPersistent()
- {
- return true;
- }
-
-
- private synchronized void stateTransition(State requiredState, State newState) throws AMQStoreException
- {
- if (_state != requiredState)
- {
- throw new AMQStoreException("Cannot transition to the state: " + newState + "; need to be in state: " + requiredState
- + "; currently in state: " + _state);
- }
-
- _state = newState;
- }
-
-
- private class DerbyTransaction implements Transaction
- {
- private final ConnectionWrapper _connWrapper;
-
-
- private DerbyTransaction()
- {
- try
- {
- _connWrapper = new ConnectionWrapper(newConnection());
- }
- catch (SQLException e)
- {
- throw new RuntimeException(e);
- }
- }
-
- public void enqueueMessage(TransactionLogResource queue, Long messageId) throws AMQStoreException
- {
- DerbyMessageStore.this.enqueueMessage(_connWrapper, queue, messageId);
- }
-
- public void dequeueMessage(TransactionLogResource queue, Long messageId) throws AMQStoreException
- {
- DerbyMessageStore.this.dequeueMessage(_connWrapper, queue, messageId);
-
- }
-
- public void commitTran() throws AMQStoreException
- {
- DerbyMessageStore.this.commitTran(_connWrapper);
- }
-
- public StoreFuture commitTranAsync() throws AMQStoreException
- {
- return DerbyMessageStore.this.commitTranAsync(_connWrapper);
- }
-
- public void abortTran() throws AMQStoreException
- {
- DerbyMessageStore.this.abortTran(_connWrapper);
- }
- }
-
- private class StoredDerbyMessage implements StoredMessage
- {
-
- private final long _messageId;
- private volatile SoftReference<StorableMessageMetaData> _metaDataRef;
- private Connection _conn;
-
- StoredDerbyMessage(long messageId, StorableMessageMetaData metaData)
- {
- this(messageId, metaData, true);
- }
-
-
- StoredDerbyMessage(long messageId,
- StorableMessageMetaData metaData, boolean persist)
- {
- try
- {
- _messageId = messageId;
-
- _metaDataRef = new SoftReference<StorableMessageMetaData>(metaData);
- if(persist)
- {
- _conn = newConnection();
- storeMetaData(_conn, messageId, metaData);
- }
- }
- catch (SQLException e)
- {
- throw new RuntimeException(e);
- }
-
- }
-
- public StorableMessageMetaData getMetaData()
- {
- StorableMessageMetaData metaData = _metaDataRef.get();
- if(metaData == null)
- {
- try
- {
- metaData = DerbyMessageStore.this.getMetaData(_messageId);
- }
- catch (SQLException e)
- {
- throw new RuntimeException(e);
- }
- _metaDataRef = new SoftReference<StorableMessageMetaData>(metaData);
- }
-
- return metaData;
- }
-
- public long getMessageNumber()
- {
- return _messageId;
- }
-
- public void addContent(int offsetInMessage, java.nio.ByteBuffer src)
- {
- DerbyMessageStore.this.addContent(_conn, _messageId, offsetInMessage, src);
- }
-
- public int getContent(int offsetInMessage, java.nio.ByteBuffer dst)
- {
- return DerbyMessageStore.this.getContent(_messageId, offsetInMessage, dst);
- }
-
- public StoreFuture flushToStore()
- {
- try
- {
- if(_conn != null)
- {
- if(_logger.isDebugEnabled())
- {
- _logger.debug("Flushing message " + _messageId + " to store");
- }
-
- _conn.commit();
- _conn.close();
- }
- }
- catch (SQLException e)
- {
- if(_logger.isDebugEnabled())
- {
- _logger.debug("Error when trying to flush message " + _messageId + " to store: " + e);
- }
- throw new RuntimeException(e);
- }
- finally
- {
- _conn = null;
- }
- return IMMEDIATE_FUTURE;
- }
-
- public void remove()
- {
- flushToStore();
- DerbyMessageStore.this.removeMessage(_messageId);
- }
- }
-
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/store/DurableConfigurationStore.java b/java/broker/src/main/java/org/apache/qpid/server/store/DurableConfigurationStore.java
deleted file mode 100755
index 5fb23653cb..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/store/DurableConfigurationStore.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.store;
-
-import org.apache.commons.configuration.Configuration;
-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.logging.LogSubject;
-import org.apache.qpid.server.queue.AMQQueue;
-
-public interface DurableConfigurationStore
-{
-
- public static interface Source
- {
- DurableConfigurationStore getDurableConfigurationStore();
- }
-
- /**
- * Called after instantiation in order to configure the message store. A particular implementation can define
- * whatever parameters it wants.
- *
- * @param name The name to be used by this storem
- * @param recoveryHandler Handler to be called as the store recovers on start up
- * @param config The apache commons configuration object.
- *
- * @throws Exception If any error occurs that means the store is unable to configure itself.
- */
- void configureConfigStore(String name,
- ConfigurationRecoveryHandler recoveryHandler,
- Configuration config,
- LogSubject logSubject) throws Exception;
- /**
- * Makes the specified exchange persistent.
- *
- * @param exchange The exchange to persist.
- *
- * @throws AMQStoreException If the operation fails for any reason.
- */
- void createExchange(Exchange exchange) throws AMQStoreException;
-
- /**
- * Removes the specified persistent exchange.
- *
- * @param exchange The exchange to remove.
- *
- * @throws AMQStoreException If the operation fails for any reason.
- */
- void removeExchange(Exchange exchange) throws AMQStoreException;
-
- /**
- * Binds the specified queue to an exchange with a routing key.
- *
- * @param exchange The exchange to bind to.
- * @param routingKey The routing key to bind by.
- * @param queue The queue to bind.
- * @param args Additional parameters.
- *
- * @throws AMQStoreException if the operation fails for any reason.
- */
- void bindQueue(Exchange exchange, AMQShortString routingKey, AMQQueue queue, FieldTable args) throws AMQStoreException;
-
- /**
- * Unbinds the specified from an exchange under a particular routing key.
- *
- * @param exchange The exchange to unbind from.
- * @param routingKey The routing key to unbind.
- * @param queue The queue to unbind.
- * @param args Additonal parameters.
- *
- * @throws AMQStoreException If the operation fails for any reason.
- */
- void unbindQueue(Exchange exchange, AMQShortString routingKey, AMQQueue queue, FieldTable args) throws AMQStoreException;
-
- /**
- * Makes the specified queue persistent.
- *
- * @param queue The queue to store.
- *
- * @throws AMQStoreException If the operation fails for any reason.
- */
- void createQueue(AMQQueue queue) throws AMQStoreException;
-
- /**
- * Makes the specified queue persistent.
- *
- * @param queue The queue to store.
- * @param arguments The additional arguments to the binding
- *
- * @throws AMQStoreException If the operation fails for any reason.
- */
- void createQueue(AMQQueue queue, FieldTable arguments) throws AMQStoreException;
-
- /**
- * Removes the specified queue from the persistent store.
- *
- * @param queue The queue to remove.
- *
- * @throws AMQStoreException If the operation fails for any reason.
- */
- void removeQueue(AMQQueue queue) throws AMQStoreException;
-
- /**
- * Updates the specified queue in the persistent store, IF it is already present. If the queue
- * is not present in the store, it will not be added.
- *
- * @param queue The queue to update the entry for.
- * @throws AMQStoreException If the operation fails for any reason.
- */
- void updateQueue(AMQQueue queue) throws AMQStoreException;
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/store/MemoryMessageStore.java b/java/broker/src/main/java/org/apache/qpid/server/store/MemoryMessageStore.java
deleted file mode 100644
index d008d42fa0..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/store/MemoryMessageStore.java
+++ /dev/null
@@ -1,196 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.store;
-
-import 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;
-import org.apache.qpid.framing.FieldTable;
-import org.apache.qpid.server.exchange.Exchange;
-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.queue.AMQQueue;
-
-/** A simple message store that stores the messages in a threadsafe structure in memory. */
-public class MemoryMessageStore implements MessageStore
-{
- private static final Logger _log = Logger.getLogger(MemoryMessageStore.class);
-
- private static final int DEFAULT_HASHTABLE_CAPACITY = 50000;
-
- private static final String HASHTABLE_CAPACITY_CONFIG = "hashtable-capacity";
-
-
- private final AtomicLong _messageId = new AtomicLong(1);
- private AtomicBoolean _closed = new AtomicBoolean(false);
- private LogSubject _logSubject;
-
- private static final Transaction IN_MEMORY_TRANSACTION = new Transaction()
- {
- public void enqueueMessage(TransactionLogResource queue, Long messageId) throws AMQStoreException
- {
- }
-
- public void dequeueMessage(TransactionLogResource queue, Long messageId) throws AMQStoreException
- {
- }
-
- public void commitTran() throws AMQStoreException
- {
- }
-
- public StoreFuture commitTranAsync() throws AMQStoreException
- {
- return IMMEDIATE_FUTURE;
- }
-
- public void abortTran() throws AMQStoreException
- {
- }
-
- };
-
- public void configureConfigStore(String name, ConfigurationRecoveryHandler handler, Configuration configuration, LogSubject logSubject) throws Exception
- {
- _logSubject = logSubject;
- CurrentActor.get().message(_logSubject, ConfigStoreMessages.CREATED(this.getClass().getName()));
-
-
- }
-
- public void configureMessageStore(String name,
- MessageStoreRecoveryHandler recoveryHandler,
- Configuration config,
- LogSubject logSubject) throws Exception
- {
- if(_logSubject == null)
- {
- _logSubject = logSubject;
- }
- int hashtableCapacity = config.getInt(name + "." + HASHTABLE_CAPACITY_CONFIG, DEFAULT_HASHTABLE_CAPACITY);
- _log.info("Using capacity " + hashtableCapacity + " for hash tables");
- CurrentActor.get().message(_logSubject, MessageStoreMessages.CREATED(this.getClass().getName()));
- }
-
- public void close() throws Exception
- {
- _closed.getAndSet(true);
- CurrentActor.get().message(_logSubject,MessageStoreMessages.CLOSED());
-
- }
-
- public StoredMessage addMessage(StorableMessageMetaData metaData)
- {
- final long id = _messageId.getAndIncrement();
- StoredMemoryMessage message = new StoredMemoryMessage(id, metaData);
-
- return message;
- }
-
-
- public void createExchange(Exchange exchange) throws AMQStoreException
- {
-
- }
-
- public void removeExchange(Exchange exchange) throws AMQStoreException
- {
-
- }
-
- public void bindQueue(Exchange exchange, AMQShortString routingKey, AMQQueue queue, FieldTable args) throws AMQStoreException
- {
-
- }
-
- public void unbindQueue(Exchange exchange, AMQShortString routingKey, AMQQueue queue, FieldTable args) throws AMQStoreException
- {
-
- }
-
-
- public void createQueue(AMQQueue queue) throws AMQStoreException
- {
- // Not requred to do anything
- }
-
- public void createQueue(AMQQueue queue, FieldTable arguments) throws AMQStoreException
- {
- // Not required to do anything
- }
-
- public void removeQueue(final AMQQueue queue) throws AMQStoreException
- {
- // Not required to do anything
- }
-
- public void updateQueue(final AMQQueue queue) throws AMQStoreException
- {
- // Not required to do anything
- }
-
- public void configureTransactionLog(String name,
- TransactionLogRecoveryHandler recoveryHandler,
- Configuration storeConfiguration,
- LogSubject logSubject) throws Exception
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public Transaction newTransaction()
- {
- return IN_MEMORY_TRANSACTION;
- }
-
-
- public List<AMQQueue> createQueues() throws AMQException
- {
- return null;
- }
-
- public Long getNewMessageId()
- {
- return _messageId.getAndIncrement();
- }
-
- public boolean isPersistent()
- {
- return false;
- }
-
- private void checkNotClosed() throws MessageStoreClosedException
- {
- if (_closed.get())
- {
- throw new MessageStoreClosedException();
- }
- }
-
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/store/MessageMetaDataType.java b/java/broker/src/main/java/org/apache/qpid/server/store/MessageMetaDataType.java
deleted file mode 100755
index 428bb1e41b..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/store/MessageMetaDataType.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.store;
-
-import org.apache.qpid.server.message.MessageMetaData;
-import org.apache.qpid.server.message.MessageMetaData_0_10;
-
-import java.nio.ByteBuffer;
-
-public enum MessageMetaDataType
-{
- META_DATA_0_8 { public Factory<MessageMetaData> getFactory() { return MessageMetaData.FACTORY; } },
- META_DATA_0_10 { public Factory<MessageMetaData_0_10> getFactory() { return MessageMetaData_0_10.FACTORY; } };
-
-
- public static interface Factory<M extends StorableMessageMetaData>
- {
- M createMetaData(ByteBuffer buf);
- }
-
- abstract public Factory<? extends StorableMessageMetaData> getFactory();
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/store/MessageStore.java b/java/broker/src/main/java/org/apache/qpid/server/store/MessageStore.java
deleted file mode 100644
index e2fca2f9c7..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/store/MessageStore.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.store;
-
-import org.apache.qpid.server.logging.LogSubject;
-import org.apache.commons.configuration.Configuration;
-
-/**
- * MessageStore defines the interface to a storage area, which can be used to preserve the state of messages.
- *
- */
-public interface MessageStore extends DurableConfigurationStore, TransactionLog
-{
- StoreFuture IMMEDIATE_FUTURE = new StoreFuture()
- {
- public boolean isComplete()
- {
- return true;
- }
-
- public void waitForCompletion()
- {
-
- }
- };
-
-
- /**
- * Called after instantiation in order to configure the message store. A particular implementation can define
- * whatever parameters it wants.
- *
- * @param name The name to be used by this storem
- * @param recoveryHandler Handler to be called as the store recovers on start up
- * @param config The apache commons configuration object.
- *
- * @throws Exception If any error occurs that means the store is unable to configure itself.
- */
- void configureMessageStore(String name,
- MessageStoreRecoveryHandler recoveryHandler,
- Configuration config,
- LogSubject logSubject) throws Exception;
-
- /**
- * Called to close and cleanup any resources used by the message store.
- *
- * @throws Exception If the close fails.
- */
- void close() throws Exception;
-
-
- public <T extends StorableMessageMetaData> StoredMessage<T> addMessage(T metaData);
-
-
- /**
- * Is this store capable of persisting the data
- *
- * @return true if this store is capable of persisting data
- */
- boolean isPersistent();
-
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/store/MessageStoreClosedException.java b/java/broker/src/main/java/org/apache/qpid/server/store/MessageStoreClosedException.java
deleted file mode 100644
index 3d1538c7eb..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/store/MessageStoreClosedException.java
+++ /dev/null
@@ -1,36 +0,0 @@
-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
- * 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.
- *
- */
-
-/**
- * NOTE: this class currently extends AMQException but
- * we should be using AMQExceptions internally in the code base for Protocol errors hence
- * the message store interface should throw a different super class which this should be
- * moved to reflect
- */
-public class MessageStoreClosedException extends AMQException
-{
- public MessageStoreClosedException()
- {
- super("Message store closed");
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/store/MessageStoreRecoveryHandler.java b/java/broker/src/main/java/org/apache/qpid/server/store/MessageStoreRecoveryHandler.java
deleted file mode 100755
index ba65b8e1ec..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/store/MessageStoreRecoveryHandler.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
-*
-* Licensed to the Apache Software Foundation (ASF) under one
-* or more contributor license agreements. See the NOTICE file
-* distributed with this work for additional information
-* regarding copyright ownership. The ASF licenses this file
-* to you under the Apache License, Version 2.0 (the
-* "License"); you may not use this file except in compliance
-* with the License. You may obtain a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing,
-* software distributed under the License is distributed on an
-* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-* KIND, either express or implied. See the License for the
-* specific language governing permissions and limitations
-* under the License.
-*
-*/
-package org.apache.qpid.server.store;
-
-public interface MessageStoreRecoveryHandler
-{
- StoredMessageRecoveryHandler begin();
-
- public static interface StoredMessageRecoveryHandler
- {
- void message(StoredMessage message);
-
- void completeMessageRecovery();
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/store/StorableMessageMetaData.java b/java/broker/src/main/java/org/apache/qpid/server/store/StorableMessageMetaData.java
deleted file mode 100755
index 12d2a6a6c7..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/store/StorableMessageMetaData.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.store;
-
-import java.nio.ByteBuffer;
-
-public interface StorableMessageMetaData
-{
- MessageMetaDataType getType();
-
- int getStorableSize();
-
- int writeToBuffer(int offsetInMetaData, ByteBuffer dest);
-
- int getContentSize();
-
- boolean isPersistent();
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/store/StoreContext.java b/java/broker/src/main/java/org/apache/qpid/server/store/StoreContext.java
deleted file mode 100644
index 88cc68bc71..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/store/StoreContext.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.store;
-
-import org.apache.log4j.Logger;
-
-/**
- * A context that the store can use to associate with a transactional context. For example, it could store
- * some kind of txn id.
- *
- * @author Apache Software Foundation
- */
-public class StoreContext
-{
- private static final Logger _logger = Logger.getLogger(StoreContext.class);
-
- private String _name;
- private Object _payload;
-
-
- public StoreContext()
- {
- _name = "StoreContext";
- }
-
- public StoreContext(String name)
- {
- _name = name;
- }
-
- public Object getPayload()
- {
- return _payload;
- }
-
- public void setPayload(Object payload)
- {
- if(_logger.isDebugEnabled())
- {
- _logger.debug("public void setPayload(Object payload = " + payload + "): called");
- }
- _payload = payload;
- }
-
- /**
- * Prints out the transactional context as a string, mainly for debugging purposes.
- *
- * @return The transactional context as a string.
- */
- public String toString()
- {
- return "<_name = " + _name + ", _payload = " + _payload + ">";
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/store/StoredMemoryMessage.java b/java/broker/src/main/java/org/apache/qpid/server/store/StoredMemoryMessage.java
deleted file mode 100755
index 1f5b027b80..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/store/StoredMemoryMessage.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.qpid.server.store;
-
-import java.nio.ByteBuffer;
-
-public class StoredMemoryMessage implements StoredMessage
-{
- private final long _messageNumber;
- private final ByteBuffer _content;
- private final StorableMessageMetaData _metaData;
-
- public StoredMemoryMessage(long messageNumber, StorableMessageMetaData metaData)
- {
- _messageNumber = messageNumber;
- _metaData = metaData;
- _content = ByteBuffer.allocate(metaData.getContentSize());
-
- }
-
- public long getMessageNumber()
- {
- return _messageNumber;
- }
-
- public void addContent(int offsetInMessage, ByteBuffer src)
- {
- src = src.duplicate();
- ByteBuffer dst = _content.duplicate();
- dst.position(offsetInMessage);
- dst.put(src);
- }
-
- public int getContent(int offset, ByteBuffer dst)
- {
- ByteBuffer src = _content.duplicate();
- src.position(offset);
- src = src.slice();
- if(dst.remaining() < src.limit())
- {
- src.limit(dst.remaining());
- }
- dst.put(src);
- return src.limit();
- }
-
- public TransactionLog.StoreFuture flushToStore()
- {
- return MessageStore.IMMEDIATE_FUTURE;
- }
-
-
- public StorableMessageMetaData getMetaData()
- {
- return _metaData;
- }
-
- public void remove()
- {
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/store/StoredMessage.java b/java/broker/src/main/java/org/apache/qpid/server/store/StoredMessage.java
deleted file mode 100755
index 0bc45c6718..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/store/StoredMessage.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.store;
-
-import java.nio.ByteBuffer;
-
-public interface StoredMessage<M extends StorableMessageMetaData>
-{
- M getMetaData();
-
- public long getMessageNumber();
-
- void addContent(int offsetInMessage, ByteBuffer src);
-
- int getContent(int offsetInMessage, ByteBuffer dst);
-
- TransactionLog.StoreFuture flushToStore();
-
- void remove();
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/store/TransactionLog.java b/java/broker/src/main/java/org/apache/qpid/server/store/TransactionLog.java
deleted file mode 100755
index d196a91930..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/store/TransactionLog.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.server.store;
-
-import org.apache.qpid.server.logging.LogSubject;
-import org.apache.qpid.AMQStoreException;
-import org.apache.commons.configuration.Configuration;
-
-public interface TransactionLog
-{
-
- public static interface Transaction
- {
- /**
- * Places a message onto a specified queue, in a given transactional context.
- *
- * @param queue The queue to place the message on.
- * @param messageId The message to enqueue.
- * @throws AMQStoreException If the operation fails for any reason.
- */
- void enqueueMessage(TransactionLogResource queue, Long messageId) throws AMQStoreException;
-
- /**
- * Extracts a message from a specified queue, in a given transactional context.
- *
- * @param queue The queue to place the message on.
- * @param messageId The message to dequeue.
- * @throws AMQStoreException If the operation fails for any reason, or if the specified message does not exist.
- */
- void dequeueMessage(TransactionLogResource queue, Long messageId) throws AMQStoreException;
-
-
- /**
- * Commits all operations performed within a given transactional context.
- *
- * @throws AMQStoreException If the operation fails for any reason.
- */
- void commitTran() throws AMQStoreException;
-
- /**
- * Commits all operations performed within a given transactional context.
- *
- * @throws AMQStoreException If the operation fails for any reason.
- */
- StoreFuture commitTranAsync() throws AMQStoreException;
-
- /**
- * Abandons all operations performed within a given transactional context.
- *
- * @throws AMQStoreException If the operation fails for any reason.
- */
- void abortTran() throws AMQStoreException;
-
-
-
- }
-
- public void configureTransactionLog(String name,
- TransactionLogRecoveryHandler recoveryHandler,
- Configuration storeConfiguration,
- LogSubject logSubject) throws Exception;
-
- Transaction newTransaction();
-
-
-
- public static interface StoreFuture
- {
- boolean isComplete();
-
- void waitForCompletion();
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/store/TransactionLogRecoveryHandler.java b/java/broker/src/main/java/org/apache/qpid/server/store/TransactionLogRecoveryHandler.java
deleted file mode 100755
index 7781c52df3..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/store/TransactionLogRecoveryHandler.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
-*
-* Licensed to the Apache Software Foundation (ASF) under one
-* or more contributor license agreements. See the NOTICE file
-* distributed with this work for additional information
-* regarding copyright ownership. The ASF licenses this file
-* to you under the Apache License, Version 2.0 (the
-* "License"); you may not use this file except in compliance
-* with the License. You may obtain a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing,
-* software distributed under the License is distributed on an
-* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-* KIND, either express or implied. See the License for the
-* specific language governing permissions and limitations
-* under the License.
-*
-*/
-package org.apache.qpid.server.store;
-
-public interface TransactionLogRecoveryHandler
-{
- QueueEntryRecoveryHandler begin(TransactionLog log);
-
- public static interface QueueEntryRecoveryHandler
- {
- void queueEntry(String queuename, long messageId);
-
- void completeQueueEntryRecovery();
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/store/TransactionLogResource.java b/java/broker/src/main/java/org/apache/qpid/server/store/TransactionLogResource.java
deleted file mode 100755
index 0d81dd151d..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/store/TransactionLogResource.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
-*
-* Licensed to the Apache Software Foundation (ASF) under one
-* or more contributor license agreements. See the NOTICE file
-* distributed with this work for additional information
-* regarding copyright ownership. The ASF licenses this file
-* to you under the Apache License, Version 2.0 (the
-* "License"); you may not use this file except in compliance
-* with the License. You may obtain a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing,
-* software distributed under the License is distributed on an
-* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-* KIND, either express or implied. See the License for the
-* specific language governing permissions and limitations
-* under the License.
-*
-*/
-package org.apache.qpid.server.store;
-
-public interface TransactionLogResource
-{
- public String getResourceName();
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/subscription/ClientDeliveryMethod.java b/java/broker/src/main/java/org/apache/qpid/server/subscription/ClientDeliveryMethod.java
deleted file mode 100644
index fbc8b3af7d..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/subscription/ClientDeliveryMethod.java
+++ /dev/null
@@ -1,29 +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.subscription;
-
-import org.apache.qpid.server.queue.QueueEntry;
-import org.apache.qpid.AMQException;
-
-public interface ClientDeliveryMethod
-{
- void deliverToClient(final Subscription sub, final QueueEntry entry, final long deliveryTag) throws AMQException;
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/subscription/ExplicitAcceptDispositionChangeListener.java b/java/broker/src/main/java/org/apache/qpid/server/subscription/ExplicitAcceptDispositionChangeListener.java
deleted file mode 100755
index b49b12fb79..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/subscription/ExplicitAcceptDispositionChangeListener.java
+++ /dev/null
@@ -1,93 +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.subscription;
-
-import org.apache.qpid.server.transport.ServerSession;
-import org.apache.qpid.server.queue.QueueEntry;
-import org.apache.log4j.Logger;
-
-
-class ExplicitAcceptDispositionChangeListener implements ServerSession.MessageDispositionChangeListener
-{
- private static final Logger _logger = Logger.getLogger(ExplicitAcceptDispositionChangeListener.class);
-
-
- private final QueueEntry _entry;
- private final Subscription_0_10 _sub;
-
- public ExplicitAcceptDispositionChangeListener(QueueEntry entry, Subscription_0_10 subscription_0_10)
- {
- _entry = entry;
- _sub = subscription_0_10;
- }
-
- public void onAccept()
- {
- final Subscription_0_10 subscription = getSubscription();
- if(subscription != null && _entry.isAcquiredBy(_sub))
- {
- subscription.getSession().acknowledge(subscription, _entry);
- }
- else
- {
- _logger.warn("MessageAccept received for message which has not been acquired (likely client error)");
- }
-
- }
-
- public void onRelease()
- {
- final Subscription_0_10 subscription = getSubscription();
- if(subscription != null && _entry.isAcquiredBy(_sub))
- {
- subscription.release(_entry);
- }
- else
- {
- _logger.warn("MessageRelease received for message which has not been acquired (likely client error)");
- }
- }
-
- public void onReject()
- {
- final Subscription_0_10 subscription = getSubscription();
- if(subscription != null && _entry.isAcquiredBy(_sub))
- {
- subscription.reject(_entry);
- }
- else
- {
- _logger.warn("MessageReject received for message which has not been acquired (likely client error)");
- }
-
- }
-
- public boolean acquire()
- {
- return _entry.acquire(getSubscription());
- }
-
-
- private Subscription_0_10 getSubscription()
- {
- return _sub;
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/subscription/ImplicitAcceptDispositionChangeListener.java b/java/broker/src/main/java/org/apache/qpid/server/subscription/ImplicitAcceptDispositionChangeListener.java
deleted file mode 100755
index b5bb2014b5..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/subscription/ImplicitAcceptDispositionChangeListener.java
+++ /dev/null
@@ -1,86 +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.subscription;
-
-import org.apache.qpid.server.transport.ServerSession;
-import org.apache.qpid.server.queue.QueueEntry;
-import org.apache.log4j.Logger;
-
-class ImplicitAcceptDispositionChangeListener implements ServerSession.MessageDispositionChangeListener
-{
- private static final Logger _logger = Logger.getLogger(ImplicitAcceptDispositionChangeListener.class);
-
-
- private final QueueEntry _entry;
- private Subscription_0_10 _sub;
-
- public ImplicitAcceptDispositionChangeListener(QueueEntry entry, Subscription_0_10 subscription_0_10)
- {
- _entry = entry;
- _sub = subscription_0_10;
- }
-
- public void onAccept()
- {
- _logger.warn("MessageAccept received for message which is using NONE as the accept mode (likely client error)");
- }
-
- public void onRelease()
- {
- if(_entry.isAcquiredBy(_sub))
- {
- getSubscription().release(_entry);
- }
- else
- {
- _logger.warn("MessageRelease received for message which has not been acquired (likely client error)");
- }
- }
-
- public void onReject()
- {
- if(_entry.isAcquiredBy(_sub))
- {
- getSubscription().reject(_entry);
- }
- else
- {
- _logger.warn("MessageReject received for message which has not been acquired (likely client error)");
- }
-
- }
-
- public boolean acquire()
- {
- boolean acquired = _entry.acquire(getSubscription());
- //TODO - why acknowledge here??? seems bizarre...
- // getSubscription().getSession().acknowledge(getSubscription(), _entry);
- return acquired;
-
- }
-
- public Subscription_0_10 getSubscription()
- {
- return _sub;
- }
-
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/subscription/MessageAcceptCompletionListener.java b/java/broker/src/main/java/org/apache/qpid/server/subscription/MessageAcceptCompletionListener.java
deleted file mode 100755
index 8a2a370236..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/subscription/MessageAcceptCompletionListener.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.subscription;
-
-import org.apache.qpid.server.queue.QueueEntry;
-import org.apache.qpid.server.transport.ServerSession;
-import org.apache.qpid.transport.Method;
-
-public class MessageAcceptCompletionListener implements Method.CompletionListener
-{
- private final Subscription_0_10 _sub;
- private final QueueEntry _entry;
- private final ServerSession _session;
- private boolean _restoreCredit;
-
- public MessageAcceptCompletionListener(Subscription_0_10 sub, ServerSession session, QueueEntry entry, boolean restoreCredit)
- {
- super();
- _sub = sub;
- _entry = entry;
- _session = session;
- _restoreCredit = restoreCredit;
- }
-
- public void onComplete(Method method)
- {
- if(_restoreCredit)
- {
- _sub.restoreCredit(_entry);
- }
- if(_entry.isAcquiredBy(_sub))
- {
- _session.acknowledge(_sub, _entry);
- }
-
- _session.removeDispositionListener(method);
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/subscription/RecordDeliveryMethod.java b/java/broker/src/main/java/org/apache/qpid/server/subscription/RecordDeliveryMethod.java
deleted file mode 100644
index e2ed4104de..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/subscription/RecordDeliveryMethod.java
+++ /dev/null
@@ -1,28 +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.subscription;
-
-import org.apache.qpid.server.queue.QueueEntry;
-
-public interface RecordDeliveryMethod
-{
- void recordMessageDelivery(final Subscription sub, final QueueEntry entry, final long deliveryTag);
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/subscription/Subscription.java b/java/broker/src/main/java/org/apache/qpid/server/subscription/Subscription.java
deleted file mode 100644
index 0a3576ff42..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/subscription/Subscription.java
+++ /dev/null
@@ -1,109 +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.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;
-
-public interface Subscription
-{
- LogActor getLogActor();
-
- boolean isTransient();
-
- public static enum State
- {
- ACTIVE,
- SUSPENDED,
- CLOSED
- }
-
- public static interface StateListener
- {
- public void stateChange(Subscription sub, State oldState, State newState);
- }
-
- AMQQueue getQueue();
-
- QueueEntry.SubscriptionAcquiredState getOwningState();
- QueueEntry.SubscriptionAssignedState getAssignedState();
-
-
- void setQueue(AMQQueue queue, boolean exclusive);
-
- void setNoLocal(boolean noLocal);
-
- AMQShortString getConsumerTag();
-
- long getSubscriptionID();
-
- boolean isSuspended();
-
- boolean hasInterest(QueueEntry msg);
-
- boolean isAutoClose();
-
- boolean isClosed();
-
- boolean acquires();
-
- boolean seesRequeues();
-
- void close();
-
- void send(QueueEntry msg) throws AMQException;
-
- void queueDeleted(AMQQueue queue);
-
-
- boolean wouldSuspend(QueueEntry msg);
-
- void getSendLock();
-
- void releaseSendLock();
-
- void onDequeue(final QueueEntry queueEntry);
-
- void restoreCredit(final QueueEntry queueEntry);
-
- void setStateListener(final StateListener listener);
-
- public State getState();
-
- AMQQueue.Context getQueueContext();
-
- void setQueueContext(AMQQueue.Context queueContext);
-
-
- boolean isActive();
-
- void confirmAutoClose();
-
- public void set(String key, Object value);
-
- public Object get(String key);
-
- boolean isSessionTransactional();
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/subscription/SubscriptionFactory.java b/java/broker/src/main/java/org/apache/qpid/server/subscription/SubscriptionFactory.java
deleted file mode 100644
index ce0362d73f..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/subscription/SubscriptionFactory.java
+++ /dev/null
@@ -1,59 +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.subscription;
-
-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.flow.FlowCreditManager;
-import org.apache.qpid.server.subscription.Subscription;
-import org.apache.qpid.server.AMQChannel;
-
-/**
- * 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
- * implementation.
- *
- * @see org.apache.qpid.server.queue.AMQQueue
- */
-public interface SubscriptionFactory
-{
- Subscription createSubscription(int channel,
- AMQProtocolSession protocolSession,
- AMQShortString consumerTag,
- boolean acks,
- FieldTable filters,
- boolean noLocal, FlowCreditManager creditManager) throws AMQException;
-
-
- Subscription createSubscription(AMQChannel channel,
- AMQProtocolSession protocolSession,
- AMQShortString consumerTag,
- boolean acks,
- FieldTable filters,
- boolean noLocal,
- FlowCreditManager creditManager,
- ClientDeliveryMethod clientMethod,
- RecordDeliveryMethod recordMethod
- )
- throws AMQException;
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/subscription/SubscriptionFactoryImpl.java b/java/broker/src/main/java/org/apache/qpid/server/subscription/SubscriptionFactoryImpl.java
deleted file mode 100644
index 1bba2529c6..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/subscription/SubscriptionFactoryImpl.java
+++ /dev/null
@@ -1,95 +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.subscription;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.common.AMQPFilterTypes;
-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.flow.FlowCreditManager;
-import org.apache.qpid.server.protocol.AMQProtocolSession;
-
-public class SubscriptionFactoryImpl implements SubscriptionFactory
-{
- public Subscription createSubscription(int channelId, AMQProtocolSession protocolSession,
- AMQShortString consumerTag, boolean acks, FieldTable filters,
- boolean noLocal, FlowCreditManager creditManager) throws AMQException
- {
- AMQChannel channel = protocolSession.getChannel(channelId);
- if (channel == null)
- {
- throw new AMQException(AMQConstant.NOT_FOUND, "channel :" + channelId + " not found in protocol session");
- }
- ClientDeliveryMethod clientMethod = channel.getClientDeliveryMethod();
- RecordDeliveryMethod recordMethod = channel.getRecordDeliveryMethod();
-
-
- return createSubscription(channel, protocolSession, consumerTag, acks, filters,
- noLocal,
- creditManager,
- clientMethod,
- recordMethod
- );
- }
-
- public Subscription createSubscription(final AMQChannel channel,
- final AMQProtocolSession protocolSession,
- final AMQShortString consumerTag,
- final boolean acks,
- final FieldTable filters,
- final boolean noLocal,
- final FlowCreditManager creditManager,
- final ClientDeliveryMethod clientMethod,
- final RecordDeliveryMethod recordMethod
- )
- throws AMQException
- {
- boolean isBrowser;
-
- if (filters != null)
- {
- Boolean isBrowserObj = (Boolean) filters.get(AMQPFilterTypes.NO_CONSUME.getValue());
- isBrowser = (isBrowserObj != null) && isBrowserObj.booleanValue();
- }
- else
- {
- isBrowser = false;
- }
-
- if(isBrowser)
- {
- return new SubscriptionImpl.BrowserSubscription(channel, protocolSession, consumerTag, filters, noLocal, creditManager, clientMethod, recordMethod);
- }
- else if(acks)
- {
- return new SubscriptionImpl.AckSubscription(channel, protocolSession, consumerTag, filters, noLocal, creditManager, clientMethod, recordMethod);
- }
- else
- {
- return new SubscriptionImpl.NoAckSubscription(channel, protocolSession, consumerTag, filters, noLocal, creditManager, clientMethod, recordMethod);
- }
- }
-
-
- public static final SubscriptionFactoryImpl INSTANCE = new SubscriptionFactoryImpl();
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/subscription/SubscriptionImpl.java b/java/broker/src/main/java/org/apache/qpid/server/subscription/SubscriptionImpl.java
deleted file mode 100644
index d8f44c9f7f..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/subscription/SubscriptionImpl.java
+++ /dev/null
@@ -1,785 +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.subscription;
-
-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;
-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.filter.FilterManager;
-import org.apache.qpid.server.filter.FilterManagerFactory;
-import org.apache.qpid.server.flow.FlowCreditManager;
-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.SubscriptionActor;
-import org.apache.qpid.server.logging.messages.SubscriptionMessages;
-import org.apache.qpid.server.logging.subjects.SubscriptionLogSubject;
-import org.apache.qpid.server.message.AMQMessage;
-import org.apache.qpid.server.output.ProtocolOutputConverter;
-import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.server.queue.AMQQueue;
-import org.apache.qpid.server.queue.QueueEntry;
-
-import java.util.Map;
-import java.util.UUID;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicLong;
-import java.util.concurrent.atomic.AtomicReference;
-import java.util.concurrent.locks.Lock;
-import java.util.concurrent.locks.ReentrantLock;
-
-/**
- * Encapsulation of a supscription to a queue. <p/> Ties together the protocol session of a subscriber, the consumer tag
- * that was given out by the broker and the channel id. <p/>
- */
-public abstract class SubscriptionImpl implements Subscription, FlowCreditManager.FlowCreditManagerListener,
- SubscriptionConfig
-{
-
- private StateListener _stateListener = new StateListener()
- {
-
- public void stateChange(Subscription sub, State oldState, State newState)
- {
-
- }
- };
-
-
- private final AtomicReference<State> _state = new AtomicReference<State>(State.ACTIVE);
- private AMQQueue.Context _queueContext;
-
- private final ClientDeliveryMethod _deliveryMethod;
- private final RecordDeliveryMethod _recordMethod;
-
- private final QueueEntry.SubscriptionAcquiredState _owningState = new QueueEntry.SubscriptionAcquiredState(this);
- private final QueueEntry.SubscriptionAssignedState _assignedState = new QueueEntry.SubscriptionAssignedState(this);
-
- private final Map<String, Object> _properties = new ConcurrentHashMap<String, Object>();
-
- private final Lock _stateChangeLock;
-
- 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 LogSubject _logSubject;
- private LogActor _logActor;
- private UUID _id;
- private final AtomicLong _deliveredCount = new AtomicLong(0);
- private long _createTime = System.currentTimeMillis();
-
-
- static final class BrowserSubscription extends SubscriptionImpl
- {
- public BrowserSubscription(AMQChannel channel, AMQProtocolSession protocolSession,
- AMQShortString consumerTag, FieldTable filters,
- boolean noLocal, FlowCreditManager creditManager,
- ClientDeliveryMethod deliveryMethod,
- RecordDeliveryMethod recordMethod)
- throws AMQException
- {
- super(channel, protocolSession, consumerTag, filters, noLocal, creditManager, deliveryMethod, recordMethod);
- }
-
-
- public boolean isBrowser()
- {
- return true;
- }
-
- /**
- * This method can be called by each of the publisher threads. As a result all changes to the channel object must be
- * thread safe.
- *
- * @param msg The message to send
- * @throws AMQException
- */
- @Override
- public void send(QueueEntry msg) throws AMQException
- {
- // We don't decrement the reference here as we don't want to consume the message
- // but we do want to send it to the client.
-
- synchronized (getChannel())
- {
- long deliveryTag = getChannel().getNextDeliveryTag();
- sendToClient(msg, deliveryTag);
- }
-
- }
-
- @Override
- public boolean wouldSuspend(QueueEntry msg)
- {
- return false;
- }
-
- }
-
- public static class NoAckSubscription extends SubscriptionImpl
- {
- public NoAckSubscription(AMQChannel channel, AMQProtocolSession protocolSession,
- AMQShortString consumerTag, FieldTable filters,
- boolean noLocal, FlowCreditManager creditManager,
- ClientDeliveryMethod deliveryMethod,
- RecordDeliveryMethod recordMethod)
- throws AMQException
- {
- super(channel, protocolSession, consumerTag, filters, noLocal, creditManager, deliveryMethod, recordMethod);
- }
-
-
- public boolean isBrowser()
- {
- return false;
- }
-
- @Override
- public boolean isExplicitAcknowledge()
- {
- return false;
- }
-
- /**
- * This method can be called by each of the publisher threads. As a result all changes to the channel object must be
- * thread safe.
- *
- * @param entry The message to send
- * @throws AMQException
- */
- @Override
- public void send(QueueEntry entry) throws AMQException
- {
- // if we do not need to wait for client acknowledgements
- // we can decrement the reference count immediately.
-
- // By doing this _before_ the send we ensure that it
- // doesn't get sent if it can't be dequeued, preventing
- // duplicate delivery on recovery.
-
- // The send may of course still fail, in which case, as
- // the message is unacked, it will be lost.
- entry.dequeue();
-
-
- synchronized (getChannel())
- {
- long deliveryTag = getChannel().getNextDeliveryTag();
-
- sendToClient(entry, deliveryTag);
-
- }
- entry.dispose();
-
-
- }
-
- @Override
- public boolean wouldSuspend(QueueEntry msg)
- {
- return false;
- }
-
- }
-
- static final class AckSubscription extends SubscriptionImpl
- {
- public AckSubscription(AMQChannel channel, AMQProtocolSession protocolSession,
- AMQShortString consumerTag, FieldTable filters,
- boolean noLocal, FlowCreditManager creditManager,
- ClientDeliveryMethod deliveryMethod,
- RecordDeliveryMethod recordMethod)
- throws AMQException
- {
- super(channel, protocolSession, consumerTag, filters, noLocal, creditManager, deliveryMethod, recordMethod);
- }
-
-
- public boolean isBrowser()
- {
- return false;
- }
-
-
- /**
- * This method can be called by each of the publisher threads. As a result all changes to the channel object must be
- * thread safe.
- *
- * @param entry The message to send
- * @throws AMQException
- */
- @Override
- public void send(QueueEntry entry) throws AMQException
- {
-
- // if we do not need to wait for client acknowledgements
- // we can decrement the reference count immediately.
-
- // By doing this _before_ the send we ensure that it
- // doesn't get sent if it can't be dequeued, preventing
- // duplicate delivery on recovery.
-
- // The send may of course still fail, in which case, as
- // the message is unacked, it will be lost.
-
- synchronized (getChannel())
- {
- long deliveryTag = getChannel().getNextDeliveryTag();
-
-
- recordMessageDelivery(entry, deliveryTag);
- sendToClient(entry, deliveryTag);
-
-
- }
- }
-
-
-
- }
-
-
- private static final Logger _logger = Logger.getLogger(SubscriptionImpl.class);
-
- private final AMQChannel _channel;
-
- private final AMQShortString _consumerTag;
-
-
- private boolean _noLocal;
-
- private final FlowCreditManager _creditManager;
-
- private FilterManager _filters;
-
- private final Boolean _autoClose;
-
-
- private static final String CLIENT_PROPERTIES_INSTANCE = ClientProperties.instance.toString();
-
- private AMQQueue _queue;
- private final AtomicBoolean _deleted = new AtomicBoolean(false);
-
-
-
-
- public SubscriptionImpl(AMQChannel channel , AMQProtocolSession protocolSession,
- AMQShortString consumerTag, FieldTable arguments,
- boolean noLocal, FlowCreditManager creditManager,
- ClientDeliveryMethod deliveryMethod,
- RecordDeliveryMethod recordMethod)
- throws AMQException
- {
-
- _channel = channel;
- _consumerTag = consumerTag;
-
- _creditManager = creditManager;
- creditManager.addStateListener(this);
-
- _noLocal = noLocal;
-
-
- _filters = FilterManagerFactory.createManager(arguments);
-
- _deliveryMethod = deliveryMethod;
- _recordMethod = recordMethod;
-
-
- _stateChangeLock = new ReentrantLock();
-
-
- if (arguments != null)
- {
- Object autoClose = arguments.get(AMQPFilterTypes.AUTO_CLOSE.getValue());
- if (autoClose != null)
- {
- _autoClose = (Boolean) autoClose;
- }
- else
- {
- _autoClose = false;
- }
- }
- else
- {
- _autoClose = false;
- }
-
- }
-
- public ConfigStore getConfigStore()
- {
- return getQueue().getConfigStore();
- }
-
- public Long getDelivered()
- {
- return _deliveredCount.get();
- }
-
- public synchronized void setQueue(AMQQueue queue, boolean exclusive)
- {
- if(getQueue() != null)
- {
- throw new IllegalStateException("Attempt to set queue for subscription " + this + " to " + queue + "when already set to " + getQueue());
- }
- _queue = queue;
-
- _id = getConfigStore().createId();
- getConfigStore().addConfiguredObject(this);
-
- _logSubject = new SubscriptionLogSubject(this);
- _logActor = new SubscriptionActor(CurrentActor.get().getRootMessageLogger(), this);
-
- if (CurrentActor.get().getRootMessageLogger().
- isMessageEnabled(CurrentActor.get(), _logSubject, SubscriptionMessages.CREATE_LOG_HIERARCHY))
- {
- // Get the string value of the filters
- String filterLogString = null;
- if (_filters != null && _filters.hasFilters())
- {
- filterLogString = _filters.toString();
- }
-
- if (isAutoClose())
- {
- if (filterLogString == null)
- {
- filterLogString = "";
- }
- else
- {
- filterLogString += ",";
- }
- filterLogString += "AutoClose";
- }
-
- if (isBrowser())
- {
- // We do not need to check for null here as all Browsers are AutoClose
- filterLogString +=",Browser";
- }
-
- CurrentActor.get().
- message(_logSubject,
- SubscriptionMessages.CREATE(filterLogString,
- queue.isDurable() && exclusive,
- filterLogString != null));
- }
- }
-
- public String toString()
- {
- String subscriber = "[channel=" + _channel +
- ", consumerTag=" + _consumerTag +
- ", session=" + getProtocolSession().getKey() ;
-
- return subscriber + "]";
- }
-
- /**
- * This method can be called by each of the publisher threads. As a result all changes to the channel object must be
- * thread safe.
- *
- * @param msg The message to send
- * @throws AMQException
- */
- abstract public void send(QueueEntry msg) throws AMQException;
-
-
- public boolean isSuspended()
- {
- return !isActive() || _channel.isSuspended() || _deleted.get();
- }
-
- /**
- * Callback indicating that a queue has been deleted.
- *
- * @param queue The queue to delete
- */
- public void queueDeleted(AMQQueue queue)
- {
- _deleted.set(true);
-// _channel.queueDeleted(queue);
- }
-
- public boolean filtersMessages()
- {
- return _filters != null || _noLocal;
- }
-
- public boolean hasInterest(QueueEntry entry)
- {
-
-
-
-
- //check that the message hasn't been rejected
- if (entry.isRejectedBy(this))
- {
- if (_logger.isDebugEnabled())
- {
- _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();
-
- // We don't want local messages so check to see if message is one we sent
- Object localInstance = getProtocolSession();
-
- if(publisher.equals(localInstance))
- {
- return false;
- }
-
-
- }
-
-
- if (_logger.isDebugEnabled())
- {
- _logger.debug("(" + this + ") checking filters for message (" + entry);
- }
- return checkFilters(entry);
-
- }
-
- private String id = String.valueOf(System.identityHashCode(this));
-
- private String debugIdentity()
- {
- return id;
- }
-
- private boolean checkFilters(QueueEntry msg)
- {
- return (_filters == null) || _filters.allAllow(msg);
- }
-
- public boolean isAutoClose()
- {
- return _autoClose;
- }
-
- public FlowCreditManager getCreditManager()
- {
- return _creditManager;
- }
-
-
- public void close()
- {
- boolean closed = false;
- State state = getState();
-
- _stateChangeLock.lock();
- try
- {
- while(!closed && state != State.CLOSED)
- {
- closed = _state.compareAndSet(state, State.CLOSED);
- if(!closed)
- {
- state = getState();
- }
- else
- {
- _stateListener.stateChange(this,state, State.CLOSED);
- }
- }
- _creditManager.removeListener(this);
- }
- finally
- {
- _stateChangeLock.unlock();
- }
- getConfigStore().removeConfiguredObject(this);
-
- //Log Subscription closed
- CurrentActor.get().message(_logSubject, SubscriptionMessages.CLOSE());
- }
-
- public boolean isClosed()
- {
- return getState() == State.CLOSED;
- }
-
-
- public boolean wouldSuspend(QueueEntry msg)
- {
- return !_creditManager.useCreditForMessage(msg.getMessage());//_channel.wouldSuspend(msg.getMessage());
- }
-
- public void getSendLock()
- {
- _stateChangeLock.lock();
- }
-
- public void releaseSendLock()
- {
- _stateChangeLock.unlock();
- }
-
- public AMQChannel getChannel()
- {
- return _channel;
- }
-
- public AMQShortString getConsumerTag()
- {
- return _consumerTag;
- }
-
- public long getSubscriptionID()
- {
- return _subscriptionID;
- }
-
- public AMQProtocolSession getProtocolSession()
- {
- return _channel.getProtocolSession();
- }
-
- public LogActor getLogActor()
- {
- return _logActor;
- }
-
- public AMQQueue getQueue()
- {
- return _queue;
- }
-
- public void onDequeue(final QueueEntry queueEntry)
- {
- restoreCredit(queueEntry);
- }
-
- public void restoreCredit(final QueueEntry queueEntry)
- {
- _creditManager.restoreCredit(1, queueEntry.getSize());
- }
-
-
-
- public void creditStateChanged(boolean hasCredit)
- {
-
- if(hasCredit)
- {
- if(_state.compareAndSet(State.SUSPENDED, State.ACTIVE))
- {
- _stateListener.stateChange(this, State.SUSPENDED, State.ACTIVE);
- }
- else
- {
- // this is a hack to get round the issue of increasing bytes credit
- _stateListener.stateChange(this, State.ACTIVE, State.ACTIVE);
- }
- }
- else
- {
- if(_state.compareAndSet(State.ACTIVE, State.SUSPENDED))
- {
- _stateListener.stateChange(this, State.ACTIVE, State.SUSPENDED);
- }
- }
- CurrentActor.get().message(_logSubject,SubscriptionMessages.STATE(_state.get().toString()));
- }
-
- public State getState()
- {
- return _state.get();
- }
-
-
- public void setStateListener(final StateListener listener)
- {
- _stateListener = listener;
- }
-
-
- public AMQQueue.Context getQueueContext()
- {
- return _queueContext;
- }
-
- public void setQueueContext(AMQQueue.Context context)
- {
- _queueContext = context;
- }
-
-
- protected void sendToClient(final QueueEntry entry, final long deliveryTag)
- throws AMQException
- {
- _deliveryMethod.deliverToClient(this,entry,deliveryTag);
- _deliveredCount.incrementAndGet();
- }
-
-
- protected void recordMessageDelivery(final QueueEntry entry, final long deliveryTag)
- {
- _recordMethod.recordMessageDelivery(this,entry,deliveryTag);
- }
-
-
- public boolean isActive()
- {
- return getState() == State.ACTIVE;
- }
-
- public QueueEntry.SubscriptionAcquiredState getOwningState()
- {
- return _owningState;
- }
-
- public QueueEntry.SubscriptionAssignedState getAssignedState()
- {
- return _assignedState;
- }
-
-
- public void confirmAutoClose()
- {
- ProtocolOutputConverter converter = getChannel().getProtocolSession().getProtocolOutputConverter();
- converter.confirmConsumerAutoClose(getChannel().getChannelId(), getConsumerTag());
- }
-
- public boolean acquires()
- {
- return !isBrowser();
- }
-
- public boolean seesRequeues()
- {
- return !isBrowser();
- }
-
- public boolean isTransient()
- {
- return false;
- }
-
- public void set(String key, Object value)
- {
- _properties.put(key, value);
- }
-
- public Object get(String key)
- {
- return _properties.get(key);
- }
-
-
- public void setNoLocal(boolean noLocal)
- {
- _noLocal = noLocal;
- }
-
- abstract boolean isBrowser();
-
- public String getCreditMode()
- {
- return "WINDOW";
- }
-
- public SessionConfig getSessionConfig()
- {
- return getChannel();
- }
-
- public boolean isBrowsing()
- {
- return isBrowser();
- }
-
- public boolean isExplicitAcknowledge()
- {
- return true;
- }
-
- public UUID getId()
- {
- return _id;
- }
-
- public boolean isDurable()
- {
- return false;
- }
-
- public SubscriptionConfigType getConfigType()
- {
- return SubscriptionConfigType.getInstance();
- }
-
- public boolean isExclusive()
- {
- return getQueue().hasExclusiveSubscriber();
- }
-
- public ConfiguredObject getParent()
- {
- return getSessionConfig();
- }
-
- public String getName()
- {
- return String.valueOf(_consumerTag);
- }
-
- public Map<String, Object> getArguments()
- {
- return null;
- }
-
- public boolean isSessionTransactional()
- {
- return _channel.isTransactional();
- }
-
- public long getCreateTime()
- {
- return _createTime;
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/subscription/SubscriptionList.java b/java/broker/src/main/java/org/apache/qpid/server/subscription/SubscriptionList.java
deleted file mode 100644
index 9ea81660c6..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/subscription/SubscriptionList.java
+++ /dev/null
@@ -1,245 +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.subscription;
-
-import org.apache.qpid.server.queue.AMQQueue;
-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.nio.ByteBuffer;
-
-public class SubscriptionList
-{
-
- private final SubscriptionNode _head = new SubscriptionNode();
-
- private AtomicReference<SubscriptionNode> _tail = new AtomicReference<SubscriptionNode>(_head);
- private AtomicInteger _size = new AtomicInteger();
-
-
- public final class SubscriptionNode
- {
- private final AtomicBoolean _deleted = new AtomicBoolean();
- private final AtomicReference<SubscriptionNode> _next = new AtomicReference<SubscriptionNode>();
- private final Subscription _sub;
-
-
- public SubscriptionNode()
- {
-
- _sub = null;
- _deleted.set(true);
- }
-
- public SubscriptionNode(final Subscription sub)
- {
- _sub = sub;
- }
-
-
- public SubscriptionNode getNext()
- {
-
- SubscriptionNode next = nextNode();
- while(next != null && next.isDeleted())
- {
-
- final SubscriptionNode newNext = next.nextNode();
- if(newNext != null)
- {
- _next.compareAndSet(next, newNext);
- next = nextNode();
- }
- else
- {
- next = null;
- }
-
- }
- return next;
- }
-
- private SubscriptionNode nextNode()
- {
- return _next.get();
- }
-
- public boolean isDeleted()
- {
- return _deleted.get();
- }
-
-
- public boolean delete()
- {
- if(_deleted.compareAndSet(false,true))
- {
- _size.decrementAndGet();
- advanceHead();
- return true;
- }
- else
- {
- return false;
- }
- }
-
-
- public Subscription getSubscription()
- {
- return _sub;
- }
- }
-
-
- public SubscriptionList(AMQQueue queue)
- {
- }
-
- private void advanceHead()
- {
- SubscriptionNode head = _head.nextNode();
- while(head._next.get() != null && head.isDeleted())
- {
-
- final SubscriptionNode newhead = head.nextNode();
- if(newhead != null)
- {
- _head._next.compareAndSet(head, newhead);
- }
- head = _head.nextNode();
- }
- }
-
-
- public SubscriptionNode add(Subscription sub)
- {
- SubscriptionNode node = new SubscriptionNode(sub);
- for (;;)
- {
- SubscriptionNode tail = _tail.get();
- SubscriptionNode next = tail.nextNode();
- if (tail == _tail.get())
- {
- if (next == null)
- {
- if (tail._next.compareAndSet(null, node))
- {
- _tail.compareAndSet(tail, node);
- _size.incrementAndGet();
- return node;
- }
- }
- else
- {
- _tail.compareAndSet(tail, next);
- }
- }
- }
-
- }
-
- public boolean remove(Subscription sub)
- {
- SubscriptionNode node = _head.getNext();
- while(node != null)
- {
- if(sub.equals(node._sub) && node.delete())
- {
- return true;
- }
- node = node.getNext();
- }
- return false;
- }
-
-
- public static class SubscriptionNodeIterator
- {
-
- private SubscriptionNode _lastNode;
-
- SubscriptionNodeIterator(SubscriptionNode startNode)
- {
- _lastNode = startNode;
- }
-
-
- public boolean atTail()
- {
- return _lastNode.nextNode() == null;
- }
-
- public SubscriptionNode getNode()
- {
-
- return _lastNode;
-
- }
-
- public boolean advance()
- {
-
- if(!atTail())
- {
- SubscriptionNode nextNode = _lastNode.nextNode();
- while(nextNode.isDeleted() && nextNode.nextNode() != null)
- {
- nextNode = nextNode.nextNode();
- }
- _lastNode = nextNode;
- return true;
-
- }
- else
- {
- return false;
- }
-
- }
-
- }
-
-
- public SubscriptionNodeIterator iterator()
- {
- return new SubscriptionNodeIterator(_head);
- }
-
-
- public SubscriptionNode getHead()
- {
- return _head;
- }
-
- public int size()
- {
- return _size.get();
- }
-
-
-
-}
-
-
-
diff --git a/java/broker/src/main/java/org/apache/qpid/server/subscription/Subscription_0_10.java b/java/broker/src/main/java/org/apache/qpid/server/subscription/Subscription_0_10.java
deleted file mode 100644
index 68e47fd86a..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/subscription/Subscription_0_10.java
+++ /dev/null
@@ -1,957 +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.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.QueueEntry;
-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.flow.FlowCreditManager;
-import org.apache.qpid.server.flow.CreditCreditManager;
-import org.apache.qpid.server.flow.WindowCreditManager;
-import org.apache.qpid.server.flow.FlowCreditManager_0_10;
-import org.apache.qpid.server.filter.FilterManager;
-import org.apache.qpid.server.logging.actors.CurrentActor;
-import org.apache.qpid.server.logging.actors.GenericActor;
-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.logging.actors.SubscriptionActor;
-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.transport.ServerSession;
-import org.apache.qpid.server.txn.ServerTransaction;
-import org.apache.qpid.server.txn.AutoCommitTransaction;
-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.Struct;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.BasicContentHeaderProperties;
-import org.apache.qpid.framing.FieldTable;
-import org.apache.qpid.AMQException;
-
-import java.text.MessageFormat;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-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.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicLong;
-import java.util.concurrent.ConcurrentHashMap;
-import java.nio.ByteBuffer;
-
-public class Subscription_0_10 implements Subscription, FlowCreditManager.FlowCreditManagerListener, SubscriptionConfig, LogSubject
-{
-
- 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 final QueueEntry.SubscriptionAcquiredState _owningState = new QueueEntry.SubscriptionAcquiredState(this);
- private final QueueEntry.SubscriptionAssignedState _assignedState = new QueueEntry.SubscriptionAssignedState(this);
-
- private final Lock _stateChangeLock = new ReentrantLock();
-
- private final AtomicReference<State> _state = new AtomicReference<State>(State.ACTIVE);
- private AMQQueue.Context _queueContext;
- private final AtomicBoolean _deleted = new AtomicBoolean(false);
-
-
- private FlowCreditManager_0_10 _creditManager;
-
- private StateListener _stateListener = new StateListener()
- {
-
- public void stateChange(Subscription sub, State oldState, State newState)
- {
- CurrentActor.get().message(SubscriptionMessages.STATE(newState.toString()));
- }
- };
- private AMQQueue _queue;
- private final String _destination;
- private boolean _noLocal;
- private final FilterManager _filters;
- private final MessageAcceptMode _acceptMode;
- private final MessageAcquireMode _acquireMode;
- private MessageFlowMode _flowMode;
- private final ServerSession _session;
- private AtomicBoolean _stopped = new AtomicBoolean(true);
- private ConcurrentHashMap<Integer, QueueEntry> _sentMap = new ConcurrentHashMap<Integer, QueueEntry>();
- private static final Struct[] EMPTY_STRUCT_ARRAY = new Struct[0];
-
- private LogActor _logActor;
- private Map<String, Object> _properties = new ConcurrentHashMap<String, Object>();
- private UUID _id;
- private String _traceExclude;
- private String _trace;
- private long _createTime = System.currentTimeMillis();
- private final AtomicLong _deliveredCount = new AtomicLong(0);
- private final Map<String, Object> _arguments;
-
-
- public Subscription_0_10(ServerSession session, String destination, MessageAcceptMode acceptMode,
- MessageAcquireMode acquireMode,
- MessageFlowMode flowMode,
- FlowCreditManager_0_10 creditManager,
- FilterManager filters,Map<String, Object> arguments)
- {
- _session = session;
- _destination = destination;
- _acceptMode = acceptMode;
- _acquireMode = acquireMode;
- _creditManager = creditManager;
- _flowMode = flowMode;
- _filters = filters;
- _creditManager.addStateListener(this);
- _arguments = arguments == null ? Collections.<String, Object> emptyMap() :
- Collections.<String, Object> unmodifiableMap(arguments);
- _state.set(_creditManager.hasCredit() ? State.ACTIVE : State.SUSPENDED);
-
- }
-
- public void setNoLocal(boolean noLocal)
- {
- _noLocal = noLocal;
- }
-
- public AMQQueue getQueue()
- {
- return _queue;
- }
-
- public QueueEntry.SubscriptionAcquiredState getOwningState()
- {
- return _owningState;
- }
-
- public QueueEntry.SubscriptionAssignedState getAssignedState()
- {
- return _assignedState;
- }
-
- public void setQueue(AMQQueue queue, boolean exclusive)
- {
- if(getQueue() != null)
- {
- throw new IllegalStateException("Attempt to set queue for subscription " + this + " to " + queue + "when already set to " + getQueue());
- }
- _queue = queue;
- Map<String, Object> arguments = queue.getArguments() == null ? Collections.EMPTY_MAP : queue.getArguments();
- _traceExclude = (String) arguments.get("qpid.trace.exclude");
- _trace = (String) arguments.get("qpid.trace.id");
- _id = getConfigStore().createId();
- getConfigStore().addConfiguredObject(this);
- String filterLogString = null;
-
- _logActor = GenericActor.getInstance(this);
- if (CurrentActor.get().getRootMessageLogger().isMessageEnabled(_logActor, this, SubscriptionMessages.CREATE_LOG_HIERARCHY))
- {
- filterLogString = getFilterLogString();
- CurrentActor.get().message(this, SubscriptionMessages.CREATE(filterLogString, queue.isDurable() && exclusive,
- filterLogString.length() > 0));
- }
-
- }
-
- public AMQShortString getConsumerTag()
- {
- return new AMQShortString(_destination);
- }
-
- public boolean isSuspended()
- {
- return !isActive() || _deleted.get(); // TODO check for Session suspension
- }
-
- public boolean hasInterest(QueueEntry entry)
- {
-
-
-
- //check that the message hasn't been rejected
- if (entry.isRejectedBy(this))
- {
-
- return false;
- }
-
-
-
- if (_noLocal
- && (entry.getMessage() instanceof MessageTransferMessage)
- && ((MessageTransferMessage)entry.getMessage()).getSession() == _session)
- {
- return false;
- }
-
-
- return checkFilters(entry);
-
-
- }
-
- private boolean checkFilters(QueueEntry entry)
- {
- return (_filters == null) || _filters.allAllow(entry);
- }
-
- public boolean isAutoClose()
- {
- // no such thing in 0-10
- return false;
- }
-
- public boolean isClosed()
- {
- return getState() == State.CLOSED;
- }
-
- public boolean isBrowser()
- {
- return _acquireMode == MessageAcquireMode.NOT_ACQUIRED;
- }
-
- public boolean seesRequeues()
- {
- return _acquireMode != MessageAcquireMode.NOT_ACQUIRED || _acceptMode == MessageAcceptMode.EXPLICIT;
- }
-
- public void close()
- {
- boolean closed = false;
- State state = getState();
-
- _stateChangeLock.lock();
- try
- {
- while(!closed && state != State.CLOSED)
- {
- closed = _state.compareAndSet(state, State.CLOSED);
- if(!closed)
- {
- state = getState();
- }
- else
- {
- _stateListener.stateChange(this,state, State.CLOSED);
- }
- }
- _creditManager.removeListener(this);
- getConfigStore().removeConfiguredObject(this);
- CurrentActor.get().message(getLogSubject(), SubscriptionMessages.CLOSE());
- }
- finally
- {
- _stateChangeLock.unlock();
- }
-
-
-
- }
-
- public ConfigStore getConfigStore()
- {
- return getQueue().getConfigStore();
- }
-
- public Long getDelivered()
- {
- return _deliveredCount.get();
- }
-
- public void creditStateChanged(boolean hasCredit)
- {
-
- if(hasCredit)
- {
- if(_state.compareAndSet(State.SUSPENDED, State.ACTIVE))
- {
- _stateListener.stateChange(this, State.SUSPENDED, State.ACTIVE);
- }
- else
- {
- // this is a hack to get round the issue of increasing bytes credit
- _stateListener.stateChange(this, State.ACTIVE, State.ACTIVE);
- }
- }
- else
- {
- if(_state.compareAndSet(State.ACTIVE, State.SUSPENDED))
- {
- _stateListener.stateChange(this, State.ACTIVE, State.SUSPENDED);
- }
- }
- }
-
-
- private class AddMessageDispositionListnerAction implements Runnable
- {
- public MessageTransfer _xfr;
- public ServerSession.MessageDispositionChangeListener _action;
-
- public void run()
- {
- if(_action != null)
- {
- _session.onMessageDispositionChange(_xfr, _action);
- }
- }
- }
-
- private final AddMessageDispositionListnerAction _postIdSettingAction = new AddMessageDispositionListnerAction();
-
- public void send(final QueueEntry entry) throws AMQException
- {
- ServerMessage serverMsg = entry.getMessage();
-
-
- MessageTransfer xfr;
-
- DeliveryProperties deliveryProps;
- MessageProperties messageProps = null;
-
- if(serverMsg instanceof MessageTransferMessage)
- {
-
- MessageTransferMessage msg = (MessageTransferMessage) serverMsg;
-
-
- Struct[] headers;
- if(msg.getHeader() == null)
- {
- headers = EMPTY_STRUCT_ARRAY;
- }
- else
- {
- headers = msg.getHeader().getStructs();
- }
-
- ArrayList<Struct> newHeaders = new ArrayList<Struct>(headers.length);
- DeliveryProperties origDeliveryProps = null;
- for(Struct header : headers)
- {
- if(header instanceof DeliveryProperties)
- {
- origDeliveryProps = (DeliveryProperties) header;
- }
- else
- {
- if(header instanceof MessageProperties)
- {
- messageProps = (MessageProperties) header;
- }
- newHeaders.add(header);
- }
- }
-
- deliveryProps = new DeliveryProperties();
- if(origDeliveryProps != null)
- {
- if(origDeliveryProps.hasDeliveryMode())
- {
- deliveryProps.setDeliveryMode(origDeliveryProps.getDeliveryMode());
- }
- if(origDeliveryProps.hasExchange())
- {
- deliveryProps.setExchange(origDeliveryProps.getExchange());
- }
- if(origDeliveryProps.hasExpiration())
- {
- deliveryProps.setExpiration(origDeliveryProps.getExpiration());
- }
- if(origDeliveryProps.hasPriority())
- {
- deliveryProps.setPriority(origDeliveryProps.getPriority());
- }
- if(origDeliveryProps.hasRoutingKey())
- {
- deliveryProps.setRoutingKey(origDeliveryProps.getRoutingKey());
- }
- if(origDeliveryProps.hasTimestamp())
- {
- deliveryProps.setTimestamp(origDeliveryProps.getTimestamp());
- }
-
-
- }
-
- deliveryProps.setRedelivered(entry.isRedelivered());
-
- newHeaders.add(deliveryProps);
-
- if(_trace != null && messageProps == null)
- {
- messageProps = new MessageProperties();
- newHeaders.add(messageProps);
- }
-
- Header header = new Header(newHeaders);
-
- xfr = new MessageTransfer(_destination,_acceptMode,_acquireMode,header,msg.getBody());
- }
- else if(serverMsg instanceof AMQMessage)
- {
- AMQMessage message_0_8 = (AMQMessage) serverMsg;
- deliveryProps = new DeliveryProperties();
- messageProps = new MessageProperties();
-
- int size = (int) message_0_8.getSize();
- ByteBuffer body = ByteBuffer.allocate(size);
- message_0_8.getContent(body, 0);
- body.flip();
-
- Struct[] headers = new Struct[] { deliveryProps, messageProps };
-
- BasicContentHeaderProperties properties =
- (BasicContentHeaderProperties) message_0_8.getContentHeaderBody().getProperties();
- final AMQShortString exchange = message_0_8.getMessagePublishInfo().getExchange();
- if(exchange != null)
- {
- deliveryProps.setExchange(exchange.toString());
- }
- deliveryProps.setExpiration(message_0_8.getExpiration());
- deliveryProps.setImmediate(message_0_8.isImmediate());
- deliveryProps.setPriority(MessageDeliveryPriority.get(properties.getPriority()));
- deliveryProps.setRedelivered(entry.isRedelivered());
- deliveryProps.setRoutingKey(message_0_8.getRoutingKey());
- deliveryProps.setTimestamp(properties.getTimestamp());
-
- messageProps.setContentEncoding(properties.getEncodingAsString());
- messageProps.setContentLength(size);
- if(properties.getAppId() != null)
- {
- messageProps.setAppId(properties.getAppId().getBytes());
- }
- messageProps.setContentType(properties.getContentTypeAsString());
- if(properties.getCorrelationId() != null)
- {
- messageProps.setCorrelationId(properties.getCorrelationId().getBytes());
- }
-
- // TODO - ReplyTo
-
- if(properties.getUserId() != null)
- {
- messageProps.setUserId(properties.getUserId().getBytes());
- }
-
- FieldTable fieldTable = properties.getHeaders();
-
- final Map<String, Object> appHeaders = FieldTable.convertToMap(fieldTable);
-
-
- messageProps.setApplicationHeaders(appHeaders);
-
- Header header = new Header(headers);
- xfr = new MessageTransfer(_destination,_acceptMode,_acquireMode,header, body);
- }
- else
- {
-
- deliveryProps = new DeliveryProperties();
- messageProps = new MessageProperties();
-
- int size = (int) serverMsg.getSize();
- ByteBuffer body = ByteBuffer.allocate(size);
- serverMsg.getContent(body, 0);
- body.flip();
-
- Struct[] headers = new Struct[] { deliveryProps, messageProps };
-
-
- deliveryProps.setExpiration(serverMsg.getExpiration());
- deliveryProps.setImmediate(serverMsg.isImmediate());
- deliveryProps.setPriority(MessageDeliveryPriority.get(serverMsg.getMessageHeader().getPriority()));
- deliveryProps.setRedelivered(entry.isRedelivered());
- deliveryProps.setRoutingKey(serverMsg.getRoutingKey());
- deliveryProps.setTimestamp(serverMsg.getMessageHeader().getTimestamp());
-
- messageProps.setContentEncoding(serverMsg.getMessageHeader().getEncoding());
- messageProps.setContentLength(size);
- messageProps.setContentType(serverMsg.getMessageHeader().getMimeType());
- if(serverMsg.getMessageHeader().getCorrelationId() != null)
- {
- messageProps.setCorrelationId(serverMsg.getMessageHeader().getCorrelationId().getBytes());
- }
-
-
- // TODO - ReplyTo
-
-
- final Map<String, Object> appHeaders = new HashMap<String, Object>();
-
- /*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(headers);
- xfr = new MessageTransfer(_destination,_acceptMode,_acquireMode,header, body);
- }
-
- boolean excludeDueToFederation = false;
-
- if(_trace != null)
- {
- if(!messageProps.hasApplicationHeaders())
- {
- messageProps.setApplicationHeaders(new HashMap<String,Object>());
- }
- Map<String,Object> appHeaders = messageProps.getApplicationHeaders();
- String trace = (String) appHeaders.get("x-qpid.trace");
- if(trace == null)
- {
- trace = _trace;
- }
- else
- {
- if(_traceExclude != null)
- {
- excludeDueToFederation = Arrays.asList(trace.split(",")).contains(_traceExclude);
- }
- trace+=","+_trace;
- }
- appHeaders.put("x-qpid.trace",trace);
- }
-
- if(!excludeDueToFederation)
- {
- if(_acceptMode == MessageAcceptMode.NONE && _acquireMode != MessageAcquireMode.PRE_ACQUIRED)
- {
- xfr.setCompletionListener(new MessageAcceptCompletionListener(this, _session, entry, _flowMode == MessageFlowMode.WINDOW));
- }
- else if(_flowMode == MessageFlowMode.WINDOW)
- {
- xfr.setCompletionListener(new Method.CompletionListener()
- {
- public void onComplete(Method method)
- {
- restoreCredit(entry);
- }
- });
- }
-
-
- _postIdSettingAction._xfr = xfr;
- if(_acceptMode == MessageAcceptMode.EXPLICIT)
- {
- _postIdSettingAction._action = new ExplicitAcceptDispositionChangeListener(entry, this);
- }
- else if(_acquireMode != MessageAcquireMode.PRE_ACQUIRED)
- {
- _postIdSettingAction._action = new ImplicitAcceptDispositionChangeListener(entry, this);
- }
- else
- {
- _postIdSettingAction._action = null;
- }
-
- _session.sendMessage(xfr, _postIdSettingAction);
- _deliveredCount.incrementAndGet();
- if(_acceptMode == MessageAcceptMode.NONE && _acquireMode == MessageAcquireMode.PRE_ACQUIRED)
- {
- forceDequeue(entry, false);
- }
- }
- else
- {
- forceDequeue(entry, _flowMode == MessageFlowMode.WINDOW);
-
- }
- }
-
- private void forceDequeue(final QueueEntry entry, final boolean restoreCredit)
- {
- ServerTransaction txn = new AutoCommitTransaction(getQueue().getVirtualHost().getTransactionLog());
- txn.dequeue(entry.getQueue(),entry.getMessage(),
- new ServerTransaction.Action()
- {
- public void postCommit()
- {
- if(restoreCredit)
- {
- restoreCredit(entry);
- }
- entry.discard();
- }
-
- public void onRollback()
- {
-
- }
- });
- }
-
- void reject(QueueEntry entry)
- {
- entry.setRedelivered();
- entry.routeToAlternate();
-
- }
-
- void release(QueueEntry entry)
- {
- entry.setRedelivered();
- entry.release();
- }
-
- public void queueDeleted(AMQQueue queue)
- {
- _deleted.set(true);
- }
-
- public boolean wouldSuspend(QueueEntry msg)
- {
- return !_creditManager.useCreditForMessage(msg.getMessage());
- }
-
- public void getSendLock()
- {
- _stateChangeLock.lock();
- }
-
- public void releaseSendLock()
- {
- _stateChangeLock.unlock();
- }
-
- public void restoreCredit(QueueEntry queueEntry)
- {
- _creditManager.restoreCredit(1, queueEntry.getSize());
- }
-
- public void onDequeue(QueueEntry queueEntry)
- {
-
- }
-
- public void setStateListener(StateListener listener)
- {
- _stateListener = listener;
- }
-
- public State getState()
- {
- return _state.get();
- }
-
- public AMQQueue.Context getQueueContext()
- {
- return _queueContext;
- }
-
- public void setQueueContext(AMQQueue.Context queueContext)
- {
- _queueContext = queueContext;
- }
-
- public boolean isActive()
- {
- return getState() == State.ACTIVE;
- }
-
- public void confirmAutoClose()
- {
- //No such thing in 0-10
- }
-
- public void set(String key, Object value)
- {
- _properties.put(key, value);
- }
-
- public Object get(String key)
- {
- return _properties.get(key);
- }
-
-
- public FlowCreditManager_0_10 getCreditManager()
- {
- return _creditManager;
- }
-
-
- public void stop()
- {
- if(_state.compareAndSet(State.ACTIVE, State.SUSPENDED))
- {
- _stateListener.stateChange(this, State.ACTIVE, State.SUSPENDED);
- }
- _stopped.set(true);
- FlowCreditManager_0_10 creditManager = getCreditManager();
- creditManager.clearCredit();
- }
-
- public void addCredit(MessageCreditUnit unit, long value)
- {
- FlowCreditManager_0_10 creditManager = getCreditManager();
-
- switch (unit)
- {
- case MESSAGE:
-
- creditManager.addCredit(value, 0L);
- break;
- case BYTE:
- creditManager.addCredit(0l, value);
- break;
- }
-
- _stopped.set(false);
-
- if(creditManager.hasCredit())
- {
- if(_state.compareAndSet(State.SUSPENDED, State.ACTIVE))
- {
- _stateListener.stateChange(this, State.SUSPENDED, State.ACTIVE);
- }
- }
-
- }
-
- public void setFlowMode(MessageFlowMode flowMode)
- {
-
-
- _creditManager.removeListener(this);
-
- switch(flowMode)
- {
- case CREDIT:
- _creditManager = new CreditCreditManager(0l,0l);
- break;
- case WINDOW:
- _creditManager = new WindowCreditManager(0l,0l);
- break;
- default:
- throw new RuntimeException("Unknown message flow mode: " + flowMode);
- }
- _flowMode = flowMode;
- if(_state.compareAndSet(State.ACTIVE, State.SUSPENDED))
- {
- _stateListener.stateChange(this, State.ACTIVE, State.SUSPENDED);
- }
-
- _creditManager.addStateListener(this);
-
- }
-
- public boolean isStopped()
- {
- return _stopped.get();
- }
-
- public boolean acquires()
- {
- return _acquireMode == MessageAcquireMode.PRE_ACQUIRED;
- }
-
- public void acknowledge(QueueEntry entry)
- {
- // TODO Fix Store Context / cleanup
- if(entry.isAcquiredBy(this))
- {
- entry.discard();
- }
- }
-
- public void flush() throws AMQException
- {
- _queue.flushSubscription(this);
- stop();
- }
-
- public long getSubscriptionID()
- {
- return _subscriptionID;
- }
-
- public LogActor getLogActor()
- {
- return _logActor;
- }
-
- public boolean isTransient()
- {
- return false;
- }
-
- ServerSession getSession()
- {
- return _session;
- }
-
-
- public SessionConfig getSessionConfig()
- {
- return getSession();
- }
-
- public boolean isBrowsing()
- {
- return _acquireMode == MessageAcquireMode.NOT_ACQUIRED;
- }
-
- public boolean isExclusive()
- {
- return getQueue().hasExclusiveSubscriber();
- }
-
- public ConfiguredObject getParent()
- {
- return getSessionConfig();
- }
-
- public boolean isDurable()
- {
- return false;
- }
-
- public SubscriptionConfigType getConfigType()
- {
- return SubscriptionConfigType.getInstance();
- }
-
- public boolean isExplicitAcknowledge()
- {
- return _acceptMode == MessageAcceptMode.EXPLICIT;
- }
-
- public String getCreditMode()
- {
- return _flowMode.toString();
- }
-
- public UUID getId()
- {
- return _id;
- }
-
- public String getName()
- {
- return _destination;
- }
-
- public Map<String, Object> getArguments()
- {
- return _arguments;
- }
-
- public boolean isSessionTransactional()
- {
- return _session.isTransactional();
- }
-
- public long getCreateTime()
- {
- return _createTime;
- }
-
- public String toLogString()
- {
- String queueInfo = MessageFormat.format(QUEUE_FORMAT, _queue.getVirtualHost().getName(),
- _queue.getNameShortString());
- String result = "[" + MessageFormat.format(SUBSCRIPTION_FORMAT, getSubscriptionID()) + "("
- // queueString is "vh(/{0})/qu({1}) " so need to trim
- + queueInfo.substring(0, queueInfo.length() - 1) + ")" + "] ";
- return result;
- }
-
- private String getFilterLogString()
- {
- StringBuilder filterLogString = new StringBuilder();
- String delimiter = ", ";
- boolean hasEntries = false;
- if (_filters != null && _filters.hasFilters())
- {
- filterLogString.append(_filters.toString());
- hasEntries = true;
- }
-
- if (isBrowser())
- {
- if (hasEntries)
- {
- filterLogString.append(delimiter);
- }
- filterLogString.append("Browser");
- hasEntries = true;
- }
-
- if (isDurable())
- {
- if (hasEntries)
- {
- filterLogString.append(delimiter);
- }
- filterLogString.append("Durable");
- hasEntries = true;
- }
-
- return filterLogString.toString();
- }
-
- public LogSubject getLogSubject()
- {
- return (LogSubject) this;
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/transport/QpidAcceptor.java b/java/broker/src/main/java/org/apache/qpid/server/transport/QpidAcceptor.java
deleted file mode 100644
index 3ca22b60c8..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/transport/QpidAcceptor.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.transport;
-
-import org.apache.qpid.transport.NetworkDriver;
-
-public class QpidAcceptor
-{
- NetworkDriver _driver;
- String _protocol;
- public QpidAcceptor(NetworkDriver driver, String protocol)
- {
- _driver = driver;
- _protocol = protocol;
- }
-
- public NetworkDriver getNetworkDriver()
- {
- return _driver;
- }
-
- public String toString()
- {
- return _protocol;
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/transport/ServerConnection.java b/java/broker/src/main/java/org/apache/qpid/server/transport/ServerConnection.java
deleted file mode 100644
index 54cd709af3..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/transport/ServerConnection.java
+++ /dev/null
@@ -1,346 +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.transport;
-
-import static org.apache.qpid.server.logging.subjects.LogSubjectFormat.*;
-
-import java.text.MessageFormat;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.UUID;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.protocol.AMQConstant;
-import org.apache.qpid.server.configuration.ConnectionConfig;
-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.ConnectionMessages;
-import org.apache.qpid.server.protocol.AMQConnectionModel;
-import org.apache.qpid.server.protocol.AMQSessionModel;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-import org.apache.qpid.server.stats.StatisticsCounter;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-import org.apache.qpid.transport.Connection;
-import org.apache.qpid.transport.ConnectionCloseCode;
-import org.apache.qpid.transport.ExecutionErrorCode;
-import org.apache.qpid.transport.ExecutionException;
-import org.apache.qpid.transport.Method;
-import org.apache.qpid.transport.ProtocolEvent;
-import org.apache.qpid.transport.Session;
-
-public class ServerConnection extends Connection implements AMQConnectionModel, LogSubject
-{
- private ConnectionConfig _config;
- private Runnable _onOpenTask;
- private AtomicBoolean _logClosed = new AtomicBoolean(false);
- private LogActor _actor = GenericActor.getInstance(this);
-
- private ApplicationRegistry _registry;
- private boolean _statisticsEnabled = false;
- private StatisticsCounter _messagesDelivered, _dataDelivered, _messagesReceived, _dataReceived;
-
- public ServerConnection()
- {
-
- }
-
- public UUID getId()
- {
- return _config.getId();
- }
-
- @Override
- protected void invoke(Method method)
- {
- super.invoke(method);
- }
-
- @Override
- protected void setState(State state)
- {
- super.setState(state);
-
- if (state == State.OPEN)
- {
- if (_onOpenTask != null)
- {
- _onOpenTask.run();
- }
- _actor.message(ConnectionMessages.OPEN(getClientId(), "0-10", true, true));
-
- getVirtualHost().getConnectionRegistry().registerConnection(this);
- }
-
- if (state == State.CLOSE_RCVD || state == State.CLOSED || state == State.CLOSING)
- {
- if(_virtualHost != null)
- {
- _virtualHost.getConnectionRegistry().deregisterConnection(this);
- }
- }
-
- if (state == State.CLOSED)
- {
- logClosed();
- }
- }
-
- protected void logClosed()
- {
- if(_logClosed.compareAndSet(false, true))
- {
- CurrentActor.get().message(this, ConnectionMessages.CLOSE());
- }
- }
-
- @Override
- public ServerConnectionDelegate getConnectionDelegate()
- {
- return (ServerConnectionDelegate) super.getConnectionDelegate();
- }
-
- public void setConnectionDelegate(ServerConnectionDelegate delegate)
- {
- super.setConnectionDelegate(delegate);
- }
-
- private VirtualHost _virtualHost;
-
-
- public VirtualHost getVirtualHost()
- {
- return _virtualHost;
- }
-
- public void setVirtualHost(VirtualHost virtualHost)
- {
- _virtualHost = virtualHost;
-
- initialiseStatistics();
- }
-
- public void setConnectionConfig(final ConnectionConfig config)
- {
- _config = config;
- }
-
- public ConnectionConfig getConfig()
- {
- return _config;
- }
-
- public void onOpen(final Runnable task)
- {
- _onOpenTask = task;
- }
-
- public void closeSession(AMQSessionModel session, AMQConstant cause, String message) throws AMQException
- {
- ExecutionException ex = new ExecutionException();
- ExecutionErrorCode code = ExecutionErrorCode.INTERNAL_ERROR;
- try
- {
- code = ExecutionErrorCode.get(cause.getCode());
- }
- catch (IllegalArgumentException iae)
- {
- // Ignore, already set to INTERNAL_ERROR
- }
- ex.setErrorCode(code);
- ex.setDescription(message);
- ((ServerSession)session).invoke(ex);
-
- ((ServerSession)session).close();
- }
-
- public LogSubject getLogSubject()
- {
- return (LogSubject) this;
- }
-
- @Override
- public void received(ProtocolEvent event)
- {
- if (event.isConnectionControl())
- {
- CurrentActor.set(_actor);
- }
- else
- {
- ServerSession channel = (ServerSession) getSession(event.getChannel());
- LogActor channelActor = null;
-
- if (channel != null)
- {
- channelActor = channel.getLogActor();
- }
-
- CurrentActor.set(channelActor == null ? _actor : channelActor);
- }
-
- try
- {
- super.received(event);
- }
- finally
- {
- CurrentActor.remove();
- }
- }
-
- public String toLogString()
- {
- boolean hasVirtualHost = (null != this.getVirtualHost());
- boolean hasPrincipal = (null != getAuthorizationID());
-
- if (hasPrincipal && hasVirtualHost)
- {
- return "[" +
- MessageFormat.format(CONNECTION_FORMAT,
- getConnectionId(),
- getClientId(),
- getConfig().getAddress(),
- getVirtualHost().getName())
- + "] ";
- }
- else if (hasPrincipal)
- {
- return "[" +
- MessageFormat.format(USER_FORMAT,
- getConnectionId(),
- getClientId(),
- getConfig().getAddress())
- + "] ";
-
- }
- else
- {
- return "[" +
- MessageFormat.format(SOCKET_FORMAT,
- getConnectionId(),
- getConfig().getAddress())
- + "] ";
- }
- }
-
- public LogActor getLogActor()
- {
- return _actor;
- }
-
- @Override
- public void close(AMQConstant cause, String message) throws AMQException
- {
- ConnectionCloseCode replyCode = ConnectionCloseCode.NORMAL;
- try
- {
- replyCode = ConnectionCloseCode.get(cause.getCode());
- }
- catch (IllegalArgumentException iae)
- {
- // Ignore
- }
- close(replyCode, message);
- }
-
- @Override
- public List<AMQSessionModel> getSessionModels()
- {
- List<AMQSessionModel> sessions = new ArrayList<AMQSessionModel>();
- for (Session ssn : getChannels())
- {
- sessions.add((AMQSessionModel) ssn);
- }
- return sessions;
- }
-
- public void registerMessageDelivered(long messageSize)
- {
- if (isStatisticsEnabled())
- {
- _messagesDelivered.registerEvent(1L);
- _dataDelivered.registerEvent(messageSize);
- }
- _virtualHost.registerMessageDelivered(messageSize);
- }
-
- public void registerMessageReceived(long messageSize, long timestamp)
- {
- if (isStatisticsEnabled())
- {
- _messagesReceived.registerEvent(1L, timestamp);
- _dataReceived.registerEvent(messageSize, timestamp);
- }
- _virtualHost.registerMessageReceived(messageSize, timestamp);
- }
-
- public StatisticsCounter getMessageReceiptStatistics()
- {
- return _messagesReceived;
- }
-
- public StatisticsCounter getDataReceiptStatistics()
- {
- return _dataReceived;
- }
-
- public StatisticsCounter getMessageDeliveryStatistics()
- {
- return _messagesDelivered;
- }
-
- public StatisticsCounter getDataDeliveryStatistics()
- {
- return _dataDelivered;
- }
-
- public void resetStatistics()
- {
- _messagesDelivered.reset();
- _dataDelivered.reset();
- _messagesReceived.reset();
- _dataReceived.reset();
- }
-
- public void initialiseStatistics()
- {
- setStatisticsEnabled(!StatisticsCounter.DISABLE_STATISTICS &&
- _virtualHost.getApplicationRegistry().getConfiguration().isStatisticsGenerationConnectionsEnabled());
-
- _messagesDelivered = new StatisticsCounter("messages-delivered-" + getConnectionId());
- _dataDelivered = new StatisticsCounter("data-delivered-" + getConnectionId());
- _messagesReceived = new StatisticsCounter("messages-received-" + getConnectionId());
- _dataReceived = new StatisticsCounter("data-received-" + getConnectionId());
- }
-
- public boolean isStatisticsEnabled()
- {
- return _statisticsEnabled;
- }
-
- public void setStatisticsEnabled(boolean enabled)
- {
- _statisticsEnabled = enabled;
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/transport/ServerConnectionDelegate.java b/java/broker/src/main/java/org/apache/qpid/server/transport/ServerConnectionDelegate.java
deleted file mode 100644
index 174dcbfa69..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/transport/ServerConnectionDelegate.java
+++ /dev/null
@@ -1,158 +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.transport;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.StringTokenizer;
-
-import javax.security.sasl.SaslException;
-import javax.security.sasl.SaslServer;
-
-import org.apache.qpid.protocol.ProtocolEngine;
-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.virtualhost.VirtualHost;
-import org.apache.qpid.transport.*;
-
-public class ServerConnectionDelegate extends ServerDelegate
-{
- private String _localFQDN;
- private final IApplicationRegistry _appRegistry;
-
- public ServerConnectionDelegate(IApplicationRegistry appRegistry, String localFQDN)
- {
- this(new HashMap<String,Object>(Collections.singletonMap("qpid.federation_tag",appRegistry.getBroker().getFederationTag())), Collections.singletonList((Object)"en_US"), appRegistry, localFQDN);
- }
-
-
- public ServerConnectionDelegate(Map<String, Object> properties,
- List<Object> locales,
- IApplicationRegistry appRegistry,
- String localFQDN)
- {
- super(properties, parseToList(appRegistry.getAuthenticationManager().getMechanisms()), locales);
-
- _appRegistry = appRegistry;
- _localFQDN = localFQDN;
- }
-
- private static List<Object> parseToList(String mechanisms)
- {
- List<Object> list = new ArrayList<Object>();
- StringTokenizer tokenizer = new StringTokenizer(mechanisms, " ");
- while(tokenizer.hasMoreTokens())
- {
- list.add(tokenizer.nextToken());
- }
- return list;
- }
-
- @Override
- public ServerSession getSession(Connection conn, SessionAttach atc)
- {
- SessionDelegate serverSessionDelegate = new ServerSessionDelegate(_appRegistry);
-
- ServerSession ssn = new ServerSession(conn, serverSessionDelegate, new Binary(atc.getName()), 0);
-
- return ssn;
- }
-
- @Override
- protected SaslServer createSaslServer(String mechanism) throws SaslException
- {
- return _appRegistry.getAuthenticationManager().createSaslServer(mechanism, _localFQDN);
-
- }
-
- @Override
- public void connectionClose(Connection conn, ConnectionClose close)
- {
- try
- {
- ((ServerConnection) conn).logClosed();
- }
- finally
- {
- super.connectionClose(conn, close);
- }
-
- }
-
- @Override
- public void connectionOpen(Connection conn, ConnectionOpen open)
- {
- ServerConnection sconn = (ServerConnection) conn;
-
- VirtualHost vhost;
- String vhostName;
- if(open.hasVirtualHost())
- {
- vhostName = open.getVirtualHost();
- }
- else
- {
- vhostName = "";
- }
- vhost = _appRegistry.getVirtualHostRegistry().getVirtualHost(vhostName);
-
- SecurityManager.setThreadPrincipal(conn.getAuthorizationID());
-
- if(vhost != null)
- {
- sconn.setVirtualHost(vhost);
-
- if (!vhost.getSecurityManager().accessVirtualhost(vhostName, ((ProtocolEngine) sconn.getConfig()).getRemoteAddress()))
- {
- sconn.invoke(new ConnectionClose(ConnectionCloseCode.CONNECTION_FORCED, "Permission denied '"+vhostName+"'"));
- sconn.setState(Connection.State.CLOSING);
- }
- else
- {
- sconn.invoke(new ConnectionOpenOk(Collections.emptyList()));
- sconn.setState(Connection.State.OPEN);
- }
- }
- else
- {
- sconn.invoke(new ConnectionClose(ConnectionCloseCode.INVALID_PATH, "Unknown virtualhost '"+vhostName+"'"));
- sconn.setState(Connection.State.CLOSING);
- }
-
- }
-
- @Override
- protected int getHeartbeatMax()
- {
- //TODO: implement broker support for actually sending heartbeats
- return 0;
- }
-
- @Override
- protected int getChannelMax()
- {
- return ApplicationRegistry.getInstance().getConfiguration().getMaxChannelCount();
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/transport/ServerSession.java b/java/broker/src/main/java/org/apache/qpid/server/transport/ServerSession.java
deleted file mode 100644
index 60c94b43c0..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/transport/ServerSession.java
+++ /dev/null
@@ -1,678 +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.transport;
-
-import static org.apache.qpid.server.logging.subjects.LogSubjectFormat.*;
-import static org.apache.qpid.util.Serial.*;
-
-import java.lang.ref.WeakReference;
-import java.security.Principal;
-import java.text.MessageFormat;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.SortedMap;
-import java.util.UUID;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentSkipListMap;
-import java.util.concurrent.CopyOnWriteArrayList;
-import java.util.concurrent.atomic.AtomicLong;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.protocol.AMQConstant;
-import org.apache.qpid.protocol.ProtocolEngine;
-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.SessionConfig;
-import org.apache.qpid.server.configuration.SessionConfigType;
-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.message.ServerMessage;
-import org.apache.qpid.server.protocol.AMQConnectionModel;
-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.QueueEntry;
-import org.apache.qpid.server.security.PrincipalHolder;
-import org.apache.qpid.server.store.MessageStore;
-import org.apache.qpid.server.subscription.Subscription_0_10;
-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.Binary;
-import org.apache.qpid.transport.Connection;
-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.Session;
-import org.apache.qpid.transport.SessionDelegate;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.sun.security.auth.UserPrincipal;
-
-public class ServerSession extends Session implements PrincipalHolder, SessionConfig, AMQSessionModel, LogSubject
-{
- private static final Logger _logger = LoggerFactory.getLogger(ServerSession.class);
-
- private static final String NULL_DESTINTATION = UUID.randomUUID().toString();
-
- private final UUID _id;
- private ConnectionConfig _connectionConfig;
- private long _createTime = System.currentTimeMillis();
- private LogActor _actor = GenericActor.getInstance(this);
-
- public static interface MessageDispositionChangeListener
- {
- public void onAccept();
-
- public void onRelease();
-
- public void onReject();
-
- public boolean acquire();
-
-
- }
-
- public static interface Task
- {
- public void doTask(ServerSession session);
- }
-
-
- private final SortedMap<Integer, MessageDispositionChangeListener> _messageDispositionListenerMap =
- new ConcurrentSkipListMap<Integer, MessageDispositionChangeListener>();
-
- private ServerTransaction _transaction;
-
- private final AtomicLong _txnStarts = new AtomicLong(0);
- private final AtomicLong _txnCommits = new AtomicLong(0);
- private final AtomicLong _txnRejects = new AtomicLong(0);
- private final AtomicLong _txnCount = new AtomicLong(0);
- private final AtomicLong _txnUpdateTime = new AtomicLong(0);
-
- private Principal _principal;
-
- private Map<String, Subscription_0_10> _subscriptions = new ConcurrentHashMap<String, Subscription_0_10>();
-
- private final List<Task> _taskList = new CopyOnWriteArrayList<Task>();
-
- private final WeakReference<Session> _reference;
-
- ServerSession(Connection connection, SessionDelegate delegate, Binary name, long expiry)
- {
- this(connection, delegate, name, expiry, ((ServerConnection)connection).getConfig());
- }
-
- protected void setState(State state)
- {
- super.setState(state);
-
- if (state == State.OPEN)
- {
- _actor.message(ChannelMessages.CREATE());
- }
- }
-
- public ServerSession(Connection connection, SessionDelegate delegate, Binary name, long expiry, ConnectionConfig connConfig)
- {
- super(connection, delegate, name, expiry);
- _connectionConfig = connConfig;
- _transaction = new AutoCommitTransaction(this.getMessageStore());
- _principal = new UserPrincipal(connection.getAuthorizationID());
- _reference = new WeakReference<Session>(this);
- _id = getConfigStore().createId();
- getConfigStore().addConfiguredObject(this);
- }
-
- private ConfigStore getConfigStore()
- {
- return getConnectionConfig().getConfigStore();
- }
-
-
- @Override
- protected boolean isFull(int id)
- {
- return isCommandsFull(id);
- }
-
- public void enqueue(final ServerMessage message, final ArrayList<? extends BaseQueue> queues)
- {
- getConnectionModel().registerMessageReceived(message.getSize(), message.getArrivalTime());
- _transaction.enqueue(queues,message, new ServerTransaction.Action()
- {
-
- BaseQueue[] _queues = queues.toArray(new BaseQueue[queues.size()]);
-
- public void postCommit()
- {
- for(int i = 0; i < _queues.length; i++)
- {
- try
- {
- _queues[i].enqueue(message);
- }
- catch (AMQException e)
- {
- // TODO
- throw new RuntimeException(e);
- }
- }
- }
-
- public void onRollback()
- {
- // NO-OP
- }
- });
-
- incrementOutstandingTxnsIfNecessary();
- updateTransactionalActivity();
- }
-
-
- public void sendMessage(MessageTransfer xfr,
- Runnable postIdSettingAction)
- {
- invoke(xfr, postIdSettingAction);
- getConnectionModel().registerMessageDelivered(xfr.getBodySize());
- }
-
- public void onMessageDispositionChange(MessageTransfer xfr, MessageDispositionChangeListener acceptListener)
- {
- _messageDispositionListenerMap.put(xfr.getId(), acceptListener);
- }
-
-
- private static interface MessageDispositionAction
- {
- void performAction(MessageDispositionChangeListener listener);
- }
-
- public void accept(RangeSet ranges)
- {
- dispositionChange(ranges, new MessageDispositionAction()
- {
- public void performAction(MessageDispositionChangeListener listener)
- {
- listener.onAccept();
- }
- });
- }
-
-
- public void release(RangeSet ranges)
- {
- dispositionChange(ranges, new MessageDispositionAction()
- {
- public void performAction(MessageDispositionChangeListener listener)
- {
- listener.onRelease();
- }
- });
- }
-
- public void reject(RangeSet ranges)
- {
- dispositionChange(ranges, new MessageDispositionAction()
- {
- public void performAction(MessageDispositionChangeListener listener)
- {
- listener.onReject();
- }
- });
- }
-
- public RangeSet acquire(RangeSet transfers)
- {
- RangeSet acquired = new RangeSet();
-
- if(!_messageDispositionListenerMap.isEmpty())
- {
- Iterator<Integer> unacceptedMessages = _messageDispositionListenerMap.keySet().iterator();
- Iterator<Range> rangeIter = transfers.iterator();
-
- if(rangeIter.hasNext())
- {
- Range range = rangeIter.next();
-
- while(range != null && unacceptedMessages.hasNext())
- {
- int next = unacceptedMessages.next();
- while(gt(next, range.getUpper()))
- {
- if(rangeIter.hasNext())
- {
- range = rangeIter.next();
- }
- else
- {
- range = null;
- break;
- }
- }
- if(range != null && range.includes(next))
- {
- MessageDispositionChangeListener changeListener = _messageDispositionListenerMap.get(next);
- if(changeListener != null && changeListener.acquire())
- {
- acquired.add(next);
- }
- }
-
-
- }
-
- }
-
-
- }
-
- return acquired;
- }
-
- public void dispositionChange(RangeSet ranges, MessageDispositionAction action)
- {
- if(ranges != null && !_messageDispositionListenerMap.isEmpty())
- {
- Iterator<Integer> unacceptedMessages = _messageDispositionListenerMap.keySet().iterator();
- Iterator<Range> rangeIter = ranges.iterator();
-
- if(rangeIter.hasNext())
- {
- Range range = rangeIter.next();
-
- while(range != null && unacceptedMessages.hasNext())
- {
- int next = unacceptedMessages.next();
- while(gt(next, range.getUpper()))
- {
- if(rangeIter.hasNext())
- {
- range = rangeIter.next();
- }
- else
- {
- range = null;
- break;
- }
- }
- if(range != null && range.includes(next))
- {
- MessageDispositionChangeListener changeListener = _messageDispositionListenerMap.remove(next);
- action.performAction(changeListener);
- }
-
-
- }
-
- }
-
- }
- }
-
- public void removeDispositionListener(Method method)
- {
- _messageDispositionListenerMap.remove(method.getId());
- }
-
- public void onClose()
- {
- _transaction.rollback();
- for(MessageDispositionChangeListener listener : _messageDispositionListenerMap.values())
- {
- listener.onRelease();
- }
- _messageDispositionListenerMap.clear();
-
- getConfigStore().removeConfiguredObject(this);
-
- for (Task task : _taskList)
- {
- task.doTask(this);
- }
-
- CurrentActor.get().message(getLogSubject(), ChannelMessages.CLOSE());
- }
-
- @Override
- protected void awaitClose()
- {
- // Broker shouldn't block awaiting close - thus do override this method to do nothing
- }
-
- public void acknowledge(final Subscription_0_10 sub, final QueueEntry entry)
- {
- _transaction.dequeue(entry.getQueue(), entry.getMessage(),
- new ServerTransaction.Action()
- {
-
- public void postCommit()
- {
- sub.acknowledge(entry);
- }
-
- public void onRollback()
- {
- entry.release();
- }
- });
- updateTransactionalActivity();
- }
-
- public Collection<Subscription_0_10> getSubscriptions()
- {
- return _subscriptions.values();
- }
-
- public void register(String destination, Subscription_0_10 sub)
- {
- _subscriptions.put(destination == null ? NULL_DESTINTATION : destination, sub);
- }
-
- public Subscription_0_10 getSubscription(String destination)
- {
- return _subscriptions.get(destination == null ? NULL_DESTINTATION : destination);
- }
-
- public void unregister(Subscription_0_10 sub)
- {
- _subscriptions.remove(sub.getConsumerTag().toString());
- try
- {
- sub.getSendLock();
- AMQQueue queue = sub.getQueue();
- if(queue != null)
- {
- queue.unregisterSubscription(sub);
- }
-
- }
- catch (AMQException e)
- {
- // TODO
- e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
- }
- finally
- {
- sub.releaseSendLock();
- }
- }
-
- public boolean isTransactional()
- {
- // this does not look great but there should only be one "non-transactional"
- // transactional context, while there could be several transactional ones in
- // theory
- return !(_transaction instanceof AutoCommitTransaction);
- }
-
- public boolean inTransaction()
- {
- return isTransactional() && _txnUpdateTime.get() > 0 && _transaction.getTransactionStartTime() > 0;
- }
-
- public void selectTx()
- {
- _transaction = new LocalTransaction(this.getMessageStore());
- _txnStarts.incrementAndGet();
- }
-
- public void commit()
- {
- _transaction.commit();
-
- _txnCommits.incrementAndGet();
- _txnStarts.incrementAndGet();
- decrementOutstandingTxnsIfNecessary();
- }
-
- public void rollback()
- {
- _transaction.rollback();
-
- _txnRejects.incrementAndGet();
- _txnStarts.incrementAndGet();
- decrementOutstandingTxnsIfNecessary();
- }
-
-
- private void incrementOutstandingTxnsIfNecessary()
- {
- if(isTransactional())
- {
- //There can currently only be at most one outstanding transaction
- //due to only having LocalTransaction support. Set value to 1 if 0.
- _txnCount.compareAndSet(0,1);
- }
- }
-
- private void decrementOutstandingTxnsIfNecessary()
- {
- if(isTransactional())
- {
- //There can currently only be at most one outstanding transaction
- //due to only having LocalTransaction support. Set value to 0 if 1.
- _txnCount.compareAndSet(1,0);
- }
- }
-
- /**
- * Update last transaction activity timestamp
- */
- public void updateTransactionalActivity()
- {
- if (isTransactional())
- {
- _txnUpdateTime.set(System.currentTimeMillis());
- }
- }
-
- public Long getTxnStarts()
- {
- return _txnStarts.get();
- }
-
- public Long getTxnCommits()
- {
- return _txnCommits.get();
- }
-
- public Long getTxnRejects()
- {
- return _txnRejects.get();
- }
-
- public Long getTxnCount()
- {
- return _txnCount.get();
- }
-
- public Principal getPrincipal()
- {
- return _principal;
- }
-
- public void addSessionCloseTask(Task task)
- {
- _taskList.add(task);
- }
-
- public void removeSessionCloseTask(Task task)
- {
- _taskList.remove(task);
- }
-
- public WeakReference<Session> getReference()
- {
- return _reference;
- }
-
- public MessageStore getMessageStore()
- {
- return getVirtualHost().getMessageStore();
- }
-
- public VirtualHost getVirtualHost()
- {
- return (VirtualHost) _connectionConfig.getVirtualHost();
- }
-
- public UUID getId()
- {
- return _id;
- }
-
- public SessionConfigType getConfigType()
- {
- return SessionConfigType.getInstance();
- }
-
- public ConfiguredObject getParent()
- {
- return getVirtualHost();
- }
-
- public boolean isDurable()
- {
- return false;
- }
-
- public boolean isAttached()
- {
- return true;
- }
-
- public long getDetachedLifespan()
- {
- return 0;
- }
-
- public Long getExpiryTime()
- {
- return null;
- }
-
- public Long getMaxClientRate()
- {
- return null;
- }
-
- public ConnectionConfig getConnectionConfig()
- {
- return _connectionConfig;
- }
-
- public String getSessionName()
- {
- return getName().toString();
- }
-
- public long getCreateTime()
- {
- return _createTime;
- }
-
- public void mgmtClose()
- {
- close();
- }
-
- public Object getID()
- {
- return getName();
- }
-
- public AMQConnectionModel getConnectionModel()
- {
- return (ServerConnection) getConnection();
- }
-
- public String getClientID()
- {
- return getConnection().getClientId();
- }
-
- public LogActor getLogActor()
- {
- return _actor;
- }
-
- public LogSubject getLogSubject()
- {
- return (LogSubject) this;
- }
-
- public void checkTransactionStatus(long openWarn, long openClose, long idleWarn, long idleClose) throws AMQException
- {
- if (inTransaction())
- {
- long currentTime = System.currentTimeMillis();
- long openTime = currentTime - _transaction.getTransactionStartTime();
- long idleTime = currentTime - _txnUpdateTime.get();
-
- // Log a warning on idle or open transactions
- if (idleWarn > 0L && idleTime > idleWarn)
- {
- CurrentActor.get().message(getLogSubject(), ChannelMessages.IDLE_TXN(openTime));
- _logger.warn("IDLE TRANSACTION ALERT " + getLogSubject().toString() + " " + idleTime + " ms");
- }
- else if (openWarn > 0L && openTime > openWarn)
- {
- CurrentActor.get().message(getLogSubject(), ChannelMessages.OPEN_TXN(openTime));
- _logger.warn("OPEN TRANSACTION ALERT " + getLogSubject().toString() + " " + openTime + " ms");
- }
-
- // Close connection for idle or open transactions that have timed out
- if (idleClose > 0L && idleTime > idleClose)
- {
- getConnectionModel().closeSession(this, AMQConstant.RESOURCE_ERROR, "Idle transaction timed out");
- }
- else if (openClose > 0L && openTime > openClose)
- {
- getConnectionModel().closeSession(this, AMQConstant.RESOURCE_ERROR, "Open transaction timed out");
- }
- }
- }
-
- @Override
- public String toLogString()
- {
- return "[" +
- MessageFormat.format(CHANNEL_FORMAT,
- getConnection().getConnectionId(),
- getClientID(),
- ((ProtocolEngine) _connectionConfig).getRemoteAddress().toString(),
- getVirtualHost().getName(),
- getChannel())
- + "] ";
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/transport/ServerSessionDelegate.java b/java/broker/src/main/java/org/apache/qpid/server/transport/ServerSessionDelegate.java
deleted file mode 100644
index be659c87ae..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/transport/ServerSessionDelegate.java
+++ /dev/null
@@ -1,1244 +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.transport;
-
-import java.nio.ByteBuffer;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Map;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.AMQUnknownExchangeType;
-import org.apache.qpid.common.AMQPFilterTypes;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.FieldTable;
-import org.apache.qpid.server.exchange.*;
-import org.apache.qpid.server.filter.FilterManager;
-import org.apache.qpid.server.filter.FilterManagerFactory;
-import org.apache.qpid.server.flow.FlowCreditManager_0_10;
-import org.apache.qpid.server.flow.WindowCreditManager;
-import org.apache.qpid.server.logging.actors.CurrentActor;
-import org.apache.qpid.server.logging.actors.GenericActor;
-import org.apache.qpid.server.message.MessageMetaData_0_10;
-import org.apache.qpid.server.message.MessageTransferMessage;
-import org.apache.qpid.server.protocol.AMQSessionModel;
-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.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.store.DurableConfigurationStore;
-import org.apache.qpid.server.store.MessageStore;
-import org.apache.qpid.server.store.StoredMessage;
-import org.apache.qpid.server.subscription.Subscription_0_10;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-import org.apache.qpid.transport.Acquired;
-import org.apache.qpid.transport.DeliveryProperties;
-import org.apache.qpid.transport.ExchangeBind;
-import org.apache.qpid.transport.ExchangeBound;
-import org.apache.qpid.transport.ExchangeBoundResult;
-import org.apache.qpid.transport.ExchangeDeclare;
-import org.apache.qpid.transport.ExchangeDelete;
-import org.apache.qpid.transport.ExchangeQuery;
-import org.apache.qpid.transport.ExchangeQueryResult;
-import org.apache.qpid.transport.ExchangeUnbind;
-import org.apache.qpid.transport.ExecutionErrorCode;
-import org.apache.qpid.transport.ExecutionException;
-import org.apache.qpid.transport.MessageAccept;
-import org.apache.qpid.transport.MessageAcceptMode;
-import org.apache.qpid.transport.MessageAcquire;
-import org.apache.qpid.transport.MessageAcquireMode;
-import org.apache.qpid.transport.MessageCancel;
-import org.apache.qpid.transport.MessageFlow;
-import org.apache.qpid.transport.MessageFlowMode;
-import org.apache.qpid.transport.MessageFlush;
-import org.apache.qpid.transport.MessageReject;
-import org.apache.qpid.transport.MessageRejectCode;
-import org.apache.qpid.transport.MessageRelease;
-import org.apache.qpid.transport.MessageResume;
-import org.apache.qpid.transport.MessageSetFlowMode;
-import org.apache.qpid.transport.MessageStop;
-import org.apache.qpid.transport.MessageSubscribe;
-import org.apache.qpid.transport.MessageTransfer;
-import org.apache.qpid.transport.Method;
-import org.apache.qpid.transport.QueueDeclare;
-import org.apache.qpid.transport.QueueDelete;
-import org.apache.qpid.transport.QueuePurge;
-import org.apache.qpid.transport.QueueQuery;
-import org.apache.qpid.transport.QueueQueryResult;
-import org.apache.qpid.transport.RangeSet;
-import org.apache.qpid.transport.Session;
-import org.apache.qpid.transport.SessionDelegate;
-import org.apache.qpid.transport.TxCommit;
-import org.apache.qpid.transport.TxRollback;
-import org.apache.qpid.transport.TxSelect;
-
-public class ServerSessionDelegate extends SessionDelegate
-{
- private final IApplicationRegistry _appRegistry;
-
- public ServerSessionDelegate(IApplicationRegistry appRegistry)
- {
- _appRegistry = appRegistry;
- }
-
- @Override
- public void command(Session session, Method method)
- {
- SecurityManager.setThreadPrincipal(session.getConnection().getAuthorizationID());
-
- if(!session.isClosing())
- {
- super.command(session, method);
- if (method.isSync())
- {
- session.flushProcessed();
- }
- }
- }
-
- @Override
- public void messageAccept(Session session, MessageAccept method)
- {
- ((ServerSession)session).accept(method.getTransfers());
- }
-
-
-
- @Override
- public void messageReject(Session session, MessageReject method)
- {
- ((ServerSession)session).reject(method.getTransfers());
- }
-
- @Override
- public void messageRelease(Session session, MessageRelease method)
- {
- ((ServerSession)session).release(method.getTransfers());
- }
-
- @Override
- public void messageAcquire(Session session, MessageAcquire method)
- {
- RangeSet acquiredRanges = ((ServerSession)session).acquire(method.getTransfers());
-
- Acquired result = new Acquired(acquiredRanges);
-
-
- session.executionResult((int) method.getId(), result);
-
-
- }
-
- @Override
- public void messageResume(Session session, MessageResume method)
- {
- super.messageResume(session, method);
- }
-
- @Override
- public void messageSubscribe(Session session, MessageSubscribe method)
- {
-
- //TODO - work around broken Python tests
- if(!method.hasAcceptMode())
- {
- method.setAcceptMode(MessageAcceptMode.EXPLICIT);
- }
- if(!method.hasAcquireMode())
- {
- method.setAcquireMode(MessageAcquireMode.PRE_ACQUIRED);
-
- }
-
- /* 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())
- {
- exception(session,method,ExecutionErrorCode.ILLEGAL_ARGUMENT, "queue not supplied");
- }
- else
- {
- String destination = method.getDestination();
-
- if(((ServerSession)session).getSubscription(destination)!=null)
- {
- exception(session, method, ExecutionErrorCode.NOT_ALLOWED, "Subscription already exists with destaination: '"+destination+"'");
- }
- else
- {
- String queueName = method.getQueue();
- QueueRegistry queueRegistry = getQueueRegistry(session);
-
-
- final AMQQueue queue = queueRegistry.getQueue(queueName);
-
- if(queue == null)
- {
- exception(session,method,ExecutionErrorCode.NOT_FOUND, "Queue: " + queueName + " not found");
- }
- else if(queue.getPrincipalHolder() != null && queue.getPrincipalHolder() != session)
- {
- exception(session,method,ExecutionErrorCode.RESOURCE_LOCKED, "Exclusive Queue: " + queueName + " owned exclusively by another session");
- }
- else
- {
- if(queue.isExclusive())
- {
- ServerSession s = (ServerSession) session;
- queue.setExclusiveOwningSession(s);
- if(queue.getPrincipalHolder() == null)
- {
- queue.setPrincipalHolder(s);
- queue.setExclusiveOwningSession(s);
- ((ServerSession) session).addSessionCloseTask(new ServerSession.Task()
- {
- public void doTask(ServerSession session)
- {
- if(queue.getPrincipalHolder() == session)
- {
- queue.setPrincipalHolder(null);
- queue.setExclusiveOwningSession(null);
- }
- }
- });
- }
-
- }
-
- FlowCreditManager_0_10 creditManager = new WindowCreditManager(0L,0L);
-
- FilterManager filterManager = null;
- try
- {
- filterManager = FilterManagerFactory.createManager(method.getArguments());
- }
- catch (AMQException amqe)
- {
- exception(session, method, ExecutionErrorCode.ILLEGAL_ARGUMENT, "Exception Creating FilterManager");
- return;
- }
-
- Subscription_0_10 sub = new Subscription_0_10((ServerSession)session,
- destination,
- method.getAcceptMode(),
- method.getAcquireMode(),
- MessageFlowMode.WINDOW,
- creditManager,
- filterManager,
- method.getArguments());
-
- ((ServerSession)session).register(destination, sub);
- try
- {
- queue.registerSubscription(sub, method.getExclusive());
- }
- catch (AMQQueue.ExistingExclusiveSubscription existing)
- {
- exception(session, method, ExecutionErrorCode.RESOURCE_LOCKED, "Queue has an exclusive consumer");
- }
- catch (AMQQueue.ExistingSubscriptionPreventsExclusive exclusive)
- {
- exception(session, method, ExecutionErrorCode.RESOURCE_LOCKED, "Queue has an existing consumer - can't subscribe exclusively");
- }
- catch (AMQException e)
- {
- exception(session, method, e, "Cannot subscribe to '" + destination);
- }
- }
- }
- }
- }
-
-
- @Override
- public void messageTransfer(Session ssn, MessageTransfer xfr)
- {
- ExchangeRegistry exchangeRegistry = getExchangeRegistry(ssn);
- Exchange exchange;
- if(xfr.hasDestination())
- {
- exchange = exchangeRegistry.getExchange(xfr.getDestination());
- if(exchange == null)
- {
- exchange = exchangeRegistry.getDefaultExchange();
- }
- }
- else
- {
- exchange = exchangeRegistry.getDefaultExchange();
- }
-
-
- DeliveryProperties delvProps = null;
- if(xfr.getHeader() != null && (delvProps = xfr.getHeader().get(DeliveryProperties.class)) != null && delvProps.hasTtl() && !delvProps.hasExpiration())
- {
- delvProps.setExpiration(System.currentTimeMillis() + delvProps.getTtl());
- }
-
- MessageMetaData_0_10 messageMetaData = new MessageMetaData_0_10(xfr);
-
- if (!getVirtualHost(ssn).getSecurityManager().authorisePublish(messageMetaData.isImmediate(), messageMetaData.getRoutingKey(), exchange.getName()))
- {
- ExecutionErrorCode errorCode = ExecutionErrorCode.UNAUTHORIZED_ACCESS;
- String description = "Permission denied: exchange-name '" + exchange.getName() + "'";
- exception(ssn, xfr, errorCode, description);
-
- return;
- }
-
- final MessageStore store = getVirtualHost(ssn).getMessageStore();
- StoredMessage<MessageMetaData_0_10> storeMessage = store.addMessage(messageMetaData);
- ByteBuffer body = xfr.getBody();
- if(body != null)
- {
- storeMessage.addContent(0, body);
- }
- storeMessage.flushToStore();
- MessageTransferMessage message = new MessageTransferMessage(storeMessage, ((ServerSession)ssn).getReference());
-
- ArrayList<? extends BaseQueue> queues = exchange.route(message);
-
-
-
- if(queues != null && queues.size() != 0)
- {
- ((ServerSession) ssn).enqueue(message, queues);
- }
- else
- {
- if(delvProps == null || !delvProps.hasDiscardUnroutable() || !delvProps.getDiscardUnroutable())
- {
- if(xfr.getAcceptMode() == MessageAcceptMode.EXPLICIT)
- {
- RangeSet rejects = new RangeSet();
- rejects.add(xfr.getId());
- MessageReject reject = new MessageReject(rejects, MessageRejectCode.UNROUTABLE, "Unroutable");
- ssn.invoke(reject);
- }
- else
- {
- Exchange alternate = exchange.getAlternateExchange();
- if(alternate != null)
- {
- queues = alternate.route(message);
- if(queues != null && queues.size() != 0)
- {
- ((ServerSession) ssn).enqueue(message, queues);
- }
- else
- {
- //TODO - log the message discard
- }
- }
- else
- {
- //TODO - log the message discard
- }
-
-
- }
- }
-
-
- }
-
- ssn.processed(xfr);
- }
-
- @Override
- public void messageCancel(Session session, MessageCancel method)
- {
- String destination = method.getDestination();
-
- Subscription_0_10 sub = ((ServerSession)session).getSubscription(destination);
-
- if(sub == null)
- {
- exception(session, method, ExecutionErrorCode.NOT_FOUND, "not-found: destination '"+destination+"'");
- }
- else
- {
- AMQQueue queue = sub.getQueue();
- ((ServerSession)session).unregister(sub);
- if(!queue.isDeleted() && queue.isExclusive() && queue.getConsumerCount() == 0)
- {
- queue.setPrincipalHolder(null);
- }
- }
- }
-
- @Override
- public void messageFlush(Session session, MessageFlush method)
- {
- String destination = method.getDestination();
-
- Subscription_0_10 sub = ((ServerSession)session).getSubscription(destination);
-
- if(sub == null)
- {
- exception(session, method, ExecutionErrorCode.NOT_FOUND, "not-found: destination '"+destination+"'");
- }
- else
- {
-
- try
- {
- sub.flush();
- }
- catch (AMQException e)
- {
- exception(session, method, e, "Cannot flush subscription '" + destination);
- }
- }
- }
-
- @Override
- public void txSelect(Session session, TxSelect method)
- {
- // TODO - check current tx mode
- ((ServerSession)session).selectTx();
- }
-
- @Override
- public void txCommit(Session session, TxCommit method)
- {
- // TODO - check current tx mode
- ((ServerSession)session).commit();
- }
-
- @Override
- public void txRollback(Session session, TxRollback method)
- {
- // TODO - check current tx mode
- ((ServerSession)session).rollback();
- }
-
-
- @Override
- public void exchangeDeclare(Session session, ExchangeDeclare method)
- {
- String exchangeName = method.getExchange();
- VirtualHost virtualHost = getVirtualHost(session);
- Exchange exchange = getExchange(session, exchangeName);
-
- if(method.getPassive())
- {
- if(exchange == null)
- {
- exception(session, method, ExecutionErrorCode.NOT_FOUND, "not-found: exchange-name '"+exchangeName+"'");
-
- }
- else
- {
- // TODO - check exchange has same properties
- if(!exchange.getTypeShortString().toString().equals(method.getType()))
- {
- exception(session, method, ExecutionErrorCode.NOT_ALLOWED, "Cannot redeclare with a different exchange type");
- }
- }
-
- }
- else
- {
- if (exchange == null)
- {
- ExchangeRegistry exchangeRegistry = getExchangeRegistry(session);
- ExchangeFactory exchangeFactory = virtualHost.getExchangeFactory();
-
-
-
- try
- {
-
- exchange = exchangeFactory.createExchange(method.getExchange(),
- method.getType(),
- method.getDurable(),
- method.getAutoDelete());
-
- String alternateExchangeName = method.getAlternateExchange();
- if(alternateExchangeName != null && alternateExchangeName.length() != 0)
- {
- Exchange alternate = getExchange(session, alternateExchangeName);
- exchange.setAlternateExchange(alternate);
- }
-
- if (exchange.isDurable())
- {
- DurableConfigurationStore store = virtualHost.getDurableConfigurationStore();
- store.createExchange(exchange);
- }
-
- 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");
- }
- }
-
- }
- }
-
- // TODO decouple AMQException and AMQConstant error codes
- private void exception(Session session, Method method, AMQException exception, String message)
- {
- ExecutionErrorCode errorCode = ExecutionErrorCode.INTERNAL_ERROR;
- if (exception.getErrorCode() != null)
- {
- try
- {
- errorCode = ExecutionErrorCode.get(exception.getErrorCode().getCode());
- }
- catch (IllegalArgumentException iae)
- {
- // ignore, already set to INTERNAL_ERROR
- }
- }
- String description = message + "': " + exception.getMessage();
-
- exception(session, method, errorCode, description);
- }
-
- private void exception(Session session, Method method, ExecutionErrorCode errorCode, String description)
- {
- ExecutionException ex = new ExecutionException();
- ex.setErrorCode(errorCode);
- ex.setCommandId(method.getId());
- ex.setDescription(description);
-
- session.invoke(ex);
-
- session.close();
- }
-
- private Exchange getExchange(Session session, String exchangeName)
- {
- ExchangeRegistry exchangeRegistry = getExchangeRegistry(session);
- return exchangeRegistry.getExchange(exchangeName);
- }
-
- private ExchangeRegistry getExchangeRegistry(Session session)
- {
- VirtualHost virtualHost = getVirtualHost(session);
- return virtualHost.getExchangeRegistry();
-
- }
-
- private VirtualHost getVirtualHost(Session session)
- {
- ServerConnection conn = getServerConnection(session);
- VirtualHost vhost = conn.getVirtualHost();
- return vhost;
- }
-
- private ServerConnection getServerConnection(Session session)
- {
- ServerConnection conn = (ServerConnection) session.getConnection();
- return conn;
- }
-
- @Override
- public void exchangeDelete(Session session, ExchangeDelete method)
- {
- VirtualHost virtualHost = getVirtualHost(session);
- ExchangeRegistry exchangeRegistry = virtualHost.getExchangeRegistry();
-
- try
- {
- Exchange exchange = getExchange(session, method.getExchange());
-
- if(exchange == null)
- {
- exception(session, method, ExecutionErrorCode.NOT_FOUND, "No such exchange '" + method.getExchange() + "'");
- }
- else if(exchange.hasReferrers())
- {
- exception(session, method, ExecutionErrorCode.NOT_ALLOWED, "Exchange in use as an alternate exchange");
- }
- else if(isStandardExchange(exchange, virtualHost.getExchangeFactory().getRegisteredTypes()))
- {
- exception(session, method, ExecutionErrorCode.NOT_ALLOWED, "Exchange '"+method.getExchange()+"' cannot be deleted");
- }
- else
- {
- exchangeRegistry.unregisterExchange(method.getExchange(), method.getIfUnused());
-
- if (exchange.isDurable() && !exchange.isAutoDelete())
- {
- DurableConfigurationStore store = virtualHost.getDurableConfigurationStore();
- store.removeExchange(exchange);
- }
- }
- }
- catch (ExchangeInUseException e)
- {
- exception(session, method, ExecutionErrorCode.PRECONDITION_FAILED, "Exchange in use");
- }
- catch (AMQException e)
- {
- exception(session, method, e, "Cannot delete exchange '" + method.getExchange() );
- }
- }
-
- private boolean isStandardExchange(Exchange exchange, Collection<ExchangeType<? extends Exchange>> registeredTypes)
- {
- for(ExchangeType type : registeredTypes)
- {
- if(type.getDefaultExchangeName().toString().equals( exchange.getName() ))
- {
- return true;
- }
- }
- return false;
- }
-
- @Override
- public void exchangeQuery(Session session, ExchangeQuery method)
- {
-
- ExchangeQueryResult result = new ExchangeQueryResult();
-
- Exchange exchange = getExchange(session, method.getName());
-
- if(exchange != null)
- {
- result.setDurable(exchange.isDurable());
- result.setType(exchange.getTypeShortString().toString());
- result.setNotFound(false);
- }
- else
- {
- result.setNotFound(true);
- }
-
- session.executionResult((int) method.getId(), result);
- }
-
- @Override
- public void exchangeBind(Session session, ExchangeBind method)
- {
-
- VirtualHost virtualHost = getVirtualHost(session);
- ExchangeRegistry exchangeRegistry = virtualHost.getExchangeRegistry();
- QueueRegistry queueRegistry = virtualHost.getQueueRegistry();
-
- if (!method.hasQueue())
- {
- exception(session, method, ExecutionErrorCode.ILLEGAL_ARGUMENT, "queue not set");
- }
- else if (!method.hasExchange())
- {
- exception(session, method, ExecutionErrorCode.ILLEGAL_ARGUMENT, "exchange not set");
- }
-/*
- else if (!method.hasBindingKey())
- {
- exception(session, method, ExecutionErrorCode.ILLEGAL_ARGUMENT, "binding-key not set");
- }
-*/
- else
- {
- //TODO - here because of non-compiant python tests
- if (!method.hasBindingKey())
- {
- method.setBindingKey(method.getQueue());
- }
- AMQQueue queue = queueRegistry.getQueue(method.getQueue());
- Exchange exchange = exchangeRegistry.getExchange(method.getExchange());
- if(queue == null)
- {
- exception(session, method, ExecutionErrorCode.NOT_FOUND, "Queue: '" + method.getQueue() + "' not found");
- }
- else if(exchange == null)
- {
- exception(session, method, ExecutionErrorCode.NOT_FOUND, "Exchange: '" + method.getExchange() + "' not found");
- }
- else if(exchange.getTypeShortString().equals(HeadersExchange.TYPE.getName()) && (!method.hasArguments() || method.getArguments() == null || !method.getArguments().containsKey("x-match")))
- {
- exception(session, method, ExecutionErrorCode.INTERNAL_ERROR, "Bindings to an exchange of type " + HeadersExchange.TYPE.getName() + " require an x-match header");
- }
- else
- {
- AMQShortString routingKey = new AMQShortString(method.getBindingKey());
- FieldTable fieldTable = FieldTable.convertToFieldTable(method.getArguments());
-
- if (!exchange.isBound(routingKey, fieldTable, queue))
- {
- try
- {
- virtualHost.getBindingFactory().addBinding(method.getBindingKey(), queue, exchange, method.getArguments());
- }
- catch (AMQException e)
- {
- exception(session, method, e, "Cannot add binding '" + method.getBindingKey());
- }
- }
- else
- {
- // todo
- }
- }
-
-
- }
-
-
-
- }
-
- @Override
- public void exchangeUnbind(Session session, ExchangeUnbind method)
- {
- VirtualHost virtualHost = getVirtualHost(session);
- ExchangeRegistry exchangeRegistry = virtualHost.getExchangeRegistry();
- QueueRegistry queueRegistry = virtualHost.getQueueRegistry();
-
- if (!method.hasQueue())
- {
- exception(session, method, ExecutionErrorCode.ILLEGAL_ARGUMENT, "queue not set");
- }
- else if (!method.hasExchange())
- {
- exception(session, method, ExecutionErrorCode.ILLEGAL_ARGUMENT, "exchange not set");
- }
- else if (!method.hasBindingKey())
- {
- exception(session, method, ExecutionErrorCode.ILLEGAL_ARGUMENT, "binding-key not set");
- }
- else
- {
- AMQQueue queue = queueRegistry.getQueue(method.getQueue());
- Exchange exchange = exchangeRegistry.getExchange(method.getExchange());
- if(queue == null)
- {
- exception(session, method, ExecutionErrorCode.NOT_FOUND, "Queue: '" + method.getQueue() + "' not found");
- }
- else if(exchange == null)
- {
- exception(session, method, ExecutionErrorCode.NOT_FOUND, "Exchange: '" + method.getExchange() + "' not found");
- }
- else
- {
- try
- {
- virtualHost.getBindingFactory().removeBinding(method.getBindingKey(), queue, exchange, null);
- }
- catch (AMQException e)
- {
- exception(session, method, e, "Cannot remove binding '" + method.getBindingKey());
- }
- }
- }
-
-
- super.exchangeUnbind(session, method);
- }
-
- @Override
- public void exchangeBound(Session session, ExchangeBound method)
- {
-
- ExchangeBoundResult result = new ExchangeBoundResult();
- Exchange exchange;
- AMQQueue queue;
- if(method.hasExchange())
- {
- exchange = getExchange(session, method.getExchange());
-
- if(exchange == null)
- {
- result.setExchangeNotFound(true);
- }
- }
- else
- {
- exchange = getExchangeRegistry(session).getDefaultExchange();
- }
-
-
- if(method.hasQueue())
- {
-
- queue = getQueue(session, method.getQueue());
- if(queue == null)
- {
- result.setQueueNotFound(true);
- }
-
-
- if(exchange != null && queue != null)
- {
-
- boolean queueMatched = exchange.isBound(queue);
-
- result.setQueueNotMatched(!queueMatched);
-
-
- 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));
- }
- else
- {
- result.setKeyNotMatched(!exchange.isBound(method.getBindingKey()));
- }
- }
- else if (method.hasArguments())
- {
- // TODO
-
- }
-
- result.setQueueNotMatched(!exchange.isBound(queue));
-
- }
- else if(exchange != null && method.hasBindingKey())
- {
- if(method.hasArguments())
- {
- // TODO
- }
- result.setKeyNotMatched(!exchange.isBound(method.getBindingKey()));
-
- }
-
- }
- else if(exchange != null && method.hasBindingKey())
- {
- if(method.hasArguments())
- {
- // TODO
- }
- result.setKeyNotMatched(!exchange.isBound(method.getBindingKey()));
-
- }
-
-
- session.executionResult((int) method.getId(), result);
-
-
- }
-
- private AMQQueue getQueue(Session session, String queue)
- {
- QueueRegistry queueRegistry = getQueueRegistry(session);
- return queueRegistry.getQueue(queue);
- }
-
- private QueueRegistry getQueueRegistry(Session session)
- {
- return getVirtualHost(session).getQueueRegistry();
- }
-
- @Override
- public void queueDeclare(Session session, final QueueDeclare method)
- {
-
- VirtualHost virtualHost = getVirtualHost(session);
- DurableConfigurationStore store = virtualHost.getDurableConfigurationStore();
-
- String queueName = method.getQueue();
- AMQQueue queue;
- QueueRegistry queueRegistry = getQueueRegistry(session);
- //TODO: do we need to check that the queue already exists with exactly the same "configuration"?
-
- synchronized (queueRegistry)
- {
-
- if (((queue = queueRegistry.getQueue(queueName)) == null))
- {
-
- if (method.getPassive())
- {
- String description = "Queue: " + queueName + " not found on VirtualHost(" + virtualHost + ").";
- ExecutionErrorCode errorCode = ExecutionErrorCode.NOT_FOUND;
-
- exception(session, method, errorCode, description);
-
- return;
- }
- else
- {
- try
- {
- queue = createQueue(queueName, method, virtualHost, (ServerSession)session);
- if(method.getExclusive())
- {
- queue.setExclusive(true);
- }
- else if(method.getAutoDelete())
- {
- queue.setDeleteOnNoConsumers(true);
- }
-
- final String alternateExchangeName = method.getAlternateExchange();
- if(alternateExchangeName != null && alternateExchangeName.length() != 0)
- {
- Exchange alternate = getExchange(session, alternateExchangeName);
- queue.setAlternateExchange(alternate);
- }
-
- if(method.hasArguments() && method.getArguments() != null)
- {
- if(method.getArguments().containsKey("no-local"))
- {
- Object no_local = method.getArguments().get("no-local");
- if(no_local instanceof Boolean && ((Boolean)no_local))
- {
- queue.setNoLocal(true);
- }
- }
- }
-
-
- if (queue.isDurable() && !queue.isAutoDelete())
- {
- if(method.hasArguments() && method.getArguments() != null)
- {
- Map<String,Object> args = method.getArguments();
- FieldTable ftArgs = new FieldTable();
- for(Map.Entry<String, Object> entry : args.entrySet())
- {
- ftArgs.put(new AMQShortString(entry.getKey()), entry.getValue());
- }
- store.createQueue(queue, ftArgs);
- }
- else
- {
- store.createQueue(queue);
- }
- }
- queueRegistry.registerQueue(queue);
- boolean autoRegister = ApplicationRegistry.getInstance().getConfiguration().getQueueAutoRegister();
-
- if (autoRegister)
- {
-
- ExchangeRegistry exchangeRegistry = getExchangeRegistry(session);
-
- Exchange defaultExchange = exchangeRegistry.getDefaultExchange();
-
- virtualHost.getBindingFactory().addBinding(queueName, queue, defaultExchange, null);
-
- }
-
- if (method.hasAutoDelete()
- && method.getAutoDelete()
- && method.hasExclusive()
- && method.getExclusive())
- {
- final AMQQueue q = queue;
- final ServerSession.Task deleteQueueTask = new ServerSession.Task()
- {
- public void doTask(ServerSession session)
- {
- try
- {
- q.delete();
- }
- catch (AMQException e)
- {
- exception(session, method, e, "Cannot delete '" + method.getQueue());
- }
- }
- };
- final ServerSession s = (ServerSession) session;
- s.addSessionCloseTask(deleteQueueTask);
- queue.addQueueDeleteTask(new AMQQueue.Task()
- {
- public void doTask(AMQQueue queue) throws AMQException
- {
- s.removeSessionCloseTask(deleteQueueTask);
- }
- });
- }
- if (method.hasExclusive()
- && method.getExclusive())
- {
- final AMQQueue q = queue;
- final ServerSession.Task removeExclusive = new ServerSession.Task()
- {
- public void doTask(ServerSession session)
- {
- q.setPrincipalHolder(null);
- q.setExclusiveOwningSession(null);
- }
- };
- final ServerSession s = (ServerSession) session;
- q.setExclusiveOwningSession(s);
- s.addSessionCloseTask(removeExclusive);
- queue.addQueueDeleteTask(new AMQQueue.Task()
- {
- public void doTask(AMQQueue queue) throws AMQException
- {
- s.removeSessionCloseTask(removeExclusive);
- }
- });
- }
- }
- catch (AMQException e)
- {
- exception(session, method, e, "Cannot declare queue '" + queueName);
- }
- }
- }
- else if (method.getExclusive() && (queue.getExclusiveOwningSession() != null && !queue.getExclusiveOwningSession().equals(session)))
- {
- String description = "Cannot declare queue('" + queueName + "'),"
- + " as exclusive queue with same name "
- + "declared on another session";
- ExecutionErrorCode errorCode = ExecutionErrorCode.RESOURCE_LOCKED;
-
- exception(session, method, errorCode, description);
-
- return;
- }
- }
- }
-
- protected AMQQueue createQueue(final String queueName,
- final QueueDeclare body,
- VirtualHost virtualHost,
- final ServerSession session)
- throws AMQException
- {
- String owner = body.getExclusive() ? session.getClientID() : null;
-
- final AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(queueName, body.getDurable(), owner, body.getAutoDelete(),
- body.getExclusive(), virtualHost, body.getArguments());
-
- return queue;
- }
-
- @Override
- public void queueDelete(Session session, QueueDelete method)
- {
- String queueName = method.getQueue();
- if(queueName == null || queueName.length()==0)
- {
- exception(session, method, ExecutionErrorCode.INVALID_ARGUMENT, "No queue name supplied");
-
- }
- else
- {
- AMQQueue queue = getQueue(session, queueName);
-
-
- if (queue == null)
- {
- exception(session, method, ExecutionErrorCode.NOT_FOUND, "No queue " + queueName + " found");
- }
- else
- {
- if(queue.getPrincipalHolder() != null && queue.getPrincipalHolder() != 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");
- }
- else if (method.getIfUnused() && !queue.isUnused())
- {
- // TODO - Error code
- exception(session, method, ExecutionErrorCode.PRECONDITION_FAILED, "Queue " + queueName + " in use");
-
- }
- else
- {
- VirtualHost virtualHost = getVirtualHost(session);
-
- try
- {
- queue.delete();
- if (queue.isDurable() && !queue.isAutoDelete())
- {
- DurableConfigurationStore store = virtualHost.getDurableConfigurationStore();
- store.removeQueue(queue);
- }
- }
- catch (AMQException e)
- {
- exception(session, method, e, "Cannot delete queue '" + queueName);
- }
- }
- }
- }
- }
-
- @Override
- public void queuePurge(Session session, QueuePurge method)
- {
- String queueName = method.getQueue();
- if(queueName == null || queueName.length()==0)
- {
- exception(session, method, ExecutionErrorCode.ILLEGAL_ARGUMENT, "No queue name supplied");
- }
- else
- {
- AMQQueue queue = getQueue(session, queueName);
-
- if (queue == null)
- {
- exception(session, method, ExecutionErrorCode.NOT_FOUND, "No queue " + queueName + " found");
- }
- else
- {
- try
- {
- queue.clearQueue();
- }
- catch (AMQException e)
- {
- exception(session, method, e, "Cannot purge queue '" + queueName);
- }
- }
- }
- }
-
- @Override
- public void queueQuery(Session session, QueueQuery method)
- {
- QueueQueryResult result = new QueueQueryResult();
-
- AMQQueue queue = getQueue(session, method.getQueue());
-
- if(queue != null)
- {
- result.setQueue(queue.getNameShortString().toString());
- result.setDurable(queue.isDurable());
- result.setExclusive(queue.isExclusive());
- result.setAutoDelete(queue.isAutoDelete());
- result.setArguments(queue.getArguments());
- result.setMessageCount(queue.getMessageCount());
- result.setSubscriberCount(queue.getConsumerCount());
-
- }
-
-
- session.executionResult((int) method.getId(), result);
-
- }
-
- @Override
- public void messageSetFlowMode(Session session, MessageSetFlowMode sfm)
- {
- String destination = sfm.getDestination();
-
- Subscription_0_10 sub = ((ServerSession)session).getSubscription(destination);
-
- if(sub == null)
- {
- exception(session, sfm, ExecutionErrorCode.NOT_FOUND, "not-found: destination '"+destination+"'");
- }
- else if(sub.isStopped())
- {
- sub.setFlowMode(sfm.getFlowMode());
- }
- }
-
- @Override
- public void messageStop(Session session, MessageStop stop)
- {
- String destination = stop.getDestination();
-
- Subscription_0_10 sub = ((ServerSession)session).getSubscription(destination);
-
- if(sub == null)
- {
- exception(session, stop, ExecutionErrorCode.NOT_FOUND, "not-found: destination '"+destination+"'");
- }
- else
- {
- sub.stop();
- }
-
- }
-
- @Override
- public void messageFlow(Session session, MessageFlow flow)
- {
- String destination = flow.getDestination();
-
- Subscription_0_10 sub = ((ServerSession)session).getSubscription(destination);
-
- if(sub == null)
- {
- exception(session, flow, ExecutionErrorCode.NOT_FOUND, "not-found: destination '"+destination+"'");
- }
- else
- {
- sub.addCredit(flow.getUnit(), flow.getValue());
- }
-
- }
-
- @Override
- public void closed(Session session)
- {
- for(Subscription_0_10 sub : getSubscriptions(session))
- {
- ((ServerSession)session).unregister(sub);
- }
- ((ServerSession)session).onClose();
- }
-
- @Override
- public void detached(Session session)
- {
- closed(session);
- }
-
- public Collection<Subscription_0_10> getSubscriptions(Session session)
- {
- return ((ServerSession)session).getSubscriptions();
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/txn/AutoCommitTransaction.java b/java/broker/src/main/java/org/apache/qpid/server/txn/AutoCommitTransaction.java
deleted file mode 100755
index 36e9d78440..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/txn/AutoCommitTransaction.java
+++ /dev/null
@@ -1,258 +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.txn;
-
-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;
-import org.apache.qpid.server.message.ServerMessage;
-import org.apache.qpid.server.queue.BaseQueue;
-import org.apache.qpid.server.queue.QueueEntry;
-import org.apache.qpid.server.store.TransactionLog;
-
-/**
- * An implementation of ServerTransaction where each enqueue/dequeue
- * operation takes place within it own transaction.
- *
- * Since there is no long-lived transaction, the commit and rollback methods of
- * this implementation are empty.
- */
-public class AutoCommitTransaction implements ServerTransaction
-{
- protected static final Logger _logger = Logger.getLogger(AutoCommitTransaction.class);
-
- private final TransactionLog _transactionLog;
-
- public AutoCommitTransaction(TransactionLog transactionLog)
- {
- _transactionLog = transactionLog;
- }
-
- public long getTransactionStartTime()
- {
- return 0L;
- }
-
- /**
- * Since AutoCommitTransaction have no concept of a long lived transaction, any Actions registered
- * by the caller are executed immediately.
- */
- public void addPostTransactionAction(Action immediateAction)
- {
- immediateAction.postCommit();
- }
-
- public void dequeue(BaseQueue queue, EnqueableMessage message, Action postTransactionAction)
- {
- TransactionLog.Transaction txn = null;
- try
- {
- if(message.isPersistent() && queue.isDurable())
- {
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Dequeue of message number " + message.getMessageNumber() + " from transaction log. Queue : " + queue.getNameShortString());
- }
-
- txn = _transactionLog.newTransaction();
- txn.dequeueMessage(queue, message.getMessageNumber());
- txn.commitTran();
- txn = null;
- }
- postTransactionAction.postCommit();
- postTransactionAction = null;
- }
- catch (AMQException e)
- {
- _logger.error("Error during message dequeue", e);
- throw new RuntimeException("Error during message dequeue", e);
- }
- finally
- {
- rollbackIfNecessary(postTransactionAction, txn);
- }
-
- }
-
- public void dequeue(Collection<QueueEntry> queueEntries, Action postTransactionAction)
- {
- TransactionLog.Transaction txn = null;
- try
- {
- for(QueueEntry entry : queueEntries)
- {
- ServerMessage message = entry.getMessage();
- BaseQueue queue = entry.getQueue();
-
- if(message.isPersistent() && queue.isDurable())
- {
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Dequeue of message number " + message.getMessageNumber() + " from transaction log. Queue : " + queue.getNameShortString());
- }
-
- if(txn == null)
- {
- txn = _transactionLog.newTransaction();
- }
-
- txn.dequeueMessage(queue, message.getMessageNumber());
- }
-
- }
- if(txn != null)
- {
- txn.commitTran();
- txn = null;
- }
- postTransactionAction.postCommit();
- postTransactionAction = null;
- }
- catch (AMQException e)
- {
- _logger.error("Error during message dequeues", e);
- throw new RuntimeException("Error during message dequeues", e);
- }
- finally
- {
- rollbackIfNecessary(postTransactionAction, txn);
- }
-
- }
-
-
- public void enqueue(BaseQueue queue, EnqueableMessage message, Action postTransactionAction)
- {
- TransactionLog.Transaction txn = null;
- try
- {
- if(message.isPersistent() && queue.isDurable())
- {
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Enqueue of message number " + message.getMessageNumber() + " to transaction log. Queue : " + queue.getNameShortString());
- }
-
- txn = _transactionLog.newTransaction();
- txn.enqueueMessage(queue, message.getMessageNumber());
- txn.commitTran();
- txn = null;
- }
- postTransactionAction.postCommit();
- postTransactionAction = null;
- }
- catch (AMQException e)
- {
- _logger.error("Error during message enqueue", e);
- throw new RuntimeException("Error during message enqueue", e);
- }
- finally
- {
- rollbackIfNecessary(postTransactionAction, txn);
- }
-
-
- }
-
- public void enqueue(List<? extends BaseQueue> queues, EnqueableMessage message, Action postTransactionAction)
- {
- TransactionLog.Transaction txn = null;
- try
- {
-
- if(message.isPersistent())
- {
- Long id = message.getMessageNumber();
- for(BaseQueue queue : queues)
- {
- if (queue.isDurable())
- {
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Enqueue of message number " + message.getMessageNumber() + " to transaction log. Queue : " + queue.getNameShortString());
- }
- if (txn == null)
- {
- txn = _transactionLog.newTransaction();
- }
-
- txn.enqueueMessage(queue, id);
- }
- }
-
- if (txn != null)
- {
- txn.commitTran();
- txn = null;
-
- }
- }
- postTransactionAction.postCommit();
- postTransactionAction = null;
- }
- catch (AMQException e)
- {
- _logger.error("Error during message enqueues", e);
- throw new RuntimeException("Error during message enqueues", e);
- }
- finally
- {
- rollbackIfNecessary(postTransactionAction, txn);
- }
-
- }
-
-
- public void commit()
- {
- }
-
- public void rollback()
- {
- }
-
- private void rollbackIfNecessary(Action postTransactionAction, TransactionLog.Transaction txn)
- {
- if (txn != null)
- {
- try
- {
- txn.abortTran();
- }
- catch (AMQStoreException e)
- {
- _logger.error("Abort transaction failed", e);
- // Deliberate decision not to re-throw this exception. Rationale: we can only reach here if a previous
- // TransactionLog method has ended in Exception. If we were to re-throw here, we would prevent
- // our caller from receiving the original exception (which is likely to be more revealing of the underlying error).
- }
- }
- if (postTransactionAction != null)
- {
- postTransactionAction.onRollback();
- }
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/txn/LocalTransaction.java b/java/broker/src/main/java/org/apache/qpid/server/txn/LocalTransaction.java
deleted file mode 100755
index 946dbd7c28..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/txn/LocalTransaction.java
+++ /dev/null
@@ -1,309 +0,0 @@
-package org.apache.qpid.server.txn;
-/*
- *
- * 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 java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.server.message.EnqueableMessage;
-import org.apache.qpid.server.message.ServerMessage;
-import org.apache.qpid.server.queue.BaseQueue;
-import org.apache.qpid.server.queue.QueueEntry;
-import org.apache.qpid.server.store.TransactionLog;
-import org.apache.qpid.server.queue.AMQQueue;
-import org.apache.qpid.server.queue.BaseQueue;
-import org.apache.qpid.server.queue.QueueEntry;
-import org.apache.qpid.server.store.TransactionLog;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * A concrete implementation of ServerTransaction where enqueue/dequeue
- * operations share a single long-lived transaction.
- *
- * The caller is responsible for invoking commit() (or rollback()) as necessary.
- */
-public class LocalTransaction implements ServerTransaction
-{
- protected static final Logger _logger = LoggerFactory.getLogger(LocalTransaction.class);
-
- private final List<Action> _postTransactionActions = new ArrayList<Action>();
-
- private volatile TransactionLog.Transaction _transaction;
- private TransactionLog _transactionLog;
- private long _txnStartTime = 0L;
-
- public LocalTransaction(TransactionLog transactionLog)
- {
- _transactionLog = transactionLog;
- }
-
- public boolean inTransaction()
- {
- return _transaction != null;
- }
-
- public long getTransactionStartTime()
- {
- return _txnStartTime;
- }
-
- public void addPostTransactionAction(Action postTransactionAction)
- {
- _postTransactionActions.add(postTransactionAction);
- }
-
- public void dequeue(BaseQueue queue, EnqueableMessage message, Action postTransactionAction)
- {
- _postTransactionActions.add(postTransactionAction);
-
- if(message.isPersistent() && queue.isDurable())
- {
- try
- {
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Dequeue of message number " + message.getMessageNumber() + " from transaction log. Queue : " + queue.getNameShortString());
- }
-
- beginTranIfNecessary();
- _transaction.dequeueMessage(queue, message.getMessageNumber());
-
- }
- catch(AMQException e)
- {
- _logger.error("Error during message dequeues", e);
- tidyUpOnError(e);
- }
- }
- }
-
- public void dequeue(Collection<QueueEntry> queueEntries, Action postTransactionAction)
- {
- _postTransactionActions.add(postTransactionAction);
-
- try
- {
- for(QueueEntry entry : queueEntries)
- {
- ServerMessage message = entry.getMessage();
- BaseQueue queue = entry.getQueue();
-
- if(message.isPersistent() && queue.isDurable())
- {
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Dequeue of message number " + message.getMessageNumber() + " from transaction log. Queue : " + queue.getNameShortString());
- }
-
- beginTranIfNecessary();
- _transaction.dequeueMessage(queue, message.getMessageNumber());
- }
-
- }
- }
- catch(AMQException e)
- {
- _logger.error("Error during message dequeues", e);
- tidyUpOnError(e);
- }
- }
-
- private void tidyUpOnError(Exception e)
- {
- try
- {
- for(Action action : _postTransactionActions)
- {
- action.onRollback();
- }
- }
- finally
- {
- try
- {
- if (_transaction != null)
- {
- _transaction.abortTran();
- }
- }
- catch (Exception abortException)
- {
- _logger.error("Abort transaction failed while trying to handle previous error", abortException);
- }
- finally
- {
- resetDetails();
- }
- }
-
- throw new RuntimeException(e);
- }
-
- private void beginTranIfNecessary()
- {
-
- if(_transaction == null)
- {
- try
- {
- _transaction = _transactionLog.newTransaction();
- }
- catch (Exception e)
- {
- tidyUpOnError(e);
- }
- }
- }
-
- public void enqueue(BaseQueue queue, EnqueableMessage message, Action postTransactionAction)
- {
- _postTransactionActions.add(postTransactionAction);
-
- if(message.isPersistent() && queue.isDurable())
- {
- try
- {
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Enqueue of message number " + message.getMessageNumber() + " to transaction log. Queue : " + queue.getNameShortString());
- }
-
- beginTranIfNecessary();
- _transaction.enqueueMessage(queue, message.getMessageNumber());
- }
- catch (Exception e)
- {
- _logger.error("Error during message enqueue", e);
-
- tidyUpOnError(e);
- }
- }
- }
-
- public void enqueue(List<? extends BaseQueue> queues, EnqueableMessage message, Action postTransactionAction)
- {
- _postTransactionActions.add(postTransactionAction);
-
- if (_txnStartTime == 0L)
- {
- _txnStartTime = System.currentTimeMillis();
- }
-
- if(message.isPersistent())
- {
- try
- {
- for(BaseQueue queue : queues)
- {
- if(queue.isDurable())
- {
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Enqueue of message number " + message.getMessageNumber() + " to transaction log. Queue : " + queue.getNameShortString() );
- }
-
-
- beginTranIfNecessary();
- _transaction.enqueueMessage(queue, message.getMessageNumber());
- }
- }
-
- }
- catch (Exception e)
- {
- _logger.error("Error during message enqueue", e);
-
- tidyUpOnError(e);
- }
- }
- }
-
- public void commit()
- {
- try
- {
- if(_transaction != null)
- {
- _transaction.commitTran();
- }
-
- for(Action action : _postTransactionActions)
- {
- action.postCommit();
- }
- }
- catch (Exception e)
- {
- _logger.error("Failed to commit transaction", e);
-
- for(Action action : _postTransactionActions)
- {
- action.onRollback();
- }
- throw new RuntimeException("Failed to commit transaction", e);
- }
- finally
- {
- resetDetails();
- }
- }
-
- public void rollback()
- {
- try
- {
- if(_transaction != null)
- {
- _transaction.abortTran();
- }
- }
- catch (AMQException e)
- {
- _logger.error("Failed to rollback transaction", e);
- throw new RuntimeException("Failed to rollback transaction", e);
- }
- finally
- {
- try
- {
- for(Action action : _postTransactionActions)
- {
- action.onRollback();
- }
- }
- finally
- {
- resetDetails();
- }
- }
- }
-
- private void resetDetails()
- {
- _transaction = null;
- _postTransactionActions.clear();
- _txnStartTime = 0L;
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/txn/ServerTransaction.java b/java/broker/src/main/java/org/apache/qpid/server/txn/ServerTransaction.java
deleted file mode 100755
index b3c6e1ac3a..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/txn/ServerTransaction.java
+++ /dev/null
@@ -1,110 +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.txn;
-
-import org.apache.qpid.server.message.EnqueableMessage;
-import org.apache.qpid.server.queue.BaseQueue;
-import org.apache.qpid.server.queue.QueueEntry;
-
-import java.util.Collection;
-import java.util.List;
-
-
-/**
- * The ServerTransaction interface allows a set enqueue/dequeue operations to be
- * performed against the transaction belonging the underlying TransactionLog object.
- *
- * Typically all ServerTransaction implementations decide if a message should be enlisted
- * into a store transaction by examining the durable property of the queue, and the persistence
- * property of the message.
- *
- * A caller may register a list of post transaction Actions to be
- * performed on commit() (or rollback()).
- *
- */
-public interface ServerTransaction
-{
- /**
- * Represents an action to be performed on transaction commit or rollback
- */
- public static interface Action
- {
- public void postCommit();
-
- public void onRollback();
- }
-
- /**
- * Return the time the current transaction started.
- *
- * @return the time this transaction started or 0 if not in a transaction
- */
- long getTransactionStartTime();
-
- /**
- * Register an Action for execution after transaction commit or rollback. Actions
- * will be executed in the order in which they are registered.
- */
- void addPostTransactionAction(Action postTransactionAction);
-
- /**
- * Dequeue a message from a queue registering a post transaction action.
- *
- * A store operation will result only for a persistent message on a durable queue.
- */
- void dequeue(BaseQueue queue, EnqueableMessage message, Action postTransactionAction);
-
- /**
- * Dequeue a message(s) from queue(s) registering a post transaction action.
- *
- * Store operations will result only for a persistent messages on durable queues.
- */
- void dequeue(Collection<QueueEntry> messages, Action postTransactionAction);
-
- /**
- * Enqueue a message to a queue registering a post transaction action.
- *
- * A store operation will result only for a persistent message on a durable queue.
- */
- void enqueue(BaseQueue queue, EnqueableMessage message, Action postTransactionAction);
-
- /**
- * Enqueue a message(s) to queue(s) registering a post transaction action.
- *
- * Store operations will result only for a persistent messages on durable queues.
- */
- void enqueue(List<? extends BaseQueue> queues, EnqueableMessage message, Action postTransactionAction);
-
- /**
- * Commit the transaction represented by this object.
- *
- * If the caller has registered one or more Actions, the postCommit() method on each will
- * be executed immediately after the underlying transaction has committed.
- */
- void commit();
-
- /** Rollback the transaction represented by this object.
- *
- * If the caller has registered one or more Actions, the onRollback() method on each will
- * be executed immediately after the underlying transaction has rolled-back.
- */
- void rollback();
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/util/CircularBuffer.java b/java/broker/src/main/java/org/apache/qpid/server/util/CircularBuffer.java
deleted file mode 100644
index e730e2f3c3..0000000000
--- a/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/java/broker/src/main/java/org/apache/qpid/server/util/LoggingProxy.java b/java/broker/src/main/java/org/apache/qpid/server/util/LoggingProxy.java
deleted file mode 100644
index eda97e0ed2..0000000000
--- a/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.
- * <p>
- * Useful in debugging.
- * <p>
- */
-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/java/broker/src/main/java/org/apache/qpid/server/virtualhost/HouseKeepingTask.java b/java/broker/src/main/java/org/apache/qpid/server/virtualhost/HouseKeepingTask.java
deleted file mode 100644
index 2db1944cd1..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/HouseKeepingTask.java
+++ /dev/null
@@ -1,76 +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.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 VirtualHost _virtualHost;
-
- private String _name;
-
- private RootMessageLogger _rootLogger;
- public HouseKeepingTask(VirtualHost vhost)
- {
- _virtualHost = vhost;
- _name = _virtualHost.getName() + ":" + this.getClass().getSimpleName();
- _rootLogger = CurrentActor.get().getRootMessageLogger();
- }
-
- final public void run()
- {
- // Don't need to undo this as this is a thread pool thread so will
- // always go through here before we do any real work.
- Thread.currentThread().setName(_name);
- CurrentActor.set(new AbstractActor(_rootLogger)
- {
- @Override
- public String getLogMessage()
- {
- return _name;
- }
- });
-
- try
- {
- execute();
- }
- catch (Throwable e)
- {
- _logger.warn(this.getClass().getSimpleName() + " throw exception: " + e, e);
- }
- }
-
- public VirtualHost getVirtualHost()
- {
- return _virtualHost;
- }
-
- /** Execute the plugin. */
- public abstract void execute();
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/ManagedVirtualHost.java b/java/broker/src/main/java/org/apache/qpid/server/virtualhost/ManagedVirtualHost.java
deleted file mode 100644
index 767474d5ae..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/ManagedVirtualHost.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.virtualhost;
-
-import java.io.IOException;
-
-import org.apache.qpid.management.common.mbeans.annotations.MBeanAttribute;
-
-/**
- * The management interface exposed to allow management of a virtualHost
- */
-public interface ManagedVirtualHost
-{
- static final String TYPE = "VirtualHost";
- static final int VERSION = 1;
-
- /**
- * Returns the name of the managed virtualHost.
- * @return the name of the exchange.
- * @throws java.io.IOException
- */
- @MBeanAttribute(name="Name", description= TYPE + " Name")
- String getName() throws IOException;
-
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHost.java b/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHost.java
deleted file mode 100755
index 04f19b79bb..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHost.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.server.virtualhost;
-
-import java.util.UUID;
-
-import org.apache.qpid.common.Closeable;
-import org.apache.qpid.server.binding.BindingFactory;
-import org.apache.qpid.server.configuration.ConfigStore;
-import org.apache.qpid.server.configuration.VirtualHostConfig;
-import org.apache.qpid.server.configuration.VirtualHostConfiguration;
-import org.apache.qpid.server.connection.IConnectionRegistry;
-import org.apache.qpid.server.exchange.ExchangeFactory;
-import org.apache.qpid.server.exchange.ExchangeRegistry;
-import org.apache.qpid.server.federation.BrokerLink;
-import org.apache.qpid.server.management.ManagedObject;
-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.store.TransactionLog;
-
-public interface VirtualHost extends DurableConfigurationStore.Source, VirtualHostConfig, Closeable, StatisticsGatherer
-{
- IConnectionRegistry getConnectionRegistry();
-
- VirtualHostConfiguration getConfiguration();
-
- String getName();
-
- QueueRegistry getQueueRegistry();
-
- ExchangeRegistry getExchangeRegistry();
-
- ExchangeFactory getExchangeFactory();
-
- MessageStore getMessageStore();
-
- TransactionLog getTransactionLog();
-
- DurableConfigurationStore getDurableConfigurationStore();
-
- AuthenticationManager getAuthenticationManager();
-
- SecurityManager getSecurityManager();
-
- void close();
-
- ManagedObject getManagedObject();
-
- UUID getBrokerId();
-
- void scheduleHouseKeepingTask(long period, HouseKeepingTask task);
-
- long getHouseKeepingTaskCount();
-
- public long getHouseKeepingCompletedTaskCount();
-
- int getHouseKeepingPoolSize();
-
- void setHouseKeepingPoolSize(int newSize);
-
- int getHouseKeepingActiveCount();
-
- IApplicationRegistry getApplicationRegistry();
-
- BindingFactory getBindingFactory();
-
- void createBrokerConnection(String transport,
- String host,
- int port,
- String vhost,
- boolean durable,
- String authMechanism, String username, String password);
-
- ConfigStore getConfigStore();
-
- void removeBrokerConnection(BrokerLink brokerLink);
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHostConfigRecoveryHandler.java b/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHostConfigRecoveryHandler.java
deleted file mode 100755
index 96a9ac729e..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHostConfigRecoveryHandler.java
+++ /dev/null
@@ -1,360 +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.virtualhost;
-
-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.TransactionLog;
-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 java.nio.ByteBuffer;
-
-import java.util.List;
-import java.util.ArrayList;
-import java.util.Map;
-import java.util.HashMap;
-import java.util.TreeMap;
-
-public class VirtualHostConfigRecoveryHandler implements ConfigurationRecoveryHandler,
- ConfigurationRecoveryHandler.QueueRecoveryHandler,
- ConfigurationRecoveryHandler.ExchangeRecoveryHandler,
- ConfigurationRecoveryHandler.BindingRecoveryHandler,
- MessageStoreRecoveryHandler,
- MessageStoreRecoveryHandler.StoredMessageRecoveryHandler,
- TransactionLogRecoveryHandler,
- TransactionLogRecoveryHandler.QueueEntryRecoveryHandler
-{
- private static final Logger _logger = Logger.getLogger(VirtualHostConfigRecoveryHandler.class);
-
-
- private final VirtualHost _virtualHost;
-
- private MessageStoreLogSubject _logSubject;
- private List<ProcessAction> _actions;
-
- private MessageStore _store;
- private TransactionLog _transactionLog;
-
- private final Map<String, Integer> _queueRecoveries = new TreeMap<String, Integer>();
- private Map<Long, ServerMessage> _recoveredMessages = new HashMap<Long, ServerMessage>();
- private Map<Long, StoredMessage> _unusedMessages = new HashMap<Long, StoredMessage>();
-
-
-
- public VirtualHostConfigRecoveryHandler(VirtualHost virtualHost)
- {
- _virtualHost = virtualHost;
- }
-
- public QueueRecoveryHandler begin(MessageStore store)
- {
- _logSubject = new MessageStoreLogSubject(_virtualHost,store);
- _store = store;
- CurrentActor.get().message(_logSubject, TransactionLogMessages.RECOVERY_START(null, false));
-
- return this;
- }
-
- public void queue(String queueName, String owner, boolean exclusive, FieldTable arguments)
- {
- try
- {
- AMQShortString queueNameShortString = new AMQShortString(queueName);
-
- AMQQueue q = _virtualHost.getQueueRegistry().getQueue(queueNameShortString);
-
- if (q == null)
- {
- q = AMQQueueFactory.createAMQQueueImpl(queueNameShortString, true, owner == null ? null : new AMQShortString(owner), false, exclusive, _virtualHost,
- arguments);
- _virtualHost.getQueueRegistry().registerQueue(q);
- }
-
- CurrentActor.get().message(_logSubject, TransactionLogMessages.RECOVERY_START(queueName, true));
-
- //Record that we have a queue for recovery
- _queueRecoveries.put(queueName, 0);
- }
- catch (AMQException e)
- {
- // TODO
- throw new RuntimeException(e);
- }
- }
-
- public ExchangeRecoveryHandler completeQueueRecovery()
- {
- return this;
- }
-
- public void exchange(String exchangeName, String type, boolean autoDelete)
- {
- try
- {
- Exchange exchange;
- AMQShortString exchangeNameSS = new AMQShortString(exchangeName);
- exchange = _virtualHost.getExchangeRegistry().getExchange(exchangeNameSS);
- if (exchange == null)
- {
- exchange = _virtualHost.getExchangeFactory().createExchange(exchangeNameSS, new AMQShortString(type), true, autoDelete, 0);
- _virtualHost.getExchangeRegistry().registerExchange(exchange);
- }
- }
- catch (AMQException e)
- {
- // TODO
- throw new RuntimeException(e);
- }
- }
-
- public BindingRecoveryHandler completeExchangeRecovery()
- {
- return this;
- }
-
- public StoredMessageRecoveryHandler begin()
- {
- // TODO - log begin
- return this;
- }
-
- public void message(StoredMessage message)
- {
- ServerMessage serverMessage;
- switch(message.getMetaData().getType())
- {
- case META_DATA_0_8:
- serverMessage = new AMQMessage(message);
- break;
- case META_DATA_0_10:
- serverMessage = new MessageTransferMessage(message, null);
- break;
- default:
- 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);
- }
-
- public void completeMessageRecovery()
- {
- //TODO - log end
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public TransactionLogRecoveryHandler.QueueEntryRecoveryHandler begin(TransactionLog log)
- {
- _transactionLog = log;
- return this;
- }
-
- private static final class ProcessAction
- {
- private final AMQQueue _queue;
- private final AMQMessage _message;
-
- public ProcessAction(AMQQueue queue, AMQMessage message)
- {
- _queue = queue;
- _message = message;
- }
-
- public void process()
- {
- try
- {
- _queue.enqueue(_message);
- }
- catch(AMQException e)
- {
- throw new RuntimeException(e);
- }
- }
-
- }
-
- public void binding(String exchangeName, String queueName, String bindingKey, ByteBuffer buf)
- {
- _actions = new ArrayList<ProcessAction>();
- try
- {
- Exchange exchange = _virtualHost.getExchangeRegistry().getExchange(exchangeName);
- if (exchange == null)
- {
- _logger.error("Unknown exchange: " + exchangeName + ", cannot bind queue : " + queueName);
- return;
- }
-
- AMQQueue queue = _virtualHost.getQueueRegistry().getQueue(new AMQShortString(queueName));
- if (queue == null)
- {
- _logger.error("Unknown queue: " + queueName + ", cannot be bound to exchange: " + exchangeName);
- }
- else
- {
- FieldTable argumentsFT = null;
- if(buf != null)
- {
- argumentsFT = new FieldTable(org.apache.mina.common.ByteBuffer.wrap(buf),buf.limit());
- }
-
- BindingFactory bf = _virtualHost.getBindingFactory();
-
- Map<String, Object> argumentMap = FieldTable.convertToMap(argumentsFT);
-
- if(bf.getBinding(bindingKey, queue, exchange, argumentMap) == null)
- {
-
- _logger.info("Restoring binding: (Exchange: " + exchange.getNameShortString() + ", Queue: " + queueName
- + ", Routing Key: " + bindingKey + ", Arguments: " + argumentsFT + ")");
-
- bf.restoreBinding(bindingKey, queue, exchange, argumentMap);
- }
- }
- }
- catch (AMQException e)
- {
- throw new RuntimeException(e);
- }
-
- }
-
- public void completeBindingRecovery()
- {
- //return this;
- }
-
- public void complete()
- {
-
-
- }
-
- public void queueEntry(final String queueName, long messageId)
- {
- AMQShortString queueNameShortString = new AMQShortString(queueName);
-
- AMQQueue queue = _virtualHost.getQueueRegistry().getQueue(queueNameShortString);
-
- try
- {
- if(queue != null)
- {
- ServerMessage message = _recoveredMessages.get(messageId);
- _unusedMessages.remove(messageId);
-
- if(message != null)
- {
-
-
- if (_logger.isDebugEnabled())
- {
- _logger.debug("On recovery, delivering " + message.getMessageNumber() + " to " + queue.getNameShortString());
- }
-
- Integer count = _queueRecoveries.get(queueName);
- if (count == null)
- {
- count = 0;
- }
-
- queue.enqueue(message);
-
- _queueRecoveries.put(queueName, ++count);
- }
- else
- {
- _logger.warn("Message id " + messageId + " referenced in log as enqueued in queue " + queue.getNameShortString() + " is unknown, entry will be discarded");
- TransactionLog.Transaction txn = _transactionLog.newTransaction();
- txn.dequeueMessage(queue, messageId);
- txn.commitTranAsync();
- }
- }
- else
- {
- _logger.warn("Message id " + messageId + " in log references queue " + queueName + " which is not in the configuration, entry will be discarded");
- TransactionLog.Transaction txn = _transactionLog.newTransaction();
- TransactionLogResource mockQueue =
- new TransactionLogResource()
- {
-
- public String getResourceName()
- {
- return queueName;
- }
- };
- txn.dequeueMessage(mockQueue, messageId);
- txn.commitTranAsync();
- }
-
- }
- catch(AMQException e)
- {
- throw new RuntimeException(e);
- }
-
-
-
- }
-
- public void 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<String,Integer> entry : _queueRecoveries.entrySet())
- {
- CurrentActor.get().message(_logSubject, TransactionLogMessages.RECOVERED(entry.getValue(), entry.getKey()));
-
- CurrentActor.get().message(_logSubject, TransactionLogMessages.RECOVERY_COMPLETE(entry.getKey(), true));
- }
-
- CurrentActor.get().message(_logSubject, TransactionLogMessages.RECOVERY_COMPLETE(null, false));
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHostImpl.java b/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHostImpl.java
deleted file mode 100644
index 33c713c62a..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHostImpl.java
+++ /dev/null
@@ -1,876 +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.virtualhost;
-
-import java.util.Collections;
-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 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;
-import org.apache.qpid.framing.FieldTable;
-import org.apache.qpid.server.AMQBrokerManagerMBean;
-import org.apache.qpid.server.binding.BindingFactory;
-import org.apache.qpid.server.configuration.BrokerConfig;
-import org.apache.qpid.server.configuration.ConfigStore;
-import org.apache.qpid.server.configuration.ConfiguredObject;
-import org.apache.qpid.server.configuration.ExchangeConfiguration;
-import org.apache.qpid.server.configuration.QueueConfiguration;
-import org.apache.qpid.server.configuration.VirtualHostConfigType;
-import org.apache.qpid.server.configuration.VirtualHostConfiguration;
-import org.apache.qpid.server.connection.ConnectionRegistry;
-import org.apache.qpid.server.connection.IConnectionRegistry;
-import org.apache.qpid.server.exchange.DefaultExchangeFactory;
-import org.apache.qpid.server.exchange.DefaultExchangeRegistry;
-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.federation.BrokerLink;
-import org.apache.qpid.server.logging.LogSubject;
-import org.apache.qpid.server.logging.actors.CurrentActor;
-import org.apache.qpid.server.logging.messages.VirtualHostMessages;
-import org.apache.qpid.server.logging.subjects.MessageStoreLogSubject;
-import org.apache.qpid.server.management.AMQManagedObject;
-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.queue.AMQQueue;
-import org.apache.qpid.server.queue.AMQQueueFactory;
-import org.apache.qpid.server.queue.DefaultQueueRegistry;
-import org.apache.qpid.server.queue.QueueRegistry;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-import org.apache.qpid.server.registry.IApplicationRegistry;
-import org.apache.qpid.server.security.SecurityManager;
-import org.apache.qpid.server.security.auth.manager.AuthenticationManager;
-import org.apache.qpid.server.security.auth.manager.PrincipalDatabaseAuthenticationManager;
-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.store.TransactionLog;
-import org.apache.qpid.server.virtualhost.plugins.VirtualHostPlugin;
-import org.apache.qpid.server.virtualhost.plugins.VirtualHostPluginFactory;
-
-public class VirtualHostImpl implements VirtualHost
-{
- private static final Logger _logger = Logger.getLogger(VirtualHostImpl.class);
-
- private final String _name;
-
- private ConnectionRegistry _connectionRegistry;
-
- private QueueRegistry _queueRegistry;
-
- private ExchangeRegistry _exchangeRegistry;
-
- private ExchangeFactory _exchangeFactory;
-
- private MessageStore _messageStore;
-
- protected VirtualHostMBean _virtualHostMBean;
-
- private AMQBrokerManagerMBean _brokerMBean;
-
- private final AuthenticationManager _authenticationManager;
-
- private SecurityManager _securityManager;
-
- private final ScheduledThreadPoolExecutor _houseKeepingTasks;
- private final IApplicationRegistry _appRegistry;
- private VirtualHostConfiguration _configuration;
- private DurableConfigurationStore _durableConfigurationStore;
- private BindingFactory _bindingFactory;
- private BrokerConfig _broker;
- private UUID _id;
-
- private boolean _statisticsEnabled = false;
- private StatisticsCounter _messagesDelivered, _dataDelivered, _messagesReceived, _dataReceived;
-
- private final long _createTime = System.currentTimeMillis();
- private final ConcurrentHashMap<BrokerLink,BrokerLink> _links = new ConcurrentHashMap<BrokerLink, BrokerLink>();
- private static final int HOUSEKEEPING_SHUTDOWN_TIMEOUT = 5;
-
- public IConnectionRegistry getConnectionRegistry()
- {
- return _connectionRegistry;
- }
-
- public VirtualHostConfiguration getConfiguration()
- {
- return _configuration;
- }
-
- public UUID getId()
- {
- return _id;
- }
-
- public VirtualHostConfigType getConfigType()
- {
- return VirtualHostConfigType.getInstance();
- }
-
- public ConfiguredObject getParent()
- {
- return getBroker();
- }
-
- public boolean isDurable()
- {
- return false;
- }
-
- /**
- * Virtual host JMX MBean class.
- *
- * This has some of the methods implemented from management intrerface for exchanges. Any
- * implementaion of an Exchange MBean should extend this class.
- */
- public class VirtualHostMBean extends AMQManagedObject implements ManagedVirtualHost
- {
- public VirtualHostMBean() throws NotCompliantMBeanException
- {
- super(ManagedVirtualHost.class, ManagedVirtualHost.TYPE);
- }
-
- public String getObjectInstanceName()
- {
- return ObjectName.quote(_name);
- }
-
- public String getName()
- {
- return _name;
- }
-
- public VirtualHostImpl getVirtualHost()
- {
- return VirtualHostImpl.this;
- }
- }
-
- public VirtualHostImpl(IApplicationRegistry appRegistry, VirtualHostConfiguration hostConfig) throws Exception
- {
- this(appRegistry, hostConfig, null);
- }
-
-
- public VirtualHostImpl(VirtualHostConfiguration hostConfig, MessageStore store) throws Exception
- {
- this(ApplicationRegistry.getInstance(),hostConfig,store);
- }
-
- private VirtualHostImpl(IApplicationRegistry appRegistry, VirtualHostConfiguration hostConfig, MessageStore store) throws Exception
- {
- if (hostConfig == null)
- {
- throw new IllegalAccessException("HostConfig and MessageStore cannot be null");
- }
-
- _appRegistry = appRegistry;
- _broker = _appRegistry.getBroker();
- _configuration = hostConfig;
- _name = _configuration.getName();
-
- _id = _appRegistry.getConfigStore().createId();
-
- CurrentActor.get().message(VirtualHostMessages.CREATED(_name));
-
- if (_name == null || _name.length() == 0)
- {
- throw new IllegalArgumentException("Illegal name (" + _name + ") for virtualhost.");
- }
-
- _securityManager = new SecurityManager(_appRegistry.getSecurityManager());
- _securityManager.configureHostPlugins(_configuration);
-
- _virtualHostMBean = new VirtualHostMBean();
-
- _connectionRegistry = new ConnectionRegistry();
-
- _houseKeepingTasks = new ScheduledThreadPoolExecutor(_configuration.getHouseKeepingThreadCount());
-
- _queueRegistry = new DefaultQueueRegistry(this);
-
- _exchangeFactory = new DefaultExchangeFactory(this);
- _exchangeFactory.initialise(_configuration);
-
- _exchangeRegistry = new DefaultExchangeRegistry(this);
-
- StartupRoutingTable configFileRT = new StartupRoutingTable();
-
- _durableConfigurationStore = configFileRT;
-
- // This needs to be after the RT has been defined as it creates the default durable exchanges.
- _exchangeRegistry.initialise();
-
- _bindingFactory = new BindingFactory(this);
-
- initialiseModel(_configuration);
-
- if (store != null)
- {
- _messageStore = store;
- _durableConfigurationStore = store;
- }
- else
- {
- initialiseMessageStore(hostConfig);
- }
-
- _authenticationManager = ApplicationRegistry.getInstance().getAuthenticationManager();
-
- _brokerMBean = new AMQBrokerManagerMBean(_virtualHostMBean);
- _brokerMBean.register();
- initialiseHouseKeeping(hostConfig.getHousekeepingExpiredMessageCheckPeriod());
-
- initialiseStatistics();
- }
-
- private void initialiseHouseKeeping(long period)
- {
- /* add a timer task to iterate over queues, cleaning expired messages from queues with no consumers */
- if (period != 0L)
- {
- class ExpiredMessagesTask extends HouseKeepingTask
- {
- public ExpiredMessagesTask(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 ExpiredMessagesTask(this));
-
- Map<String, VirtualHostPluginFactory> plugins =
- ApplicationRegistry.getInstance().getPluginManager().getVirtualHostPlugins();
-
- if (plugins != null)
- {
- for (Map.Entry<String, VirtualHostPluginFactory> entry : plugins.entrySet())
- {
- String pluginName = entry.getKey();
- VirtualHostPluginFactory factory = entry.getValue();
- try
- {
- VirtualHostPlugin plugin = factory.newInstance(this);
-
- // If we had configuration for the plugin the schedule it.
- if (plugin != null)
- {
- _houseKeepingTasks.scheduleAtFixedRate(plugin, plugin.getDelay() / 2,
- plugin.getDelay(), plugin.getTimeUnit());
-
- _logger.info("Loaded VirtualHostPlugin:" + plugin);
- }
- }
- catch (RuntimeException e)
- {
- _logger.error("Unable to load VirtualHostPlugin:" + pluginName + " due to:" + e.getMessage(), e);
- }
- }
- }
- }
- }
-
- /**
- * Allow other broker components to register a HouseKeepingTask
- *
- * @param period How often this task should run, in ms.
- * @param task The task to run.
- */
- public void scheduleHouseKeepingTask(long period, HouseKeepingTask task)
- {
- _houseKeepingTasks.scheduleAtFixedRate(task, period / 2, period,
- TimeUnit.MILLISECONDS);
- }
-
- public long getHouseKeepingTaskCount()
- {
- return _houseKeepingTasks.getTaskCount();
- }
-
- public long getHouseKeepingCompletedTaskCount()
- {
- return _houseKeepingTasks.getCompletedTaskCount();
- }
-
- public int getHouseKeepingPoolSize()
- {
- return _houseKeepingTasks.getCorePoolSize();
- }
-
- public void setHouseKeepingPoolSize(int newSize)
- {
- _houseKeepingTasks.setCorePoolSize(newSize);
- }
-
-
- public int getHouseKeepingActiveCount()
- {
- return _houseKeepingTasks.getActiveCount();
- }
-
-
- private void initialiseMessageStore(VirtualHostConfiguration hostConfig) throws Exception
- {
- String messageStoreClass = hostConfig.getMessageStoreClass();
-
- Class clazz = Class.forName(messageStoreClass);
- Object o = clazz.newInstance();
-
- if (!(o instanceof MessageStore))
- {
- throw new ClassCastException("Message store class must implement " + MessageStore.class + ". Class " + clazz +
- " does not.");
- }
- MessageStore messageStore = (MessageStore) o;
- VirtualHostConfigRecoveryHandler recoveryHandler = new VirtualHostConfigRecoveryHandler(this);
-
- MessageStoreLogSubject storeLogSubject = new MessageStoreLogSubject(this, messageStore);
-
- messageStore.configureConfigStore(this.getName(),
- recoveryHandler,
- hostConfig.getStoreConfiguration(),
- storeLogSubject);
-
- messageStore.configureMessageStore(this.getName(),
- recoveryHandler,
- hostConfig.getStoreConfiguration(),
- storeLogSubject);
- messageStore.configureTransactionLog(this.getName(),
- recoveryHandler,
- hostConfig.getStoreConfiguration(),
- storeLogSubject);
-
- _messageStore = messageStore;
- _durableConfigurationStore = messageStore;
- }
-
- private void initialiseModel(VirtualHostConfiguration config) throws ConfigurationException, AMQException
- {
- _logger.debug("Loading configuration for virtualhost: " + config.getName());
-
- List exchangeNames = config.getExchanges();
-
- for (Object exchangeNameObj : exchangeNames)
- {
- String exchangeName = String.valueOf(exchangeNameObj);
- configureExchange(config.getExchangeConfiguration(exchangeName));
- }
-
- String[] queueNames = config.getQueueNames();
-
- for (Object queueNameObj : queueNames)
- {
- String queueName = String.valueOf(queueNameObj);
- configureQueue(config.getQueueConfiguration(queueName));
- }
- }
-
- private void configureExchange(ExchangeConfiguration exchangeConfiguration) throws AMQException
- {
- AMQShortString exchangeName = new AMQShortString(exchangeConfiguration.getName());
-
- Exchange exchange;
- exchange = _exchangeRegistry.getExchange(exchangeName);
- if (exchange == null)
- {
-
- AMQShortString type = new AMQShortString(exchangeConfiguration.getType());
- boolean durable = exchangeConfiguration.getDurable();
- boolean autodelete = exchangeConfiguration.getAutoDelete();
-
- Exchange newExchange = _exchangeFactory.createExchange(exchangeName, type, durable, autodelete, 0);
- _exchangeRegistry.registerExchange(newExchange);
-
- if (newExchange.isDurable())
- {
- _durableConfigurationStore.createExchange(newExchange);
- }
- }
- }
-
- private void configureQueue(QueueConfiguration queueConfiguration) throws AMQException, ConfigurationException
- {
- AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(queueConfiguration, this);
-
- if (queue.isDurable())
- {
- getDurableConfigurationStore().createQueue(queue);
- }
-
- String exchangeName = queueConfiguration.getExchange();
-
- Exchange exchange = _exchangeRegistry.getExchange(exchangeName == null ? null : new AMQShortString(exchangeName));
-
- if (exchange == null)
- {
- exchange = _exchangeRegistry.getDefaultExchange();
- }
-
- if (exchange == null)
- {
- throw new ConfigurationException("Attempt to bind queue to unknown exchange:" + exchangeName);
- }
-
- List routingKeys = queueConfiguration.getRoutingKeys();
- if (routingKeys == null || routingKeys.isEmpty())
- {
- routingKeys = Collections.singletonList(queue.getNameShortString());
- }
-
- for (Object routingKeyNameObj : routingKeys)
- {
- AMQShortString routingKey = new AMQShortString(String.valueOf(routingKeyNameObj));
- if (_logger.isInfoEnabled())
- {
- _logger.info("Binding queue:" + queue + " with routing key '" + routingKey + "' to exchange:" + this);
- }
- _bindingFactory.addBinding(routingKey.toString(), queue, exchange, null);
- }
-
- if (exchange != _exchangeRegistry.getDefaultExchange())
- {
- _bindingFactory.addBinding(queue.getNameShortString().toString(), queue, exchange, null);
- }
- }
-
- public String getName()
- {
- return _name;
- }
-
- public BrokerConfig getBroker()
- {
- return _broker;
- }
-
- public String getFederationTag()
- {
- return _broker.getFederationTag();
- }
-
- public void setBroker(final BrokerConfig broker)
- {
- _broker = broker;
- }
-
- public long getCreateTime()
- {
- return _createTime;
- }
-
- public QueueRegistry getQueueRegistry()
- {
- return _queueRegistry;
- }
-
- public ExchangeRegistry getExchangeRegistry()
- {
- return _exchangeRegistry;
- }
-
- public ExchangeFactory getExchangeFactory()
- {
- return _exchangeFactory;
- }
-
- public MessageStore getMessageStore()
- {
- return _messageStore;
- }
-
- public TransactionLog getTransactionLog()
- {
- return _messageStore;
- }
-
- public DurableConfigurationStore getDurableConfigurationStore()
- {
- return _durableConfigurationStore;
- }
-
- public AuthenticationManager getAuthenticationManager()
- {
- return _authenticationManager;
- }
-
- public SecurityManager getSecurityManager()
- {
- return _securityManager;
- }
-
- public void close()
- {
- //Stop Connections
- _connectionRegistry.close();
-
- //Stop the Queues processing
- if (_queueRegistry != null)
- {
- for (AMQQueue queue : _queueRegistry.getQueues())
- {
- queue.stop();
- }
- }
-
- //Stop Housekeeping
- if (_houseKeepingTasks != null)
- {
- _houseKeepingTasks.shutdown();
-
- try
- {
- if (!_houseKeepingTasks.awaitTermination(HOUSEKEEPING_SHUTDOWN_TIMEOUT, TimeUnit.SECONDS))
- {
- _houseKeepingTasks.shutdownNow();
- }
- }
- catch (InterruptedException e)
- {
- _logger.warn("Interrupted during Housekeeping shutdown:" + e.getMessage());
- // Swallowing InterruptedException ok as we are shutting down.
- }
- }
-
- //Close MessageStore
- if (_messageStore != null)
- {
- //Remove MessageStore Interface should not throw Exception
- try
- {
- _messageStore.close();
- }
- catch (Exception e)
- {
- e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
- }
- }
-
- CurrentActor.get().message(VirtualHostMessages.CLOSED());
- }
-
- public ManagedObject getBrokerMBean()
- {
- return _brokerMBean;
- }
-
- public ManagedObject getManagedObject()
- {
- return _virtualHostMBean;
- }
-
- public UUID getBrokerId()
- {
- return _appRegistry.getBrokerId();
- }
-
- public IApplicationRegistry getApplicationRegistry()
- {
- return _appRegistry;
- }
-
- public BindingFactory getBindingFactory()
- {
- return _bindingFactory;
- }
-
- public void registerMessageDelivered(long messageSize)
- {
- if (isStatisticsEnabled())
- {
- _messagesDelivered.registerEvent(1L);
- _dataDelivered.registerEvent(messageSize);
- }
- _appRegistry.registerMessageDelivered(messageSize);
- }
-
- public void registerMessageReceived(long messageSize, long timestamp)
- {
- if (isStatisticsEnabled())
- {
- _messagesReceived.registerEvent(1L, timestamp);
- _dataReceived.registerEvent(messageSize, timestamp);
- }
- _appRegistry.registerMessageReceived(messageSize, timestamp);
- }
-
- public StatisticsCounter getMessageReceiptStatistics()
- {
- return _messagesReceived;
- }
-
- public StatisticsCounter getDataReceiptStatistics()
- {
- return _dataReceived;
- }
-
- public StatisticsCounter getMessageDeliveryStatistics()
- {
- return _messagesDelivered;
- }
-
- public StatisticsCounter getDataDeliveryStatistics()
- {
- return _dataDelivered;
- }
-
- public void resetStatistics()
- {
- _messagesDelivered.reset();
- _dataDelivered.reset();
- _messagesReceived.reset();
- _dataReceived.reset();
-
- for (AMQConnectionModel connection : _connectionRegistry.getConnections())
- {
- connection.resetStatistics();
- }
- }
-
- public void initialiseStatistics()
- {
- setStatisticsEnabled(!StatisticsCounter.DISABLE_STATISTICS &&
- _appRegistry.getConfiguration().isStatisticsGenerationVirtualhostsEnabled());
-
- _messagesDelivered = new StatisticsCounter("messages-delivered-" + getName());
- _dataDelivered = new StatisticsCounter("bytes-delivered-" + getName());
- _messagesReceived = new StatisticsCounter("messages-received-" + getName());
- _dataReceived = new StatisticsCounter("bytes-received-" + getName());
- }
-
- public boolean isStatisticsEnabled()
- {
- return _statisticsEnabled;
- }
-
- public void setStatisticsEnabled(boolean enabled)
- {
- _statisticsEnabled = enabled;
- }
-
- public void createBrokerConnection(final String transport,
- final String host,
- final int port,
- final String vhost,
- final boolean durable,
- final String authMechanism,
- final String username,
- final String password)
- {
- BrokerLink blink = new BrokerLink(this, transport, host, port, vhost, durable, authMechanism, username, password);
- if(_links.putIfAbsent(blink,blink) != null)
- {
- getConfigStore().addConfiguredObject(blink);
- }
- }
-
- public void removeBrokerConnection(final String transport,
- final String host,
- final int port,
- final String vhost)
- {
- removeBrokerConnection(new BrokerLink(this, transport, host, port, vhost, false, null,null,null));
-
- }
-
- public void removeBrokerConnection(BrokerLink blink)
- {
- blink = _links.get(blink);
- if(blink != null)
- {
- blink.close();
- getConfigStore().removeConfiguredObject(blink);
- }
- }
-
- public ConfigStore getConfigStore()
- {
- return getApplicationRegistry().getConfigStore();
- }
-
- /**
- * Temporary Startup RT class to record the creation of persistent queues / exchanges.
- *
- *
- * This is so we can replay the creation of queues/exchanges in to the real _RT after it has been loaded.
- * This should be removed after the _RT has been fully split from the the TL
- */
- private static class StartupRoutingTable implements DurableConfigurationStore
- {
- public List<Exchange> exchange = new LinkedList<Exchange>();
- public List<CreateQueueTuple> queue = new LinkedList<CreateQueueTuple>();
- public List<CreateBindingTuple> bindings = new LinkedList<CreateBindingTuple>();
-
- public void configure(VirtualHost virtualHost, String base, VirtualHostConfiguration config) throws Exception
- {
- }
-
- public void close() throws Exception
- {
- }
-
- public void removeMessage(Long messageId) throws AMQException
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void configureConfigStore(String name,
- ConfigurationRecoveryHandler recoveryHandler,
- Configuration config,
- LogSubject logSubject) throws Exception
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void createExchange(Exchange exchange) throws AMQStoreException
- {
- if (exchange.isDurable())
- {
- this.exchange.add(exchange);
- }
- }
-
- public void removeExchange(Exchange exchange) throws AMQStoreException
- {
- }
-
- public void bindQueue(Exchange exchange, AMQShortString routingKey, AMQQueue queue, FieldTable args) throws AMQStoreException
- {
- if (exchange.isDurable() && queue.isDurable())
- {
- bindings.add(new CreateBindingTuple(exchange, routingKey, queue, args));
- }
- }
-
- public void unbindQueue(Exchange exchange, AMQShortString routingKey, AMQQueue queue, FieldTable args) throws AMQStoreException
- {
- }
-
- public void createQueue(AMQQueue queue) throws AMQStoreException
- {
- createQueue(queue, null);
- }
-
- public void createQueue(AMQQueue queue, FieldTable arguments) throws AMQStoreException
- {
- if (queue.isDurable())
- {
- this.queue.add(new CreateQueueTuple(queue, arguments));
- }
- }
-
- public void removeQueue(AMQQueue queue) throws AMQStoreException
- {
- }
-
-
- private static class CreateQueueTuple
- {
- public AMQQueue queue;
- public FieldTable arguments;
-
- public CreateQueueTuple(AMQQueue queue, FieldTable arguments)
- {
- this.queue = queue;
- this.arguments = arguments;
- }
- }
-
- private static class CreateBindingTuple
- {
- public AMQQueue queue;
- public FieldTable arguments;
- public Exchange exchange;
- public AMQShortString routingKey;
-
- public CreateBindingTuple(Exchange exchange, AMQShortString routingKey, AMQQueue queue, FieldTable args)
- {
- this.exchange = exchange;
- this.routingKey = routingKey;
- this.queue = queue;
- arguments = args;
- }
- }
-
- public void updateQueue(AMQQueue queue) throws AMQStoreException
- {
- }
- }
-
- @Override
- public String toString()
- {
- return _name;
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHostRegistry.java b/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHostRegistry.java
deleted file mode 100644
index 32d0c4c4d1..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHostRegistry.java
+++ /dev/null
@@ -1,109 +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.virtualhost;
-
-import org.apache.qpid.common.Closeable;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-import org.apache.qpid.server.configuration.ConfigStore;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-
-public class VirtualHostRegistry implements Closeable
-{
- private final Map<String, VirtualHost> _registry = new ConcurrentHashMap<String, VirtualHost>();
-
-
- private String _defaultVirtualHostName;
- private ApplicationRegistry _applicationRegistry;
-
- public VirtualHostRegistry(ApplicationRegistry applicationRegistry)
- {
- _applicationRegistry = applicationRegistry;
- }
-
- public synchronized void registerVirtualHost(VirtualHost host) throws Exception
- {
- if(_registry.containsKey(host.getName()))
- {
- throw new Exception("Virtual Host with name " + host.getName() + " already registered.");
- }
- _registry.put(host.getName(),host);
- }
-
- public synchronized void unregisterVirtualHost(VirtualHost host)
- {
- _registry.remove(host.getName());
- }
-
- public VirtualHost getVirtualHost(String name)
- {
- if(name == null || name.trim().length() == 0 || "/".equals(name.trim()))
- {
- name = getDefaultVirtualHostName();
- }
-
- return _registry.get(name);
- }
-
- public VirtualHost getDefaultVirtualHost()
- {
- return getVirtualHost(getDefaultVirtualHostName());
- }
-
- private String getDefaultVirtualHostName()
- {
- return _defaultVirtualHostName;
- }
-
- public void setDefaultVirtualHostName(String defaultVirtualHostName)
- {
- _defaultVirtualHostName = defaultVirtualHostName;
- }
-
-
- public Collection<VirtualHost> getVirtualHosts()
- {
- return new ArrayList<VirtualHost>(_registry.values());
- }
-
- public ApplicationRegistry getApplicationRegistry()
- {
- return _applicationRegistry;
- }
-
- public ConfigStore getConfigStore()
- {
- return _applicationRegistry.getConfigStore();
- }
-
- public void close()
- {
- for (VirtualHost virtualHost : getVirtualHosts())
- {
- virtualHost.close();
- }
-
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/ConfiguredQueueBindingListener.java b/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/ConfiguredQueueBindingListener.java
deleted file mode 100644
index 12206013eb..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/ConfiguredQueueBindingListener.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.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;
-
-/**
- * This is a listener that caches queues that are configured for slow consumer disconnection.
- *
- * There should be one listener per virtual host, which can be added to all exchanges on
- * that host.
- *
- * TODO In future, it will be possible to configure the policy at runtime, so only the queue
- * itself is cached, and the configuration looked up by the housekeeping thread. This means
- * that there may be occasions where the copy of the cache contents retrieved by the thread
- * does not contain queues that are configured, or that configured queues are not present.
- *
- * @see BindingListener
- */
-public class ConfiguredQueueBindingListener implements BindingListener
-{
- private static final Logger _log = Logger.getLogger(ConfiguredQueueBindingListener.class);
-
- private String _vhostName;
- private Set<AMQQueue> _cache = Collections.synchronizedSet(new HashSet<AMQQueue>());
-
- public ConfiguredQueueBindingListener(String vhostName)
- {
- _vhostName = vhostName;
- }
-
- /**
- * @see BindingListener#bindingAdded(Exchange, Binding)
- */
- public void bindingAdded(Exchange exchange, Binding binding)
- {
- processBinding(binding);
- }
-
- /**
- * @see BindingListener#bindingRemoved(Exchange, Binding)
- */
- public void bindingRemoved(Exchange exchange, Binding binding)
- {
- processBinding(binding);
- }
-
- private void processBinding(Binding binding)
- {
- AMQQueue queue = binding.getQueue();
-
- SlowConsumerDetectionQueueConfiguration config =
- queue.getConfiguration().getConfiguration(SlowConsumerDetectionQueueConfiguration.class.getName());
- if (config != null)
- {
- _cache.add(queue);
- }
- else
- {
- _cache.remove(queue);
- }
- }
-
- /**
- * Lookup and return the cache of configured {@link AMQQueue}s.
- *
- * Note that when accessing the cached queues, the {@link Iterator} is not thread safe
- * (see the {@link Collections#synchronizedSet(Set)} documentation) so a copy of the
- * cache is returned.
- *
- * @return a copy of the cached {@link java.util.Set} of queues
- */
- public Set<AMQQueue> getQueueCache()
- {
- return new HashSet<AMQQueue>(_cache);
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/SlowConsumerDetection.java b/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/SlowConsumerDetection.java
deleted file mode 100644
index 5c4fe0aab8..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/SlowConsumerDetection.java
+++ /dev/null
@@ -1,158 +0,0 @@
-/*
- *
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.virtualhost.plugins;
-
-import java.util.Set;
-import java.util.concurrent.TimeUnit;
-
-import org.apache.qpid.framing.AMQShortString;
-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.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;
-
-public class SlowConsumerDetection extends VirtualHostHouseKeepingPlugin
-{
- private SlowConsumerDetectionConfiguration _config;
- private ConfiguredQueueBindingListener _listener;
-
- public static class SlowConsumerFactory implements VirtualHostPluginFactory
- {
- public SlowConsumerDetection newInstance(VirtualHost vhost)
- {
- SlowConsumerDetectionConfiguration config = vhost.getConfiguration().getConfiguration(SlowConsumerDetectionConfiguration.class.getName());
-
- if (config == null)
- {
- return null;
- }
-
- SlowConsumerDetection plugin = new SlowConsumerDetection(vhost);
- plugin.configure(config);
- return plugin;
- }
- }
-
- /**
- * Configures the slow consumer disconnect plugin by adding a listener to each exchange on this
- * cirtual host to record all the configured queues in a cache for processing by the housekeeping
- * thread.
- *
- * @see Plugin#configure(ConfigurationPlugin)
- */
- public void configure(ConfigurationPlugin config)
- {
- _config = (SlowConsumerDetectionConfiguration) config;
- _listener = new ConfiguredQueueBindingListener(getVirtualHost().getName());
- for (AMQShortString exchangeName : getVirtualHost().getExchangeRegistry().getExchangeNames())
- {
- getVirtualHost().getExchangeRegistry().getExchange(exchangeName).addBindingListener(_listener);
- }
- }
-
- public SlowConsumerDetection(VirtualHost vhost)
- {
- super(vhost);
- }
-
- public void execute()
- {
- CurrentActor.get().message(SlowConsumerDetectionMessages.RUNNING());
-
- Set<AMQQueue> cache = _listener.getQueueCache();
- for (AMQQueue q : cache)
- {
- CurrentActor.get().message(SlowConsumerDetectionMessages.CHECKING_QUEUE(q.getName()));
-
- try
- {
- SlowConsumerDetectionQueueConfiguration config =
- q.getConfiguration().getConfiguration(SlowConsumerDetectionQueueConfiguration.class.getName());
- if (checkQueueStatus(q, config))
- {
- config.getPolicy().performPolicy(q);
- }
- }
- 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);
- }
- }
-
- CurrentActor.get().message(SlowConsumerDetectionMessages.COMPLETE());
- }
-
- public long getDelay()
- {
- return _config.getDelay();
- }
-
- public TimeUnit getTimeUnit()
- {
- return _config.getTimeUnit();
- }
-
- /**
- * Check the depth,messageSize,messageAge,messageCount values for this q
- *
- * @param q the queue to check
- * @param config the queue configuration to compare against the queue state
- *
- * @return true if the queue has reached a threshold.
- */
- private boolean checkQueueStatus(AMQQueue q, SlowConsumerDetectionQueueConfiguration config)
- {
- if (config != null)
- {
- _logger.info("Retrieved Queue(" + q.getName() + ") Config:" + config);
-
- int count = q.getMessageCount();
-
- // First Check message counts
- if ((config.getMessageCount() != 0 && count >= config.getMessageCount()) ||
- // The check queue depth
- (config.getDepth() != 0 && q.getQueueDepth() >= config.getDepth()) ||
- // finally if we have messages on the queue check Arrival time.
- // We must check count as OldestArrival time is Long.MAX_LONG when
- // there are no messages.
- (config.getMessageAge() != 0 &&
- ((count > 0) && q.getOldestMessageArrivalTime() >= config.getMessageAge())))
- {
-
- if (_logger.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());
- }
-
- return true;
- }
- }
- return false;
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/VirtualHostHouseKeepingPlugin.java b/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/VirtualHostHouseKeepingPlugin.java
deleted file mode 100644
index 3798f47f0b..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/VirtualHostHouseKeepingPlugin.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.virtualhost.plugins;
-
-import org.apache.log4j.Logger;
-import org.apache.qpid.server.virtualhost.HouseKeepingTask;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-
-import java.util.concurrent.TimeUnit;
-
-public abstract class VirtualHostHouseKeepingPlugin extends HouseKeepingTask implements VirtualHostPlugin
-{
- protected final Logger _logger = Logger.getLogger(getClass());
-
- public VirtualHostHouseKeepingPlugin(VirtualHost vhost)
- {
- super(vhost);
- }
-
-
- /**
- * Long value representing the delay between repeats
- *
- * @return
- */
- public abstract long getDelay();
-
- /**
- * Option to specify what the delay value represents
- *
- * @return
- *
- * @see java.util.concurrent.TimeUnit for valid value.
- */
- public abstract TimeUnit getTimeUnit();
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/VirtualHostPlugin.java b/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/VirtualHostPlugin.java
deleted file mode 100644
index 1886c2d01d..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/VirtualHostPlugin.java
+++ /dev/null
@@ -1,43 +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.virtualhost.plugins;
-
-import java.util.concurrent.TimeUnit;
-
-import org.apache.qpid.server.plugins.Plugin;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-
-public interface VirtualHostPlugin extends Runnable, Plugin
-{
- /**
- * Long value representing the delay between repeats
- *
- * @return
- */
- public long getDelay();
-
- /**
- * Option to specify what the delay value represents
- * @see java.util.concurrent.TimeUnit for valid value.
- * @return
- */
- public TimeUnit getTimeUnit();
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/VirtualHostPluginFactory.java b/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/VirtualHostPluginFactory.java
deleted file mode 100644
index c8bea18444..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/VirtualHostPluginFactory.java
+++ /dev/null
@@ -1,28 +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.virtualhost.plugins;
-
-import org.apache.qpid.server.virtualhost.VirtualHost;
-
-public interface VirtualHostPluginFactory
-{
- public VirtualHostHouseKeepingPlugin newInstance(VirtualHost vhost);
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/logging/SlowConsumerDetection_logmessages.properties b/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/logging/SlowConsumerDetection_logmessages.properties
deleted file mode 100644
index 03c56910c2..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/logging/SlowConsumerDetection_logmessages.properties
+++ /dev/null
@@ -1,23 +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.
-#
-# Default File used for all non-defined locales.
-
-RUNNING = SCD-1001 : Running
-COMPLETE = SCD-1002 : Complete
-CHECKING_QUEUE = SCD-1003 : Checking Status of Queue {0} \ No newline at end of file
diff --git a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/logging/TopicDeletePolicy_logmessages.properties b/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/logging/TopicDeletePolicy_logmessages.properties
deleted file mode 100644
index ed4fb1d45a..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/logging/TopicDeletePolicy_logmessages.properties
+++ /dev/null
@@ -1,22 +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.
-#
-# Default File used for all non-defined locales.
-
-DELETING_QUEUE = TDP-1001 : Deleting Queue
-DISCONNECTING = TDP-1002 : Disconnecting Session \ No newline at end of file
diff --git a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/policies/TopicDeletePolicy.java b/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/policies/TopicDeletePolicy.java
deleted file mode 100644
index 6028f63fdb..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/policies/TopicDeletePolicy.java
+++ /dev/null
@@ -1,141 +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.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;
-import org.apache.qpid.server.protocol.AMQSessionModel;
-import org.apache.qpid.server.queue.AMQQueue;
-import org.apache.qpid.server.virtualhost.plugins.logging.TopicDeletePolicyMessages;
-import org.apache.qpid.slowconsumerdetection.policies.SlowConsumerPolicyPlugin;
-import org.apache.qpid.slowconsumerdetection.policies.SlowConsumerPolicyPluginFactory;
-
-public class TopicDeletePolicy implements SlowConsumerPolicyPlugin
-{
- Logger _logger = Logger.getLogger(TopicDeletePolicy.class);
- private TopicDeletePolicyConfiguration _configuration;
-
- public static class TopicDeletePolicyFactory implements SlowConsumerPolicyPluginFactory
- {
- public TopicDeletePolicy newInstance(ConfigurationPlugin configuration) throws ConfigurationException
- {
- TopicDeletePolicyConfiguration config =
- configuration.getConfiguration(TopicDeletePolicyConfiguration.class.getName());
-
- TopicDeletePolicy policy = new TopicDeletePolicy();
- policy.configure(config);
- return policy;
- }
-
- public String getPluginName()
- {
- return "topicdelete";
- }
-
- public Class<TopicDeletePolicy> getPluginClass()
- {
- return TopicDeletePolicy.class;
- }
- }
-
- public void performPolicy(AMQQueue q)
- {
- if (q == null)
- {
- return;
- }
-
- AMQSessionModel owner = q.getExclusiveOwningSession();
-
- // Only process exclusive queues
- if (owner == null)
- {
- return;
- }
-
- //Only process Topics
- if (!validateQueueIsATopic(q))
- {
- return;
- }
-
- try
- {
- CurrentActor.get().message(owner.getLogSubject(),TopicDeletePolicyMessages.DISCONNECTING());
- // Close the consumer . this will cause autoDelete Queues to be purged
- owner.getConnectionModel().
- closeSession(owner, AMQConstant.RESOURCE_ERROR,
- "Consuming to slow.");
-
- // Actively delete non autoDelete queues if deletePersistent is set
- if (!q.isAutoDelete() && (_configuration != null && _configuration.deletePersistent()))
- {
- CurrentActor.get().message(q.getLogSubject(), TopicDeletePolicyMessages.DELETING_QUEUE());
- q.delete();
- }
-
- }
- catch (AMQException e)
- {
- _logger.warn("Unable to close consumer:" + owner + ", on queue:" + q.getName());
- }
-
- }
-
- /**
- * Check the queue bindings to validate the queue is bound to the
- * topic exchange.
- *
- * @param q the Queue
- *
- * @return true iff Q is bound to a TopicExchange
- */
- private boolean validateQueueIsATopic(AMQQueue q)
- {
- for (Binding binding : q.getBindings())
- {
- if (binding.getExchange() instanceof TopicExchange)
- {
- return true;
- }
- }
-
- return false;
- }
-
- public void configure(ConfigurationPlugin config)
- {
- _configuration = (TopicDeletePolicyConfiguration) config;
- }
-
- @Override
- public String toString()
- {
- return "TopicDelete" + (_configuration == null ? "" : "[" + _configuration + "]");
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/policies/TopicDeletePolicyConfiguration.java b/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/policies/TopicDeletePolicyConfiguration.java
deleted file mode 100644
index 7dfd22c733..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/policies/TopicDeletePolicyConfiguration.java
+++ /dev/null
@@ -1,81 +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.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;
-
-public class TopicDeletePolicyConfiguration extends ConfigurationPlugin
-{
-
- public static class TopicDeletePolicyConfigurationFactory
- implements ConfigurationPluginFactory
- {
- public ConfigurationPlugin newInstance(String path,
- Configuration config)
- throws ConfigurationException
- {
- TopicDeletePolicyConfiguration slowConsumerConfig =
- new TopicDeletePolicyConfiguration();
- slowConsumerConfig.setConfiguration(path, config);
- return slowConsumerConfig;
- }
-
- public List<String> getParentPaths()
- {
- return Arrays.asList(
- "virtualhosts.virtualhost.queues.slow-consumer-detection.policy.topicDelete",
- "virtualhosts.virtualhost.queues.queue.slow-consumer-detection.policy.topicDelete",
- "virtualhosts.virtualhost.topics.slow-consumer-detection.policy.topicDelete",
- "virtualhosts.virtualhost.topics.topic.slow-consumer-detection.policy.topicDelete");
- }
- }
-
- public String[] getElementsProcessed()
- {
- return new String[]{"delete-persistent"};
- }
-
- @Override
- public void validateConfiguration() throws ConfigurationException
- {
- // No validation required.
- }
-
- public boolean deletePersistent()
- {
- // If we don't have configuration then we don't deletePersistent Queues
- return (hasConfiguration() && contains("delete-persistent"));
- }
-
- @Override
- public String formatToString()
- {
- return (deletePersistent()?"delete-durable":"");
- }
-
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/slowconsumerdetection/policies/SlowConsumerPolicyPlugin.java b/java/broker/src/main/java/org/apache/qpid/slowconsumerdetection/policies/SlowConsumerPolicyPlugin.java
deleted file mode 100644
index 7f600abdc9..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/slowconsumerdetection/policies/SlowConsumerPolicyPlugin.java
+++ /dev/null
@@ -1,29 +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.slowconsumerdetection.policies;
-
-import org.apache.qpid.server.plugins.Plugin;
-import org.apache.qpid.server.queue.AMQQueue;
-
-public interface SlowConsumerPolicyPlugin extends Plugin
-{
- public void performPolicy(AMQQueue Queue);
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/slowconsumerdetection/policies/SlowConsumerPolicyPluginFactory.java b/java/broker/src/main/java/org/apache/qpid/slowconsumerdetection/policies/SlowConsumerPolicyPluginFactory.java
deleted file mode 100644
index b2fe6766a6..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/slowconsumerdetection/policies/SlowConsumerPolicyPluginFactory.java
+++ /dev/null
@@ -1,27 +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.slowconsumerdetection.policies;
-
-import org.apache.qpid.server.plugins.PluginFactory;
-
-public interface SlowConsumerPolicyPluginFactory<P extends SlowConsumerPolicyPlugin> extends PluginFactory<P>
-{
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/MessageStoreTool.java b/java/broker/src/main/java/org/apache/qpid/tools/messagestore/MessageStoreTool.java
deleted file mode 100644
index dca165fa7e..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/MessageStoreTool.java
+++ /dev/null
@@ -1,652 +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.tools.messagestore;
-
-import org.apache.commons.cli.Option;
-import org.apache.commons.cli.OptionBuilder;
-import org.apache.commons.configuration.ConfigurationException;
-import org.apache.qpid.configuration.Configuration;
-import org.apache.qpid.server.exchange.Exchange;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-import org.apache.qpid.server.registry.ConfigurationFileApplicationRegistry;
-import org.apache.qpid.server.store.MemoryMessageStore;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-import org.apache.qpid.server.queue.AMQQueue;
-import org.apache.qpid.tools.messagestore.commands.Clear;
-import org.apache.qpid.tools.messagestore.commands.Command;
-import org.apache.qpid.tools.messagestore.commands.Copy;
-import org.apache.qpid.tools.messagestore.commands.Dump;
-import org.apache.qpid.tools.messagestore.commands.Help;
-import org.apache.qpid.tools.messagestore.commands.List;
-import org.apache.qpid.tools.messagestore.commands.Load;
-import org.apache.qpid.tools.messagestore.commands.Quit;
-import org.apache.qpid.tools.messagestore.commands.Select;
-import org.apache.qpid.tools.messagestore.commands.Show;
-import org.apache.qpid.tools.messagestore.commands.Move;
-import org.apache.qpid.tools.messagestore.commands.Purge;
-import org.apache.qpid.tools.utils.CommandParser;
-import org.apache.qpid.tools.utils.Console;
-import org.apache.qpid.tools.utils.SimpleCommandParser;
-import org.apache.qpid.tools.utils.SimpleConsole;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.io.BufferedReader;
-import java.io.BufferedWriter;
-import java.io.File;
-import java.io.FileReader;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.Map;
-import java.util.StringTokenizer;
-
-/**
- * MessageStoreTool.
- */
-public class MessageStoreTool
-{
- /** Text outputted at the start of each console.*/
- private static final String BOILER_PLATE = "MessageStoreTool - for examining Persistent Qpid Broker MessageStore instances";
-
- /** I/O Wrapper. */
- protected Console _console;
-
- /** Batch mode flag. */
- protected boolean _batchMode;
-
- /** Internal State object. */
- private State _state = new State();
-
- private HashMap<String, Command> _commands = new HashMap<String, Command>();
-
- /** SLF4J Logger. */
- private static Logger _devlog = LoggerFactory.getLogger(MessageStoreTool.class);
-
- /** Loaded configuration file. */
- private Configuration _config;
-
- /** Control used for main run loop. */
- private boolean _running = true;
- private boolean _initialised = false;
-
- //---------------------------------------------------------------------------------------------------/
-
- public static void main(String[] args) throws Configuration.InitException
- {
-
- MessageStoreTool tool = new MessageStoreTool(args);
-
- tool.start();
- }
-
-
- public MessageStoreTool(String[] args) throws Configuration.InitException
- {
- this(args, System.in, System.out);
- }
-
- public MessageStoreTool(String[] args, InputStream in, OutputStream out) throws Configuration.InitException
- {
- BufferedReader consoleReader = new BufferedReader(new InputStreamReader(in));
- BufferedWriter consoleWriter = new BufferedWriter(new OutputStreamWriter(out));
-
- Runtime.getRuntime().addShutdownHook(new Thread(new ShutdownHook(this)));
- _batchMode = false;
-
- _console = new SimpleConsole(consoleWriter, consoleReader);
-
- _config = new Configuration();
-
- setOptions();
- _config.processCommandline(args);
- }
-
-
- private void setOptions()
- {
- Option help = new Option("h", "help", false, "print this message");
- Option version = new Option("v", "version", false, "print the version information and exit");
- Option configFile =
- OptionBuilder.withArgName("file").hasArg()
- .withDescription("use given configuration file By "
- + "default looks for a file named "
- + Configuration.DEFAULT_CONFIG_FILE + " in " + Configuration.QPID_HOME)
- .withLongOpt("config")
- .create("c");
-
- _config.setOption(help);
- _config.setOption(version);
- _config.setOption(configFile);
- }
-
- public State getState()
- {
- return _state;
- }
-
- public Map<String, Command> getCommands()
- {
- return _commands;
- }
-
- public void setConfigurationFile(String configfile) throws Configuration.InitException
- {
- _config.loadConfig(new File(configfile));
- setup();
- }
-
- public Console getConsole()
- {
- return _console;
- }
-
- public void setConsole(Console console)
- {
- _console = console;
- }
-
- /**
- * Simple ShutdownHook to cleanly shutdown the databases
- */
- static class ShutdownHook implements Runnable
- {
- MessageStoreTool _tool;
-
- ShutdownHook(MessageStoreTool messageStoreTool)
- {
- _tool = messageStoreTool;
- }
-
- public void run()
- {
- _tool.quit();
- }
- }
-
- public void quit()
- {
- _running = false;
-
- if (_initialised)
- {
- ApplicationRegistry.remove(1);
- }
-
- _console.println("...exiting");
-
- _console.close();
- }
-
- public void setBatchMode(boolean batchmode)
- {
- _batchMode = batchmode;
- }
-
- /**
- * Main loop
- */
- protected void start()
- {
- setup();
-
- if (!_initialised)
- {
- System.exit(1);
- }
-
- _console.println("");
-
- _console.println(BOILER_PLATE);
-
- runCLI();
- }
-
- private void setup()
- {
- loadDefaultVirtualHosts();
-
- loadCommands();
-
- _state.clearAll();
- }
-
- private void loadCommands()
- {
- _commands.clear();
- //todo Dynamically load the classes that exis in com.redhat.etp.qpid.commands
- _commands.put("close", new Clear(this));
- _commands.put("copy", new Copy(this));
- _commands.put("dump", new Dump(this));
- _commands.put("help", new Help(this));
- _commands.put("list", new List(this));
- _commands.put("load", new Load(this));
- _commands.put("move", new Move(this));
- _commands.put("purge", new Purge(this));
- _commands.put("quit", new Quit(this));
- _commands.put("select", new Select(this));
- _commands.put("show", new Show(this));
- }
-
- private void loadDefaultVirtualHosts()
- {
- final File configFile = _config.getConfigFile();
-
- loadVirtualHosts(configFile);
- }
-
- private void loadVirtualHosts(File configFile)
- {
-
- if (!configFile.exists())
- {
- _devlog.error("Config file not found:" + configFile.getAbsolutePath());
- return;
- }
- else
- {
- _devlog.debug("using config file :" + configFile.getAbsolutePath());
- }
-
- try
- {
- ConfigurationFileApplicationRegistry registry = new ConfigurationFileApplicationRegistry(configFile);
-
- ApplicationRegistry.remove(1);
-
- ApplicationRegistry.initialise(registry);
-
- checkMessageStores();
- _initialised = true;
- }
- catch (ConfigurationException e)
- {
- _console.println("Unable to load configuration due to configuration error: " + e.getMessage());
- e.printStackTrace();
- }
- catch (Exception e)
- {
- _console.println("Unable to load configuration due to: " + e.getMessage());
- e.printStackTrace();
- }
-
-
- }
-
- private void checkMessageStores()
- {
- Collection<VirtualHost> vhosts = ApplicationRegistry.getInstance().getVirtualHostRegistry().getVirtualHosts();
-
- boolean warning = false;
- for (VirtualHost vhost : vhosts)
- {
- if (vhost.getMessageStore() instanceof MemoryMessageStore)
- {
- _console.println("WARNING: Virtualhost '" + vhost.getName() + "' is using a MemoryMessageStore. "
- + "Changes will not persist.");
- warning = true;
- }
- }
-
- if (warning)
- {
- _console.println("");
- _console.println("Please ensure you are using the correct config file currently using '"
- + _config.getConfigFile().getAbsolutePath() + "'");
- _console.println("New config file can be specifed by 'load <config file>' or -c on the commandline.");
- _console.println("");
- }
- }
-
- private void runCLI()
- {
- while (_running)
- {
- if (!_batchMode)
- {
- printPrompt();
- }
-
- String[] args = _console.readCommand();
-
- while (args != null)
- {
- exec(args);
-
- if (_running)
- {
- if (!_batchMode)
- {
- printPrompt();
- }
-
- args = _console.readCommand();
- }
- }
- }
- }
-
- private void printPrompt()
- {
- _console.print(prompt());
- }
-
-
- /**
- * Execute a script (batch mode).
- *
- * @param script The file script
- */
- protected void runScripts(String script)
- {
- //Store Current State
- boolean oldBatch = _batchMode;
- CommandParser oldParser = _console.getCommandParser();
- setBatchMode(true);
-
- try
- {
- _devlog.debug("Running script '" + script + "'");
-
- _console.setCommandParser(new SimpleCommandParser(new BufferedReader(new FileReader(script))));
-
- start();
- }
- catch (java.io.FileNotFoundException e)
- {
- _devlog.error("Script not found: '" + script + "' due to:" + e.getMessage());
- }
-
- //Restore previous state
- _console.setCommandParser(oldParser);
- setBatchMode(oldBatch);
- }
-
- public String prompt()
- {
- String state = _state.toString();
- if (state != null && state.length() != 0)
- {
- return state + ":bdb$ ";
- }
- else
- {
- return "bdb$ ";
- }
- }
-
- /**
- * Execute the command.
- *
- * @param args [command, arg0, arg1...].
- */
- protected void exec(String[] args)
- {
- // Comment lines start with a #
- if (args.length == 0 || args[0].startsWith("#"))
- {
- return;
- }
-
- final String command = args[0];
-
- Command cmd = _commands.get(command);
-
- if (cmd == null)
- {
- _console.println("Command not understood: " + command);
- }
- else
- {
- cmd.execute(args);
- }
- }
-
-
- /**
- * Displays usage info.
- */
- protected static void help()
- {
- System.out.println(BOILER_PLATE);
- System.out.println("Usage: java " + MessageStoreTool.class + " [Options]");
- System.out.println(" [-c <broker config file>] : Defaults to \"$QPID_HOME/etc/config.xml\"");
- }
-
-
- /**
- * This class is used to store the current state of the tool.
- *
- * This is then interrogated by the various commands to augment their behaviour.
- *
- *
- */
- public static class State
- {
- private VirtualHost _vhost = null;
- private AMQQueue _queue = null;
- private Exchange _exchange = null;
- private java.util.List<Long> _msgids = null;
-
- public State()
- {
- }
-
- public void setQueue(AMQQueue queue)
- {
- _queue = queue;
- }
-
- public AMQQueue getQueue()
- {
- return _queue;
- }
-
- public void setVhost(VirtualHost vhost)
- {
- _vhost = vhost;
- }
-
- public VirtualHost getVhost()
- {
- return _vhost;
- }
-
- public Exchange getExchange()
- {
- return _exchange;
- }
-
- public void setExchange(Exchange exchange)
- {
- _exchange = exchange;
- }
-
- public String toString()
- {
- StringBuilder status = new StringBuilder();
-
- if (_vhost != null)
- {
- status.append(_vhost.getName());
-
- if (_exchange != null)
- {
- status.append("[");
- status.append(_exchange.getNameShortString());
- status.append("]");
-
- if (_queue != null)
- {
- status.append("->'");
- status.append(_queue.getNameShortString());
- status.append("'");
-
- if (_msgids != null)
- {
- status.append(printMessages());
- }
- }
- }
- }
-
- return status.toString();
- }
-
-
- public String printMessages()
- {
- StringBuilder sb = new StringBuilder();
-
- Long previous = null;
-
- Long start = null;
- for (Long id : _msgids)
- {
- if (previous != null)
- {
- if (id == previous + 1)
- {
- if (start == null)
- {
- start = previous;
- }
- }
- else
- {
- if (start != null)
- {
- sb.append(",");
- sb.append(start);
- sb.append("-");
- sb.append(id);
- start = null;
- }
- else
- {
- sb.append(",");
- sb.append(previous);
- }
- }
- }
-
- previous = id;
- }
-
- if (start != null)
- {
- sb.append(",");
- sb.append(start);
- sb.append("-");
- sb.append(_msgids.get(_msgids.size() - 1));
- }
- else
- {
- sb.append(",");
- sb.append(previous);
- }
-
- // surround list in ()
- sb.replace(0, 1, "(");
- sb.append(")");
- return sb.toString();
- }
-
- public void clearAll()
- {
- _vhost = null;
- clearExchange();
- }
-
- public void clearExchange()
- {
- _exchange = null;
- clearQueue();
- }
-
- public void clearQueue()
- {
- _queue = null;
- clearMessages();
- }
-
- public void clearMessages()
- {
- _msgids = null;
- }
-
- /**
- * A common location to provide parsing of the message id string
- * utilised by a number of the commands.
- * The String is comma separated list of ids that can be individual ids
- * or a range (4-10)
- *
- * @param msgString string of msg ids to parse 1,2,4-10
- */
- public void setMessages(String msgString)
- {
- StringTokenizer tok = new StringTokenizer(msgString, ",");
-
- if (tok.hasMoreTokens())
- {
- _msgids = new LinkedList<Long>();
- }
-
- while (tok.hasMoreTokens())
- {
- String next = tok.nextToken();
- if (next.contains("-"))
- {
- Long start = Long.parseLong(next.substring(0, next.indexOf("-")));
- Long end = Long.parseLong(next.substring(next.indexOf("-") + 1));
-
- if (end >= start)
- {
- for (long l = start; l <= end; l++)
- {
- _msgids.add(l);
- }
- }
- }
- else
- {
- _msgids.add(Long.parseLong(next));
- }
- }
-
- }
-
- public void setMessages(java.util.List<Long> msgids)
- {
- _msgids = msgids;
- }
-
- public java.util.List<Long> getMessages()
- {
- return _msgids;
- }
- }//Class State
-
-}//Class MessageStoreTool
diff --git a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/AbstractCommand.java b/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/AbstractCommand.java
deleted file mode 100644
index 5444197cb4..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/AbstractCommand.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.
- *
- *
- */
-package org.apache.qpid.tools.messagestore.commands;
-
-import org.apache.qpid.tools.messagestore.MessageStoreTool;
-import org.apache.qpid.tools.utils.Console;
-
-public abstract class AbstractCommand implements Command
-{
- protected Console _console;
- protected MessageStoreTool _tool;
-
- public AbstractCommand(MessageStoreTool tool)
- {
- _console = tool.getConsole();
- _tool = tool;
- }
-
- public void setOutput(Console out)
- {
- _console = out;
- }
-
- protected void commandError(String message, String[] args)
- {
- _console.print(getCommand() + " : " + message);
-
- if (args != null)
- {
- for (int i = 1; i < args.length; i++)
- {
- _console.print(args[i]);
- }
- }
- _console.println("");
- _console.println(help());
- }
-
-
- public abstract String help();
-
- public abstract String usage();
-
- public abstract String getCommand();
-
-
- public abstract void execute(String... args);
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Clear.java b/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Clear.java
deleted file mode 100644
index b0006b3fe6..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Clear.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- *
- */
-package org.apache.qpid.tools.messagestore.commands;
-
-import org.apache.qpid.tools.messagestore.MessageStoreTool;
-
-public class Clear extends AbstractCommand
-{
- public Clear(MessageStoreTool tool)
- {
- super(tool);
- }
-
- public String help()
- {
- return "Clears any selection.";
- }
-
- public String usage()
- {
- return "clear [ all | virtualhost | exchange | queue | msgs ]";
- }
-
- public String getCommand()
- {
- return "clear";
- }
-
- public void execute(String... args)
- {
- assert args.length > 0;
- assert args[0].equals(getCommand());
-
- if (args.length < 1)
- {
- doClose("all");
- }
- else
- {
- doClose(args[1]);
- }
- }
-
- private void doClose(String type)
- {
- if (type.equals("virtualhost")
- || type.equals("all"))
- {
- _tool.getState().clearAll();
- }
-
- if (type.equals("exchange"))
- {
- _tool.getState().clearExchange();
- }
-
- if (type.equals("queue"))
- {
- _tool.getState().clearQueue();
- }
-
- if (type.equals("msgs"))
- {
- _tool.getState().clearMessages();
- }
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Command.java b/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Command.java
deleted file mode 100644
index bfa775a34a..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Command.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.tools.messagestore.commands;
-
-import org.apache.qpid.tools.utils.Console;
-
-public interface Command
-{
- public void setOutput(Console out);
-
- public String help();
-
- public abstract String usage();
-
- String getCommand();
-
- public void execute(String... args);
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Copy.java b/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Copy.java
deleted file mode 100644
index 348c95572d..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Copy.java
+++ /dev/null
@@ -1,59 +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.tools.messagestore.commands;
-
-import org.apache.qpid.tools.messagestore.MessageStoreTool;
-import org.apache.qpid.server.queue.AMQQueue;
-import org.apache.qpid.server.txn.ServerTransaction;
-import org.apache.qpid.server.txn.LocalTransaction;
-
-public class Copy extends Move
-{
- public Copy(MessageStoreTool tool)
- {
- super(tool);
- }
-
- public String help()
- {
- return "Copy messages between queues.";/*\n" +
- "The currently selected message set will be copied to the specifed queue.\n" +
- "Alternatively the values can be provided on the command line."; */
- }
-
- public String usage()
- {
- return "copy to=<queue> [from=<queue>] [msgids=<msgids eg, 1,2,4-10>]";
- }
-
- public String getCommand()
- {
- return "copy";
- }
-
- protected void doCommand(AMQQueue fromQueue, long start, long end, AMQQueue toQueue)
- {
- ServerTransaction txn = new LocalTransaction(fromQueue.getVirtualHost().getTransactionLog());
- fromQueue.copyMessagesToAnotherQueue(start, end, toQueue.getNameShortString().toString(), txn);
- txn.commit();
- }
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Dump.java b/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Dump.java
deleted file mode 100644
index 8bb5d02b01..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Dump.java
+++ /dev/null
@@ -1,305 +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.tools.messagestore.commands;
-
-import org.apache.commons.codec.binary.Hex;
-import org.apache.qpid.server.queue.QueueEntryImpl;
-import org.apache.qpid.server.queue.QueueEntry;
-import org.apache.qpid.server.message.ServerMessage;
-import org.apache.qpid.tools.messagestore.MessageStoreTool;
-import org.apache.qpid.tools.utils.Console;
-
-import java.io.UnsupportedEncodingException;
-import java.util.LinkedList;
-import java.util.List;
-
-public class Dump extends Show
-{
- private static final int LINE_SIZE = 8;
- private static final String DEFAULT_ENCODING = "utf-8";
- private static final boolean SPACE_BYTES = true;
- private static final String BYTE_SPACER = " ";
- private static final String NON_PRINTING_ASCII_CHAR = "?";
-
- protected boolean _content = true;
-
- public Dump(MessageStoreTool tool)
- {
- super(tool);
- }
-
- public String help()
- {
- return "Dump selected message content. Default: show=content";
- }
-
- public String usage()
- {
- return getCommand() + " [show=[all],[msgheaders],[_amqHeaders],[routing],[content]] [id=<msgid e.g. 1,2,4-10>]";
- }
-
- public String getCommand()
- {
- return "dump";
- }
-
- public void execute(String... args)
- {
- assert args.length > 0;
- assert args[0].equals(getCommand());
-
-
- if (args.length >= 2)
- {
- for (String arg : args)
- {
- if (arg.startsWith("show="))
- {
- _content = arg.contains("content") || arg.contains("all");
- }
- }
-
- parseArgs(args);
- }
-
- performShow();
- }
-
-
- protected List<List> createMessageData(java.util.List<Long> msgids, List<QueueEntry> messages, boolean showHeaders, boolean showRouting,
- boolean showMessageHeaders)
- {
-
- List<List> display = new LinkedList<List>();
-
- List<String> hex = new LinkedList<String>();
- List<String> ascii = new LinkedList<String>();
- display.add(hex);
- display.add(ascii);
-
- for (QueueEntry entry : messages)
- {
- ServerMessage msg = entry.getMessage();
- if (!includeMsg(msg, msgids))
- {
- continue;
- }
-
- //Add divider between messages
- hex.add(Console.ROW_DIVIDER);
- ascii.add(Console.ROW_DIVIDER);
-
- // Show general message information
- hex.add(Show.Columns.ID.name());
- ascii.add(msg.getMessageNumber().toString());
-
- hex.add(Console.ROW_DIVIDER);
- ascii.add(Console.ROW_DIVIDER);
-
- if (showRouting)
- {
- addShowInformation(hex, ascii, msg, "Routing Details", true, false, false);
- }
- if (showHeaders)
- {
- addShowInformation(hex, ascii, msg, "Headers", false, true, false);
- }
- if (showMessageHeaders)
- {
- addShowInformation(hex, ascii, msg, null, false, false, true);
- }
-
- // Add Content Body section
- hex.add("Content Body");
- ascii.add("");
- hex.add(Console.ROW_DIVIDER);
- ascii.add(Console.ROW_DIVIDER);
-
-
- final int messageSize = (int) msg.getSize();
- if (messageSize != 0)
- {
- hex.add("Hex");
- hex.add(Console.ROW_DIVIDER);
-
-
- ascii.add("ASCII");
- ascii.add(Console.ROW_DIVIDER);
-
- java.nio.ByteBuffer buf = java.nio.ByteBuffer.allocate(64 * 1024);
-
- int position = 0;
-
- while(position < messageSize)
- {
-
- position += msg.getContent(buf, position);
- buf.flip();
- //Duplicate so we don't destroy original data :)
- java.nio.ByteBuffer hexBuffer = buf;
-
- java.nio.ByteBuffer charBuffer = hexBuffer.duplicate();
-
- Hex hexencoder = new Hex();
-
- while (hexBuffer.hasRemaining())
- {
- byte[] line = new byte[LINE_SIZE];
-
- int bufsize = hexBuffer.remaining();
- if (bufsize < LINE_SIZE)
- {
- hexBuffer.get(line, 0, bufsize);
- }
- else
- {
- bufsize = line.length;
- hexBuffer.get(line);
- }
-
- byte[] encoded = hexencoder.encode(line);
-
- try
- {
- String encStr = new String(encoded, 0, bufsize * 2, DEFAULT_ENCODING);
- String hexLine = "";
-
- int strLength = encStr.length();
- for (int c = 0; c < strLength; c++)
- {
- hexLine += encStr.charAt(c);
-
- if ((c & 1) == 1 && SPACE_BYTES)
- {
- hexLine += BYTE_SPACER;
- }
- }
-
- hex.add(hexLine);
- }
- catch (UnsupportedEncodingException e)
- {
- _console.println(e.getMessage());
- return null;
- }
- }
-
- while (charBuffer.hasRemaining())
- {
- String asciiLine = "";
-
- for (int pos = 0; pos < LINE_SIZE; pos++)
- {
- if (charBuffer.hasRemaining())
- {
- byte ch = charBuffer.get();
-
- if (isPrintable(ch))
- {
- asciiLine += (char) ch;
- }
- else
- {
- asciiLine += NON_PRINTING_ASCII_CHAR;
- }
-
- if (SPACE_BYTES)
- {
- asciiLine += BYTE_SPACER;
- }
- }
- else
- {
- break;
- }
- }
-
- ascii.add(asciiLine);
- }
- buf.clear();
- }
- }
- else
- {
- List<String> result = new LinkedList<String>();
-
- display.add(result);
- result.add("No ContentBodies");
- }
- }
-
- // if hex is empty then we have no data to display
- if (hex.size() == 0)
- {
- return null;
- }
-
- return display;
- }
-
- private void addShowInformation(List<String> column1, List<String> column2, ServerMessage msg,
- String title, boolean routing, boolean headers, boolean messageHeaders)
- {
- List<QueueEntry> single = new LinkedList<QueueEntry>();
- single.add(new QueueEntryImpl(null,msg, Long.MIN_VALUE));
-
- List<List> routingData = super.createMessageData(null, single, headers, routing, messageHeaders);
-
- //Reformat data
- if (title != null)
- {
- column1.add(title);
- column2.add("");
- column1.add(Console.ROW_DIVIDER);
- column2.add(Console.ROW_DIVIDER);
- }
-
- // look at all columns in the routing Data
- for (List item : routingData)
- {
- // the item should be:
- // Title
- // *divider
- // value
- // otherwise we can't reason about the correct value
- if (item.size() == 3)
- {
- //Filter out the columns we are not interested in.
-
- String columnName = item.get(0).toString();
-
- if (!(columnName.equals(Show.Columns.ID.name())
- || columnName.equals(Show.Columns.Size.name())))
- {
- column1.add(columnName);
- column2.add(item.get(2).toString());
- }
- }
- }
- column1.add(Console.ROW_DIVIDER);
- column2.add(Console.ROW_DIVIDER);
- }
-
- private boolean isPrintable(byte c)
- {
- return c > 31 && c < 127;
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Help.java b/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Help.java
deleted file mode 100644
index 0f9546541b..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Help.java
+++ /dev/null
@@ -1,98 +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.tools.messagestore.commands;
-
-import org.apache.qpid.tools.messagestore.MessageStoreTool;
-import org.apache.qpid.tools.utils.Console;
-
-import java.util.LinkedList;
-import java.util.Map;
-
-public class Help extends AbstractCommand
-{
- public Help(MessageStoreTool tool)
- {
- super(tool);
- }
-
- public String help()
- {
- return "Provides detailed help on commands.";
- }
-
- public String getCommand()
- {
- return "help";
- }
-
- public String usage()
- {
- return "help [<command>]";
- }
-
- public void execute(String... args)
- {
- assert args.length > 0;
- assert args[0].equals(getCommand());
-
- if (args.length > 1)
- {
- Command command = _tool.getCommands().get(args[1]);
- if (command != null)
- {
- _console.println(command.help());
- _console.println("Usage:" + command.usage());
- }
- else
- {
- commandError("Command not found: ", args);
- }
- }
- else
- {
- java.util.List<java.util.List> data = new LinkedList<java.util.List>();
-
- java.util.List<String> commandName = new LinkedList<String>();
- java.util.List<String> commandDescription = new LinkedList<String>();
-
- data.add(commandName);
- data.add(commandDescription);
-
- //Set up Headers
- commandName.add("Command");
- commandDescription.add("Description");
-
- commandName.add(Console.ROW_DIVIDER);
- commandDescription.add(Console.ROW_DIVIDER);
-
- //Add current Commands with descriptions
- Map<String, Command> commands = _tool.getCommands();
-
- for (Command command : commands.values())
- {
- commandName.add(command.getCommand());
- commandDescription.add(command.help());
- }
-
- _console.printMap("Available Commands", data);
- }
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/List.java b/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/List.java
deleted file mode 100644
index 3c4a0c8fac..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/List.java
+++ /dev/null
@@ -1,314 +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.tools.messagestore.commands;
-
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.server.exchange.Exchange;
-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.tools.messagestore.MessageStoreTool;
-import org.apache.qpid.tools.utils.Console;
-
-import java.util.Collection;
-import java.util.LinkedList;
-
-public class List extends AbstractCommand
-{
-
- public List(MessageStoreTool tool)
- {
- super(tool);
- }
-
- public void setOutput(Console out)
- {
- _console = out;
- }
-
- public String help()
- {
- return "list available items.";
- }
-
- public String usage()
- {
- return "list queues [<exchange>] | exchanges | bindings [<exchange>] | all";
- }
-
- public String getCommand()
- {
- return "list";
- }
-
- public void execute(String... args)
- {
- assert args.length > 0;
- assert args[0].equals(getCommand());
-
- if (args.length > 1)
- {
- if ((args[1].equals("exchanges"))
- || (args[1].equals("queues"))
- || (args[1].equals("bindings"))
- || (args[1].equals("all")))
- {
- if (args.length == 2)
- {
- doList(args[1]);
- }
- else if (args.length == 3)
- {
- doList(args[1], args[2]);
- }
- }
- else
- {
- commandError("Unknown options. ", args);
- }
- }
- else if (args.length < 2)
- {
- doList("all");
- }
- else
- {
- doList(args[1]);
- }
- }
-
- private void doList(String... listItem)
- {
- if (_tool.getState().getVhost() == null)
- {
- _console.println("No Virtualhost open. Open a Virtualhost first.");
- listVirtualHosts();
- return;
- }
-
- VirtualHost vhost = _tool.getState().getVhost();
-
- java.util.List<String> data = null;
-
- if (listItem[0].equals("queues"))
- {
- if (listItem.length > 1)
- {
- data = listQueues(vhost, new AMQShortString(listItem[1]));
- }
- else
- {
- Exchange exchange = _tool.getState().getExchange();
- data = listQueues(vhost, exchange);
- }
- }
-
- if (listItem[0].equals("exchanges"))
- {
- data = listExchanges(vhost);
- }
-
- if (listItem[0].equals("bindings"))
- {
-
- if (listItem.length > 1)
- {
- data = listBindings(vhost, new AMQShortString(listItem[1]));
- }
- else
- {
- Exchange exchange = _tool.getState().getExchange();
-
- data = listBindings(vhost, exchange);
- }
- }
-
- if (data != null)
- {
- if (data.size() == 1)
- {
- _console.println("No '" + listItem[0] + "' to display,");
- }
- else
- {
- _console.displayList(true, data.toArray(new String[0]));
- }
- }
-
-
- if (listItem[0].equals("all"))
- {
-
- boolean displayed = false;
- Exchange exchange = _tool.getState().getExchange();
-
- //Do the display here for each one so that they are pretty printed
- data = listQueues(vhost, exchange);
- if (data != null)
- {
- displayed = true;
- _console.displayList(true, data.toArray(new String[0]));
- }
-
- if (exchange == null)
- {
- data = listExchanges(vhost);
- if (data != null)
- {
- displayed = true;
- _console.displayList(true, data.toArray(new String[0]));
- }
- }
-
- data = listBindings(vhost, exchange);
- if (data != null)
- {
- displayed = true;
- _console.displayList(true, data.toArray(new String[0]));
- }
-
- if (!displayed)
- {
- _console.println("Nothing to list");
- }
- }
- }
-
- private void listVirtualHosts()
- {
- Collection<VirtualHost> vhosts = ApplicationRegistry.getInstance()
- .getVirtualHostRegistry().getVirtualHosts();
-
- String[] data = new String[vhosts.size() + 1];
-
- data[0] = "Available VirtualHosts";
-
- int index = 1;
- for (VirtualHost vhost : vhosts)
- {
- data[index] = vhost.getName();
- index++;
- }
-
- _console.displayList(true, data);
- }
-
- private java.util.List<String> listBindings(VirtualHost vhost, AMQShortString exchangeName)
- {
- return listBindings(vhost, vhost.getExchangeRegistry().getExchange(exchangeName));
- }
-
- private java.util.List<String> listBindings(VirtualHost vhost, Exchange exchange)
- {
- Collection<AMQShortString> queues = vhost.getQueueRegistry().getQueueNames();
-
- if (queues == null || queues.size() == 0)
- {
- return null;
- }
-
- java.util.List<String> data = new LinkedList<String>();
-
- data.add("Current Bindings");
-
- for (AMQShortString queue : queues)
- {
- if (exchange != null)
- {
- if (exchange.isBound(queue))
- {
- data.add(queue.toString());
- }
- }
- else
- {
- data.add(queue.toString());
- }
- }
-
- return data;
- }
-
- private java.util.List<String> listExchanges(VirtualHost vhost)
- {
- Collection<AMQShortString> queues = vhost.getExchangeRegistry().getExchangeNames();
-
- if (queues == null || queues.size() == 0)
- {
- return null;
- }
-
- java.util.List<String> data = new LinkedList<String>();
-
- data.add("Available Exchanges");
-
- for (AMQShortString queue : queues)
- {
- data.add(queue.toString());
- }
-
- return data;
- }
-
- private java.util.List<String> listQueues(VirtualHost vhost, AMQShortString exchangeName)
- {
- return listQueues(vhost, vhost.getExchangeRegistry().getExchange(exchangeName));
- }
-
- private java.util.List<String> listQueues(VirtualHost vhost, Exchange exchange)
- {
- Collection<AMQQueue> queues = vhost.getQueueRegistry().getQueues();
-
- if (queues == null || queues.size() == 0)
- {
- return null;
- }
-
- java.util.List<String> data = new LinkedList<String>();
-
- data.add("Available Queues");
-
- for (AMQQueue queue : queues)
- {
- if (exchange != null)
- {
- if (exchange.isBound(queue))
- {
- data.add(queue.getNameShortString().toString());
- }
- }
- else
- {
- data.add(queue.getNameShortString().toString());
- }
- }
-
- if (exchange != null)
- {
- if (queues.size() == 1)
- {
- return null;
- }
- }
-
- return data;
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Load.java b/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Load.java
deleted file mode 100644
index 244a311c30..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Load.java
+++ /dev/null
@@ -1,94 +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.tools.messagestore.commands;
-
-import org.apache.qpid.configuration.Configuration;
-import org.apache.qpid.tools.messagestore.MessageStoreTool;
-
-public class Load extends AbstractCommand
-{
- public Load(MessageStoreTool tool)
- {
- super(tool);
- }
-
- public String help()
- {
- return "Loads specified broker configuration file.";
- }
-
- public String usage()
- {
- return "load <configuration file>";
- }
-
- public String getCommand()
- {
- return "load";
- }
-
- public void execute(String... args)
- {
- assert args.length > 0;
- assert args[0].equals(getCommand());
-
- if (args.length > 2)
- {
- _console.print("load " + args[1] + ": additional options not understood:");
- for (int i = 2; i < args.length; i++)
- {
- _console.print(args[i] + " ");
- }
- _console.println("");
- }
- else if (args.length < 2)
- {
- _console.println("Enter Configuration file.");
- String input = _console.readln();
- if (input != null)
- {
- doLoad(input);
- }
- else
- {
- _console.println("Did not recognise config file.");
- }
- }
- else
- {
- doLoad(args[1]);
- }
- }
-
- private void doLoad(String configfile)
- {
- _console.println("Loading Configuration:" + configfile);
-
- try
- {
- _tool.setConfigurationFile(configfile);
- }
- catch (Configuration.InitException e)
- {
- _console.println("Unable to open config file due to: '" + e.getMessage() + "'");
- }
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Move.java b/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Move.java
deleted file mode 100644
index 615f6ec1c2..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Move.java
+++ /dev/null
@@ -1,202 +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.tools.messagestore.commands;
-
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.server.queue.AMQQueue;
-import org.apache.qpid.server.queue.QueueEntry;
-import org.apache.qpid.server.txn.ServerTransaction;
-import org.apache.qpid.server.txn.LocalTransaction;
-import org.apache.qpid.tools.messagestore.MessageStoreTool;
-
-import java.util.LinkedList;
-import java.util.List;
-
-public class Move extends AbstractCommand
-{
-
- public Move(MessageStoreTool tool)
- {
- super(tool);
- }
-
- public String help()
- {
- return "Move messages between queues.";/*\n" +
- "The currently selected message set will be moved to the specifed queue.\n" +
- "Alternatively the values can be provided on the command line.";*/
- }
-
- public String usage()
- {
- return "move to=<queue> [from=<queue>] [msgids=<msgids eg, 1,2,4-10>]";
- }
-
- public String getCommand()
- {
- return "move";
- }
-
- public void execute(String... args)
- {
- AMQQueue toQueue = null;
- AMQQueue fromQueue = _tool.getState().getQueue();
- java.util.List<Long> msgids = _tool.getState().getMessages();
-
- if (args.length >= 2)
- {
- for (String arg : args)
- {
- if (arg.startsWith("to="))
- {
- String queueName = arg.substring(arg.indexOf("=") + 1);
- toQueue = _tool.getState().getVhost().getQueueRegistry().getQueue(new AMQShortString(queueName));
- }
-
- if (arg.startsWith("from="))
- {
- String queueName = arg.substring(arg.indexOf("=") + 1);
- fromQueue = _tool.getState().getVhost().getQueueRegistry().getQueue(new AMQShortString(queueName));
- }
-
- if (arg.startsWith("msgids="))
- {
- String msgidStr = arg.substring(arg.indexOf("=") + 1);
-
- // Record the current message selection
- java.util.List<Long> currentIDs = _tool.getState().getMessages();
-
- // Use the ToolState class to perform the messasge parsing
- _tool.getState().setMessages(msgidStr);
- msgids = _tool.getState().getMessages();
-
- // Reset the original selection of messages
- _tool.getState().setMessages(currentIDs);
- }
- }
- }
-
- if (!checkRequirements(fromQueue, toQueue, msgids))
- {
- return;
- }
-
- processIDs(fromQueue, toQueue, msgids);
- }
-
- private void processIDs(AMQQueue fromQueue, AMQQueue toQueue, java.util.List<Long> msgids)
- {
- Long previous = null;
- Long start = null;
-
- if (msgids == null)
- {
- msgids = allMessageIDs(fromQueue);
- }
-
- if (msgids == null || msgids.size() == 0)
- {
- _console.println("No Messages to move.");
- return;
- }
-
- for (long id : msgids)
- {
- if (previous != null)
- {
- if (id == previous + 1)
- {
- if (start == null)
- {
- start = previous;
- }
- }
- else
- {
- if (start != null)
- {
- //move a range of ids
- doCommand(fromQueue, start, id, toQueue);
- start = null;
- }
- else
- {
- //move a single id
- doCommand(fromQueue, id, id, toQueue);
- }
- }
- }
-
- previous = id;
- }
-
- if (start != null)
- {
- //move a range of ids
- doCommand(fromQueue, start, previous, toQueue);
- }
- }
-
- private List<Long> allMessageIDs(AMQQueue fromQueue)
- {
- List<Long> ids = new LinkedList<Long>();
-
- if (fromQueue != null)
- {
- List<QueueEntry> messages = fromQueue.getMessagesOnTheQueue();
- if (messages != null)
- {
- for (QueueEntry msg : messages)
- {
- ids.add(msg.getMessage().getMessageNumber());
- }
- }
- }
-
- return ids;
- }
-
- protected boolean checkRequirements(AMQQueue fromQueue, AMQQueue toQueue, List<Long> msgids)
- {
- if (toQueue == null)
- {
- _console.println("Destination queue not specifed.");
- _console.println(usage());
- return false;
- }
-
- if (fromQueue == null)
- {
- _console.println("Source queue not specifed.");
- _console.println(usage());
- return false;
- }
-
- return true;
- }
-
- protected void doCommand(AMQQueue fromQueue, long start, long id, AMQQueue toQueue)
- {
- ServerTransaction txn = new LocalTransaction(fromQueue.getVirtualHost().getTransactionLog());
- fromQueue.moveMessagesToAnotherQueue(start, id, toQueue.getNameShortString().toString(), txn);
- txn.commit();
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Purge.java b/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Purge.java
deleted file mode 100644
index 8df4afa2db..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Purge.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- *
- */
-package org.apache.qpid.tools.messagestore.commands;
-
-import org.apache.qpid.tools.messagestore.MessageStoreTool;
-import org.apache.qpid.server.queue.AMQQueue;
-
-public class Purge extends Move
-{
- public Purge(MessageStoreTool tool)
- {
- super(tool);
- }
-
- public String help()
- {
- return "Purge messages from a queue.\n" +
- "The currently selected message set will be purged from the specifed queue.\n" +
- "Alternatively the values can be provided on the command line.";
- }
-
- public String usage()
- {
- return "purge from=<queue> [msgids=<msgids eg, 1,2,4-10>]";
- }
-
- public String getCommand()
- {
- return "purge";
- }
-
-
- protected boolean checkRequirements(AMQQueue fromQueue, AMQQueue toQueue, java.util.List<Long> msgids)
- {
- if (fromQueue == null)
- {
- _console.println("Source queue not specifed.");
- _console.println(usage());
- return false;
- }
-
- return true;
- }
-
- protected void doCommand(AMQQueue fromQueue, long start, long end, AMQQueue toQueue)
- {
- fromQueue.removeMessagesFromQueue(start, end);
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Quit.java b/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Quit.java
deleted file mode 100644
index a81bc07c38..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Quit.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- *
- */
-package org.apache.qpid.tools.messagestore.commands;
-
-import org.apache.qpid.tools.messagestore.MessageStoreTool;
-
-public class Quit extends AbstractCommand
-{
- public Quit(MessageStoreTool tool)
- {
- super(tool);
- }
-
- public String help()
- {
- return "Quit the tool.";
- }
-
- public String usage()
- {
- return "quit";
- }
-
- public String getCommand()
- {
- return "quit";
- }
-
- public void execute(String... args)
- {
- assert args.length > 0;
- assert args[0].equals("quit");
-
- _tool.quit();
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Select.java b/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Select.java
deleted file mode 100644
index ff59568374..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Select.java
+++ /dev/null
@@ -1,233 +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.tools.messagestore.commands;
-
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.server.exchange.Exchange;
-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.tools.messagestore.MessageStoreTool;
-
-import java.util.LinkedList;
-import java.util.StringTokenizer;
-
-public class Select extends AbstractCommand
-{
-
- public Select(MessageStoreTool tool)
- {
- super(tool);
- }
-
- public String help()
- {
- return "Perform a selection.";
- }
-
- public String usage()
- {
- return "select virtualhost <name> |exchange <name> |queue <name> | msg id=<msgids eg. 1,2,4-10>";
- }
-
- public String getCommand()
- {
- return "select";
- }
-
- public void execute(String... args)
- {
- assert args.length > 2;
- assert args[0].equals("select");
-
- if (args.length < 3)
- {
- if (args[1].equals("show"))
- {
- doSelect(args[1], null);
- }
- else
- {
- _console.print("select : unknown command:");
- _console.println(help());
- }
- }
- else
- {
- if (args[1].equals("virtualhost")
- || args[1].equals("vhost")
- || args[1].equals("exchange")
- || args[1].equals("queue")
- || args[1].equals("msg")
- )
- {
- doSelect(args[1], args[2]);
- }
- else
- {
- _console.println(help());
- }
- }
- }
-
- private void doSelect(String type, String item)
- {
- if (type.equals("virtualhost"))
- {
-
- VirtualHost vhost = ApplicationRegistry.getInstance()
- .getVirtualHostRegistry().getVirtualHost(item);
-
- if (vhost == null)
- {
- _console.println("Virtualhost '" + item + "' not found.");
- }
- else
- {
- _tool.getState().setVhost(vhost);
- }
- }
-
- if (type.equals("exchange"))
- {
-
- VirtualHost vhost = _tool.getState().getVhost();
-
- if (vhost == null)
- {
- _console.println("No Virtualhost open. Open a Virtualhost first.");
- return;
- }
-
-
- Exchange exchange = vhost.getExchangeRegistry().getExchange(new AMQShortString(item));
-
- if (exchange == null)
- {
- _console.println("Exchange '" + item + "' not found.");
- }
- else
- {
- _tool.getState().setExchange(exchange);
- }
-
- if (_tool.getState().getQueue() != null)
- {
- if (!exchange.isBound(_tool.getState().getQueue()))
- {
- _tool.getState().setQueue(null);
- }
- }
- }
-
- if (type.equals("queue"))
- {
- VirtualHost vhost = _tool.getState().getVhost();
-
- if (vhost == null)
- {
- _console.println("No Virtualhost open. Open a Virtualhost first.");
- return;
- }
-
- AMQQueue queue = vhost.getQueueRegistry().getQueue(new AMQShortString(item));
-
- if (queue == null)
- {
- _console.println("Queue '" + item + "' not found.");
- }
- else
- {
- _tool.getState().setQueue(queue);
-
- if (_tool.getState().getExchange() == null)
- {
- for (AMQShortString exchangeName : vhost.getExchangeRegistry().getExchangeNames())
- {
- Exchange exchange = vhost.getExchangeRegistry().getExchange(exchangeName);
- if (exchange.isBound(queue))
- {
- _tool.getState().setExchange(exchange);
- break;
- }
- }
- }
-
- //remove the message selection
- _tool.getState().setMessages((java.util.List<Long>) null);
- }
- }
-
- if (type.equals("msg"))
- {
- if (item.startsWith("id="))
- {
- StringTokenizer tok = new StringTokenizer(item.substring(item.indexOf("=") + 1), ",");
-
- java.util.List<Long> msgids = null;
-
- if (tok.hasMoreTokens())
- {
- msgids = new LinkedList<Long>();
- }
-
- while (tok.hasMoreTokens())
- {
- String next = tok.nextToken();
- if (next.contains("-"))
- {
- Long start = Long.parseLong(next.substring(0, next.indexOf("-")));
- Long end = Long.parseLong(next.substring(next.indexOf("-") + 1));
-
- if (end >= start)
- {
- for (long l = start; l <= end; l++)
- {
- msgids.add(l);
- }
- }
- }
- else
- {
- msgids.add(Long.parseLong(next));
- }
- }
-
- _tool.getState().setMessages(msgids);
- }
-
- }
-
- if (type.equals("show"))
- {
- _console.println(_tool.getState().toString());
- if (_tool.getState().getMessages() != null)
- {
- _console.print("Msgs:");
- for (Long l : _tool.getState().getMessages())
- {
- _console.print(" " + l);
- }
- _console.println("");
- }
- }
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Show.java b/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Show.java
deleted file mode 100644
index 806e161bbc..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Show.java
+++ /dev/null
@@ -1,516 +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.tools.messagestore.commands;
-
-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.framing.abstraction.MessagePublishInfo;
-import org.apache.qpid.server.message.AMQMessage;
-import org.apache.qpid.server.queue.AMQQueue;
-import org.apache.qpid.server.queue.QueueEntry;
-import org.apache.qpid.server.message.ServerMessage;
-import org.apache.qpid.tools.messagestore.MessageStoreTool;
-import org.apache.qpid.tools.utils.Console;
-
-import java.util.LinkedList;
-import java.util.List;
-
-public class Show extends AbstractCommand
-{
- protected boolean _amqHeaders = false;
- protected boolean _routing = false;
- protected boolean _msgHeaders = false;
-
- public Show(MessageStoreTool tool)
- {
- super(tool);
- }
-
- public String help()
- {
- return "Shows the messages headers.";
- }
-
- public String usage()
- {
- return getCommand() + " [show=[all],[msgheaders],[amqheaders],[routing]] [id=<msgid e.g. 1,2,4-10>]";
- }
-
- public String getCommand()
- {
- return "show";
- }
-
- public void execute(String... args)
- {
- assert args.length > 0;
- assert args[0].equals(getCommand());
-
- if (args.length < 2)
- {
- parseArgs("all");
- }
- else
- {
- parseArgs(args);
- }
-
- performShow();
- }
-
- protected void parseArgs(String... args)
- {
- List<Long> msgids = null;
-
- if (args.length >= 2)
- {
- for (String arg : args)
- {
- if (arg.startsWith("show="))
- {
- _msgHeaders = arg.contains("msgheaders") || arg.contains("all");
- _amqHeaders = arg.contains("amqheaders") || arg.contains("all");
- _routing = arg.contains("routing") || arg.contains("all");
- }
-
- if (arg.startsWith("id="))
- {
- _tool.getState().setMessages(msgids);
- }
- }//for args
- }// if args > 2
- }
-
- protected void performShow()
- {
- if (_tool.getState().getVhost() == null)
- {
- _console.println("No Virtualhost selected. 'DuSelect' a Virtualhost first.");
- return;
- }
-
- AMQQueue _queue = _tool.getState().getQueue();
-
- List<Long> msgids = _tool.getState().getMessages();
-
- if (_queue != null)
- {
- List<QueueEntry> messages = _queue.getMessagesOnTheQueue();
- if (messages == null || messages.size() == 0)
- {
- _console.println("No messages on queue");
- return;
- }
-
- List<List> data = createMessageData(msgids, messages, _amqHeaders, _routing, _msgHeaders);
- if (data != null)
- {
- _console.printMap(null, data);
- }
- else
- {
- String message = "No data to display.";
- if (msgids != null)
- {
- message += " Is message selection correct? " + _tool.getState().printMessages();
- }
- _console.println(message);
- }
-
- }
- else
- {
- _console.println("No Queue specified to show.");
- }
- }
-
- /**
- * Create the list data for display from the messages.
- *
- * @param msgids The list of message ids to display
- * @param messages A list of messages to format and display.
- * @param showHeaders should the header info be shown
- * @param showRouting show the routing info be shown
- * @param showMessageHeaders show the msg headers be shown
- * @return the formated data lists for printing
- */
- protected List<List> createMessageData(List<Long> msgids, List<QueueEntry> messages, boolean showHeaders, boolean showRouting,
- boolean showMessageHeaders)
- {
-
- // Currenly exposed message properties
-// //Printing the content Body
-// msg.getContentBodyIterator();
-// //Print the Headers
-// ((BasicContentHeaderProperties)msg.getContentHeaderBody().properties).getAppId();
-// ((BasicContentHeaderProperties)msg.getContentHeaderBody().properties).getAppIdAsString();
-// ((BasicContentHeaderProperties)msg.getContentHeaderBody().properties).getClusterId();
-// ((BasicContentHeaderProperties)msg.getContentHeaderBody().properties).getContentType();
-// ((BasicContentHeaderProperties)msg.getContentHeaderBody().properties).getCorrelationId();
-// ((BasicContentHeaderProperties)msg.getContentHeaderBody().properties).getDeliveryMode();
-// ((BasicContentHeaderProperties)msg.getContentHeaderBody().properties).getEncoding();
-// ((BasicContentHeaderProperties)msg.getContentHeaderBody().properties).getExpiration();
-// ((BasicContentHeaderProperties)msg.getContentHeaderBody().properties).getHeaders();
-// ((BasicContentHeaderProperties)msg.getContentHeaderBody().properties).getMessageNumber();
-// ((BasicContentHeaderProperties)msg.getContentHeaderBody().properties).getPriority();
-// ((BasicContentHeaderProperties)msg.getContentHeaderBody().properties).getPropertyFlags();
-// ((BasicContentHeaderProperties)msg.getContentHeaderBody().properties).getReplyTo();
-// ((BasicContentHeaderProperties)msg.getContentHeaderBody().properties).getTimestamp();
-// ((BasicContentHeaderProperties)msg.getContentHeaderBody().properties).getType();
-// ((BasicContentHeaderProperties)msg.getContentHeaderBody().properties).getUserId();
-//
-// //Print out all the property names
-// ((BasicContentHeaderProperties)msg.getContentHeaderBody().properties).getHeaders().getPropertyNames();
-//
-// msg.getMessageNumber();
-// msg.getSize();
-// msg.getArrivalTime();
-
-// msg.getDeliveredSubscription();
-// msg.getDeliveredToConsumer();
-// msg.getMessageHandle();
-// msg.getMessageNumber();
-// msg.getMessagePublishInfo();
-// msg.getPublisher();
-
-// msg.getStoreContext();
-// msg.isAllContentReceived();
-// msg.isPersistent();
-// msg.isRedelivered();
-// msg.isRejectedBy();
-// msg.isTaken();
-
- //Header setup
-
- List<List> data = new LinkedList<List>();
-
- List<String> id = new LinkedList<String>();
- data.add(id);
- id.add(Columns.ID.name());
- id.add(Console.ROW_DIVIDER);
-
- List<String> exchange = new LinkedList<String>();
- List<String> routingkey = new LinkedList<String>();
- List<String> immediate = new LinkedList<String>();
- List<String> mandatory = new LinkedList<String>();
- if (showRouting)
- {
- data.add(exchange);
- exchange.add(Columns.Exchange.name());
- exchange.add(Console.ROW_DIVIDER);
-
- data.add(routingkey);
- routingkey.add(Columns.RoutingKey.name());
- routingkey.add(Console.ROW_DIVIDER);
-
- data.add(immediate);
- immediate.add(Columns.isImmediate.name());
- immediate.add(Console.ROW_DIVIDER);
-
- data.add(mandatory);
- mandatory.add(Columns.isMandatory.name());
- mandatory.add(Console.ROW_DIVIDER);
- }
-
- List<String> size = new LinkedList<String>();
- List<String> appid = new LinkedList<String>();
- List<String> clusterid = new LinkedList<String>();
- List<String> contenttype = new LinkedList<String>();
- List<String> correlationid = new LinkedList<String>();
- List<String> deliverymode = new LinkedList<String>();
- List<String> encoding = new LinkedList<String>();
- List<String> arrival = new LinkedList<String>();
- List<String> expiration = new LinkedList<String>();
- List<String> priority = new LinkedList<String>();
- List<String> propertyflag = new LinkedList<String>();
- List<String> replyto = new LinkedList<String>();
- List<String> timestamp = new LinkedList<String>();
- List<String> type = new LinkedList<String>();
- List<String> userid = new LinkedList<String>();
- List<String> ispersitent = new LinkedList<String>();
- List<String> isredelivered = new LinkedList<String>();
- List<String> isdelivered = new LinkedList<String>();
-
- data.add(size);
- size.add(Columns.Size.name());
- size.add(Console.ROW_DIVIDER);
-
- if (showHeaders)
- {
- data.add(ispersitent);
- ispersitent.add(Columns.isPersistent.name());
- ispersitent.add(Console.ROW_DIVIDER);
-
- data.add(isredelivered);
- isredelivered.add(Columns.isRedelivered.name());
- isredelivered.add(Console.ROW_DIVIDER);
-
- data.add(isdelivered);
- isdelivered.add(Columns.isDelivered.name());
- isdelivered.add(Console.ROW_DIVIDER);
-
- data.add(appid);
- appid.add(Columns.App_ID.name());
- appid.add(Console.ROW_DIVIDER);
-
- data.add(clusterid);
- clusterid.add(Columns.Cluster_ID.name());
- clusterid.add(Console.ROW_DIVIDER);
-
- data.add(contenttype);
- contenttype.add(Columns.Content_Type.name());
- contenttype.add(Console.ROW_DIVIDER);
-
- data.add(correlationid);
- correlationid.add(Columns.Correlation_ID.name());
- correlationid.add(Console.ROW_DIVIDER);
-
- data.add(deliverymode);
- deliverymode.add(Columns.Delivery_Mode.name());
- deliverymode.add(Console.ROW_DIVIDER);
-
- data.add(encoding);
- encoding.add(Columns.Encoding.name());
- encoding.add(Console.ROW_DIVIDER);
-
- data.add(arrival);
- expiration.add(Columns.Arrival.name());
- expiration.add(Console.ROW_DIVIDER);
-
- data.add(expiration);
- expiration.add(Columns.Expiration.name());
- expiration.add(Console.ROW_DIVIDER);
-
- data.add(priority);
- priority.add(Columns.Priority.name());
- priority.add(Console.ROW_DIVIDER);
-
- data.add(propertyflag);
- propertyflag.add(Columns.Property_Flag.name());
- propertyflag.add(Console.ROW_DIVIDER);
-
- data.add(replyto);
- replyto.add(Columns.ReplyTo.name());
- replyto.add(Console.ROW_DIVIDER);
-
- data.add(timestamp);
- timestamp.add(Columns.Timestamp.name());
- timestamp.add(Console.ROW_DIVIDER);
-
- data.add(type);
- type.add(Columns.Type.name());
- type.add(Console.ROW_DIVIDER);
-
- data.add(userid);
- userid.add(Columns.UserID.name());
- userid.add(Console.ROW_DIVIDER);
- }
-
- List<String> msgHeaders = new LinkedList<String>();
- if (showMessageHeaders)
- {
- data.add(msgHeaders);
- msgHeaders.add(Columns.MsgHeaders.name());
- msgHeaders.add(Console.ROW_DIVIDER);
- }
-
- //Add create the table of data
- for (QueueEntry entry : messages)
- {
- ServerMessage msg = entry.getMessage();
- if (!includeMsg(msg, msgids))
- {
- continue;
- }
-
- id.add(msg.getMessageNumber().toString());
-
- size.add("" + msg.getSize());
-
- arrival.add("" + msg.getArrivalTime());
-
- ispersitent.add(msg.isPersistent() ? "true" : "false");
-
-
- isredelivered.add(entry.isRedelivered() ? "true" : "false");
-
- isdelivered.add(entry.getDeliveredToConsumer() ? "true" : "false");
-
-// msg.getMessageHandle();
-
- BasicContentHeaderProperties headers = null;
-
- try
- {
- if(msg instanceof AMQMessage)
- {
- headers = ((BasicContentHeaderProperties) ((AMQMessage)msg).getContentHeaderBody().getProperties());
- }
- }
- catch (AMQException e)
- {
- //ignore
-// commandError("Unable to read properties for message: " + e.getMessage(), null);
- }
-
- if (headers != null)
- {
- String appidS = headers.getAppIdAsString();
- appid.add(appidS == null ? "null" : appidS);
-
- String clusterS = headers.getClusterIdAsString();
- clusterid.add(clusterS == null ? "null" : clusterS);
-
- String contentS = headers.getContentTypeAsString();
- contenttype.add(contentS == null ? "null" : contentS);
-
- String correlationS = headers.getCorrelationIdAsString();
- correlationid.add(correlationS == null ? "null" : correlationS);
-
- deliverymode.add("" + headers.getDeliveryMode());
-
- AMQShortString encodeSS = headers.getEncoding();
- encoding.add(encodeSS == null ? "null" : encodeSS.toString());
-
- expiration.add("" + headers.getExpiration());
-
- FieldTable headerFT = headers.getHeaders();
- msgHeaders.add(headerFT == null ? "none" : "" + headerFT.toString());
-
- priority.add("" + headers.getPriority());
- propertyflag.add("" + headers.getPropertyFlags());
-
- AMQShortString replytoSS = headers.getReplyTo();
- replyto.add(replytoSS == null ? "null" : replytoSS.toString());
-
- timestamp.add("" + headers.getTimestamp());
-
- AMQShortString typeSS = headers.getType();
- type.add(typeSS == null ? "null" : typeSS.toString());
-
- AMQShortString useridSS = headers.getUserId();
- userid.add(useridSS == null ? "null" : useridSS.toString());
-
- MessagePublishInfo info = null;
- try
- {
- if(msg instanceof AMQMessage)
- {
- info = ((AMQMessage)msg).getMessagePublishInfo();
- }
-
- }
- catch (AMQException e)
- {
- //ignore
- }
-
- if (info != null)
- {
- AMQShortString exchangeSS = info.getExchange();
- exchange.add(exchangeSS == null ? "null" : exchangeSS.toString());
-
- AMQShortString routingkeySS = info.getRoutingKey();
- routingkey.add(routingkeySS == null ? "null" : routingkeySS.toString());
-
- immediate.add(info.isImmediate() ? "true" : "false");
- mandatory.add(info.isMandatory() ? "true" : "false");
- }
-
-// msg.getPublisher(); -- only used in clustering
-// msg.getStoreContext();
-// msg.isAllContentReceived();
-
- }// if headers!=null
-
-// need to access internal map and do lookups.
-// msg.isTaken();
-// msg.getDeliveredSubscription();
-// msg.isRejectedBy();
-
- }
-
- // if id only had the header and the divider in it then we have no data to display
- if (id.size() == 2)
- {
- return null;
- }
- return data;
- }
-
- protected boolean includeMsg(ServerMessage msg, List<Long> msgids)
- {
- if (msgids == null)
- {
- return true;
- }
-
- Long msgid = msg.getMessageNumber();
-
- boolean found = false;
-
- if (msgids != null)
- {
- //check msgid is in msgids
- for (Long l : msgids)
- {
- if (l.equals(msgid))
- {
- found = true;
- break;
- }
- }
- }
- return found;
- }
-
- public enum Columns
- {
- ID,
- Size,
- Exchange,
- RoutingKey,
- isImmediate,
- isMandatory,
- isPersistent,
- isRedelivered,
- isDelivered,
- App_ID,
- Cluster_ID,
- Content_Type,
- Correlation_ID,
- Delivery_Mode,
- Encoding,
- Arrival,
- Expiration,
- Priority,
- Property_Flag,
- ReplyTo,
- Timestamp,
- Type,
- UserID,
- MsgHeaders
- }
-}
-
-
diff --git a/java/broker/src/main/java/org/apache/qpid/tools/security/Passwd.java b/java/broker/src/main/java/org/apache/qpid/tools/security/Passwd.java
deleted file mode 100644
index c27c52eb8e..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/tools/security/Passwd.java
+++ /dev/null
@@ -1,81 +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.tools.security;
-
-import org.apache.commons.codec.binary.Base64;
-
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-import java.security.DigestException;
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.PrintStream;
-
-public class Passwd
-{
- public static void main(String args[]) throws NoSuchAlgorithmException, DigestException, IOException
- {
- if (args.length != 2)
- {
- System.out.println("Passwd <username> <password>");
- System.exit(0);
- }
-
- byte[] data = args[1].getBytes("utf-8");
-
- MessageDigest md = MessageDigest.getInstance("MD5");
-
- for (byte b : data)
- {
- md.update(b);
- }
-
- byte[] digest = md.digest();
-
- Base64 b64 = new Base64();
-
- byte[] encoded = b64.encode(digest);
-
- output(args[0], encoded);
- }
-
- private static void output(String user, byte[] encoded) throws IOException
- {
-
-// File passwdFile = new File("qpid.passwd");
-
- PrintStream ps = new PrintStream(System.out);
-
- user += ":";
- ps.write(user.getBytes("utf-8"));
-
- for (byte b : encoded)
- {
- ps.write(b);
- }
-
- ps.println();
-
- ps.flush();
- ps.close();
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/tools/utils/CommandParser.java b/java/broker/src/main/java/org/apache/qpid/tools/utils/CommandParser.java
deleted file mode 100644
index 986fea32cc..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/tools/utils/CommandParser.java
+++ /dev/null
@@ -1,51 +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.tools.utils;
-
-public interface CommandParser
-{
- /**
- * If there is more than one command received on the last parse request.
- *
- * Subsequent calls to parse will utilise this input rather than reading new data from the input source
- * @return boolean
- */
- boolean more();
-
- /**
- * True if the currently parsed command has been requested as a background operation
- *
- * @return boolean
- */
- boolean isBackground();
-
- /**
- * Parses user commands, and groups tokens in the
- * String[] format that all Java main's love.
- *
- * If more than one command is provided in one input line then the more() method will return true.
- * A subsequent call to parse() will continue to parse that input line before reading new input.
- *
- * @return <code>input</code> split in args[] format; null if eof.
- * @throws java.io.IOException if there is a problem reading from the input stream
- */
- String[] parse() throws java.io.IOException;
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/tools/utils/Console.java b/java/broker/src/main/java/org/apache/qpid/tools/utils/Console.java
deleted file mode 100644
index cf457d1ea5..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/tools/utils/Console.java
+++ /dev/null
@@ -1,90 +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.tools.utils;
-
-import java.util.List;
-
-public interface Console
-{
- public enum CellFormat
- {
- CENTRED, LEFT, RIGHT
- }
-
- public static String ROW_DIVIDER = "*divider";
-
- public void print(String... message);
-
- public void println(String... message);
-
- public String readln();
-
- /**
- * Reads and parses the command line.
- *
- *
- * @return The next command or null
- */
- public String[] readCommand();
-
- public CommandParser getCommandParser();
-
- public void setCommandParser(CommandParser parser);
-
- /**
- *
- * Prints the list of String nicely.
- *
- * +-------------+
- * | Heading |
- * +-------------+
- * | Item 1 |
- * | Item 2 |
- * | Item 3 |
- * +-------------+
- *
- * @param hasTitle should list[0] be used as a heading
- * @param list The list of Strings to display
- */
- public void displayList(boolean hasTitle, String... list);
-
- /**
- *
- * Prints the list of String nicely.
- *
- * +----------------------------+
- * | Heading |
- * +----------------------------+
- * | title | title | ..
- * +----------------------------+
- * | Item 2 | value 2 | ..
- * +----------------------------+ (*divider)
- * | Item 3 | value 2 | ..
- * +----------------------------+
- *
- * @param title The title to display if any
- * @param entries the entries to display in a map.
- */
- void printMap(String title, List<List> entries);
-
-
- public void close();
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/tools/utils/SimpleCommandParser.java b/java/broker/src/main/java/org/apache/qpid/tools/utils/SimpleCommandParser.java
deleted file mode 100644
index 09444ccdd7..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/tools/utils/SimpleCommandParser.java
+++ /dev/null
@@ -1,121 +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.tools.utils;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.util.StringTokenizer;
-
-public class SimpleCommandParser implements CommandParser
-{
- private static final String COMMAND_SEPERATOR = ";";
-
- /** Input source of commands */
- protected BufferedReader _reader;
-
- /** The next list of commands from the command line */
- private StringBuilder _nextCommand = null;
-
- public SimpleCommandParser(BufferedReader reader)
- {
- _reader = reader;
- }
-
- public boolean more()
- {
- return _nextCommand != null;
- }
-
- public boolean isBackground()
- {
- return false;
- }
-
- public String[] parse() throws IOException
- {
- String[] commands = null;
-
- String input = null;
-
- if (_nextCommand == null)
- {
- input = _reader.readLine();
- }
- else
- {
- input = _nextCommand.toString();
- _nextCommand = null;
- }
-
- if (input == null)
- {
- return null;
- }
-
- StringTokenizer tok = new StringTokenizer(input, " ");
-
- int tokenCount = tok.countTokens();
- int index = 0;
-
- if (tokenCount > 0)
- {
- commands = new String[tokenCount];
- boolean commandComplete = false;
-
- while (tok.hasMoreTokens())
- {
- String next = tok.nextToken();
-
- if (next.equals(COMMAND_SEPERATOR))
- {
- commandComplete = true;
- _nextCommand = new StringBuilder();
- continue;
- }
-
- if (commandComplete)
- {
- _nextCommand.append(next);
- _nextCommand.append(" ");
- }
- else
- {
- commands[index] = next;
- index++;
- }
- }
-
- }
-
- //Reduce the String[] if not all the tokens were used in this command.
- // i.e. there is more than one command on the line.
- if (index != tokenCount)
- {
- String[] shortCommands = new String[index];
- System.arraycopy(commands, 0, shortCommands, 0, index);
- return shortCommands;
- }
- else
- {
- return commands;
- }
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/tools/utils/SimpleConsole.java b/java/broker/src/main/java/org/apache/qpid/tools/utils/SimpleConsole.java
deleted file mode 100644
index 2791a39f92..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/tools/utils/SimpleConsole.java
+++ /dev/null
@@ -1,364 +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.tools.utils;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.io.BufferedReader;
-import java.io.BufferedWriter;
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.LinkedList;
-import java.util.List;
-
-public class SimpleConsole implements Console
-{
- /** SLF4J Logger. */
- private static Logger _devlog = LoggerFactory.getLogger(SimpleConsole.class);
-
- /** Console Writer. */
- protected BufferedWriter _consoleWriter;
-
- /** Console Reader. */
- protected BufferedReader _consoleReader;
-
- /** Parser for command-line input. */
- protected CommandParser _parser;
-
- public SimpleConsole(BufferedWriter writer, BufferedReader reader)
- {
- _consoleWriter = writer;
- _consoleReader = reader;
- _parser = new SimpleCommandParser(_consoleReader);
- }
-
- public void print(String... message)
- {
- try
- {
- for (String s : message)
- {
- _consoleWriter.write(s);
- }
- _consoleWriter.flush();
- }
- catch (IOException e)
- {
- _devlog.error(e.getMessage() + ": Occurred whilst trying to write:" + Arrays.asList(message));
- }
-
- }
-
- public void println(String... message)
- {
- print(message);
- print(System.getProperty("line.separator"));
- }
-
-
- public String readln()
- {
- try
- {
- return _consoleReader.readLine();
- }
- catch (IOException e)
- {
- _devlog.debug("Unable to read input due to:" + e.getMessage());
- return null;
- }
- }
-
- public String[] readCommand()
- {
- try
- {
- return _parser.parse();
- }
- catch (IOException e)
- {
- _devlog.error("Error reading command:" + e.getMessage());
- return new String[0];
- }
- }
-
- public CommandParser getCommandParser()
- {
- return _parser;
- }
-
- public void setCommandParser(CommandParser parser)
- {
- _parser = parser;
- }
-
- public void displayList(boolean hasTitle, String... list)
- {
- java.util.List<java.util.List> data = new LinkedList<List>();
-
- java.util.List<String> values = new LinkedList<String>();
-
- data.add(values);
-
- for (String value : list)
- {
- values.add(value);
- }
-
- if (hasTitle)
- {
- values.add(1, "*divider");
- }
-
- printMap(null, data);
- }
-
- /**
- *
- * Prints the list of String nicely.
- *
- * +----------------------------+
- * | Heading |
- * +----------------------------+
- * | title | title | ..
- * +----------------------------+
- * | Item 2 | value 2 | ..
- * | Item 3 | value 2 | ..
- * +----------------------------+
- *
- * @param title The title to display if any
- * @param entries the entries to display in a map.
- */
- public void printMap(String title, java.util.List<java.util.List> entries)
- {
- try
- {
- int columns = entries.size();
-
- int[] columnWidth = new int[columns];
-
- // calculate row count
- int rowMax = 0;
-
- //the longest item
- int itemMax = 0;
-
- for (int i = 0; i < columns; i++)
- {
- int columnIRowMax = entries.get(i).size();
-
- if (columnIRowMax > rowMax)
- {
- rowMax = columnIRowMax;
- }
- for (Object values : entries.get(i))
- {
- if (values.toString().equals(Console.ROW_DIVIDER))
- {
- continue;
- }
-
- int itemLength = values.toString().length();
-
- //note for single width
- if (itemLength > itemMax)
- {
- itemMax = itemLength;
- }
-
- //note for mulit width
- if (itemLength > columnWidth[i])
- {
- columnWidth[i] = itemLength;
- }
-
- }
- }
-
- int tableWidth = 0;
-
-
- for (int i = 0; i < columns; i++)
- {
- // plus 2 for the space padding
- columnWidth[i] += 2;
- }
- for (int size : columnWidth)
- {
- tableWidth += size;
- }
- tableWidth += (columns - 1);
-
- if (title != null)
- {
- if (title.length() > tableWidth)
- {
- tableWidth = title.length();
- }
-
- printCellRow("+", "-", tableWidth);
-
- printCell(CellFormat.CENTRED, "|", tableWidth, " " + title + " ", 0);
- _consoleWriter.newLine();
-
- }
-
- //put top line | or bottom of title
- printCellRow("+", "-", tableWidth);
-
- //print the table data
- int row = 0;
-
- for (; row < rowMax; row++)
- {
- for (int i = 0; i < columns; i++)
- {
- java.util.List columnData = entries.get(i);
-
- String value;
- // does this column have a value for this row
- if (columnData.size() > row)
- {
- value = " " + columnData.get(row).toString() + " ";
- }
- else
- {
- value = " ";
- }
-
- if (i == 0 && value.equals(" " + Console.ROW_DIVIDER + " "))
- {
- printCellRow("+", "-", tableWidth);
- //move on to the next row
- break;
- }
- else
- {
- printCell(CellFormat.LEFT, "|", columnWidth[i], value, i);
- }
-
- // if it is the last row then do a new line.
- if (i == columns - 1)
- {
- _consoleWriter.newLine();
- }
- }
- }
-
- printCellRow("+", "-", tableWidth);
-
- }
- catch (IOException e)
- {
- _devlog.error(e.getMessage() + ": Occured whilst trying to write.");
- }
- }
-
- public void close()
- {
-
- try
- {
- _consoleReader.close();
- }
- catch (IOException e)
- {
- _devlog.error(e.getMessage() + ": Occured whilst trying to close reader.");
- }
-
- try
- {
-
- _consoleWriter.close();
- }
- catch (IOException e)
- {
- _devlog.error(e.getMessage() + ": Occured whilst trying to close writer.");
- }
-
- }
-
- private void printCell(CellFormat format, String edge, int cellWidth, String cell, int column) throws IOException
- {
- int pad = cellWidth - cell.length();
-
- if (column == 0)
- {
- _consoleWriter.write(edge);
- }
-
- switch (format)
- {
- case CENTRED:
- printPad(" ", pad / 2);
- break;
- case RIGHT:
- printPad(" ", pad);
- break;
- }
-
- _consoleWriter.write(cell);
-
-
- switch (format)
- {
- case CENTRED:
- // if pad isn't even put the extra one on the right
- if (pad % 2 == 0)
- {
- printPad(" ", pad / 2);
- }
- else
- {
- printPad(" ", (pad / 2) + 1);
- }
- break;
- case LEFT:
- printPad(" ", pad);
- break;
- }
-
-
- _consoleWriter.write(edge);
-
- }
-
- private void printCellRow(String edge, String mid, int cellWidth) throws IOException
- {
- _consoleWriter.write(edge);
-
- printPad(mid, cellWidth);
-
- _consoleWriter.write(edge);
- _consoleWriter.newLine();
- }
-
- private void printPad(String padChar, int count) throws IOException
- {
- for (int i = 0; i < count; i++)
- {
- _consoleWriter.write(padChar);
- }
- }
-
-
-}
diff --git a/java/broker/src/test/java/org/apache/log4j/xml/QpidLog4JConfiguratorTest.java b/java/broker/src/test/java/org/apache/log4j/xml/QpidLog4JConfiguratorTest.java
deleted file mode 100644
index 445c7d57f2..0000000000
--- a/java/broker/src/test/java/org/apache/log4j/xml/QpidLog4JConfiguratorTest.java
+++ /dev/null
@@ -1,396 +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.log4j.xml;
-
-
-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");
-
- private File _testConfigFile;
-
- private File createTempTestLog4JConfig(String loggerLevel,String rootLoggerLevel, boolean missingTagClose, boolean incorrectAttribute)
- {
- File tmpFile = null;
- try
- {
- tmpFile = File.createTempFile("QpidLog4JConfiguratorTestLog4jConfig", ".tmp");
- tmpFile.deleteOnExit();
-
- FileWriter fstream = new FileWriter(tmpFile);
- BufferedWriter writer = new BufferedWriter(fstream);
-
- writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+NEWLINE);
- writer.write("<!DOCTYPE log4j:configuration SYSTEM \"log4j.dtd\">"+NEWLINE);
-
- writer.write("<log4j:configuration xmlns:log4j=\"http://jakarta.apache.org/log4j/\" debug=\"null\" " +
- "threshold=\"null\">"+NEWLINE);
-
- writer.write(" <appender class=\"org.apache.log4j.ConsoleAppender\" name=\"STDOUT\">"+NEWLINE);
- writer.write(" <layout class=\"org.apache.log4j.PatternLayout\">"+NEWLINE);
- writer.write(" <param name=\"ConversionPattern\" value=\"%d %-5p [%t] %C{2} (%F:%L) - %m%n\"/>"+NEWLINE);
- writer.write(" </layout>"+NEWLINE);
- writer.write(" </appender>"+NEWLINE);
-
- String closeTag="/";
- if(missingTagClose)
- {
- closeTag="";
- }
-
- //Example of a 'category' with a 'priority'
- writer.write(" <category additivity=\"true\" name=\"logger1\">"+NEWLINE);
- writer.write(" <priority value=\"" + loggerLevel+ "\"" + closeTag + ">"+NEWLINE);
- writer.write(" <appender-ref ref=\"STDOUT\"/>"+NEWLINE);
- writer.write(" </category>"+NEWLINE);
-
- String attributeName="value";
- if(incorrectAttribute)
- {
- attributeName="values";
- }
-
- //Example of a 'category' with a 'level'
- writer.write(" <category additivity=\"true\" name=\"logger2\">"+NEWLINE);
- writer.write(" <level " + attributeName + "=\"" + loggerLevel+ "\"/>"+NEWLINE);
- writer.write(" <appender-ref ref=\"STDOUT\"/>"+NEWLINE);
- writer.write(" </category>"+NEWLINE);
-
- //Example of a 'logger' with a 'level'
- writer.write(" <logger additivity=\"true\" name=\"logger3\">"+NEWLINE);
- writer.write(" <level value=\"" + loggerLevel+ "\"/>"+NEWLINE);
- writer.write(" <appender-ref ref=\"STDOUT\"/>"+NEWLINE);
- writer.write(" </logger>"+NEWLINE);
-
- //'root' logger
- writer.write(" <root>"+NEWLINE);
- writer.write(" <priority value=\"" + rootLoggerLevel+ "\"/>"+NEWLINE);
- writer.write(" <appender-ref ref=\"STDOUT\"/>"+NEWLINE);
- writer.write(" </root>"+NEWLINE);
-
- writer.write("</log4j:configuration>"+NEWLINE);
-
- writer.flush();
- writer.close();
- }
- catch (IOException e)
- {
- fail("Unable to create temporary test log4j configuration");
- }
-
- return tmpFile;
- }
-
-
-
- //******* Test Methods ******* //
-
- public void testCheckLevelsAndStrictParser()
- {
- //try the valid logger levels
- _testConfigFile = createTempTestLog4JConfig("all", "info", false, false);
- try
- {
- QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath());
- }
- catch (Exception e)
- {
- fail("No exception expected, valid levels and xml were used");
- }
-
- _testConfigFile = createTempTestLog4JConfig("trace", "info", false, false);
- try
- {
- QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath());
- }
- catch (Exception e)
- {
- fail("No exception expected, valid levels and xml were used");
- }
-
- _testConfigFile = createTempTestLog4JConfig("debug", "info", false, false);
- try
- {
- QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath());
- }
- catch (Exception e)
- {
- fail("No exception expected, valid levels and xml were used");
- }
-
- _testConfigFile = createTempTestLog4JConfig("info", "info", false, false);
- try
- {
- QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath());
- }
- catch (Exception e)
- {
- fail("No exception expected, valid levels and xml were used");
- }
-
- _testConfigFile = createTempTestLog4JConfig("warn", "info", false, false);
- try
- {
- QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath());
- }
- catch (Exception e)
- {
- fail("No exception expected, valid levels and xml were used");
- }
-
- _testConfigFile = createTempTestLog4JConfig("error", "info", false, false);
- try
- {
- QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath());
- }
- catch (Exception e)
- {
- fail("No exception expected, valid levels and xml were used");
- }
-
- _testConfigFile = createTempTestLog4JConfig("fatal", "info", false, false);
- try
- {
- QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath());
- }
- catch (Exception e)
- {
- fail("No exception expected, valid levels and xml were used");
- }
-
- _testConfigFile = createTempTestLog4JConfig("off", "info", false, false);
- try
- {
- QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath());
- }
- catch (Exception e)
- {
- fail("No exception expected, valid levels and xml were used");
- }
-
- _testConfigFile = createTempTestLog4JConfig("null", "info", false, false);
- try
- {
- QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath());
- }
- catch (Exception e)
- {
- fail("No exception expected, valid levels and xml were used");
- }
-
- _testConfigFile = createTempTestLog4JConfig("inherited", "info", false, false);
- try
- {
- QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath());
- }
- catch (Exception e)
- {
- fail("No exception expected, valid levels and xml were used");
- }
-
- //now try an invalid logger level
- _testConfigFile = createTempTestLog4JConfig("madeup", "info", false, false);
- try
- {
- QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath());
- fail("IllegalLoggerLevelException expected, invalid levels used");
- }
- catch (IllegalLoggerLevelException e)
- {
- //expected, ignore
- }
- catch (IOException e)
- {
- fail("Incorrect Exception, expected an IllegalLoggerLevelException");
- }
-
-
-
- //now try the valid rootLogger levels
- _testConfigFile = createTempTestLog4JConfig("info", "all", false, false);
- try
- {
- QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath());
- }
- catch (Exception e)
- {
- fail("No exception expected, valid levels and xml were used");
- }
-
- _testConfigFile = createTempTestLog4JConfig("info", "trace", false, false);
- try
- {
- QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath());
- }
- catch (Exception e)
- {
- fail("No exception expected, valid levels and xml were used");
- }
-
- _testConfigFile = createTempTestLog4JConfig("info", "debug", false, false);
- try
- {
- QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath());
- }
- catch (Exception e)
- {
- fail("No exception expected, valid levels and xml were used");
- }
-
- _testConfigFile = createTempTestLog4JConfig("info", "info", false, false);
- try
- {
- QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath());
- }
- catch (Exception e)
- {
- fail("No exception expected, valid levels and xml were used");
- }
-
- _testConfigFile = createTempTestLog4JConfig("info", "warn", false, false);
- try
- {
- QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath());
- }
- catch (Exception e)
- {
- fail("No exception expected, valid levels and xml were used");
- }
-
- _testConfigFile = createTempTestLog4JConfig("info", "error", false, false);
- try
- {
- QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath());
- }
- catch (Exception e)
- {
- fail("No exception expected, valid levels and xml were used");
- }
-
- _testConfigFile = createTempTestLog4JConfig("info", "fatal", false, false);
- try
- {
- QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath());
- }
- catch (Exception e)
- {
- fail("No exception expected, valid levels and xml were used");
- }
-
- _testConfigFile = createTempTestLog4JConfig("info", "off", false, false);
- try
- {
- QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath());
- }
- catch (Exception e)
- {
- fail("No exception expected, valid levels and xml were used");
- }
-
- _testConfigFile = createTempTestLog4JConfig("info", "null", false, false);
- try
- {
- QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath());
- }
- catch (Exception e)
- {
- fail("No exception expected, valid levels and xml were used");
- }
-
- _testConfigFile = createTempTestLog4JConfig("info", "inherited", false, false);
- try
- {
- QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath());
- }
- catch (Exception e)
- {
- fail("No exception expected, valid levels and xml were used");
- }
-
- _testConfigFile = createTempTestLog4JConfig("info", "debug", false, false);
- try
- {
- QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath());
- }
- catch (Exception e)
- {
- fail("No exception expected, valid levels and xml were used");
- }
-
- //now try an invalid logger level
- _testConfigFile = createTempTestLog4JConfig("info", "madeup", false, false);
- try
- {
- QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath());
- fail("IllegalLoggerLevelException expected, invalid levels used");
- }
- catch (IllegalLoggerLevelException e)
- {
- //expected, ignore
- }
- catch (IOException e)
- {
- fail("Incorrect Exception, expected an IllegalLoggerLevelException");
- }
-
-
-
- //now try invalid xml
- _testConfigFile = createTempTestLog4JConfig("info", "info", true, false);
- try
- {
- QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath());
- fail("IOException expected, malformed XML used");
- }
- catch (IllegalLoggerLevelException e)
- {
- fail("Incorrect Exception, expected an IOException");
- }
- catch (IOException e)
- {
- //expected, ignore
- }
-
- _testConfigFile = createTempTestLog4JConfig("info", "info", false, true);
- try
- {
- QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath());
- fail("IOException expected, malformed XML used");
- }
- catch (IllegalLoggerLevelException e)
- {
- //expected, ignore
- }
- catch (IOException e)
- {
- fail("Incorrect Exception, expected an IllegalLoggerLevelException");
- }
- }
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/AMQBrokerManagerMBeanTest.java b/java/broker/src/test/java/org/apache/qpid/server/AMQBrokerManagerMBeanTest.java
deleted file mode 100644
index 6c135e8ba7..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/AMQBrokerManagerMBeanTest.java
+++ /dev/null
@@ -1,94 +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;
-
-import junit.framework.TestCase;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.management.common.mbeans.ManagedBroker;
-import org.apache.qpid.server.exchange.ExchangeRegistry;
-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.util.InternalBrokerBaseCase;
-import org.apache.qpid.server.virtualhost.VirtualHostImpl;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-
-public class AMQBrokerManagerMBeanTest extends InternalBrokerBaseCase
-{
- private QueueRegistry _queueRegistry;
- private ExchangeRegistry _exchangeRegistry;
- private VirtualHost _vHost;
-
- public void testExchangeOperations() throws Exception
- {
- String exchange1 = "testExchange1_" + System.currentTimeMillis();
- String exchange2 = "testExchange2_" + System.currentTimeMillis();
- String exchange3 = "testExchange3_" + System.currentTimeMillis();
-
- assertTrue(_exchangeRegistry.getExchange(new AMQShortString(exchange1)) == null);
- assertTrue(_exchangeRegistry.getExchange(new AMQShortString(exchange2)) == null);
- assertTrue(_exchangeRegistry.getExchange(new AMQShortString(exchange3)) == null);
-
-
- ManagedBroker mbean = new AMQBrokerManagerMBean((VirtualHostImpl.VirtualHostMBean) _vHost.getManagedObject());
- mbean.createNewExchange(exchange1, "direct", false);
- mbean.createNewExchange(exchange2, "topic", false);
- mbean.createNewExchange(exchange3, "headers", false);
-
- assertTrue(_exchangeRegistry.getExchange(new AMQShortString(exchange1)) != null);
- assertTrue(_exchangeRegistry.getExchange(new AMQShortString(exchange2)) != null);
- assertTrue(_exchangeRegistry.getExchange(new AMQShortString(exchange3)) != null);
-
- mbean.unregisterExchange(exchange1);
- mbean.unregisterExchange(exchange2);
- mbean.unregisterExchange(exchange3);
-
- assertTrue(_exchangeRegistry.getExchange(new AMQShortString(exchange1)) == null);
- assertTrue(_exchangeRegistry.getExchange(new AMQShortString(exchange2)) == null);
- assertTrue(_exchangeRegistry.getExchange(new AMQShortString(exchange3)) == null);
- }
-
- public void testQueueOperations() throws Exception
- {
- String queueName = "testQueue_" + System.currentTimeMillis();
-
- ManagedBroker mbean = new AMQBrokerManagerMBean((VirtualHostImpl.VirtualHostMBean) _vHost.getManagedObject());
-
- assertTrue(_queueRegistry.getQueue(new AMQShortString(queueName)) == null);
-
- mbean.createNewQueue(queueName, "test", false);
- assertTrue(_queueRegistry.getQueue(new AMQShortString(queueName)) != null);
-
- mbean.deleteQueue(queueName);
- assertTrue(_queueRegistry.getQueue(new AMQShortString(queueName)) == null);
- }
-
- @Override
- public void setUp() throws Exception
- {
- super.setUp();
- IApplicationRegistry appRegistry = ApplicationRegistry.getInstance();
- _vHost = appRegistry.getVirtualHostRegistry().getVirtualHost("test");
- _queueRegistry = _vHost.getQueueRegistry();
- _exchangeRegistry = _vHost.getExchangeRegistry();
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/ExtractResendAndRequeueTest.java b/java/broker/src/test/java/org/apache/qpid/server/ExtractResendAndRequeueTest.java
deleted file mode 100644
index d2408ba21f..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/ExtractResendAndRequeueTest.java
+++ /dev/null
@@ -1,255 +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;
-
-import junit.framework.TestCase;
-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.queue.AMQQueue;
-import org.apache.qpid.server.queue.MockAMQQueue;
-import org.apache.qpid.server.message.AMQMessage;
-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.store.MemoryMessageStore;
-import org.apache.qpid.server.store.MessageStore;
-import org.apache.qpid.AMQException;
-
-import java.util.Map;
-import java.util.LinkedHashMap;
-import java.util.LinkedList;
-
-/**
- * QPID-1385 : Race condition between added to unacked map and resending due to a rollback.
- *
- * In AMQChannel _unackedMap.clear() was done after the visit. This meant that the clear was not in the same
- * synchronized block as as the preparation to resend.
- *
- * This clearing/prep for resend was done as a result of the rollback call. HOWEVER, the delivery thread was still
- * in the process of sending messages to the client. It is therefore possible that a message could block on the
- * _unackedMap lock waiting for the visit to compelete so that it can add the new message to the unackedMap....
- * which is then cleared by the resend/rollback thread.
- *
- * This problem was encountered by the testSend2ThenRollback test.
- *
- * To try and increase the chance of the race condition occuring this test will send multiple messages so that the
- * delivery thread will be in progress while the rollback method is called. Hopefully this will cause the
- * deliveryTag to be lost
- */
-public class ExtractResendAndRequeueTest extends TestCase
-{
-
- UnacknowledgedMessageMapImpl _unacknowledgedMessageMap;
- private static final int INITIAL_MSG_COUNT = 10;
- private AMQQueue _queue = new MockAMQQueue(getName());
- private MessageStore _messageStore = new MemoryMessageStore();
- private LinkedList<QueueEntry> _referenceList = new LinkedList<QueueEntry>();
-
- @Override
- public void setUp() throws AMQException
- {
- _unacknowledgedMessageMap = new UnacknowledgedMessageMapImpl(100);
-
- long id = 0;
- SimpleQueueEntryList list = new SimpleQueueEntryList(_queue);
-
- // Add initial messages to QueueEntryList
- for (int count = 0; count < INITIAL_MSG_COUNT; count++)
- {
- AMQMessage msg = new MockAMQMessage(id);
-
- list.add(msg);
-
- //Increment ID;
- id++;
- }
-
- // Iterate through the QueueEntryList and add entries to unacknowledgeMessageMap and referecenList
- QueueEntryIterator queueEntries = list.iterator();
- while(queueEntries.advance())
- {
- QueueEntry entry = queueEntries.getNode();
- _unacknowledgedMessageMap.add(entry.getMessage().getMessageNumber(), entry);
-
- // Store the entry for future inspection
- _referenceList.add(entry);
- }
-
- assertEquals("Map does not contain correct setup data", INITIAL_MSG_COUNT, _unacknowledgedMessageMap.size());
- }
-
- /**
- * Helper method to create a new subscription and aquire the given messages.
- *
- * @param messageList The messages to aquire
- *
- * @return Subscription that performed the aquire
- */
- private Subscription createSubscriptionAndAquireMessages(LinkedList<QueueEntry> messageList)
- {
- Subscription subscription = new MockSubscription();
-
- // Aquire messages in subscription
- for (QueueEntry entry : messageList)
- {
- entry.acquire(subscription);
- }
-
- return subscription;
- }
-
- /**
- * This is the normal consumer rollback method.
- *
- * An active consumer that has aquired messages expects those messasges to be reset when rollback is requested.
- *
- * This test validates that the msgToResend map includes all the messages and none are left behind.
- *
- * @throws AMQException the visit interface throws this
- */
- public void testResend() throws AMQException
- {
- //We don't need the subscription object here.
- createSubscriptionAndAquireMessages(_referenceList);
-
- final Map<Long, QueueEntry> msgToRequeue = new LinkedHashMap<Long, QueueEntry>();
- final Map<Long, QueueEntry> msgToResend = new LinkedHashMap<Long, QueueEntry>();
-
- // requeueIfUnabletoResend doesn't matter here.
- _unacknowledgedMessageMap.visit(new ExtractResendAndRequeue(_unacknowledgedMessageMap, msgToRequeue,
- msgToResend, true, _messageStore));
-
- assertEquals("Message count for resend not correct.", INITIAL_MSG_COUNT, msgToResend.size());
- assertEquals("Message count for requeue not correct.", 0, msgToRequeue.size());
- assertEquals("Map was not emptied", 0, _unacknowledgedMessageMap.size());
- }
-
- /**
- * This is the normal consumer close method.
- *
- * When a consumer that has aquired messages expects closes the messages that it has aquired should be removed from
- * the unacknowledgeMap and placed in msgToRequeue
- *
- * This test validates that the msgToRequeue map includes all the messages and none are left behind.
- *
- * @throws AMQException the visit interface throws this
- */
- public void testRequeueDueToSubscriptionClosure() throws AMQException
- {
- Subscription subscription = createSubscriptionAndAquireMessages(_referenceList);
-
- // Close subscription
- subscription.close();
-
- final Map<Long, QueueEntry> msgToRequeue = new LinkedHashMap<Long, QueueEntry>();
- final Map<Long, QueueEntry> msgToResend = new LinkedHashMap<Long, QueueEntry>();
-
- // requeueIfUnabletoResend doesn't matter here.
- _unacknowledgedMessageMap.visit(new ExtractResendAndRequeue(_unacknowledgedMessageMap, msgToRequeue,
- msgToResend, true, _messageStore));
-
- assertEquals("Message count for resend not correct.", 0, msgToResend.size());
- assertEquals("Message count for requeue not correct.", INITIAL_MSG_COUNT, msgToRequeue.size());
- assertEquals("Map was not emptied", 0, _unacknowledgedMessageMap.size());
- }
-
- /**
- * If the subscription is null, due to message being retrieved via a GET, And we request that messages are requeued
- * requeueIfUnabletoResend(set to true) then all messages should be sent to the msgToRequeue map.
- *
- * @throws AMQException the visit interface throws this
- */
-
- public void testRequeueDueToMessageHavingNoConsumerTag() throws AMQException
- {
- final Map<Long, QueueEntry> msgToRequeue = new LinkedHashMap<Long, QueueEntry>();
- final Map<Long, QueueEntry> msgToResend = new LinkedHashMap<Long, QueueEntry>();
-
- // requeueIfUnabletoResend = true so all messages should go to msgToRequeue
- _unacknowledgedMessageMap.visit(new ExtractResendAndRequeue(_unacknowledgedMessageMap, msgToRequeue,
- msgToResend, true, _messageStore));
-
- assertEquals("Message count for resend not correct.", 0, msgToResend.size());
- assertEquals("Message count for requeue not correct.", INITIAL_MSG_COUNT, msgToRequeue.size());
- assertEquals("Map was not emptied", 0, _unacknowledgedMessageMap.size());
- }
-
- /**
- * If the subscription is null, due to message being retrieved via a GET, And we request that we don't
- * requeueIfUnabletoResend(set to false) then all messages should be dropped as we do not have a dead letter queue.
- *
- * @throws AMQException the visit interface throws this
- */
-
- public void testDrop() throws AMQException
- {
- final Map<Long, QueueEntry> msgToRequeue = new LinkedHashMap<Long, QueueEntry>();
- final Map<Long, QueueEntry> msgToResend = new LinkedHashMap<Long, QueueEntry>();
-
- // requeueIfUnabletoResend = false so all messages should be dropped all maps should be empty
- _unacknowledgedMessageMap.visit(new ExtractResendAndRequeue(_unacknowledgedMessageMap, msgToRequeue,
- msgToResend, false, _messageStore));
-
- assertEquals("Message count for resend not correct.", 0, msgToResend.size());
- assertEquals("Message count for requeue not correct.", 0, msgToRequeue.size());
- assertEquals("Map was not emptied", 0, _unacknowledgedMessageMap.size());
-
-
- for (QueueEntry entry : _referenceList)
- {
- assertTrue("Message was not discarded", entry.isDeleted());
- }
-
- }
-
- /**
- * If the subscription is null, due to message being retrieved via a GET, AND the queue upon which the message was
- * delivered has been deleted then it is not possible to requeue. Currently we simply discar the message but in the
- * future we may wish to dead letter the message.
- *
- * Validate that at the end of the visit all Maps are empty and all messages are marked as deleted
- *
- * @throws AMQException the visit interface throws this
- */
- public void testDiscard() throws AMQException
- {
- final Map<Long, QueueEntry> msgToRequeue = new LinkedHashMap<Long, QueueEntry>();
- final Map<Long, QueueEntry> msgToResend = new LinkedHashMap<Long, QueueEntry>();
-
- _queue.delete();
-
- // requeueIfUnabletoResend : value doesn't matter here as queue has been deleted
- _unacknowledgedMessageMap.visit(new ExtractResendAndRequeue(_unacknowledgedMessageMap, msgToRequeue,
- msgToResend, false, _messageStore));
-
- assertEquals("Message count for resend not correct.", 0, msgToResend.size());
- assertEquals("Message count for requeue not correct.", 0, msgToRequeue.size());
- assertEquals("Map was not emptied", 0, _unacknowledgedMessageMap.size());
-
- for (QueueEntry entry : _referenceList)
- {
- assertTrue("Message was not discarded", entry.isDeleted());
- }
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/RunBrokerWithCommand.java b/java/broker/src/test/java/org/apache/qpid/server/RunBrokerWithCommand.java
deleted file mode 100644
index 59543874b4..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/RunBrokerWithCommand.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.server;
-
-import org.apache.log4j.Logger;
-import org.apache.log4j.Level;
-
-import java.io.InputStream;
-import java.io.BufferedReader;
-import java.io.InputStreamReader;
-import java.io.IOException;
-
-public class RunBrokerWithCommand
-{
- public static void main(String[] args)
- {
- //Start the broker
- try
- {
- String[] fudge = args.clone();
-
- // Override the first value which is the command we are going to run later.
- fudge[0] = "-v";
- new Main(fudge).startup();
- }
- catch (Exception e)
- {
- System.err.println("Unable to start broker due to: " + e.getMessage());
-
- e.printStackTrace();
- exit(1);
- }
-
- Logger.getRootLogger().setLevel(Level.ERROR);
-
- //run command
- try
- {
- Process task = Runtime.getRuntime().exec(args[0]);
- System.err.println("Started Proccess: " + args[0]);
-
- InputStream inputStream = task.getInputStream();
-
- InputStream errorStream = task.getErrorStream();
-
- Thread out = new Thread(new Outputter("[OUT]", new BufferedReader(new InputStreamReader(inputStream))));
- Thread err = new Thread(new Outputter("[ERR]", new BufferedReader(new InputStreamReader(errorStream))));
-
- out.start();
- err.start();
-
- out.join();
- err.join();
-
- System.err.println("Waiting for process to exit: " + args[0]);
- task.waitFor();
- System.err.println("Done Proccess: " + args[0]);
-
- }
- catch (IOException e)
- {
- System.err.println("Proccess had problems: " + e.getMessage());
- e.printStackTrace(System.err);
- exit(1);
- }
- catch (InterruptedException e)
- {
- System.err.println("Proccess had problems: " + e.getMessage());
- e.printStackTrace(System.err);
-
- exit(1);
- }
-
-
- exit(0);
- }
-
- private static void exit(int i)
- {
- Logger.getRootLogger().setLevel(Level.INFO);
- System.exit(i);
- }
-
- static class Outputter implements Runnable
- {
-
- BufferedReader reader;
- String prefix;
-
- Outputter(String s, BufferedReader r)
- {
- prefix = s;
- reader = r;
- }
-
- public void run()
- {
- String line;
- try
- {
- while ((line = reader.readLine()) != null)
- {
- System.out.println(prefix + line);
- }
- }
- catch (IOException e)
- {
- System.out.println("Error occured reading; " + e.getMessage());
- }
- }
-
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/SelectorParserTest.java b/java/broker/src/test/java/org/apache/qpid/server/SelectorParserTest.java
deleted file mode 100644
index a0304a7b01..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/SelectorParserTest.java
+++ /dev/null
@@ -1,128 +0,0 @@
-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
- * 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 SelectorParserTest extends TestCase
-{
- public void testSelectorWithHyphen()
- {
- testPass("Cost = 2 AND \"property-with-hyphen\" = 'wibble'");
- }
-
- public void testLike()
- {
- testFail("Cost LIKE 2");
- testPass("Cost LIKE 'Hello'");
- }
-
- public void testStringQuoted()
- {
- testPass("string = 'Test'");
- }
-
- public void testProperty()
- {
- testPass("prop1 = prop2");
- }
-
- public void testPropertyNames()
- {
- testPass("$min= TRUE AND _max= FALSE AND Prop_2 = true AND prop$3 = false");
- }
-
- public void testProtected()
- {
- testFail("NULL = 0 ");
- testFail("TRUE = 0 ");
- testFail("FALSE = 0 ");
- testFail("NOT = 0 ");
- testFail("AND = 0 ");
- testFail("OR = 0 ");
- testFail("BETWEEN = 0 ");
- testFail("LIKE = 0 ");
- testFail("IN = 0 ");
- testFail("IS = 0 ");
- testFail("ESCAPE = 0 ");
- }
-
-
- public void testBoolean()
- {
- testPass("min= TRUE AND max= FALSE ");
- testPass("min= true AND max= false");
- }
-
- public void testDouble()
- {
- testPass("positive=31E2 AND negative=-31.4E3");
- testPass("min=" + Double.MIN_VALUE + " AND max=" + Double.MAX_VALUE);
- }
-
- public void testLong()
- {
- testPass("minLong=" + Long.MIN_VALUE + "L AND maxLong=" + Long.MAX_VALUE + "L");
- }
-
- public void testInt()
- {
- testPass("minInt=" + Integer.MIN_VALUE + " AND maxInt=" + Integer.MAX_VALUE);
- }
-
- public void testSigned()
- {
- testPass("negative=-42 AND positive=+42");
- }
-
- public void testOctal()
- {
- testPass("octal=042");
- }
-
-
- private void testPass(String selector)
- {
- try
- {
- new JMSSelectorFilter(selector);
- }
- catch (AMQException e)
- {
- fail("Selector '" + selector + "' was not parsed :" + e.getMessage());
- }
- }
-
- private void testFail(String selector)
- {
- try
- {
- new JMSSelectorFilter(selector);
- fail("Selector '" + selector + "' was parsed ");
- }
- catch (AMQException e)
- {
- //normal path
- }
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/ack/AcknowledgeTest.java b/java/broker/src/test/java/org/apache/qpid/server/ack/AcknowledgeTest.java
deleted file mode 100644
index b3223f16c4..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/ack/AcknowledgeTest.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.ack;
-
-
-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;
-
-public class AcknowledgeTest extends InternalBrokerBaseCase
-{
-
- public void testTransactionalSingleAck() throws AMQException
- {
- getChannel().setLocalTransactional();
- runMessageAck(1, 1, 1, false, 0);
- }
-
- public void testTransactionalMultiAck() throws AMQException
- {
- getChannel().setLocalTransactional();
- runMessageAck(10, 1, 5, true, 5);
- }
-
- public void testTransactionalAckAll() throws AMQException
- {
- getChannel().setLocalTransactional();
- runMessageAck(10, 1, 0, true, 0);
- }
-
- public void testNonTransactionalSingleAck() throws AMQException
- {
- runMessageAck(1, 1, 1, false, 0);
- }
-
- public void testNonTransactionalMultiAck() throws AMQException
- {
- runMessageAck(10, 1, 5, true, 5);
- }
-
- public void testNonTransactionalAckAll() throws AMQException
- {
- runMessageAck(10, 1, 0, true, 0);
- }
-
- protected void runMessageAck(int sendMessageCount, long firstDeliveryTag, long acknowledgeDeliveryTag, boolean acknowldegeMultiple, int remainingUnackedMessages) throws AMQException
- {
- //Check store is empty
- checkStoreContents(0);
-
- //Send required messsages to the queue
- publishMessages(getSession(), getChannel(), sendMessageCount);
-
- if (getChannel().isTransactional())
- {
- getChannel().commit();
- }
-
- //Ensure they are stored
- checkStoreContents(sendMessageCount);
-
- //Check that there are no unacked messages
- assertEquals("Channel should have no unacked msgs ", 0, getChannel().getUnacknowledgedMessageMap().size());
-
- //Subscribe to the queue
- AMQShortString subscriber = subscribe(getSession(), getChannel(), getQueue());
-
- getQueue().deliverAsync();
-
- //Wait for the messages to be delivered
- getSession().awaitDelivery(sendMessageCount);
-
- //Check that they are all waiting to be acknoledged
- assertEquals("Channel should have unacked msgs", sendMessageCount, getChannel().getUnacknowledgedMessageMap().size());
-
- List<InternalTestProtocolSession.DeliveryPair> messages = getSession().getDelivers(getChannel().getChannelId(), subscriber, sendMessageCount);
-
- //Double check we received the right number of messages
- assertEquals(sendMessageCount, messages.size());
-
- //Check that the first message has the expected deliveryTag
- assertEquals("First message does not have expected deliveryTag", firstDeliveryTag, messages.get(0).getDeliveryTag());
-
- //Send required Acknowledgement
- getChannel().acknowledgeMessage(acknowledgeDeliveryTag, acknowldegeMultiple);
-
- if (getChannel().isTransactional())
- {
- getChannel().commit();
- }
-
- // Check Remaining Acknowledgements
- assertEquals("Channel unacked msgs count incorrect", remainingUnackedMessages, getChannel().getUnacknowledgedMessageMap().size());
-
- //Check store contents are also correct.
- checkStoreContents(remainingUnackedMessages);
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/configuration/QueueConfigurationTest.java b/java/broker/src/test/java/org/apache/qpid/server/configuration/QueueConfigurationTest.java
deleted file mode 100644
index d2f2ae5eea..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/configuration/QueueConfigurationTest.java
+++ /dev/null
@@ -1,145 +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.configuration;
-
-import junit.framework.TestCase;
-import org.apache.commons.configuration.CompositeConfiguration;
-import org.apache.commons.configuration.ConfigurationException;
-import org.apache.commons.configuration.PropertiesConfiguration;
-
-public class QueueConfigurationTest extends TestCase
-{
-
- private VirtualHostConfiguration _emptyConf;
- private PropertiesConfiguration _env;
- private VirtualHostConfiguration _fullHostConf;
-
- public void setUp() throws Exception
- {
- _env = new PropertiesConfiguration();
- _emptyConf = new VirtualHostConfiguration("test", _env);
-
- PropertiesConfiguration fullEnv = new PropertiesConfiguration();
- fullEnv.setProperty("queues.maximumMessageAge", 1);
- fullEnv.setProperty("queues.maximumQueueDepth", 1);
- fullEnv.setProperty("queues.maximumMessageSize", 1);
- fullEnv.setProperty("queues.maximumMessageCount", 1);
- fullEnv.setProperty("queues.minimumAlertRepeatGap", 1);
-
- _fullHostConf = new VirtualHostConfiguration("test", fullEnv);
-
- }
-
- public void testGetMaximumMessageAge() throws ConfigurationException
- {
- // Check default value
- QueueConfiguration qConf = new QueueConfiguration("test", _emptyConf);
- assertEquals(0, qConf.getMaximumMessageAge());
-
- // Check explicit value
- VirtualHostConfiguration vhostConfig = overrideConfiguration("maximumMessageAge", 2);
-
- qConf = new QueueConfiguration("test", vhostConfig);
- assertEquals(2, qConf.getMaximumMessageAge());
-
- // Check inherited value
- qConf = new QueueConfiguration("test", _fullHostConf);
- assertEquals(1, qConf.getMaximumMessageAge());
- }
-
- public void testGetMaximumQueueDepth() throws ConfigurationException
- {
- // Check default value
- QueueConfiguration qConf = new QueueConfiguration("test", _emptyConf);
- assertEquals(0, qConf.getMaximumQueueDepth());
-
- // Check explicit value
- VirtualHostConfiguration vhostConfig = overrideConfiguration("maximumQueueDepth", 2);
- qConf = new QueueConfiguration("test", vhostConfig);
- assertEquals(2, qConf.getMaximumQueueDepth());
-
- // Check inherited value
- qConf = new QueueConfiguration("test", _fullHostConf);
- assertEquals(1, qConf.getMaximumQueueDepth());
- }
-
- public void testGetMaximumMessageSize() throws ConfigurationException
- {
- // Check default value
- QueueConfiguration qConf = new QueueConfiguration("test", _emptyConf);
- assertEquals(0, qConf.getMaximumMessageSize());
-
- // Check explicit value
- VirtualHostConfiguration vhostConfig = overrideConfiguration("maximumMessageSize", 2);
- qConf = new QueueConfiguration("test", vhostConfig);
- assertEquals(2, qConf.getMaximumMessageSize());
-
- // Check inherited value
- qConf = new QueueConfiguration("test", _fullHostConf);
- assertEquals(1, qConf.getMaximumMessageSize());
- }
-
- public void testGetMaximumMessageCount() throws ConfigurationException
- {
- // Check default value
- QueueConfiguration qConf = new QueueConfiguration("test", _emptyConf);
- assertEquals(0, qConf.getMaximumMessageCount());
-
- // Check explicit value
- VirtualHostConfiguration vhostConfig = overrideConfiguration("maximumMessageCount", 2);
- qConf = new QueueConfiguration("test", vhostConfig);
- assertEquals(2, qConf.getMaximumMessageCount());
-
- // Check inherited value
- qConf = new QueueConfiguration("test", _fullHostConf);
- assertEquals(1, qConf.getMaximumMessageCount());
- }
-
- public void testGetMinimumAlertRepeatGap() throws ConfigurationException
- {
- // Check default value
- QueueConfiguration qConf = new QueueConfiguration("test", _emptyConf);
- assertEquals(0, qConf.getMinimumAlertRepeatGap());
-
- // Check explicit value
- VirtualHostConfiguration vhostConfig = overrideConfiguration("minimumAlertRepeatGap", 2);
- qConf = new QueueConfiguration("test", vhostConfig);
- assertEquals(2, qConf.getMinimumAlertRepeatGap());
-
- // Check inherited value
- qConf = new QueueConfiguration("test", _fullHostConf);
- assertEquals(1, qConf.getMinimumAlertRepeatGap());
- }
-
- private VirtualHostConfiguration overrideConfiguration(String property, int value)
- throws ConfigurationException
- {
- PropertiesConfiguration queueConfig = new PropertiesConfiguration();
- queueConfig.setProperty("queues.queue.test." + property, value);
-
- CompositeConfiguration config = new CompositeConfiguration();
- config.addConfiguration(_fullHostConf.getConfig());
- config.addConfiguration(queueConfig);
-
- return new VirtualHostConfiguration("test", config);
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/configuration/ServerConfigurationTest.java b/java/broker/src/test/java/org/apache/qpid/server/configuration/ServerConfigurationTest.java
deleted file mode 100644
index 43540c88a1..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/configuration/ServerConfigurationTest.java
+++ /dev/null
@@ -1,1492 +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.configuration;
-
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.RandomAccessFile;
-import java.util.List;
-import java.util.Locale;
-
-import junit.framework.TestCase;
-
-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.protocol.AMQProtocolEngine;
-import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-import org.apache.qpid.server.registry.ConfigurationFileApplicationRegistry;
-import org.apache.qpid.server.util.InternalBrokerBaseCase;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-import org.apache.qpid.server.virtualhost.VirtualHostRegistry;
-import org.apache.qpid.transport.TestNetworkDriver;
-
-public class ServerConfigurationTest extends InternalBrokerBaseCase
-{
- private XMLConfiguration _config = new XMLConfiguration();
-
-
- public void testSetJMXManagementPort() throws ConfigurationException
- {
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- serverConfig.setJMXManagementPort(23);
- assertEquals(23, serverConfig.getJMXManagementPort());
- }
-
- public void testGetJMXManagementPort() throws ConfigurationException
- {
- _config.setProperty("management.jmxport", 42);
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(42, serverConfig.getJMXManagementPort());
- }
-
- public void testGetPlatformMbeanserver() throws ConfigurationException
- {
- // Check default
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(true, serverConfig.getPlatformMbeanserver());
-
- // Check value we set
- _config.setProperty("management.platform-mbeanserver", false);
- serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(false, serverConfig.getPlatformMbeanserver());
- }
-
- public void testGetPluginDirectory() throws ConfigurationException
- {
- // Check default
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(null, serverConfig.getPluginDirectory());
-
- // Check value we set
- _config.setProperty("plugin-directory", "/path/to/plugins");
- serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals("/path/to/plugins", serverConfig.getPluginDirectory());
- }
-
- public void testGetCacheDirectory() throws ConfigurationException
- {
- // Check default
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(null, serverConfig.getCacheDirectory());
-
- // Check value we set
- _config.setProperty("cache-directory", "/path/to/cache");
- serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals("/path/to/cache", serverConfig.getCacheDirectory());
- }
-
- public void testGetPrincipalDatabaseNames() throws ConfigurationException
- {
- // Check default
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(0, serverConfig.getPrincipalDatabaseNames().size());
-
- // Check value we set
- _config.setProperty("security.principal-databases.principal-database(0).name", "a");
- _config.setProperty("security.principal-databases.principal-database(1).name", "b");
- serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- List<String> dbs = serverConfig.getPrincipalDatabaseNames();
- assertEquals(2, dbs.size());
- assertEquals("a", dbs.get(0));
- assertEquals("b", dbs.get(1));
- }
-
- public void testGetPrincipalDatabaseClass() throws ConfigurationException
- {
- // Check default
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(0, serverConfig.getPrincipalDatabaseClass().size());
-
- // Check value we set
- _config.setProperty("security.principal-databases.principal-database(0).class", "a");
- _config.setProperty("security.principal-databases.principal-database(1).class", "b");
- serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- List<String> dbs = serverConfig.getPrincipalDatabaseClass();
- assertEquals(2, dbs.size());
- assertEquals("a", dbs.get(0));
- assertEquals("b", dbs.get(1));
- }
-
- public void testGetPrincipalDatabaseAttributeNames() throws ConfigurationException
- {
- // Check default
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(0, serverConfig.getPrincipalDatabaseAttributeNames(1).size());
-
- // Check value we set
- _config.setProperty("security.principal-databases.principal-database(0).attributes(0).attribute.name", "a");
- _config.setProperty("security.principal-databases.principal-database(0).attributes(1).attribute.name", "b");
- serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- List<String> dbs = serverConfig.getPrincipalDatabaseAttributeNames(0);
- assertEquals(2, dbs.size());
- assertEquals("a", dbs.get(0));
- assertEquals("b", dbs.get(1));
- }
-
- public void testGetPrincipalDatabaseAttributeValues() throws ConfigurationException
- {
- // Check default
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(0, serverConfig.getPrincipalDatabaseAttributeValues(1).size());
-
- // Check value we set
- _config.setProperty("security.principal-databases.principal-database(0).attributes(0).attribute.value", "a");
- _config.setProperty("security.principal-databases.principal-database(0).attributes(1).attribute.value", "b");
- serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- List<String> dbs = serverConfig.getPrincipalDatabaseAttributeValues(0);
- assertEquals(2, dbs.size());
- assertEquals("a", dbs.get(0));
- assertEquals("b", dbs.get(1));
- }
-
-
-
- public void testGetFrameSize() throws ConfigurationException
- {
- // Check default
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(65536, serverConfig.getFrameSize());
-
- // Check value we set
- _config.setProperty("advanced.framesize", "23");
- serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(23, serverConfig.getFrameSize());
- }
-
- public void testGetProtectIOEnabled() throws ConfigurationException
- {
- // Check default
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(false, serverConfig.getProtectIOEnabled());
-
- // Check value we set
- _config.setProperty(ServerConfiguration.CONNECTOR_PROTECTIO_ENABLED, true);
- serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(true, serverConfig.getProtectIOEnabled());
- }
-
- public void testGetBufferReadLimit() throws ConfigurationException
- {
- // Check default
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(262144, serverConfig.getBufferReadLimit());
-
- // Check value we set
- _config.setProperty(ServerConfiguration.CONNECTOR_PROTECTIO_READ_BUFFER_LIMIT_SIZE, 23);
- serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(23, serverConfig.getBufferReadLimit());
- }
-
- public void testGetBufferWriteLimit() throws ConfigurationException
- {
- // Check default
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(262144, serverConfig.getBufferWriteLimit());
-
- // Check value we set
- _config.setProperty(ServerConfiguration.CONNECTOR_PROTECTIO_WRITE_BUFFER_LIMIT_SIZE, 23);
- serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(23, serverConfig.getBufferWriteLimit());
- }
-
-
- public void testGetStatusEnabled() throws ConfigurationException
- {
- // Check default
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(ServerConfiguration.DEFAULT_STATUS_UPDATES.equalsIgnoreCase("on"),
- serverConfig.getStatusUpdatesEnabled());
-
- // Check disabling we set
- _config.setProperty(ServerConfiguration.STATUS_UPDATES, "off");
- serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(false, serverConfig.getStatusUpdatesEnabled());
-
- // Check invalid values don't cause error but result in disabled
- _config.setProperty(ServerConfiguration.STATUS_UPDATES, "Yes Please");
- serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(false, serverConfig.getStatusUpdatesEnabled());
-
- }
- public void testGetSynchedClocks() throws ConfigurationException
- {
- // Check default
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(false, serverConfig.getSynchedClocks());
-
- // Check value we set
- _config.setProperty("advanced.synced-clocks", true);
- serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(true, serverConfig.getSynchedClocks());
- }
-
- public void testGetLocale() throws ConfigurationException
- {
- // Check default
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
-
- // The Default is what ever the VMs default is
- Locale defaultLocale = Locale.getDefault();
-
- assertEquals(defaultLocale, serverConfig.getLocale());
-
-
- //Test Language only
- Locale update = new Locale("es");
- _config.setProperty(ServerConfiguration.ADVANCED_LOCALE, "es");
- serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(update, serverConfig.getLocale());
-
- //Test Language and Country
- update = new Locale("es","ES");
- _config.setProperty(ServerConfiguration.ADVANCED_LOCALE, "es_ES");
- serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(update, serverConfig.getLocale());
-
- //Test Language and Country and Variant
- update = new Locale("es","ES", "Traditional_WIN");
- _config.setProperty(ServerConfiguration.ADVANCED_LOCALE, "es_ES_Traditional_WIN");
- serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(update, serverConfig.getLocale());
- }
-
-
- public void testGetMsgAuth() throws ConfigurationException
- {
- // Check default
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(false, serverConfig.getMsgAuth());
-
- // Check value we set
- _config.setProperty("security.msg-auth", true);
- serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(true, serverConfig.getMsgAuth());
- }
-
- public void testGetJMXPrincipalDatabase() throws ConfigurationException
- {
- // Check default
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(null, serverConfig.getJMXPrincipalDatabase());
-
- // Check value we set
- _config.setProperty("security.jmx.principal-database", "a");
- serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals("a", serverConfig.getJMXPrincipalDatabase());
- }
-
- public void testGetManagementKeyStorePath() throws ConfigurationException
- {
- // Check default
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(null, serverConfig.getManagementKeyStorePath());
-
- // Check value we set
- _config.setProperty("management.ssl.keyStorePath", "a");
- serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals("a", serverConfig.getManagementKeyStorePath());
- }
-
- public void testGetManagementSSLEnabled() throws ConfigurationException
- {
- // Check default
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(true, serverConfig.getManagementSSLEnabled());
-
- // Check value we set
- _config.setProperty("management.ssl.enabled", false);
- serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(false, serverConfig.getManagementSSLEnabled());
- }
-
- public void testGetManagementKeyStorePassword() throws ConfigurationException
- {
- // Check default
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(null, serverConfig.getManagementKeyStorePassword());
-
- // Check value we set
- _config.setProperty("management.ssl.keyStorePassword", "a");
- serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals("a", serverConfig.getManagementKeyStorePassword());
- }
-
- public void testGetQueueAutoRegister() throws ConfigurationException
- {
- // Check default
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(true, serverConfig.getQueueAutoRegister());
-
- // Check value we set
- _config.setProperty("queue.auto_register", false);
- serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(false, serverConfig.getQueueAutoRegister());
- }
-
- public void testGetManagementEnabled() throws ConfigurationException
- {
- // Check default
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(true, serverConfig.getManagementEnabled());
-
- // Check value we set
- _config.setProperty("management.enabled", false);
- serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(false, serverConfig.getManagementEnabled());
- }
-
- public void testSetManagementEnabled() throws ConfigurationException
- {
- // Check value we set
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- serverConfig.setManagementEnabled(false);
- assertEquals(false, serverConfig.getManagementEnabled());
- }
-
- public void testGetHeartBeatDelay() throws ConfigurationException
- {
- // Check default
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(5, serverConfig.getHeartBeatDelay());
-
- // Check value we set
- _config.setProperty("heartbeat.delay", 23);
- serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(23, serverConfig.getHeartBeatDelay());
- }
-
- public void testGetHeartBeatTimeout() throws ConfigurationException
- {
- // Check default
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(2.0, serverConfig.getHeartBeatTimeout());
-
- // Check value we set
- _config.setProperty("heartbeat.timeoutFactor", 2.3);
- serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(2.3, serverConfig.getHeartBeatTimeout());
- }
-
- public void testGetMaximumMessageAge() throws ConfigurationException
- {
- // Check default
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(0, serverConfig.getMaximumMessageAge());
-
- // Check value we set
- _config.setProperty("maximumMessageAge", 10L);
- serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(10, serverConfig.getMaximumMessageAge());
- }
-
- public void testGetMaximumMessageCount() throws ConfigurationException
- {
- // Check default
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(0, serverConfig.getMaximumMessageCount());
-
- // Check value we set
- _config.setProperty("maximumMessageCount", 10L);
- serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(10, serverConfig.getMaximumMessageCount());
- }
-
- public void testGetMaximumQueueDepth() throws ConfigurationException
- {
- // Check default
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(0, serverConfig.getMaximumQueueDepth());
-
- // Check value we set
- _config.setProperty("maximumQueueDepth", 10L);
- serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(10, serverConfig.getMaximumQueueDepth());
- }
-
- public void testGetMaximumMessageSize() throws ConfigurationException
- {
- // Check default
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(0, serverConfig.getMaximumMessageSize());
-
- // Check value we set
- _config.setProperty("maximumMessageSize", 10L);
- serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(10, serverConfig.getMaximumMessageSize());
- }
-
- public void testGetMinimumAlertRepeatGap() throws ConfigurationException
- {
- // Check default
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(0, serverConfig.getMinimumAlertRepeatGap());
-
- // Check value we set
- _config.setProperty("minimumAlertRepeatGap", 10L);
- serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(10, serverConfig.getMinimumAlertRepeatGap());
- }
-
- public void testGetProcessors() throws ConfigurationException
- {
- // Check default
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(4, serverConfig.getProcessors());
-
- // Check value we set
- _config.setProperty("connector.processors", 10);
- serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(10, serverConfig.getProcessors());
- }
-
- public void testGetPort() throws ConfigurationException
- {
- // Check default
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertNotNull(serverConfig.getPorts());
- assertEquals(1, serverConfig.getPorts().size());
- assertEquals(5672, serverConfig.getPorts().get(0));
-
-
- // Check value we set
- _config.setProperty("connector.port", "10");
- serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertNotNull(serverConfig.getPorts());
- assertEquals(1, serverConfig.getPorts().size());
- assertEquals("10", serverConfig.getPorts().get(0));
- }
-
- public void testGetBind() throws ConfigurationException
- {
- // Check default
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals("wildcard", serverConfig.getBind());
-
- // Check value we set
- _config.setProperty("connector.bind", "a");
- serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals("a", serverConfig.getBind());
- }
-
- public void testGetReceiveBufferSize() throws ConfigurationException
- {
- // Check default
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(32767, serverConfig.getReceiveBufferSize());
-
- // Check value we set
- _config.setProperty("connector.socketReceiveBuffer", "23");
- serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(23, serverConfig.getReceiveBufferSize());
- }
-
- public void testGetWriteBufferSize() throws ConfigurationException
- {
- // Check default
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(32767, serverConfig.getWriteBufferSize());
-
- // Check value we set
- _config.setProperty("connector.socketWriteBuffer", "23");
- serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(23, serverConfig.getWriteBufferSize());
- }
-
- public void testGetTcpNoDelay() throws ConfigurationException
- {
- // Check default
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(true, serverConfig.getTcpNoDelay());
-
- // Check value we set
- _config.setProperty("connector.tcpNoDelay", false);
- serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(false, serverConfig.getTcpNoDelay());
- }
-
- public void testGetEnableExecutorPool() throws ConfigurationException
- {
- // Check default
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- 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
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(false, serverConfig.getEnableSSL());
-
- // Check value we set
- _config.setProperty("connector.ssl.enabled", true);
- serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(true, serverConfig.getEnableSSL());
- }
-
- public void testGetSSLOnly() throws ConfigurationException
- {
- // Check default
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(false, serverConfig.getSSLOnly());
-
- // Check value we set
- _config.setProperty("connector.ssl.sslOnly", true);
- serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(true, serverConfig.getSSLOnly());
- }
-
- public void testGetSSLPort() throws ConfigurationException
- {
- // Check default
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(8672, serverConfig.getSSLPort());
-
- // Check value we set
- _config.setProperty("connector.ssl.port", 23);
- serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(23, serverConfig.getSSLPort());
- }
-
- public void testGetKeystorePath() throws ConfigurationException
- {
- // Check default
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals("none", serverConfig.getKeystorePath());
-
- // Check value we set
- _config.setProperty("connector.ssl.keystorePath", "a");
- serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals("a", serverConfig.getKeystorePath());
- }
-
- public void testGetKeystorePassword() throws ConfigurationException
- {
- // Check default
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals("none", serverConfig.getKeystorePassword());
-
- // Check value we set
- _config.setProperty("connector.ssl.keystorePassword", "a");
- serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals("a", serverConfig.getKeystorePassword());
- }
-
- public void testGetCertType() throws ConfigurationException
- {
- // Check default
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals("SunX509", serverConfig.getCertType());
-
- // Check value we set
- _config.setProperty("connector.ssl.certType", "a");
- serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals("a", serverConfig.getCertType());
- }
-
- public void testGetQpidNIO() throws ConfigurationException
- {
- // Check default
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(false, serverConfig.getQpidNIO());
-
- // Check value we set
- _config.setProperty("connector.qpidnio", true);
- serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(true, serverConfig.getQpidNIO());
- }
-
- public void testGetUseBiasedWrites() throws ConfigurationException
- {
- // Check default
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(false, serverConfig.getUseBiasedWrites());
-
- // Check value we set
- _config.setProperty("advanced.useWriteBiasedPool", true);
- serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(true, serverConfig.getUseBiasedWrites());
- }
-
- public void testGetHousekeepingExpiredMessageCheckPeriod() throws ConfigurationException
- {
- // Check default
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(30000, serverConfig.getHousekeepingCheckPeriod());
-
- // Check value we set
- _config.setProperty("housekeeping.expiredMessageCheckPeriod", 23L);
- serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
- assertEquals(23, serverConfig.getHousekeepingCheckPeriod());
- serverConfig.setHousekeepingExpiredMessageCheckPeriod(42L);
- assertEquals(42, serverConfig.getHousekeepingCheckPeriod());
- }
-
- public void testSingleConfiguration() throws IOException, ConfigurationException
- {
- File fileA = File.createTempFile(getClass().getName(), null);
- fileA.deleteOnExit();
- FileWriter out = new FileWriter(fileA);
- out.write("<broker><connector><port>2342</port><ssl><port>4235</port></ssl></connector></broker>");
- out.close();
- ServerConfiguration conf = new ServerConfiguration(fileA);
- conf.initialise();
- assertEquals(4235, conf.getSSLPort());
- }
-
- public void testCombinedConfiguration() throws IOException, ConfigurationException
- {
- File mainFile = File.createTempFile(getClass().getName(), null);
- File fileA = File.createTempFile(getClass().getName(), null);
- File fileB = File.createTempFile(getClass().getName(), null);
-
- mainFile.deleteOnExit();
- fileA.deleteOnExit();
- fileB.deleteOnExit();
-
- FileWriter out = new FileWriter(mainFile);
- out.write("<configuration><system/>");
- out.write("<xml fileName=\"" + fileA.getAbsolutePath() + "\"/>");
- out.write("<xml fileName=\"" + fileB.getAbsolutePath() + "\"/>");
- out.write("</configuration>");
- out.close();
-
- out = new FileWriter(fileA);
- out.write("<broker><connector><port>2342</port><ssl><port>4235</port></ssl></connector></broker>");
- out.close();
-
- out = new FileWriter(fileB);
- out.write("<broker><connector><ssl><port>2345</port></ssl><qpidnio>true</qpidnio></connector></broker>");
- out.close();
-
- ServerConfiguration config = new ServerConfiguration(mainFile.getAbsoluteFile());
- config.initialise();
- assertEquals(4235, config.getSSLPort()); // From first file, not
- // overriden by second
- assertNotNull(config.getPorts());
- assertEquals(1, config.getPorts().size());
- assertEquals("2342", config.getPorts().get(0)); // From the first file, not
- // present in the second
- assertEquals(true, config.getQpidNIO()); // From the second file, not
- // present in the first
- }
-
- public void testVariableInterpolation() throws Exception
- {
- File mainFile = File.createTempFile(getClass().getName(), null);
-
- mainFile.deleteOnExit();
-
- FileWriter out = new FileWriter(mainFile);
- out.write("<broker>\n");
- out.write("\t<work>foo</work>\n");
- out.write("\t<management><ssl><keyStorePath>${work}</keyStorePath></ssl></management>\n");
- out.write("</broker>\n");
- out.close();
-
- ServerConfiguration config = new ServerConfiguration(mainFile.getAbsoluteFile());
- config.initialise();
- assertEquals("Did not get correct interpolated value",
- "foo", config.getManagementKeyStorePath());
- }
-
- private void writeConfigFile(File mainFile, boolean allow) throws IOException {
- writeConfigFile(mainFile, allow, true, null, "test");
- }
-
- private void writeConfigFile(File mainFile, boolean allow, boolean includeVhosts, File vhostsFile, String name) throws IOException {
- FileWriter out = new FileWriter(mainFile);
- out.write("<broker>\n");
- out.write("\t<management><enabled>false</enabled></management>\n");
- out.write("\t<security>\n");
- out.write("\t\t<principal-databases>\n");
- out.write("\t\t\t<principal-database>\n");
- out.write("\t\t\t\t<name>passwordfile</name>\n");
- out.write("\t\t\t\t<class>org.apache.qpid.server.security.auth.database.PlainPasswordFilePrincipalDatabase</class>\n");
- out.write("\t\t\t\t<attributes>\n");
- out.write("\t\t\t\t\t<attribute>\n");
- out.write("\t\t\t\t\t\t<name>passwordFile</name>\n");
- out.write("\t\t\t\t\t\t<value>/dev/null</value>\n");
- out.write("\t\t\t\t\t</attribute>\n");
- out.write("\t\t\t\t</attributes>\n");
- out.write("\t\t\t</principal-database>\n");
- out.write("\t\t</principal-databases>\n");
- out.write("\t\t<jmx>\n");
- out.write("\t\t\t<principal-database>passwordfile</principal-database>\n");
- out.write("\t\t</jmx>\n");
- out.write("\t\t<firewall>\n");
- out.write("\t\t\t<rule access=\""+ ((allow) ? "allow" : "deny") +"\" network=\"127.0.0.1\"/>");
- out.write("\t\t</firewall>\n");
- out.write("\t</security>\n");
- if (includeVhosts)
- {
- out.write("\t<virtualhosts>\n");
- out.write("\t\t<default>test</default>\n");
- out.write("\t\t<virtualhost>\n");
- out.write(String.format("\t\t\t<name>%s</name>\n", name));
- out.write(String.format("\t\t<%s> \n", name));
- out.write("\t\t\t<exchanges>\n");
- out.write("\t\t\t\t<exchange>\n");
- out.write("\t\t\t\t\t<type>topic</type>\n");
- out.write(String.format("\t\t\t\t\t<name>%s.topic</name>\n", name));
- out.write("\t\t\t\t\t<durable>true</durable>\n");
- out.write("\t\t\t\t</exchange>\n");
- out.write("\t\tt</exchanges>\n");
- out.write(String.format("\t\t</%s> \n", name));
- out.write("\t\t</virtualhost>\n");
- out.write("\t</virtualhosts>\n");
- }
- if (vhostsFile != null)
- {
- out.write("\t<virtualhosts>"+vhostsFile.getAbsolutePath()+"</virtualhosts>\n");
- }
- out.write("</broker>\n");
- out.close();
- }
-
- private void writeTestFishConfigFile(File mainFile) throws IOException {
- FileWriter out = new FileWriter(mainFile);
- out.write("<broker>\n");
- out.write("\t<management><enabled>false</enabled></management>\n");
- out.write("\t<security>\n");
- out.write("\t\t<principal-databases>\n");
- out.write("\t\t\t<principal-database>\n");
- out.write("\t\t\t\t<name>passwordfile</name>\n");
- out.write("\t\t\t\t<class>org.apache.qpid.server.security.auth.database.PlainPasswordFilePrincipalDatabase</class>\n");
- out.write("\t\t\t\t<attributes>\n");
- out.write("\t\t\t\t\t<attribute>\n");
- out.write("\t\t\t\t\t\t<name>passwordFile</name>\n");
- out.write("\t\t\t\t\t\t<value>/dev/null</value>\n");
- out.write("\t\t\t\t\t</attribute>\n");
- out.write("\t\t\t\t</attributes>\n");
- out.write("\t\t\t</principal-database>\n");
- out.write("\t\t</principal-databases>\n");
- out.write("\t\t<jmx>\n");
- out.write("\t\t\t<principal-database>passwordfile</principal-database>\n");
- out.write("\t\t</jmx>\n");
- out.write("\t\t<firewall>\n");
- out.write("\t\t\t<rule access=\"allow\" network=\"127.0.0.1\"/>");
- out.write("\t\t</firewall>\n");
- out.write("\t</security>\n");
- out.write("\t<virtualhosts>\n");
- out.write("\t\t<virtualhost>\n");
- out.write("\t\t\t<name>test</name>\n");
- out.write("\t\t<test> \n");
- out.write("\t\t\t<exchanges>\n");
- out.write("\t\t\t\t<exchange>\n");
- out.write("\t\t\t\t\t<type>topic</type>\n");
- out.write("\t\t\t\t\t<name>test.topic</name>\n");
- out.write("\t\t\t\t\t<durable>true</durable>\n");
- out.write("\t\t\t\t</exchange>\n");
- out.write("\t\tt</exchanges>\n");
- out.write("\t\t</test> \n");
- out.write("\t\t</virtualhost>\n");
- out.write("\t\t<virtualhost>\n");
- out.write("\t\t\t<name>fish</name>\n");
- out.write("\t\t<fish> \n");
- out.write("\t\t\t<exchanges>\n");
- out.write("\t\t\t\t<exchange>\n");
- out.write("\t\t\t\t\t<type>topic</type>\n");
- out.write("\t\t\t\t\t<name>fish.topic</name>\n");
- out.write("\t\t\t\t\t<durable>false</durable>\n");
- out.write("\t\t\t\t</exchange>\n");
- out.write("\t\tt</exchanges>\n");
- out.write("\t\t</fish> \n");
- out.write("\t\t</virtualhost>\n");
- out.write("\t</virtualhosts>\n");
- out.write("</broker>\n");
- out.close();
- }
-
- private void writeVirtualHostsFile(File vhostsFile, String name) throws IOException {
- FileWriter out = new FileWriter(vhostsFile);
- out.write("<virtualhosts>\n");
- out.write(String.format("\t\t<default>%s</default>\n", name));
- out.write("\t<virtualhost>\n");
- out.write(String.format("\t\t<name>%s</name>\n", name));
- out.write(String.format("\t\t<%s>\n", name));
- out.write("\t\t\t<exchanges>\n");
- out.write("\t\t\t\t<exchange>\n");
- out.write("\t\t\t\t\t<type>topic</type>\n");
- out.write("\t\t\t\t\t<name>test.topic</name>\n");
- out.write("\t\t\t\t\t<durable>true</durable>\n");
- out.write("\t\t\t\t</exchange>\n");
- out.write("\t\tt</exchanges>\n");
- out.write(String.format("\t\t</%s>\n", name));
- out.write("\t</virtualhost>\n");
- out.write("</virtualhosts>\n");
- out.close();
- }
-
- private void writeMultiVirtualHostsFile(File vhostsFile) throws IOException {
- FileWriter out = new FileWriter(vhostsFile);
- out.write("<virtualhosts>\n");
- out.write("\t<virtualhost>\n");
- out.write("\t\t<name>topic</name>\n");
- out.write("\t\t<topic>\n");
- out.write("\t\t\t<exchanges>\n");
- out.write("\t\t\t\t<exchange>\n");
- out.write("\t\t\t\t\t<type>topic</type>\n");
- out.write("\t\t\t\t\t<name>test.topic</name>\n");
- out.write("\t\t\t\t\t<durable>true</durable>\n");
- out.write("\t\t\t\t</exchange>\n");
- out.write("\t\tt</exchanges>\n");
- out.write("\t\t</topic>\n");
- out.write("\t</virtualhost>\n");
- out.write("\t<virtualhost>\n");
- out.write("\t\t<name>fanout</name>\n");
- out.write("\t\t<fanout>\n");
- out.write("\t\t\t<exchanges>\n");
- out.write("\t\t\t\t<exchange>\n");
- out.write("\t\t\t\t\t<type>fanout</type>\n");
- out.write("\t\t\t\t\t<name>test.fanout</name>\n");
- out.write("\t\t\t\t\t<durable>true</durable>\n");
- out.write("\t\t\t\t</exchange>\n");
- out.write("\t\tt</exchanges>\n");
- out.write("\t\t</fanout>\n");
- out.write("\t</virtualhost>\n");
- out.write("</virtualhosts>\n");
- out.close();
- }
-
- private void writeMultipleVhostsConfigFile(File mainFile, File[] vhostsFileArray) throws IOException {
- FileWriter out = new FileWriter(mainFile);
- out.write("<broker>\n");
- out.write("\t<management><enabled>false</enabled></management>\n");
- out.write("\t<security>\n");
- out.write("\t\t<principal-databases>\n");
- out.write("\t\t\t<principal-database>\n");
- out.write("\t\t\t\t<name>passwordfile</name>\n");
- out.write("\t\t\t\t<class>org.apache.qpid.server.security.auth.database.PlainPasswordFilePrincipalDatabase</class>\n");
- out.write("\t\t\t\t<attributes>\n");
- out.write("\t\t\t\t\t<attribute>\n");
- out.write("\t\t\t\t\t\t<name>passwordFile</name>\n");
- out.write("\t\t\t\t\t\t<value>/dev/null</value>\n");
- out.write("\t\t\t\t\t</attribute>\n");
- out.write("\t\t\t\t</attributes>\n");
- out.write("\t\t\t</principal-database>\n");
- out.write("\t\t</principal-databases>\n");
- out.write("\t\t<jmx>\n");
- out.write("\t\t\t<principal-database>passwordfile</principal-database>\n");
- out.write("\t\t</jmx>\n");
- out.write("\t\t<firewall>\n");
- out.write("\t\t\t<rule access=\"allow\" network=\"127.0.0.1\"/>");
- out.write("\t\t</firewall>\n");
- out.write("\t</security>\n");
- for (File vhostsFile : vhostsFileArray)
- {
- out.write("\t<virtualhosts>"+vhostsFile.getAbsolutePath()+"</virtualhosts>\n");
- }
- out.write("</broker>\n");
- out.close();
- }
-
- private void writeCombinedConfigFile(File mainFile, File fileA, File fileB) throws Exception
- {
- FileWriter out = new FileWriter(mainFile);
- out.write("<configuration><system/>");
- out.write("<xml fileName=\"" + fileA.getAbsolutePath() + "\"/>");
- out.write("<xml fileName=\"" + fileB.getAbsolutePath() + "\"/>");
- out.write("</configuration>");
- out.close();
- }
-
- /**
- * Test that configuration loads correctly when virtual hosts are specified in the main
- * configuration file only.
- * <p>
- * Test for QPID-2361
- */
- public void testInternalVirtualhostConfigFile() throws Exception
- {
- // Write out config
- File mainFile = File.createTempFile(getClass().getName(), "config");
- mainFile.deleteOnExit();
- writeConfigFile(mainFile, false, true, null, "test");
-
- // Load config
- ApplicationRegistry reg = new ConfigurationFileApplicationRegistry(mainFile);
- ApplicationRegistry.initialise(reg, 1);
-
- // Test config
- VirtualHostRegistry virtualHostRegistry = reg.getVirtualHostRegistry();
- String defaultVirtualHost = reg.getConfiguration().getDefaultVirtualHost();
- VirtualHost virtualHost = virtualHostRegistry.getVirtualHost("test");
- Exchange exchange = virtualHost.getExchangeRegistry().getExchange(new AMQShortString("test.topic"));
-
- assertEquals("Incorrect default host", "test", defaultVirtualHost);
- assertEquals("Incorrect virtualhost count", 1, virtualHostRegistry.getVirtualHosts().size());
- assertEquals("Incorrect virtualhost name", "test", virtualHost.getName());
- assertEquals("Incorrect exchange type", "topic", exchange.getType().getName().toString());
- }
-
- /**
- * Test that configuration loads correctly when virtual hosts are specified in an external
- * configuration file only.
- * <p>
- * Test for QPID-2361
- */
- public void testExternalVirtualhostXMLFile() throws Exception
- {
- // Write out config
- File mainFile = File.createTempFile(getClass().getName(), "config");
- mainFile.deleteOnExit();
- File vhostsFile = File.createTempFile(getClass().getName(), "vhosts");
- vhostsFile.deleteOnExit();
- writeConfigFile(mainFile, false, false, vhostsFile, null);
- writeVirtualHostsFile(vhostsFile, "test");
-
- // Load config
- ApplicationRegistry reg = new ConfigurationFileApplicationRegistry(mainFile);
- ApplicationRegistry.initialise(reg, 1);
-
- // Test config
- VirtualHostRegistry virtualHostRegistry = reg.getVirtualHostRegistry();
- String defaultVirtualHost = reg.getConfiguration().getDefaultVirtualHost();
- VirtualHost virtualHost = virtualHostRegistry.getVirtualHost("test");
- Exchange exchange = virtualHost.getExchangeRegistry().getExchange(new AMQShortString("test.topic"));
-
- assertEquals("Incorrect default host", "test", defaultVirtualHost);
- assertEquals("Incorrect virtualhost count", 1, virtualHostRegistry.getVirtualHosts().size());
- assertEquals("Incorrect virtualhost name", "test", virtualHost.getName());
- assertEquals("Incorrect exchange type", "topic", exchange.getType().getName().toString());
- }
-
- /**
- * Test that configuration loads correctly when virtual hosts are specified in an external
- * configuration file only, with two vhosts that have different properties.
- * <p>
- * Test for QPID-2361
- */
- public void testExternalMultiVirtualhostXMLFile() throws Exception
- {
- // Write out vhosts
- File vhostsFile = File.createTempFile(getClass().getName(), "vhosts-multi");
- vhostsFile.deleteOnExit();
- writeMultiVirtualHostsFile(vhostsFile);
-
- // Write out config
- File mainFile = File.createTempFile(getClass().getName(), "config");
- mainFile.deleteOnExit();
- writeConfigFile(mainFile, false, false, vhostsFile, null);
-
- // Load config
- ApplicationRegistry reg = new ConfigurationFileApplicationRegistry(mainFile);
- ApplicationRegistry.initialise(reg, 1);
-
- // Test config
- VirtualHostRegistry virtualHostRegistry = reg.getVirtualHostRegistry();
-
- assertEquals("Incorrect virtualhost count", 2, virtualHostRegistry.getVirtualHosts().size());
-
- // test topic host
- VirtualHost topicVirtualHost = virtualHostRegistry.getVirtualHost("topic");
- Exchange topicExchange = topicVirtualHost.getExchangeRegistry().getExchange(new AMQShortString("test.topic"));
-
- assertEquals("Incorrect topic virtualhost name", "topic", topicVirtualHost.getName());
- assertEquals("Incorrect topic exchange type", "topic", topicExchange.getType().getName().toString());
-
- // Test fanout host
- VirtualHost fanoutVirtualHost = virtualHostRegistry.getVirtualHost("fanout");
- Exchange fanoutExchange = fanoutVirtualHost.getExchangeRegistry().getExchange(new AMQShortString("test.fanout"));
-
- assertEquals("Incorrect fanout virtualhost name", "fanout", fanoutVirtualHost.getName());
- assertEquals("Incorrect fanout exchange type", "fanout", fanoutExchange.getType().getName().toString());
- }
-
- /**
- * Test that configuration does not load when virtual hosts are specified in both the main
- * configuration file and an external file. Should throw a {@link ConfigurationException}.
- * <p>
- * Test for QPID-2361
- */
- public void testInternalAndExternalVirtualhostXMLFile() throws Exception
- {
- // Write out vhosts
- File vhostsFile = File.createTempFile(getClass().getName(), "vhosts");
- vhostsFile.deleteOnExit();
- writeVirtualHostsFile(vhostsFile, "test");
-
- // Write out config
- File mainFile = File.createTempFile(getClass().getName(), "config");
- mainFile.deleteOnExit();
- writeConfigFile(mainFile, false, true, vhostsFile, "test");
-
- // Load config
- try
- {
- ApplicationRegistry reg = new ConfigurationFileApplicationRegistry(mainFile);
- ApplicationRegistry.initialise(reg, 1);
- fail("Different virtualhost XML configurations not allowed");
- }
- catch (ConfigurationException ce)
- {
- assertEquals("Incorrect error message", "Only one of external or embedded virtualhosts configuration allowed.", ce.getMessage());
- }
- }
-
- /**
- * Test that configuration does not load when virtual hosts are specified in multiple external
- * files. Should throw a {@link ConfigurationException}.
- * <p>
- * Test for QPID-2361
- */
- public void testMultipleInternalVirtualhostXMLFile() throws Exception
- {
- // Write out vhosts
- File vhostsFileOne = File.createTempFile(getClass().getName(), "vhosts-one");
- vhostsFileOne.deleteOnExit();
- writeVirtualHostsFile(vhostsFileOne, "one");
- File vhostsFileTwo = File.createTempFile(getClass().getName(), "vhosts-two");
- vhostsFileTwo.deleteOnExit();
- writeVirtualHostsFile(vhostsFileTwo, "two");
-
- // Write out config
- File mainFile = File.createTempFile(getClass().getName(), "config");
- mainFile.deleteOnExit();
- writeMultipleVhostsConfigFile(mainFile, new File[] { vhostsFileOne, vhostsFileTwo });
-
- // Load config
- try
- {
- ApplicationRegistry reg = new ConfigurationFileApplicationRegistry(mainFile);
- ApplicationRegistry.initialise(reg, 1);
- fail("Multiple virtualhost XML configurations not allowed");
- }
- catch (ConfigurationException ce)
- {
- assertEquals("Incorrect error message",
- "Only one external virtualhosts configuration file allowed, multiple filenames found.",
- ce.getMessage());
- }
- }
-
- /**
- * Test that configuration loads correctly when virtual hosts are specified in an external
- * configuration file in the first of two configurations and embedded in the second. This
- * will throe a {@link ConfigurationException} since the configurations have different
- * types.
- * <p>
- * Test for QPID-2361
- */
- public void testCombinedDifferentVirtualhostConfig() throws Exception
- {
- // Write out vhosts config
- File vhostsFile = File.createTempFile(getClass().getName(), "vhosts");
- vhostsFile.deleteOnExit();
- writeVirtualHostsFile(vhostsFile, "external");
-
- // Write out combined config file
- File mainFile = File.createTempFile(getClass().getName(), "main");
- File fileA = File.createTempFile(getClass().getName(), "a");
- File fileB = File.createTempFile(getClass().getName(), "b");
- mainFile.deleteOnExit();
- fileA.deleteOnExit();
- fileB.deleteOnExit();
- writeCombinedConfigFile(mainFile, fileA, fileB);
- writeConfigFile(fileA, false, false, vhostsFile, null);
- writeConfigFile(fileB, false);
-
- // Load config
- try
- {
- ServerConfiguration config = new ServerConfiguration(mainFile.getAbsoluteFile());
- config.initialise();
- fail("Different virtualhost XML configurations not allowed");
- }
- catch (ConfigurationException ce)
- {
- assertEquals("Incorrect error message", "Only one of external or embedded virtualhosts configuration allowed.", ce.getMessage());
- }
- }
-
- /**
- * Test that configuration loads correctly when virtual hosts are specified two overriding configurations
- * each with an embedded virtualhost section. The first configuration section should be used.
- * <p>
- * Test for QPID-2361
- */
- public void testCombinedConfigEmbeddedVirtualhost() throws Exception
- {
- // Write out combined config file
- File mainFile = File.createTempFile(getClass().getName(), "main");
- File fileA = File.createTempFile(getClass().getName(), "a");
- File fileB = File.createTempFile(getClass().getName(), "b");
- mainFile.deleteOnExit();
- fileA.deleteOnExit();
- fileB.deleteOnExit();
- writeCombinedConfigFile(mainFile, fileA, fileB);
- writeConfigFile(fileA, false, true, null, "a");
- writeConfigFile(fileB, false, true, null, "b");
-
- // Load config
- ServerConfiguration config = new ServerConfiguration(mainFile.getAbsoluteFile());
- config.initialise();
-
- // Test config
- VirtualHostConfiguration virtualHost = config.getVirtualHostConfig("a");
-
- assertEquals("Incorrect virtualhost count", 1, config.getVirtualHosts().length);
- assertEquals("Incorrect virtualhost name", "a", virtualHost.getName());
- }
-
- /**
- * Test that configuration loads correctly when virtual hosts are specified two overriding configurations
- * each with an external virtualhost XML file. The first configuration file should be used.
- * <p>
- * Test for QPID-2361
- */
- public void testCombinedConfigExternalVirtualhost() throws Exception
- {
- // Write out vhosts config
- File vhostsOne = File.createTempFile(getClass().getName(), "vhosts-one");
- vhostsOne.deleteOnExit();
- writeVirtualHostsFile(vhostsOne, "one");
- File vhostsTwo = File.createTempFile(getClass().getName(), "vhosts-two");
- vhostsTwo.deleteOnExit();
- writeVirtualHostsFile(vhostsTwo, "two");
-
- // Write out combined config file
- File mainFile = File.createTempFile(getClass().getName(), "main");
- File fileA = File.createTempFile(getClass().getName(), "a");
- File fileB = File.createTempFile(getClass().getName(), "b");
- mainFile.deleteOnExit();
- fileA.deleteOnExit();
- fileB.deleteOnExit();
- writeCombinedConfigFile(mainFile, fileA, fileB);
- writeConfigFile(fileA, false, false, vhostsOne, null);
- writeConfigFile(fileB, false, false, vhostsTwo, null);
-
- // Load config
- ServerConfiguration config = new ServerConfiguration(mainFile.getAbsoluteFile());
- config.initialise();
-
- // Test config
- VirtualHostConfiguration virtualHost = config.getVirtualHostConfig("one");
-
- assertEquals("Incorrect virtualhost count", 1, config.getVirtualHosts().length);
- assertEquals("Incorrect virtualhost name", "one", virtualHost.getName());
- }
-
- /**
- * Test that configuration loads correctly when an overriding virtualhost configuration resets
- * a property of an embedded virtualhost section. The overriding configuration property value
- * should be used.
- * <p>
- * Test for QPID-2361
- */
- public void testCombinedConfigEmbeddedVirtualhostOverride() throws Exception
- {
- // Write out combined config file
- File mainFile = File.createTempFile(getClass().getName(), "main");
- File fileA = File.createTempFile(getClass().getName(), "override");
- File fileB = File.createTempFile(getClass().getName(), "config");
- mainFile.deleteOnExit();
- fileA.deleteOnExit();
- fileB.deleteOnExit();
- writeCombinedConfigFile(mainFile, fileA, fileB);
- writeTestFishConfigFile(fileB);
-
- // Write out overriding virtualhosts section
- FileWriter out = new FileWriter(fileA);
- out.write("<broker>\n");
- out.write("<virtualhosts>\n");
- out.write("\t<virtualhost>\n");
- out.write("\t\t<test>\n");
- out.write("\t\t\t<exchanges>\n");
- out.write("\t\t\t\t<exchange>\n");
- out.write("\t\t\t\t\t<durable>false</durable>\n");
- out.write("\t\t\t\t</exchange>\n");
- out.write("\t\tt</exchanges>\n");
- out.write("\t\t</test>\n");
- out.write("\t\t<fish>\n");
- out.write("\t\t\t<exchanges>\n");
- out.write("\t\t\t\t<exchange>\n");
- out.write("\t\t\t\t\t<durable>true</durable>\n");
- out.write("\t\t\t\t</exchange>\n");
- out.write("\t\tt</exchanges>\n");
- out.write("\t\t</fish>\n");
- out.write("\t</virtualhost>\n");
- out.write("</virtualhosts>\n");
- out.write("</broker>\n");
- out.close();
-
- // Load config
- ServerConfiguration config = new ServerConfiguration(mainFile.getAbsoluteFile());
- config.initialise();
-
- // Test config
- VirtualHostConfiguration testHost = config.getVirtualHostConfig("test");
- ExchangeConfiguration testExchange = testHost.getExchangeConfiguration("test.topic");
- VirtualHostConfiguration fishHost = config.getVirtualHostConfig("fish");
- ExchangeConfiguration fishExchange = fishHost.getExchangeConfiguration("fish.topic");
-
- assertEquals("Incorrect virtualhost count", 2, config.getVirtualHosts().length);
- assertEquals("Incorrect virtualhost name", "test", testHost.getName());
- assertFalse("Incorrect exchange durable property", testExchange.getDurable());
- assertEquals("Incorrect virtualhost name", "fish", fishHost.getName());
- assertTrue("Incorrect exchange durable property", fishExchange.getDurable());
- }
-
- /**
- * Test that configuration loads correctly when the virtualhost configuration is a set of overriding
- * configuration files that resets a property of a virtualhost. The opmost overriding configuration
- * property value should be used.
- * <p>
- * Test for QPID-2361
- */
- public void testCombinedVirtualhostOverride() throws Exception
- {
- // Write out combined config file
- File mainFile = File.createTempFile(getClass().getName(), "main");
- File vhostsFile = File.createTempFile(getClass().getName(), "vhosts");
- File fileA = File.createTempFile(getClass().getName(), "vhosts-override");
- File fileB = File.createTempFile(getClass().getName(), "vhosts-base");
- mainFile.deleteOnExit();
- vhostsFile.deleteOnExit();
- fileA.deleteOnExit();
- fileB.deleteOnExit();
- writeConfigFile(mainFile, true, false, vhostsFile, null);
- writeCombinedConfigFile(vhostsFile, fileA, fileB);
-
- // Write out overriding virtualhosts sections
- FileWriter out = new FileWriter(fileA);
- out.write("<virtualhosts>\n");
- out.write("\t<virtualhost>\n");
- out.write("\t\t<test>\n");
- out.write("\t\t\t<exchanges>\n");
- out.write("\t\t\t\t<exchange>\n");
- out.write("\t\t\t\t\t<durable>false</durable>\n");
- out.write("\t\t\t\t</exchange>\n");
- out.write("\t\tt</exchanges>\n");
- out.write("\t\t</test>\n");
- out.write("\t</virtualhost>\n");
- out.write("</virtualhosts>\n");
- out.close();
- writeVirtualHostsFile(fileB, "test");
-
- // Load config
- ServerConfiguration config = new ServerConfiguration(mainFile.getAbsoluteFile());
- config.initialise();
-
- // Test config
- VirtualHostConfiguration testHost = config.getVirtualHostConfig("test");
- ExchangeConfiguration testExchange = testHost.getExchangeConfiguration("test.topic");
-
- assertEquals("Incorrect virtualhost count", 1, config.getVirtualHosts().length);
- assertEquals("Incorrect virtualhost name", "test", testHost.getName());
- assertFalse("Incorrect exchange durable property", testExchange.getDurable());
- }
-
- /**
- * Test that configuration loads correctly when the virtualhost configuration is a set of overriding
- * configuration files that define multiple virtualhosts, one per file. Only the virtualhosts defined in
- * the topmost file should be used.
- * <p>
- * Test for QPID-2361
- */
- public void testCombinedMultipleVirtualhosts() throws Exception
- {
- // Write out combined config file
- File mainFile = File.createTempFile(getClass().getName(), "main");
- File vhostsFile = File.createTempFile(getClass().getName(), "vhosts");
- File fileA = File.createTempFile(getClass().getName(), "vhosts-one");
- File fileB = File.createTempFile(getClass().getName(), "vhosts-two");
- mainFile.deleteOnExit();
- vhostsFile.deleteOnExit();
- fileA.deleteOnExit();
- fileB.deleteOnExit();
- writeConfigFile(mainFile, true, false, vhostsFile, null);
- writeCombinedConfigFile(vhostsFile, fileA, fileB);
-
- // Write both virtualhosts definitions
- writeVirtualHostsFile(fileA, "test-one");
- writeVirtualHostsFile(fileB, "test-two");
-
- // Load config
- ServerConfiguration config = new ServerConfiguration(mainFile.getAbsoluteFile());
- config.initialise();
-
- // Test config
- VirtualHostConfiguration oneHost = config.getVirtualHostConfig("test-one");
-
- assertEquals("Incorrect virtualhost count", 1, config.getVirtualHosts().length);
- assertEquals("Incorrect virtualhost name", "test-one", oneHost.getName());
- }
-
- /**
- * Test that a non-existant virtualhost file throws a {@link ConfigurationException}.
- * <p>
- * Test for QPID-2624
- */
- public void testNonExistantVirtualhosts() throws Exception
- {
- // Write out combined config file
- File mainFile = File.createTempFile(getClass().getName(), "main");
- File vhostsFile = new File("doesnotexist");
- mainFile.deleteOnExit();
- writeConfigFile(mainFile, true, false, vhostsFile, null);
-
- // Load config
- try
- {
- ServerConfiguration config = new ServerConfiguration(mainFile.getAbsoluteFile());
- config.initialise();
- }
- catch (ConfigurationException ce)
- {
- assertEquals("Virtualhosts file does not exist", ce.getMessage());
- }
- catch (Exception e)
- {
- fail("Should throw a ConfigurationException");
- }
- }
-
- /*
- * Tests that the old element security.jmx.access (that used to be used
- * to define JMX access rights) is rejected.
- */
- public void testManagementAccessRejected() throws ConfigurationException
- {
- // Check default
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- serverConfig.initialise();
-
- // Check value we set
- _config.setProperty("security.jmx.access(0)", "jmxremote.access");
- serverConfig = new ServerConfiguration(_config);
-
- try
- {
- serverConfig.initialise();
- fail("Exception not thrown");
- }
- catch (ConfigurationException ce)
- {
- assertEquals("Incorrect error message",
- "Validation error : security/jmx/access is no longer a supported element within the configuration xml.",
- ce.getMessage());
- }
- }
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/configuration/TopicConfigurationTest.java b/java/broker/src/test/java/org/apache/qpid/server/configuration/TopicConfigurationTest.java
deleted file mode 100644
index 7fc3b2d06a..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/configuration/TopicConfigurationTest.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.server.configuration;
-
-import org.apache.commons.configuration.ConfigurationException;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.AMQInternalException;
-import org.apache.qpid.AMQSecurityException;
-import org.apache.qpid.exchange.ExchangeDefaults;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.server.exchange.Exchange;
-import org.apache.qpid.server.queue.AMQQueue;
-import org.apache.qpid.server.queue.AMQQueueFactory;
-import org.apache.qpid.server.util.InternalBrokerBaseCase;
-
-/**
- * Test of the new Topic configuration processing
- */
-public class TopicConfigurationTest extends InternalBrokerBaseCase
-{
-
- @Override
- public void configure()
- {
- getConfigXml().addProperty("virtualhosts.virtualhost.test.topics.topic.name", "stocks.nyse.appl");
-
- getConfigXml().addProperty("virtualhosts.virtualhost.test.topics.topic(1).subscriptionName", getName()+":stockSubscription");
-
- getConfigXml().addProperty("virtualhosts.virtualhost.test.topics.topic(2).name", "stocks.nyse.orcl");
- getConfigXml().addProperty("virtualhosts.virtualhost.test.topics.topic(2).subscriptionName", getName()+":stockSubscription");
- }
-
- /**
- * Test that a TopicConfig object is created and attached to the queue when it is bound to the topic exchange.
- *
-
- * @throws ConfigurationException
- * @throws AMQSecurityException
- */
- public void testTopicCreation() throws ConfigurationException, AMQSecurityException, AMQInternalException
- {
- Exchange topicExchange = getVirtualHost().getExchangeRegistry().getExchange(ExchangeDefaults.TOPIC_EXCHANGE_NAME);
- getVirtualHost().getBindingFactory().addBinding("stocks.nyse.appl", getQueue(), topicExchange, null);
-
- TopicConfig config = getQueue().getConfiguration().getConfiguration(TopicConfig.class.getName());
-
- assertNotNull("Queue should have topic configuration bound to it.", config);
- assertEquals("Configuration name not correct", "stocks.nyse.appl", config.getName());
- }
-
- /**
- * Test that a queue created for a subscription correctly has topic
- * configuration selected based on the subscription and topic name.
- *
- * @throws ConfigurationException
- * @throws AMQException
- */
- public void testSubscriptionWithTopicCreation() throws ConfigurationException, AMQException
- {
-
- AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(new AMQShortString(getName()+":stockSubscription"), false, new AMQShortString("testowner"),
- false, false, getVirtualHost(), null);
-
- getVirtualHost().getQueueRegistry().registerQueue(queue);
- Exchange defaultExchange = getVirtualHost().getExchangeRegistry().getDefaultExchange();
- getVirtualHost().getBindingFactory().addBinding(getName(), queue, defaultExchange, null);
-
-
- Exchange topicExchange = getVirtualHost().getExchangeRegistry().getExchange(ExchangeDefaults.TOPIC_EXCHANGE_NAME);
- getVirtualHost().getBindingFactory().addBinding("stocks.nyse.orcl", queue, topicExchange, null);
-
- TopicConfig config = queue.getConfiguration().getConfiguration(TopicConfig.class.getName());
-
- assertNotNull("Queue should have topic configuration bound to it.", config);
- assertEquals("Configuration subscription name not correct", getName() + ":stockSubscription", config.getSubscriptionName());
- assertEquals("Configuration name not correct", "stocks.nyse.orcl", config.getName());
-
- }
-
- /**
- * Test that a queue created for a subscription correctly has topic
- * configuration attached here this should be the generic topic section
- * with just the subscriptionName
- *
- * @throws ConfigurationException
- * @throws AMQException
- */
- public void testSubscriptionCreation() throws ConfigurationException, AMQException
- {
-
- AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(new AMQShortString(getName()+":stockSubscription"), false, new AMQShortString("testowner"),
- false, false, getVirtualHost(), null);
-
- getVirtualHost().getQueueRegistry().registerQueue(queue);
- Exchange defaultExchange = getVirtualHost().getExchangeRegistry().getDefaultExchange();
- getVirtualHost().getBindingFactory().addBinding(getName(), queue, defaultExchange, null);
-
-
- Exchange topicExchange = getVirtualHost().getExchangeRegistry().getExchange(ExchangeDefaults.TOPIC_EXCHANGE_NAME);
- getVirtualHost().getBindingFactory().addBinding("stocks.nyse.ibm", queue, topicExchange, null);
-
- TopicConfig config = queue.getConfiguration().getConfiguration(TopicConfig.class.getName());
-
- assertNotNull("Queue should have topic configuration bound to it.", config);
- assertEquals("Configuration subscription name not correct", getName() + ":stockSubscription", config.getSubscriptionName());
- assertEquals("Configuration name not correct", "#", config.getName());
-
- }
-
-
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/configuration/VirtualHostConfigurationTest.java b/java/broker/src/test/java/org/apache/qpid/server/configuration/VirtualHostConfigurationTest.java
deleted file mode 100644
index 593119041d..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/configuration/VirtualHostConfigurationTest.java
+++ /dev/null
@@ -1,233 +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.configuration;
-
-
-import org.apache.commons.configuration.ConfigurationException;
-import org.apache.commons.configuration.XMLConfiguration;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.server.queue.AMQPriorityQueue;
-import org.apache.qpid.server.queue.AMQQueue;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-import org.apache.qpid.server.store.TestableMemoryMessageStore;
-import org.apache.qpid.server.util.InternalBrokerBaseCase;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-
-public class VirtualHostConfigurationTest extends InternalBrokerBaseCase
-{
-
- @Override
- public void setUp() throws Exception
- {
- super.setUp();
- // Set the default configuration items
- getConfigXml().clear();
- getConfigXml().addProperty("virtualhosts.virtualhost(-1).name", "test");
- getConfigXml().addProperty("virtualhosts.virtualhost(-1).test.store.class", TestableMemoryMessageStore.class.getName());
-
- getConfigXml().addProperty("virtualhosts.virtualhost.name", getName());
- getConfigXml().addProperty("virtualhosts.virtualhost."+getName()+".store.class", TestableMemoryMessageStore.class.getName());
- }
-
- @Override
- public void createBroker()
- {
- // Prevent auto broker startup
- }
-
- public void testQueuePriority() throws Exception
- {
- // Set up queue with 5 priorities
- getConfigXml().addProperty("virtualhosts.virtualhost.testQueuePriority.queues(-1).queue(-1).name(-1)",
- "atest");
- getConfigXml().addProperty("virtualhosts.virtualhost.testQueuePriority.queues.queue.atest(-1).exchange",
- "amq.direct");
- getConfigXml().addProperty("virtualhosts.virtualhost.testQueuePriority.queues.queue.atest.priorities",
- "5");
-
- // Set up queue with JMS style priorities
- getConfigXml().addProperty("virtualhosts.virtualhost.testQueuePriority.queues(-1).queue(-1).name(-1)",
- "ptest");
- getConfigXml().addProperty("virtualhosts.virtualhost.testQueuePriority.queues.queue.ptest(-1).exchange",
- "amq.direct");
- getConfigXml().addProperty("virtualhosts.virtualhost.testQueuePriority.queues.queue.ptest.priority",
- "true");
-
- // Set up queue with no priorities
- getConfigXml().addProperty("virtualhosts.virtualhost.testQueuePriority.queues(-1).queue(-1).name(-1)",
- "ntest");
- getConfigXml().addProperty("virtualhosts.virtualhost.testQueuePriority.queues.queue.ntest(-1).exchange",
- "amq.direct");
- getConfigXml().addProperty("virtualhosts.virtualhost.testQueuePriority.queues.queue.ntest.priority",
- "false");
-
- // Start the broker now.
- super.createBroker();
-
- VirtualHost vhost =
- ApplicationRegistry.getInstance().getVirtualHostRegistry().getVirtualHost(getName());
-
- // Check that atest was a priority queue with 5 priorities
- AMQQueue atest = vhost.getQueueRegistry().getQueue(new AMQShortString("atest"));
- assertTrue(atest instanceof AMQPriorityQueue);
- assertEquals(5, ((AMQPriorityQueue) atest).getPriorities());
-
- // Check that ptest was a priority queue with 10 priorities
- AMQQueue ptest = vhost.getQueueRegistry().getQueue(new AMQShortString("ptest"));
- assertTrue(ptest instanceof AMQPriorityQueue);
- assertEquals(10, ((AMQPriorityQueue) ptest).getPriorities());
-
- // Check that ntest wasn't a priority queue
- AMQQueue ntest = vhost.getQueueRegistry().getQueue(new AMQShortString("ntest"));
- assertFalse(ntest instanceof AMQPriorityQueue);
- }
-
- public void testQueueAlerts() throws Exception
- {
- // Set up queue with 5 priorities
- getConfigXml().addProperty("virtualhosts.virtualhost.testQueueAlerts.queues.exchange", "amq.topic");
- getConfigXml().addProperty("virtualhosts.virtualhost.testQueueAlerts.queues.maximumQueueDepth", "1");
- getConfigXml().addProperty("virtualhosts.virtualhost.testQueueAlerts.queues.maximumMessageSize", "2");
- getConfigXml().addProperty("virtualhosts.virtualhost.testQueueAlerts.queues.maximumMessageAge", "3");
-
- getConfigXml().addProperty("virtualhosts.virtualhost.testQueueAlerts.queues(-1).queue(1).name(1)", "atest");
- getConfigXml().addProperty("virtualhosts.virtualhost.testQueueAlerts.queues.queue.atest(-1).exchange", "amq.direct");
- getConfigXml().addProperty("virtualhosts.virtualhost.testQueueAlerts.queues.queue.atest(-1).maximumQueueDepth", "4");
- getConfigXml().addProperty("virtualhosts.virtualhost.testQueueAlerts.queues.queue.atest(-1).maximumMessageSize", "5");
- getConfigXml().addProperty("virtualhosts.virtualhost.testQueueAlerts.queues.queue.atest(-1).maximumMessageAge", "6");
-
- getConfigXml().addProperty("virtualhosts.virtualhost.testQueueAlerts.queues(-1).queue(-1).name(-1)", "btest");
-
- // Start the broker now.
- super.createBroker();
-
- VirtualHost vhost =
- ApplicationRegistry.getInstance().getVirtualHostRegistry().getVirtualHost(getName());
-
- // Check specifically configured values
- AMQQueue aTest = vhost.getQueueRegistry().getQueue(new AMQShortString("atest"));
- assertEquals(4, aTest.getMaximumQueueDepth());
- assertEquals(5, aTest.getMaximumMessageSize());
- assertEquals(6, aTest.getMaximumMessageAge());
-
- // Check default values
- AMQQueue bTest = vhost.getQueueRegistry().getQueue(new AMQShortString("btest"));
- assertEquals(1, bTest.getMaximumQueueDepth());
- assertEquals(2, bTest.getMaximumMessageSize());
- assertEquals(3, bTest.getMaximumMessageAge());
- }
-
- /**
- * Test that the house keeping pool sizes is correctly processed
- *
- * @throws Exception
- */
- public void testHouseKeepingThreadCount() throws Exception
- {
- int initialPoolSize = 10;
-
- getConfigXml().addProperty("virtualhosts.virtualhost.testHouseKeepingThreadCount.housekeeping.poolSize",
- initialPoolSize);
-
- // Start the broker now.
- super.createBroker();
-
- VirtualHost vhost =
- ApplicationRegistry.getInstance().getVirtualHostRegistry().getVirtualHost(getName());
-
- assertEquals("HouseKeeping PoolSize not set correctly.",
- initialPoolSize, vhost.getHouseKeepingPoolSize());
- }
-
- /**
- * Test default house keeping tasks
- *
- * @throws Exception
- */
- public void testDefaultHouseKeepingTasks() throws Exception
- {
- // Start the broker now.
- super.createBroker();
-
- VirtualHost vhost =
- ApplicationRegistry.getInstance().getVirtualHostRegistry().getVirtualHost(getName());
-
- assertEquals("Default houseKeeping task count incorrect.", 2,
- vhost.getHouseKeepingTaskCount());
-
- // Currently the two are tasks:
- // ExpiredMessageTask from VirtualHost
- // UpdateTask from the QMF ManagementExchange
- }
-
- /**
- * Test that we can dynamically change the thread pool size
- *
- * @throws Exception
- */
- public void testDynamicHouseKeepingPoolSizeChange() throws Exception
- {
- int initialPoolSize = 10;
-
- getConfigXml().addProperty("virtualhosts.virtualhost.testDynamicHouseKeepingPoolSizeChange.housekeeping.poolSize",
- initialPoolSize);
-
- // Start the broker now.
- super.createBroker();
-
- VirtualHost vhost =
- ApplicationRegistry.getInstance().getVirtualHostRegistry().getVirtualHost(getName());
-
- assertEquals("HouseKeeping PoolSize not set correctly.",
- initialPoolSize, vhost.getHouseKeepingPoolSize());
-
- vhost.setHouseKeepingPoolSize(1);
-
- assertEquals("HouseKeeping PoolSize not correctly change.",
- 1, vhost.getHouseKeepingPoolSize());
-
- }
-
- /**
- * Tests that the old element security.authentication.name is rejected. This element
- * was never supported properly as authentication is performed before the virtual host
- * is considered.
- */
- public void testSecurityAuthenticationNameRejected() throws Exception
- {
- getConfigXml().addProperty("virtualhosts.virtualhost.testSecurityAuthenticationNameRejected.security.authentication.name",
- "testdb");
-
- try
- {
- super.createBroker();
- fail("Exception not thrown");
- }
- catch(ConfigurationException ce)
- {
- assertEquals("Incorrect error message",
- "Validation error : security/authentication/name is no longer a supported element within the configuration xml." +
- " It appears in virtual host definition : " + getName(),
- ce.getMessage());
- }
- }
-
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/configuration/plugins/ConfigurationPluginTest.java b/java/broker/src/test/java/org/apache/qpid/server/configuration/plugins/ConfigurationPluginTest.java
deleted file mode 100644
index ee2f77f16b..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/configuration/plugins/ConfigurationPluginTest.java
+++ /dev/null
@@ -1,210 +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.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;
-
-/**
- * Test that verifies that given a Configuration a ConfigurationPlugin can
- * process and validate that data.
- */
-public class ConfigurationPluginTest extends InternalBrokerBaseCase
-{
- private static final double DOUBLE = 3.14;
- private static final long POSITIVE_LONG = 1000;
- private static final long NEGATIVE_LONG = -1000;
- private static final int LIST_SIZE = 3;
-
- class ConfigPlugin extends ConfigurationPlugin
- {
- @Override
- public String[] getElementsProcessed()
- {
- return new String[]{"[@property]", "name",
- "positiveLong", "negativeLong",
- "true", "list", "double"};
- }
-
- @Override
- public void validateConfiguration() throws ConfigurationException
- {
- // no validation requried
- }
-
- public String getName()
- {
- return getStringValue("name");
- }
-
- public String getProperty()
- {
- return getStringValue("[@property]");
- }
-
-
- }
-
- ConfigPlugin _plugin;
-
- @Override
- public void setUp() throws Exception
- {
- // Test does not directly use the AppRegistry but the configured broker
- // is required for the correct ConfigurationPlugin processing
- super.setUp();
- XMLConfiguration xmlconfig = new XMLConfiguration();
- xmlconfig.addProperty("base.element[@property]", "property");
- xmlconfig.addProperty("base.element.name", "name");
- // We make these strings as that is how they will be read from the file.
- xmlconfig.addProperty("base.element.positiveLong", String.valueOf(POSITIVE_LONG));
- xmlconfig.addProperty("base.element.negativeLong", String.valueOf(NEGATIVE_LONG));
- xmlconfig.addProperty("base.element.boolean", String.valueOf(true));
- xmlconfig.addProperty("base.element.double", String.valueOf(DOUBLE));
- for (int i = 0; i < LIST_SIZE; i++)
- {
- xmlconfig.addProperty("base.element.list", i);
- }
-
- //Use a composite configuration as this is what our broker code uses.
- CompositeConfiguration composite = new CompositeConfiguration();
- composite.addConfiguration(xmlconfig);
-
- _plugin = new ConfigPlugin();
-
- try
- {
- _plugin.setConfiguration("base.element", composite.subset("base.element"));
- }
- catch (ConfigurationException e)
- {
- e.printStackTrace();
- fail(e.toString());
- }
-
- }
-
- public void testHasConfiguration()
- {
- assertTrue("Plugin has no configuration ", _plugin.hasConfiguration());
- _plugin = new ConfigPlugin();
- assertFalse("Plugins has configuration", _plugin.hasConfiguration());
- }
-
- public void testValuesRetreived()
- {
- assertEquals("Name not correct", "name", _plugin.getName());
- assertEquals("Property not correct", "property", _plugin.getProperty());
- }
-
- public void testContainsPositiveLong()
- {
- assertTrue("positiveLong is not positive", _plugin.containsPositiveLong("positiveLong"));
- assertFalse("NonExistentValue was found", _plugin.containsPositiveLong("NonExistentValue"));
-
- try
- {
- _plugin.validatePositiveLong("positiveLong");
- }
- catch (ConfigurationException e)
- {
- fail(e.getMessage());
- }
-
- try
- {
- _plugin.validatePositiveLong("negativeLong");
- fail("negativeLong should not be positive");
- }
- catch (ConfigurationException e)
- {
- assertEquals("negativeLong should not be reported as positive",
- "ConfigPlugin: unable to configure invalid negativeLong:" + NEGATIVE_LONG, e.getMessage());
- }
-
- }
-
- public void testDouble()
- {
- assertEquals("Double value not returned", DOUBLE, _plugin.getDoubleValue("double"));
- assertEquals("default Double value not returned", 0.0, _plugin.getDoubleValue("NonExistent"));
- assertEquals("set default Double value not returned", DOUBLE, _plugin.getDoubleValue("NonExistent", DOUBLE));
- }
-
- public void testLong()
- {
- assertTrue("Long value not returned", _plugin.containsLong("positiveLong"));
- assertFalse("Long value returned", _plugin.containsLong("NonExistent"));
- assertEquals("Long value not returned", POSITIVE_LONG, _plugin.getLongValue("positiveLong"));
- assertEquals("default Long value not returned", 0, _plugin.getLongValue("NonExistent"));
- assertEquals("set default Long value not returned", NEGATIVE_LONG, _plugin.getLongValue("NonExistent", NEGATIVE_LONG));
- }
-
- public void testInt()
- {
- assertTrue("Int value not returned", _plugin.containsInt("positiveLong"));
- assertFalse("Int value returned", _plugin.containsInt("NonExistent"));
- assertEquals("Int value not returned", (int) POSITIVE_LONG, _plugin.getIntValue("positiveLong"));
- assertEquals("default Int value not returned", 0, _plugin.getIntValue("NonExistent"));
- assertEquals("set default Int value not returned", (int) NEGATIVE_LONG, _plugin.getIntValue("NonExistent", (int) NEGATIVE_LONG));
- }
-
- public void testString()
- {
- assertEquals("String value not returned", "name", _plugin.getStringValue("name"));
- assertNull("Null default String value not returned", _plugin.getStringValue("NonExistent", null));
- assertNull("default String value not returned", _plugin.getStringValue("NonExistent"));
- assertEquals("default String value not returned", "Default", _plugin.getStringValue("NonExistent", "Default"));
- }
-
- public void testBoolean()
- {
- assertTrue("Boolean value not returned", _plugin.containsBoolean("boolean"));
- assertFalse("Boolean value not returned", _plugin.containsBoolean("NonExistent"));
- assertTrue("Boolean value not returned", _plugin.getBooleanValue("boolean"));
- assertFalse("default String value not returned", _plugin.getBooleanValue("NonExistent"));
- assertTrue("set default String value not returned", _plugin.getBooleanValue("NonExistent", true));
- }
-
- public void testList()
- {
- assertTrue("list not found in plugin", _plugin.contains("list"));
- List list = _plugin.getListValue("list");
- assertNotNull("Returned list should not be null", list);
- assertEquals("List should not be empty", LIST_SIZE, list.size());
-
- list = _plugin.getListValue("NonExistent");
- assertNotNull("Returned list should not be null", list);
- assertEquals("List is not empty", 0, list.size());
- }
-
- public void testContains()
- {
- assertTrue("list not found in plugin", _plugin.contains("list"));
- assertFalse("NonExistent found in plugin", _plugin.contains("NonExistent"));
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/exchange/AbstractHeadersExchangeTestBase.java b/java/broker/src/test/java/org/apache/qpid/server/exchange/AbstractHeadersExchangeTestBase.java
deleted file mode 100644
index 9e831b2a8e..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/exchange/AbstractHeadersExchangeTestBase.java
+++ /dev/null
@@ -1,625 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.exchange;
-
-import junit.framework.TestCase;
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.AMQException;
-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.FieldTable;
-import org.apache.qpid.framing.FieldTableFactory;
-import org.apache.qpid.framing.abstraction.MessagePublishInfo;
-import org.apache.qpid.server.binding.Binding;
-import org.apache.qpid.server.binding.BindingFactory;
-import org.apache.qpid.server.message.AMQMessage;
-import org.apache.qpid.server.message.AMQMessageHeader;
-import org.apache.qpid.server.message.MessageMetaData;
-import org.apache.qpid.server.message.ServerMessage;
-import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.server.queue.AMQQueue;
-import org.apache.qpid.server.queue.BaseQueue;
-import org.apache.qpid.server.queue.IncomingMessage;
-import org.apache.qpid.server.queue.MockStoredMessage;
-import org.apache.qpid.server.queue.QueueEntry;
-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.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);
-
- private final HeadersExchange exchange = new HeadersExchange();
- protected final Set<TestQueue> queues = new HashSet<TestQueue>();
-
-
-
- /**
- * Not used in this test, just there to stub out the routing calls
- */
- private MessageStore _store = new MemoryMessageStore();
-
-
- BindingFactory bindingFactory = new BindingFactory(new DurableConfigurationStore.Source()
- {
-
- public DurableConfigurationStore getDurableConfigurationStore()
- {
- return _store;
- }
- },
- exchange);
-
- private int count;
-
- public void testDoNothing()
- {
- // this is here only to make junit under Eclipse happy
- }
-
- protected TestQueue bindDefault(String... bindings) throws AMQException
- {
- String queueName = "Queue" + (++count);
-
- return bind(queueName, queueName, getHeadersMap(bindings));
- }
-
- protected void unbind(TestQueue queue, String... bindings) throws AMQException
- {
- String queueName = queue.getName();
- //TODO - check this
- exchange.onUnbind(new Binding(null,queueName, queue, exchange, getHeadersMap(bindings)));
- }
-
- protected int getCount()
- {
- return count;
- }
-
- private TestQueue bind(String key, String queueName, Map<String,Object> args) throws AMQException
- {
- TestQueue queue = new TestQueue(new AMQShortString(queueName));
- queues.add(queue);
- exchange.onBind(new Binding(null,key, queue, exchange, args));
- return queue;
- }
-
-
- protected int route(Message m) throws AMQException
- {
- m.getIncomingMessage().headersReceived();
- m.route(exchange);
- if(m.getIncomingMessage().allContentReceived())
- {
- for(BaseQueue q : m.getIncomingMessage().getDestinationQueues())
- {
- q.enqueue(m);
- }
- }
- return m.getIncomingMessage().getDestinationQueues().size();
- }
-
- protected void routeAndTest(Message m, TestQueue... expected) throws AMQException
- {
- routeAndTest(m, false, Arrays.asList(expected));
- }
-
- protected void routeAndTest(Message m, boolean expectReturn, TestQueue... expected) throws AMQException
- {
- routeAndTest(m, expectReturn, Arrays.asList(expected));
- }
-
- protected void routeAndTest(Message m, List<TestQueue> expected) throws AMQException
- {
- routeAndTest(m, false, expected);
- }
-
- protected void routeAndTest(Message m, boolean expectReturn, List<TestQueue> expected) throws AMQException
- {
- int queueCount = route(m);
-
- for (TestQueue q : queues)
- {
- if (expected.contains(q))
- {
- assertTrue("Expected " + m + " to be delivered to " + q, q.isInQueue(m));
- //assert m.isInQueue(q) : "Expected " + m + " to be delivered to " + q;
- }
- else
- {
- assertFalse("Did not expect " + m + " to be delivered to " + q, q.isInQueue(m));
- //assert !m.isInQueue(q) : "Did not expect " + m + " to be delivered to " + q;
- }
- }
-
- if(expectReturn)
- {
- assertEquals("Expected "+m+" to be returned due to manadatory flag, and lack of routing",0, queueCount);
- }
-
- }
-
- static Map<String,Object> getHeadersMap(String... entries)
- {
- if(entries == null)
- {
- return null;
- }
-
- Map<String,Object> headers = new HashMap<String,Object>();
-
- for (String s : entries)
- {
- String[] parts = s.split("=", 2);
- headers.put(parts[0], parts.length > 1 ? parts[1] : "");
- }
- return headers;
- }
-
- static FieldTable getHeaders(String... entries)
- {
- FieldTable headers = FieldTableFactory.newFieldTable();
- for (String s : entries)
- {
- String[] parts = s.split("=", 2);
- headers.setObject(parts[0], parts.length > 1 ? parts[1] : "");
- }
- return headers;
- }
-
-
- static final class MessagePublishInfoImpl implements MessagePublishInfo
- {
- private AMQShortString _exchange;
- private boolean _immediate;
- private boolean _mandatory;
- private AMQShortString _routingKey;
-
- public MessagePublishInfoImpl(AMQShortString routingKey)
- {
- _routingKey = routingKey;
- }
-
- public MessagePublishInfoImpl(AMQShortString exchange, boolean immediate, boolean mandatory, AMQShortString routingKey)
- {
- _exchange = exchange;
- _immediate = immediate;
- _mandatory = mandatory;
- _routingKey = routingKey;
- }
-
- public AMQShortString getExchange()
- {
- return _exchange;
- }
-
- public boolean isImmediate()
- {
- return _immediate;
-
- }
-
- public boolean isMandatory()
- {
- return _mandatory;
- }
-
- public AMQShortString getRoutingKey()
- {
- return _routingKey;
- }
-
-
- public void setExchange(AMQShortString exchange)
- {
- _exchange = exchange;
- }
-
- public void setImmediate(boolean immediate)
- {
- _immediate = immediate;
- }
-
- public void setMandatory(boolean mandatory)
- {
- _mandatory = mandatory;
- }
-
- public void setRoutingKey(AMQShortString routingKey)
- {
- _routingKey = routingKey;
- }
- }
-
- static MessagePublishInfo getPublishRequest(final String id)
- {
- return new MessagePublishInfoImpl(null, false, false, new AMQShortString(id));
- }
-
- static ContentHeaderBody getContentHeader(FieldTable headers)
- {
- ContentHeaderBody header = new ContentHeaderBody();
- header.setProperties(getProperties(headers));
- return header;
- }
-
- static BasicContentHeaderProperties getProperties(FieldTable headers)
- {
- BasicContentHeaderProperties properties = new BasicContentHeaderProperties();
- properties.setHeaders(headers);
- return properties;
- }
-
- static class TestQueue extends SimpleAMQQueue
- {
- final List<HeadersExchangeTest.Message> messages = new ArrayList<HeadersExchangeTest.Message>();
-
- public String toString()
- {
- return getNameShortString().toString();
- }
-
- public TestQueue(AMQShortString name) throws AMQException
- {
- super(name, false, new AMQShortString("test"), true, false,ApplicationRegistry.getInstance().getVirtualHostRegistry().getVirtualHost("test"), Collections.EMPTY_MAP);
- ApplicationRegistry.getInstance().getVirtualHostRegistry().getVirtualHost("test").getQueueRegistry().registerQueue(this);
- }
-
-
-
- /**
- * We override this method so that the default behaviour, which attempts to use a delivery manager, is
- * not invoked. It is unnecessary since for this test we only care to know whether the message was
- * sent to the queue; the queue processing logic is not being tested.
- * @param msg
- * @throws AMQException
- */
- @Override
- public void enqueue(ServerMessage msg, PostEnqueueAction action) throws AMQException
- {
- messages.add( new HeadersExchangeTest.Message((AMQMessage) msg));
- final QueueEntry queueEntry = new QueueEntry()
- {
-
- public AMQQueue getQueue()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public AMQMessage getMessage()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public long getSize()
- {
- return 0; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean getDeliveredToConsumer()
- {
- return false; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean expired() throws AMQException
- {
- return false; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean isAvailable()
- {
- return false; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean isAcquired()
- {
- return false; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean acquire()
- {
- return false; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean acquire(Subscription sub)
- {
- return false; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean delete()
- {
- return false;
- }
-
- public boolean isDeleted()
- {
- return false;
- }
-
- public boolean acquiredBySubscription()
- {
- return false; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean isAcquiredBy(Subscription subscription)
- {
- return false; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void release()
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean releaseButRetain()
- {
- return false;
- }
-
- public boolean immediateAndNotDelivered()
- {
- return false; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void setRedelivered()
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public AMQMessageHeader getMessageHeader()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean isPersistent()
- {
- return false; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean isRedelivered()
- {
- return false; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public Subscription getDeliveredSubscription()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void reject()
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void reject(Subscription subscription)
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean isRejectedBy(Subscription subscription)
- {
- return false; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void requeue(Subscription subscription)
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void dequeue()
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void dispose()
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void discard()
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void routeToAlternate()
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean isQueueDeleted()
- {
- return false; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void addStateChangeListener(StateChangeListener listener)
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean removeStateChangeListener(StateChangeListener listener)
- {
- return false; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public int compareTo(final QueueEntry o)
- {
- return 0; //To change body of implemented methods use File | Settings | File Templates.
- }
- };
-
- if(action != null)
- {
- action.onEnqueue(queueEntry);
- }
-
- }
-
- boolean isInQueue(Message msg)
- {
- return messages.contains(msg);
- }
-
- }
-
- /**
- * Just add some extra utility methods to AMQMessage to aid testing.
- */
- static class Message extends AMQMessage
- {
- private static AtomicLong _messageId = new AtomicLong();
-
- private class TestIncomingMessage extends IncomingMessage
- {
-
- public TestIncomingMessage(final long messageId,
- final MessagePublishInfo info,
- final AMQProtocolSession publisher)
- {
- super(info);
- }
-
-
- public AMQMessage getUnderlyingMessage()
- {
- return Message.this;
- }
-
-
- public ContentHeaderBody getContentHeader()
- {
- try
- {
- return Message.this.getContentHeaderBody();
- }
- catch (AMQException e)
- {
- throw new RuntimeException(e);
- }
- }
- }
-
- private IncomingMessage _incoming;
-
-
- Message(AMQProtocolSession protocolSession, String id, String... headers) throws AMQException
- {
- this(protocolSession, id, getHeaders(headers));
- }
-
- Message(AMQProtocolSession protocolSession, String id, FieldTable headers) throws AMQException
- {
- this(protocolSession, _messageId.incrementAndGet(),getPublishRequest(id), getContentHeader(headers), Collections.EMPTY_LIST);
- }
-
- public IncomingMessage getIncomingMessage()
- {
- return _incoming;
- }
-
- private Message(AMQProtocolSession protocolsession, long messageId,
- MessagePublishInfo publish,
- ContentHeaderBody header,
- List<ContentBody> bodies) throws AMQException
- {
- super(new MockStoredMessage(messageId, publish, header));
-
- StoredMessage<MessageMetaData> storedMessage = getStoredMessage();
-
- int pos = 0;
- for(ContentBody body : bodies)
- {
- storedMessage.addContent(pos, body.payload.duplicate().buf());
- pos += body.payload.limit();
- }
-
- _incoming = new TestIncomingMessage(getMessageId(),publish, protocolsession);
- _incoming.setContentHeaderBody(header);
-
-
- }
-
-
- private Message(AMQMessage msg) throws AMQException
- {
- super(msg.getStoredMessage());
- }
-
-
-
- void route(Exchange exchange) throws AMQException
- {
- _incoming.enqueue(exchange.route(_incoming));
- }
-
-
- public int hashCode()
- {
- return getKey().hashCode();
- }
-
- public boolean equals(Object o)
- {
- return o instanceof HeadersExchangeTest.Message && equals((HeadersExchangeTest.Message) o);
- }
-
- private boolean equals(HeadersExchangeTest.Message m)
- {
- return getKey().equals(m.getKey());
- }
-
- public String toString()
- {
- return getKey().toString();
- }
-
- private Object getKey()
- {
- try
- {
- return getMessagePublishInfo().getRoutingKey();
- }
- catch (AMQException e)
- {
- _log.error("Error getting routing key: " + e, e);
- return null;
- }
- }
- }
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/exchange/ExchangeMBeanTest.java b/java/broker/src/test/java/org/apache/qpid/server/exchange/ExchangeMBeanTest.java
deleted file mode 100644
index 71e92b5294..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/exchange/ExchangeMBeanTest.java
+++ /dev/null
@@ -1,195 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.exchange;
-
-import junit.framework.TestCase;
-
-import org.apache.qpid.management.common.mbeans.ManagedExchange;
-import org.apache.qpid.server.queue.QueueRegistry;
-import org.apache.qpid.server.queue.AMQQueue;
-import org.apache.qpid.server.queue.AMQQueueFactory;
-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.openmbean.TabularData;
-import java.util.ArrayList;
-import java.util.Collections;
-
-/**
- * Unit test class for testing different Exchange MBean operations
- */
-public class ExchangeMBeanTest extends InternalBrokerBaseCase
-{
- private AMQQueue _queue;
- private QueueRegistry _queueRegistry;
- private VirtualHost _virtualHost;
-
- /**
- * Test for direct exchange mbean
- * @throws Exception
- */
-
- public void testDirectExchangeMBean() throws Exception
- {
- DirectExchange exchange = new DirectExchange();
- exchange.initialise(_virtualHost, ExchangeDefaults.DIRECT_EXCHANGE_NAME, false, 0, true);
- ManagedObject managedObj = exchange.getManagedObject();
- ManagedExchange mbean = (ManagedExchange)managedObj;
-
- mbean.createNewBinding(_queue.getNameShortString().toString(), "binding1");
- mbean.createNewBinding(_queue.getNameShortString().toString(), "binding2");
-
- TabularData data = mbean.bindings();
- ArrayList<Object> list = new ArrayList<Object>(data.values());
- assertTrue(list.size() == 2);
-
- // test general exchange properties
- assertEquals(mbean.getName(), "amq.direct");
- assertEquals(mbean.getExchangeType(), "direct");
- assertTrue(mbean.getTicketNo() == 0);
- assertTrue(!mbean.isDurable());
- assertTrue(mbean.isAutoDelete());
- }
-
- /**
- * Test for "topic" exchange mbean
- * @throws Exception
- */
-
- public void testTopicExchangeMBean() throws Exception
- {
- TopicExchange exchange = new TopicExchange();
- exchange.initialise(_virtualHost,ExchangeDefaults.TOPIC_EXCHANGE_NAME, false, 0, true);
- ManagedObject managedObj = exchange.getManagedObject();
- ManagedExchange mbean = (ManagedExchange)managedObj;
-
- mbean.createNewBinding(_queue.getNameShortString().toString(), "binding1");
- mbean.createNewBinding(_queue.getNameShortString().toString(), "binding2");
-
- TabularData data = mbean.bindings();
- ArrayList<Object> list = new ArrayList<Object>(data.values());
- assertTrue(list.size() == 2);
-
- // test general exchange properties
- assertEquals(mbean.getName(), "amq.topic");
- assertEquals(mbean.getExchangeType(), "topic");
- assertTrue(mbean.getTicketNo() == 0);
- assertTrue(!mbean.isDurable());
- assertTrue(mbean.isAutoDelete());
- }
-
- /**
- * Test for "Headers" exchange mbean
- * @throws Exception
- */
-
- public void testHeadersExchangeMBean() throws Exception
- {
- HeadersExchange exchange = new HeadersExchange();
- exchange.initialise(_virtualHost,ExchangeDefaults.HEADERS_EXCHANGE_NAME, false, 0, true);
- ManagedObject managedObj = exchange.getManagedObject();
- ManagedExchange mbean = (ManagedExchange)managedObj;
-
- mbean.createNewBinding(_queue.getNameShortString().toString(), "key1=binding1,key2=binding2");
- mbean.createNewBinding(_queue.getNameShortString().toString(), "key3=binding3");
-
- TabularData data = mbean.bindings();
- ArrayList<Object> list = new ArrayList<Object>(data.values());
- assertTrue(list.size() == 2);
-
- // test general exchange properties
- assertEquals(mbean.getName(), "amq.match");
- assertEquals(mbean.getExchangeType(), "headers");
- assertTrue(mbean.getTicketNo() == 0);
- assertTrue(!mbean.isDurable());
- assertTrue(mbean.isAutoDelete());
- }
-
- /**
- * Test adding bindings and removing them from the default exchange via JMX.
- * <p>
- * QPID-2700
- */
- public void testDefaultBindings() throws Exception
- {
- int bindings = _queue.getBindingCount();
-
- Exchange exchange = _queue.getVirtualHost().getExchangeRegistry().getDefaultExchange();
- ManagedExchange mbean = (ManagedExchange) ((AbstractExchange) exchange).getManagedObject();
-
- mbean.createNewBinding(_queue.getName(), "robot");
- mbean.createNewBinding(_queue.getName(), "kitten");
-
- assertEquals("Should have added two bindings", bindings + 2, _queue.getBindingCount());
-
- mbean.removeBinding(_queue.getName(), "robot");
-
- assertEquals("Should have one extra binding", bindings + 1, _queue.getBindingCount());
-
- mbean.removeBinding(_queue.getName(), "kitten");
-
- assertEquals("Should have original number of binding", bindings, _queue.getBindingCount());
- }
-
- /**
- * Test adding bindings and removing them from the topic exchange via JMX.
- * <p>
- * QPID-2700
- */
- public void testTopicBindings() throws Exception
- {
- int bindings = _queue.getBindingCount();
-
- Exchange exchange = _queue.getVirtualHost().getExchangeRegistry().getExchange(new AMQShortString("amq.topic"));
- ManagedExchange mbean = (ManagedExchange) ((AbstractExchange) exchange).getManagedObject();
-
- mbean.createNewBinding(_queue.getName(), "robot.#");
- mbean.createNewBinding(_queue.getName(), "#.kitten");
-
- assertEquals("Should have added two bindings", bindings + 2, _queue.getBindingCount());
-
- mbean.removeBinding(_queue.getName(), "robot.#");
-
- assertEquals("Should have one extra binding", bindings + 1, _queue.getBindingCount());
-
- mbean.removeBinding(_queue.getName(), "#.kitten");
-
- assertEquals("Should have original number of binding", bindings, _queue.getBindingCount());
- }
-
- @Override
- public void setUp() throws Exception
- {
- super.setUp();
-
- IApplicationRegistry applicationRegistry = ApplicationRegistry.getInstance();
- _virtualHost = applicationRegistry.getVirtualHostRegistry().getVirtualHost("test");
- _queueRegistry = _virtualHost.getQueueRegistry();
- _queue = AMQQueueFactory.createAMQQueueImpl(new AMQShortString("testQueue"), false, new AMQShortString("ExchangeMBeanTest"), false, false,
- _virtualHost, null);
- _queueRegistry.registerQueue(_queue);
- }
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/exchange/HeadersBindingTest.java b/java/broker/src/test/java/org/apache/qpid/server/exchange/HeadersBindingTest.java
deleted file mode 100644
index a7c226cbd8..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/exchange/HeadersBindingTest.java
+++ /dev/null
@@ -1,317 +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 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;
-
-/**
- */
-public class HeadersBindingTest extends TestCase
-{
-
- private class MockHeader implements AMQMessageHeader
- {
-
- private final Map<String, Object> _headers = new HashMap<String, Object>();
-
- public String getCorrelationId()
- {
- return null;
- }
-
- public long getExpiration()
- {
- return 0;
- }
-
- public String getMessageId()
- {
- return null;
- }
-
- public String getMimeType()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public String getEncoding()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public byte getPriority()
- {
- return 0;
- }
-
- public long getTimestamp()
- {
- return 0;
- }
-
- public String getType()
- {
- return null;
- }
-
- public String getReplyTo()
- {
- return null;
- }
-
- public String getReplyToExchange()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public String getReplyToRoutingKey()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public Object getHeader(String name)
- {
- return _headers.get(name);
- }
-
- public boolean containsHeaders(Set<String> names)
- {
- return _headers.keySet().containsAll(names);
- }
-
- public boolean containsHeader(String name)
- {
- return _headers.containsKey(name);
- }
-
- public void setString(String key, String value)
- {
- setObject(key,value);
- }
-
- public void setObject(String key, Object value)
- {
- _headers.put(key,value);
- }
- }
-
- private Map<String,Object> bindHeaders = new HashMap<String,Object>();
- private MockHeader matchHeaders = new MockHeader();
- private int _count = 0;
- private MockAMQQueue _queue;
-
- protected void setUp()
- {
- _count++;
- _queue = new MockAMQQueue(getQueueName());
- }
-
- protected String getQueueName()
- {
- return "Queue" + _count;
- }
-
- public void testDefault_1()
- {
- bindHeaders.put("A", "Value of A");
-
- matchHeaders.setString("A", "Value of A");
-
- Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders);
- assertTrue(new HeadersBinding(b).matches(matchHeaders));
- }
-
- public void testDefault_2()
- {
- bindHeaders.put("A", "Value of A");
-
- matchHeaders.setString("A", "Value of A");
- matchHeaders.setString("B", "Value of B");
-
- Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders);
- assertTrue(new HeadersBinding(b).matches(matchHeaders));
- }
-
- public void testDefault_3()
- {
- bindHeaders.put("A", "Value of A");
-
- matchHeaders.setString("A", "Altered value of A");
-
- Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders);
- assertFalse(new HeadersBinding(b).matches(matchHeaders));
- }
-
- public void testAll_1()
- {
- bindHeaders.put("X-match", "all");
- bindHeaders.put("A", "Value of A");
-
- matchHeaders.setString("A", "Value of A");
-
- Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders);
- assertTrue(new HeadersBinding(b).matches(matchHeaders));
- }
-
- public void testAll_2()
- {
- bindHeaders.put("X-match", "all");
- bindHeaders.put("A", "Value of A");
- bindHeaders.put("B", "Value of B");
-
- matchHeaders.setString("A", "Value of A");
-
- Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders);
- assertFalse(new HeadersBinding(b).matches(matchHeaders));
- }
-
- public void testAll_3()
- {
- bindHeaders.put("X-match", "all");
- bindHeaders.put("A", "Value of A");
- bindHeaders.put("B", "Value of B");
-
- matchHeaders.setString("A", "Value of A");
- matchHeaders.setString("B", "Value of B");
-
- Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders);
- assertTrue(new HeadersBinding(b).matches(matchHeaders));
- }
-
- public void testAll_4()
- {
- bindHeaders.put("X-match", "all");
- bindHeaders.put("A", "Value of A");
- bindHeaders.put("B", "Value of B");
-
- matchHeaders.setString("A", "Value of A");
- matchHeaders.setString("B", "Value of B");
- matchHeaders.setString("C", "Value of C");
-
- Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders);
- assertTrue(new HeadersBinding(b).matches(matchHeaders));
- }
-
- public void testAll_5()
- {
- bindHeaders.put("X-match", "all");
- bindHeaders.put("A", "Value of A");
- bindHeaders.put("B", "Value of B");
-
- matchHeaders.setString("A", "Value of A");
- matchHeaders.setString("B", "Altered value of B");
- matchHeaders.setString("C", "Value of C");
-
- Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders);
- assertFalse(new HeadersBinding(b).matches(matchHeaders));
- }
-
- public void testAny_1()
- {
- bindHeaders.put("X-match", "any");
- bindHeaders.put("A", "Value of A");
-
- matchHeaders.setString("A", "Value of A");
-
- Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders);
- assertTrue(new HeadersBinding(b).matches(matchHeaders));
- }
-
- public void testAny_2()
- {
- bindHeaders.put("X-match", "any");
- bindHeaders.put("A", "Value of A");
- bindHeaders.put("B", "Value of B");
-
- matchHeaders.setString("A", "Value of A");
-
- Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders);
- assertTrue(new HeadersBinding(b).matches(matchHeaders));
- }
-
- public void testAny_3()
- {
- bindHeaders.put("X-match", "any");
- bindHeaders.put("A", "Value of A");
- bindHeaders.put("B", "Value of B");
-
- matchHeaders.setString("A", "Value of A");
- matchHeaders.setString("B", "Value of B");
-
- Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders);
- assertTrue(new HeadersBinding(b).matches(matchHeaders));
- }
-
- public void testAny_4()
- {
- bindHeaders.put("X-match", "any");
- bindHeaders.put("A", "Value of A");
- bindHeaders.put("B", "Value of B");
-
- matchHeaders.setString("A", "Value of A");
- matchHeaders.setString("B", "Value of B");
- matchHeaders.setString("C", "Value of C");
-
- Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders);
- assertTrue(new HeadersBinding(b).matches(matchHeaders));
- }
-
- public void testAny_5()
- {
- bindHeaders.put("X-match", "any");
- bindHeaders.put("A", "Value of A");
- bindHeaders.put("B", "Value of B");
-
- matchHeaders.setString("A", "Value of A");
- matchHeaders.setString("B", "Altered value of B");
- matchHeaders.setString("C", "Value of C");
-
- Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders);
- assertTrue(new HeadersBinding(b).matches(matchHeaders));
- }
-
- public void testAny_6()
- {
- bindHeaders.put("X-match", "any");
- bindHeaders.put("A", "Value of A");
- bindHeaders.put("B", "Value of B");
-
- matchHeaders.setString("A", "Altered value of A");
- matchHeaders.setString("B", "Altered value of B");
- matchHeaders.setString("C", "Value of C");
-
- Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders);
- assertFalse(new HeadersBinding(b).matches(matchHeaders));
- }
-
- public static junit.framework.Test suite()
- {
- return new junit.framework.TestSuite(HeadersBindingTest.class);
- }
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/exchange/HeadersExchangeTest.java b/java/broker/src/test/java/org/apache/qpid/server/exchange/HeadersExchangeTest.java
deleted file mode 100644
index ac638e4e6a..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/exchange/HeadersExchangeTest.java
+++ /dev/null
@@ -1,124 +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.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;
-
- @Override
- public void setUp() throws Exception
- {
- super.setUp();
- // Just use the first vhost.
- VirtualHost
- virtualHost = ApplicationRegistry.getInstance().getVirtualHostRegistry().getVirtualHosts().iterator().next();
- _protocolSession = new InternalTestProtocolSession(virtualHost);
- }
-
- public void testSimple() throws AMQException
- {
- TestQueue q1 = bindDefault("F0000");
- TestQueue q2 = bindDefault("F0000=Aardvark");
- TestQueue q3 = bindDefault("F0001");
- TestQueue q4 = bindDefault("F0001=Bear");
- TestQueue q5 = bindDefault("F0000", "F0001");
- TestQueue q6 = bindDefault("F0000=Aardvark", "F0001=Bear");
- TestQueue q7 = bindDefault("F0000", "F0001=Bear");
- TestQueue q8 = bindDefault("F0000=Aardvark", "F0001");
-
- routeAndTest(new Message(_protocolSession, "Message1", "F0000"), q1);
- routeAndTest(new Message(_protocolSession, "Message2", "F0000=Aardvark"), q1, q2);
- routeAndTest(new Message(_protocolSession, "Message3", "F0000=Aardvark", "F0001"), q1, q2, q3, q5, q8);
- routeAndTest(new Message(_protocolSession, "Message4", "F0000", "F0001=Bear"), q1, q3, q4, q5, q7);
- routeAndTest(new Message(_protocolSession, "Message5", "F0000=Aardvark", "F0001=Bear"),
- q1, q2, q3, q4, q5, q6, q7, q8);
- routeAndTest(new Message(_protocolSession, "Message6", "F0002"));
-
- Message m7 = new Message(_protocolSession, "Message7", "XXXXX");
-
- MessagePublishInfoImpl pb7 = (MessagePublishInfoImpl) (m7.getMessagePublishInfo());
- pb7.setMandatory(true);
- routeAndTest(m7,true);
-
- Message m8 = new Message(_protocolSession, "Message8", "F0000");
- MessagePublishInfoImpl pb8 = (MessagePublishInfoImpl)(m8.getMessagePublishInfo());
- pb8.setMandatory(true);
- routeAndTest(m8,false,q1);
-
-
- }
-
- public void testAny() throws AMQException
- {
- TestQueue q1 = bindDefault("F0000", "F0001", "X-match=any");
- TestQueue q2 = bindDefault("F0000=Aardvark", "F0001=Bear", "X-match=any");
- TestQueue q3 = bindDefault("F0000", "F0001=Bear", "X-match=any");
- TestQueue q4 = bindDefault("F0000=Aardvark", "F0001", "X-match=any");
- TestQueue q6 = bindDefault("F0000=Apple", "F0001", "X-match=any");
-
- routeAndTest(new Message(_protocolSession, "Message1", "F0000"), q1, q3);
- routeAndTest(new Message(_protocolSession, "Message2", "F0000=Aardvark"), q1, q2, q3, q4);
- routeAndTest(new Message(_protocolSession, "Message3", "F0000=Aardvark", "F0001"), q1, q2, q3, q4, q6);
- routeAndTest(new Message(_protocolSession, "Message4", "F0000", "F0001=Bear"), q1, q2, q3, q4, q6);
- routeAndTest(new Message(_protocolSession, "Message5", "F0000=Aardvark", "F0001=Bear"), q1, q2, q3, q4, q6);
- routeAndTest(new Message(_protocolSession, "Message6", "F0002"));
- }
-
- public void testMandatory() throws AMQException
- {
- bindDefault("F0000");
- Message m1 = new Message(_protocolSession, "Message1", "XXXXX");
- Message m2 = new Message(_protocolSession, "Message2", "F0000");
- MessagePublishInfoImpl pb1 = (MessagePublishInfoImpl) (m1.getMessagePublishInfo());
- pb1.setMandatory(true);
- MessagePublishInfoImpl pb2 = (MessagePublishInfoImpl) (m2.getMessagePublishInfo());
- pb2.setMandatory(true);
- routeAndTest(m1,true);
- }
-
- public void testOnUnbind() throws AMQException
- {
- TestQueue q1 = bindDefault("F0000");
- TestQueue q2 = bindDefault("F0000=Aardvark");
- TestQueue q3 = bindDefault("F0001");
-
- routeAndTest(new Message(_protocolSession, "Message1", "F0000"), q1);
- routeAndTest(new Message(_protocolSession, "Message2", "F0000=Aardvark"), q1, q2);
- routeAndTest(new Message(_protocolSession, "Message3", "F0001"), q3);
-
- unbind(q1,"F0000");
- routeAndTest(new Message(_protocolSession, "Message4", "F0000"));
- routeAndTest(new Message(_protocolSession, "Message5", "F0000=Aardvark"), q2);
- }
-
-
- public static junit.framework.Test suite()
- {
- return new junit.framework.TestSuite(HeadersExchangeTest.class);
- }
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/exchange/TopicExchangeTest.java b/java/broker/src/test/java/org/apache/qpid/server/exchange/TopicExchangeTest.java
deleted file mode 100644
index 403a290a0f..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/exchange/TopicExchangeTest.java
+++ /dev/null
@@ -1,441 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- *
- */
-package org.apache.qpid.server.exchange;
-
-import junit.framework.TestCase;
-import 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.abstraction.MessagePublishInfo;
-
-public class TopicExchangeTest extends InternalBrokerBaseCase
-{
-
- TopicExchange _exchange;
-
- VirtualHost _vhost;
- MessageStore _store;
-
- InternalTestProtocolSession _protocolSession;
-
-
- @Override
- public void setUp() throws Exception
- {
- super.setUp();
- _exchange = new TopicExchange();
- _vhost = ApplicationRegistry.getInstance().getVirtualHostRegistry().getVirtualHosts().iterator().next();
- _store = new MemoryMessageStore();
- _protocolSession = new InternalTestProtocolSession(_vhost);
- }
-
- public void testNoRoute() throws AMQException
- {
- AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(new AMQShortString("a*#b"), false, null, false, false, _vhost, null);
- _exchange.registerQueue(new Binding(null,"a.*.#.b", queue,_exchange, null));
-
-
- IncomingMessage message = createMessage("a.b");
- routeMessage(message);
-
- Assert.assertEquals(0, queue.getMessageCount());
- }
-
- public void testDirectMatch() throws AMQException
- {
- AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(new AMQShortString("ab"), false, null, false, false, _vhost, null);
- _exchange.registerQueue(new Binding(null,"a.b", queue,_exchange, null));
-
-
- IncomingMessage message = createMessage("a.b");
-
- routeMessage(message);
-
- Assert.assertEquals(1, queue.getMessageCount());
-
- Assert.assertEquals("Wrong message recevied", (Object) message.getMessageNumber(), queue.getMessagesOnTheQueue().get(0).getMessage().getMessageNumber());
-
- queue.deleteMessageFromTop();
- Assert.assertEquals(0, queue.getMessageCount());
-
-
- message = createMessage("a.c");
-
- int queueCount = routeMessage(message);
- Assert.assertEquals("Message should not route to any queues", 0, queueCount);
-
- Assert.assertEquals(0, queue.getMessageCount());
- }
-
-
- public void testStarMatch() throws AMQException
- {
- AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(new AMQShortString("a*"), false, null, false, false, _vhost, null);
- _exchange.registerQueue(new Binding(null,"a.*", queue,_exchange, null));
-
-
- IncomingMessage message = createMessage("a.b");
-
- routeMessage(message);
-
- Assert.assertEquals(1, queue.getMessageCount());
-
- Assert.assertEquals("Wrong message recevied", (Object) message.getMessageNumber(), queue.getMessagesOnTheQueue().get(0).getMessage().getMessageNumber());
-
- queue.deleteMessageFromTop();
- Assert.assertEquals(0, queue.getMessageCount());
-
-
- message = createMessage("a.c");
-
- int queueCount = routeMessage(message);
-
- Assert.assertEquals(1, queue.getMessageCount());
-
- Assert.assertEquals("Wrong message recevied", (Object) message.getMessageNumber(), queue.getMessagesOnTheQueue().get(0).getMessage().getMessageNumber());
-
- queue.deleteMessageFromTop();
- Assert.assertEquals(0, queue.getMessageCount());
-
-
- message = createMessage("a");
-
-
- queueCount = routeMessage(message);
- Assert.assertEquals("Message should not route to any queues", 0, queueCount);
-
- Assert.assertEquals(0, queue.getMessageCount());
- }
-
- public void testHashMatch() throws AMQException
- {
- AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(new AMQShortString("a#"), false, null, false, false, _vhost, null);
- _exchange.registerQueue(new Binding(null,"a.#", queue,_exchange, null));
-
-
- IncomingMessage message = createMessage("a.b.c");
-
- int queueCount = routeMessage(message);
-
- Assert.assertEquals(1, queue.getMessageCount());
-
- Assert.assertEquals("Wrong message recevied", (Object) message.getMessageNumber(), queue.getMessagesOnTheQueue().get(0).getMessage().getMessageNumber());
-
- queue.deleteMessageFromTop();
- Assert.assertEquals(0, queue.getMessageCount());
-
-
- message = createMessage("a.b");
-
- queueCount = routeMessage(message);
-
- Assert.assertEquals(1, queue.getMessageCount());
-
- Assert.assertEquals("Wrong message recevied", (Object) message.getMessageNumber(), queue.getMessagesOnTheQueue().get(0).getMessage().getMessageNumber());
-
- queue.deleteMessageFromTop();
- Assert.assertEquals(0, queue.getMessageCount());
-
-
- message = createMessage("a.c");
-
- queueCount = routeMessage(message);
-
- Assert.assertEquals(1, queue.getMessageCount());
-
- Assert.assertEquals("Wrong message recevied", (Object) message.getMessageNumber(), queue.getMessagesOnTheQueue().get(0).getMessage().getMessageNumber());
-
- queue.deleteMessageFromTop();
- Assert.assertEquals(0, queue.getMessageCount());
-
- message = createMessage("a");
-
- queueCount = routeMessage(message);
-
- Assert.assertEquals(1, queue.getMessageCount());
-
- Assert.assertEquals("Wrong message recevied", (Object) message.getMessageNumber(), queue.getMessagesOnTheQueue().get(0).getMessage().getMessageNumber());
-
- queue.deleteMessageFromTop();
- Assert.assertEquals(0, queue.getMessageCount());
-
-
- message = createMessage("b");
-
-
- queueCount = routeMessage(message);
- Assert.assertEquals("Message should not route to any queues", 0, queueCount);
-
- Assert.assertEquals(0, queue.getMessageCount());
- }
-
-
- public void testMidHash() throws AMQException
- {
- AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(new AMQShortString("a"), false, null, false, false, _vhost, null);
- _exchange.registerQueue(new Binding(null,"a.*.#.b", queue,_exchange, null));
-
-
- IncomingMessage message = createMessage("a.c.d.b");
-
- routeMessage(message);
-
- Assert.assertEquals(1, queue.getMessageCount());
-
- Assert.assertEquals("Wrong message recevied", (Object) message.getMessageNumber(), queue.getMessagesOnTheQueue().get(0).getMessage().getMessageNumber());
-
- queue.deleteMessageFromTop();
- Assert.assertEquals(0, queue.getMessageCount());
-
- message = createMessage("a.c.b");
-
- routeMessage(message);
-
- Assert.assertEquals(1, queue.getMessageCount());
-
- Assert.assertEquals("Wrong message recevied", (Object) message.getMessageNumber(), queue.getMessagesOnTheQueue().get(0).getMessage().getMessageNumber());
-
- queue.deleteMessageFromTop();
- Assert.assertEquals(0, queue.getMessageCount());
-
- }
-
- public void testMatchafterHash() throws AMQException
- {
- AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(new AMQShortString("a#"), false, null, false, false, _vhost, null);
- _exchange.registerQueue(new Binding(null,"a.*.#.b.c", queue,_exchange, null));
-
-
- IncomingMessage message = createMessage("a.c.b.b");
-
- int queueCount = routeMessage(message);
- Assert.assertEquals("Message should not route to any queues", 0, queueCount);
-
- Assert.assertEquals(0, queue.getMessageCount());
-
-
- message = createMessage("a.a.b.c");
-
- routeMessage(message);
-
- Assert.assertEquals(1, queue.getMessageCount());
-
- Assert.assertEquals("Wrong message recevied", (Object) message.getMessageNumber(), queue.getMessagesOnTheQueue().get(0).getMessage().getMessageNumber());
-
- queue.deleteMessageFromTop();
- Assert.assertEquals(0, queue.getMessageCount());
-
- message = createMessage("a.b.c.b");
-
- queueCount = routeMessage(message);
- Assert.assertEquals("Message should not route to any queues", 0, queueCount);
-
- Assert.assertEquals(0, queue.getMessageCount());
-
- message = createMessage("a.b.c.b.c");
-
- routeMessage(message);
-
- Assert.assertEquals(1, queue.getMessageCount());
-
- Assert.assertEquals("Wrong message recevied", (Object) message.getMessageNumber(), queue.getMessagesOnTheQueue().get(0).getMessage().getMessageNumber());
-
- queue.deleteMessageFromTop();
- Assert.assertEquals(0, queue.getMessageCount());
-
- }
-
-
- public void testHashAfterHash() throws AMQException
- {
- AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(new AMQShortString("a#"), false, null, false, false, _vhost, null);
- _exchange.registerQueue(new Binding(null,"a.*.#.b.c.#.d", queue,_exchange, null));
-
-
- IncomingMessage message = createMessage("a.c.b.b.c");
-
- int queueCount = routeMessage(message);
- Assert.assertEquals("Message should not route to any queues", 0, queueCount);
-
- Assert.assertEquals(0, queue.getMessageCount());
-
-
- message = createMessage("a.a.b.c.d");
-
- routeMessage(message);
-
- Assert.assertEquals(1, queue.getMessageCount());
-
- Assert.assertEquals("Wrong message recevied", (Object) message.getMessageNumber(), queue.getMessagesOnTheQueue().get(0).getMessage().getMessageNumber());
-
- queue.deleteMessageFromTop();
- Assert.assertEquals(0, queue.getMessageCount());
-
- }
-
- public void testHashHash() throws AMQException
- {
- AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(new AMQShortString("a#"), false, null, false, false, _vhost, null);
- _exchange.registerQueue(new Binding(null,"a.#.*.#.d", queue,_exchange, null));
-
-
- IncomingMessage message = createMessage("a.c.b.b.c");
-
- int queueCount = routeMessage(message);
- Assert.assertEquals("Message should not route to any queues", 0, queueCount);
-
- Assert.assertEquals(0, queue.getMessageCount());
-
- message = createMessage("a.a.b.c.d");
-
- routeMessage(message);
-
- Assert.assertEquals(1, queue.getMessageCount());
-
- Assert.assertEquals("Wrong message recevied", (Object) message.getMessageNumber(), queue.getMessagesOnTheQueue().get(0).getMessage().getMessageNumber());
-
- queue.deleteMessageFromTop();
- Assert.assertEquals(0, queue.getMessageCount());
-
- }
-
- public void testSubMatchFails() throws AMQException
- {
- AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(new AMQShortString("a"), false, null, false, false, _vhost, null);
- _exchange.registerQueue(new Binding(null,"a.b.c.d", queue,_exchange, null));
-
-
- IncomingMessage message = createMessage("a.b.c");
-
- int queueCount = routeMessage(message);
- Assert.assertEquals("Message should not route to any queues", 0, queueCount);
-
- Assert.assertEquals(0, queue.getMessageCount());
-
- }
-
- private int routeMessage(final IncomingMessage message)
- throws AMQException
- {
- MessageMetaData mmd = message.headersReceived();
- message.setStoredMessage(_store.addMessage(mmd));
-
- message.enqueue(_exchange.route(message));
- AMQMessage msg = new AMQMessage(message.getStoredMessage());
- for(BaseQueue q : message.getDestinationQueues())
- {
- q.enqueue(msg);
- }
- return message.getDestinationQueues().size();
- }
-
- public void testMoreRouting() throws AMQException
- {
- AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(new AMQShortString("a"), false, null, false, false, _vhost, null);
- _exchange.registerQueue(new Binding(null,"a.b", queue,_exchange, null));
-
-
- IncomingMessage message = createMessage("a.b.c");
-
- int queueCount = routeMessage(message);
- Assert.assertEquals("Message should not route to any queues", 0, queueCount);
-
- Assert.assertEquals(0, queue.getMessageCount());
-
- }
-
- public void testMoreQueue() throws AMQException
- {
- AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(new AMQShortString("a"), false, null, false, false, _vhost, null);
- _exchange.registerQueue(new Binding(null,"a.b", queue,_exchange, null));
-
-
- IncomingMessage message = createMessage("a");
-
- int queueCount = routeMessage(message);
- Assert.assertEquals("Message should not route to any queues", 0, queueCount);
-
- Assert.assertEquals(0, queue.getMessageCount());
-
- }
-
- private IncomingMessage createMessage(String s) throws AMQException
- {
- MessagePublishInfo info = new PublishInfo(new AMQShortString(s));
-
- IncomingMessage message = new IncomingMessage(info);
- final ContentHeaderBody chb = new ContentHeaderBody();
- BasicContentHeaderProperties props = new BasicContentHeaderProperties();
- chb.setProperties(props);
- message.setContentHeaderBody(chb);
-
-
- return message;
- }
-
-
- class PublishInfo implements MessagePublishInfo
- {
- AMQShortString _routingkey;
-
- PublishInfo(AMQShortString routingkey)
- {
- _routingkey = routingkey;
- }
-
- public AMQShortString getExchange()
- {
- return null;
- }
-
- public void setExchange(AMQShortString exchange)
- {
-
- }
-
- public boolean isImmediate()
- {
- return false;
- }
-
- public boolean isMandatory()
- {
- return true;
- }
-
- public AMQShortString getRoutingKey()
- {
- return _routingkey;
- }
- }
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/Log4jMessageLoggerTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/Log4jMessageLoggerTest.java
deleted file mode 100644
index a845bff9ce..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/logging/Log4jMessageLoggerTest.java
+++ /dev/null
@@ -1,271 +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.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;
-
-/** Test that the Log4jMessageLogger defaults behave as expected */
-public class Log4jMessageLoggerTest extends TestCase
-{
- Level _rootLevel;
- Log4jTestAppender _appender;
-
- @Override
- public void setUp() throws IOException
- {
- // Setup a file for logging
- _appender = new Log4jTestAppender();
-
- Logger root = Logger.getRootLogger();
- root.addAppender(_appender);
-
- _rootLevel = Logger.getRootLogger().getLevel();
- if (_rootLevel != Level.INFO)
- {
- root.setLevel(Level.INFO);
- root.warn("Root Logger set to:" + _rootLevel + " Resetting to INFO for test.");
- }
- root.warn("Adding Test Appender:" + _appender);
- }
-
- @Override
- public void tearDown()
- {
- Logger root = Logger.getRootLogger();
- root.warn("Removing Test Appender:" + _appender);
- root.warn("Resetting Root Level to : " + _rootLevel);
-
- Logger.getRootLogger().setLevel(_rootLevel);
-
- Logger.getRootLogger().removeAppender(_appender);
-
- //Call close on our appender. This will clear the log messages
- // from Memory
- _appender.close();
- }
-
- /**
- * Verify that the Log4jMessageLogger successfully logs a message.
- */
- public void testLoggedMessage()
- {
- Log4jMessageLogger msgLogger = new Log4jMessageLogger();
- assertTrue("Expected message logger to be enabled", msgLogger.isEnabled());
-
- testLoggedMessage(msgLogger, true, getName());
- }
-
- /**
- * Verify that for the given Log4jMessageLogger, after generating a message for the given
- * log hierarchy that the outcome is as expected.
- */
- private String testLoggedMessage(Log4jMessageLogger logger, boolean logExpected, String hierarchy)
- {
- //Create Message for test
- String message = "testDefaults";
-
- // Log the message
- logger.rawMessage(message, hierarchy);
-
- if(logExpected)
- {
- verifyLogPresent(message);
- }
- else
- {
- verifyNoLog(message);
- }
-
- return message;
- }
-
- /**
- * Test that specifying different log hierarchies to be used works as expected.
- * <p/>
- * Test this by using one hierarchy and verifying it succeeds, then disabling it and
- * confirming this takes effect, and finally that using another hierarchy still succeeds.
- */
- public void testMultipleHierarchyUsage()
- {
- String loggerName1 = getName() + ".TestLogger1";
- String loggerName2 = getName() + ".TestLogger2";
-
- // Create a message logger to test
- Log4jMessageLogger msgLogger = new Log4jMessageLogger();
- assertTrue("Expected message logger to be enabled", msgLogger.isEnabled());
-
- //verify that using this hierarchy the message gets logged ok
- String message = testLoggedMessage(msgLogger, true, loggerName1);
-
- //now disable that hierarchy in log4j
- Logger.getLogger(loggerName1).setLevel(Level.OFF);
-
- //clear the previous message from the test appender
- _appender.close();
- verifyNoLog(message);
-
- //verify that the hierarchy disabling took effect
- testLoggedMessage(msgLogger, false, loggerName1);
-
- //now ensure that using a new hierarchy results in the message being output
- testLoggedMessage(msgLogger, true, loggerName2);
- }
-
- /**
- * Test that log4j can be used to manipulate on a per-hierarchy(and thus message) basis
- * whether a particular status message is enabled.
- * <p/>
- * Test this by using two hierarchies, setting one off and one on (info) via log4j directly,
- * then confirming this gives the expected isMessageEnabled() result. Then reverse the log4j
- * Levels for the Logger's and ensure the results change as expected.
- */
- public void testEnablingAndDisablingMessages()
- {
- String loggerName1 = getName() + ".TestLogger1";
- String loggerName2 = getName() + ".TestLogger2";
-
- Logger.getLogger(loggerName1).setLevel(Level.INFO);
- Logger.getLogger(loggerName2).setLevel(Level.OFF);
-
- Log4jMessageLogger msgLogger = new Log4jMessageLogger();
- BrokerActor actor = new BrokerActor(msgLogger);
-
- assertTrue("Expected message logger to be enabled", msgLogger.isEnabled());
-
- assertTrue("Message should be enabled", msgLogger.isMessageEnabled(actor, loggerName1));
- assertFalse("Message should be disabled", msgLogger.isMessageEnabled(actor, loggerName2));
-
- Logger.getLogger(loggerName1).setLevel(Level.WARN);
- Logger.getLogger(loggerName2).setLevel(Level.INFO);
-
- assertFalse("Message should be disabled", msgLogger.isMessageEnabled(actor, loggerName1));
- assertTrue("Message should be enabled", msgLogger.isMessageEnabled(actor, loggerName2));
- }
-
- /**
- * Check that the Log Message reached log4j
- * @param message the message to search for
- */
- private void verifyLogPresent(String message)
- {
- List<String> results = findMessageInLog(message);
-
- //Validate we only got one message
- assertEquals("The result set was not as expected.", 1, results.size());
-
- // Validate message
- String line = results.get(0);
-
- assertNotNull("No Message retrieved from log file", line);
- assertTrue("Message not contained in log.:" + line,
- line.contains(message));
- }
-
- /**
- * Check that the given Message is not present in the log4j records.
- * @param message the message to search for
- */
- private void verifyNoLog(String message)
- {
- List<String> results = findMessageInLog(message);
-
- if (results.size() > 0)
- {
- System.err.println("Unexpected Log messages");
-
- for (String msg : results)
- {
- System.err.println(msg);
- }
- }
-
- assertEquals("No message was expected.", 0, results.size());
- }
-
- /**
- * Get the appenders list of events and return a list of all the messages
- * that contain the given message
- *
- * @param message the search string
- * @return The list of all logged messages that contain the search string.
- */
- private List<String> findMessageInLog(String message)
- {
- List<LoggingEvent> log = _appender.getLog();
-
- // Search Results for requested message
- List<String> result = new LinkedList<String>();
-
- for (LoggingEvent event : log)
- {
- if (String.valueOf(event.getMessage()).contains(message))
- {
- result.add(String.valueOf(event.getMessage()));
- }
- }
-
- return result;
- }
-
-
- /**
- * Log4j Appender that simply records all the Logging Events so we can
- * verify that the above logging will make it to log4j in a unit test.
- */
- private class Log4jTestAppender extends AppenderSkeleton
- {
- List<LoggingEvent> _log = new LinkedList<LoggingEvent>();
-
- protected void append(LoggingEvent loggingEvent)
- {
- _log.add(loggingEvent);
- }
-
- public void close()
- {
- _log.clear();
- }
-
- /**
- * @return the list of LoggingEvents that have occured in this Appender
- */
- public List<LoggingEvent> getLog()
- {
- return _log;
- }
-
- public boolean requiresLayout()
- {
- return false;
- }
- }
-}
-
diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/LogMessageTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/LogMessageTest.java
deleted file mode 100644
index 956bb6f8fa..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/logging/LogMessageTest.java
+++ /dev/null
@@ -1,169 +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.logging;
-
-import junit.framework.TestCase;
-import org.apache.qpid.server.logging.messages.BrokerMessages;
-
-import java.util.Locale;
-import java.util.ResourceBundle;
-
-public class LogMessageTest extends TestCase
-{
-
- /**
- * Test that the US local has a loadable bundle.
- * No longer have a specific en_US bundle so cannot verify that that version
- * is loaded. Can only verify that we get a ResourceBundle loaded.
- */
- public void testBundle()
- {
- Locale usLocal = Locale.US;
- Locale.setDefault(usLocal);
- ResourceBundle _messages = ResourceBundle.getBundle("org.apache.qpid.server.logging.messages.Broker_logmessages",
- usLocal);
-
- assertNotNull("Unable to load ResourceBundle", _messages);
- }
-
- /**
- * Test that loading an undefined locale will result in loading of the
- * default US locale.
- */
- public void testUndefinedLocale()
- {
- Locale japanese = Locale.JAPANESE;
-
- Locale.setDefault(japanese);
- try
- {
- ResourceBundle _messages = ResourceBundle.getBundle("org.apache.qpid.server.logging.messages.Broker_logmessages",
- japanese);
-
- assertNotNull("Unable to load ResourceBundle", _messages);
-
- // If we attempt to load an undefined locale it should default to the Root locale.
- assertEquals("Loaded bundle has incorrect locale.", Locale.ROOT, _messages.getLocale());
- }
- catch (Throwable t)
- {
- fail(t.getMessage());
- }
- }
-
- /**
- * test Simultaneous log message generation.
- * QPID-2137 highlighted that log message generation was not thread-safe.
- * Test to ensure that simultaneous logging is possible and does not throw an exception.
- * @throws InterruptedException if there is a problem joining logging threads.
- */
- public void testSimultaneousLogging() throws InterruptedException
- {
- int LOGGERS = 10;
- int LOG_COUNT = 10;
- LogGenerator[] logGenerators = new LogGenerator[LOGGERS];
- Thread[] threads = new Thread[LOGGERS];
-
- //Create Loggers
- for (int i = 0; i < LOGGERS; i++)
- {
- logGenerators[i] = new LogGenerator(LOG_COUNT);
- threads[i] = new Thread(logGenerators[i]);
- }
-
- //Run Loggers
- for (int i = 0; i < LOGGERS; i++)
- {
- threads[i].start();
- }
-
- //End Loggers
- for (int i = 0; i < LOGGERS; i++)
- {
- threads[i].join();
- Exception e = logGenerators[i].getThrowException();
- // If we have an exception something went wrong.
- // Check and see if it was QPID-2137
- if (e != null)
- {
- // Just log out if we find the usual exception causing QPID-2137
- if (e instanceof StringIndexOutOfBoundsException)
- {
- System.err.println("Detected QPID-2137");
- }
- fail("Exception thrown during log generation:" + e);
- }
- }
- }
-
- /**
- * Inner class used by testSimultaneousLogging.
- *
- * This class creates a given number of LogMessages using the BrokerMessages package.
- * CONFIG and LISTENING messages are both created per count.
- *
- * This class is run multiple times simultaneously so that we increase the chance of
- * reproducing QPID-2137. This is reproduced when the pattern string used in the MessageFormat
- * class is changed whilst formatting is taking place.
- *
- */
- class LogGenerator implements Runnable
- {
- private Exception _exception = null;
- private int _count;
-
- /**
- * @param count The number of Log Messages to generate
- */
- LogGenerator(int count)
- {
- _count = count;
- }
-
- public void run()
- {
- try
- {
- // try and generate _count iterations of Config & Listening messages.
- for (int i = 0; i < _count; i++)
- {
- BrokerMessages.CONFIG("Config");
- BrokerMessages.LISTENING("TCP", 1234);
- }
- }
- catch (Exception e)
- {
- // if something goes wrong recorded it for later analysis.
- _exception = e;
- }
- }
-
- /**
- * Return any exception that was thrown during the log generation.
- * @return Exception
- */
- public Exception getThrowException()
- {
- return _exception;
- }
- }
-
-} \ No newline at end of file
diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/UnitTestMessageLogger.java b/java/broker/src/test/java/org/apache/qpid/server/logging/UnitTestMessageLogger.java
deleted file mode 100644
index 3752dcb37e..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/logging/UnitTestMessageLogger.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- *
- */
-package org.apache.qpid.server.logging;
-
-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
-{
- List<Object> _log;
-
- {
- _log = new LinkedList<Object>();
- }
-
- public UnitTestMessageLogger()
- {
-
- }
-
- public UnitTestMessageLogger(ServerConfiguration config)
- {
- super(config);
- }
-
- public void rawMessage(String message, String logHierarchy)
- {
- _log.add(message);
- }
-
- public void rawMessage(String message, Throwable throwable, String logHierarchy)
- {
- _log.add(message);
-
- if(throwable != null)
- {
- _log.add(throwable);
- }
- }
-
-
- public List<Object> getLogMessages()
- {
- return _log;
- }
-
- public void clearLogMessages()
- {
- _log.clear();
- }
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/UnitTestMessageLoggerTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/UnitTestMessageLoggerTest.java
deleted file mode 100644
index e2e112be8f..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/logging/UnitTestMessageLoggerTest.java
+++ /dev/null
@@ -1,103 +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.logging;
-
-import junit.framework.TestCase;
-
-import java.util.List;
-
-/**
- * Test: UnitTestMessageLoggerTest
- *
- * This test verifies that UnitTestMessageLogger adheres to its interface.
- *
- * Messages are logged, and Throwables recorded in an array that can be
- * retrieved and cleared.
- *
- */
-public class UnitTestMessageLoggerTest extends TestCase
-{
- private static final String TEST_MESSAGE = "Test";
- private static final String TEST_THROWABLE = "Test Throwable";
- private static final String TEST_HIERARCHY = "test.hierarchy";
-
- public void testRawMessage()
- {
- UnitTestMessageLogger logger = new UnitTestMessageLogger();
-
- assertEquals("Messages logged before test start", 0,
- logger.getLogMessages().size());
-
- // Log a message
- logger.rawMessage(TEST_MESSAGE, TEST_HIERARCHY);
-
- List<Object> messages = logger.getLogMessages();
-
- assertEquals("Expected to have 1 messages logged", 1, messages.size());
-
- assertEquals("First message not what was logged",
- TEST_MESSAGE, messages.get(0));
- }
-
- public void testRawMessageWithThrowable()
- {
- UnitTestMessageLogger logger = new UnitTestMessageLogger();
-
- assertEquals("Messages logged before test start", 0,
- logger.getLogMessages().size());
-
- // Log a message
- Throwable throwable = new Throwable(TEST_THROWABLE);
-
- logger.rawMessage(TEST_MESSAGE, throwable, TEST_HIERARCHY);
-
- List<Object> messages = logger.getLogMessages();
-
- assertEquals("Expected to have 2 entries", 2, messages.size());
-
- assertEquals("Message text not what was logged",
- TEST_MESSAGE, messages.get(0));
-
- assertEquals("Message throwable not what was logged",
- TEST_THROWABLE, ((Throwable) messages.get(1)).getMessage());
-
- }
-
- public void testClear()
- {
- UnitTestMessageLogger logger = new UnitTestMessageLogger();
-
- assertEquals("Messages logged before test start", 0,
- logger.getLogMessages().size());
-
- // Log a message
- logger.rawMessage(TEST_MESSAGE, null, TEST_HIERARCHY);
-
- assertEquals("Expected to have 1 messages logged",
- 1, logger.getLogMessages().size());
-
- logger.clearLogMessages();
-
- assertEquals("Expected to have no messagse after a clear",
- 0, logger.getLogMessages().size());
-
- }
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/actors/AMQPChannelActorTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/actors/AMQPChannelActorTest.java
deleted file mode 100644
index 6346fff85f..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/logging/actors/AMQPChannelActorTest.java
+++ /dev/null
@@ -1,221 +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.logging.actors;
-
-import java.util.List;
-
-import org.apache.commons.configuration.ConfigurationException;
-import org.apache.qpid.AMQException;
-
-/**
- * Test : AMQPChannelActorTest
- * Validate the AMQPChannelActor class.
- *
- * The test creates a new AMQPActor and then logs a message using it.
- *
- * The test then verifies that the logged message was the only one created and
- * that the message contains the required message.
- */
-public class AMQPChannelActorTest extends BaseConnectionActorTestCase
-{
-
- @Override
- public void configure()
- {
- // Prevent defaulting Logging to ON
- }
-
-
- @Override
- public void createBroker() throws Exception
- {
- //prevent auto-broker startup
- }
-
- private void startBrokerNow() throws Exception
- {
- super.createBroker();
-
- _amqpActor = new AMQPChannelActor(getChannel(), _rootLogger);
- }
-
-
- /**
- * Test that when logging on behalf of the channel
- * The test sends a message then verifies that it entered the logs.
- *
- * The log message should be fully repalaced (no '{n}' values) and should
- * contain the channel id ('/ch:1') identification.
- */
- public void testChannel() throws Exception
- {
- getConfigXml().setProperty("status-updates", "ON");
-
- startBrokerNow();
-
- final String message = sendTestLogMessage(_amqpActor);
-
- List<Object> logs = _rawLogger.getLogMessages();
-
- assertEquals("Message log size not as expected.", 1, logs.size());
-
- // Verify that the logged message is present in the output
- assertTrue("Message was not found in log message:" + logs.get(0),
- logs.get(0).toString().contains(message));
-
- // Verify that the message has the correct type
- assertTrue("Message contains the [con: prefix",
- logs.get(0).toString().contains("[con:"));
-
-
- // Verify that all the values were presented to the MessageFormatter
- // so we will not end up with '{n}' entries in the log.
- assertFalse("Verify that the string does not contain any '{'." + logs.get(0),
- logs.get(0).toString().contains("{"));
-
- // Verify that the logged message contains the 'ch:1' marker
- assertTrue("Message was not logged as part of channel 1" + logs.get(0),
- logs.get(0).toString().contains("/ch:1"));
-
- }
-
- /**
- * Test that if logging is configured to be off in the configuration that
- * no logging is presented
- * @throws ConfigurationException
- * @throws AMQException
- */
- public void testChannelLoggingOFF() throws Exception, AMQException
- {
- getConfigXml().setProperty("status-updates", "OFF");
-
- // Start the broker now.
- startBrokerNow();
-
- sendTestLogMessage(_amqpActor);
-
- List<Object> logs = _rawLogger.getLogMessages();
-
- assertEquals("Message log size not as expected.", 0, logs.size());
-
- }
-
- /**
- * Test that if logging is configured to be off in the configuration that
- * no logging is presented
- * @throws ConfigurationException
- * @throws AMQException
- */
- public void testChannelLoggingOfF() throws Exception, AMQException
- {
- getConfigXml().setProperty("status-updates", "OfF");
-
- startBrokerNow();
-
- sendTestLogMessage(_amqpActor);
-
- List<Object> logs = _rawLogger.getLogMessages();
-
- assertEquals("Message log size not as expected.", 0, logs.size());
-
- }
-
- /**
- * Test that if logging is configured to be off in the configuration that
- * no logging is presented
- * @throws ConfigurationException
- * @throws AMQException
- */
- public void testChannelLoggingOff() throws Exception, AMQException
- {
- getConfigXml().setProperty("status-updates", "Off");
-
- startBrokerNow();
-
- sendTestLogMessage(_amqpActor);
-
- List<Object> logs = _rawLogger.getLogMessages();
-
- assertEquals("Message log size not as expected.", 0, logs.size());
-
- }
-
- /**
- * Test that if logging is configured to be off in the configuration that
- * no logging is presented
- * @throws ConfigurationException
- * @throws AMQException
- */
- public void testChannelLoggingofF() throws Exception, AMQException
- {
- getConfigXml().setProperty("status-updates", "ofF");
-
- startBrokerNow();
-
- sendTestLogMessage(_amqpActor);
-
- List<Object> logs = _rawLogger.getLogMessages();
-
- assertEquals("Message log size not as expected.", 0, logs.size());
-
- }
-
- /**
- * Test that if logging is configured to be off in the configuration that
- * no logging is presented
- * @throws ConfigurationException
- * @throws AMQException
- */
- public void testChannelLoggingoff() throws Exception, AMQException
- {
- getConfigXml().setProperty("status-updates", "off");
-
- startBrokerNow();
-
- sendTestLogMessage(_amqpActor);
-
- List<Object> logs = _rawLogger.getLogMessages();
-
- assertEquals("Message log size not as expected.", 0, logs.size());
-
- }
-
- /**
- * Test that if logging is configured to be off in the configuration that
- * no logging is presented
- * @throws ConfigurationException
- * @throws AMQException
- */
- public void testChannelLoggingoFf() throws Exception, AMQException
- {
- getConfigXml().setProperty("status-updates", "oFf");
-
- startBrokerNow();
-
- sendTestLogMessage(_amqpActor);
-
- List<Object> logs = _rawLogger.getLogMessages();
-
- assertEquals("Message log size not as expected.", 0, logs.size());
-
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/actors/AMQPConnectionActorTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/actors/AMQPConnectionActorTest.java
deleted file mode 100644
index 4eda9e9da1..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/logging/actors/AMQPConnectionActorTest.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.server.logging.actors;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.server.logging.LogMessage;
-import org.apache.qpid.server.logging.LogSubject;
-
-import java.util.List;
-
-/**
- * Test : AMQPConnectionActorTest
- * Validate the AMQPConnectionActor class.
- *
- * The test creates a new AMQPActor and then logs a message using it.
- *
- * The test then verifies that the logged message was the only one created and
- * that the message contains the required message.
- */
-public class AMQPConnectionActorTest extends BaseConnectionActorTestCase
-{
- @Override
- public void configure()
- {
- // Prevent defaulting Logging to ON
- }
-
-
- @Override
- public void createBroker()
- {
- //Prevent auto-broker startup
- }
-
- /**
- * Test the AMQPActor logging as a Connection level.
- *
- * The test sends a message then verifies that it entered the logs.
- *
- * The log message should be fully repalaced (no '{n}' values) and should
- * not contain any channel identification.
- */
- public void testConnection() throws Exception
- {
- getConfigXml().setProperty("status-updates", "ON");
-
- super.createBroker();
-
- final String message = sendLogMessage();
-
- List<Object> logs = _rawLogger.getLogMessages();
-
- assertEquals("Message log size not as expected.", 1, logs.size());
-
- // Verify that the logged message is present in the output
- assertTrue("Message was not found in log message",
- logs.get(0).toString().contains(message));
-
- // Verify that the message has the correct type
- assertTrue("Message does not contain the [con: prefix",
- logs.get(0).toString().contains("[con:"));
-
- // Verify that all the values were presented to the MessageFormatter
- // so we will not end up with '{n}' entries in the log.
- assertFalse("Verify that the string does not contain any '{'.",
- logs.get(0).toString().contains("{"));
-
- // Verify that the logged message does not contains the 'ch:' marker
- assertFalse("Message was logged with a channel identifier." + logs.get(0),
- logs.get(0).toString().contains("/ch:"));
- }
-
- public void testConnectionLoggingOff() throws Exception, AMQException
- {
- getConfigXml().setProperty("status-updates", "OFF");
-
- // Start the broker now.
- super.createBroker();
-
- sendLogMessage();
-
- List<Object> logs = _rawLogger.getLogMessages();
-
- assertEquals("Message log size not as expected.", 0, logs.size());
-
- }
-
- private String sendLogMessage()
- {
- final String message = "test logging";
-
- _amqpActor.message(new LogSubject()
- {
- public String toLogString()
- {
- return "[AMQPActorTest]";
- }
-
- }, new LogMessage()
- {
- public String toString()
- {
- return message;
- }
-
- public String getLogHierarchy()
- {
- return "test.hieracrchy";
- }
- });
- return message;
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/actors/BaseActorTestCase.java b/java/broker/src/test/java/org/apache/qpid/server/logging/actors/BaseActorTestCase.java
deleted file mode 100644
index 60ecbef438..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/logging/actors/BaseActorTestCase.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.server.logging.actors;
-
-import org.apache.qpid.server.configuration.ServerConfiguration;
-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
-{
- protected LogActor _amqpActor;
- protected UnitTestMessageLogger _rawLogger;
- protected RootMessageLogger _rootLogger;
-
- @Override
- public void configure()
- {
- getConfiguration().getConfig().setProperty(ServerConfiguration.STATUS_UPDATES, "on");
- }
-
- @Override
- public void createBroker() throws Exception
- {
- super.createBroker();
-
- _rawLogger = new UnitTestMessageLogger(getConfiguration());
- _rootLogger = _rawLogger;
- }
-
- public void tearDown() throws Exception
- {
- _rawLogger.clearLogMessages();
-
- super.tearDown();
- }
-
- public String sendTestLogMessage(LogActor actor)
- {
- String message = "Test logging: " + getName();
- sendTestLogMessage(actor, message);
-
- return message;
- }
-
- public void sendTestLogMessage(LogActor actor, final String message)
- {
- actor.message(new LogSubject()
- {
- public String toLogString()
- {
- return message;
- }
-
- }, new LogMessage()
- {
- public String toString()
- {
- return message;
- }
-
- public String getLogHierarchy()
- {
- return "test.hierarchy";
- }
- });
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/actors/BaseConnectionActorTestCase.java b/java/broker/src/test/java/org/apache/qpid/server/logging/actors/BaseConnectionActorTestCase.java
deleted file mode 100644
index 956d296dce..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/logging/actors/BaseConnectionActorTestCase.java
+++ /dev/null
@@ -1,33 +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.logging.actors;
-
-public class BaseConnectionActorTestCase extends BaseActorTestCase
-{
-
- @Override
- public void createBroker() throws Exception
- {
- super.createBroker();
-
- _amqpActor = new AMQPConnectionActor(getSession(), _rootLogger);
- }
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/actors/CurrentActorTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/actors/CurrentActorTest.java
deleted file mode 100644
index 32ad1d110d..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/logging/actors/CurrentActorTest.java
+++ /dev/null
@@ -1,256 +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.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.NullRootMessageLogger;
-
-/**
- * Test : CurrentActorTest
- * Summary:
- * Validate ThreadLocal operation.
- *
- * Test creates THREADS number of threads which all then execute the same test
- * together ( as close as looping Thread.start() will allow).
- *
- * Test:
- * Test sets the CurrentActor then proceeds to retrieve the value and use it.
- *
- * The test also validates that it is the same LogActor that this thread set.
- *
- * Finally the LogActor is removed and tested to make sure that it was
- * successfully removed.
- *
- * By having a higher number of threads than would normally be used in the
- * Poolling filter we aim to catch the race condition where a ThreadLocal remove
- * is called before one or more threads call get(). This way we can ensure that
- * the remove does not affect more than the Thread it was called in.
- */
-public class CurrentActorTest extends BaseConnectionActorTestCase
-{
- //Set this to be a reasonably large number
- int THREADS = 10;
-
- // Record any exceptions that are thrown by the threads
- Exception[] _errors = new Exception[THREADS];
-
- /**
- * Test that CurrentActor behaves as LIFO queue.
- *
- * Test creates two Actors Connection and Channel and then sets the
- * CurrentActor.
- *
- * The test validates that CurrentActor remembers the Connection actor
- * after the Channel actor has been removed.
- *
- * And then finally validates that removing the Connection actor results
- * in there being no actors set.
- *
- * @throws AMQException
- * @throws org.apache.commons.configuration.ConfigurationException
- */
- public void testLIFO() throws AMQException, ConfigurationException
- {
- // This test only needs the local objects created, _session etc.
- // So stopping the broker and making them useless will not affect the
- // test, but the extra actors the test broker adds will so by stopping
- // we remove the session actor and so all is good.
- stopBroker();
-
- AMQPConnectionActor connectionActor = new AMQPConnectionActor(getSession(),
- new NullRootMessageLogger());
-
- /*
- * Push the actor on to the stack:
- *
- * CurrentActor -> Connection
- * Stack -> null
- */
- CurrentActor.set(connectionActor);
-
- //Use the Actor to send a simple message
- sendTestLogMessage(CurrentActor.get());
-
- // Verify it was the same actor as we set earlier
- assertEquals("Retrieved actor is not as expected ",
- connectionActor, CurrentActor.get());
-
- /**
- * Set the actor to now be the Channel actor so testing the ability
- * to push the actor on to the stack:
- *
- * CurrentActor -> Channel
- * Stack -> Connection, null
- *
- */
-
- AMQChannel channel = new AMQChannel(getSession(), 1, getSession().getVirtualHost().getMessageStore());
-
- AMQPChannelActor channelActor = new AMQPChannelActor(channel,
- new NullRootMessageLogger());
-
- CurrentActor.set(channelActor);
-
- //Use the Actor to send a simple message
- sendTestLogMessage(CurrentActor.get());
-
- // Verify it was the same actor as we set earlier
- assertEquals("Retrieved actor is not as expected ",
- channelActor, CurrentActor.get());
-
- // Remove the ChannelActor from the stack
- CurrentActor.remove();
- /*
- * Pop the actor on to the stack:
- *
- * CurrentActor -> Connection
- * Stack -> null
- */
-
-
- // Verify we now have the same connection actor as we set earlier
- assertEquals("Retrieved actor is not as expected ",
- connectionActor, CurrentActor.get());
-
- // Verify that removing the our last actor it returns us to the test
- // default that the ApplicationRegistry sets.
- CurrentActor.remove();
- /*
- * Pop the actor on to the stack:
- *
- * CurrentActor -> null
- */
-
-
- assertEquals("CurrentActor not the Test default", TestLogActor.class ,CurrentActor.get().getClass());
- }
-
- /**
- * Test the setting CurrentActor is done correctly as a ThreadLocal.
- *
- * The test starts 'THREADS' threads that all set the CurrentActor log
- * a message then remove the actor.
- *
- * Checks are done to ensure that there is no set actor after the remove.
- *
- * If the ThreadLocal was not working then having concurrent actor sets
- * would result in more than one actor and so the remove will not result
- * in the clearing of the CurrentActor
- *
- */
- public void testThreadLocal()
- {
-
- new Runnable(){
- public void run()
- {
- System.out.println(_errors[0]);
- }
- };
-
- // Setup the threads
- Thread[] threads = new Thread[THREADS];
- for (int count = 0; count < THREADS; count++)
- {
- Runnable test = new LogMessagesWithAConnectionActor(count);
- threads[count] = new Thread(test);
- }
-
- //Run the threads
- for (int count = 0; count < THREADS; count++)
- {
- threads[count].start();
- }
-
- // Wait for them to finish
- for (int count = 0; count < THREADS; count++)
- {
- try
- {
- threads[count].join();
- }
- catch (InterruptedException e)
- {
- //if we are interrupted then we will exit shortly.
- }
- }
-
- // Verify that none of the tests threw an exception
- for (int count = 0; count < THREADS; count++)
- {
- if (_errors[count] != null)
- {
- _errors[count].printStackTrace();
- fail("Error occured in thread:" + count);
- }
- }
- }
-
- /**
- * Creates a new ConnectionActor and logs the given number of messages
- * before removing the actor and validating that there is no set actor.
- */
- public class LogMessagesWithAConnectionActor implements Runnable
- {
- int count;
-
- LogMessagesWithAConnectionActor(int count)
- {
- this.count = count;
- }
-
- public void run()
- {
-
- // Create a new actor using retrieving the rootMessageLogger from
- // the default ApplicationRegistry.
- //fixme reminder that we need a better approach for broker testing.
- try
- {
-
- AMQPConnectionActor actor = new AMQPConnectionActor(getSession(),
- new NullRootMessageLogger());
-
- CurrentActor.set(actor);
-
- //Use the Actor to send a simple message
- sendTestLogMessage(CurrentActor.get());
-
- // Verify it was the same actor as we set earlier
- assertEquals("Retrieved actor is not as expected ",
- actor, CurrentActor.get());
-
- // Verify that removing the actor works for this thread
- CurrentActor.remove();
-
- assertNull("CurrentActor should be null", CurrentActor.get());
- }
- catch (Exception e)
- {
- _errors[count] = e;
- }
-
- }
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/actors/ManagementActorTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/actors/ManagementActorTest.java
deleted file mode 100644
index 033ae3b4b3..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/logging/actors/ManagementActorTest.java
+++ /dev/null
@@ -1,103 +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.logging.actors;
-
-import org.apache.qpid.server.configuration.ServerConfiguration;
-import org.apache.qpid.server.logging.LogMessage;
-import org.apache.qpid.server.logging.LogSubject;
-import org.apache.qpid.AMQException;
-
-import java.util.List;
-
-/**
- * Test : AMQPManagementActorTest
- * Validate the AMQPManagementActor class.
- *
- * The test creates a new AMQPActor and then logs a message using it.
- *
- * The test then verifies that the logged message was the only one created and
- * that the message contains the required message.
- */
-public class ManagementActorTest extends BaseActorTestCase
-{
-
- private static final String IP = "127.0.0.1";
- private static final String CONNECTION_ID = "1";
- private String _threadName;
-
- @Override
- public void createBroker() throws Exception
- {
- super.createBroker();
- _amqpActor = new ManagementActor(_rootLogger);
-
- // Set the thread name to be the same as a RMI JMX Connection would use
- _threadName = Thread.currentThread().getName();
- Thread.currentThread().setName("RMI TCP Connection(" + CONNECTION_ID + ")-" + IP);
- }
-
- @Override
- public void tearDown() throws Exception
- {
- Thread.currentThread().setName(_threadName);
- super.tearDown();
- }
-
- /**
- * Test the AMQPActor logging as a Connection level.
- *
- * The test sends a message then verifies that it entered the logs.
- *
- * The log message should be fully repalaced (no '{n}' values) and should
- * not contain any channel identification.
- */
- public void testConnection()
- {
- final String message = sendTestLogMessage(_amqpActor);
-
- List<Object> logs = _rawLogger.getLogMessages();
-
- assertEquals("Message log size not as expected.", 1, logs.size());
-
- // Verify that the logged message is present in the output
- assertTrue("Message was not found in log message",
- logs.get(0).toString().contains(message));
-
- // Verify that all the values were presented to the MessageFormatter
- // so we will not end up with '{n}' entries in the log.
- assertFalse("Verify that the string does not contain any '{'.",
- logs.get(0).toString().contains("{"));
-
- // Verify that the message has the correct type
- assertTrue("Message does not contain the [mng: prefix",
- logs.get(0).toString().contains("[mng:"));
-
- // Verify that the logged message does not contains the 'ch:' marker
- assertFalse("Message was logged with a channel identifier." + logs.get(0),
- logs.get(0).toString().contains("/ch:"));
-
- // Verify that the message has the right values
- assertTrue("Message contains the [mng: prefix",
- logs.get(0).toString().contains("[mng:" + CONNECTION_ID + "(" + IP + ")"));
-
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/actors/QueueActorTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/actors/QueueActorTest.java
deleted file mode 100644
index 409f7c84b7..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/logging/actors/QueueActorTest.java
+++ /dev/null
@@ -1,73 +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.logging.actors;
-
-import java.util.List;
-
-public class QueueActorTest extends BaseConnectionActorTestCase
-{
-
- @Override
- public void createBroker() throws Exception
- {
- super.createBroker();
- _amqpActor = new QueueActor(getQueue(), _rootLogger);
- }
-
- /**
- * Test the QueueActor as a logger.
- *
- * The test logs a message then verifies that it entered the logs correctly
- *
- * The log message should be fully repalaced (no '{n}' values) and should
- * contain the correct queue identification.
- */
- public void testQueueActor()
- {
- final String message = sendTestLogMessage(_amqpActor);
-
- List<Object> logs = _rawLogger.getLogMessages();
-
- assertEquals("Message log size not as expected.", 1, logs.size());
-
- String log = logs.get(0).toString();
-
- // Verify that the logged message is present in the output
- assertTrue("Message was not found in log message",
- log.contains(message));
-
- // Verify that all the values were presented to the MessageFormatter
- // so we will not end up with '{n}' entries in the log.
- assertFalse("Verify that the string does not contain any '{':" + log,
- log.contains("{"));
-
- // Verify that the message has the correct type
- assertTrue("Message contains the [vh: prefix:" + log,
- log.contains("[vh("));
-
- // Verify that the logged message contains the 'qu(' marker
- String expected = "qu(" + getName() + ")";
- assertTrue("Message was not logged with a queue identifer '"+expected+"' actual:" + log,
- log.contains(expected));
- }
-
-}
-
diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/actors/SubscriptionActorTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/actors/SubscriptionActorTest.java
deleted file mode 100644
index a2272cc395..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/logging/actors/SubscriptionActorTest.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.logging.actors;
-
-import java.util.List;
-
-import org.apache.qpid.server.subscription.MockSubscription;
-
-/**
- * Test : AMQPConnectionActorTest
- * Validate the AMQPConnectionActor class.
- *
- * The test creates a new AMQPActor and then logs a message using it.
- *
- * The test then verifies that the logged message was the only one created and
- * that the message contains the required message.
- */
-public class SubscriptionActorTest extends BaseConnectionActorTestCase
-{
-
- @Override
- public void createBroker() throws Exception
- {
- super.createBroker();
-
- MockSubscription mockSubscription = new MockSubscription();
-
- mockSubscription.setQueue(getQueue(), false);
-
- _amqpActor = new SubscriptionActor(_rootLogger, mockSubscription);
- }
-
- /**
- * Test the AMQPActor logging as a Subscription logger.
- *
- * The test sends a message then verifies that it entered the logs.
- *
- * The log message should be fully repalaced (no '{n}' values) and should
- * contain subscription identification.
- */
- public void testSubscription()
- {
- final String message = sendTestLogMessage(_amqpActor);
-
- List<Object> logs = _rawLogger.getLogMessages();
-
- assertEquals("Message log size not as expected.", 1, logs.size());
-
- // Verify that the logged message is present in the output
- assertTrue("Message was not found in log message",
- logs.get(0).toString().contains(message));
-
- // Verify that all the values were presented to the MessageFormatter
- // so we will not end up with '{n}' entries in the log.
- assertFalse("Verify that the string does not contain any '{'.",
- logs.get(0).toString().contains("{"));
-
- // Verify that the message has the correct type
- assertTrue("Message contains the [sub: prefix",
- logs.get(0).toString().contains("[sub:"));
-
- // Verify that the logged message does not contains the 'ch:' marker
- assertFalse("Message was logged with a channel identifier." + logs.get(0),
- logs.get(0).toString().contains("/ch:"));
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/actors/TestLogActor.java b/java/broker/src/test/java/org/apache/qpid/server/logging/actors/TestLogActor.java
deleted file mode 100644
index 30f4e16e42..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/logging/actors/TestLogActor.java
+++ /dev/null
@@ -1,37 +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.logging.actors;
-
-import org.apache.qpid.server.logging.RootMessageLogger;
-
-public class TestLogActor extends AbstractActor
-{
- public TestLogActor(RootMessageLogger rootLogger)
- {
- super(rootLogger);
- }
-
- public String getLogMessage()
- {
- return "[Test Actor] ";
- }
-}
- \ No newline at end of file
diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/management/LoggingManagementMBeanTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/management/LoggingManagementMBeanTest.java
deleted file mode 100644
index 2d25a769aa..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/logging/management/LoggingManagementMBeanTest.java
+++ /dev/null
@@ -1,431 +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.logging.management;
-
-import static org.apache.qpid.management.common.mbeans.LoggingManagement.LOGGER_LEVEL;
-import static org.apache.qpid.management.common.mbeans.LoggingManagement.LOGGER_NAME;
-
-import java.io.BufferedWriter;
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
-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";
- private static final String TEST_LOGGER_CHILD1 = "LoggingManagementMBeanTestLogger.child1";
- private static final String TEST_LOGGER_CHILD2 = "LoggingManagementMBeanTestLogger.child2";
-
- private static final String TEST_CATEGORY_PRIORITY = "LogManMBeanTest.category.priority";
- private static final String TEST_CATEGORY_LEVEL = "LogManMBeanTest.category.level";
- private static final String TEST_LOGGER_LEVEL = "LogManMBeanTest.logger.level";
-
- private static final String NEWLINE = System.getProperty("line.separator");
-
- private File _testConfigFile;
-
- @Override
- public void setUp() throws Exception
- {
- super.setUp();
- _testConfigFile = createTempTestLog4JConfig();
- }
-
- @Override
- public void tearDown() throws Exception
- {
- File oldTestConfigFile = new File(_testConfigFile.getAbsolutePath() + ".old");
- if(oldTestConfigFile.exists())
- {
- oldTestConfigFile.delete();
- }
-
- _testConfigFile.delete();
-
- super.tearDown();
- }
-
- private File createTempTestLog4JConfig()
- {
- File tmpFile = null;
- try
- {
- tmpFile = File.createTempFile("LogManMBeanTestLog4jConfig", ".tmp");
- tmpFile.deleteOnExit();
-
- FileWriter fstream = new FileWriter(tmpFile);
- BufferedWriter writer = new BufferedWriter(fstream);
-
- writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+NEWLINE);
- writer.write("<!DOCTYPE log4j:configuration SYSTEM \"log4j.dtd\">"+NEWLINE);
-
- writer.write("<log4j:configuration xmlns:log4j=\"http://jakarta.apache.org/log4j/\" debug=\"null\" " +
- "threshold=\"null\">"+NEWLINE);
-
- writer.write(" <appender class=\"org.apache.log4j.ConsoleAppender\" name=\"STDOUT\">"+NEWLINE);
- writer.write(" <layout class=\"org.apache.log4j.PatternLayout\">"+NEWLINE);
- writer.write(" <param name=\"ConversionPattern\" value=\"%d %-5p [%t] %C{2} (%F:%L) - %m%n\"/>"+NEWLINE);
- writer.write(" </layout>"+NEWLINE);
- writer.write(" </appender>"+NEWLINE);
-
- //Example of a 'category' with a 'priority'
- writer.write(" <category additivity=\"true\" name=\"" + TEST_CATEGORY_PRIORITY +"\">"+NEWLINE);
- writer.write(" <priority value=\"info\"/>"+NEWLINE);
- writer.write(" <appender-ref ref=\"STDOUT\"/>"+NEWLINE);
- writer.write(" </category>"+NEWLINE);
-
- //Example of a 'category' with a 'level'
- writer.write(" <category additivity=\"true\" name=\"" + TEST_CATEGORY_LEVEL +"\">"+NEWLINE);
- writer.write(" <level value=\"warn\"/>"+NEWLINE);
- writer.write(" <appender-ref ref=\"STDOUT\"/>"+NEWLINE);
- writer.write(" </category>"+NEWLINE);
-
- //Example of a 'logger' with a 'level'
- writer.write(" <logger additivity=\"true\" name=\"" + TEST_LOGGER_LEVEL + "\">"+NEWLINE);
- writer.write(" <level value=\"error\"/>"+NEWLINE);
- writer.write(" <appender-ref ref=\"STDOUT\"/>"+NEWLINE);
- writer.write(" </logger>"+NEWLINE);
-
- //'root' logger
- writer.write(" <root>"+NEWLINE);
- writer.write(" <priority value=\"info\"/>"+NEWLINE);
- writer.write(" <appender-ref ref=\"STDOUT\"/>"+NEWLINE);
- writer.write(" </root>"+NEWLINE);
-
- writer.write("</log4j:configuration>"+NEWLINE);
-
- writer.flush();
- writer.close();
- }
- catch (IOException e)
- {
- fail("Unable to create temporary test log4j configuration");
- }
-
- return tmpFile;
- }
-
-
-
- //******* Test Methods ******* //
-
- public void testSetRuntimeLoggerLevel()
- {
- LoggingManagementMBean lm = null;
- try
- {
- lm = new LoggingManagementMBean(_testConfigFile.getAbsolutePath(), 0);
- }
- catch (JMException e)
- {
- fail("Could not create test LoggingManagementMBean");
- }
-
- //create a parent test logger, set its level explicitly
- Logger log = Logger.getLogger(TEST_LOGGER);
- log.setLevel(Level.toLevel("info"));
-
- //create child1 test logger, check its *effective* level is the same as the parent, "info"
- Logger log1 = Logger.getLogger(TEST_LOGGER_CHILD1);
- assertTrue("Test logger's level was not the expected value",
- log1.getEffectiveLevel().toString().equalsIgnoreCase("info"));
-
- //now change its level to "warn"
- assertTrue("Failed to set logger level", lm.setRuntimeLoggerLevel(TEST_LOGGER_CHILD1, "warn"));
-
- //check the change, see its actual level is "warn
- assertTrue("Test logger's level was not the expected value",
- log1.getLevel().toString().equalsIgnoreCase("warn"));
-
- //try an invalid level
- assertFalse("Trying to set an invalid level succeded", lm.setRuntimeLoggerLevel(TEST_LOGGER_CHILD1, "made.up.level"));
- }
-
- public void testSetRuntimeRootLoggerLevel()
- {
- LoggingManagementMBean lm = null;
- try
- {
- lm = new LoggingManagementMBean(_testConfigFile.getAbsolutePath(), 0);
- }
- catch (JMException e)
- {
- fail("Could not create test LoggingManagementMBean");
- }
-
- Logger log = Logger.getRootLogger();
-
- //get current root logger level
- Level origLevel = log.getLevel();
-
- //change level twice to ensure a new level is actually selected
-
- //set root loggers level to info
- assertTrue("Failed to set root logger level", lm.setRuntimeRootLoggerLevel("debug"));
- //check it is now actually info
- Level currentLevel = log.getLevel();
- assertTrue("Logger level was not expected value", currentLevel.equals(Level.toLevel("debug")));
-
- //try an invalid level
- assertFalse("Trying to set an invalid level succeded", lm.setRuntimeRootLoggerLevel("made.up.level"));
-
- //set root loggers level to warn
- assertTrue("Failed to set logger level", lm.setRuntimeRootLoggerLevel("info"));
- //check it is now actually warn
- currentLevel = log.getLevel();
- assertTrue("Logger level was not expected value", currentLevel.equals(Level.toLevel("info")));
-
- //restore original level
- log.setLevel(origLevel);
- }
-
- public void testGetRuntimeRootLoggerLevel()
- {
- LoggingManagementMBean lm = null;
- try
- {
- lm = new LoggingManagementMBean(_testConfigFile.getAbsolutePath(), 0);
- }
- catch (JMException e)
- {
- fail("Could not create test LoggingManagementMBean");
- }
-
- Logger log = Logger.getRootLogger();
-
- //get current root logger level
- Level origLevel = log.getLevel();
-
- //change level twice to ensure a new level is actually selected
-
- //set root loggers level to debug
- log.setLevel(Level.toLevel("debug"));
- //check it is now actually debug
- assertTrue("Logger level was not expected value", lm.getRuntimeRootLoggerLevel().equalsIgnoreCase("debug"));
-
-
- //set root loggers level to warn
- log.setLevel(Level.toLevel("info"));
- //check it is now actually warn
- assertTrue("Logger level was not expected value", lm.getRuntimeRootLoggerLevel().equalsIgnoreCase("info"));
-
- //restore original level
- log.setLevel(origLevel);
- }
-
- public void testViewEffectiveRuntimeLoggerLevels()
- {
- LoggingManagementMBean lm = null;
- try
- {
- lm = new LoggingManagementMBean(_testConfigFile.getAbsolutePath(), 0);
- }
- catch (JMException e)
- {
- fail("Could not create test LoggingManagementMBean");
- }
-
- //(re)create a parent test logger, set its level explicitly
- Logger log = Logger.getLogger(TEST_LOGGER);
- log.setLevel(Level.toLevel("info"));
-
- //retrieve the current effective runtime logger level values
- TabularDataSupport levels = (TabularDataSupport) lm.viewEffectiveRuntimeLoggerLevels();
- Collection<Object> records = levels.values();
- Map<String,String> list = new HashMap<String,String>();
- for (Object o : records)
- {
- CompositeData data = (CompositeData) o;
- list.put(data.get(LOGGER_NAME).toString(), data.get(LOGGER_LEVEL).toString());
- }
-
- //check child2 does not exist already
- assertFalse("Did not expect this logger to exist already", list.containsKey(TEST_LOGGER_CHILD2));
-
- //create child2 test logger
- Logger log2 = Logger.getLogger(TEST_LOGGER_CHILD2);
-
- //retrieve the current effective runtime logger level values
- levels = (TabularDataSupport) lm.viewEffectiveRuntimeLoggerLevels();
- records = levels.values();
- list = new HashMap<String,String>();
- for (Object o : records)
- {
- CompositeData data = (CompositeData) o;
- list.put(data.get(LOGGER_NAME).toString(), data.get(LOGGER_LEVEL).toString());
- }
-
- //verify the parent and child2 loggers are present in returned values
- assertTrue(TEST_LOGGER + " logger was not in the returned list", list.containsKey(TEST_LOGGER));
- assertTrue(TEST_LOGGER_CHILD2 + " logger was not in the returned list", list.containsKey(TEST_LOGGER_CHILD2));
-
- //check child2's effective level is the same as the parent, "info"
- assertTrue("Test logger's level was not the expected value",
- list.get(TEST_LOGGER_CHILD2).equalsIgnoreCase("info"));
-
- //now change its level explicitly to "warn"
- log2.setLevel(Level.toLevel("warn"));
-
- //retrieve the current effective runtime logger level values
- levels = (TabularDataSupport) lm.viewEffectiveRuntimeLoggerLevels();
- records = levels.values();
- list = new HashMap<String,String>();
- for (Object o : records)
- {
- CompositeData data = (CompositeData) o;
- list.put(data.get(LOGGER_NAME).toString(), data.get(LOGGER_LEVEL).toString());
- }
-
- //check child2's effective level is now "warn"
- assertTrue("Test logger's level was not the expected value",
- list.get(TEST_LOGGER_CHILD2).equalsIgnoreCase("warn"));
- }
-
- public void testViewAndSetConfigFileLoggerLevel() throws Exception
- {
- LoggingManagementMBean lm =null;
- try
- {
- lm = new LoggingManagementMBean(_testConfigFile.getAbsolutePath(), 0);
- }
- catch (JMException e)
- {
- fail("Could not create test LoggingManagementMBean");
- }
-
- //retrieve the current values
- TabularDataSupport levels = (TabularDataSupport) lm.viewConfigFileLoggerLevels();
- Collection<Object> records = levels.values();
- Map<String,String> list = new HashMap<String,String>();
- for (Object o : records)
- {
- CompositeData data = (CompositeData) o;
- list.put(data.get(LOGGER_NAME).toString(), data.get(LOGGER_LEVEL).toString());
- }
-
- //check the 3 different types of logger definition are successfully retrieved before update
- assertTrue("Wrong number of items in returned list", list.size() == 3);
- assertTrue(TEST_CATEGORY_PRIORITY + " logger was not in the returned list", list.containsKey(TEST_CATEGORY_PRIORITY));
- assertTrue(TEST_CATEGORY_LEVEL + " logger was not in the returned list", list.containsKey(TEST_CATEGORY_LEVEL));
- assertTrue(TEST_LOGGER_LEVEL + " logger was not in the returned list", list.containsKey(TEST_LOGGER_LEVEL));
-
- //check that their level is as expected
- assertTrue(TEST_CATEGORY_PRIORITY + " logger's level was incorrect", list.get(TEST_CATEGORY_PRIORITY).equalsIgnoreCase("info"));
- assertTrue(TEST_CATEGORY_LEVEL + " logger's level was incorrect", list.get(TEST_CATEGORY_LEVEL).equalsIgnoreCase("warn"));
- assertTrue(TEST_LOGGER_LEVEL + " logger's level was incorrect", list.get(TEST_LOGGER_LEVEL).equalsIgnoreCase("error"));
-
- //increase their levels a notch to test the 3 different types of logger definition are successfully updated
- //change the category+priority to warn
- assertTrue("failed to set new level", lm.setConfigFileLoggerLevel(TEST_CATEGORY_PRIORITY, "warn"));
- //change the category+level to error
- assertTrue("failed to set new level", lm.setConfigFileLoggerLevel(TEST_CATEGORY_LEVEL, "error"));
- //change the logger+level to trace
- assertTrue("failed to set new level", lm.setConfigFileLoggerLevel(TEST_LOGGER_LEVEL, "trace"));
-
- //try an invalid level
- assertFalse("Use of an invalid logger level was successfull", lm.setConfigFileLoggerLevel(TEST_LOGGER_LEVEL, "made.up.level"));
-
- //try an invalid logger name
- assertFalse("Use of an invalid logger name was successfull", lm.setConfigFileLoggerLevel("made.up.logger.name", "info"));
-
- //retrieve the new values from the file and check them
- levels = (TabularDataSupport) lm.viewConfigFileLoggerLevels();
- records = levels.values();
- list = new HashMap<String,String>();
- for (Object o : records)
- {
- CompositeData data = (CompositeData) o;
- list.put(data.get(LOGGER_NAME).toString(), data.get(LOGGER_LEVEL).toString());
- }
-
- //check the 3 different types of logger definition are successfully retrieved after update
- assertTrue("Wrong number of items in returned list", list.size() == 3);
- assertTrue(TEST_CATEGORY_PRIORITY + " logger was not in the returned list", list.containsKey(TEST_CATEGORY_PRIORITY));
- assertTrue(TEST_CATEGORY_LEVEL + " logger was not in the returned list", list.containsKey(TEST_CATEGORY_LEVEL));
- assertTrue(TEST_LOGGER_LEVEL + " logger was not in the returned list", list.containsKey(TEST_LOGGER_LEVEL));
-
- //check that their level is as expected after the changes
- assertTrue(TEST_CATEGORY_PRIORITY + " logger's level was incorrect", list.get(TEST_CATEGORY_PRIORITY).equalsIgnoreCase("warn"));
- assertTrue(TEST_CATEGORY_LEVEL + " logger's level was incorrect", list.get(TEST_CATEGORY_LEVEL).equalsIgnoreCase("error"));
- assertTrue(TEST_LOGGER_LEVEL + " logger's level was incorrect", list.get(TEST_LOGGER_LEVEL).equalsIgnoreCase("trace"));
- }
-
- public void testGetAndSetConfigFileRootLoggerLevel() throws Exception
- {
- LoggingManagementMBean lm =null;
- try
- {
- lm = new LoggingManagementMBean(_testConfigFile.getAbsolutePath(), 0);
- }
- catch (JMException e)
- {
- fail("Could not create test LoggingManagementMBean");
- }
-
- //retrieve the current value
- String level = lm.getConfigFileRootLoggerLevel();
-
- //check the value was successfully retrieved before update
- assertTrue("Retrieved RootLogger level was incorrect", level.equalsIgnoreCase("info"));
-
- //try an invalid level
- assertFalse("Use of an invalid RootLogger level was successfull", lm.setConfigFileRootLoggerLevel("made.up.level"));
-
- //change the level to warn
- assertTrue("Failed to set new RootLogger level", lm.setConfigFileRootLoggerLevel("warn"));
-
- //retrieve the current value
- level = lm.getConfigFileRootLoggerLevel();
-
- //check the value was successfully retrieved after update
- assertTrue("Retrieved RootLogger level was incorrect", level.equalsIgnoreCase("warn"));
- }
-
- public void testGetLog4jLogWatchInterval()
- {
- LoggingManagementMBean lm =null;
- try
- {
- lm = new LoggingManagementMBean(_testConfigFile.getAbsolutePath(), 5000);
- }
- catch (JMException e)
- {
- fail("Could not create test LoggingManagementMBean");
- }
-
- assertTrue("Wrong value returned for logWatch period", lm.getLog4jLogWatchInterval() == 5000);
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/messages/AbstractTestMessages.java b/java/broker/src/test/java/org/apache/qpid/server/logging/messages/AbstractTestMessages.java
deleted file mode 100644
index e253881d09..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/logging/messages/AbstractTestMessages.java
+++ /dev/null
@@ -1,109 +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.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;
-import org.apache.qpid.server.logging.UnitTestMessageLogger;
-import org.apache.qpid.server.logging.actors.TestLogActor;
-import org.apache.qpid.server.logging.subjects.TestBlankSubject;
-import org.apache.qpid.server.util.InternalBrokerBaseCase;
-
-public abstract class AbstractTestMessages extends InternalBrokerBaseCase
-{
- protected Configuration _config = new PropertiesConfiguration();
- protected LogMessage _logMessage = null;
- protected LogActor _actor;
- protected UnitTestMessageLogger _logger;
- protected LogSubject _logSubject = new TestBlankSubject();
-
- @Override
- public void setUp() throws Exception
- {
- super.setUp();
-
- _logger = new UnitTestMessageLogger();
-
- _actor = new TestLogActor(_logger);
- }
-
- protected List<Object> performLog()
- {
- if (_logMessage == null)
- {
- throw new NullPointerException("LogMessage has not been set");
- }
-
- _actor.message(_logSubject, _logMessage);
-
- return _logger.getLogMessages();
- }
-
- /**
- * Validate that only a single log messasge occured 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
- *
- */
- protected void validateLogMessage(List<Object> logs, String tag, String[] expected)
- {
- assertEquals("Log has incorrect message count", 1, logs.size());
-
- //We trim() here as we don't care about extra white space at the end of the log message
- // but we do care about the ability to easily check we don't have unexpected text at
- // the end.
- String log = String.valueOf(logs.get(0)).trim();
-
- // Simple switch to print out all the logged messages
- //System.err.println(log);
-
- int msgIndex = log.indexOf(_logSubject.toLogString())+_logSubject.toLogString().length();
-
- assertTrue("Unable to locate Subject:" + log, msgIndex != -1);
-
- String message = log.substring(msgIndex);
-
- assertTrue("Message does not start with tag:" + tag + ":" + message,
- message.startsWith(tag));
-
- // Test that the expected items occur in order.
- int index = 0;
- for (String text : expected)
- {
- index = message.indexOf(text, index);
- assertTrue("Message does not contain expected (" + text + ") text :" + message, index != -1);
- index = index + text.length();
- }
-
- //Check there is nothing left on the log message
- assertEquals("Message has more text. '" + log.substring(msgIndex + index) + "'",
- log.length(), msgIndex + index);
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/messages/BindingMessagesTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/messages/BindingMessagesTest.java
deleted file mode 100644
index 22de8349c6..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/logging/messages/BindingMessagesTest.java
+++ /dev/null
@@ -1,64 +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.logging.messages;
-
-import java.util.List;
-
-/**
- * Test BND Log Messages
- */
-public class BindingMessagesTest extends AbstractTestMessages
-{
-
- public void testBindCreate_NoArgs()
- {
- _logMessage = BindingMessages.CREATED(null, false);
- List<Object> log = performLog();
-
- String[] expected = {"Create"};
-
- validateLogMessage(log, "BND-1001", expected);
- }
-
- public void testBindCreate_Args()
- {
- String arguments = "arguments";
-
- _logMessage = BindingMessages.CREATED(arguments, true);
- List<Object> log = performLog();
-
- String[] expected = {"Create", ": Arguments :", arguments};
-
- validateLogMessage(log, "BND-1001", expected);
- }
-
- public void testBindDelete()
- {
- _logMessage = BindingMessages.DELETED();
-
- List<Object> log = performLog();
-
- String[] expected = {"Deleted"};
-
- validateLogMessage(log, "BND-1002", expected);
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/messages/BrokerMessagesTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/messages/BrokerMessagesTest.java
deleted file mode 100644
index a3d46f5716..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/logging/messages/BrokerMessagesTest.java
+++ /dev/null
@@ -1,116 +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.logging.messages;
-
-import java.util.List;
-
-/**
- * Test BRK log Messages
- */
-public class BrokerMessagesTest extends AbstractTestMessages
-{
- public void testBrokerStartup()
- {
- String version = "Qpid 0.6";
- String build = "796936M";
-
- _logMessage = BrokerMessages.STARTUP(version, build);
- List<Object> log = performLog();
-
- String[] expected = {"Startup :", "Version:", version, "Build:", build};
-
- validateLogMessage(log, "BRK-1001", expected);
- }
-
- public void testBrokerListening()
- {
- String transport = "TCP";
- Integer port = 2765;
-
- _logMessage = BrokerMessages.LISTENING(transport, port);
-
- List<Object> log = performLog();
-
- String[] expected = {"Starting", "Listening on ",
- transport, "port ", String.valueOf(port)};
-
- validateLogMessage(log, "BRK-1002", expected);
- }
-
- public void testBrokerShuttingDown()
- {
- String transport = "TCP";
- Integer port = 2765;
-
- _logMessage = BrokerMessages.SHUTTING_DOWN(transport, port);
-
- List<Object> log = performLog();
-
- String[] expected = {"Shuting down", transport, "port ", String.valueOf(port)};
-
- validateLogMessage(log, "BRK-1003", expected);
- }
-
- public void testBrokerReady()
- {
- _logMessage = BrokerMessages.READY();
- List<Object> log = performLog();
-
- String[] expected = {"Ready"};
-
- validateLogMessage(log, "BRK-1004", expected);
- }
-
- public void testBrokerStopped()
- {
- _logMessage = BrokerMessages.STOPPED();
- List<Object> log = performLog();
-
- String[] expected = {"Stopped"};
-
- validateLogMessage(log, "BRK-1005", expected);
- }
-
- public void testBrokerConfig()
- {
- String path = "/file/path/to/configuration.xml";
-
- _logMessage = BrokerMessages.CONFIG(path);
- List<Object> log = performLog();
-
- String[] expected = {"Using configuration :", path};
-
- validateLogMessage(log, "BRK-1006", expected);
- }
-
- public void testBrokerLogConfig()
- {
- String path = "/file/path/to/configuration.xml";
-
- _logMessage = BrokerMessages.LOG_CONFIG(path);
- List<Object> log = performLog();
-
- String[] expected = {"Using logging configuration :", path};
-
- validateLogMessage(log, "BRK-1007", expected);
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/messages/ChannelMessagesTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/messages/ChannelMessagesTest.java
deleted file mode 100644
index e94b79ba95..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/logging/messages/ChannelMessagesTest.java
+++ /dev/null
@@ -1,64 +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.logging.messages;
-
-import java.util.List;
-
-/**
- * Test CHN Log Messges
- */
-public class ChannelMessagesTest extends AbstractTestMessages
-{
- public void testChannelCreate()
- {
- _logMessage = ChannelMessages.CREATE();
- List<Object> log = performLog();
-
- // We use the MessageFormat here as that is what the ChannelMessage
- // will do, this makes the resulting value 12,345
- String[] expected = {"Create"};
-
- validateLogMessage(log, "CHN-1001", expected);
- }
-
- public void testChannelFlow()
- {
- String flow = "ON";
-
- _logMessage = ChannelMessages.FLOW(flow);
- List<Object> log = performLog();
-
- String[] expected = {"Flow", flow};
-
- validateLogMessage(log, "CHN-1002", expected);
- }
-
- public void testChannelClose()
- {
- _logMessage = ChannelMessages.CLOSE();
- List<Object> log = performLog();
-
- String[] expected = {"Close"};
-
- validateLogMessage(log, "CHN-1003", expected);
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/messages/ConnectionMessagesTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/messages/ConnectionMessagesTest.java
deleted file mode 100644
index 24fccf8446..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/logging/messages/ConnectionMessagesTest.java
+++ /dev/null
@@ -1,90 +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.logging.messages;
-
-import java.util.List;
-
-/**
- * Test CON Log Messages
- */
-public class ConnectionMessagesTest extends AbstractTestMessages
-{
- public void testConnectionOpen_WithClientIDProtocolVersion()
- {
- String clientID = "client";
- String protocolVersion = "8-0";
-
- _logMessage = ConnectionMessages.OPEN(clientID, protocolVersion, true , true);
- List<Object> log = performLog();
-
- String[] expected = {"Open :", "Client ID", clientID,
- ": Protocol Version :", protocolVersion};
-
- validateLogMessage(log, "CON-1001", expected);
- }
-
- public void testConnectionOpen_WithClientIDNoProtocolVersion()
- {
- String clientID = "client";
-
- _logMessage = ConnectionMessages.OPEN(clientID, null,true, false);
- List<Object> log = performLog();
-
- String[] expected = {"Open :", "Client ID", clientID};
-
- validateLogMessage(log, "CON-1001", expected);
- }
-
- public void testConnectionOpen_WithNOClientIDProtocolVersion()
- {
- String protocolVersion = "8-0";
-
- _logMessage = ConnectionMessages.OPEN(null, protocolVersion, false , true);
- List<Object> log = performLog();
-
- String[] expected = {"Open", ": Protocol Version :", protocolVersion};
-
- validateLogMessage(log, "CON-1001", expected);
- }
-
- public void testConnectionOpen_WithNoClientIDNoProtocolVersion()
- {
- _logMessage = ConnectionMessages.OPEN(null, null,false, false);
- List<Object> log = performLog();
-
- String[] expected = {"Open"};
-
- validateLogMessage(log, "CON-1001", expected);
- }
-
-
-
- public void testConnectionClose()
- {
- _logMessage = ConnectionMessages.CLOSE();
- List<Object> log = performLog();
-
- String[] expected = {"Close"};
-
- validateLogMessage(log, "CON-1002", expected);
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/messages/ExchangeMessagesTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/messages/ExchangeMessagesTest.java
deleted file mode 100644
index 728a98e009..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/logging/messages/ExchangeMessagesTest.java
+++ /dev/null
@@ -1,80 +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.logging.messages;
-
-import org.apache.qpid.server.exchange.Exchange;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-
-import java.util.List;
-
-/**
- * Test EXH Log Messages
- */
-public class ExchangeMessagesTest extends AbstractTestMessages
-{
- public void testExchangeCreated_Transient()
- {
- // Get the Default Exchange on the Test Vhost for testing
- Exchange exchange = ApplicationRegistry.getInstance().
- getVirtualHostRegistry().getVirtualHost("test").
- getExchangeRegistry().getDefaultExchange();
-
- String type = exchange.getTypeShortString().toString();
- String name = exchange.getNameShortString().toString();
-
- _logMessage = ExchangeMessages.CREATED(type, name, false);
- List<Object> log = performLog();
-
- String[] expected = {"Create :", "Type:", type, "Name:", name};
-
- validateLogMessage(log, "EXH-1001", expected);
- }
-
- public void testExchangeCreated_Persistent()
- {
- // Get the Default Exchange on the Test Vhost for testing
- Exchange exchange = ApplicationRegistry.getInstance().
- getVirtualHostRegistry().getVirtualHost("test").
- getExchangeRegistry().getDefaultExchange();
-
- String type = exchange.getTypeShortString().toString();
- String name = exchange.getNameShortString().toString();
-
- _logMessage = ExchangeMessages.CREATED(type, name, true);
- List<Object> log = performLog();
-
- String[] expected = {"Create :", "Durable", "Type:", type, "Name:", name};
-
- validateLogMessage(log, "EXH-1001", expected);
- }
-
-
- public void testExchangeDeleted()
- {
- _logMessage = ExchangeMessages.DELETED();
- List<Object> log = performLog();
-
- String[] expected = {"Deleted"};
-
- validateLogMessage(log, "EXH-1002", expected);
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/messages/ManagementConsoleMessagesTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/messages/ManagementConsoleMessagesTest.java
deleted file mode 100644
index 4bfbae44ac..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/logging/messages/ManagementConsoleMessagesTest.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.server.logging.messages;
-
-import java.util.List;
-
-/**
- * Test MNG Log Messages
- */
-public class ManagementConsoleMessagesTest extends AbstractTestMessages
-{
- public void testManagementStartup()
- {
- _logMessage = ManagementConsoleMessages.STARTUP();
- List<Object> log = performLog();
-
- String[] expected = {"Startup"};
-
- validateLogMessage(log, "MNG-1001", expected);
- }
-
- public void testManagementListening()
- {
- String transport = "JMX";
- Integer port = 8889;
-
- _logMessage = ManagementConsoleMessages.LISTENING(transport, port);
- List<Object> log = performLog();
-
- String[] expected = {"Starting :", transport, ": Listening on port", String.valueOf(port)};
-
- validateLogMessage(log, "MNG-1002", expected);
- }
-
- public void testManagementShuttingDown()
- {
- String transport = "JMX";
- Integer port = 8889;
-
- _logMessage = ManagementConsoleMessages.SHUTTING_DOWN(transport, port);
- List<Object> log = performLog();
-
- String[] expected = {"Shutting down :", transport, ": port", String.valueOf(port)};
-
- validateLogMessage(log, "MNG-1003", expected);
- }
-
- public void testManagementReady()
- {
- _logMessage = ManagementConsoleMessages.READY(false);
- List<Object> log = performLog();
-
- String[] expected = {"Ready"};
-
- validateLogMessage(log, "MNG-1004", expected);
-
- _logger.clearLogMessages();
-
- _logMessage = ManagementConsoleMessages.READY(true);
- log = performLog();
-
- expected = new String[]{"Ready : Using the platform JMX Agent"};
-
- validateLogMessage(log, "MNG-1004", expected);
- }
-
- public void testManagementStopped()
- {
- _logMessage = ManagementConsoleMessages.STOPPED();
- List<Object> log = performLog();
-
- String[] expected = {"Stopped"};
-
- validateLogMessage(log, "MNG-1005", expected);
- }
-
- public void testManagementSSLKeyStore()
- {
- String path = "/path/to/the/keystore/files.jks";
-
- _logMessage = ManagementConsoleMessages.SSL_KEYSTORE(path);
- List<Object> log = performLog();
-
- String[] expected = {"Using SSL Keystore :", path};
-
- validateLogMessage(log, "MNG-1006", expected);
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/messages/MessageStoreMessagesTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/messages/MessageStoreMessagesTest.java
deleted file mode 100644
index cc032a0430..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/logging/messages/MessageStoreMessagesTest.java
+++ /dev/null
@@ -1,125 +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.logging.messages;
-
-import java.util.List;
-
-/**
- * Test MST Log Messages
- */
-public class MessageStoreMessagesTest extends AbstractTestMessages
-{
- public void testMessageStoreCreated()
- {
- String name = "DerbyMessageStore";
-
- _logMessage = MessageStoreMessages.CREATED(name);
- List<Object> log = performLog();
-
- String[] expected = {"Created :", name};
-
- validateLogMessage(log, "MST-1001", expected);
- }
-
- public void testMessageStoreStoreLocation()
- {
- String location = "/path/to/the/message/store.files";
-
- _logMessage = MessageStoreMessages.STORE_LOCATION(location);
- List<Object> log = performLog();
-
- String[] expected = {"Store location :", location};
-
- validateLogMessage(log, "MST-1002", expected);
- }
-
- public void testMessageStoreClosed()
- {
- _logMessage = MessageStoreMessages.CLOSED();
- List<Object> log = performLog();
-
- String[] expected = {"Closed"};
-
- validateLogMessage(log, "MST-1003", expected);
- }
-
- public void testMessageStoreRecoveryStart()
- {
- _logMessage = MessageStoreMessages.RECOVERY_START();
- List<Object> log = performLog();
-
- String[] expected = {"Recovery Start"};
-
- validateLogMessage(log, "MST-1004", expected);
- }
-/*
- public void testMessageStoreRecoveryStart_withQueue()
- {
- String queueName = "testQueue";
-
- _logMessage = MessageStoreMessages.RECOVERY_START(queueName, true);
- List<Object> log = performLog();
-
- String[] expected = {"Recovery Start :", queueName};
-
- validateLogMessage(log, "MST-1004", expected);
- }
-
- public void testMessageStoreRecovered()
- {
- String queueName = "testQueue";
- Integer messasgeCount = 2000;
-
- _logMessage = MessageStoreMessages.MST_RECOVERED(messasgeCount, queueName);
- List<Object> log = performLog();
-
- // Here we use MessageFormat to ensure the messasgeCount of 2000 is
- // reformated for display as '2,000'
- String[] expected = {"Recovered ",
- MessageFormat.format("{0,number}", messasgeCount),
- "messages for queue", queueName};
-
- validateLogMessage(log, "MST-1005", expected);
- }
-
- public void testMessageStoreRecoveryComplete()
- {
- _logMessage = MessageStoreMessages.MST_RECOVERY_COMPLETE(null,false);
- List<Object> log = performLog();
-
- String[] expected = {"Recovery Complete"};
-
- validateLogMessage(log, "MST-1006", expected);
- }
-
- public void testMessageStoreRecoveryComplete_withQueue()
- {
- String queueName = "testQueue";
-
- _logMessage = MessageStoreMessages.MST_RECOVERY_COMPLETE(queueName, true);
- List<Object> log = performLog();
-
- String[] expected = {"Recovery Complete :", queueName};
-
- validateLogMessage(log, "MST-1006", expected);
- }
- */
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/messages/QueueMessagesTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/messages/QueueMessagesTest.java
deleted file mode 100644
index d51e6a6bb7..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/logging/messages/QueueMessagesTest.java
+++ /dev/null
@@ -1,239 +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.logging.messages;
-
-import java.util.List;
-
-/**
- * Test QUE Log Messages
- */
-public class QueueMessagesTest extends AbstractTestMessages
-{
- public void testQueueCreatedALL()
- {
- String owner = "guest";
- Integer priority = 3;
-
- _logMessage = QueueMessages.CREATED(owner, priority, true, true, true, true, true);
- List<Object> log = performLog();
-
- String[] expected = {"Create :", "Owner:", owner, "AutoDelete",
- "Durable", "Transient", "Priority:",
- String.valueOf(priority)};
-
- validateLogMessage(log, "QUE-1001", expected);
- }
-
- public void testQueueCreatedOwnerAutoDelete()
- {
- String owner = "guest";
-
- _logMessage = QueueMessages.CREATED(owner, null, true, true, false, false, false);
- List<Object> log = performLog();
-
- String[] expected = {"Create :", "Owner:", owner, "AutoDelete"};
-
- validateLogMessage(log, "QUE-1001", expected);
- }
-
- public void testQueueCreatedOwnerPriority()
- {
- String owner = "guest";
- Integer priority = 3;
-
- _logMessage = QueueMessages.CREATED(owner, priority, true, false, false, false, true);
- List<Object> log = performLog();
-
- String[] expected = {"Create :", "Owner:", owner, "Priority:",
- String.valueOf(priority)};
-
- validateLogMessage(log, "QUE-1001", expected);
- }
-
- public void testQueueCreatedOwnerAutoDeletePriority()
- {
- String owner = "guest";
- Integer priority = 3;
-
- _logMessage = QueueMessages.CREATED(owner, priority, true, true, false, false, true);
- List<Object> log = performLog();
-
- String[] expected = {"Create :", "Owner:", owner, "AutoDelete",
- "Priority:",
- String.valueOf(priority)};
-
- validateLogMessage(log, "QUE-1001", expected);
- }
-
- public void testQueueCreatedOwnerAutoDeleteTransient()
- {
- String owner = "guest";
-
- _logMessage = QueueMessages.CREATED(owner, null, true, true, false, true, false);
- List<Object> log = performLog();
-
- String[] expected = {"Create :", "Owner:", owner, "AutoDelete",
- "Transient"};
-
- validateLogMessage(log, "QUE-1001", expected);
- }
-
- public void testQueueCreatedOwnerAutoDeleteTransientPriority()
- {
- String owner = "guest";
- Integer priority = 3;
-
- _logMessage = QueueMessages.CREATED(owner, priority, true, true, false, true, true);
- List<Object> log = performLog();
-
- String[] expected = {"Create :", "Owner:", owner, "AutoDelete",
- "Transient", "Priority:",
- String.valueOf(priority)};
-
- validateLogMessage(log, "QUE-1001", expected);
- }
-
- public void testQueueCreatedOwnerAutoDeleteDurable()
- {
- String owner = "guest";
-
- _logMessage = QueueMessages.CREATED(owner, null, true, true, true, false, false);
- List<Object> log = performLog();
-
- String[] expected = {"Create :", "Owner:", owner, "AutoDelete",
- "Durable"};
-
- validateLogMessage(log, "QUE-1001", expected);
- }
-
- public void testQueueCreatedOwnerAutoDeleteDurablePriority()
- {
- String owner = "guest";
- Integer priority = 3;
-
- _logMessage = QueueMessages.CREATED(owner, priority, true, true, true, false, true);
- List<Object> log = performLog();
-
- String[] expected = {"Create :", "Owner:", owner, "AutoDelete",
- "Durable", "Priority:",
- String.valueOf(priority)};
-
- validateLogMessage(log, "QUE-1001", expected);
- }
-
- public void testQueueCreatedAutoDelete()
- {
- _logMessage = QueueMessages.CREATED(null, null, false, true, false, false, false);
- List<Object> log = performLog();
-
- String[] expected = {"Create :", "AutoDelete"};
-
- validateLogMessage(log, "QUE-1001", expected);
- }
-
- public void testQueueCreatedPriority()
- {
- Integer priority = 3;
-
- _logMessage = QueueMessages.CREATED(null, priority, false, false, false, false, true);
- List<Object> log = performLog();
-
- String[] expected = {"Create :", "Priority:",
- String.valueOf(priority)};
-
- validateLogMessage(log, "QUE-1001", expected);
- }
-
- public void testQueueCreatedAutoDeletePriority()
- {
- Integer priority = 3;
-
- _logMessage = QueueMessages.CREATED(null, priority, false, true, false, false, true);
- List<Object> log = performLog();
-
- String[] expected = {"Create :", "AutoDelete",
- "Priority:",
- String.valueOf(priority)};
-
- validateLogMessage(log, "QUE-1001", expected);
- }
-
- public void testQueueCreatedAutoDeleteTransient()
- {
- _logMessage = QueueMessages.CREATED(null, null, false, true, false, true, false);
- List<Object> log = performLog();
-
- String[] expected = {"Create :", "AutoDelete",
- "Transient"};
-
- validateLogMessage(log, "QUE-1001", expected);
- }
-
- public void testQueueCreatedAutoDeleteTransientPriority()
- {
- Integer priority = 3;
-
- _logMessage = QueueMessages.CREATED(null, priority, false, true, false, true, true);
- List<Object> log = performLog();
-
- String[] expected = {"Create :", "AutoDelete",
- "Transient", "Priority:",
- String.valueOf(priority)};
-
- validateLogMessage(log, "QUE-1001", expected);
- }
-
- public void testQueueCreatedAutoDeleteDurable()
- {
- _logMessage = QueueMessages.CREATED(null, null, false, true, true, false, false);
- List<Object> log = performLog();
-
- String[] expected = {"Create :", "AutoDelete",
- "Durable"};
-
- validateLogMessage(log, "QUE-1001", expected);
- }
-
- public void testQueueCreatedAutoDeleteDurablePriority()
- {
- Integer priority = 3;
-
- _logMessage = QueueMessages.CREATED(null, priority, false, true, true, false, true);
- List<Object> log = performLog();
-
- String[] expected = {"Create :", "AutoDelete",
- "Durable", "Priority:",
- String.valueOf(priority)};
-
- validateLogMessage(log, "QUE-1001", expected);
- }
-
- public void testQueueDeleted()
- {
- _logMessage = QueueMessages.DELETED();
- List<Object> log = performLog();
-
- String[] expected = {"Deleted"};
-
- validateLogMessage(log, "QUE-1002", expected);
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/messages/SubscriptionMessagesTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/messages/SubscriptionMessagesTest.java
deleted file mode 100644
index b2bc351f8f..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/logging/messages/SubscriptionMessagesTest.java
+++ /dev/null
@@ -1,86 +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.logging.messages;
-
-import java.util.List;
-
-/**
- * Test SUB Log Messages
- */
-public class SubscriptionMessagesTest extends AbstractTestMessages
-{
- public void testSubscriptionCreateALL()
- {
- String arguments = "arguments";
-
- _logMessage = SubscriptionMessages.CREATE(arguments, true, true);
- List<Object> log = performLog();
-
- String[] expected = {"Create :", "Durable", "Arguments :", arguments};
-
- validateLogMessage(log, "SUB-1001", expected);
- }
-
- public void testSubscriptionCreateDurable()
- {
- _logMessage = SubscriptionMessages.CREATE(null, true, false);
- List<Object> log = performLog();
-
- String[] expected = {"Create :", "Durable"};
-
- validateLogMessage(log, "SUB-1001", expected);
- }
-
- public void testSubscriptionCreateArguments()
- {
- String arguments = "arguments";
-
- _logMessage = SubscriptionMessages.CREATE(arguments, false, true);
- List<Object> log = performLog();
-
- String[] expected = {"Create :","Arguments :", arguments};
-
- validateLogMessage(log, "SUB-1001", expected);
- }
-
-
- public void testSubscriptionClose()
- {
- _logMessage = SubscriptionMessages.CLOSE();
- List<Object> log = performLog();
-
- String[] expected = {"Close"};
-
- validateLogMessage(log, "SUB-1002", expected);
- }
-
- public void testSubscriptionState()
- {
- String state = "ACTIVE";
-
- _logMessage = SubscriptionMessages.STATE(state);
- List<Object> log = performLog();
-
- String[] expected = {"State :", state};
-
- validateLogMessage(log, "SUB-1003", expected);
- }
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/messages/VirtualHostMessagesTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/messages/VirtualHostMessagesTest.java
deleted file mode 100644
index 17d68ef7c3..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/logging/messages/VirtualHostMessagesTest.java
+++ /dev/null
@@ -1,51 +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.logging.messages;
-
-import java.util.List;
-
-/**
- * Test VHT Log Messages
- */
-public class VirtualHostMessagesTest extends AbstractTestMessages
-{
- public void testVirtualhostCreated()
- {
- String name = "test";
- _logMessage = VirtualHostMessages.CREATED(name);
- List<Object> log = performLog();
-
- String[] expected = {"Created :", name};
-
- validateLogMessage(log, "VHT-1001", expected);
- }
-
- public void testSubscriptionClosed()
- {
- _logMessage = VirtualHostMessages.CLOSED();
- List<Object> log = performLog();
-
- String[] expected = {"Closed"};
-
- validateLogMessage(log, "VHT-1002", expected);
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/AbstractTestLogSubject.java b/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/AbstractTestLogSubject.java
deleted file mode 100644
index 1cd8d55b0d..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/AbstractTestLogSubject.java
+++ /dev/null
@@ -1,288 +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.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;
-
-/**
- * Abstract Test for LogSubject testing
- * Includes common validation code and two common tests.
- *
- * Each test class sets up the LogSubject and contains details of how to
- * validate this class then performs a log statement with logging enabled and
- * logging disabled.
- *
- * The resulting log file is then validated.
- *
- */
-public abstract class AbstractTestLogSubject extends InternalBrokerBaseCase
-{
- protected Configuration _config = new PropertiesConfiguration();
- protected LogSubject _subject = null;
-
- @Override
- public void setUp() throws Exception
- {
- super.setUp();
-
- _config.setProperty(ServerConfiguration.STATUS_UPDATES, "ON");
- }
-
-
- protected List<Object> performLog() throws ConfigurationException
- {
- if (_subject == null)
- {
- throw new NullPointerException("LogSubject has not been set");
- }
-
- ServerConfiguration serverConfig = new ServerConfiguration(_config);
- UnitTestMessageLogger logger = new UnitTestMessageLogger(serverConfig);
-
- LogActor actor = new TestLogActor(logger);
-
- actor.message(_subject, new LogMessage()
- {
- public String toString()
- {
- return "<Log Message>";
- }
-
- public String getLogHierarchy()
- {
- return "test.hierarchy";
- }
- });
-
- return logger.getLogMessages();
- }
-
- /**
- * Verify that the connection section has the expected items
- *
- * @param connectionID - The connection id (int) to check for
- * @param user - the Connected username
- * @param ipString - the ipString/hostname
- * @param vhost - the virtualhost that the user connected to.
- * @param message - the message these values should appear in.
- */
- protected void verifyConnection(long connectionID, String user, String ipString, String vhost, String message)
- {
- // This should return us MockProtocolSessionUser@null/test
- String connectionSlice = getSlice("con:" + connectionID, message);
-
- assertNotNull("Unable to find connection 'con:" + connectionID + "'",
- connectionSlice);
-
- // Exract the userName
- String[] userNameParts = connectionSlice.split("@");
-
- assertEquals("Unable to split Username from rest of Connection:"
- + connectionSlice, 2, userNameParts.length);
-
- assertEquals("Username not as expected", userNameParts[0], user);
-
- // Extract IP.
- // The connection will be of the format - guest@/127.0.0.1:1/test
- // and so our userNamePart will be '/127.0.0.1:1/test'
- String[] ipParts = userNameParts[1].split("/");
-
- // We will have three sections
- assertEquals("Unable to split IP from rest of Connection:"
- + userNameParts[1], 3, ipParts.length);
-
- // We need to skip the first '/' split will be empty so validate 1 as IP
- assertEquals("IP not as expected", ipString, ipParts[1]);
-
- //Finally check vhost which is section 2
- assertEquals("Virtualhost name not as expected.", vhost, ipParts[2]);
- }
-
- /**
- * Verify that the RoutingKey is present in the provided message.
- *
- * @param message The message to check
- * @param routingKey The routing key to check against
- */
- protected void verifyRoutingKey(String message, AMQShortString routingKey)
- {
- String routingKeySlice = getSlice("rk", message);
-
- assertNotNull("Routing Key not found:" + message, routingKey);
-
- assertEquals("Routing key not correct",
- routingKey.toString(), routingKeySlice);
- }
-
- /**
- * Verify that the given Queue's name exists in the provided message
- *
- * @param message The message to check
- * @param queue The queue to check against
- */
- protected void verifyQueue(String message, AMQQueue queue)
- {
- String queueSlice = getSlice("qu", message);
-
- assertNotNull("Queue not found:" + message, queueSlice);
-
- assertEquals("Queue name not correct",
- queue.getNameShortString().toString(), queueSlice);
- }
-
- /**
- * Verify that the given exchange (name and type) are present in the
- * provided message.
- *
- * @param message The message to check
- * @param exchange the exchange to check against
- */
- protected void verifyExchange(String message, Exchange exchange)
- {
- String exchangeSilce = getSlice("ex", message);
-
- assertNotNull("Exchange not found:" + message, exchangeSilce);
-
- String[] exchangeParts = exchangeSilce.split("/");
-
- assertEquals("Exchange should be in two parts ex(type/name)", 2,
- exchangeParts.length);
-
- assertEquals("Exchange type not correct",
- exchange.getTypeShortString().toString(), exchangeParts[0]);
-
- assertEquals("Exchange name not correct",
- exchange.getNameShortString().toString(), exchangeParts[1]);
-
- }
-
- /**
- * Verify that a VirtualHost with the given name appears in the given
- * message.
- *
- * @param message the message to search
- * @param vhost the vhostName to check against
- */
- static public void verifyVirtualHost(String message, VirtualHost vhost)
- {
- String vhostSlice = getSlice("vh", message);
-
- assertNotNull("Virtualhost not found:" + message, vhostSlice);
-
- assertEquals("Virtualhost not correct", "/" + vhost.getName(), vhostSlice);
- }
-
- /**
- * Parse the log message and return the slice according to the following:
- * Given Example:
- * con:1(guest@127.0.0.1/test)/ch:2/ex(amq.direct)/qu(myQueue)/rk(myQueue)
- *
- * Each item (except channel) is of the format <key>(<values>)
- *
- * So Given an ID to slice on:
- * con:1 - Connection 1
- * ex - exchange
- * qu - queue
- * rk - routing key
- *
- * @param sliceID the slice to locate
- * @param message the message to search in
- *
- * @return the slice if found otherwise null is returned
- */
- static public String getSlice(String sliceID, String message)
- {
- int indexOfSlice = message.indexOf(sliceID + "(");
-
- if (indexOfSlice == -1)
- {
- return null;
- }
-
- int endIndex = message.indexOf(')', indexOfSlice);
-
- if (endIndex == -1)
- {
- return null;
- }
-
- return message.substring(indexOfSlice + 1 + sliceID.length(),
- endIndex);
- }
-
- /**
- * Test that when Logging occurs a single log statement is provided
- *
- * @throws ConfigurationException
- */
- public void testEnabled() throws ConfigurationException
- {
- List<Object> logs = performLog();
-
- assertEquals("Log has incorrect message count", 1, logs.size());
-
- validateLogStatement(String.valueOf(logs.get(0)));
- }
-
- /**
- * Call to the individiual tests to validate the message is formatted as
- * expected
- *
- * @param message the message whos format needs validation
- */
- protected abstract void validateLogStatement(String message);
-
- /**
- * Ensure that when status-updates are off this does not perform logging
- *
- * @throws ConfigurationException
- */
- public void testDisabled() throws ConfigurationException
- {
- _config.setProperty(ServerConfiguration.STATUS_UPDATES, "OFF");
-
- List<Object> logs = performLog();
-
- assertEquals("Log has incorrect message count", 0, logs.size());
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/BindingLogSubjectTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/BindingLogSubjectTest.java
deleted file mode 100644
index e80c4c4679..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/BindingLogSubjectTest.java
+++ /dev/null
@@ -1,71 +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.logging.subjects;
-
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.server.exchange.Exchange;
-import org.apache.qpid.server.queue.AMQQueue;
-import org.apache.qpid.server.queue.MockAMQQueue;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-
-/**
- * Validate BindingLogSubjects are logged as expected
- */
-public class BindingLogSubjectTest extends AbstractTestLogSubject
-{
-
- private AMQQueue _queue;
- private AMQShortString _routingKey;
- private Exchange _exchange;
- private VirtualHost _testVhost;
-
- public void setUp() throws Exception
- {
- super.setUp();
-
- _testVhost = ApplicationRegistry.getInstance().getVirtualHostRegistry().
- getVirtualHost("test");
- // Configure items for subjectCreation
- _routingKey = new AMQShortString("RoutingKey");
- _exchange = _testVhost.getExchangeRegistry().getDefaultExchange();
- _queue = new MockAMQQueue("BindingLogSubjectTest");
- ((MockAMQQueue) _queue).setVirtualHost(_testVhost);
-
- _subject = new BindingLogSubject(String.valueOf(_routingKey), _exchange, _queue);
- }
-
- /**
- * Validate that the logged Subject message is as expected:
- * MESSAGE [Blank][vh(/test)/ex(direct/<<default>>)/qu(BindingLogSubjectTest)/rk(RoutingKey)] <Log Message>
- * @param message the message whos format needs validation
- */
- @Override
- protected void validateLogStatement(String message)
- {
- verifyVirtualHost(message, _testVhost);
- verifyExchange(message, _exchange);
- verifyQueue(message, _queue);
- verifyRoutingKey(message, _routingKey);
- }
-
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/ChannelLogSubjectTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/ChannelLogSubjectTest.java
deleted file mode 100644
index 6bc5effa05..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/ChannelLogSubjectTest.java
+++ /dev/null
@@ -1,58 +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.logging.subjects;
-
-import org.apache.qpid.server.AMQChannel;
-
-/**
- * Validate ChannelLogSubjects are logged as expected
- */
-public class ChannelLogSubjectTest extends ConnectionLogSubjectTest
-{
- private final int _channelID = 1;
-
- @Override
- public void setUp() throws Exception
- {
- super.setUp();
-
- AMQChannel channel = new AMQChannel(getSession(), _channelID, getSession().getVirtualHost().getMessageStore());
-
- _subject = new ChannelLogSubject(channel);
- }
-
- /**
- * MESSAGE [Blank][con:0(MockProtocolSessionUser@null/test)/ch:1] <Log Message>
- *
- * @param message the message whos format needs validation
- */
- protected void validateLogStatement(String message)
- {
- // Use the ConnectionLogSubjectTest to vaildate that the connection
- // section is ok
- super.validateLogStatement(message);
-
- // Finally check that the channel identifier is correctly added
- assertTrue("Channel 1 identifier not found as part of Subject",
- message.contains(")/ch:1]"));
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/ConnectionLogSubjectTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/ConnectionLogSubjectTest.java
deleted file mode 100644
index c246fff2a8..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/ConnectionLogSubjectTest.java
+++ /dev/null
@@ -1,46 +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.logging.subjects;
-
-/**
- * Validate ConnectionLogSubjects are logged as expected
- */
-public class ConnectionLogSubjectTest extends AbstractTestLogSubject
-{
-
- public void setUp() throws Exception
- {
- super.setUp();
-
- _subject = new ConnectionLogSubject(getSession());
- }
-
- /**
- * MESSAGE [Blank][con:0(MockProtocolSessionUser@null/test)] <Log Message>
- *
- * @param message the message whos format needs validation
- */
- protected void validateLogStatement(String message)
- {
- verifyConnection(getSession().getSessionID(), "InternalTestProtocolSession", "127.0.0.1:1", "test", message);
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/ExchangeLogSubjectTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/ExchangeLogSubjectTest.java
deleted file mode 100644
index 7e16516fc6..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/ExchangeLogSubjectTest.java
+++ /dev/null
@@ -1,58 +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.logging.subjects;
-
-import org.apache.qpid.server.exchange.Exchange;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-
-
-/**
- * Validate ExchangeLogSubjects are logged as expected
- */
-public class ExchangeLogSubjectTest extends AbstractTestLogSubject
-{
- Exchange _exchange;
- VirtualHost _testVhost;
-
- public void setUp() throws Exception
- {
- super.setUp();
-
- _testVhost = ApplicationRegistry.getInstance().getVirtualHostRegistry().
- getVirtualHost("test");
-
- _exchange = _testVhost.getExchangeRegistry().getDefaultExchange();
- _subject = new ExchangeLogSubject(_exchange,_testVhost);
- }
-
- /**
- * Validate that the logged Subject message is as expected:
- * MESSAGE [Blank][vh(/test)/ex(direct/<<default>>)] <Log Message>
- * @param message the message whos format needs validation
- */
- @Override
- protected void validateLogStatement(String message)
- {
- verifyVirtualHost(message, _testVhost);
- verifyExchange(message, _exchange);
- }
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/MessageStoreLogSubjectTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/MessageStoreLogSubjectTest.java
deleted file mode 100644
index 9c868ea651..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/MessageStoreLogSubjectTest.java
+++ /dev/null
@@ -1,62 +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.logging.subjects;
-
-import org.apache.qpid.server.virtualhost.VirtualHost;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-
-/**
- * Validate MessageStoreLogSubjects are logged as expected
- */
-public class MessageStoreLogSubjectTest extends AbstractTestLogSubject
-{
- VirtualHost _testVhost;
-
- public void setUp() throws Exception
- {
- super.setUp();
-
- _testVhost = ApplicationRegistry.getInstance().getVirtualHostRegistry().
- getVirtualHost("test");
-
- _subject = new MessageStoreLogSubject(_testVhost, _testVhost.getMessageStore());
- }
-
- /**
- * Validate that the logged Subject message is as expected:
- * MESSAGE [Blank][vh(/test)/ms(MemoryMessageStore)] <Log Message>
- * @param message the message whos format needs validation
- */
- @Override
- protected void validateLogStatement(String message)
- {
- verifyVirtualHost(message, _testVhost);
-
- String msSlice = getSlice("ms", message);
-
- assertNotNull("MessageStore not found:" + message, msSlice);
-
- assertEquals("MessageStore not correct",
- _testVhost.getMessageStore().getClass().getSimpleName(),
- msSlice);
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/QueueLogSubjectTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/QueueLogSubjectTest.java
deleted file mode 100644
index 1f432be57a..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/QueueLogSubjectTest.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.server.logging.subjects;
-
-import org.apache.qpid.server.queue.AMQQueue;
-import org.apache.qpid.server.queue.MockAMQQueue;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-
-/**
- * Validate QueueLogSubjects are logged as expected
- */
-public class QueueLogSubjectTest extends AbstractTestLogSubject
-{
-
- private AMQQueue _queue;
- private VirtualHost _testVhost;
-
- @Override
- public void setUp() throws Exception
- {
- super.setUp();
-
- _testVhost = ApplicationRegistry.getInstance().getVirtualHostRegistry().
- getVirtualHost("test");
-
- _queue = new MockAMQQueue("QueueLogSubjectTest");
- ((MockAMQQueue) _queue).setVirtualHost(_testVhost);
-
- _subject = new QueueLogSubject(_queue);
- }
-
- /**
- * Validate that the logged Subject message is as expected:
- * MESSAGE [Blank][vh(/test)/qu(QueueLogSubjectTest)] <Log Message>
- *
- * @param message the message whos format needs validation
- */
- @Override
- protected void validateLogStatement(String message)
- {
- verifyVirtualHost(message, _testVhost);
- verifyQueue(message, _queue);
- }
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/SubscriptionLogSubjectTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/SubscriptionLogSubjectTest.java
deleted file mode 100644
index 0c356e1838..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/SubscriptionLogSubjectTest.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.logging.subjects;
-
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.server.AMQChannel;
-import org.apache.qpid.server.flow.LimitlessCreditManager;
-import org.apache.qpid.server.queue.AMQQueue;
-import org.apache.qpid.server.queue.MockAMQQueue;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-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.virtualhost.VirtualHost;
-
-/**
- * Validate SubscriptionLogSubjects are logged as expected
- */
-public class SubscriptionLogSubjectTest extends AbstractTestLogSubject
-{
-
- private AMQQueue _queue;
- private VirtualHost _testVhost;
- private int _channelID = 1;
- private Subscription _subscription;
-
- public void setUp() throws Exception
- {
- super.setUp();
-
- _testVhost = ApplicationRegistry.getInstance().getVirtualHostRegistry().
- getVirtualHost("test");
-
- _queue = new MockAMQQueue("SubscriptionLogSubjectTest");
- ((MockAMQQueue) _queue).setVirtualHost(_testVhost);
-
- AMQChannel channel = new AMQChannel(getSession(), _channelID, getSession().getVirtualHost().getMessageStore());
-
- getSession().addChannel(channel);
-
- SubscriptionFactory factory = new SubscriptionFactoryImpl();
-
- _subscription = factory.createSubscription(_channelID, getSession(), new AMQShortString("cTag"),
- false, null, false,
- new LimitlessCreditManager());
-
- _subscription.setQueue(_queue, false);
-
- _subject = new SubscriptionLogSubject(_subscription);
- }
-
- /**
- * Validate that the logged Subject message is as expected:
- * MESSAGE [Blank][sub:0(vh(/test)/qu(SubscriptionLogSubjectTest))] <Log Message>
- *
- * @param message the message whos format needs validation
- */
- @Override
- protected void validateLogStatement(String message)
- {
- String subscriptionSlice = getSlice("sub:"
- + _subscription.getSubscriptionID(),
- message);
-
- assertNotNull("Unable to locate subscription 'sub:" +
- _subscription.getSubscriptionID() + "'");
-
-
-
- // Pull out the qu(..) section from the subscription message
- // Split it into three parts
- // MESSAGE [Blank][sub:0(vh(/
- // test)/
- // qu(SubscriptionLogSubjectTest))]
- // Take the last bit and drop off the extra )]
- String[] parts = message.split("/");
- assertEquals("Message part count wrong", 3, parts.length);
- String subscription = parts[2].substring(0, parts[2].indexOf(")") + 1);
-
- // Adding the ')' is a bit ugly but SubscriptionLogSubject is the only
- // Subject that nests () and so the simple parser of checking for the
- // next ')' falls down.
- verifyVirtualHost(subscriptionSlice+ ")", _queue.getVirtualHost());
-
- verifyQueue(subscription, _queue);
- }
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/TestBlankSubject.java b/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/TestBlankSubject.java
deleted file mode 100644
index 89688e13b3..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/TestBlankSubject.java
+++ /dev/null
@@ -1,33 +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.logging.subjects;
-
-/**
- * Blank Subject for testing
- */
-public class TestBlankSubject extends AbstractLogSubject
-{
- public TestBlankSubject()
- {
- _logString = "[TestBlankSubject]";
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/management/AMQUserManagementMBeanTest.java b/java/broker/src/test/java/org/apache/qpid/server/management/AMQUserManagementMBeanTest.java
deleted file mode 100644
index 21f79e4b69..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/management/AMQUserManagementMBeanTest.java
+++ /dev/null
@@ -1,191 +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.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;
-
-/**
- *
- * Tests the AMQUserManagementMBean and its interaction with the PrincipalDatabase.
- *
- */
-public class AMQUserManagementMBeanTest extends InternalBrokerBaseCase
-{
- private PlainPasswordFilePrincipalDatabase _database;
- private AMQUserManagementMBean _amqumMBean;
-
- private File _passwordFile;
-
- private static final String TEST_USERNAME = "testuser";
- private static final String TEST_PASSWORD = "password";
-
- @Override
- public void setUp() throws Exception
- {
- super.setUp();
-
- _database = new PlainPasswordFilePrincipalDatabase();
- _amqumMBean = new AMQUserManagementMBean();
- loadFreshTestPasswordFile();
- }
-
- @Override
- public void tearDown() throws Exception
- {
- //clean up test password/access files
- File _oldPasswordFile = new File(_passwordFile.getAbsolutePath() + ".old");
- _oldPasswordFile.delete();
- _passwordFile.delete();
-
- super.tearDown();
- }
-
- public void testDeleteUser()
- {
- assertEquals("Unexpected number of users before test", 1,_amqumMBean.viewUsers().size());
- assertTrue("Delete should return true to flag successful delete", _amqumMBean.deleteUser(TEST_USERNAME));
- assertEquals("Unexpected number of users after test", 0,_amqumMBean.viewUsers().size());
- }
-
- public void testDeleteUserWhereUserDoesNotExist()
- {
- assertEquals("Unexpected number of users before test", 1,_amqumMBean.viewUsers().size());
- assertFalse("Delete should return false to flag unsuccessful delete", _amqumMBean.deleteUser("made.up.username"));
- assertEquals("Unexpected number of users after test", 1,_amqumMBean.viewUsers().size());
-
- }
-
- public void testCreateUser()
- {
- assertEquals("Unexpected number of users before test", 1,_amqumMBean.viewUsers().size());
- assertTrue("Create should return true to flag successful create", _amqumMBean.createUser("newuser", "mypass"));
- assertEquals("Unexpected number of users before test", 2,_amqumMBean.viewUsers().size());
- }
-
- public void testCreateUserWhereUserAlreadyExists()
- {
- assertEquals("Unexpected number of users before test", 1,_amqumMBean.viewUsers().size());
- assertFalse("Create should return false to flag unsuccessful create", _amqumMBean.createUser(TEST_USERNAME, "mypass"));
- assertEquals("Unexpected number of users before test", 1,_amqumMBean.viewUsers().size());
- }
-
- public void testFiveArgCreateUserWithNegativeRightsRemainsSupported()
- {
- assertEquals("Unexpected number of users before test", 1,_amqumMBean.viewUsers().size());
- assertTrue("Create should return true to flag successful create", _amqumMBean.createUser("newuser", "mypass".toCharArray(), false, false, false));
- assertEquals("Unexpected number of users before test", 2,_amqumMBean.viewUsers().size());
- }
-
- public void testSetPassword()
- {
- assertTrue("Set password should return true to flag successful change", _amqumMBean.setPassword(TEST_USERNAME, "newpassword"));
- }
-
- public void testSetPasswordWhereUserDoesNotExist()
- {
- assertFalse("Set password should return false to flag successful change", _amqumMBean.setPassword("made.up.username", "newpassword"));
- }
-
- public void testViewUsers()
- {
- TabularData userList = _amqumMBean.viewUsers();
-
- assertNotNull(userList);
- assertEquals("Unexpected number of users in user list", 1, userList.size());
- assertTrue(userList.containsKey(new Object[]{TEST_USERNAME}));
-
- // Check the deprecated read, write and admin items continue to exist but return false.
- CompositeData userRec = userList.get(new Object[]{TEST_USERNAME});
- assertTrue(userRec.containsKey(UserManagement.RIGHTS_READ_ONLY));
- assertEquals(false, userRec.get(UserManagement.RIGHTS_READ_ONLY));
- assertEquals(false, userRec.get(UserManagement.RIGHTS_READ_WRITE));
- assertTrue(userRec.containsKey(UserManagement.RIGHTS_READ_WRITE));
- assertTrue(userRec.containsKey(UserManagement.RIGHTS_ADMIN));
- assertEquals(false, userRec.get(UserManagement.RIGHTS_ADMIN));
- }
-
- // TEST DEPRECATED METHODS
- public void testFiveArgCreateUserWithPositiveRightsThrowsUnsupportedOperation()
- {
- try
- {
- _amqumMBean.createUser(TEST_USERNAME, "mypass", true, false, false);
- fail("Exception not thrown");
- }
- catch (UnsupportedOperationException uoe)
- {
- // PASS
- }
- }
-
- public void testSetRightsThrowsUnsupportedOperation()
- {
- try
- {
- _amqumMBean.setRights("", false, false, false);
- fail("Exception not thrown");
- }
- catch(UnsupportedOperationException nie)
- {
- // PASS
- }
- }
-
- // ============================ Utility methods =========================
-
- private void loadFreshTestPasswordFile()
- {
- try
- {
- if(_passwordFile == null)
- {
- _passwordFile = File.createTempFile(this.getClass().getName(),".password");
- }
-
- BufferedWriter passwordWriter = new BufferedWriter(new FileWriter(_passwordFile, false));
- passwordWriter.write(TEST_USERNAME + ":" + TEST_PASSWORD);
- passwordWriter.newLine();
- passwordWriter.flush();
- passwordWriter.close();
- _database.setPasswordFile(_passwordFile.toString());
- _amqumMBean.setPrincipalDatabase(_database);
- }
- catch (IOException e)
- {
- fail("Unable to create test password file: " + e.getMessage());
- }
- }
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/plugins/MockPluginManager.java b/java/broker/src/test/java/org/apache/qpid/server/plugins/MockPluginManager.java
deleted file mode 100644
index a64ec5d3b1..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/plugins/MockPluginManager.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.server.plugins;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.qpid.server.configuration.plugins.ConfigurationPluginFactory;
-import org.apache.qpid.server.exchange.ExchangeType;
-import org.apache.qpid.server.security.SecurityPluginFactory;
-
-public class MockPluginManager extends PluginManager
-{
- private Map<String, SecurityPluginFactory> _securityPlugins = new HashMap<String, SecurityPluginFactory>();
- private Map<List<String>, ConfigurationPluginFactory> _configPlugins = new HashMap<List<String>, ConfigurationPluginFactory>();
-
- public MockPluginManager(String pluginPath, String cachePath) throws Exception
- {
- super(pluginPath, cachePath);
- }
-
- @Override
- public Map<String, ExchangeType<?>> getExchanges()
- {
- return null;
- }
-
- @Override
- public Map<String, SecurityPluginFactory> getSecurityPlugins()
- {
- return _securityPlugins;
- }
-
- @Override
- public Map<List<String>, ConfigurationPluginFactory> getConfigurationPlugins()
- {
- return _configPlugins;
- }
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/plugins/PluginTest.java b/java/broker/src/test/java/org/apache/qpid/server/plugins/PluginTest.java
deleted file mode 100644
index 8c18ab85b0..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/plugins/PluginTest.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.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
-{
- private static final String TEST_EXCHANGE_CLASS = "org.apache.qpid.extras.exchanges.example.TestExchangeType";
-
- private static final String PLUGIN_DIRECTORY = System.getProperty("example.plugin.target");
- private static final String CACHE_DIRECTORY = System.getProperty("example.cache.target");
-
- @Override
- public void configure()
- {
- getConfiguration().getConfig().addProperty("plugin-directory", PLUGIN_DIRECTORY);
- getConfiguration().getConfig().addProperty("cache-directory", CACHE_DIRECTORY);
- }
-
- public void disabled_testLoadExchanges() throws Exception
- {
- PluginManager manager = getRegistry().getPluginManager();
- Map<String, ExchangeType<?>> exchanges = manager.getExchanges();
- assertNotNull("No exchanges found in " + PLUGIN_DIRECTORY, exchanges);
- assertEquals("Wrong number of exchanges found in " + PLUGIN_DIRECTORY, 2, exchanges.size());
- assertNotNull("Wrong exchange found in " + PLUGIN_DIRECTORY, exchanges.get(TEST_EXCHANGE_CLASS));
- }
-
- public void testNoExchanges() throws Exception
- {
- PluginManager manager = new PluginManager("/path/to/nowhere", "/tmp");
- Map<String, ExchangeType<?>> exchanges = manager.getExchanges();
- assertTrue("Exchanges found", exchanges.isEmpty());
- }
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/protocol/AMQProtocolSessionMBeanTest.java b/java/broker/src/test/java/org/apache/qpid/server/protocol/AMQProtocolSessionMBeanTest.java
deleted file mode 100644
index 4df051edb5..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/protocol/AMQProtocolSessionMBeanTest.java
+++ /dev/null
@@ -1,146 +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.protocol;
-
-import junit.framework.TestCase;
-import org.apache.log4j.Logger;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.management.common.mbeans.ManagedConnection;
-import org.apache.qpid.server.AMQChannel;
-import org.apache.qpid.server.util.InternalBrokerBaseCase;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-import org.apache.qpid.server.queue.AMQQueue;
-import org.apache.qpid.server.queue.AMQQueueFactory;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-import org.apache.qpid.server.store.MessageStore;
-import org.apache.qpid.server.store.SkeletonMessageStore;
-
-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
-{
- /** Used for debugging. */
- private static final Logger log = Logger.getLogger(AMQProtocolSessionMBeanTest.class);
-
- private MessageStore _messageStore = new SkeletonMessageStore();
- private AMQProtocolEngine _protocolSession;
- private AMQChannel _channel;
- private AMQProtocolSessionMBean _mbean;
-
- public void testChannels() throws Exception
- {
- // check the channel count is correct
- int channelCount = _mbean.channels().size();
- assertTrue(channelCount == 1);
- AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(new AMQShortString("testQueue_" + System.currentTimeMillis()),
- false,
- new AMQShortString("test"),
- true,
- false, _protocolSession.getVirtualHost(), null);
- AMQChannel channel = new AMQChannel(_protocolSession, 2, _messageStore);
- channel.setDefaultQueue(queue);
- _protocolSession.addChannel(channel);
- channelCount = _mbean.channels().size();
- assertTrue(channelCount == 2);
-
- // general properties test
- _mbean.setMaximumNumberOfChannels(1000L);
- assertTrue(_mbean.getMaximumNumberOfChannels() == 1000L);
-
- // check APIs
- AMQChannel channel3 = new AMQChannel(_protocolSession, 3, _messageStore);
- channel3.setLocalTransactional();
- _protocolSession.addChannel(channel3);
- _mbean.rollbackTransactions(2);
- _mbean.rollbackTransactions(3);
- _mbean.commitTransactions(2);
- _mbean.commitTransactions(3);
-
- // This should throw exception, because the channel does't exist
- try
- {
- _mbean.commitTransactions(4);
- fail();
- }
- catch (JMException ex)
- {
- log.debug("expected exception is thrown :" + ex.getMessage());
- }
-
- // check channels() return type conveys flow control blocking status correctly
- AMQChannel channel4 = new AMQChannel(_protocolSession, 4, _messageStore);
- _protocolSession.addChannel(channel4);
- channel4.setDefaultQueue(queue);
-
- final String blocking = ManagedConnection.FLOW_BLOCKED;
- TabularData channels = _mbean.channels();
- CompositeData chan4result = channels.get(new Integer[]{4});
- assertNotNull(chan4result);
- assertEquals("Flow should not have been blocked", false, chan4result.get(blocking));
-
- channel4.block(queue);
- channels = _mbean.channels();
- chan4result = channels.get(new Integer[]{4});
- assertNotNull(chan4result);
- assertEquals("Flow should have been blocked", true, chan4result.get(blocking));
-
- channel4.unblock(queue);
- channels = _mbean.channels();
- chan4result = channels.get(new Integer[]{4});
- assertNotNull(chan4result);
- assertEquals("Flow should have been unblocked", false, chan4result.get(blocking));
-
- // check if closing of session works
- _protocolSession.addChannel(new AMQChannel(_protocolSession, 5, _messageStore));
- _mbean.closeConnection();
- try
- {
- channelCount = _mbean.channels().size();
- assertTrue(channelCount == 0);
- // session is now closed so adding another channel should throw an exception
- _protocolSession.addChannel(new AMQChannel(_protocolSession, 6, _messageStore));
- fail();
- }
- catch (AMQException ex)
- {
- log.debug("expected exception is thrown :" + ex.getMessage());
- }
- }
-
- @Override
- public void setUp() throws Exception
- {
- super.setUp();
-
- VirtualHost vhost = ApplicationRegistry.getInstance().getVirtualHostRegistry().getVirtualHost("test");
- _protocolSession = new InternalTestProtocolSession(vhost);
-
- _channel = new AMQChannel(_protocolSession, 1, _messageStore);
- _protocolSession.addChannel(_channel);
- _mbean = (AMQProtocolSessionMBean) _protocolSession.getManagedObject();
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/protocol/InternalTestProtocolSession.java b/java/broker/src/test/java/org/apache/qpid/server/protocol/InternalTestProtocolSession.java
deleted file mode 100644
index 3b6cd37ea9..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/protocol/InternalTestProtocolSession.java
+++ /dev/null
@@ -1,213 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.protocol;
-
-import java.security.Principal;
-import java.util.*;
-import java.util.concurrent.atomic.AtomicInteger;
-
-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.protocol.AMQConstant;
-import org.apache.qpid.server.AMQChannel;
-import org.apache.qpid.server.output.ProtocolOutputConverter;
-import org.apache.qpid.server.message.AMQMessage;
-import org.apache.qpid.server.queue.QueueEntry;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-import org.apache.qpid.server.state.AMQState;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-import org.apache.qpid.server.message.MessageContentSource;
-import org.apache.qpid.transport.TestNetworkDriver;
-
-public class InternalTestProtocolSession extends AMQProtocolEngine implements ProtocolOutputConverter
-{
- // ChannelID(LIST) -> LinkedList<Pair>
- final Map<Integer, Map<AMQShortString, LinkedList<DeliveryPair>>> _channelDelivers;
- private AtomicInteger _deliveryCount = new AtomicInteger(0);
-
- public InternalTestProtocolSession(VirtualHost virtualHost) throws AMQException
- {
- super(ApplicationRegistry.getInstance().getVirtualHostRegistry(), new TestNetworkDriver());
-
- _channelDelivers = new HashMap<Integer, Map<AMQShortString, LinkedList<DeliveryPair>>>();
-
- // Need to authenticate session for it to be representative testing.
- setAuthorizedID(new Principal()
- {
- public String getName()
- {
- return "InternalTestProtocolSession";
- }
- });
-
- setVirtualHost(virtualHost);
- }
-
- public ProtocolOutputConverter getProtocolOutputConverter()
- {
- return this;
- }
-
- public byte getProtocolMajorVersion()
- {
- return (byte) 8;
- }
-
- public void writeReturn(MessagePublishInfo messagePublishInfo,
- ContentHeaderBody header,
- MessageContentSource msgContent,
- int channelId,
- int replyCode,
- AMQShortString replyText) throws AMQException
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public byte getProtocolMinorVersion()
- {
- return (byte) 0;
- }
-
- // ***
-
- public List<DeliveryPair> getDelivers(int channelId, AMQShortString consumerTag, int count)
- {
- synchronized (_channelDelivers)
- {
- List<DeliveryPair> all =_channelDelivers.get(channelId).get(consumerTag);
-
- if (all == null)
- {
- return new ArrayList<DeliveryPair>(0);
- }
-
- List<DeliveryPair> msgs = all.subList(0, count);
-
- List<DeliveryPair> response = new ArrayList<DeliveryPair>(msgs);
-
- //Remove the msgs from the receivedList.
- msgs.clear();
-
- return response;
- }
- }
-
- // *** ProtocolOutputConverter Implementation
- public void writeReturn(AMQMessage message, int channelId, int replyCode, AMQShortString replyText) throws AMQException
- {
- }
-
- public void confirmConsumerAutoClose(int channelId, AMQShortString consumerTag)
- {
- }
-
- public void writeDeliver(QueueEntry entry, int channelId, long deliveryTag, AMQShortString consumerTag) throws AMQException
- {
- _deliveryCount.incrementAndGet();
-
- synchronized (_channelDelivers)
- {
- Map<AMQShortString, LinkedList<DeliveryPair>> consumers = _channelDelivers.get(channelId);
-
- if (consumers == null)
- {
- consumers = new HashMap<AMQShortString, LinkedList<DeliveryPair>>();
- _channelDelivers.put(channelId, consumers);
- }
-
- LinkedList<DeliveryPair> consumerDelivers = consumers.get(consumerTag);
-
- if (consumerDelivers == null)
- {
- consumerDelivers = new LinkedList<DeliveryPair>();
- consumers.put(consumerTag, consumerDelivers);
- }
-
- consumerDelivers.add(new DeliveryPair(deliveryTag, (AMQMessage)entry.getMessage()));
- }
- }
-
- public void writeGetOk(QueueEntry message, int channelId, long deliveryTag, int queueSize) throws AMQException
- {
- }
-
- public void awaitDelivery(int msgs)
- {
- while (msgs > _deliveryCount.get())
- {
- try
- {
- Thread.sleep(100);
- }
- catch (InterruptedException e)
- {
- e.printStackTrace();
- }
- }
- }
-
- public class DeliveryPair
- {
- private long _deliveryTag;
- private AMQMessage _message;
-
- public DeliveryPair(long deliveryTag, AMQMessage message)
- {
- _deliveryTag = deliveryTag;
- _message = message;
- }
-
- public AMQMessage getMessage()
- {
- return _message;
- }
-
- public long getDeliveryTag()
- {
- return _deliveryTag;
- }
- }
-
- public boolean isClosed()
- {
- return _closed;
- }
-
- public void closeProtocolSession(boolean waitLast)
- {
- // Override as we don't have a real IOSession to close.
- // The alternative is to fully implement the TestIOSession to return a CloseFuture from close();
- // Then the AMQMinaProtocolSession can join on the returning future without a NPE.
- }
-
- public void closeSession(AMQSessionModel session, AMQConstant cause, String message) throws AMQException
- {
- super.closeSession(session, cause, message);
-
- //Simulate the Client responding with a CloseOK
- // should really update the StateManger but we don't have access here
- // changeState(AMQState.CONNECTION_CLOSED);
- ((AMQChannel)session).getProtocolSession().closeSession();
-
- }
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/protocol/MaxChannelsTest.java b/java/broker/src/test/java/org/apache/qpid/server/protocol/MaxChannelsTest.java
deleted file mode 100644
index f6e83e6369..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/protocol/MaxChannelsTest.java
+++ /dev/null
@@ -1,79 +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.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.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
-{
- private AMQProtocolEngine _session;
-
- public void testChannels() throws Exception
- {
- VirtualHost vhost = ApplicationRegistry.getInstance().getVirtualHostRegistry().getVirtualHost("test");
- _session = new InternalTestProtocolSession(vhost);
-
- // check the channel count is correct
- int channelCount = _session.getChannels().size();
- assertEquals("Initial channel count wrong", 0, channelCount);
-
- long maxChannels = 10L;
- _session.setMaximumNumberOfChannels(maxChannels);
- assertEquals("Number of channels not correctly set.", new Long(maxChannels), _session.getMaximumNumberOfChannels());
-
-
- try
- {
- for (long currentChannel = 0L; currentChannel < maxChannels; currentChannel++)
- {
- _session.addChannel(new AMQChannel(_session, (int) currentChannel, null));
- }
- }
- catch (AMQException e)
- {
- assertEquals("Wrong exception recevied.", e.getErrorCode(), AMQConstant.NOT_ALLOWED);
- }
- assertEquals("Maximum number of channels not set.", new Long(maxChannels), new Long(_session.getChannels().size()));
- }
-
- @Override
- public void tearDown() throws Exception
- {
- try {
- _session.closeSession();
- } catch (AMQException e) {
- // Yikes
- fail(e.getMessage());
- }
- finally
- {
- super.tearDown();
- }
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/queue/AMQPriorityQueueTest.java b/java/broker/src/test/java/org/apache/qpid/server/queue/AMQPriorityQueueTest.java
deleted file mode 100644
index 3961b3b355..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/queue/AMQPriorityQueueTest.java
+++ /dev/null
@@ -1,108 +0,0 @@
-package org.apache.qpid.server.queue;
-/*
- *
- * 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 java.util.ArrayList;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.server.message.AMQMessage;
-import org.apache.qpid.framing.BasicContentHeaderProperties;
-import org.apache.qpid.framing.FieldTable;
-import junit.framework.AssertionFailedError;
-
-public class AMQPriorityQueueTest extends SimpleAMQQueueTest
-{
-
- @Override
- public void setUp() throws Exception
- {
- _arguments = new FieldTable();
- _arguments.put(AMQQueueFactory.X_QPID_PRIORITIES, 3);
- super.setUp();
- }
-
- public void testPriorityOrdering() throws AMQException, InterruptedException
- {
-
- // Enqueue messages in order
- _queue.enqueue(createMessage(1L, (byte) 10));
- _queue.enqueue(createMessage(2L, (byte) 4));
- _queue.enqueue(createMessage(3L, (byte) 0));
-
- // Enqueue messages in reverse order
- _queue.enqueue(createMessage(4L, (byte) 0));
- _queue.enqueue(createMessage(5L, (byte) 4));
- _queue.enqueue(createMessage(6L, (byte) 10));
-
- // Enqueue messages out of order
- _queue.enqueue(createMessage(7L, (byte) 4));
- _queue.enqueue(createMessage(8L, (byte) 10));
- _queue.enqueue(createMessage(9L, (byte) 0));
-
- // Register subscriber
- _queue.registerSubscription(_subscription, false);
- Thread.sleep(150);
-
- ArrayList<QueueEntry> msgs = _subscription.getMessages();
- try
- {
- assertEquals(new Long(1L), msgs.get(0).getMessage().getMessageNumber());
- assertEquals(new Long(6L), msgs.get(1).getMessage().getMessageNumber());
- assertEquals(new Long(8L), msgs.get(2).getMessage().getMessageNumber());
-
- assertEquals(new Long(2L), msgs.get(3).getMessage().getMessageNumber());
- assertEquals(new Long(5L), msgs.get(4).getMessage().getMessageNumber());
- assertEquals(new Long(7L), msgs.get(5).getMessage().getMessageNumber());
-
- assertEquals(new Long(3L), msgs.get(6).getMessage().getMessageNumber());
- assertEquals(new Long(4L), msgs.get(7).getMessage().getMessageNumber());
- assertEquals(new Long(9L), msgs.get(8).getMessage().getMessageNumber());
- }
- catch (AssertionFailedError afe)
- {
- // Show message order on failure.
- int index = 1;
- for (QueueEntry qe : msgs)
- {
- System.err.println(index + ":" + qe.getMessage().getMessageNumber());
- index++;
- }
-
- throw afe;
- }
-
- }
-
- protected AMQMessage createMessage(Long id, byte i) throws AMQException
- {
- AMQMessage msg = super.createMessage(id);
- BasicContentHeaderProperties props = new BasicContentHeaderProperties();
- props.setPriority(i);
- msg.getContentHeaderBody().setProperties(props);
- return msg;
- }
-
- protected AMQMessage createMessage(Long id) throws AMQException
- {
- return createMessage(id, (byte) 0);
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueAlertTest.java b/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueAlertTest.java
deleted file mode 100644
index a8bddcf6bf..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueAlertTest.java
+++ /dev/null
@@ -1,350 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.queue;
-
-import org.apache.mina.common.ByteBuffer;
-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.abstraction.ContentChunk;
-import org.apache.qpid.framing.abstraction.MessagePublishInfo;
-import org.apache.qpid.server.AMQChannel;
-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.subscription.Subscription;
-import org.apache.qpid.server.subscription.SubscriptionFactoryImpl;
-import org.apache.qpid.server.util.InternalBrokerBaseCase;
-
-import javax.management.Notification;
-import java.util.ArrayList;
-
-/** This class tests all the alerts an AMQQueue can throw based on threshold values of different parameters */
-public class AMQQueueAlertTest extends InternalBrokerBaseCase
-{
- private final static long MAX_MESSAGE_COUNT = 50;
- private final static long MAX_MESSAGE_AGE = 250; // 0.25 sec
- private final static long MAX_MESSAGE_SIZE = 2000; // 2 KB
- private final static long MAX_QUEUE_DEPTH = 10000; // 10 KB
- private AMQQueueMBean _queueMBean;
- private static final SubscriptionFactoryImpl SUBSCRIPTION_FACTORY = SubscriptionFactoryImpl.INSTANCE;
-
- /**
- * Tests if the alert gets thrown when message count increases the threshold limit
- *
- * @throws Exception
- */
- public void testMessageCountAlert() throws Exception
- {
- setSession(new InternalTestProtocolSession(getVirtualHost()));
- AMQChannel channel = new AMQChannel(getSession(), 2, getMessageStore());
- getSession().addChannel(channel);
-
- setQueue(AMQQueueFactory.createAMQQueueImpl(new AMQShortString("testQueue1"), false, new AMQShortString("AMQueueAlertTest"),
- false, false,
- getVirtualHost(), null));
- _queueMBean = (AMQQueueMBean) getQueue().getManagedObject();
-
- _queueMBean.setMaximumMessageCount(MAX_MESSAGE_COUNT);
-
- sendMessages(channel, MAX_MESSAGE_COUNT, 256l);
- assertTrue(_queueMBean.getMessageCount() == MAX_MESSAGE_COUNT);
-
- Notification lastNotification = _queueMBean.getLastNotification();
- assertNotNull(lastNotification);
-
- String notificationMsg = lastNotification.getMessage();
- assertTrue(notificationMsg.startsWith(NotificationCheck.MESSAGE_COUNT_ALERT.name()));
- }
-
- /**
- * Tests if the Message Size alert gets thrown when message of higher than threshold limit is sent
- *
- * @throws Exception
- */
- public void testMessageSizeAlert() throws Exception
- {
- setSession(new InternalTestProtocolSession(getVirtualHost()));
- AMQChannel channel = new AMQChannel(getSession(), 2, getMessageStore());
- getSession().addChannel(channel);
-
- setQueue(AMQQueueFactory.createAMQQueueImpl(new AMQShortString("testQueue2"), false, new AMQShortString("AMQueueAlertTest"),
- false, false,
- getVirtualHost(), null));
- _queueMBean = (AMQQueueMBean) getQueue().getManagedObject();
- _queueMBean.setMaximumMessageCount(MAX_MESSAGE_COUNT);
- _queueMBean.setMaximumMessageSize(MAX_MESSAGE_SIZE);
-
- sendMessages(channel, 1, MAX_MESSAGE_SIZE * 2);
- assertTrue(_queueMBean.getMessageCount() == 1);
-
- Notification lastNotification = _queueMBean.getLastNotification();
- assertNotNull(lastNotification);
-
- String notificationMsg = lastNotification.getMessage();
- assertTrue(notificationMsg.startsWith(NotificationCheck.MESSAGE_SIZE_ALERT.name()));
- }
-
- /**
- * Tests if Queue Depth alert is thrown when queue depth reaches the threshold value
- *
- * Based on FT-402 subbmitted by client
- *
- * @throws Exception
- */
- public void testQueueDepthAlertNoSubscriber() throws Exception
- {
- setSession(new InternalTestProtocolSession(getVirtualHost()));
- AMQChannel channel = new AMQChannel(getSession(), 2, getMessageStore());
- getSession().addChannel(channel);
-
- setQueue(AMQQueueFactory.createAMQQueueImpl(new AMQShortString("testQueue3"), false, new AMQShortString("AMQueueAlertTest"),
- false, false,
- getVirtualHost(), null));
- _queueMBean = (AMQQueueMBean) getQueue().getManagedObject();
- _queueMBean.setMaximumMessageCount(MAX_MESSAGE_COUNT);
- _queueMBean.setMaximumQueueDepth(MAX_QUEUE_DEPTH);
-
- while (getQueue().getQueueDepth() < MAX_QUEUE_DEPTH)
- {
- sendMessages(channel, 1, MAX_MESSAGE_SIZE);
- }
-
- Notification lastNotification = _queueMBean.getLastNotification();
- assertNotNull(lastNotification);
-
- String notificationMsg = lastNotification.getMessage();
- assertTrue(notificationMsg.startsWith(NotificationCheck.QUEUE_DEPTH_ALERT.name()));
- }
-
- /**
- * Tests if MESSAGE AGE alert is thrown, when a message is in the queue for time higher than threshold value of
- * message age
- *
- * Alternative test to FT-401 provided by client
- *
- * @throws Exception
- */
- public void testMessageAgeAlert() throws Exception
- {
- setSession(new InternalTestProtocolSession(getVirtualHost()));
- AMQChannel channel = new AMQChannel(getSession(), 2, getMessageStore());
- getSession().addChannel(channel);
-
- setQueue(AMQQueueFactory.createAMQQueueImpl(new AMQShortString("testQueue4"), false, new AMQShortString("AMQueueAlertTest"),
- false, false,
- getVirtualHost(), null));
- _queueMBean = (AMQQueueMBean) getQueue().getManagedObject();
- _queueMBean.setMaximumMessageCount(MAX_MESSAGE_COUNT);
- _queueMBean.setMaximumMessageAge(MAX_MESSAGE_AGE);
-
- sendMessages(channel, 1, MAX_MESSAGE_SIZE);
-
- // Ensure message sits on queue long enough to age.
- Thread.sleep(MAX_MESSAGE_AGE * 2);
-
- Notification lastNotification = _queueMBean.getLastNotification();
- assertNotNull("Last notification was null", lastNotification);
-
- String notificationMsg = lastNotification.getMessage();
- assertTrue(notificationMsg.startsWith(NotificationCheck.MESSAGE_AGE_ALERT.name()));
- }
-
- /*
- This test sends some messages to the queue with subscribers needing message to be acknowledged.
- The messages will not be acknowledged and will be required twice. Why we are checking this is because
- the bug reported said that the queueDepth keeps increasing when messages are requeued.
- // TODO - queue depth now includes unacknowledged messages so does not go down when messages are delivered
-
- The QueueDepth should decrease when messages are delivered from the queue (QPID-408)
- */
- public void testQueueDepthAlertWithSubscribers() throws Exception
- {
- AMQChannel channel = new AMQChannel(getSession(), 2, getMessageStore());
- getSession().addChannel(channel);
-
- // Create queue
- setQueue(getNewQueue());
- Subscription subscription =
- SUBSCRIPTION_FACTORY.createSubscription(channel.getChannelId(), getSession(), new AMQShortString("consumer_tag"), true, null, false, channel.getCreditManager());
-
- getQueue().registerSubscription(
- subscription, false);
-
- _queueMBean = (AMQQueueMBean) getQueue().getManagedObject();
- _queueMBean.setMaximumMessageCount(9999l); // Set a high value, because this is not being tested
- _queueMBean.setMaximumQueueDepth(MAX_QUEUE_DEPTH);
-
- // Send messages(no of message to be little more than what can cause a Queue_Depth alert)
- int messageCount = Math.round(MAX_QUEUE_DEPTH / MAX_MESSAGE_SIZE) + 10;
- long totalSize = (messageCount * MAX_MESSAGE_SIZE);
- sendMessages(channel, messageCount, MAX_MESSAGE_SIZE);
-
- // Check queueDepth. There should be no messages on the queue and as the subscriber is listening
- // so there should be no Queue_Deoth alert raised
- assertEquals(new Long(totalSize), new Long(_queueMBean.getQueueDepth()));
- Notification lastNotification = _queueMBean.getLastNotification();
-// assertNull(lastNotification);
-
- // Kill the subscriber and check for the queue depth values.
- // Messages are unacknowledged, so those should get requeued. All messages should be on the Queue
- getQueue().unregisterSubscription(subscription);
- channel.requeue();
-
- assertEquals(new Long(totalSize), new Long(_queueMBean.getQueueDepth()));
-
- lastNotification = _queueMBean.getLastNotification();
- assertNotNull(lastNotification);
- String notificationMsg = lastNotification.getMessage();
- assertTrue(notificationMsg.startsWith(NotificationCheck.QUEUE_DEPTH_ALERT.name()));
-
- // Connect a consumer again and check QueueDepth values. The queue should get emptied.
- // Messages will get delivered but still are unacknowledged.
- Subscription subscription2 =
- SUBSCRIPTION_FACTORY.createSubscription(channel.getChannelId(), getSession(), new AMQShortString("consumer_tag"), true, null, false, channel.getCreditManager());
-
- getQueue().registerSubscription(
- subscription2, false);
-
- while (getQueue().getUndeliveredMessageCount()!= 0)
- {
- Thread.sleep(100);
- }
-// assertEquals(new Long(0), new Long(_queueMBean.getQueueDepth()));
-
- // Kill the subscriber again. Now those messages should get requeued again. Check if the queue depth
- // value is correct.
- getQueue().unregisterSubscription(subscription2);
- channel.requeue();
-
- assertEquals(new Long(totalSize), new Long(_queueMBean.getQueueDepth()));
- getSession().closeSession();
-
- // Check the clear queue
- _queueMBean.clearQueue();
- assertEquals(new Long(0), new Long(_queueMBean.getQueueDepth()));
- }
-
- protected IncomingMessage message(final boolean immediate, long size) throws AMQException
- {
- MessagePublishInfo publish = new MessagePublishInfo()
- {
-
- public AMQShortString getExchange()
- {
- return null;
- }
-
- public void setExchange(AMQShortString exchange)
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean isImmediate()
- {
- return immediate;
- }
-
- public boolean isMandatory()
- {
- return false;
- }
-
- public AMQShortString getRoutingKey()
- {
- return null;
- }
- };
-
- ContentHeaderBody contentHeaderBody = new ContentHeaderBody();
- BasicContentHeaderProperties props = new BasicContentHeaderProperties();
- contentHeaderBody.setProperties(props);
- contentHeaderBody.bodySize = size; // in bytes
- IncomingMessage message = new IncomingMessage(publish);
- message.setContentHeaderBody(contentHeaderBody);
-
- return message;
- }
-
- @Override
- protected void configure()
- {
- // Increase Alert Check period
- getConfiguration().setHousekeepingExpiredMessageCheckPeriod(200);
- }
-
- private void sendMessages(AMQChannel channel, long messageCount, final long size) throws AMQException
- {
- IncomingMessage[] messages = new IncomingMessage[(int) messageCount];
- MessageMetaData[] metaData = new MessageMetaData[(int) messageCount];
- for (int i = 0; i < messages.length; i++)
- {
- messages[i] = message(false, size);
- ArrayList<AMQQueue> qs = new ArrayList<AMQQueue>();
- qs.add(getQueue());
- metaData[i] = messages[i].headersReceived();
- messages[i].setStoredMessage(getMessageStore().addMessage(metaData[i]));
-
- messages[i].enqueue(qs);
-
- }
-
- for (int i = 0; i < messageCount; i++)
- {
- messages[i].addContentBodyFrame(new ContentChunk(){
-
- ByteBuffer _data = ByteBuffer.allocate((int)size);
-
- {
- _data.limit((int)size);
- }
-
- public int getSize()
- {
- return (int) size;
- }
-
- public ByteBuffer getData()
- {
- return _data;
- }
-
- public void reduceToFit()
- {
-
- }
- });
-
- getQueue().enqueue(new AMQMessage(messages[i].getStoredMessage()));
-
- }
- }
-
- private AMQQueue getNewQueue() throws AMQException
- {
- return AMQQueueFactory.createAMQQueueImpl(new AMQShortString("testQueue" + Math.random()),
- false,
- new AMQShortString("AMQueueAlertTest"),
- false,
- false, getVirtualHost(), null);
- }
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueFactoryTest.java b/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueFactoryTest.java
deleted file mode 100644
index 27891289fb..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueFactoryTest.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.queue;
-
-import org.apache.qpid.server.registry.ApplicationRegistry;
-import org.apache.qpid.server.util.InternalBrokerBaseCase;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.FieldTable;
-
-public class AMQQueueFactoryTest extends InternalBrokerBaseCase
-{
- QueueRegistry _queueRegistry;
- VirtualHost _virtualHost;
- int _defaultQueueCount;
-
- @Override
- public void setUp() throws Exception
- {
- super.setUp();
- ApplicationRegistry registry = (ApplicationRegistry) ApplicationRegistry.getInstance();
-
- _virtualHost = registry.getVirtualHostRegistry().getVirtualHost("test");
-
- _queueRegistry = _virtualHost.getQueueRegistry();
-
- _defaultQueueCount = _queueRegistry.getQueues().size();
- }
-
- @Override
- public void tearDown() throws Exception
- {
- assertEquals("Queue was not registered in virtualhost", _defaultQueueCount + 1, _queueRegistry.getQueues().size());
- super.tearDown();
- }
-
-
- public void testPriorityQueueRegistration() throws Exception
- {
- FieldTable fieldTable = new FieldTable();
- fieldTable.put(new AMQShortString(AMQQueueFactory.X_QPID_PRIORITIES), 5);
-
-
- AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(new AMQShortString("testPriorityQueue"), false, new AMQShortString("owner"), false,
- false, _virtualHost, fieldTable);
-
- assertEquals("Queue not a priorty queue", AMQPriorityQueue.class, queue.getClass());
- }
-
-
- public void testSimpleQueueRegistration() throws Exception
- {
- AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(new AMQShortString("testQueue"), false, new AMQShortString("owner"), false,
- false, _virtualHost, null);
- assertEquals("Queue not a simple queue", SimpleAMQQueue.class, queue.getClass());
- }
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueMBeanTest.java b/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueMBeanTest.java
deleted file mode 100644
index 365353e734..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueMBeanTest.java
+++ /dev/null
@@ -1,456 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.queue;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.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.abstraction.MessagePublishInfo;
-import org.apache.qpid.framing.abstraction.ContentChunk;
-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.mina.common.ByteBuffer;
-
-import javax.management.JMException;
-
-import java.util.ArrayList;
-
-/**
- * Test class to test AMQQueueMBean attribtues and operations
- */
-public class AMQQueueMBeanTest extends InternalBrokerBaseCase
-{
- private static long MESSAGE_SIZE = 1000;
- private AMQQueueMBean _queueMBean;
- private static final SubscriptionFactoryImpl SUBSCRIPTION_FACTORY = SubscriptionFactoryImpl.INSTANCE;
-
- public void testMessageCountTransient() throws Exception
- {
- int messageCount = 10;
- sendMessages(messageCount, false);
- assertTrue(_queueMBean.getMessageCount() == messageCount);
- assertTrue(_queueMBean.getReceivedMessageCount() == messageCount);
- long queueDepth = (messageCount * MESSAGE_SIZE);
- assertTrue(_queueMBean.getQueueDepth() == queueDepth);
-
- _queueMBean.deleteMessageFromTop();
- assertTrue(_queueMBean.getMessageCount() == (messageCount - 1));
- assertTrue(_queueMBean.getReceivedMessageCount() == messageCount);
-
- _queueMBean.clearQueue();
- assertEquals(0,(int)_queueMBean.getMessageCount());
- assertTrue(_queueMBean.getReceivedMessageCount() == messageCount);
-
- //Ensure that the data has been removed from the Store
- verifyBrokerState();
- }
-
- public void testMessageCountPersistent() throws Exception
- {
- int messageCount = 10;
- sendMessages(messageCount, true);
- assertEquals("", messageCount, _queueMBean.getMessageCount().intValue());
- assertTrue(_queueMBean.getReceivedMessageCount() == messageCount);
- long queueDepth = (messageCount * MESSAGE_SIZE);
- assertTrue(_queueMBean.getQueueDepth() == queueDepth);
-
- _queueMBean.deleteMessageFromTop();
- assertTrue(_queueMBean.getMessageCount() == (messageCount - 1));
- assertTrue(_queueMBean.getReceivedMessageCount() == messageCount);
-
- _queueMBean.clearQueue();
- assertTrue(_queueMBean.getMessageCount() == 0);
- assertTrue(_queueMBean.getReceivedMessageCount() == messageCount);
-
- //Ensure that the data has been removed from the Store
- verifyBrokerState();
- }
-
- public void testDeleteMessages() throws Exception
- {
- int messageCount = 10;
- sendMessages(messageCount, true);
- assertEquals("", messageCount, _queueMBean.getMessageCount().intValue());
- assertTrue(_queueMBean.getReceivedMessageCount() == messageCount);
- long queueDepth = (messageCount * MESSAGE_SIZE);
- assertTrue(_queueMBean.getQueueDepth() == queueDepth);
-
- //delete first message
- _queueMBean.deleteMessages(1L,1L);
- assertTrue(_queueMBean.getMessageCount() == (messageCount - 1));
- assertTrue(_queueMBean.getReceivedMessageCount() == messageCount);
- try
- {
- _queueMBean.viewMessageContent(1L);
- fail("Message should no longer be on the queue");
- }
- catch(Exception e)
- {
-
- }
-
- //delete last message, leaving 2nd to 9th
- _queueMBean.deleteMessages(10L,10L);
- assertTrue(_queueMBean.getMessageCount() == (messageCount - 2));
- assertTrue(_queueMBean.getReceivedMessageCount() == messageCount);
- try
- {
- _queueMBean.viewMessageContent(10L);
- fail("Message should no longer be on the queue");
- }
- catch(Exception e)
- {
-
- }
-
- //delete remaining messages, leaving none
- _queueMBean.deleteMessages(2L,9L);
- assertTrue(_queueMBean.getMessageCount() == (0));
- assertTrue(_queueMBean.getReceivedMessageCount() == messageCount);
-
- //Ensure that the data has been removed from the Store
- verifyBrokerState();
- }
-
- // todo: collect to a general testing class -duplicated from Systest/MessageReturntest
- private void verifyBrokerState()
- {
-
- TestableMemoryMessageStore store = (TestableMemoryMessageStore) getVirtualHost().getMessageStore();
-
- // Unlike MessageReturnTest there is no need for a delay as there this thread does the clean up.
-
- assertEquals("Store should have no messages:" + store.getMessageCount(), 0, store.getMessageCount());
- }
-
- public void testConsumerCount() throws AMQException
- {
-
- assertTrue(getQueue().getActiveConsumerCount() == 0);
- assertTrue(_queueMBean.getActiveConsumerCount() == 0);
-
-
- InternalTestProtocolSession protocolSession = new InternalTestProtocolSession(getVirtualHost());
-
- AMQChannel channel = new AMQChannel(protocolSession, 1, getMessageStore());
- protocolSession.addChannel(channel);
-
- Subscription subscription =
- SUBSCRIPTION_FACTORY.createSubscription(channel.getChannelId(), protocolSession, new AMQShortString("test"), false, null, false, channel.getCreditManager());
-
- getQueue().registerSubscription(subscription, false);
- assertEquals(1,(int)_queueMBean.getActiveConsumerCount());
-
-
- SubscriptionFactory subscriptionFactory = SUBSCRIPTION_FACTORY;
- Subscription s1 = subscriptionFactory.createSubscription(channel.getChannelId(),
- protocolSession,
- new AMQShortString("S1"),
- false,
- null,
- true,
- channel.getCreditManager());
-
- Subscription s2 = subscriptionFactory.createSubscription(channel.getChannelId(),
- protocolSession,
- new AMQShortString("S2"),
- false,
- null,
- true,
- channel.getCreditManager());
- getQueue().registerSubscription(s1,false);
- getQueue().registerSubscription(s2,false);
- assertTrue(_queueMBean.getActiveConsumerCount() == 3);
- assertTrue(_queueMBean.getConsumerCount() == 3);
-
- s1.close();
- assertEquals(2, (int) _queueMBean.getActiveConsumerCount());
- assertTrue(_queueMBean.getConsumerCount() == 3);
- }
-
- public void testGeneralProperties() throws Exception
- {
- long maxQueueDepth = 1000; // in bytes
- _queueMBean.setMaximumMessageCount(50000l);
- _queueMBean.setMaximumMessageSize(2000l);
- _queueMBean.setMaximumQueueDepth(maxQueueDepth);
-
- assertEquals("Max MessageCount not set",50000,_queueMBean.getMaximumMessageCount().longValue());
- assertEquals("Max MessageSize not set",2000, _queueMBean.getMaximumMessageSize().longValue());
- assertEquals("Max QueueDepth not set",maxQueueDepth, _queueMBean.getMaximumQueueDepth().longValue());
-
- assertEquals("Queue Name does not match", new AMQShortString(getName()), _queueMBean.getName());
- assertFalse("AutoDelete should not be set.",_queueMBean.isAutoDelete());
- assertFalse("Queue should not be durable.",_queueMBean.isDurable());
-
- //set+get exclusivity using the mbean, and also verify it is actually updated in the queue
- _queueMBean.setExclusive(true);
- assertTrue("Exclusive property should be true.",_queueMBean.isExclusive());
- assertTrue("Exclusive property should be true.", getQueue().isExclusive());
- _queueMBean.setExclusive(false);
- assertFalse("Exclusive property should be false.",_queueMBean.isExclusive());
- assertFalse("Exclusive property should be false.", getQueue().isExclusive());
- }
-
- public void testExceptions() throws Exception
- {
- try
- {
- _queueMBean.viewMessages(0L, 3L);
- fail();
- }
- catch (JMException ex)
- {
-
- }
-
- try
- {
- _queueMBean.viewMessages(2L, 1L);
- fail();
- }
- catch (JMException ex)
- {
-
- }
-
- try
- {
- _queueMBean.viewMessages(-1L, 1L);
- fail();
- }
- catch (JMException ex)
- {
-
- }
-
- try
- {
- long end = Integer.MAX_VALUE;
- end+=2;
- _queueMBean.viewMessages(1L, end);
- fail("Expected Exception due to oversized(> 2^31) message range");
- }
- catch (JMException ex)
- {
-
- }
-
- IncomingMessage msg = message(false, false);
- getQueue().clearQueue();
- ArrayList<AMQQueue> qs = new ArrayList<AMQQueue>();
- qs.add(getQueue());
- msg.enqueue(qs);
- MessageMetaData mmd = msg.headersReceived();
- msg.setStoredMessage(getMessageStore().addMessage(mmd));
- long id = msg.getMessageNumber();
-
- msg.addContentBodyFrame(new ContentChunk()
- {
- ByteBuffer _data = ByteBuffer.allocate((int)MESSAGE_SIZE);
-
- {
- _data.limit((int)MESSAGE_SIZE);
- }
-
- public int getSize()
- {
- return (int) MESSAGE_SIZE;
- }
-
- public ByteBuffer getData()
- {
- return _data;
- }
-
- public void reduceToFit()
- {
-
- }
- });
-
- AMQMessage m = new AMQMessage(msg.getStoredMessage());
- for(BaseQueue q : msg.getDestinationQueues())
- {
- q.enqueue(m);
- }
-// _queue.process(_storeContext, new QueueEntry(_queue, msg), false);
- _queueMBean.viewMessageContent(id);
- try
- {
- _queueMBean.viewMessageContent(id + 1);
- fail();
- }
- catch (JMException ex)
- {
-
- }
- }
-
- public void testFlowControlProperties() throws Exception
- {
- assertTrue(_queueMBean.getCapacity() == 0);
- assertTrue(_queueMBean.getFlowResumeCapacity() == 0);
- assertFalse(_queueMBean.isFlowOverfull());
-
- //capacity currently 0, try setting FlowResumeCapacity above this
- try
- {
- _queueMBean.setFlowResumeCapacity(1L);
- fail("Should have failed to allow setting FlowResumeCapacity above Capacity");
- }
- catch (IllegalArgumentException ex)
- {
- //expected exception
- assertTrue(_queueMBean.getFlowResumeCapacity() == 0);
- }
-
- //add a message to the queue
- sendMessages(1, true);
-
- //(FlowResume)Capacity currently 0, set both to 2
- _queueMBean.setCapacity(2L);
- assertTrue(_queueMBean.getCapacity() == 2L);
- _queueMBean.setFlowResumeCapacity(2L);
- assertTrue(_queueMBean.getFlowResumeCapacity() == 2L);
-
- //Try setting Capacity below FlowResumeCapacity
- try
- {
- _queueMBean.setCapacity(1L);
- fail("Should have failed to allow setting Capacity below FlowResumeCapacity");
- }
- catch (IllegalArgumentException ex)
- {
- //expected exception
- assertTrue(_queueMBean.getCapacity() == 2);
- }
-
- //create a channel and use it to exercise the capacity check mechanism
- AMQChannel channel = new AMQChannel(getSession(), 1, getMessageStore());
- getQueue().checkCapacity(channel);
-
- assertTrue(_queueMBean.isFlowOverfull());
- assertTrue(channel.getBlocking());
-
- //set FlowResumeCapacity to MESSAGE_SIZE and check queue is now underfull and channel unblocked
- _queueMBean.setCapacity(MESSAGE_SIZE);//must increase capacity too
- _queueMBean.setFlowResumeCapacity(MESSAGE_SIZE);
-
- assertFalse(_queueMBean.isFlowOverfull());
- assertFalse(channel.getBlocking());
- }
-
- private IncomingMessage message(final boolean immediate, boolean persistent) throws AMQException
- {
- MessagePublishInfo publish = new MessagePublishInfo()
- {
-
- public AMQShortString getExchange()
- {
- return null;
- }
-
- public void setExchange(AMQShortString exchange)
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean isImmediate()
- {
- return immediate;
- }
-
- public boolean isMandatory()
- {
- return false;
- }
-
- public AMQShortString getRoutingKey()
- {
- return null;
- }
- };
-
- ContentHeaderBody contentHeaderBody = new ContentHeaderBody();
- contentHeaderBody.bodySize = MESSAGE_SIZE; // in bytes
- contentHeaderBody.setProperties(new BasicContentHeaderProperties());
- ((BasicContentHeaderProperties) contentHeaderBody.getProperties()).setDeliveryMode((byte) (persistent ? 2 : 1));
- IncomingMessage msg = new IncomingMessage(publish);
- msg.setContentHeaderBody(contentHeaderBody);
- return msg;
-
- }
-
- @Override
- public void setUp() throws Exception
- {
- super.setUp();
-
- _queueMBean = new AMQQueueMBean(getQueue());
- }
-
- public void tearDown()
- {
- ApplicationRegistry.remove();
- }
-
- private void sendMessages(int messageCount, boolean persistent) throws AMQException
- {
- for (int i = 0; i < messageCount; i++)
- {
- IncomingMessage currentMessage = message(false, persistent);
- ArrayList<AMQQueue> qs = new ArrayList<AMQQueue>();
- qs.add(getQueue());
- currentMessage.enqueue(qs);
-
- // route header
- MessageMetaData mmd = currentMessage.headersReceived();
- currentMessage.setStoredMessage(getMessageStore().addMessage(mmd));
-
- // Add the body so we have somthing to test later
- currentMessage.addContentBodyFrame(
- getSession().getMethodRegistry()
- .getProtocolVersionMethodConverter()
- .convertToContentChunk(
- new ContentBody(ByteBuffer.allocate((int) MESSAGE_SIZE),
- MESSAGE_SIZE)));
-
- AMQMessage m = new AMQMessage(currentMessage.getStoredMessage());
- for(BaseQueue q : currentMessage.getDestinationQueues())
- {
- q.enqueue(m);
- }
-
-
- }
- }
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/queue/AckTest.java b/java/broker/src/test/java/org/apache/qpid/server/queue/AckTest.java
deleted file mode 100644
index 0f5374b3e5..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/queue/AckTest.java
+++ /dev/null
@@ -1,427 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.queue;
-
-import junit.framework.TestCase;
-import org.apache.log4j.Logger;
-import org.apache.qpid.AMQException;
-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.message.AMQMessage;
-import org.apache.qpid.server.message.MessageMetaData;
-import org.apache.qpid.server.txn.ServerTransaction;
-import org.apache.qpid.server.txn.AutoCommitTransaction;
-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;
-
-/**
- * Tests that acknowledgements are handled correctly.
- */
-public class AckTest extends InternalBrokerBaseCase
-{
- private static final Logger _log = Logger.getLogger(AckTest.class);
-
- private Subscription _subscription;
-
- private AMQProtocolSession _protocolSession;
-
- private TestMemoryMessageStore _messageStore;
-
- private AMQChannel _channel;
-
- private AMQQueue _queue;
-
- private static final AMQShortString DEFAULT_CONSUMER_TAG = new AMQShortString("conTag");
- private VirtualHost _virtualHost;
-
- @Override
- public void setUp() throws Exception
- {
- super.setUp();
- _virtualHost = ApplicationRegistry.getInstance().getVirtualHostRegistry().getVirtualHost("test");
- _messageStore = new TestMemoryMessageStore();
- _protocolSession = new InternalTestProtocolSession(_virtualHost);
- _channel = new AMQChannel(_protocolSession,5, _messageStore /*dont need exchange registry*/);
-
- _protocolSession.addChannel(_channel);
-
- _queue = AMQQueueFactory.createAMQQueueImpl(new AMQShortString("myQ"), false, new AMQShortString("guest"), true, false,
- _virtualHost, null);
- }
-
- private void publishMessages(int count) throws AMQException
- {
- publishMessages(count, false);
- }
-
- private void publishMessages(int count, boolean persistent) throws AMQException
- {
- _queue.registerSubscription(_subscription,false);
- for (int i = 1; i <= count; i++)
- {
- // AMQP version change: Hardwire the version to 0-8 (major=8, minor=0)
- // TODO: Establish some way to determine the version for the test.
- MessagePublishInfo publishBody = new MessagePublishInfo()
- {
-
- public AMQShortString getExchange()
- {
- return new AMQShortString("someExchange");
- }
-
- public void setExchange(AMQShortString exchange)
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean isImmediate()
- {
- return false;
- }
-
- public boolean isMandatory()
- {
- return false;
- }
-
- public AMQShortString getRoutingKey()
- {
- return new AMQShortString("rk");
- }
- };
- final IncomingMessage msg = new IncomingMessage(publishBody);
- //IncomingMessage msg2 = null;
- BasicContentHeaderProperties b = new BasicContentHeaderProperties();
- ContentHeaderBody cb = new ContentHeaderBody();
- cb.setProperties(b);
-
- if (persistent)
- {
- //This is DeliveryMode.PERSISTENT
- b.setDeliveryMode((byte) 2);
- }
-
- msg.setContentHeaderBody(cb);
-
- // we increment the reference here since we are not delivering the messaging to any queues, which is where
- // the reference is normally incremented. The test is easier to construct if we have direct access to the
- // subscription
- ArrayList<AMQQueue> qs = new ArrayList<AMQQueue>();
- qs.add(_queue);
- msg.enqueue(qs);
- MessageMetaData mmd = msg.headersReceived();
- msg.setStoredMessage(_messageStore.addMessage(mmd));
- if(msg.allContentReceived())
- {
- ServerTransaction txn = new AutoCommitTransaction(_messageStore);
- txn.enqueue(_queue, msg, new ServerTransaction.Action() {
- public void postCommit()
- {
- try
- {
- _queue.enqueue(new AMQMessage(msg.getStoredMessage()));
- }
- catch (AMQException e)
- {
- throw new RuntimeException(e);
- }
- }
-
- public void onRollback()
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
- });
-
- }
- // we manually send the message to the subscription
- //_subscription.send(new QueueEntry(_queue,msg), _queue);
- }
- }
-
- /**
- * Tests that the acknowledgements are correctly associated with a channel and
- * order is preserved when acks are enabled
- */
- public void testAckChannelAssociationTest() throws AMQException
- {
- _subscription = SubscriptionFactoryImpl.INSTANCE.createSubscription(5, _protocolSession, DEFAULT_CONSUMER_TAG, true, null, false, new LimitlessCreditManager());
- final int msgCount = 10;
- publishMessages(msgCount, true);
-
- UnacknowledgedMessageMap map = _channel.getUnacknowledgedMessageMap();
- assertEquals("",msgCount,map.size());
-
- Set<Long> deliveryTagSet = map.getDeliveryTags();
- int i = 1;
- for (long deliveryTag : deliveryTagSet)
- {
- assertTrue(deliveryTag == i);
- i++;
- QueueEntry unackedMsg = map.get(deliveryTag);
- assertTrue(unackedMsg.getQueue() == _queue);
- }
-
- }
-
- /**
- * Tests that in no-ack mode no messages are retained
- */
- public void testNoAckMode() throws AMQException
- {
- // false arg means no acks expected
- _subscription = SubscriptionFactoryImpl.INSTANCE.createSubscription(5, _protocolSession, DEFAULT_CONSUMER_TAG, false, null, false, new LimitlessCreditManager());
- final int msgCount = 10;
- publishMessages(msgCount);
-
- UnacknowledgedMessageMap map = _channel.getUnacknowledgedMessageMap();
- assertTrue(map.size() == 0);
- assertTrue(_messageStore.getMessageCount() == 0);
-
-
- }
-
- /**
- * Tests that in no-ack mode no messages are retained
- */
- public void testPersistentNoAckMode() throws AMQException
- {
- // false arg means no acks expected
- _subscription = SubscriptionFactoryImpl.INSTANCE.createSubscription(5, _protocolSession, DEFAULT_CONSUMER_TAG, false,null,false, new LimitlessCreditManager());
- final int msgCount = 10;
- publishMessages(msgCount, true);
-
- UnacknowledgedMessageMap map = _channel.getUnacknowledgedMessageMap();
- assertTrue(map.size() == 0);
- assertTrue(_messageStore.getMessageCount() == 0);
-
-
- }
-
- /**
- * Tests that a single acknowledgement is handled correctly (i.e multiple flag not
- * set case)
- */
- public void testSingleAckReceivedTest() throws AMQException
- {
- _subscription = SubscriptionFactoryImpl.INSTANCE.createSubscription(5, _protocolSession, DEFAULT_CONSUMER_TAG, true,null,false, new LimitlessCreditManager());
- final int msgCount = 10;
- publishMessages(msgCount);
-
- _channel.acknowledgeMessage(5, false);
- UnacknowledgedMessageMap map = _channel.getUnacknowledgedMessageMap();
- assertTrue(map.size() == msgCount - 1);
-
- Set<Long> deliveryTagSet = map.getDeliveryTags();
- int i = 1;
- for (long deliveryTag : deliveryTagSet)
- {
- assertTrue(deliveryTag == i);
- QueueEntry unackedMsg = map.get(deliveryTag);
- assertTrue(unackedMsg.getQueue() == _queue);
- // 5 is the delivery tag of the message that *should* be removed
- if (++i == 5)
- {
- ++i;
- }
- }
- }
-
- /**
- * Tests that a single acknowledgement is handled correctly (i.e multiple flag not
- * set case)
- */
- public void testMultiAckReceivedTest() throws AMQException
- {
- _subscription = SubscriptionFactoryImpl.INSTANCE.createSubscription(5, _protocolSession, DEFAULT_CONSUMER_TAG, true,null,false, new LimitlessCreditManager());
- final int msgCount = 10;
- publishMessages(msgCount);
-
- _channel.acknowledgeMessage(5, true);
- UnacknowledgedMessageMap map = _channel.getUnacknowledgedMessageMap();
- assertTrue(map.size() == 5);
-
- Set<Long> deliveryTagSet = map.getDeliveryTags();
- int i = 1;
- for (long deliveryTag : deliveryTagSet)
- {
- assertTrue(deliveryTag == i + 5);
- QueueEntry unackedMsg = map.get(deliveryTag);
- assertTrue(unackedMsg.getQueue() == _queue);
- ++i;
- }
- }
-
- /**
- * Tests that a multiple acknowledgement is handled correctly. When ack'ing all pending msgs.
- */
- public void testMultiAckAllReceivedTest() throws AMQException
- {
- _subscription = SubscriptionFactoryImpl.INSTANCE.createSubscription(5, _protocolSession, DEFAULT_CONSUMER_TAG, true,null,false, new LimitlessCreditManager());
- final int msgCount = 10;
- publishMessages(msgCount);
-
- _channel.acknowledgeMessage(0, true);
- UnacknowledgedMessageMap map = _channel.getUnacknowledgedMessageMap();
- assertTrue(map.size() == 0);
-
- Set<Long> deliveryTagSet = map.getDeliveryTags();
- int i = 1;
- for (long deliveryTag : deliveryTagSet)
- {
- assertTrue(deliveryTag == i + 5);
- QueueEntry unackedMsg = map.get(deliveryTag);
- assertTrue(unackedMsg.getQueue() == _queue);
- ++i;
- }
- }
-
- /**
- * A regression fixing QPID-1136 showed this up
- *
- * @throws Exception
- */
- public void testMessageDequeueRestoresCreditTest() throws Exception
- {
- // Send 10 messages
- Pre0_10CreditManager creditManager = new Pre0_10CreditManager(0l, 1);
-
- _subscription = SubscriptionFactoryImpl.INSTANCE.createSubscription(5, _protocolSession,
- DEFAULT_CONSUMER_TAG, true, null, false, creditManager);
- final int msgCount = 1;
- publishMessages(msgCount);
-
- _queue.deliverAsync(_subscription);
-
- _channel.acknowledgeMessage(1, false);
-
- // Check credit available
- assertTrue("No credit available", creditManager.hasCredit());
-
- }
-
-
-/*
- public void testPrefetchHighLow() throws AMQException
- {
- int lowMark = 5;
- int highMark = 10;
-
- _subscription = SubscriptionFactoryImpl.INSTANCE.createSubscription(5, _protocolSession, DEFAULT_CONSUMER_TAG, true,null,false, new LimitlessCreditManager());
- _channel.setPrefetchLowMarkCount(lowMark);
- _channel.setPrefetchHighMarkCount(highMark);
-
- assertTrue(_channel.getPrefetchLowMarkCount() == lowMark);
- assertTrue(_channel.getPrefetchHighMarkCount() == highMark);
-
- publishMessages(highMark);
-
- // at this point we should have sent out only highMark messages
- // which have not bee received so will be queued up in the channel
- // which should be suspended
- assertTrue(_subscription.isSuspended());
- UnacknowledgedMessageMap map = _channel.getUnacknowledgedMessageMap();
- assertTrue(map.size() == highMark);
-
- //acknowledge messages so we are just above lowMark
- _channel.acknowledgeMessage(lowMark - 1, true);
-
- //we should still be suspended
- assertTrue(_subscription.isSuspended());
- assertTrue(map.size() == lowMark + 1);
-
- //acknowledge one more message
- _channel.acknowledgeMessage(lowMark, true);
-
- //and suspension should be lifted
- assertTrue(!_subscription.isSuspended());
-
- //pubilsh more msgs so we are just below the limit
- publishMessages(lowMark - 1);
-
- //we should not be suspended
- assertTrue(!_subscription.isSuspended());
-
- //acknowledge all messages
- _channel.acknowledgeMessage(0, true);
- try
- {
- Thread.sleep(3000);
- }
- catch (InterruptedException e)
- {
- _log.error("Error: " + e, e);
- }
- //map will be empty
- assertTrue(map.size() == 0);
- }
-
-*/
-/*
- public void testPrefetch() throws AMQException
- {
- _subscription = SubscriptionFactoryImpl.INSTANCE.createSubscription(5, _protocolSession, DEFAULT_CONSUMER_TAG, true,null,false, new LimitlessCreditManager());
- _channel.setMessageCredit(5);
-
- assertTrue(_channel.getPrefetchCount() == 5);
-
- final int msgCount = 5;
- publishMessages(msgCount);
-
- // at this point we should have sent out only 5 messages with a further 5 queued
- // up in the channel which should now be suspended
- assertTrue(_subscription.isSuspended());
- UnacknowledgedMessageMap map = _channel.getUnacknowledgedMessageMap();
- assertTrue(map.size() == 5);
- _channel.acknowledgeMessage(5, true);
- assertTrue(!_subscription.isSuspended());
- try
- {
- Thread.sleep(3000);
- }
- catch (InterruptedException e)
- {
- _log.error("Error: " + e, e);
- }
- assertTrue(map.size() == 0);
- }
-
-*/
- public static junit.framework.Test suite()
- {
- return new junit.framework.TestSuite(AckTest.class);
- }
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/queue/MockAMQMessage.java b/java/broker/src/test/java/org/apache/qpid/server/queue/MockAMQMessage.java
deleted file mode 100644
index 7000df157e..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/queue/MockAMQMessage.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.queue;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.server.message.AMQMessage;
-
-public class MockAMQMessage extends AMQMessage
-{
- public MockAMQMessage(long messageId)
- throws AMQException
- {
- super(new MockStoredMessage(messageId));
- }
-
-
-
-
- @Override
- public long getSize()
- {
- return 0l;
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/queue/MockAMQQueue.java b/java/broker/src/test/java/org/apache/qpid/server/queue/MockAMQQueue.java
deleted file mode 100644
index 888a16053c..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/queue/MockAMQQueue.java
+++ /dev/null
@@ -1,614 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.queue;
-
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.server.configuration.*;
-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.PrincipalHolder;
-import org.apache.qpid.server.AMQChannel;
-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 java.util.List;
-import java.util.Set;
-import java.util.Map;
-import java.util.UUID;
-import java.util.concurrent.CopyOnWriteArrayList;
-
-public class MockAMQQueue implements AMQQueue
-{
- private boolean _deleted = false;
- private AMQShortString _name;
- private VirtualHost _virtualhost;
-
- private PrincipalHolder _principalHolder;
-
- private AMQSessionModel _exclusiveOwner;
- private AMQShortString _owner;
- private List<Binding> _bindings = new CopyOnWriteArrayList<Binding>();
- private boolean _autoDelete;
-
- public MockAMQQueue(String name)
- {
- _name = new AMQShortString(name);
- }
-
- public boolean getDeleteOnNoConsumers()
- {
- return false;
- }
-
- public void setDeleteOnNoConsumers(boolean b)
- {
- }
-
- public void addBinding(final Binding binding)
- {
- _bindings.add(binding);
- }
-
- public void removeBinding(final Binding binding)
- {
- _bindings.remove(binding);
- }
-
- public List<Binding> getBindings()
- {
- return _bindings;
- }
-
- public int getBindingCount()
- {
- return 0;
- }
-
- public LogSubject getLogSubject()
- {
- return new LogSubject()
- {
- public String toLogString()
- {
- return "[MockAMQQueue]";
- }
-
- };
- }
-
- public ConfigStore getConfigStore()
- {
- return getVirtualHost().getConfigStore();
- }
-
- public long getMessageDequeueCount()
- {
- return 0;
- }
-
- public long getTotalEnqueueSize()
- {
- return 0;
- }
-
- public long getTotalDequeueSize()
- {
- return 0;
- }
-
- public int getBindingCountHigh()
- {
- return 0;
- }
-
- public long getPersistentByteEnqueues()
- {
- return 0;
- }
-
- public long getPersistentByteDequeues()
- {
- return 0;
- }
-
- public long getPersistentMsgEnqueues()
- {
- return 0;
- }
-
- public long getPersistentMsgDequeues()
- {
- return 0;
- }
-
- public void purge(final long request)
- {
-
- }
-
- public long getCreateTime()
- {
- return 0;
- }
-
- public AMQShortString getNameShortString()
- {
- return _name;
- }
-
- public void setNoLocal(boolean b)
- {
-
- }
-
- public UUID getId()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public QueueConfigType getConfigType()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public ConfiguredObject getParent()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean isDurable()
- {
- return false; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean isAutoDelete()
- {
- return _autoDelete;
- }
-
- public void setAutoDelete(boolean autodelete)
- {
- _autoDelete = autodelete;
- }
-
-
- public AMQShortString getOwner()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void setVirtualHost(VirtualHost virtualhost)
- {
- _virtualhost = virtualhost;
- }
-
- public VirtualHost getVirtualHost()
- {
- return _virtualhost;
- }
-
- public String getName()
- {
- return _name.asString();
- }
-
- public void registerSubscription(Subscription subscription, boolean exclusive) throws AMQException
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void unregisterSubscription(Subscription subscription) throws AMQException
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public int getConsumerCount()
- {
- return 0; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public int getActiveConsumerCount()
- {
- return 0; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean hasExclusiveSubscriber()
- {
- return false;
- }
-
- public boolean isUnused()
- {
- return false; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean isEmpty()
- {
- return false; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public int getMessageCount()
- {
- return 0; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public int getUndeliveredMessageCount()
- {
- return 0; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public long getQueueDepth()
- {
- return 0; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public long getReceivedMessageCount()
- {
- return 0; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public long getOldestMessageArrivalTime()
- {
- return 0; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean isDeleted()
- {
- return _deleted;
- }
-
- public int delete() throws AMQException
- {
- _deleted = true;
- return getMessageCount();
- }
-
- public void enqueue(ServerMessage message) throws AMQException
- {
- }
-
- public void enqueue(ServerMessage message, PostEnqueueAction action) throws AMQException
- {
- }
-
-
- public void requeue(QueueEntry entry)
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void requeue(QueueEntryImpl storeContext, Subscription subscription)
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void dequeue(QueueEntry entry, Subscription sub)
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean resend(QueueEntry entry, Subscription subscription) throws AMQException
- {
- return false; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void addQueueDeleteTask(Task task)
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void removeQueueDeleteTask(final Task task)
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public List<QueueEntry> getMessagesOnTheQueue()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public List<QueueEntry> getMessagesOnTheQueue(long fromMessageId, long toMessageId)
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public List<Long> getMessagesOnTheQueue(int num)
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public List<Long> getMessagesOnTheQueue(int num, int offest)
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public QueueEntry getMessageOnTheQueue(long messageId)
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public List<QueueEntry> getMessagesRangeOnTheQueue(long fromPosition, long toPosition)
- {
- return null;
- }
-
- public void moveMessagesToAnotherQueue(long fromMessageId, long toMessageId, String queueName, ServerTransaction storeContext)
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void copyMessagesToAnotherQueue(long fromMessageId, long toMessageId, String queueName, ServerTransaction storeContext)
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void removeMessagesFromQueue(long fromMessageId, long toMessageId)
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public long getMaximumMessageSize()
- {
- return 0; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void setMaximumMessageSize(long value)
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public long getMaximumMessageCount()
- {
- return 0; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void setMaximumMessageCount(long value)
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public long getMaximumQueueDepth()
- {
- return 0; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void setMaximumQueueDepth(long value)
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public long getMaximumMessageAge()
- {
- return 0; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void setMaximumMessageAge(long maximumMessageAge)
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean getBlockOnQueueFull()
- {
- return false;
- }
-
- public void setBlockOnQueueFull(boolean block)
- {
- }
-
- public long getMinimumAlertRepeatGap()
- {
- return 0; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void deleteMessageFromTop()
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public long clearQueue()
- {
- return 0; //To change body of implemented methods use File | Settings | File Templates.
- }
-
-
- public void checkMessageStatus() throws AMQException
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public Set<NotificationCheck> getNotificationChecks()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void flushSubscription(Subscription sub) throws AMQException
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void deliverAsync(Subscription sub)
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void deliverAsync()
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void stop()
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean isExclusive()
- {
- return false; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public Exchange getAlternateExchange()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void setAlternateExchange(Exchange exchange)
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public Map<String, Object> getArguments()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void checkCapacity(AMQChannel channel)
- {
- }
-
- public ManagedObject getManagedObject()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public int compareTo(AMQQueue o)
- {
- return 0; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void setMinimumAlertRepeatGap(long value)
- {
-
- }
-
- public long getCapacity()
- {
- return 0; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void setCapacity(long capacity)
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public long getFlowResumeCapacity()
- {
- return 0; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void setFlowResumeCapacity(long flowResumeCapacity)
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void configure(ConfigurationPlugin config)
- {
-
- }
-
- public ConfigurationPlugin getConfiguration()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public PrincipalHolder getPrincipalHolder()
- {
- return _principalHolder;
- }
-
- public void setPrincipalHolder(PrincipalHolder principalHolder)
- {
- _principalHolder = principalHolder;
- }
-
- public AMQSessionModel getExclusiveOwningSession()
- {
- return _exclusiveOwner;
- }
-
- public void setExclusiveOwningSession(AMQSessionModel exclusiveOwner)
- {
- _exclusiveOwner = exclusiveOwner;
- }
-
-
- public String getResourceName()
- {
- return _name.toString();
- }
-
- public boolean isOverfull()
- {
- return false;
- }
-
- public int getConsumerCountHigh()
- {
- return 0;
- }
-
- public long getByteTxnEnqueues()
- {
- return 0;
- }
-
- public long getMsgTxnEnqueues()
- {
- return 0;
- }
-
- public long getByteTxnDequeues()
- {
- return 0;
- }
-
- public long getMsgTxnDequeues()
- {
- return 0;
- }
-
- public void decrementUnackedMsgCount()
- {
-
- }
-
- public long getUnackedMessageCount()
- {
- return 0;
- }
-
- public long getUnackedMessageCountHigh()
- {
- return 0;
- }
-
- public void setExclusive(boolean exclusive)
- {
-
- }
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/queue/MockMessagePublishInfo.java b/java/broker/src/test/java/org/apache/qpid/server/queue/MockMessagePublishInfo.java
deleted file mode 100644
index 5a5ffaa14d..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/queue/MockMessagePublishInfo.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.queue;
-
-import org.apache.qpid.framing.abstraction.MessagePublishInfo;
-import org.apache.qpid.framing.AMQShortString;
-
-public class MockMessagePublishInfo implements MessagePublishInfo
-{
- public AMQShortString getExchange()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void setExchange(AMQShortString exchange)
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean isImmediate()
- {
- return false; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean isMandatory()
- {
- return false; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public AMQShortString getRoutingKey()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/queue/MockQueueEntry.java b/java/broker/src/test/java/org/apache/qpid/server/queue/MockQueueEntry.java
deleted file mode 100644
index 5bdbe2c68e..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/queue/MockQueueEntry.java
+++ /dev/null
@@ -1,234 +0,0 @@
-/*
-*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.queue;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.server.subscription.Subscription;
-import org.apache.qpid.server.message.AMQMessageHeader;
-import org.apache.qpid.server.message.AMQMessage;
-import org.apache.qpid.server.message.ServerMessage;
-
-public class MockQueueEntry implements QueueEntry
-{
-
- private AMQMessage _message;
-
- public boolean acquire()
- {
- return false;
- }
-
- public boolean acquire(Subscription sub)
- {
- return false;
- }
-
- public boolean acquiredBySubscription()
- {
- return false;
- }
-
- public boolean isAcquiredBy(Subscription subscription)
- {
- return false;
- }
-
- public void addStateChangeListener(StateChangeListener listener)
- {
-
- }
-
- public boolean delete()
- {
- return false;
- }
-
- public void dequeue()
- {
-
- }
-
- public void discard()
- {
-
- }
-
- public void routeToAlternate()
- {
-
- }
-
- public void dispose()
- {
-
- }
-
- public boolean expired() throws AMQException
- {
- return false;
- }
-
- public boolean isAvailable()
- {
- return false;
- }
-
- public Subscription getDeliveredSubscription()
- {
- return null;
- }
-
- public boolean getDeliveredToConsumer()
- {
- return false;
- }
-
- public ServerMessage getMessage()
- {
- return _message;
- }
-
- public AMQQueue getQueue()
- {
- return null;
- }
-
- public long getSize()
- {
- return 0;
- }
-
- public boolean immediateAndNotDelivered()
- {
- return false;
- }
-
- public boolean isAcquired()
- {
- return false;
- }
-
- public boolean isDeleted()
- {
- return false;
- }
-
-
- public boolean isQueueDeleted()
- {
-
- return false;
- }
-
-
- public boolean isRejectedBy(Subscription subscription)
- {
-
- return false;
- }
-
-
- public void reject()
- {
-
-
- }
-
-
- public void reject(Subscription subscription)
- {
-
-
- }
-
-
- public void release()
- {
-
-
- }
-
- public boolean releaseButRetain()
- {
- return false;
- }
-
-
- public boolean removeStateChangeListener(StateChangeListener listener)
- {
-
- return false;
- }
-
-
- public void requeue()
- {
-
-
- }
-
- public void requeue(Subscription subscription)
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
-
- public void setDeliveredToSubscription()
- {
-
-
- }
-
-
- public void setRedelivered()
- {
-
-
- }
-
- public AMQMessageHeader getMessageHeader()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean isPersistent()
- {
- return false; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean isRedelivered()
- {
- return false;
- }
-
-
- public int compareTo(QueueEntry o)
- {
-
- return 0;
- }
-
- public void setMessage(AMQMessage msg)
- {
- _message = msg;
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/queue/MockStoredMessage.java b/java/broker/src/test/java/org/apache/qpid/server/queue/MockStoredMessage.java
deleted file mode 100755
index 7dc491de4d..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/queue/MockStoredMessage.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.server.queue;
-
-import org.apache.qpid.server.store.MessageStore;
-import org.apache.qpid.server.store.TransactionLog;
-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;
-
-public class MockStoredMessage implements StoredMessage<MessageMetaData>
-{
- private long _messageId;
- private MessageMetaData _metaData;
- private final ByteBuffer _content;
-
-
- public MockStoredMessage(long messageId)
- {
- this(messageId, new MockMessagePublishInfo(), new ContentHeaderBody(new BasicContentHeaderProperties(), 60));
- }
-
- public MockStoredMessage(long messageId, MessagePublishInfo info, ContentHeaderBody chb)
- {
- _messageId = messageId;
- _metaData = new MessageMetaData(info, chb, 0);
- _content = ByteBuffer.allocate(_metaData.getContentSize());
-
- }
-
- public MessageMetaData getMetaData()
- {
- return _metaData;
- }
-
- public long getMessageNumber()
- {
- return _messageId;
- }
-
- public void addContent(int offsetInMessage, ByteBuffer src)
- {
- src = src.duplicate();
- ByteBuffer dst = _content.duplicate();
- dst.position(offsetInMessage);
- dst.put(src);
- }
-
- public int getContent(int offset, ByteBuffer dst)
- {
- ByteBuffer src = _content.duplicate();
- src.position(offset);
- src = src.slice();
- if(dst.remaining() < src.limit())
- {
- src.limit(dst.remaining());
- }
- dst.put(src);
- return src.limit();
- }
-
- public TransactionLog.StoreFuture flushToStore()
- {
- return MessageStore.IMMEDIATE_FUTURE;
- }
-
- public void remove()
- {
- }
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/queue/QueueEntryTest.java b/java/broker/src/test/java/org/apache/qpid/server/queue/QueueEntryTest.java
deleted file mode 100644
index b67723dd25..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/queue/QueueEntryTest.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.queue;
-
-import org.apache.qpid.test.utils.QpidTestCase;
-
-/**
- *
- * Tests QueueEntry
- *
- */
-public class QueueEntryTest extends QpidTestCase
-{
- private QueueEntryImpl _queueEntry1 = null;
- private QueueEntryImpl _queueEntry2 = null;
- private QueueEntryImpl _queueEntry3 = null;
-
- @Override
- protected void setUp() throws Exception
- {
- super.setUp();
-
- int i = 0;
-
- SimpleQueueEntryList queueEntryList = new SimpleQueueEntryList(null);
- _queueEntry1 = (QueueEntryImpl) queueEntryList.add(new MockAMQMessage(i++));
- _queueEntry2 = (QueueEntryImpl) queueEntryList.add(new MockAMQMessage(i++));
- _queueEntry3 = (QueueEntryImpl) queueEntryList.add(new MockAMQMessage(i++));
- }
-
- public void testCompareTo()
- {
- assertTrue(_queueEntry1.compareTo(_queueEntry2) < 0);
- assertTrue(_queueEntry2.compareTo(_queueEntry1) > 0);
- assertTrue(_queueEntry1.compareTo(_queueEntry1) == 0);
- }
-
- /**
- * Tests that the getNext() can be used to traverse the list.
- */
- public void testTraverseWithNoDeletedEntries()
- {
- QueueEntryImpl current = _queueEntry1;
-
- current = current.getNext();
- assertSame("Unexpected current entry",_queueEntry2, current);
-
- current = current.getNext();
- assertSame("Unexpected current entry",_queueEntry3, current);
-
- current = current.getNext();
- assertNull(current);
-
- }
-
- /**
- * Tests that the getNext() can be used to traverse the list but deleted
- * entries are skipped and de-linked from the chain of entries.
- */
- public void testTraverseWithDeletedEntries()
- {
- // Delete 2nd queue entry
- _queueEntry2.delete();
- assertTrue(_queueEntry2.isDeleted());
-
-
- QueueEntryImpl current = _queueEntry1;
-
- current = current.getNext();
- assertSame("Unexpected current entry",_queueEntry3, current);
-
- current = current.getNext();
- assertNull(current);
-
- // Assert the side effects of getNext()
- assertSame("Next node of entry 1 should now be entry 3",
- _queueEntry3, _queueEntry1.nextNode());
- }
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleAMQQueueTest.java b/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleAMQQueueTest.java
deleted file mode 100644
index abe2d1728f..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleAMQQueueTest.java
+++ /dev/null
@@ -1,817 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.qpid.server.queue;
-
-import org.apache.commons.configuration.PropertiesConfiguration;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.AMQInternalException;
-import org.apache.qpid.AMQSecurityException;
-import org.apache.qpid.exchange.ExchangeDefaults;
-import org.apache.qpid.framing.AMQShortString;
-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.configuration.VirtualHostConfiguration;
-import org.apache.qpid.server.exchange.DirectExchange;
-import org.apache.qpid.server.message.AMQMessage;
-import org.apache.qpid.server.message.MessageMetaData;
-import org.apache.qpid.server.queue.BaseQueue.PostEnqueueAction;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-import org.apache.qpid.server.store.StoredMessage;
-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.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;
-
-public class SimpleAMQQueueTest extends InternalBrokerBaseCase
-{
-
- protected SimpleAMQQueue _queue;
- protected VirtualHost _virtualHost;
- protected TestableMemoryMessageStore _store = new TestableMemoryMessageStore();
- protected AMQShortString _qname = new AMQShortString("qname");
- protected AMQShortString _owner = new AMQShortString("owner");
- protected AMQShortString _routingKey = new AMQShortString("routing key");
- protected DirectExchange _exchange;
- protected MockSubscription _subscription = new MockSubscription();
- protected FieldTable _arguments = null;
-
- MessagePublishInfo info = new MessagePublishInfo()
- {
-
- public AMQShortString getExchange()
- {
- return null;
- }
-
- public void setExchange(AMQShortString exchange)
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean isImmediate()
- {
- return false;
- }
-
- public boolean isMandatory()
- {
- return false;
- }
-
- public AMQShortString getRoutingKey()
- {
- return null;
- }
- };
-
- @Override
- public void setUp() throws Exception
- {
- super.setUp();
- //Create Application Registry for test
- ApplicationRegistry applicationRegistry = (ApplicationRegistry)ApplicationRegistry.getInstance();
-
- PropertiesConfiguration env = new PropertiesConfiguration();
- _virtualHost = new VirtualHostImpl(new VirtualHostConfiguration(getClass().getName(), env), _store);
- applicationRegistry.getVirtualHostRegistry().registerVirtualHost(_virtualHost);
-
- _queue = (SimpleAMQQueue) AMQQueueFactory.createAMQQueueImpl(_qname, false, _owner, false, false, _virtualHost, _arguments);
-
- _exchange = (DirectExchange)_virtualHost.getExchangeRegistry().getExchange(ExchangeDefaults.DIRECT_EXCHANGE_NAME);
- }
-
- @Override
- public void tearDown() throws Exception
- {
- _queue.stop();
- super.tearDown();
- }
-
- public void testCreateQueue() throws AMQException
- {
- _queue.stop();
- try {
- _queue = (SimpleAMQQueue) AMQQueueFactory.createAMQQueueImpl(null, false, _owner, false, false, _virtualHost, _arguments );
- assertNull("Queue was created", _queue);
- }
- catch (IllegalArgumentException e)
- {
- assertTrue("Exception was not about missing name",
- e.getMessage().contains("name"));
- }
-
- try {
- _queue = new SimpleAMQQueue(_qname, false, _owner, false, false,null, Collections.EMPTY_MAP);
- assertNull("Queue was created", _queue);
- }
- catch (IllegalArgumentException e)
- {
- assertTrue("Exception was not about missing vhost",
- e.getMessage().contains("Host"));
- }
-
- _queue = (SimpleAMQQueue) AMQQueueFactory.createAMQQueueImpl(_qname, false, _owner, false,
- false, _virtualHost, _arguments);
- assertNotNull("Queue was not created", _queue);
- }
-
- public void testGetVirtualHost()
- {
- assertEquals("Virtual host was wrong", _virtualHost, _queue.getVirtualHost());
- }
-
- public void testBinding() throws AMQSecurityException, AMQInternalException
- {
- _virtualHost.getBindingFactory().addBinding(String.valueOf(_routingKey), _queue, _exchange, Collections.EMPTY_MAP);
-
- assertTrue("Routing key was not bound",
- _exchange.isBound(_routingKey));
- assertTrue("Queue was not bound to key",
- _exchange.isBound(_routingKey,_queue));
- assertEquals("Exchange binding count", 1,
- _queue.getBindings().size());
- assertEquals("Wrong exchange bound", String.valueOf(_routingKey),
- _queue.getBindings().get(0).getBindingKey());
- assertEquals("Wrong exchange bound", _exchange,
- _queue.getBindings().get(0).getExchange());
-
- _virtualHost.getBindingFactory().removeBinding(String.valueOf(_routingKey), _queue, _exchange, Collections.EMPTY_MAP);
- assertFalse("Routing key was still bound",
- _exchange.isBound(_routingKey));
-
- }
-
- public void testRegisterSubscriptionThenEnqueueMessage() throws AMQException
- {
- // Check adding a subscription adds it to the queue
- _queue.registerSubscription(_subscription, false);
- assertEquals("Subscription did not get queue", _queue,
- _subscription.getQueue());
- assertEquals("Queue does not have consumer", 1,
- _queue.getConsumerCount());
- assertEquals("Queue does not have active consumer", 1,
- _queue.getActiveConsumerCount());
-
- // Check sending a message ends up with the subscriber
- AMQMessage messageA = createMessage(new Long(24));
- _queue.enqueue(messageA);
- assertEquals(messageA, _subscription.getQueueContext().getLastSeenEntry().getMessage());
- assertNull(((QueueContext)_subscription.getQueueContext())._releasedEntry);
-
- // Check removing the subscription removes it's information from the queue
- _queue.unregisterSubscription(_subscription);
- assertTrue("Subscription still had queue", _subscription.isClosed());
- assertFalse("Queue still has consumer", 1 == _queue.getConsumerCount());
- assertFalse("Queue still has active consumer",
- 1 == _queue.getActiveConsumerCount());
-
- AMQMessage messageB = createMessage(new Long (25));
- _queue.enqueue(messageB);
- assertNull(_subscription.getQueueContext());
-
- }
-
- public void testEnqueueMessageThenRegisterSubscription() throws AMQException, InterruptedException
- {
- AMQMessage messageA = createMessage(new Long(24));
- _queue.enqueue(messageA);
- _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);
- }
-
- /**
- * Tests enqueuing two messages.
- */
- public void testEnqueueTwoMessagesThenRegisterSubscription() throws Exception
- {
- AMQMessage messageA = createMessage(new Long(24));
- AMQMessage messageB = createMessage(new Long(25));
- _queue.enqueue(messageA);
- _queue.enqueue(messageB);
- _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);
- }
-
- /**
- * Tests that a released queue entry is resent to the subscriber. Verifies also that the
- * QueueContext._releasedEntry is reset to null after the entry has been reset.
- */
- public void testReleasedMessageIsResentToSubscriber() throws Exception
- {
- _queue.registerSubscription(_subscription, false);
-
- final ArrayList<QueueEntry> queueEntries = new ArrayList<QueueEntry>();
- PostEnqueueAction postEnqueueAction = new PostEnqueueAction()
- {
- public void onEnqueue(QueueEntry entry)
- {
- queueEntries.add(entry);
- }
- };
-
- AMQMessage messageA = createMessage(new Long(24));
- AMQMessage messageB = createMessage(new Long(25));
- AMQMessage messageC = createMessage(new Long(26));
-
- /* Enqueue three messages */
-
- _queue.enqueue(messageA, postEnqueueAction);
- _queue.enqueue(messageB, postEnqueueAction);
- _queue.enqueue(messageC, postEnqueueAction);
-
- Thread.sleep(150); // Work done by SubFlushRunner/QueueRunner Threads
-
- assertEquals("Unexpected total number of messages sent to subscription", 3, _subscription.getMessages().size());
- assertFalse("Redelivery flag should not be set", queueEntries.get(0).isRedelivered());
- assertFalse("Redelivery flag should not be set", queueEntries.get(1).isRedelivered());
- assertFalse("Redelivery flag should not be set", queueEntries.get(2).isRedelivered());
-
- /* Now release the first message only, causing it to be requeued */
-
- queueEntries.get(0).release();
-
- Thread.sleep(150); // Work done by SubFlushRunner/QueueRunner Threads
-
- assertEquals("Unexpected total number of messages sent to subscription", 4, _subscription.getMessages().size());
- 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);
- }
-
- /**
- * Tests that a released message that becomes expired is not resent to the subscriber.
- * This tests ensures that SimpleAMQQueueEntry.getNextAvailableEntry avoids expired entries.
- * Verifies also that the QueueContext._releasedEntry is reset to null after the entry has been reset.
- */
- public void testReleaseMessageThatBecomesExpiredIsNotRedelivered() throws Exception
- {
- _queue.registerSubscription(_subscription, false);
-
- final ArrayList<QueueEntry> queueEntries = new ArrayList<QueueEntry>();
- PostEnqueueAction postEnqueueAction = new PostEnqueueAction()
- {
- public void onEnqueue(QueueEntry entry)
- {
- queueEntries.add(entry);
- }
- };
-
- /* Enqueue one message with expiration set for a short time in the future */
-
- AMQMessage messageA = createMessage(new Long(24));
- int messageExpirationOffset = 200;
- messageA.setExpiration(System.currentTimeMillis() + messageExpirationOffset);
-
- _queue.enqueue(messageA, postEnqueueAction);
-
- int subFlushWaitTime = 150;
- Thread.sleep(subFlushWaitTime); // Work done by SubFlushRunner/QueueRunner Threads
-
- assertEquals("Unexpected total number of messages sent to subscription", 1, _subscription.getMessages().size());
- assertFalse("Redelivery flag should not be set", queueEntries.get(0).isRedelivered());
-
- /* Wait a little more to be sure that message will have expired, then release the first message only, causing it to be requeued */
- Thread.sleep(messageExpirationOffset - subFlushWaitTime + 10);
- queueEntries.get(0).release();
-
- Thread.sleep(subFlushWaitTime); // Work done by SubFlushRunner/QueueRunner Threads
-
- 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);
-
- }
-
- /**
- * Tests that if a client releases entries 'out of order' (the order
- * used by QueueEntryImpl.compareTo) that messages are still resent
- * successfully. Specifically this test ensures the {@see SimpleAMQQueue#requeue()}
- * can correctly move the _releasedEntry to an earlier position in the QueueEntry list.
- */
- public void testReleasedOutOfComparableOrderAreRedelivered() throws Exception
- {
- _queue.registerSubscription(_subscription, false);
-
- final ArrayList<QueueEntry> queueEntries = new ArrayList<QueueEntry>();
- PostEnqueueAction postEnqueueAction = new PostEnqueueAction()
- {
- public void onEnqueue(QueueEntry entry)
- {
- queueEntries.add(entry);
- }
- };
-
- AMQMessage messageA = createMessage(new Long(24));
- AMQMessage messageB = createMessage(new Long(25));
- AMQMessage messageC = createMessage(new Long(26));
-
- /* Enqueue three messages */
-
- _queue.enqueue(messageA, postEnqueueAction);
- _queue.enqueue(messageB, postEnqueueAction);
- _queue.enqueue(messageC, postEnqueueAction);
-
- Thread.sleep(150); // Work done by SubFlushRunner/QueueRunner Threads
-
- assertEquals("Unexpected total number of messages sent to subscription", 3, _subscription.getMessages().size());
- assertFalse("Redelivery flag should not be set", queueEntries.get(0).isRedelivered());
- assertFalse("Redelivery flag should not be set", queueEntries.get(1).isRedelivered());
- assertFalse("Redelivery flag should not be set", queueEntries.get(2).isRedelivered());
-
- /* Now release the third and first message only, causing it to be requeued */
-
- queueEntries.get(2).release();
- queueEntries.get(0).release();
-
- Thread.sleep(150); // Work done by SubFlushRunner/QueueRunner Threads
-
- assertEquals("Unexpected total number of messages sent to subscription", 5, _subscription.getMessages().size());
- 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);
- }
-
-
- /**
- * Tests that a release requeues an entry for a queue with multiple subscriptions. Verifies that a
- * requeue resends a message to a <i>single</i> subscriber.
- */
- public void testReleaseForQueueWithMultipleSubscriptions() throws Exception
- {
- MockSubscription subscription1 = new MockSubscription();
- MockSubscription subscription2 = new MockSubscription();
-
- _queue.registerSubscription(subscription1, false);
- _queue.registerSubscription(subscription2, false);
-
- final ArrayList<QueueEntry> queueEntries = new ArrayList<QueueEntry>();
- PostEnqueueAction postEnqueueAction = new PostEnqueueAction()
- {
- public void onEnqueue(QueueEntry entry)
- {
- queueEntries.add(entry);
- }
- };
-
- AMQMessage messageA = createMessage(new Long(24));
- AMQMessage messageB = createMessage(new Long(25));
-
- /* Enqueue two messages */
-
- _queue.enqueue(messageA, postEnqueueAction);
- _queue.enqueue(messageB, postEnqueueAction);
-
- Thread.sleep(150); // Work done by SubFlushRunner/QueueRunner Threads
-
- assertEquals("Unexpected total number of messages sent to both after enqueue", 2, subscription1.getMessages().size() + subscription2.getMessages().size());
-
- /* Now release the first message only, causing it to be requeued */
- queueEntries.get(0).release();
-
- 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);
- }
-
- public void testExclusiveConsumer() throws AMQException
- {
- // Check adding an exclusive subscription adds it to the queue
- _queue.registerSubscription(_subscription, true);
- assertEquals("Subscription did not get queue", _queue,
- _subscription.getQueue());
- assertEquals("Queue does not have consumer", 1,
- _queue.getConsumerCount());
- assertEquals("Queue does not have active consumer", 1,
- _queue.getActiveConsumerCount());
-
- // Check sending a message ends up with the subscriber
- AMQMessage messageA = createMessage(new Long(24));
- _queue.enqueue(messageA);
- assertEquals(messageA, _subscription.getQueueContext().getLastSeenEntry().getMessage());
-
- // Check we cannot add a second subscriber to the queue
- Subscription subB = new MockSubscription();
- Exception ex = null;
- try
- {
- _queue.registerSubscription(subB, false);
- }
- catch (AMQException e)
- {
- ex = e;
- }
- assertNotNull(ex);
-
- // Check we cannot add an exclusive subscriber to a queue with an
- // existing subscription
- _queue.unregisterSubscription(_subscription);
- _queue.registerSubscription(_subscription, false);
- try
- {
- _queue.registerSubscription(subB, true);
- }
- catch (AMQException e)
- {
- ex = e;
- }
- assertNotNull(ex);
- }
-
- public void testAutoDeleteQueue() throws Exception
- {
- _queue.stop();
- _queue = new SimpleAMQQueue(_qname, false, null, true, false, _virtualHost, Collections.EMPTY_MAP);
- _queue.setDeleteOnNoConsumers(true);
- _queue.registerSubscription(_subscription, false);
- AMQMessage message = createMessage(new Long(25));
- _queue.enqueue(message);
- _queue.unregisterSubscription(_subscription);
- assertTrue("Queue was not deleted when subscription was removed",
- _queue.isDeleted());
- }
-
- public void testResend() throws Exception
- {
- _queue.registerSubscription(_subscription, false);
- Long id = new Long(26);
- AMQMessage message = createMessage(id);
- _queue.enqueue(message);
- QueueEntry entry = _subscription.getQueueContext().getLastSeenEntry();
- entry.setRedelivered();
- _queue.resend(entry, _subscription);
-
- }
-
- public void testGetFirstMessageId() throws Exception
- {
- // Create message
- Long messageId = new Long(23);
- AMQMessage message = createMessage(messageId);
-
- // Put message on queue
- _queue.enqueue(message);
- // Get message id
- Long testmsgid = _queue.getMessagesOnTheQueue(1).get(0);
-
- // Check message id
- assertEquals("Message ID was wrong", messageId, testmsgid);
- }
-
- public void testGetFirstFiveMessageIds() throws Exception
- {
- for (int i = 0 ; i < 5; i++)
- {
- // Create message
- Long messageId = new Long(i);
- AMQMessage message = createMessage(messageId);
- // Put message on queue
- _queue.enqueue(message);
- }
- // Get message ids
- List<Long> msgids = _queue.getMessagesOnTheQueue(5);
-
- // Check message id
- for (int i = 0; i < 5; i++)
- {
- Long messageId = new Long(i);
- assertEquals("Message ID was wrong", messageId, msgids.get(i));
- }
- }
-
- public void testGetLastFiveMessageIds() throws Exception
- {
- for (int i = 0 ; i < 10; i++)
- {
- // Create message
- Long messageId = new Long(i);
- AMQMessage message = createMessage(messageId);
- // Put message on queue
- _queue.enqueue(message);
- }
- // Get message ids
- List<Long> msgids = _queue.getMessagesOnTheQueue(5, 5);
-
- // Check message id
- for (int i = 0; i < 5; i++)
- {
- Long messageId = new Long(i+5);
- assertEquals("Message ID was wrong", messageId, msgids.get(i));
- }
- }
-
- public void testGetMessagesRangeOnTheQueue() throws Exception
- {
- for (int i = 1 ; i <= 10; i++)
- {
- // Create message
- Long messageId = new Long(i);
- AMQMessage message = createMessage(messageId);
- // Put message on queue
- _queue.enqueue(message);
- }
-
- // Get non-existent 0th QueueEntry & check returned list was empty
- // (the position parameters in this method are indexed from 1)
- List<QueueEntry> entries = _queue.getMessagesRangeOnTheQueue(0, 0);
- assertTrue(entries.size() == 0);
-
- // Check that when 'from' is 0 it is ignored and the range continues from 1
- entries = _queue.getMessagesRangeOnTheQueue(0, 2);
- assertTrue(entries.size() == 2);
- long msgID = entries.get(0).getMessage().getMessageNumber();
- assertEquals("Message ID was wrong", msgID, 1L);
- msgID = entries.get(1).getMessage().getMessageNumber();
- assertEquals("Message ID was wrong", msgID, 2L);
-
- // Check that when 'from' is greater than 'to' the returned list is empty
- entries = _queue.getMessagesRangeOnTheQueue(5, 4);
- assertTrue(entries.size() == 0);
-
- // Get first QueueEntry & check id
- entries = _queue.getMessagesRangeOnTheQueue(1, 1);
- assertTrue(entries.size() == 1);
- msgID = entries.get(0).getMessage().getMessageNumber();
- assertEquals("Message ID was wrong", msgID, 1L);
-
- // Get 5th,6th,7th entries and check id's
- entries = _queue.getMessagesRangeOnTheQueue(5, 7);
- assertTrue(entries.size() == 3);
- msgID = entries.get(0).getMessage().getMessageNumber();
- assertEquals("Message ID was wrong", msgID, 5L);
- msgID = entries.get(1).getMessage().getMessageNumber();
- assertEquals("Message ID was wrong", msgID, 6L);
- msgID = entries.get(2).getMessage().getMessageNumber();
- assertEquals("Message ID was wrong", msgID, 7L);
-
- // Get 10th QueueEntry & check id
- entries = _queue.getMessagesRangeOnTheQueue(10, 10);
- assertTrue(entries.size() == 1);
- msgID = entries.get(0).getMessage().getMessageNumber();
- assertEquals("Message ID was wrong", msgID, 10L);
-
- // Get non-existent 11th QueueEntry & check returned set was empty
- entries = _queue.getMessagesRangeOnTheQueue(11, 11);
- assertTrue(entries.size() == 0);
-
- // Get 9th,10th, and non-existent 11th entries & check result is of size 2 with correct IDs
- entries = _queue.getMessagesRangeOnTheQueue(9, 11);
- assertTrue(entries.size() == 2);
- msgID = entries.get(0).getMessage().getMessageNumber();
- assertEquals("Message ID was wrong", msgID, 9L);
- msgID = entries.get(1).getMessage().getMessageNumber();
- assertEquals("Message ID was wrong", msgID, 10L);
- }
-
- public void testEnqueueDequeueOfPersistentMessageToNonDurableQueue() throws AMQException
- {
- // Create IncomingMessage and nondurable queue
- final IncomingMessage msg = new IncomingMessage(info);
- ContentHeaderBody contentHeaderBody = new ContentHeaderBody();
- contentHeaderBody.setProperties(new BasicContentHeaderProperties());
- ((BasicContentHeaderProperties) contentHeaderBody.getProperties()).setDeliveryMode((byte) 2);
- msg.setContentHeaderBody(contentHeaderBody);
-
- final ArrayList<BaseQueue> qs = new ArrayList<BaseQueue>();
-
- // Send persistent message
-
- qs.add(_queue);
- MessageMetaData metaData = msg.headersReceived();
- StoredMessage handle = _store.addMessage(metaData);
- msg.setStoredMessage(handle);
-
-
- ServerTransaction txn = new AutoCommitTransaction(_store);
-
- txn.enqueue(qs, msg, new ServerTransaction.Action()
- {
- public void postCommit()
- {
- msg.enqueue(qs);
- }
-
- public void onRollback()
- {
- }
- });
-
-
-
- // Check that it is enqueued
- AMQQueue data = _store.getMessages().get(1L);
- assertNull(data);
-
- // Dequeue message
- MockQueueEntry entry = new MockQueueEntry();
- AMQMessage amqmsg = new AMQMessage(handle);
-
- entry.setMessage(amqmsg);
- _queue.dequeue(entry,null);
-
- // Check that it is dequeued
- data = _store.getMessages().get(1L);
- assertNull(data);
- }
-
-
- /**
- * processQueue() is used when asynchronously delivering messages to
- * subscriptions which could not be delivered immediately during the
- * enqueue() operation.
- *
- * A defect within the method would mean that delivery of these messages may
- * not occur should the Runner stop before all messages have been processed.
- * Such a defect was discovered when Selectors were used such that one and
- * only one subscription can/will accept any given messages, but multiple
- * subscriptions are present, and one of the earlier subscriptions receives
- * more messages than the others.
- *
- * This test is to validate that the processQueue() method is able to
- * correctly deliver all of the messages present for asynchronous delivery
- * to subscriptions in such a scenario.
- */
- public void testProcessQueueWithUniqueSelectors() throws Exception
- {
- TestSimpleQueueEntryListFactory factory = new TestSimpleQueueEntryListFactory();
- SimpleAMQQueue testQueue = new SimpleAMQQueue("testQueue", false, "testOwner",false,
- false, _virtualHost, factory, null)
- {
- @Override
- public void deliverAsync(Subscription sub)
- {
- // do nothing, i.e prevent deliveries by the SubFlushRunner
- // when registering the new subscriptions
- }
- };
-
- // retrieve the QueueEntryList the queue creates and insert the test
- // messages, thus avoiding straight-through delivery attempts during
- //enqueue() process.
- QueueEntryList list = factory.getQueueEntryList();
- assertNotNull("QueueEntryList should have been created", list);
-
- QueueEntry msg1 = list.add(createMessage(1L));
- QueueEntry msg2 = list.add(createMessage(2L));
- QueueEntry msg3 = list.add(createMessage(3L));
- QueueEntry msg4 = list.add(createMessage(4L));
- QueueEntry msg5 = list.add(createMessage(5L));
-
- // Create lists of the entries each subscription should be interested
- // in.Bias over 50% of the messages to the first subscription so that
- // the later subscriptions reject them and report being done before
- // the first subscription as the processQueue method proceeds.
- List<QueueEntry> msgListSub1 = createEntriesList(msg1, msg2, msg3);
- List<QueueEntry> msgListSub2 = createEntriesList(msg4);
- List<QueueEntry> msgListSub3 = createEntriesList(msg5);
-
- MockSubscription sub1 = new MockSubscription(msgListSub1);
- MockSubscription sub2 = new MockSubscription(msgListSub2);
- MockSubscription sub3 = new MockSubscription(msgListSub3);
-
- // register the subscriptions
- testQueue.registerSubscription(sub1, false);
- testQueue.registerSubscription(sub2, false);
- testQueue.registerSubscription(sub3, false);
-
- //check that no messages have been delivered to the
- //subscriptions during registration
- assertEquals("No messages should have been delivered yet", 0, sub1.getMessages().size());
- assertEquals("No messages should have been delivered yet", 0, sub2.getMessages().size());
- assertEquals("No messages should have been delivered yet", 0, sub3.getMessages().size());
-
- // call processQueue to deliver the messages
- testQueue.processQueue(new QueueRunner(testQueue, 1)
- {
- @Override
- public void run()
- {
- // we dont actually want/need this runner to do any work
- // because we we are already doing it!
- }
- });
-
- // check expected messages delivered to correct consumers
- verifyRecievedMessages(msgListSub1, sub1.getMessages());
- verifyRecievedMessages(msgListSub2, sub2.getMessages());
- verifyRecievedMessages(msgListSub3, sub3.getMessages());
- }
-
- private List<QueueEntry> createEntriesList(QueueEntry... entries)
- {
- ArrayList<QueueEntry> entriesList = new ArrayList<QueueEntry>();
- for (QueueEntry entry : entries)
- {
- entriesList.add(entry);
- }
- return entriesList;
- }
-
- private void verifyRecievedMessages(List<QueueEntry> expected,
- List<QueueEntry> delivered)
- {
- assertEquals("Consumer did not receive the expected number of messages",
- expected.size(), delivered.size());
-
- for (QueueEntry msg : expected)
- {
- assertTrue("Consumer did not recieve msg: "
- + msg.getMessage().getMessageNumber(), delivered.contains(msg));
- }
- }
-
- public class TestMessage extends AMQMessage
- {
- private final long _tag;
- private int _count;
-
- TestMessage(long tag, long messageId, MessagePublishInfo publishBody)
- throws AMQException
- {
- this(tag, messageId, publishBody, new ContentHeaderBody(1, 1, new BasicContentHeaderProperties(), 0));
-
- }
- TestMessage(long tag, long messageId, MessagePublishInfo publishBody, ContentHeaderBody chb)
- throws AMQException
- {
- super(new MockStoredMessage(messageId, publishBody, chb));
- _tag = tag;
- }
-
- public boolean incrementReference()
- {
- _count++;
- return true;
- }
-
- public void decrementReference()
- {
- _count--;
- }
-
- void assertCountEquals(int expected)
- {
- assertEquals("Wrong count for message with tag " + _tag, expected, _count);
- }
- }
-
- protected AMQMessage createMessage(Long id) throws AMQException
- {
- AMQMessage messageA = new TestMessage(id, id, info);
- return messageA;
- }
-
- class TestSimpleQueueEntryListFactory implements QueueEntryListFactory
- {
- QueueEntryList _list;
-
- public QueueEntryList createQueueEntryList(AMQQueue queue)
- {
- _list = new SimpleQueueEntryList(queue);
- return _list;
- }
-
- public QueueEntryList getQueueEntryList()
- {
- return _list;
- }
- }
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleAMQQueueThreadPoolTest.java b/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleAMQQueueThreadPoolTest.java
deleted file mode 100644
index a40dc5670f..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleAMQQueueThreadPoolTest.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.queue;
-
-import junit.framework.TestCase;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.pool.ReferenceCountingExecutorService;
-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
-{
-
- public void test() throws AMQException
- {
- int initialCount = ReferenceCountingExecutorService.getInstance().getReferenceCount();
- VirtualHost test = ApplicationRegistry.getInstance().getVirtualHostRegistry().getVirtualHost("test");
-
- try
- {
- SimpleAMQQueue queue = (SimpleAMQQueue) AMQQueueFactory.createAMQQueueImpl(new AMQShortString("test"), false,
- new AMQShortString("owner"),
- false, false, test, null);
-
- assertFalse("Creation did not start Pool.", ReferenceCountingExecutorService.getInstance().getPool().isShutdown());
-
- assertEquals("References not increased", initialCount + 1, ReferenceCountingExecutorService.getInstance().getReferenceCount());
-
- queue.stop();
-
- assertEquals("References not decreased", initialCount , ReferenceCountingExecutorService.getInstance().getReferenceCount());
- }
- finally
- {
- ApplicationRegistry.remove();
- }
- }
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleQueueEntryListTest.java b/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleQueueEntryListTest.java
deleted file mode 100644
index 320a75045a..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleQueueEntryListTest.java
+++ /dev/null
@@ -1,159 +0,0 @@
-/*
-*
-* Licensed to the Apache Software Foundation (ASF) under one
-* or more contributor license agreements. See the NOTICE file
-* distributed with this work for additional information
-* regarding copyright ownership. The ASF licenses this file
-* to you under the Apache License, Version 2.0 (the
-* "License"); you may not use this file except in compliance
-* with the License. You may obtain a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing,
-* software distributed under the License is distributed on an
-* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-* KIND, either express or implied. See the License for the
-* specific language governing permissions and limitations
-* under the License.
-*
-*/
-package org.apache.qpid.server.queue;
-
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-import org.apache.qpid.server.message.AMQMessage;
-
-import junit.framework.TestCase;
-
-public class SimpleQueueEntryListTest extends TestCase
-{
- private static final String SCAVENGE_PROP = "qpid.queue.scavenge_count";
- String oldScavengeValue = null;
-
- @Override
- protected void setUp()
- {
- oldScavengeValue = System.setProperty(SCAVENGE_PROP, "9");
- }
-
- @Override
- protected void tearDown()
- {
- if(oldScavengeValue != null)
- {
- System.setProperty(SCAVENGE_PROP, oldScavengeValue);
- }
- else
- {
- System.clearProperty(SCAVENGE_PROP);
- }
- }
-
- /**
- * Tests the behavior of the next(QueuyEntry) method.
- */
- public void testNext() throws Exception
- {
- SimpleQueueEntryList sqel = new SimpleQueueEntryList(null);
- int i = 0;
-
- QueueEntry queueEntry1 = sqel.add(new MockAMQMessage(i++));
- QueueEntry queueEntry2 = sqel.add(new MockAMQMessage(i++));
-
- assertSame(queueEntry2, sqel.next(queueEntry1));
- assertNull(sqel.next(queueEntry2));
- }
-
- public void testScavenge() throws Exception
- {
- SimpleQueueEntryList sqel = new SimpleQueueEntryList(null);
- ConcurrentHashMap<Integer,QueueEntry> entriesMap = new ConcurrentHashMap<Integer,QueueEntry>();
-
-
- //Add messages to generate QueueEntry's
- for(int i = 1; i <= 100 ; i++)
- {
- AMQMessage msg = new MockAMQMessage(i);
- QueueEntry bleh = sqel.add(msg);
- assertNotNull("QE should not have been null", bleh);
- entriesMap.put(i,bleh);
- }
-
- QueueEntryImpl head = ((QueueEntryImpl) sqel.getHead());
-
- //We shall now delete some specific messages mid-queue that will lead to
- //requiring a scavenge once the requested threshold of 9 deletes is passed
-
- //Delete the 2nd message only
- assertTrue("Failed to delete QueueEntry", entriesMap.remove(2).delete());
- verifyDeletedButPresentBeforeScavenge(head, 2);
-
- //Delete messages 12 to 14
- assertTrue("Failed to delete QueueEntry", entriesMap.remove(12).delete());
- verifyDeletedButPresentBeforeScavenge(head, 12);
- assertTrue("Failed to delete QueueEntry", entriesMap.remove(13).delete());
- verifyDeletedButPresentBeforeScavenge(head, 13);
- assertTrue("Failed to delete QueueEntry", entriesMap.remove(14).delete());
- verifyDeletedButPresentBeforeScavenge(head, 14);
-
-
- //Delete message 20 only
- assertTrue("Failed to delete QueueEntry", entriesMap.remove(20).delete());
- verifyDeletedButPresentBeforeScavenge(head, 20);
-
- //Delete messages 81 to 84
- assertTrue("Failed to delete QueueEntry", entriesMap.remove(81).delete());
- verifyDeletedButPresentBeforeScavenge(head, 81);
- assertTrue("Failed to delete QueueEntry", entriesMap.remove(82).delete());
- verifyDeletedButPresentBeforeScavenge(head, 82);
- assertTrue("Failed to delete QueueEntry", entriesMap.remove(83).delete());
- verifyDeletedButPresentBeforeScavenge(head, 83);
- assertTrue("Failed to delete QueueEntry", entriesMap.remove(84).delete());
- verifyDeletedButPresentBeforeScavenge(head, 84);
-
- //Delete message 99 - this is the 10th message deleted that is after the queue head
- //and so will invoke the scavenge() which is set to go after 9 previous deletions
- assertTrue("Failed to delete QueueEntry", entriesMap.remove(99).delete());
-
- verifyAllDeletedMessagedNotPresent(head, entriesMap);
- }
-
- private void verifyDeletedButPresentBeforeScavenge(QueueEntryImpl head, long messageId)
- {
- //Use the head to get the initial entry in the queue
- QueueEntryImpl entry = head._next;
-
- for(long i = 1; i < messageId ; i++)
- {
- assertEquals("Expected QueueEntry was not found in the list", i, (long) entry.getMessage().getMessageNumber());
- entry = entry._next;
- }
-
- assertTrue("Entry should have been deleted", entry.isDeleted());
- }
-
- private void verifyAllDeletedMessagedNotPresent(QueueEntryImpl head, Map<Integer,QueueEntry> remainingMessages)
- {
- //Use the head to get the initial entry in the queue
- QueueEntryImpl entry = head._next;
-
- assertNotNull("Initial entry should not have been null", entry);
-
- int count = 0;
-
- while (entry != null)
- {
- assertFalse("Entry " + entry.getMessage().getMessageNumber() + " should not have been deleted", entry.isDeleted());
- assertNotNull("QueueEntry was not found in the list of remaining entries",
- remainingMessages.get(entry.getMessage().getMessageNumber().intValue()));
-
- count++;
- entry = entry._next;
- }
-
- assertEquals("Count should have been equal",count,remainingMessages.size());
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/registry/ApplicationRegistryShutdownTest.java b/java/broker/src/test/java/org/apache/qpid/server/registry/ApplicationRegistryShutdownTest.java
deleted file mode 100644
index e45c8d7b96..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/registry/ApplicationRegistryShutdownTest.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.registry;
-
-import org.apache.qpid.server.util.InternalBrokerBaseCase;
-
-import java.security.Security;
-import java.security.Provider;
-import java.util.List;
-import java.util.LinkedList;
-
-/**
- * QPID-1390 : Test to validate that the AuthenticationManger can successfully unregister any new SASL providers when
- * The ApplicationRegistry is closed.
- *
- * This should be expanded as QPID-1399 is implemented.
- */
-public class ApplicationRegistryShutdownTest extends InternalBrokerBaseCase
-{
-
- Provider[] _defaultProviders;
- @Override
- public void setUp() throws Exception
- {
- // Get default providers
- _defaultProviders = Security.getProviders();
-
- //Startup the new broker and register the new providers
- super.setUp();
- }
-
-
- /**
- * QPID-1399 : Ensure that the Authentiction manager unregisters any SASL providers created during
- * ApplicationRegistry initialisation.
- *
- */
- public void testAuthenticationMangerCleansUp() throws Exception
- {
-
- // Get the providers after initialisation
- Provider[] providersAfterInitialisation = Security.getProviders();
-
- // Find the additions
- List additions = new LinkedList();
- for (Provider afterInit : providersAfterInitialisation)
- {
- boolean found = false;
- for (Provider defaultProvider : _defaultProviders)
- {
- if (defaultProvider == afterInit)
- {
- found=true;
- break;
- }
- }
-
- // Record added registies
- if (!found)
- {
- additions.add(afterInit);
- }
- }
-
- // Not using isEmpty as that is not in Java 5
- assertTrue("No new SASL mechanisms added by initialisation.", additions.size() != 0 );
-
- //Close the registry which will perform the close the AuthenticationManager
- getRegistry().close();
-
- //Validate that the SASL plugFins have been removed.
- Provider[] providersAfterClose = Security.getProviders();
-
- assertTrue("No providers unregistered", providersAfterInitialisation.length > providersAfterClose.length);
-
- //Ensure that the additions are not still present after close().
- for (Provider afterClose : providersAfterClose)
- {
- assertFalse("Added provider not unregistered", additions.contains(afterClose));
- }
- }
-
-
-
-
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/Base64MD5PasswordFilePrincipalDatabaseTest.java b/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/Base64MD5PasswordFilePrincipalDatabaseTest.java
deleted file mode 100644
index 2ab15d4872..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/Base64MD5PasswordFilePrincipalDatabaseTest.java
+++ /dev/null
@@ -1,466 +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.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 java.io.BufferedReader;
-import java.io.BufferedWriter;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileReader;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.UnsupportedEncodingException;
-import java.security.Principal;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.regex.Pattern;
-
-public class Base64MD5PasswordFilePrincipalDatabaseTest extends TestCase
-{
-
- private static final String TEST_COMMENT = "# Test Comment";
-
- private static final String USERNAME = "testUser";
- private static final String PASSWORD = "guest";
- private static final String PASSWORD_B64MD5HASHED = "CE4DQ6BIb/BVMN9scFyLtA==";
- private static char[] PASSWORD_MD5_CHARS;
- private static final String PRINCIPAL_USERNAME = "testUserPrincipal";
- private static final Principal PRINCIPAL = new UsernamePrincipal(PRINCIPAL_USERNAME);
- private Base64MD5PasswordFilePrincipalDatabase _database;
- private File _pwdFile;
- private List<File> _testPwdFiles = new ArrayList<File>();
-
- static
- {
- try
- {
- Base64 b64 = new Base64();
- byte[] md5passBytes = PASSWORD_B64MD5HASHED.getBytes(Base64MD5PasswordFilePrincipalDatabase.DEFAULT_ENCODING);
- byte[] decoded = b64.decode(md5passBytes);
-
- PASSWORD_MD5_CHARS = new char[decoded.length];
-
- int index = 0;
- for (byte c : decoded)
- {
- PASSWORD_MD5_CHARS[index++] = (char) c;
- }
- }
- catch (UnsupportedEncodingException e)
- {
- fail("Unable to perform B64 decode to get the md5 char[] password");
- }
- }
-
-
- public void setUp() throws Exception
- {
- _database = new Base64MD5PasswordFilePrincipalDatabase();
- _pwdFile = File.createTempFile(this.getClass().getName(), "pwd");
- _pwdFile.deleteOnExit();
- _database.setPasswordFile(_pwdFile.getAbsolutePath());
- _testPwdFiles.clear();
- }
-
- public void tearDown() throws Exception
- {
- //clean up the created default password file and any backup
- File oldPwdFile = new File(_pwdFile.getAbsolutePath() + ".old");
- if(oldPwdFile.exists())
- {
- oldPwdFile.delete();
- }
-
- _pwdFile.delete();
-
- //clean up any additional files and their backups
- for(File f : _testPwdFiles)
- {
- oldPwdFile = new File(f.getAbsolutePath() + ".old");
- if(oldPwdFile.exists())
- {
- oldPwdFile.delete();
- }
-
- f.delete();
- }
- }
-
- private File createPasswordFile(int commentLines, int users)
- {
- try
- {
- File testFile = File.createTempFile("Base64MD5PDPDTest","tmp");
- testFile.deleteOnExit();
-
- BufferedWriter writer = new BufferedWriter(new FileWriter(testFile));
-
- for (int i = 0; i < commentLines; i++)
- {
- writer.write(TEST_COMMENT);
- writer.newLine();
- }
-
- for (int i = 0; i < users; i++)
- {
- writer.write(USERNAME + i + ":Password");
- writer.newLine();
- }
-
- writer.flush();
- writer.close();
-
- _testPwdFiles.add(testFile);
-
- return testFile;
-
- }
- catch (IOException e)
- {
- fail("Unable to create test password file." + e.getMessage());
- }
-
- return null;
- }
-
- private void loadPasswordFile(File file)
- {
- try
- {
- _database.setPasswordFile(file.toString());
- }
- catch (IOException e)
- {
- fail("Password File was not created." + e.getMessage());
- }
- }
-
- /** **** Test Methods ************** */
-
- public void testCreatePrincipal()
- {
- File testFile = createPasswordFile(1, 0);
-
- loadPasswordFile(testFile);
-
-
- Principal principal = new Principal()
- {
- public String getName()
- {
- return USERNAME;
- }
- };
-
- assertTrue("New user not created.", _database.createPrincipal(principal, PASSWORD.toCharArray()));
-
- PasswordCallback callback = new PasswordCallback("prompt",false);
- try
- {
- _database.setPassword(principal, callback);
- }
- catch (AccountNotFoundException e)
- {
- fail("user account did not exist");
- }
- assertTrue("Password returned was incorrect.", Arrays.equals(PASSWORD_MD5_CHARS, callback.getPassword()));
-
- loadPasswordFile(testFile);
-
- try
- {
- _database.setPassword(principal, callback);
- }
- catch (AccountNotFoundException e)
- {
- fail("user account did not exist");
- }
- assertTrue("Password returned was incorrect.", Arrays.equals(PASSWORD_MD5_CHARS, callback.getPassword()));
-
- assertNotNull("Created User was not saved", _database.getUser(USERNAME));
-
- assertFalse("Duplicate user created.", _database.createPrincipal(principal, PASSWORD.toCharArray()));
- }
-
- public void testCreatePrincipalIsSavedToFile()
- {
-
- File testFile = createPasswordFile(1, 0);
-
- loadPasswordFile(testFile);
-
- final String CREATED_PASSWORD = "guest";
- final String CREATED_B64MD5HASHED_PASSWORD = "CE4DQ6BIb/BVMN9scFyLtA==";
- final String CREATED_USERNAME = "createdUser";
-
- Principal principal = new Principal()
- {
- public String getName()
- {
- return CREATED_USERNAME;
- }
- };
-
- _database.createPrincipal(principal, CREATED_PASSWORD.toCharArray());
-
- try
- {
- BufferedReader reader = new BufferedReader(new FileReader(testFile));
-
- assertTrue("File has no content", reader.ready());
-
- assertEquals("Comment line has been corrupted.", TEST_COMMENT, reader.readLine());
-
- assertTrue("File is missing user data.", reader.ready());
-
- String userLine = reader.readLine();
-
- String[] result = Pattern.compile(":").split(userLine);
-
- assertEquals("User line not complete '" + userLine + "'", 2, result.length);
-
- assertEquals("Username not correct,", CREATED_USERNAME, result[0]);
- assertEquals("Password not correct,", CREATED_B64MD5HASHED_PASSWORD, result[1]);
-
- assertFalse("File has more content", reader.ready());
-
- }
- catch (IOException e)
- {
- fail("Unable to valdate file contents due to:" + e.getMessage());
- }
- }
-
-
- public void testDeletePrincipal()
- {
- File testFile = createPasswordFile(1, 1);
-
- loadPasswordFile(testFile);
-
- Principal user = _database.getUser(USERNAME + "0");
- assertNotNull("Generated user not present.", user);
-
- try
- {
- _database.deletePrincipal(user);
- }
- catch (AccountNotFoundException e)
- {
- fail("User should be present" + e.getMessage());
- }
-
- try
- {
- _database.deletePrincipal(user);
- fail("User should not be present");
- }
- catch (AccountNotFoundException e)
- {
- //pass
- }
-
- loadPasswordFile(testFile);
-
- try
- {
- _database.deletePrincipal(user);
- fail("User should not be present");
- }
- catch (AccountNotFoundException e)
- {
- //pass
- }
-
- assertNull("Deleted user still present.", _database.getUser(USERNAME + "0"));
- }
-
- public void testGetUsers()
- {
- int USER_COUNT = 10;
- File testFile = createPasswordFile(1, USER_COUNT);
-
- loadPasswordFile(testFile);
-
- Principal user = _database.getUser("MISSING_USERNAME");
- assertNull("Missing user present.", user);
-
- List<Principal> users = _database.getUsers();
-
- assertNotNull("Users list is null.", users);
-
- assertEquals(USER_COUNT, users.size());
-
- boolean[] verify = new boolean[USER_COUNT];
- for (int i = 0; i < USER_COUNT; i++)
- {
- Principal principal = users.get(i);
-
- assertNotNull("Generated user not present.", principal);
-
- String name = principal.getName();
-
- int id = Integer.parseInt(name.substring(USERNAME.length()));
-
- assertFalse("Duplicated username retrieve", verify[id]);
- verify[id] = true;
- }
-
- for (int i = 0; i < USER_COUNT; i++)
- {
- assertTrue("User " + i + " missing", verify[i]);
- }
- }
-
- public void testUpdatePasswordIsSavedToFile()
- {
-
- File testFile = createPasswordFile(1, 1);
-
- loadPasswordFile(testFile);
-
- Principal testUser = _database.getUser(USERNAME + "0");
-
- assertNotNull(testUser);
-
- String NEW_PASSWORD = "guest";
- String NEW_PASSWORD_HASH = "CE4DQ6BIb/BVMN9scFyLtA==";
- try
- {
- _database.updatePassword(testUser, NEW_PASSWORD.toCharArray());
- }
- catch (AccountNotFoundException e)
- {
- fail(e.toString());
- }
-
- try
- {
- BufferedReader reader = new BufferedReader(new FileReader(testFile));
-
- assertTrue("File has no content", reader.ready());
-
- assertEquals("Comment line has been corrupted.", TEST_COMMENT, reader.readLine());
-
- assertTrue("File is missing user data.", reader.ready());
-
- String userLine = reader.readLine();
-
- String[] result = Pattern.compile(":").split(userLine);
-
- assertEquals("User line not complete '" + userLine + "'", 2, result.length);
-
- assertEquals("Username not correct,", USERNAME + "0", result[0]);
- assertEquals("New Password not correct,", NEW_PASSWORD_HASH, result[1]);
-
- assertFalse("File has more content", reader.ready());
-
- }
- catch (IOException e)
- {
- fail("Unable to valdate file contents due to:" + e.getMessage());
- }
- }
-
- public void testSetPasswordFileWithMissingFile()
- {
- try
- {
- _database.setPasswordFile("DoesntExist");
- }
- catch (FileNotFoundException fnfe)
- {
- assertTrue(fnfe.getMessage(), fnfe.getMessage().startsWith("Cannot find password file"));
- }
- catch (IOException e)
- {
- fail("Password File was not created." + e.getMessage());
- }
-
- }
-
- public void testSetPasswordFileWithReadOnlyFile()
- {
-
- File testFile = createPasswordFile(0, 0);
-
- testFile.setReadOnly();
-
- try
- {
- _database.setPasswordFile(testFile.toString());
- }
- catch (FileNotFoundException fnfe)
- {
- assertTrue(fnfe.getMessage().startsWith("Cannot read password file "));
- }
- catch (IOException e)
- {
- fail("Password File was not created." + e.getMessage());
- }
- }
-
- public void testCreateUserPrincipal() throws IOException
- {
- _database.createPrincipal(PRINCIPAL, PASSWORD.toCharArray());
- Principal newPrincipal = _database.getUser(PRINCIPAL_USERNAME);
- assertNotNull(newPrincipal);
- assertEquals(PRINCIPAL.getName(), newPrincipal.getName());
- }
-
- public void testVerifyPassword() throws IOException, AccountNotFoundException
- {
- testCreateUserPrincipal();
- //assertFalse(_pwdDB.verifyPassword(_username, null));
- assertFalse(_database.verifyPassword(PRINCIPAL_USERNAME, new char[]{}));
- assertFalse(_database.verifyPassword(PRINCIPAL_USERNAME, (PASSWORD+"z").toCharArray()));
- assertTrue(_database.verifyPassword(PRINCIPAL_USERNAME, PASSWORD.toCharArray()));
-
- try
- {
- _database.verifyPassword("made.up.username", PASSWORD.toCharArray());
- fail("Should not have been able to verify this non-existant users password.");
- }
- catch (AccountNotFoundException e)
- {
- // pass
- }
- }
-
- public void testUpdatePassword() throws IOException, AccountNotFoundException
- {
- testCreateUserPrincipal();
- char[] newPwd = "newpassword".toCharArray();
- _database.updatePassword(PRINCIPAL, newPwd);
- assertFalse(_database.verifyPassword(PRINCIPAL_USERNAME, PASSWORD.toCharArray()));
- assertTrue(_database.verifyPassword(PRINCIPAL_USERNAME, newPwd));
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/HashedUserTest.java b/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/HashedUserTest.java
deleted file mode 100644
index aa85cac758..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/HashedUserTest.java
+++ /dev/null
@@ -1,95 +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.auth.database;
-
-import junit.framework.TestCase;
-import org.apache.log4j.Level;
-import org.apache.log4j.Logger;
-
-import java.io.UnsupportedEncodingException;
-
-/*
- Note User is mainly tested by Base64MD5PFPDTest this is just to catch the extra methods
- */
-public class HashedUserTest extends TestCase
-{
-
- String USERNAME = "username";
- String PASSWORD = "password";
- String B64_ENCODED_PASSWORD = "cGFzc3dvcmQ=";
-
- public void testToLongArrayConstructor()
- {
- try
- {
- HashedUser user = new HashedUser(new String[]{USERNAME, PASSWORD, USERNAME});
- fail("Error expected");
- }
- catch (IllegalArgumentException e)
- {
- 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());
- }
-
- hash = PASSWORD.toCharArray();
-
- index=0;
- for (char c : user.getPassword())
- {
- assertEquals("Password incorrect", hash[index], c);
- index++;
- }
-
- }
- catch (UnsupportedEncodingException e)
- {
- fail(e.getMessage());
- }
- }
-}
-
diff --git a/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/PlainPasswordFilePrincipalDatabaseTest.java b/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/PlainPasswordFilePrincipalDatabaseTest.java
deleted file mode 100644
index a3dad19bb4..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/PlainPasswordFilePrincipalDatabaseTest.java
+++ /dev/null
@@ -1,416 +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.auth.database;
-
-import junit.framework.TestCase;
-
-import javax.security.auth.login.AccountNotFoundException;
-
-import org.apache.qpid.server.security.auth.sasl.UsernamePrincipal;
-
-import java.io.BufferedReader;
-import java.io.BufferedWriter;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileReader;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.security.Principal;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.regex.Pattern;
-
-public class PlainPasswordFilePrincipalDatabaseTest extends TestCase
-{
-
- private static final String TEST_COMMENT = "# Test Comment";
- private static final String TEST_PASSWORD = "testPassword";
- private static final char[] TEST_PASSWORD_CHARS = TEST_PASSWORD.toCharArray();
- private static final String TEST_USERNAME = "testUser";
-
- private Principal _principal = new UsernamePrincipal(TEST_USERNAME);
- private PlainPasswordFilePrincipalDatabase _database;
- private List<File> _testPwdFiles = new ArrayList<File>();
-
- public void setUp() throws Exception
- {
- _database = new PlainPasswordFilePrincipalDatabase();
- _testPwdFiles.clear();
- }
-
- public void tearDown() throws Exception
- {
- //clean up any additional files and their backups
- for(File f : _testPwdFiles)
- {
- File oldPwdFile = new File(f.getAbsolutePath() + ".old");
- if(oldPwdFile.exists())
- {
- oldPwdFile.delete();
- }
-
- f.delete();
- }
- }
-
- // ******* Test Methods ********** //
-
- public void testCreatePrincipal()
- {
- File testFile = createPasswordFile(1, 0);
-
- loadPasswordFile(testFile);
-
- final String CREATED_PASSWORD = "guest";
- final String CREATED_USERNAME = "createdUser";
-
- Principal principal = new Principal()
- {
- public String getName()
- {
- return CREATED_USERNAME;
- }
- };
-
- assertTrue("New user not created.", _database.createPrincipal(principal, CREATED_PASSWORD.toCharArray()));
-
- loadPasswordFile(testFile);
-
- assertNotNull("Created User was not saved", _database.getUser(CREATED_USERNAME));
-
- assertFalse("Duplicate user created.", _database.createPrincipal(principal, CREATED_PASSWORD.toCharArray()));
-
- testFile.delete();
- }
-
- public void testCreatePrincipalIsSavedToFile()
- {
-
- File testFile = createPasswordFile(1, 0);
-
- loadPasswordFile(testFile);
-
- Principal principal = new Principal()
- {
- public String getName()
- {
- return TEST_USERNAME;
- }
- };
-
- _database.createPrincipal(principal, TEST_PASSWORD_CHARS);
-
- try
- {
- BufferedReader reader = new BufferedReader(new FileReader(testFile));
-
- assertTrue("File has no content", reader.ready());
-
- assertEquals("Comment line has been corrupted.", TEST_COMMENT, reader.readLine());
-
- assertTrue("File is missing user data.", reader.ready());
-
- String userLine = reader.readLine();
-
- String[] result = Pattern.compile(":").split(userLine);
-
- assertEquals("User line not complete '" + userLine + "'", 2, result.length);
-
- assertEquals("Username not correct,", TEST_USERNAME, result[0]);
- assertEquals("Password not correct,", TEST_PASSWORD, result[1]);
-
- assertFalse("File has more content", reader.ready());
-
- }
- catch (IOException e)
- {
- fail("Unable to valdate file contents due to:" + e.getMessage());
- }
- testFile.delete();
- }
-
- public void testDeletePrincipal()
- {
- File testFile = createPasswordFile(1, 1);
-
- loadPasswordFile(testFile);
-
- Principal user = _database.getUser(TEST_USERNAME + "0");
- assertNotNull("Generated user not present.", user);
-
- try
- {
- _database.deletePrincipal(user);
- }
- catch (AccountNotFoundException e)
- {
- fail("User should be present" + e.getMessage());
- }
-
- try
- {
- _database.deletePrincipal(user);
- fail("User should not be present");
- }
- catch (AccountNotFoundException e)
- {
- //pass
- }
-
- loadPasswordFile(testFile);
-
- try
- {
- _database.deletePrincipal(user);
- fail("User should not be present");
- }
- catch (AccountNotFoundException e)
- {
- //pass
- }
-
- assertNull("Deleted user still present.", _database.getUser(TEST_USERNAME + "0"));
-
- testFile.delete();
- }
-
- public void testGetUsers()
- {
- int USER_COUNT = 10;
- File testFile = createPasswordFile(1, USER_COUNT);
-
- loadPasswordFile(testFile);
-
- Principal user = _database.getUser("MISSING_USERNAME");
- assertNull("Missing user present.", user);
-
- List<Principal> users = _database.getUsers();
-
- assertNotNull("Users list is null.", users);
-
- assertEquals(USER_COUNT, users.size());
-
- boolean[] verify = new boolean[USER_COUNT];
- for (int i = 0; i < USER_COUNT; i++)
- {
- Principal principal = users.get(i);
-
- assertNotNull("Generated user not present.", principal);
-
- String name = principal.getName();
-
- int id = Integer.parseInt(name.substring(TEST_USERNAME.length()));
-
- assertFalse("Duplicated username retrieve", verify[id]);
- verify[id] = true;
- }
-
- for (int i = 0; i < USER_COUNT; i++)
- {
- assertTrue("User " + i + " missing", verify[i]);
- }
-
- testFile.delete();
- }
-
- public void testUpdatePasswordIsSavedToFile()
- {
-
- File testFile = createPasswordFile(1, 1);
-
- loadPasswordFile(testFile);
-
- Principal testUser = _database.getUser(TEST_USERNAME + "0");
-
- assertNotNull(testUser);
-
- String NEW_PASSWORD = "NewPassword";
- try
- {
- _database.updatePassword(testUser, NEW_PASSWORD.toCharArray());
- }
- catch (AccountNotFoundException e)
- {
- fail(e.toString());
- }
-
- try
- {
- BufferedReader reader = new BufferedReader(new FileReader(testFile));
-
- assertTrue("File has no content", reader.ready());
-
- assertEquals("Comment line has been corrupted.", TEST_COMMENT, reader.readLine());
-
- assertTrue("File is missing user data.", reader.ready());
-
- String userLine = reader.readLine();
-
- String[] result = Pattern.compile(":").split(userLine);
-
- assertEquals("User line not complete '" + userLine + "'", 2, result.length);
-
- assertEquals("Username not correct,", TEST_USERNAME + "0", result[0]);
- assertEquals("New Password not correct,", NEW_PASSWORD, result[1]);
-
- assertFalse("File has more content", reader.ready());
-
- }
- catch (IOException e)
- {
- fail("Unable to valdate file contents due to:" + e.getMessage());
- }
- testFile.delete();
- }
-
- public void testSetPasswordFileWithMissingFile()
- {
- try
- {
- _database.setPasswordFile("DoesntExist");
- }
- catch (FileNotFoundException fnfe)
- {
- assertTrue(fnfe.getMessage(), fnfe.getMessage().startsWith("Cannot find password file"));
- }
- catch (IOException e)
- {
- fail("Password File was not created." + e.getMessage());
- }
-
- }
-
- public void testSetPasswordFileWithReadOnlyFile()
- {
-
- File testFile = createPasswordFile(0, 0);
-
- testFile.setReadOnly();
-
- try
- {
- _database.setPasswordFile(testFile.toString());
- }
- catch (FileNotFoundException fnfe)
- {
- assertTrue(fnfe.getMessage().startsWith("Cannot read password file "));
- }
- catch (IOException e)
- {
- fail("Password File was not created." + e.getMessage());
- }
-
- testFile.delete();
- }
-
- private void createUserPrincipal() throws IOException
- {
- File testFile = createPasswordFile(0, 0);
- loadPasswordFile(testFile);
-
- _database.createPrincipal(_principal, TEST_PASSWORD_CHARS);
- Principal newPrincipal = _database.getUser(TEST_USERNAME);
- assertNotNull(newPrincipal);
- assertEquals(_principal.getName(), newPrincipal.getName());
- }
-
- public void testVerifyPassword() throws IOException, AccountNotFoundException
- {
- createUserPrincipal();
- assertFalse(_database.verifyPassword(TEST_USERNAME, new char[]{}));
- assertFalse(_database.verifyPassword(TEST_USERNAME, "massword".toCharArray()));
- assertTrue(_database.verifyPassword(TEST_USERNAME, TEST_PASSWORD_CHARS));
-
- try
- {
- _database.verifyPassword("made.up.username", TEST_PASSWORD_CHARS);
- fail("Should not have been able to verify this non-existant users password.");
- }
- catch (AccountNotFoundException e)
- {
- // pass
- }
- }
-
- public void testUpdatePassword() throws IOException, AccountNotFoundException
- {
- createUserPrincipal();
- char[] newPwd = "newpassword".toCharArray();
- _database.updatePassword(_principal, newPwd);
- assertFalse(_database.verifyPassword(TEST_USERNAME, TEST_PASSWORD_CHARS));
- assertTrue(_database.verifyPassword(TEST_USERNAME, newPwd));
- }
-
-
-
- // *********** Utility Methods ******** //
-
- private File createPasswordFile(int commentLines, int users)
- {
- try
- {
- File testFile = File.createTempFile(this.getClass().getName(),"tmp");
- testFile.deleteOnExit();
-
- BufferedWriter writer = new BufferedWriter(new FileWriter(testFile));
-
- for (int i = 0; i < commentLines; i++)
- {
- writer.write(TEST_COMMENT);
- writer.newLine();
- }
-
- for (int i = 0; i < users; i++)
- {
- writer.write(TEST_USERNAME + i + ":" + TEST_PASSWORD);
- writer.newLine();
- }
-
- writer.flush();
- writer.close();
-
- _testPwdFiles.add(testFile);
-
- return testFile;
-
- }
- catch (IOException e)
- {
- fail("Unable to create test password file." + e.getMessage());
- }
-
- return null;
- }
-
- private void loadPasswordFile(File file)
- {
- try
- {
- _database.setPasswordFile(file.toString());
- }
- catch (IOException e)
- {
- fail("Password File was not created." + e.getMessage());
- }
- }
-
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/PlainUserTest.java b/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/PlainUserTest.java
deleted file mode 100644
index 7f0843d46e..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/PlainUserTest.java
+++ /dev/null
@@ -1,78 +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.auth.database;
-
-import junit.framework.TestCase;
-
-/*
- Note PlainUser is mainly tested by PlainPFPDTest, this is just to catch the extra methods
- */
-public class PlainUserTest extends TestCase
-{
-
- String USERNAME = "username";
- String PASSWORD = "password";
-
- public void testTooLongArrayConstructor()
- {
- try
- {
- PlainUser user = new PlainUser(new String[]{USERNAME, PASSWORD, USERNAME});
- fail("Error expected");
- }
- catch (IllegalArgumentException e)
- {
- assertEquals("User Data should be length 2, username, password", e.getMessage());
- }
- }
-
- public void testStringArrayConstructor()
- {
- PlainUser user = new PlainUser(new String[]{USERNAME, PASSWORD});
- assertEquals("Username incorrect", USERNAME, user.getName());
- int index = 0;
-
- char[] password = PASSWORD.toCharArray();
-
- try
- {
- for (byte c : user.getPasswordBytes())
- {
- assertEquals("Password incorrect", password[index], (char) c);
- index++;
- }
- }
- catch (Exception e)
- {
- fail(e.getMessage());
- }
-
- password = PASSWORD.toCharArray();
-
- index=0;
- for (char c : user.getPassword())
- {
- assertEquals("Password incorrect", password[index], c);
- index++;
- }
- }
-}
-
diff --git a/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/PrincipalDatabaseAuthenticationManagerTest.java b/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/PrincipalDatabaseAuthenticationManagerTest.java
deleted file mode 100644
index f51ce0b6c6..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/PrincipalDatabaseAuthenticationManagerTest.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.security.auth.manager;
-
-import java.security.Provider;
-import java.security.Security;
-
-import javax.security.sasl.SaslException;
-import javax.security.sasl.SaslServer;
-
-import org.apache.qpid.server.security.auth.AuthenticationResult;
-import org.apache.qpid.server.security.auth.AuthenticationResult.AuthenticationStatus;
-import org.apache.qpid.server.util.InternalBrokerBaseCase;
-
-/**
- *
- * Tests the public methods of PrincipalDatabaseAuthenticationManager.
- *
- */
-public class PrincipalDatabaseAuthenticationManagerTest extends InternalBrokerBaseCase
-{
- private PrincipalDatabaseAuthenticationManager _manager = null;
-
- /**
- * @see org.apache.qpid.server.util.InternalBrokerBaseCase#tearDown()
- */
- @Override
- public void tearDown() throws Exception
- {
- super.tearDown();
- if (_manager != null)
- {
- _manager.close();
- }
- }
-
- /**
- * @see org.apache.qpid.server.util.InternalBrokerBaseCase#setUp()
- */
- @Override
- public void setUp() throws Exception
- {
- super.setUp();
-
- _manager = new PrincipalDatabaseAuthenticationManager();
- }
-
- /**
- * Tests that the PDAM registers SASL mechanisms correctly with the runtime.
- */
- public void testRegisteredMechanisms() throws Exception
- {
- assertNotNull(_manager.getMechanisms());
- // relies on those mechanisms attached to PropertiesPrincipalDatabaseManager
- assertEquals("PLAIN CRAM-MD5", _manager.getMechanisms());
-
- Provider qpidProvider = Security.getProvider(PrincipalDatabaseAuthenticationManager.PROVIDER_NAME);
- assertNotNull(qpidProvider);
- }
-
- /**
- * Tests that the SASL factory method createSaslServer correctly
- * returns a non-null implementation.
- */
- public void testSaslMechanismCreation() throws Exception
- {
- SaslServer server = _manager.createSaslServer("CRAM-MD5", "localhost");
- assertNotNull(server);
- // Merely tests the creation of the mechanism. Mechanisms themselves are tested
- // by their own tests.
- }
-
- /**
- *
- * Tests that the authenticate method correctly interprets an
- * authentication success.
- *
- */
- public void testAuthenticationSuccess() throws Exception
- {
- SaslServer testServer = createTestSaslServer(true, false);
-
- AuthenticationResult result = _manager.authenticate(testServer, "12345".getBytes());
- assertEquals(AuthenticationStatus.SUCCESS, result.status);
- }
-
- /**
- *
- * Tests that the authenticate method correctly interprets an
- * authentication not complete.
- *
- */
- public void testAuthenticationNotCompleted() throws Exception
- {
- SaslServer testServer = createTestSaslServer(false, false);
-
- AuthenticationResult result = _manager.authenticate(testServer, "12345".getBytes());
- assertEquals(AuthenticationStatus.CONTINUE, result.status);
- }
-
- /**
- *
- * Tests that the authenticate method correctly interprets an
- * authentication error.
- *
- */
- public void testAuthenticationError() throws Exception
- {
- SaslServer testServer = createTestSaslServer(false, true);
-
- AuthenticationResult result = _manager.authenticate(testServer, "12345".getBytes());
- assertEquals(AuthenticationStatus.ERROR, result.status);
- }
-
- /**
- * Tests the ability to de-register the provider.
- */
- public void testClose() throws Exception
- {
- assertEquals("PLAIN CRAM-MD5", _manager.getMechanisms());
- assertNotNull(Security.getProvider(PrincipalDatabaseAuthenticationManager.PROVIDER_NAME));
-
- _manager.close();
-
- // Check provider has been removed.
- assertNull(_manager.getMechanisms());
- assertNull(Security.getProvider(PrincipalDatabaseAuthenticationManager.PROVIDER_NAME));
- _manager = null;
- }
-
- /**
- * Test SASL implementation used to test the authenticate() method.
- */
- private SaslServer createTestSaslServer(final boolean complete, final boolean throwSaslException)
- {
- return new SaslServer()
- {
-
- @Override
- public String getMechanismName()
- {
- return null;
- }
-
- @Override
- public byte[] evaluateResponse(byte[] response) throws SaslException
- {
- if (throwSaslException)
- {
- throw new SaslException("Mocked exception");
- }
- return null;
- }
-
- @Override
- public boolean isComplete()
- {
- return complete;
- }
-
- @Override
- public String getAuthorizationID()
- {
- return null;
- }
-
- @Override
- public byte[] unwrap(byte[] incoming, int offset, int len) throws SaslException
- {
- return null;
- }
-
- @Override
- public byte[] wrap(byte[] outgoing, int offset, int len) throws SaslException
- {
- return null;
- }
-
- @Override
- public Object getNegotiatedProperty(String propName)
- {
- return null;
- }
-
- @Override
- public void dispose() throws SaslException
- {
- }
- };
- }
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/security/auth/rmi/RMIPasswordAuthenticatorTest.java b/java/broker/src/test/java/org/apache/qpid/server/security/auth/rmi/RMIPasswordAuthenticatorTest.java
deleted file mode 100644
index e8c24da68d..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/security/auth/rmi/RMIPasswordAuthenticatorTest.java
+++ /dev/null
@@ -1,267 +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.auth.rmi;
-
-import java.io.BufferedWriter;
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.util.Collections;
-
-import javax.management.remote.JMXPrincipal;
-import javax.security.auth.Subject;
-
-import org.apache.qpid.server.security.auth.database.Base64MD5PasswordFilePrincipalDatabase;
-import org.apache.qpid.server.security.auth.database.PlainPasswordFilePrincipalDatabase;
-
-import junit.framework.TestCase;
-
-public class RMIPasswordAuthenticatorTest extends TestCase
-{
- private final String USERNAME = "guest";
- private final String PASSWORD = "guest";
- private final String B64_MD5HASHED_PASSWORD = "CE4DQ6BIb/BVMN9scFyLtA==";
- private RMIPasswordAuthenticator _rmipa;
-
- private Base64MD5PasswordFilePrincipalDatabase _md5Pd;
- private File _md5PwdFile;
-
- private PlainPasswordFilePrincipalDatabase _plainPd;
- private File _plainPwdFile;
-
- private Subject testSubject;
-
- protected void setUp() throws Exception
- {
- _rmipa = new RMIPasswordAuthenticator();
-
- _md5Pd = new Base64MD5PasswordFilePrincipalDatabase();
- _md5PwdFile = createTempPasswordFile(this.getClass().getName()+"md5pwd", USERNAME, B64_MD5HASHED_PASSWORD);
- _md5Pd.setPasswordFile(_md5PwdFile.getAbsolutePath());
-
- _plainPd = new PlainPasswordFilePrincipalDatabase();
- _plainPwdFile = createTempPasswordFile(this.getClass().getName()+"plainpwd", USERNAME, PASSWORD);
- _plainPd.setPasswordFile(_plainPwdFile.getAbsolutePath());
-
- testSubject = new Subject(true,
- Collections.singleton(new JMXPrincipal(USERNAME)),
- Collections.EMPTY_SET,
- Collections.EMPTY_SET);
- }
-
- private File createTempPasswordFile(String filenamePrefix, String user, String password)
- {
- try
- {
- File testFile = File.createTempFile(filenamePrefix,"tmp");
- testFile.deleteOnExit();
-
- BufferedWriter writer = new BufferedWriter(new FileWriter(testFile));
-
- writer.write(user + ":" + password);
- writer.newLine();
-
- writer.flush();
- writer.close();
-
- return testFile;
- }
- catch (IOException e)
- {
- fail("Unable to create temporary test password file." + e.getMessage());
- }
-
- return null;
- }
-
-
- //********** Test Methods *********//
-
-
- public void testAuthenticate()
- {
- String[] credentials;
- Subject newSubject;
-
- // Test when no PD has been set
- try
- {
- credentials = new String[]{USERNAME, PASSWORD};
- newSubject = _rmipa.authenticate(credentials);
- fail("SecurityException expected due to lack of principal database");
- }
- catch (SecurityException se)
- {
- assertEquals("Unexpected exception message",
- RMIPasswordAuthenticator.UNABLE_TO_LOOKUP, se.getMessage());
- }
-
- //The PrincipalDatabase's are tested primarily by their own tests, but
- //minimal tests are done here to exercise their usage in this area.
-
- // Test correct passwords are verified with an MD5 PD
- try
- {
- _rmipa.setPrincipalDatabase(_md5Pd);
- credentials = new String[]{USERNAME, PASSWORD};
- newSubject = _rmipa.authenticate(credentials);
- assertTrue("Returned subject does not equal expected value",
- newSubject.equals(testSubject));
- }
- catch (Exception e)
- {
- fail("Unexpected Exception:" + e.getMessage());
- }
-
- // Test incorrect passwords are not verified with an MD5 PD
- try
- {
- credentials = new String[]{USERNAME, PASSWORD+"incorrect"};
- newSubject = _rmipa.authenticate(credentials);
- fail("SecurityException expected due to incorrect password");
- }
- catch (SecurityException se)
- {
- assertEquals("Unexpected exception message",
- RMIPasswordAuthenticator.INVALID_CREDENTIALS, se.getMessage());
- }
-
- // Test non-existent accounts are not verified with an MD5 PD
- try
- {
- credentials = new String[]{USERNAME+"invalid", PASSWORD};
- newSubject = _rmipa.authenticate(credentials);
- fail("SecurityException expected due to non-existant account");
- }
- catch (SecurityException se)
- {
- assertEquals("Unexpected exception message",
- RMIPasswordAuthenticator.INVALID_CREDENTIALS, se.getMessage());
- }
-
- // Test correct passwords are verified with a Plain PD
- try
- {
- _rmipa.setPrincipalDatabase(_plainPd);
- credentials = new String[]{USERNAME, PASSWORD};
- newSubject = _rmipa.authenticate(credentials);
- assertTrue("Returned subject does not equal expected value",
- newSubject.equals(testSubject));
- }
- catch (Exception e)
- {
- fail("Unexpected Exception");
- }
-
- // Test incorrect passwords are not verified with a Plain PD
- try
- {
- credentials = new String[]{USERNAME, PASSWORD+"incorrect"};
- newSubject = _rmipa.authenticate(credentials);
- fail("SecurityException expected due to incorrect password");
- }
- catch (SecurityException se)
- {
- assertEquals("Unexpected exception message",
- RMIPasswordAuthenticator.INVALID_CREDENTIALS, se.getMessage());
- }
-
- // Test non-existent accounts are not verified with an Plain PD
- try
- {
- credentials = new String[]{USERNAME+"invalid", PASSWORD};
- newSubject = _rmipa.authenticate(credentials);
- fail("SecurityException expected due to non existant account");
- }
- catch (SecurityException se)
- {
- assertEquals("Unexpected exception message",
- RMIPasswordAuthenticator.INVALID_CREDENTIALS, se.getMessage());
- }
-
- // Test handling of non-string credential's
- try
- {
- Object[] objCredentials = new Object[]{USERNAME, PASSWORD};
- newSubject = _rmipa.authenticate(objCredentials);
- fail("SecurityException expected due to non string[] credentials");
- }
- catch (SecurityException se)
- {
- assertEquals("Unexpected exception message",
- RMIPasswordAuthenticator.SHOULD_BE_STRING_ARRAY, se.getMessage());
- }
-
- // Test handling of incorrect number of credential's
- try
- {
- credentials = new String[]{USERNAME, PASSWORD, PASSWORD};
- newSubject = _rmipa.authenticate(credentials);
- fail("SecurityException expected due to supplying wrong number of credentials");
- }
- catch (SecurityException se)
- {
- assertEquals("Unexpected exception message",
- RMIPasswordAuthenticator.SHOULD_HAVE_2_ELEMENTS, se.getMessage());
- }
-
- // Test handling of null credential's
- try
- {
- //send a null array
- credentials = null;
- newSubject = _rmipa.authenticate(credentials);
- fail("SecurityException expected due to not supplying an array of credentials");
- }
- catch (SecurityException se)
- {
- assertEquals("Unexpected exception message",
- RMIPasswordAuthenticator.CREDENTIALS_REQUIRED, se.getMessage());
- }
-
- try
- {
- //send a null password
- credentials = new String[]{USERNAME, null};
- newSubject = _rmipa.authenticate(credentials);
- fail("SecurityException expected due to sending a null password");
- }
- catch (SecurityException se)
- {
- assertEquals("Unexpected exception message",
- RMIPasswordAuthenticator.SHOULD_BE_NON_NULL, se.getMessage());
- }
-
- try
- {
- //send a null username
- credentials = new String[]{null, PASSWORD};
- newSubject = _rmipa.authenticate(credentials);
- fail("SecurityException expected due to sending a null username");
- }
- catch (SecurityException se)
- {
- assertEquals("Unexpected exception message",
- RMIPasswordAuthenticator.SHOULD_BE_NON_NULL, se.getMessage());
- }
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/CRAMMD5HexInitialiserTest.java b/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/CRAMMD5HexInitialiserTest.java
deleted file mode 100644
index 3c5ed1d6c2..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/CRAMMD5HexInitialiserTest.java
+++ /dev/null
@@ -1,137 +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.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;
-
-import javax.security.auth.callback.Callback;
-import javax.security.auth.callback.NameCallback;
-import javax.security.auth.callback.PasswordCallback;
-import javax.security.auth.callback.UnsupportedCallbackException;
-import java.io.IOException;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-import java.util.Properties;
-
-/**
- * These tests ensure that the Hex wrapping that the initialiser performs does actually operate when the handle method is called.
- */
-public class CRAMMD5HexInitialiserTest extends TestCase
-{
- public void testHex()
- {
- //Create User details for testing
- String user = "testUser";
- String password = "testPassword";
-
- perform(user, password);
- }
-
- public void testHashedHex()
- {
- //Create User details for testing
- String user = "testUser";
- String password = "testPassword";
-
- //Create a hashed password that we then attempt to put through the call back mechanism.
- try
- {
- password = new String(MessageDigest.getInstance("MD5").digest(password.getBytes()));
- }
- catch (NoSuchAlgorithmException e)
- {
- fail(e.getMessage());
- }
-
- perform(user, password);
- }
-
- public void perform(String user, String password)
- {
- CRAMMD5HexInitialiser initialiser = new CRAMMD5HexInitialiser();
-
- //Use properties to create a PrincipalDatabase
- Properties users = new Properties();
- users.put(user, password);
-
- PropertiesPrincipalDatabase db = new PropertiesPrincipalDatabase(users);
-
- initialiser.initialise(db);
-
- //setup the callbacks
- PasswordCallback passwordCallback = new PasswordCallback("password:", false);
- NameCallback usernameCallback = new NameCallback("user:", user);
-
- Callback[] callbacks = new Callback[]{usernameCallback, passwordCallback};
-
- //Check the
- try
- {
- assertNull("The password was not null before the handle call.", passwordCallback.getPassword());
- initialiser.getCallbackHandler().handle(callbacks);
- }
- catch (IOException e)
- {
- fail(e.getMessage());
- }
- catch (UnsupportedCallbackException e)
- {
- fail(e.getMessage());
- }
-
- //Hex the password we initialised with and compare it with the passwordCallback
- assertArrayEquals(toHex(password.toCharArray()), passwordCallback.getPassword());
- }
-
- private void assertArrayEquals(char[] expected, char[] actual)
- {
- assertEquals("Arrays are not the same length", expected.length, actual.length);
-
- for (int index = 0; index < expected.length; index++)
- {
- assertEquals("Characters are not equal", expected[index], actual[index]);
- }
- }
-
- private char[] toHex(char[] password)
- {
- StringBuilder sb = new StringBuilder();
- for (char c : password)
- {
- //toHexString does not prepend 0 so we have to
- if (((byte) c > -1) && (byte) c < 10)
- {
- sb.append(0);
- }
-
- sb.append(Integer.toHexString(c & 0xFF));
- }
-
- //Extract the hex string as char[]
- char[] hex = new char[sb.length()];
-
- sb.getChars(0, sb.length(), hex, 0);
-
- return hex;
- }
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/CRAMMD5HexServerTest.java b/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/CRAMMD5HexServerTest.java
deleted file mode 100644
index 8b3f9c0622..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/CRAMMD5HexServerTest.java
+++ /dev/null
@@ -1,230 +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.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;
-
-/**
- * Test for the CRAM-MD5-HEX SASL mechanism.
- *
- * This test case focuses on testing {@link CRAMMD5HexSaslServer} but also exercises
- * collaborators {@link CRAMMD5HexInitialiser} and {@link Base64MD5PasswordFilePrincipalDatabase}
- */
-public class CRAMMD5HexServerTest extends TestCase
-{
-
- private SaslServer _saslServer; // Class under test
- private CRAMMD5HexServerFactory _saslFactory;
-
- @Override
- protected void setUp() throws Exception
- {
- super.setUp();
-
- CRAMMD5HexInitialiser _initializer = new CRAMMD5HexInitialiser();
-
- //Use properties to create a PrincipalDatabase
- Base64MD5PasswordFilePrincipalDatabase db = createTestPrincipalDatabase();
- assertEquals("Unexpected number of test users in the db", 2, db.getUsers().size());
-
- _initializer.initialise(db);
-
- _saslFactory = new CRAMMD5HexServerFactory();
-
- _saslServer = _saslFactory.createSaslServer(CRAMMD5HexSaslServer.MECHANISM,
- "AMQP",
- "localhost",
- _initializer.getProperties(),
- _initializer.getCallbackHandler());
- assertNotNull("Unable to create saslServer with mechanism type " + CRAMMD5HexSaslServer.MECHANISM, _saslServer);
-
- }
-
- public void testSuccessfulAuth() throws Exception
- {
-
- final byte[] serverChallenge = _saslServer.evaluateResponse(new byte[0]);
-
- // Generate client response
- final byte[] clientResponse = generateClientResponse("knownuser", "guest", serverChallenge);
-
-
- byte[] nextServerChallenge = _saslServer.evaluateResponse(clientResponse);
- assertTrue("Exchange must be flagged as complete after successful authentication", _saslServer.isComplete());
- assertNull("Next server challenge must be null after successful authentication", nextServerChallenge);
-
- }
-
- public void testKnownUserPresentsWrongPassword() throws Exception
- {
- byte[] serverChallenge = _saslServer.evaluateResponse(new byte[0]);
-
-
- final byte[] clientResponse = generateClientResponse("knownuser", "wrong!", serverChallenge);
- try
- {
- _saslServer.evaluateResponse(clientResponse);
- fail("Exception not thrown");
- }
- catch (SaslException se)
- {
- // PASS
- }
- assertFalse("Exchange must not be flagged as complete after unsuccessful authentication", _saslServer.isComplete());
- }
-
- public void testUnknownUser() throws Exception
- {
- final byte[] serverChallenge = _saslServer.evaluateResponse(new byte[0]);
-
-
- final byte[] clientResponse = generateClientResponse("unknownuser", "guest", serverChallenge);
-
- try
- {
- _saslServer.evaluateResponse(clientResponse);
- fail("Exception not thrown");
- }
- catch (SaslException se)
- {
- assertExceptionHasUnderlyingAsCause(AccountNotFoundException.class, se);
- // PASS
- }
- assertFalse("Exchange must not be flagged as complete after unsuccessful authentication", _saslServer.isComplete());
- }
-
- /**
- *
- * Demonstrates QPID-3158. A defect meant that users with some valid password were failing to
- * authenticate when using the .NET 0-8 client (uses this SASL mechanism).
- * It so happens that password "guest2" was one of the affected passwords.
- *
- * @throws Exception
- */
- public void testSuccessfulAuthReproducingQpid3158() throws Exception
- {
- byte[] serverChallenge = _saslServer.evaluateResponse(new byte[0]);
-
- // Generate client response
- byte[] resp = generateClientResponse("qpid3158user", "guest2", serverChallenge);
-
- byte[] nextServerChallenge = _saslServer.evaluateResponse(resp);
- assertTrue("Exchange must be flagged as complete after successful authentication", _saslServer.isComplete());
- assertNull("Next server challenge must be null after successful authentication", nextServerChallenge);
- }
-
- /**
- * Since we don't have a CRAM-MD5-HEX implementation client implementation in Java, this method
- * provides the implementation for first principals.
- *
- * @param userId user id
- * @param clearTextPassword clear text password
- * @param serverChallenge challenge from server
- *
- * @return challenge response
- */
- private byte[] generateClientResponse(final String userId, final String clearTextPassword, final byte[] serverChallenge) throws Exception
- {
- byte[] digestedPasswordBytes = MessageDigest.getInstance("MD5").digest(clearTextPassword.getBytes());
- char[] hexEncodedDigestedPassword = Hex.encodeHex(digestedPasswordBytes);
- byte[] hexEncodedDigestedPasswordBytes = new String(hexEncodedDigestedPassword).getBytes();
-
-
- Mac hmacMd5 = Mac.getInstance("HmacMD5");
- hmacMd5.init(new SecretKeySpec(hexEncodedDigestedPasswordBytes, "HmacMD5"));
- final byte[] messageAuthenticationCode = hmacMd5.doFinal(serverChallenge);
-
- // Build client response
- String responseAsString = userId + " " + new String(Hex.encodeHex(messageAuthenticationCode));
- byte[] resp = responseAsString.getBytes();
- return resp;
- }
-
- /**
- * Creates a test principal database.
- *
- * @return
- * @throws IOException
- */
- private Base64MD5PasswordFilePrincipalDatabase createTestPrincipalDatabase() throws IOException
- {
- Base64MD5PasswordFilePrincipalDatabase db = new Base64MD5PasswordFilePrincipalDatabase();
- File file = File.createTempFile("passwd", "db");
- file.deleteOnExit();
- db.setPasswordFile(file.getCanonicalPath());
- db.createPrincipal( createTestPrincipal("knownuser"), "guest".toCharArray());
- db.createPrincipal( createTestPrincipal("qpid3158user"), "guest2".toCharArray());
- return db;
- }
-
- private Principal createTestPrincipal(final String name)
- {
- return new Principal()
- {
-
- @Override
- public String getName()
- {
- return name;
- }
- };
- }
-
- private void assertExceptionHasUnderlyingAsCause(final Class<? extends Throwable> expectedUnderlying, Throwable e)
- {
- assertNotNull(e);
- int infiniteLoopGuard = 0; // Guard against loops in the cause chain
- boolean foundExpectedUnderlying = false;
- while (e.getCause() != null && infiniteLoopGuard++ < 10)
- {
- if (expectedUnderlying.equals(e.getCause().getClass()))
- {
- foundExpectedUnderlying = true;
- break;
- }
- e = e.getCause();
- }
-
- if (!foundExpectedUnderlying)
- {
- fail("Not found expected underlying exception " + expectedUnderlying + " as underlying cause of " + e.getClass());
- }
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/SaslServerTestCase.java b/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/SaslServerTestCase.java
deleted file mode 100644
index f80413d4f8..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/SaslServerTestCase.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.
- *
- */
-
-package org.apache.qpid.server.security.auth.sasl;
-
-import javax.security.sasl.SaslException;
-import javax.security.sasl.SaslServer;
-
-import org.apache.qpid.server.security.auth.database.PrincipalDatabase;
-
-import junit.framework.TestCase;
-
-public abstract class SaslServerTestCase extends TestCase
-{
- protected SaslServer server;
- protected String username = "u";
- protected String password = "p";
- protected String notpassword = "a";
- protected PrincipalDatabase db = new TestPrincipalDatabase();
-
- protected byte[] correctresponse;
- protected byte[] wrongresponse;
-
- public void testSucessfulAuth() throws SaslException
- {
- byte[] resp = this.server.evaluateResponse(correctresponse);
- assertNull(resp);
- }
-
- public void testFailAuth()
- {
- boolean exceptionCaught = false;
- try
- {
- byte[] resp = this.server.evaluateResponse(wrongresponse);
- }
- catch (SaslException e)
- {
- assertEquals("Authentication failed", e.getCause().getMessage());
- exceptionCaught = true;
- }
- if (!exceptionCaught)
- {
- fail("Should have thrown SaslException");
- }
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/TestPrincipalDatabase.java b/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/TestPrincipalDatabase.java
deleted file mode 100644
index 8507e49e17..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/TestPrincipalDatabase.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.server.security.auth.sasl;
-
-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
-{
-
- public boolean createPrincipal(Principal principal, char[] password)
- {
- // TODO Auto-generated method stub
- return false;
- }
-
- public boolean deletePrincipal(Principal principal) throws AccountNotFoundException
- {
- // TODO Auto-generated method stub
- return false;
- }
-
- public Map<String, AuthenticationProviderInitialiser> getMechanisms()
- {
- // TODO Auto-generated method stub
- return null;
- }
-
- public Principal getUser(String username)
- {
- // TODO Auto-generated method stub
- return null;
- }
-
- public List<Principal> getUsers()
- {
- // TODO Auto-generated method stub
- return null;
- }
-
- public void setPassword(Principal principal, PasswordCallback callback) throws IOException,
- AccountNotFoundException
- {
- callback.setPassword("p".toCharArray());
- }
-
- public boolean updatePassword(Principal principal, char[] password) throws AccountNotFoundException
- {
- // TODO Auto-generated method stub
- return false;
- }
-
- public boolean verifyPassword(String principal, char[] password) throws AccountNotFoundException
- {
- // TODO Auto-generated method stub
- return false;
- }
-
- public void reload() throws IOException
- {
- // TODO Auto-generated method stub
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/amqplain/AMQPlainSaslServerTest.java b/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/amqplain/AMQPlainSaslServerTest.java
deleted file mode 100644
index 6245064bf7..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/amqplain/AMQPlainSaslServerTest.java
+++ /dev/null
@@ -1,43 +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.auth.sasl.amqplain;
-
-import org.apache.qpid.framing.FieldTable;
-import org.apache.qpid.framing.FieldTableFactory;
-import org.apache.qpid.server.security.auth.sasl.SaslServerTestCase;
-import org.apache.qpid.server.security.auth.sasl.UsernamePasswordInitialiser;
-
-public class AMQPlainSaslServerTest extends SaslServerTestCase
-{
- protected void setUp() throws Exception
- {
- UsernamePasswordInitialiser handler = new AmqPlainInitialiser();
- handler.initialise(db);
- this.server = new AmqPlainSaslServer(handler.getCallbackHandler());
- FieldTable table = FieldTableFactory.newFieldTable();
- table.setString("LOGIN", username);
- table.setString("PASSWORD", password);
- correctresponse = table.getDataAsBytes();
- table.setString("PASSWORD", notpassword);
- wrongresponse = table.getDataAsBytes();
- }
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/plain/PlainSaslServerTest.java b/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/plain/PlainSaslServerTest.java
deleted file mode 100644
index 5dd51250dc..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/plain/PlainSaslServerTest.java
+++ /dev/null
@@ -1,39 +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.auth.sasl.plain;
-
-import org.apache.qpid.server.security.auth.sasl.SaslServerTestCase;
-import org.apache.qpid.server.security.auth.sasl.UsernamePasswordInitialiser;
-
-public class PlainSaslServerTest extends SaslServerTestCase
-{
-
- protected void setUp() throws Exception
- {
- UsernamePasswordInitialiser handler = new PlainInitialiser();
- handler.initialise(db);
- this.server = new PlainSaslServer(handler.getCallbackHandler());
- correctresponse = new byte[]{0x0, (byte) username.charAt(0), 0x0, (byte) password.charAt(0)};
- wrongresponse = new byte[]{0x0,(byte) username.charAt(0), 0x0, (byte) notpassword.charAt(0)};
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/stats/StatisticsCounterTest.java b/java/broker/src/test/java/org/apache/qpid/server/stats/StatisticsCounterTest.java
deleted file mode 100644
index fbaa1342c9..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/stats/StatisticsCounterTest.java
+++ /dev/null
@@ -1,144 +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.stats;
-
-import junit.framework.TestCase;
-
-/**
- * Unit tests for the {@link StatisticsCounter} class.
- */
-public class StatisticsCounterTest extends TestCase
-{
- /**
- * Check that statistics counters are created correctly.
- */
- public void testCreate()
- {
- long before = System.currentTimeMillis();
- StatisticsCounter counter = new StatisticsCounter("name", 1234L);
- long after = System.currentTimeMillis();
-
- assertTrue(before <= counter.getStart());
- assertTrue(after >= counter.getStart());
- assertTrue(counter.getName().startsWith("name-"));
- assertEquals(1234L, counter.getPeriod());
- }
-
- /**
- * Check that totals add up correctly.
- */
- public void testTotal()
- {
- StatisticsCounter counter = new StatisticsCounter("test", 1000L);
- long start = counter.getStart();
- for (int i = 0; i < 100; i++)
- {
- counter.registerEvent(i, start + i);
- }
- assertEquals(99 * 50, counter.getTotal()); // cf. Gauss
- }
-
- /**
- * Test totals add up correctly even when messages are delivered
- * out-of-order.
- */
- public void testTotalOutOfOrder()
- {
- StatisticsCounter counter = new StatisticsCounter("test", 1000L);
- long start = counter.getStart();
- assertEquals(0, counter.getTotal());
- counter.registerEvent(10, start + 2500);
- assertEquals(10, counter.getTotal());
- counter.registerEvent(20, start + 1500);
- assertEquals(30, counter.getTotal());
- counter.registerEvent(10, start + 500);
- assertEquals(40, counter.getTotal());
- }
-
- /**
- * Test that the peak rate is reported correctly.
- */
- public void testPeak() throws Exception
- {
- StatisticsCounter counter = new StatisticsCounter("test", 1000L);
- long start = counter.getStart();
- assertEquals(0.0, counter.getPeak());
- Thread.sleep(500);
- counter.registerEvent(1000, start + 500);
- Thread.sleep(1000);
- assertEquals(1000.0, counter.getPeak());
- counter.registerEvent(2000, start + 1500);
- Thread.sleep(1000);
- assertEquals(2000.0, counter.getPeak());
- counter.registerEvent(1000, start + 2500);
- Thread.sleep(1000);
- assertEquals(2000.0, counter.getPeak());
- }
-
- /**
- * Test that peak rate is reported correctly for out-of-order messages,
- * and the total is also unaffected.
- */
- public void testPeakOutOfOrder() throws Exception
- {
- StatisticsCounter counter = new StatisticsCounter("test", 1000L);
- long start = counter.getStart();
- assertEquals(0.0, counter.getPeak());
- counter.registerEvent(1000, start + 2500);
- Thread.sleep(1500);
- assertEquals(0.0, counter.getPeak());
- counter.registerEvent(2000, start + 1500);
- Thread.sleep(1000L);
- assertEquals(0.0, counter.getPeak());
- counter.registerEvent(1000, start + 500);
- Thread.sleep(1500);
- assertEquals(4000.0, counter.getPeak());
- Thread.sleep(2000);
- assertEquals(4000.0, counter.getPeak());
- counter.registerEvent(1000, start + 500);
- assertEquals(4000.0, counter.getPeak());
- Thread.sleep(2000);
- counter.registerEvent(1000);
- assertEquals(4000.0, counter.getPeak());
- assertEquals(6000, counter.getTotal());
- }
-
- /**
- * Test the current rate is generated correctly.
- */
- public void testRate() throws Exception
- {
- StatisticsCounter counter = new StatisticsCounter("test", 1000L);
- assertEquals(0.0, counter.getRate());
- Thread.sleep(500);
- counter.registerEvent(1000);
- Thread.sleep(1000);
- assertEquals(1000.0, counter.getRate());
- counter.registerEvent(2000);
- Thread.sleep(1000);
- assertEquals(2000.0, counter.getRate());
- counter.registerEvent(1000);
- Thread.sleep(1000);
- assertEquals(1000.0, counter.getRate());
- Thread.sleep(1000);
- assertEquals(0.0, counter.getRate());
- }
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/store/MessageStoreShutdownTest.java b/java/broker/src/test/java/org/apache/qpid/server/store/MessageStoreShutdownTest.java
deleted file mode 100644
index 6ca88d1796..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/store/MessageStoreShutdownTest.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.store;
-
-import org.apache.qpid.server.util.InternalBrokerBaseCase;
-import org.apache.qpid.server.protocol.InternalTestProtocolSession;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.AMQShortString;
-
-import java.util.List;
-
-public class MessageStoreShutdownTest extends InternalBrokerBaseCase
-{
-
- public void test()
- {
- subscribe(getSession(), getChannel(), getQueue());
-
- try
- {
- publishMessages(getSession(), getChannel(), 1);
- }
- catch (AMQException e)
- {
- e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
- fail(e.getMessage());
- }
-
- try
- {
- getRegistry().close();
- }
- catch (Exception e)
- {
- e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
- fail(e.getMessage());
- }
-
- assertTrue("Session should now be closed", getSession().isClosed());
-
-
- //Test attempting to modify the broker state after session has been closed.
-
- //The Message should have been removed from the unacked list.
-
- //Ack Messages
- List<InternalTestProtocolSession.DeliveryPair> list = getSession().getDelivers(getChannel().getChannelId(), new AMQShortString("sgen_1"), 1);
-
- InternalTestProtocolSession.DeliveryPair pair = list.get(0);
-
- try
- {
- // The message should now be requeued and so unable to ack it.
- getChannel().acknowledgeMessage(pair.getDeliveryTag(), false);
- }
- catch (AMQException e)
- {
- assertEquals("Incorrect exception thrown", "Single ack on delivery tag 1 not known for channel:1", e.getMessage());
- }
-
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/store/MessageStoreTest.java b/java/broker/src/test/java/org/apache/qpid/server/store/MessageStoreTest.java
deleted file mode 100644
index 62ceb68208..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/store/MessageStoreTest.java
+++ /dev/null
@@ -1,908 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.store;
-
-import 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;
-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.framing.amqp_8_0.BasicConsumeBodyImpl;
-import org.apache.qpid.server.binding.Binding;
-import org.apache.qpid.server.configuration.VirtualHostConfiguration;
-import org.apache.qpid.server.exchange.DirectExchange;
-import org.apache.qpid.server.exchange.Exchange;
-import org.apache.qpid.server.exchange.ExchangeRegistry;
-import org.apache.qpid.server.exchange.ExchangeType;
-import org.apache.qpid.server.exchange.TopicExchange;
-import org.apache.qpid.server.message.AMQMessage;
-import org.apache.qpid.server.message.MessageMetaData;
-import org.apache.qpid.server.queue.AMQPriorityQueue;
-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.ConflationQueue;
-import org.apache.qpid.server.queue.IncomingMessage;
-import org.apache.qpid.server.queue.QueueRegistry;
-import org.apache.qpid.server.queue.SimpleAMQQueue;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-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.util.FileUtils;
-
-/**
- * This tests the MessageStores by using the available interfaces.
- *
- * For persistent stores, it validates that Exchanges, Queues, Bindings and
- * Messages are persisted and recovered correctly.
- */
-public class MessageStoreTest extends InternalBrokerBaseCase
-{
- public static final int DEFAULT_PRIORTY_LEVEL = 5;
- 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");
-
- 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");
-
- 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");
-
- AMQShortString directRouting = new AMQShortString("MST-direct");
- AMQShortString topicRouting = new AMQShortString("MST-topic");
-
- AMQShortString queueOwner = new AMQShortString("MST");
-
- protected PropertiesConfiguration _config;
-
- public void setUp() throws Exception
- {
- super.setUp();
-
- String storePath = System.getProperty("QPID_WORK") + "/" + getName();
-
- _config = new PropertiesConfiguration();
- _config.addProperty("store.class", getTestProfileMessageStoreClassName());
- _config.addProperty("store.environment-path", storePath);
-
- cleanup(new File(storePath));
-
- reloadVirtualHost();
- }
-
- protected void reloadVirtualHost()
- {
- VirtualHost original = getVirtualHost();
-
- if (getVirtualHost() != null)
- {
- try
- {
- getVirtualHost().close();
- getVirtualHost().getApplicationRegistry().
- getVirtualHostRegistry().unregisterVirtualHost(getVirtualHost());
- }
- catch (Exception e)
- {
- fail(e.getMessage());
- }
- }
-
- try
- {
- setVirtualHost(ApplicationRegistry.getInstance().createVirtualHost(new VirtualHostConfiguration(getClass().getName(), _config)));
- }
- catch (Exception e)
- {
- e.printStackTrace();
- fail(e.getMessage());
- }
-
- assertTrue("Virtualhost has not changed, reload was not successful", original != getVirtualHost());
- }
-
- /**
- * Old MessageStoreTest segment which runs against both persistent and non-persistent stores
- * creating queues, exchanges and bindings and then verifying message delivery to them.
- */
- public void testQueueExchangeAndBindingCreation() throws Exception
- {
- assertEquals("Should not be any existing queues", 0, getVirtualHost().getQueueRegistry().getQueues().size());
-
- createAllQueues();
- createAllTopicQueues();
-
- //Register Non-Durable DirectExchange
- Exchange nonDurableExchange = createExchange(DirectExchange.TYPE, nonDurableExchangeName, false);
- bindAllQueuesToExchange(nonDurableExchange, directRouting);
-
- //Register DirectExchange
- Exchange directExchange = createExchange(DirectExchange.TYPE, directExchangeName, true);
- bindAllQueuesToExchange(directExchange, directRouting);
-
- //Register TopicExchange
- Exchange topicExchange = createExchange(TopicExchange.TYPE, topicExchangeName, true);
- bindAllTopicQueuesToExchange(topicExchange, topicRouting);
-
- //Send Message To NonDurable direct Exchange = persistent
- sendMessageOnExchange(nonDurableExchange, directRouting, true);
- // and non-persistent
- sendMessageOnExchange(nonDurableExchange, directRouting, false);
-
- //Send Message To direct Exchange = persistent
- sendMessageOnExchange(directExchange, directRouting, true);
- // and non-persistent
- sendMessageOnExchange(directExchange, directRouting, false);
-
- //Send Message To topic Exchange = persistent
- sendMessageOnExchange(topicExchange, topicRouting, true);
- // and non-persistent
- sendMessageOnExchange(topicExchange, topicRouting, false);
-
- //Ensure all the Queues have four messages (one transient, one persistent) x 2 exchange routings
- validateMessageOnQueues(4, true);
- //Ensure all the topics have two messages (one transient, one persistent)
- validateMessageOnTopics(2, true);
-
- assertEquals("Not all queues correctly registered",
- 10, getVirtualHost().getQueueRegistry().getQueues().size());
- }
-
- /**
- * Tests message persistence by running the testQueueExchangeAndBindingCreation() method above
- * before reloading the virtual host and ensuring that the persistent messages were restored.
- *
- * More specific testing of message persistence is left to store-specific unit testing.
- */
- public void testMessagePersistence() throws Exception
- {
- testQueueExchangeAndBindingCreation();
-
- reloadVirtualHost();
-
- //Validate durable queues and subscriptions still have the persistent messages
- validateMessageOnQueues(2, false);
- validateMessageOnTopics(1, false);
- }
-
- /**
- * Tests message removal by running the testMessagePersistence() method above before
- * clearing the queues, reloading the virtual host, and ensuring that the persistent
- * messages were removed from the queues.
- */
- public void testMessageRemoval() throws Exception
- {
- testMessagePersistence();
-
- QueueRegistry queueRegistry = getVirtualHost().getQueueRegistry();
-
- assertEquals("Incorrect number of queues registered after recovery",
- 6, queueRegistry.getQueues().size());
-
- //clear the queue
- queueRegistry.getQueue(durableQueueName).clearQueue();
-
- //check the messages are gone
- validateMessageOnQueue(durableQueueName, 0);
-
- //reload and verify messages arent restored
- reloadVirtualHost();
-
- validateMessageOnQueue(durableQueueName, 0);
- }
-
- /**
- * Tests queue persistence by creating a selection of queues with differing properties, both
- * durable and non durable, and ensuring that following the recovery process the correct queues
- * are present and any property manipulations (eg queue exclusivity) are correctly recovered.
- */
- public void testQueuePersistence() throws Exception
- {
- assertEquals("Should not be any existing queues",
- 0, getVirtualHost().getQueueRegistry().getQueues().size());
-
- //create durable and non durable queues/topics
- createAllQueues();
- createAllTopicQueues();
-
- //reload the virtual host, prompting recovery of the queues/topics
- reloadVirtualHost();
-
- QueueRegistry queueRegistry = getVirtualHost().getQueueRegistry();
-
- assertEquals("Incorrect number of queues registered after recovery",
- 6, queueRegistry.getQueues().size());
-
- //Validate the non-Durable Queues were not recovered.
- assertNull("Non-Durable queue still registered:" + priorityQueueName,
- queueRegistry.getQueue(priorityQueueName));
- assertNull("Non-Durable queue still registered:" + queueName,
- queueRegistry.getQueue(queueName));
- assertNull("Non-Durable queue still registered:" + priorityTopicQueueName,
- queueRegistry.getQueue(priorityTopicQueueName));
- assertNull("Non-Durable queue still registered:" + topicQueueName,
- queueRegistry.getQueue(topicQueueName));
-
- //Validate normally expected properties of Queues/Topics
- validateDurableQueueProperties();
-
- //Update the durable exclusive queue's exclusivity and verify it is persisted and recovered correctly
- setQueueExclusivity(false);
- validateQueueExclusivityProperty(false);
-
- //Reload the Virtualhost to recover the queues again
- reloadVirtualHost();
-
- //verify the change was persisted and recovered correctly
- validateQueueExclusivityProperty(false);
- }
-
- /**
- * Tests queue removal by creating a durable queue, verifying it recovers, and
- * then removing it from the store, and ensuring that following the second reload
- * process it is not recovered.
- */
- public void testDurableQueueRemoval() throws Exception
- {
- //Register Durable Queue
- createQueue(durableQueueName, false, true, false, false);
-
- QueueRegistry queueRegistry = getVirtualHost().getQueueRegistry();
- assertEquals("Incorrect number of queues registered before recovery",
- 1, queueRegistry.getQueues().size());
-
- reloadVirtualHost();
-
- queueRegistry = getVirtualHost().getQueueRegistry();
- assertEquals("Incorrect number of queues registered after first recovery",
- 1, queueRegistry.getQueues().size());
-
- //test that removing the queue means it is not recovered next time
- getVirtualHost().getDurableConfigurationStore().removeQueue(queueRegistry.getQueue(durableQueueName));
-
- reloadVirtualHost();
-
- queueRegistry = getVirtualHost().getQueueRegistry();
- assertEquals("Incorrect number of queues registered after second recovery",
- 0, queueRegistry.getQueues().size());
- assertNull("Durable queue was not removed:" + durableQueueName,
- queueRegistry.getQueue(durableQueueName));
- }
-
- /**
- * Tests exchange persistence by creating a selection of exchanges, both durable
- * and non durable, and ensuring that following the recovery process the correct
- * durable exchanges are still present.
- */
- public void testExchangePersistence() throws Exception
- {
- int origExchangeCount = getVirtualHost().getExchangeRegistry().getExchangeNames().size();
-
- Map<AMQShortString, Exchange> oldExchanges = createExchanges();
-
- assertEquals("Incorrect number of exchanges registered before recovery",
- origExchangeCount + 3, getVirtualHost().getExchangeRegistry().getExchangeNames().size());
-
- reloadVirtualHost();
-
- //verify the exchanges present after recovery
- validateExchanges(origExchangeCount, oldExchanges);
- }
-
- /**
- * Tests exchange removal by creating a durable exchange, verifying it recovers, and
- * then removing it from the store, and ensuring that following the second reload
- * process it is not recovered.
- */
- public void testDurableExchangeRemoval() throws Exception
- {
- int origExchangeCount = getVirtualHost().getExchangeRegistry().getExchangeNames().size();
-
- createExchange(DirectExchange.TYPE, directExchangeName, true);
-
- ExchangeRegistry exchangeRegistry = getVirtualHost().getExchangeRegistry();
- assertEquals("Incorrect number of exchanges registered before recovery",
- origExchangeCount + 1, exchangeRegistry.getExchangeNames().size());
-
- reloadVirtualHost();
-
- exchangeRegistry = getVirtualHost().getExchangeRegistry();
- assertEquals("Incorrect number of exchanges registered after first recovery",
- origExchangeCount + 1, exchangeRegistry.getExchangeNames().size());
-
- //test that removing the exchange means it is not recovered next time
- getVirtualHost().getDurableConfigurationStore().removeExchange(exchangeRegistry.getExchange(directExchangeName));
-
- reloadVirtualHost();
-
- exchangeRegistry = getVirtualHost().getExchangeRegistry();
- assertEquals("Incorrect number of exchanges registered after second recovery",
- origExchangeCount, exchangeRegistry.getExchangeNames().size());
- assertNull("Durable exchange was not removed:" + directExchangeName,
- exchangeRegistry.getExchange(directExchangeName));
- }
-
- /**
- * Tests binding persistence by creating a selection of queues and exchanges, both durable
- * and non durable, then adding bindings with and without selectors before reloading the
- * virtual host and verifying that following the recovery process the correct durable
- * bindings (those for durable queues to durable exchanges) are still present.
- */
- public void testBindingPersistence() throws Exception
- {
- int origExchangeCount = getVirtualHost().getExchangeRegistry().getExchangeNames().size();
-
- createAllQueues();
- createAllTopicQueues();
-
- Map<AMQShortString, Exchange> exchanges = createExchanges();
-
- Exchange nonDurableExchange = exchanges.get(nonDurableExchangeName);
- Exchange directExchange = exchanges.get(directExchangeName);
- Exchange topicExchange = exchanges.get(topicExchangeName);
-
- bindAllQueuesToExchange(nonDurableExchange, directRouting);
- bindAllQueuesToExchange(directExchange, directRouting);
- bindAllTopicQueuesToExchange(topicExchange, topicRouting);
-
- assertEquals("Incorrect number of exchanges registered before recovery",
- origExchangeCount + 3, getVirtualHost().getExchangeRegistry().getExchangeNames().size());
-
- reloadVirtualHost();
-
- validateExchanges(origExchangeCount, exchanges);
-
- validateBindingProperties();
- }
-
- /**
- * Tests binding removal by creating a durable exchange, and queue, binding them together,
- * recovering to verify the persistence, then removing it from the store, and ensuring
- * that following the second reload process it is not recovered.
- */
- public void testDurableBindingRemoval() throws Exception
- {
- QueueRegistry queueRegistry = getVirtualHost().getQueueRegistry();
-
- //create durable queue and exchange, bind them
- Exchange exch = createExchange(DirectExchange.TYPE, directExchangeName, true);
- createQueue(durableQueueName, false, true, false, false);
- bindQueueToExchange(exch, directRouting, queueRegistry.getQueue(durableQueueName), false, null);
-
- assertEquals("Incorrect number of bindings registered before recovery",
- 1, queueRegistry.getQueue(durableQueueName).getBindings().size());
-
- //verify binding is actually normally recovered
- reloadVirtualHost();
-
- queueRegistry = getVirtualHost().getQueueRegistry();
- assertEquals("Incorrect number of bindings registered after first recovery",
- 1, queueRegistry.getQueue(durableQueueName).getBindings().size());
-
- ExchangeRegistry exchangeRegistry = getVirtualHost().getExchangeRegistry();
- exch = exchangeRegistry.getExchange(directExchangeName);
- assertNotNull("Exchange was not recovered", exch);
-
- //remove the binding and verify result after recovery
- unbindQueueFromExchange(exch, directRouting, queueRegistry.getQueue(durableQueueName), false, null);
-
- reloadVirtualHost();
-
- queueRegistry = getVirtualHost().getQueueRegistry();
- assertEquals("Incorrect number of bindings registered after second recovery",
- 0, queueRegistry.getQueue(durableQueueName).getBindings().size());
- }
-
- /**
- * Validates that the durable exchanges are still present, the non durable exchange is not,
- * and that the new exchanges are not the same objects as the provided list (i.e. that the
- * reload actually generated new exchange objects)
- */
- private void validateExchanges(int originalNumExchanges, Map<AMQShortString, Exchange> oldExchanges)
- {
- ExchangeRegistry registry = getVirtualHost().getExchangeRegistry();
-
- assertTrue(directExchangeName + " exchange NOT reloaded",
- registry.getExchangeNames().contains(directExchangeName));
- assertTrue(topicExchangeName + " exchange NOT reloaded",
- registry.getExchangeNames().contains(topicExchangeName));
- assertTrue(nonDurableExchangeName + " exchange reloaded",
- !registry.getExchangeNames().contains(nonDurableExchangeName));
-
- //check the old exchange objects are not the same as the new exchanges
- assertTrue(directExchangeName + " exchange NOT reloaded",
- registry.getExchange(directExchangeName) != oldExchanges.get(directExchangeName));
- assertTrue(topicExchangeName + " exchange NOT reloaded",
- registry.getExchange(topicExchangeName) != oldExchanges.get(topicExchangeName));
-
- // There should only be the original exchanges + our 2 recovered durable exchanges
- assertEquals("Incorrect number of exchanges available",
- originalNumExchanges + 2, registry.getExchangeNames().size());
- }
-
- /** Validates the Durable queues and their properties are as expected following recovery */
- private void validateBindingProperties()
- {
- QueueRegistry queueRegistry = getVirtualHost().getQueueRegistry();
-
- assertEquals("Incorrect number of (durable) queues following recovery", 6, queueRegistry.getQueues().size());
-
- validateBindingProperties(queueRegistry.getQueue(durablePriorityQueueName).getBindings(), false);
- validateBindingProperties(queueRegistry.getQueue(durablePriorityTopicQueueName).getBindings(), true);
- validateBindingProperties(queueRegistry.getQueue(durableQueueName).getBindings(), false);
- validateBindingProperties(queueRegistry.getQueue(durableTopicQueueName).getBindings(), true);
- validateBindingProperties(queueRegistry.getQueue(durableExclusiveQueueName).getBindings(), false);
- }
-
- /**
- * Validate that each queue is bound only once following recovery (i.e. that bindings for non durable
- * queues or to non durable exchanges are not recovered), and if a selector should be present
- * that it is and contains the correct value
- *
- * @param bindings the set of bindings to validate
- * @param useSelectors if set, check the binding has a JMS_SELECTOR argument and the correct value for it
- */
- private void validateBindingProperties(List<Binding> bindings, boolean useSelectors)
- {
- assertEquals("Each queue should only be bound once.", 1, bindings.size());
-
- Binding binding = bindings.get(0);
-
- if (useSelectors)
- {
- assertTrue("Binding does not contain a Selector argument.",
- binding.getArguments().containsKey(AMQPFilterTypes.JMS_SELECTOR.getValue()));
- assertEquals("The binding selector argument is incorrect", SELECTOR_VALUE,
- binding.getArguments().get(AMQPFilterTypes.JMS_SELECTOR.getValue()).toString());
- }
- }
-
- private void setQueueExclusivity(boolean exclusive) throws AMQException
- {
- QueueRegistry queueRegistry = getVirtualHost().getQueueRegistry();
-
- AMQQueue queue = queueRegistry.getQueue(durableExclusiveQueueName);
-
- queue.setExclusive(exclusive);
- }
-
- private void validateQueueExclusivityProperty(boolean expected)
- {
- QueueRegistry queueRegistry = getVirtualHost().getQueueRegistry();
-
- AMQQueue queue = queueRegistry.getQueue(durableExclusiveQueueName);
-
- assertEquals("Queue exclusivity was incorrect", queue.isExclusive(), expected);
- }
-
-
- private void validateDurableQueueProperties()
- {
- QueueRegistry queueRegistry = getVirtualHost().getQueueRegistry();
-
- validateQueueProperties(queueRegistry.getQueue(durablePriorityQueueName), true, true, false, false);
- validateQueueProperties(queueRegistry.getQueue(durablePriorityTopicQueueName), true, true, false, false);
- validateQueueProperties(queueRegistry.getQueue(durableQueueName), false, true, false, false);
- validateQueueProperties(queueRegistry.getQueue(durableTopicQueueName), false, true, false, false);
- validateQueueProperties(queueRegistry.getQueue(durableExclusiveQueueName), false, true, true, false);
- validateQueueProperties(queueRegistry.getQueue(durableLastValueQueueName), false, true, true, true);
- }
-
- private void validateQueueProperties(AMQQueue queue, boolean usePriority, boolean durable, boolean exclusive, boolean lastValueQueue)
- {
- if(usePriority || lastValueQueue)
- {
- assertNotSame("Queues cant be both Priority and LastValue based", usePriority, lastValueQueue);
- }
-
- if (usePriority)
- {
- assertEquals("Queue is no longer a Priority Queue", AMQPriorityQueue.class, queue.getClass());
- assertEquals("Priority Queue does not have set priorities",
- DEFAULT_PRIORTY_LEVEL, ((AMQPriorityQueue) queue).getPriorities());
- }
- else if (lastValueQueue)
- {
- assertEquals("Queue is no longer a LastValue Queue", ConflationQueue.class, queue.getClass());
- assertEquals("LastValue Queue Key has changed", LVQ_KEY, ((ConflationQueue) queue).getConflationKey());
- }
- else
- {
- assertEquals("Queue is not 'simple'", SimpleAMQQueue.class, queue.getClass());
- }
-
- assertEquals("Queue owner is not as expected", queueOwner, queue.getOwner());
- assertEquals("Queue durability is not as expected", durable, queue.isDurable());
- assertEquals("Queue exclusivity is not as expected", exclusive, queue.isExclusive());
- }
-
- /**
- * Delete the Store Environment path
- *
- * @param configuration The configuration that contains the store environment path.
- */
- private void cleanup(File environmentPath)
- {
- if (environmentPath.exists())
- {
- FileUtils.delete(environmentPath, true);
- }
- }
-
- private void sendMessageOnExchange(Exchange exchange, AMQShortString routingKey, boolean deliveryMode)
- {
- //Set MessagePersistence
- BasicContentHeaderProperties properties = new BasicContentHeaderProperties();
- properties.setDeliveryMode(deliveryMode ? Integer.valueOf(2).byteValue() : Integer.valueOf(1).byteValue());
- FieldTable headers = properties.getHeaders();
- headers.setString("Test", "MST");
- properties.setHeaders(headers);
-
- MessagePublishInfo messageInfo = new TestMessagePublishInfo(exchange, false, false, routingKey);
-
- final IncomingMessage currentMessage;
-
-
- currentMessage = new IncomingMessage(messageInfo);
-
- currentMessage.setExchange(exchange);
-
- ContentHeaderBody headerBody = new ContentHeaderBody();
- headerBody.classId = BasicConsumeBodyImpl.CLASS_ID;
- headerBody.bodySize = 0;
-
- headerBody.setProperties(properties);
-
- try
- {
- currentMessage.setContentHeaderBody(headerBody);
- }
- catch (AMQException e)
- {
- fail(e.getMessage());
- }
-
- currentMessage.setExpiration();
-
- MessageMetaData mmd = currentMessage.headersReceived();
- currentMessage.setStoredMessage(getVirtualHost().getMessageStore().addMessage(mmd));
- currentMessage.getStoredMessage().flushToStore();
- currentMessage.route();
-
-
- // check and deliver if header says body length is zero
- if (currentMessage.allContentReceived())
- {
- ServerTransaction trans = new AutoCommitTransaction(getVirtualHost().getMessageStore());
- final List<? extends BaseQueue> destinationQueues = currentMessage.getDestinationQueues();
- trans.enqueue(currentMessage.getDestinationQueues(), currentMessage, new ServerTransaction.Action() {
- public void postCommit()
- {
- try
- {
- AMQMessage message = new AMQMessage(currentMessage.getStoredMessage());
-
- for(BaseQueue queue : destinationQueues)
- {
- queue.enqueue(message);
- }
- }
- catch (AMQException e)
- {
- e.printStackTrace();
- }
- }
-
- public void onRollback()
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
- });
- }
- }
-
- private void createAllQueues()
- {
- //Register Durable Priority Queue
- createQueue(durablePriorityQueueName, true, true, false, false);
-
- //Register Durable Simple Queue
- createQueue(durableQueueName, false, true, false, false);
-
- //Register Durable Exclusive Simple Queue
- createQueue(durableExclusiveQueueName, false, true, true, false);
-
- //Register Durable LastValue Queue
- createQueue(durableLastValueQueueName, false, true, true, true);
-
- //Register NON-Durable Priority Queue
- createQueue(priorityQueueName, true, false, false, false);
-
- //Register NON-Durable Simple Queue
- createQueue(queueName, false, false, false, false);
- }
-
- private void createAllTopicQueues()
- {
- //Register Durable Priority Queue
- createQueue(durablePriorityTopicQueueName, true, true, false, false);
-
- //Register Durable Simple Queue
- createQueue(durableTopicQueueName, false, true, false, false);
-
- //Register NON-Durable Priority Queue
- createQueue(priorityTopicQueueName, true, false, false, false);
-
- //Register NON-Durable Simple Queue
- createQueue(topicQueueName, false, false, false, false);
- }
-
- private void createQueue(AMQShortString queueName, boolean usePriority, boolean durable, boolean exclusive, boolean lastValueQueue)
- {
-
- FieldTable queueArguments = null;
-
- if(usePriority || lastValueQueue)
- {
- assertNotSame("Queues cant be both Priority and LastValue based", usePriority, lastValueQueue);
- }
-
- if (usePriority)
- {
- queueArguments = new FieldTable();
- queueArguments.put(AMQQueueFactory.X_QPID_PRIORITIES, DEFAULT_PRIORTY_LEVEL);
- }
-
- if (lastValueQueue)
- {
- queueArguments = new FieldTable();
- queueArguments.put(new AMQShortString(AMQQueueFactory.QPID_LAST_VALUE_QUEUE_KEY), LVQ_KEY);
- }
-
- AMQQueue queue = null;
-
- //Ideally we would be able to use the QueueDeclareHandler here.
- try
- {
- queue = AMQQueueFactory.createAMQQueueImpl(queueName, durable, queueOwner, false, exclusive,
- getVirtualHost(), queueArguments);
-
- validateQueueProperties(queue, usePriority, durable, exclusive, lastValueQueue);
-
- if (queue.isDurable() && !queue.isAutoDelete())
- {
- getVirtualHost().getMessageStore().createQueue(queue, queueArguments);
- }
- }
- catch (AMQException e)
- {
- fail(e.getMessage());
- }
-
- getVirtualHost().getQueueRegistry().registerQueue(queue);
-
- }
-
- private Map<AMQShortString, Exchange> createExchanges()
- {
- Map<AMQShortString, Exchange> exchanges = new HashMap<AMQShortString, Exchange>();
-
- //Register non-durable DirectExchange
- exchanges.put(nonDurableExchangeName, createExchange(DirectExchange.TYPE, nonDurableExchangeName, false));
-
- //Register durable DirectExchange and TopicExchange
- exchanges.put(directExchangeName ,createExchange(DirectExchange.TYPE, directExchangeName, true));
- exchanges.put(topicExchangeName,createExchange(TopicExchange.TYPE, topicExchangeName, true));
-
- return exchanges;
- }
-
- private Exchange createExchange(ExchangeType<?> type, AMQShortString name, boolean durable)
- {
- Exchange exchange = null;
-
- try
- {
- exchange = type.newInstance(getVirtualHost(), name, durable, 0, false);
- }
- catch (AMQException e)
- {
- fail(e.getMessage());
- }
-
- try
- {
- getVirtualHost().getExchangeRegistry().registerExchange(exchange);
- if (durable)
- {
- getVirtualHost().getMessageStore().createExchange(exchange);
- }
- }
- catch (AMQException e)
- {
- fail(e.getMessage());
- }
- return exchange;
- }
-
- private void bindAllQueuesToExchange(Exchange exchange, AMQShortString routingKey)
- {
- FieldTable queueArguments = new FieldTable();
- queueArguments.put(AMQQueueFactory.X_QPID_PRIORITIES, DEFAULT_PRIORTY_LEVEL);
-
- QueueRegistry queueRegistry = getVirtualHost().getQueueRegistry();
-
- bindQueueToExchange(exchange, routingKey, queueRegistry.getQueue(durablePriorityQueueName), false, queueArguments);
- bindQueueToExchange(exchange, routingKey, queueRegistry.getQueue(durableQueueName), false, null);
- bindQueueToExchange(exchange, routingKey, queueRegistry.getQueue(priorityQueueName), false, queueArguments);
- bindQueueToExchange(exchange, routingKey, queueRegistry.getQueue(queueName), false, null);
- bindQueueToExchange(exchange, routingKey, queueRegistry.getQueue(durableExclusiveQueueName), false, null);
- }
-
- private void bindAllTopicQueuesToExchange(Exchange exchange, AMQShortString routingKey)
- {
- FieldTable queueArguments = new FieldTable();
- queueArguments.put(AMQQueueFactory.X_QPID_PRIORITIES, DEFAULT_PRIORTY_LEVEL);
-
- QueueRegistry queueRegistry = getVirtualHost().getQueueRegistry();
-
- bindQueueToExchange(exchange, routingKey, queueRegistry.getQueue(durablePriorityTopicQueueName), true, queueArguments);
- bindQueueToExchange(exchange, routingKey, queueRegistry.getQueue(durableTopicQueueName), true, null);
- bindQueueToExchange(exchange, routingKey, queueRegistry.getQueue(priorityTopicQueueName), true, queueArguments);
- bindQueueToExchange(exchange, routingKey, queueRegistry.getQueue(topicQueueName), true, null);
- }
-
-
- protected void bindQueueToExchange(Exchange exchange, AMQShortString routingKey, AMQQueue queue, boolean useSelector, FieldTable queueArguments)
- {
- FieldTable bindArguments = null;
-
- if (useSelector)
- {
- bindArguments = new FieldTable();
- bindArguments.put(AMQPFilterTypes.JMS_SELECTOR.getValue(), SELECTOR_VALUE );
- }
-
- try
- {
- getVirtualHost().getBindingFactory().addBinding(String.valueOf(routingKey), queue, exchange, FieldTable.convertToMap(bindArguments));
- }
- catch (Exception e)
- {
- fail(e.getMessage());
- }
- }
-
- protected void unbindQueueFromExchange(Exchange exchange, AMQShortString routingKey, AMQQueue queue, boolean useSelector, FieldTable queueArguments)
- {
- FieldTable bindArguments = null;
-
- if (useSelector)
- {
- bindArguments = new FieldTable();
- bindArguments.put(AMQPFilterTypes.JMS_SELECTOR.getValue(), SELECTOR_VALUE );
- }
-
- try
- {
- getVirtualHost().getBindingFactory().removeBinding(String.valueOf(routingKey), queue, exchange, FieldTable.convertToMap(bindArguments));
- }
- catch (Exception e)
- {
- fail(e.getMessage());
- }
- }
-
- private void validateMessageOnTopics(long messageCount, boolean allQueues)
- {
- validateMessageOnQueue(durablePriorityTopicQueueName, messageCount);
- validateMessageOnQueue(durableTopicQueueName, messageCount);
-
- if (allQueues)
- {
- validateMessageOnQueue(priorityTopicQueueName, messageCount);
- validateMessageOnQueue(topicQueueName, messageCount);
- }
- }
-
- private void validateMessageOnQueues(long messageCount, boolean allQueues)
- {
- validateMessageOnQueue(durablePriorityQueueName, messageCount);
- validateMessageOnQueue(durableQueueName, messageCount);
-
- if (allQueues)
- {
- validateMessageOnQueue(priorityQueueName, messageCount);
- validateMessageOnQueue(queueName, messageCount);
- }
- }
-
- private void validateMessageOnQueue(AMQShortString queueName, long messageCount)
- {
- AMQQueue queue = getVirtualHost().getQueueRegistry().getQueue(queueName);
-
- assertNotNull("Queue(" + queueName + ") not correctly registered:", queue);
-
- assertEquals("Incorrect Message count on queue:" + queueName, messageCount, queue.getMessageCount());
- }
-
- private class TestMessagePublishInfo implements MessagePublishInfo
- {
-
- Exchange _exchange;
- boolean _immediate;
- boolean _mandatory;
- AMQShortString _routingKey;
-
- TestMessagePublishInfo(Exchange exchange, boolean immediate, boolean mandatory, AMQShortString routingKey)
- {
- _exchange = exchange;
- _immediate = immediate;
- _mandatory = mandatory;
- _routingKey = routingKey;
- }
-
- public AMQShortString getExchange()
- {
- return _exchange.getNameShortString();
- }
-
- public void setExchange(AMQShortString exchange)
- {
- //no-op
- }
-
- public boolean isImmediate()
- {
- return _immediate;
- }
-
- public boolean isMandatory()
- {
- return _mandatory;
- }
-
- public AMQShortString getRoutingKey()
- {
- return _routingKey;
- }
- }
-} \ No newline at end of file
diff --git a/java/broker/src/test/java/org/apache/qpid/server/store/ReferenceCountingTest.java b/java/broker/src/test/java/org/apache/qpid/server/store/ReferenceCountingTest.java
deleted file mode 100644
index 2d41eb9899..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/store/ReferenceCountingTest.java
+++ /dev/null
@@ -1,163 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.store;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.BasicContentHeaderProperties;
-import org.apache.qpid.framing.ContentHeaderBody;
-import org.apache.qpid.framing.abstraction.MessagePublishInfo;
-import org.apache.qpid.server.message.AMQMessage;
-import org.apache.qpid.server.message.MessageMetaData;
-import org.apache.qpid.test.utils.QpidTestCase;
-
-/**
- * Tests that reference counting works correctly with AMQMessage and the message store
- */
-public class ReferenceCountingTest extends QpidTestCase
-{
- private TestMemoryMessageStore _store;
-
-
- protected void setUp() throws Exception
- {
- _store = new TestMemoryMessageStore();
- }
-
- /**
- * Check that when the reference count is decremented the message removes itself from the store
- */
- public void testMessageGetsRemoved() throws AMQException
- {
- ContentHeaderBody chb = createPersistentContentHeader();
-
- MessagePublishInfo info = new MessagePublishInfo()
- {
-
- public AMQShortString getExchange()
- {
- return null;
- }
-
- public void setExchange(AMQShortString exchange)
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean isImmediate()
- {
- return false;
- }
-
- public boolean isMandatory()
- {
- return false;
- }
-
- public AMQShortString getRoutingKey()
- {
- return null;
- }
- };
-
-
-
- MessageMetaData mmd = new MessageMetaData(info, chb, 0);
- StoredMessage storedMessage = _store.addMessage(mmd);
-
-
- AMQMessage message = new AMQMessage(storedMessage);
-
- message = message.takeReference();
-
- // we call routing complete to set up the handle
- // message.routingComplete(_store, _storeContext, new MessageHandleFactory());
-
-
- assertEquals(1, _store.getMessageCount());
- message.decrementReference();
- assertEquals(0, _store.getMessageCount());
- }
-
- private ContentHeaderBody createPersistentContentHeader()
- {
- ContentHeaderBody chb = new ContentHeaderBody();
- BasicContentHeaderProperties bchp = new BasicContentHeaderProperties();
- bchp.setDeliveryMode((byte)2);
- chb.setProperties(bchp);
- return chb;
- }
-
- public void testMessageRemains() throws AMQException
- {
-
- MessagePublishInfo info = new MessagePublishInfo()
- {
-
- public AMQShortString getExchange()
- {
- return null;
- }
-
- public void setExchange(AMQShortString exchange)
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean isImmediate()
- {
- return false;
- }
-
- public boolean isMandatory()
- {
- return false;
- }
-
- public AMQShortString getRoutingKey()
- {
- return null;
- }
- };
-
- final ContentHeaderBody chb = createPersistentContentHeader();
-
- MessageMetaData mmd = new MessageMetaData(info, chb, 0);
- StoredMessage storedMessage = _store.addMessage(mmd);
-
- AMQMessage message = new AMQMessage(storedMessage);
-
-
- message = message.takeReference();
- // we call routing complete to set up the handle
- // message.routingComplete(_store, _storeContext, new MessageHandleFactory());
-
- assertEquals(1, _store.getMessageCount());
- message = message.takeReference();
- message.decrementReference();
- assertEquals(1, _store.getMessageCount());
- }
-
- public static junit.framework.Test suite()
- {
- return new junit.framework.TestSuite(ReferenceCountingTest.class);
- }
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/store/SkeletonMessageStore.java b/java/broker/src/test/java/org/apache/qpid/server/store/SkeletonMessageStore.java
deleted file mode 100644
index 5ff84557d8..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/store/SkeletonMessageStore.java
+++ /dev/null
@@ -1,226 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.store;
-
-import org.apache.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.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;
-
-/**
- * A message store that does nothing. Designed to be used in tests that do not want to use any message store
- * functionality.
- */
-public class SkeletonMessageStore implements MessageStore
-{
- private final AtomicLong _messageId = new AtomicLong(1);
-
- public void configure(String base, Configuration config) throws Exception
- {
- }
-
- public void configureConfigStore(String name,
- ConfigurationRecoveryHandler recoveryHandler,
- Configuration config,
- LogSubject logSubject) throws Exception
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void configureMessageStore(String name,
- MessageStoreRecoveryHandler recoveryHandler,
- Configuration config,
- LogSubject logSubject) throws Exception
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void close() throws Exception
- {
- }
-
- public <M extends StorableMessageMetaData> StoredMessage<M> addMessage(M metaData)
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void removeMessage(Long messageId)
- {
- }
-
- public void createExchange(Exchange exchange) throws AMQStoreException
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void removeExchange(Exchange exchange) throws AMQStoreException
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void bindQueue(Exchange exchange, AMQShortString routingKey, AMQQueue queue, FieldTable args) throws AMQStoreException
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void unbindQueue(Exchange exchange, AMQShortString routingKey, AMQQueue queue, FieldTable args) throws AMQStoreException
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void createQueue(AMQQueue queue) throws AMQStoreException
- {
- }
-
- public void createQueue(AMQQueue queue, FieldTable arguments) throws AMQStoreException
- {
- }
-
-
-
-
- public List<AMQQueue> createQueues() throws AMQException
- {
- return null;
- }
-
- public Long getNewMessageId()
- {
- return _messageId.getAndIncrement();
- }
-
- public void storeContentBodyChunk(
- Long messageId,
- int index,
- ContentChunk contentBody,
- boolean lastContentBody) throws AMQException
- {
-
- }
-
- public void storeMessageMetaData(Long messageId, MessageMetaData messageMetaData) throws AMQException
- {
-
- }
-
- public MessageMetaData getMessageMetaData(Long messageId) throws AMQException
- {
- return null;
- }
-
- public ContentChunk getContentBodyChunk(Long messageId, int index) throws AMQException
- {
- return null;
- }
-
- public boolean isPersistent()
- {
- return false;
- }
-
- public void storeMessageHeader(Long messageNumber, ServerMessage message)
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void storeContent(Long messageNumber, long offset, ByteBuffer body)
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public ServerMessage getMessage(Long messageNumber)
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void removeQueue(final AMQQueue queue) throws AMQStoreException
- {
-
- }
-
- public void configureTransactionLog(String name,
- TransactionLogRecoveryHandler recoveryHandler,
- Configuration storeConfiguration,
- LogSubject logSubject) throws Exception
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public Transaction newTransaction()
- {
- return new Transaction()
- {
-
- public void enqueueMessage(TransactionLogResource queue, Long messageId) throws AMQStoreException
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void dequeueMessage(TransactionLogResource queue, Long messageId) throws AMQStoreException
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void commitTran() throws AMQStoreException
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public StoreFuture commitTranAsync() throws AMQStoreException
- {
- return new StoreFuture()
- {
- public boolean isComplete()
- {
- return true;
- }
-
- public void waitForCompletion()
- {
-
- }
- };
- }
-
- public void abortTran() throws AMQStoreException
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
- };
- }
-
- public void updateQueue(AMQQueue queue) throws AMQStoreException
- {
-
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/store/TestMemoryMessageStore.java b/java/broker/src/test/java/org/apache/qpid/server/store/TestMemoryMessageStore.java
deleted file mode 100644
index 4dea13d391..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/store/TestMemoryMessageStore.java
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.store;
-
-import org.apache.qpid.server.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;
-
-/**
- * Adds some extra methods to the memory message store for testing purposes.
- */
-public class TestMemoryMessageStore extends MemoryMessageStore
-{
- private AtomicInteger _messageCount = new AtomicInteger(0);
-
-
- public TestMemoryMessageStore()
- {
- }
-
- @Override
- public StoredMessage addMessage(StorableMessageMetaData metaData)
- {
- return new TestableStoredMessage(super.addMessage(metaData));
- }
-
- public int getMessageCount()
- {
- return _messageCount.get();
- }
-
- private class TestableStoredMessage implements StoredMessage
- {
- private final StoredMessage _storedMessage;
-
- public TestableStoredMessage(StoredMessage storedMessage)
- {
- _messageCount.incrementAndGet();
- _storedMessage = storedMessage;
- }
-
- public StorableMessageMetaData getMetaData()
- {
- return _storedMessage.getMetaData();
- }
-
- public long getMessageNumber()
- {
- return _storedMessage.getMessageNumber();
- }
-
- public void addContent(int offsetInMessage, ByteBuffer src)
- {
- _storedMessage.addContent(offsetInMessage, src);
- }
-
- public int getContent(int offsetInMessage, ByteBuffer dst)
- {
- return _storedMessage.getContent(offsetInMessage, dst);
- }
-
- public StoreFuture flushToStore()
- {
- return _storedMessage.flushToStore();
- }
-
- public void remove()
- {
- _storedMessage.remove();
- _messageCount.decrementAndGet();
- }
-
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/store/TestableMemoryMessageStore.java b/java/broker/src/test/java/org/apache/qpid/server/store/TestableMemoryMessageStore.java
deleted file mode 100644
index 3593297a05..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/store/TestableMemoryMessageStore.java
+++ /dev/null
@@ -1,157 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.store;
-
-import java.nio.ByteBuffer;
-import java.util.HashMap;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import org.apache.qpid.AMQStoreException;
-import org.apache.qpid.server.queue.AMQQueue;
-
-/**
- * Adds some extra methods to the memory message store for testing purposes.
- */
-public class TestableMemoryMessageStore extends MemoryMessageStore
-{
-
- MemoryMessageStore _mms = null;
- private HashMap<Long, AMQQueue> _messages = new HashMap<Long, AMQQueue>();
- private AtomicInteger _messageCount = new AtomicInteger(0);
-
- public TestableMemoryMessageStore(MemoryMessageStore mms)
- {
- _mms = mms;
- }
-
- public TestableMemoryMessageStore()
- {
-
- }
-
- @Override
- public void close() throws Exception
- {
- // Not required to do anything
- }
-
- @Override
- public StoredMessage addMessage(StorableMessageMetaData metaData)
- {
- return new TestableStoredMessage(super.addMessage(metaData));
- }
-
- public int getMessageCount()
- {
- return _messageCount.get();
- }
-
- private class TestableTransaction implements Transaction
- {
- public void enqueueMessage(TransactionLogResource queue, Long messageId) throws AMQStoreException
- {
- getMessages().put(messageId, (AMQQueue)queue);
- }
-
- public void dequeueMessage(TransactionLogResource queue, Long messageId) throws AMQStoreException
- {
- getMessages().remove(messageId);
- }
-
- public void commitTran() throws AMQStoreException
- {
- }
-
- public StoreFuture commitTranAsync() throws AMQStoreException
- {
- return new StoreFuture()
- {
- public boolean isComplete()
- {
- return true;
- }
-
- public void waitForCompletion()
- {
-
- }
- };
- }
-
- public void abortTran() throws AMQStoreException
- {
- }
- }
-
-
- @Override
- public Transaction newTransaction()
- {
- return new TestableTransaction();
- }
-
- public HashMap<Long, AMQQueue> getMessages()
- {
- return _messages;
- }
-
- private class TestableStoredMessage implements StoredMessage
- {
- private final StoredMessage _storedMessage;
-
- public TestableStoredMessage(StoredMessage storedMessage)
- {
- _messageCount.incrementAndGet();
- _storedMessage = storedMessage;
- }
-
- public StorableMessageMetaData getMetaData()
- {
- return _storedMessage.getMetaData();
- }
-
- public long getMessageNumber()
- {
- return _storedMessage.getMessageNumber();
- }
-
- public void addContent(int offsetInMessage, ByteBuffer src)
- {
- _storedMessage.addContent(offsetInMessage, src);
- }
-
- public int getContent(int offsetInMessage, ByteBuffer dst)
- {
- return _storedMessage.getContent(offsetInMessage, dst);
- }
-
- public StoreFuture flushToStore()
- {
- return _storedMessage.flushToStore();
- }
-
- public void remove()
- {
- _storedMessage.remove();
- _messageCount.decrementAndGet();
- }
- }
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/subscription/MockSubscription.java b/java/broker/src/test/java/org/apache/qpid/server/subscription/MockSubscription.java
deleted file mode 100644
index 6fbc627d8c..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/subscription/MockSubscription.java
+++ /dev/null
@@ -1,262 +0,0 @@
-package org.apache.qpid.server.subscription;
-
-/*
-*
-* 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 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;
-import org.apache.qpid.server.logging.LogActor;
-import org.apache.qpid.server.queue.AMQQueue;
-import org.apache.qpid.server.queue.QueueEntry;
-import org.apache.qpid.server.queue.QueueEntry.SubscriptionAcquiredState;
-
-public class MockSubscription implements Subscription
-{
-
- private boolean _closed = false;
- private AMQShortString tag = new AMQShortString("mocktag");
- private AMQQueue queue = null;
- private StateListener _listener = null;
- private AMQQueue.Context _queueContext = null;
- private State _state = State.ACTIVE;
- private ArrayList<QueueEntry> messages = new ArrayList<QueueEntry>();
- private final Lock _stateChangeLock = new ReentrantLock();
- private List<QueueEntry> _acceptEntries = null;
-
- private final QueueEntry.SubscriptionAcquiredState _owningState = new QueueEntry.SubscriptionAcquiredState(this);
- private final QueueEntry.SubscriptionAssignedState _assignedState = new QueueEntry.SubscriptionAssignedState(this);
-
-
- private static final AtomicLong idGenerator = new AtomicLong(0);
- // Create a simple ID that increments for ever new Subscription
- private final long _subscriptionID = idGenerator.getAndIncrement();
-
- public MockSubscription()
- {
- }
-
- public MockSubscription(List<QueueEntry> acceptEntries)
- {
- _acceptEntries = acceptEntries;
- }
-
- public void close()
- {
- _closed = true;
- if (_listener != null)
- {
- _listener.stateChange(this, _state, State.CLOSED);
- }
- _state = State.CLOSED;
- }
-
- public boolean filtersMessages()
- {
- return false;
- }
-
- public AMQChannel getChannel()
- {
- return null;
- }
-
- public AMQShortString getConsumerTag()
- {
- return tag;
- }
-
- public long getSubscriptionID()
- {
- return _subscriptionID;
- }
-
- public AMQQueue.Context getQueueContext()
- {
- return _queueContext;
- }
-
- public SubscriptionAcquiredState getOwningState()
- {
- return _owningState;
- }
-
- public QueueEntry.SubscriptionAssignedState getAssignedState()
- {
- return _assignedState;
- }
-
- public LogActor getLogActor()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean isTransient()
- {
- return false;
- }
-
- public AMQQueue getQueue()
- {
- return queue;
- }
-
- public void getSendLock()
- {
- _stateChangeLock.lock();
- }
-
- public boolean hasInterest(QueueEntry entry)
- {
- if(_acceptEntries != null)
- {
- //simulate selector behaviour, only signal
- //interest in the dictated queue entries
- return _acceptEntries.contains(entry);
- }
-
- return true;
- }
-
- public boolean isActive()
- {
- return true;
- }
-
- public void confirmAutoClose()
- {
-
- }
-
- public void set(String key, Object value)
- {
- }
-
- public Object get(String key)
- {
- return null;
- }
-
- public boolean isAutoClose()
- {
- return false;
- }
-
- public boolean isBrowser()
- {
- return false;
- }
-
- public boolean isClosed()
- {
- return _closed;
- }
-
- public boolean acquires()
- {
- return true;
- }
-
- public boolean seesRequeues()
- {
- return true;
- }
-
- public boolean isSuspended()
- {
- return false;
- }
-
- public void queueDeleted(AMQQueue queue)
- {
- }
-
- public void releaseSendLock()
- {
- _stateChangeLock.unlock();
- }
-
- public void resend(QueueEntry entry) throws AMQException
- {
- }
-
- public void onDequeue(QueueEntry queueEntry)
- {
- }
-
- public void restoreCredit(QueueEntry queueEntry)
- {
- }
-
- public void send(QueueEntry entry) throws AMQException
- {
- if (messages.contains(entry))
- {
- entry.setRedelivered();
- }
- messages.add(entry);
- }
-
- public void setQueueContext(AMQQueue.Context queueContext)
- {
- _queueContext = queueContext;
- }
-
- public void setQueue(AMQQueue queue, boolean exclusive)
- {
- this.queue = queue;
- }
-
- public void setNoLocal(boolean noLocal)
- {
- }
-
- public void setStateListener(StateListener listener)
- {
- this._listener = listener;
- }
-
- public State getState()
- {
- return _state;
- }
-
- public boolean wouldSuspend(QueueEntry msg)
- {
- return false;
- }
-
- public ArrayList<QueueEntry> getMessages()
- {
- return messages;
- }
-
- public boolean isSessionTransactional()
- {
- return false;
- }
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/subscription/QueueBrowserUsesNoAckTest.java b/java/broker/src/test/java/org/apache/qpid/server/subscription/QueueBrowserUsesNoAckTest.java
deleted file mode 100644
index b315a79b33..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/subscription/QueueBrowserUsesNoAckTest.java
+++ /dev/null
@@ -1,77 +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.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 java.util.List;
-
-public class QueueBrowserUsesNoAckTest extends InternalBrokerBaseCase
-{
-
- public void testQueueBrowserUsesNoAck() throws AMQException
- {
- int sendMessageCount = 2;
- int prefetch = 1;
-
- //Check store is empty
- checkStoreContents(0);
-
- //Send required messsages to the queue
- publishMessages(getSession(), getChannel(), sendMessageCount);
-
- //Ensure they are stored
- checkStoreContents(sendMessageCount);
-
- //Check that there are no unacked messages
- assertEquals("Channel should have no unacked msgs ", 0,
- getChannel().getUnacknowledgedMessageMap().size());
-
- //Set the prefetch on the session to be less than the sent messages
- getChannel().setCredit(0, prefetch);
-
- //browse the queue
- AMQShortString browser = browse(getChannel(), getQueue());
-
- getQueue().deliverAsync();
-
- //Wait for messages to fill the prefetch
- getSession().awaitDelivery(prefetch);
-
- //Get those messages
- List<InternalTestProtocolSession.DeliveryPair> messages =
- getSession().getDelivers(getChannel().getChannelId(), browser,
- prefetch);
-
- //Ensure we recevied the prefetched messages
- assertEquals(prefetch, messages.size());
-
- //Check the process didn't suspend the subscription as this would
- // indicate we are using the prefetch credit. i.e. using acks not No-Ack
- assertTrue("The subscription has been suspended",
- !getChannel().getSubscription(browser).getState()
- .equals(Subscription.State.SUSPENDED));
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/txn/AutoCommitTransactionTest.java b/java/broker/src/test/java/org/apache/qpid/server/txn/AutoCommitTransactionTest.java
deleted file mode 100644
index 9afed49922..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/txn/AutoCommitTransactionTest.java
+++ /dev/null
@@ -1,442 +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.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;
-import org.apache.qpid.server.queue.MockQueueEntry;
-import org.apache.qpid.server.queue.QueueEntry;
-import org.apache.qpid.server.store.TransactionLog;
-import org.apache.qpid.server.txn.MockStoreTransaction.TransactionState;
-import org.apache.qpid.test.utils.QpidTestCase;
-
-/**
- * A unit test ensuring that AutoCommitTransaction creates a separate transaction for
- * each dequeue/enqueue operation that involves enlistable messages. Verifies
- * that the transaction is properly committed (or rolled-back in the case of exception),
- * and that post transaction actions are correctly fired.
- *
- */
-public class AutoCommitTransactionTest extends QpidTestCase
-{
- private ServerTransaction _transaction = null; // Class under test
-
- private TransactionLog _transactionLog;
- private AMQQueue _queue;
- private List<AMQQueue> _queues;
- private Collection<QueueEntry> _queueEntries;
- private ServerMessage _message;
- private MockAction _action;
- private MockStoreTransaction _storeTransaction;
-
-
- @Override
- protected void setUp() throws Exception
- {
- super.setUp();
-
- _storeTransaction = createTestStoreTransaction(false);
- _transactionLog = MockStoreTransaction.createTestTransactionLog(_storeTransaction);
- _action = new MockAction();
-
- _transaction = new AutoCommitTransaction(_transactionLog);
- }
-
- /**
- * Tests the enqueue of a non persistent message to a single non durable queue.
- * Asserts that a store transaction has not been started and commit action fired.
- */
- public void testEnqueueToNonDurableQueueOfNonPersistentMessage() throws Exception
- {
- _message = createTestMessage(false);
- _queue = createTestAMQQueue(false);
-
- _transaction.enqueue(_queue, _message, _action);
-
- assertEquals("Enqueue of non-persistent message must not cause message to be enqueued", 0, _storeTransaction.getNumberOfEnqueuedMessages());
- assertEquals("Unexpected transaction state", TransactionState.NOT_STARTED, _storeTransaction.getState());
- assertFalse("Rollback action must not be fired", _action.isRollbackActionFired());
- assertTrue("Post commit action must be fired", _action.isPostCommitActionFired());
-
- }
-
- /**
- * Tests the enqueue of a persistent message to a durable queue.
- * Asserts that a store transaction has been committed and commit action fired.
- */
- public void testEnqueueToDurableQueueOfPersistentMessage() throws Exception
- {
- _message = createTestMessage(true);
- _queue = createTestAMQQueue(true);
-
- _transaction.enqueue(_queue, _message, _action);
-
- assertEquals("Enqueue of persistent message to durable queue must cause message to be enqueued", 1, _storeTransaction.getNumberOfEnqueuedMessages());
- assertEquals("Unexpected transaction state", TransactionState.COMMITTED, _storeTransaction.getState());
- assertFalse("Rollback action must not be fired", _action.isRollbackActionFired());
- assertTrue("Post commit action must be fired", _action.isPostCommitActionFired());
- }
-
- /**
- * Tests the case where the store operation throws an exception.
- * Asserts that the transaction is aborted and rollback action is fired.
- */
- public void testStoreEnqueueCausesException() throws Exception
- {
- _message = createTestMessage(true);
- _queue = createTestAMQQueue(true);
-
- _storeTransaction = createTestStoreTransaction(true);
- _transactionLog = MockStoreTransaction.createTestTransactionLog(_storeTransaction);
- _transaction = new AutoCommitTransaction(_transactionLog);
-
- try
- {
- _transaction.enqueue(_queue, _message, _action);
- fail("Exception not thrown");
- }
- catch (RuntimeException re)
- {
- // PASS
- }
-
- assertEquals("Unexpected transaction state", TransactionState.ABORTED, _storeTransaction.getState());
- assertTrue("Rollback action must be fired", _action.isRollbackActionFired());
- assertFalse("Post commit action must be fired", _action.isPostCommitActionFired());
- }
-
- /**
- * Tests the enqueue of a non persistent message to a many non durable queues.
- * Asserts that a store transaction has not been started and post commit action fired.
- */
- public void testEnqueueToManyNonDurableQueuesOfNonPersistentMessage() throws Exception
- {
- _message = createTestMessage(false);
- _queues = createTestBaseQueues(new boolean[] {false, false, false});
-
- _transaction.enqueue(_queues, _message, _action);
-
- assertEquals("Enqueue of non-persistent message must not cause message to be enqueued", 0, _storeTransaction.getNumberOfEnqueuedMessages());
- assertEquals("Unexpected transaction state", TransactionState.NOT_STARTED, _storeTransaction.getState());
- assertFalse("Rollback action must not be fired", _action.isRollbackActionFired());
- assertTrue("Post commit action must be fired", _action.isPostCommitActionFired());
-
- }
-
-
- /**
- * Tests the enqueue of a persistent message to a many non durable queues.
- * Asserts that a store transaction has not been started and post commit action
- * fired.
- */
- public void testEnqueueToManyNonDurableQueuesOfPersistentMessage() throws Exception
- {
- _message = createTestMessage(true);
- _queues = createTestBaseQueues(new boolean[] {false, false, false});
-
- _transaction.enqueue(_queues, _message, _action);
-
- assertEquals("Enqueue of persistent message to non-durable queues must not cause message to be enqueued", 0, _storeTransaction.getNumberOfEnqueuedMessages());
- assertEquals("Unexpected transaction state", TransactionState.NOT_STARTED, _storeTransaction.getState());
- assertFalse("Rollback action must not be fired", _action.isRollbackActionFired());
- assertTrue("Post commit action must be fired", _action.isPostCommitActionFired());
-
- }
-
- /**
- * Tests the enqueue of a persistent message to many queues, some durable others not.
- * Asserts that a store transaction has been committed and post commit action fired.
- */
- public void testEnqueueToDurableAndNonDurableQueuesOfPersistentMessage() throws Exception
- {
- _message = createTestMessage(true);
- _queues = createTestBaseQueues(new boolean[] {false, true, false, true});
-
- _transaction.enqueue(_queues, _message, _action);
-
- assertEquals("Enqueue of persistent message to durable/non-durable queues must cause messages to be enqueued", 2, _storeTransaction.getNumberOfEnqueuedMessages());
- assertEquals("Unexpected transaction state", TransactionState.COMMITTED, _storeTransaction.getState());
- assertFalse("Rollback action must not be fired", _action.isRollbackActionFired());
- assertTrue("Post commit action must be fired", _action.isPostCommitActionFired());
- }
-
- /**
- * Tests the case where the store operation throws an exception.
- * Asserts that the transaction is aborted and rollback action fired.
- */
- public void testStoreEnqueuesCausesExceptions() throws Exception
- {
- _message = createTestMessage(true);
- _queues = createTestBaseQueues(new boolean[] {true, true});
-
- _storeTransaction = createTestStoreTransaction(true);
- _transactionLog = MockStoreTransaction.createTestTransactionLog(_storeTransaction);
- _transaction = new AutoCommitTransaction(_transactionLog);
-
- try
- {
- _transaction.enqueue(_queues, _message, _action);
- fail("Exception not thrown");
- }
- catch (RuntimeException re)
- {
- // PASS
- }
-
- assertEquals("Unexpected transaction state", TransactionState.ABORTED, _storeTransaction.getState());
- assertTrue("Rollback action must be fired", _action.isRollbackActionFired());
- assertFalse("Post commit action must not be fired", _action.isPostCommitActionFired());
- }
-
- /**
- * Tests the dequeue of a non persistent message from a single non durable queue.
- * Asserts that a store transaction has not been started and post commit action
- * fired.
- */
- public void testDequeueFromNonDurableQueueOfNonPersistentMessage() throws Exception
- {
- _message = createTestMessage(false);
- _queue = createTestAMQQueue(false);
-
- _transaction.dequeue(_queue, _message, _action);
-
- assertEquals("Dequeue of non-persistent message must not cause message to be dequeued", 0, _storeTransaction.getNumberOfDequeuedMessages());
- assertEquals("Unexpected transaction state", TransactionState.NOT_STARTED, _storeTransaction.getState());
- assertFalse("Rollback action must not be fired", _action.isRollbackActionFired());
- assertTrue("Post commit action must be fired", _action.isPostCommitActionFired());
-
- }
-
- /**
- * Tests the dequeue of a persistent message from a single non durable queue.
- * Asserts that a store transaction has not been started and post commit
- * action fired.
- */
- public void testDequeueFromDurableQueueOfPersistentMessage() throws Exception
- {
- _message = createTestMessage(true);
- _queue = createTestAMQQueue(true);
-
- _transaction.dequeue(_queue, _message, _action);
-
- assertEquals("Dequeue of persistent message to durable queue must cause message to be dequeued",1, _storeTransaction.getNumberOfDequeuedMessages());
- assertEquals("Unexpected transaction state", TransactionState.COMMITTED, _storeTransaction.getState());
- assertFalse("Rollback action must not be fired", _action.isRollbackActionFired());
- assertTrue("Post commit action must be fired", _action.isPostCommitActionFired());
- }
-
- /**
- * Tests the case where the store operation throws an exception.
- * Asserts that the transaction is aborted and post rollback action
- * fired.
- */
- public void testStoreDequeueCausesException() throws Exception
- {
- _message = createTestMessage(true);
- _queue = createTestAMQQueue(true);
-
- _storeTransaction = createTestStoreTransaction(true);
- _transactionLog = MockStoreTransaction.createTestTransactionLog(_storeTransaction);
- _transaction = new AutoCommitTransaction(_transactionLog);
-
- try
- {
- _transaction.dequeue(_queue, _message, _action);
- fail("Exception not thrown");
- }
- catch (RuntimeException re)
- {
- // PASS
- }
-
- assertEquals("Unexpected transaction state", TransactionState.ABORTED, _storeTransaction.getState());
-
- assertTrue("Rollback action must be fired", _action.isRollbackActionFired());
- assertFalse("Post commit action must not be fired", _action.isPostCommitActionFired());
- }
-
- /**
- * Tests the dequeue of a non persistent message from many non durable queues.
- * Asserts that a store transaction has not been started and post commit action
- * fired.
- */
- public void testDequeueFromManyNonDurableQueuesOfNonPersistentMessage() throws Exception
- {
- _queueEntries = createTestQueueEntries(new boolean[] {false, false, false}, new boolean[] {false, false, false});
-
- _transaction.dequeue(_queueEntries, _action);
-
- assertEquals("Dequeue of non-persistent messages must not cause message to be dequeued", 0, _storeTransaction.getNumberOfDequeuedMessages());
- assertEquals("Unexpected transaction state", TransactionState.NOT_STARTED, _storeTransaction.getState());
- assertEquals("Rollback action must not be fired", false, _action.isRollbackActionFired());
- assertEquals("Post commit action must be fired", true, _action.isPostCommitActionFired());
-
- }
-
-
- /**
- * Tests the dequeue of a persistent message from a many non durable queues.
- * Asserts that a store transaction has not been started and post commit action
- * fired.
- */
- public void testDequeueFromManyNonDurableQueuesOfPersistentMessage() throws Exception
- {
- _queueEntries = createTestQueueEntries(new boolean[] {false, false, false}, new boolean[] {true, true, true});
-
- _transaction.dequeue(_queueEntries, _action);
-
- assertEquals("Dequeue of persistent message from non-durable queues must not cause message to be enqueued", 0, _storeTransaction.getNumberOfDequeuedMessages());
- assertEquals("Unexpected transaction state", TransactionState.NOT_STARTED, _storeTransaction.getState());
- assertFalse("Rollback action must not be fired", _action.isRollbackActionFired());
- assertTrue("Post commit action must be fired", _action.isPostCommitActionFired());
- }
-
- /**
- * Tests the dequeue of a persistent message from many queues, some durable others not.
- * Asserts that a store transaction has not been started and post commit action fired.
- */
- public void testDequeueFromDurableAndNonDurableQueuesOfPersistentMessage() throws Exception
- {
- // A transaction will exist owing to the 1st and 3rd.
- _queueEntries = createTestQueueEntries(new boolean[] {true, false, true, true}, new boolean[] {true, true, true, false});
-
- _transaction.dequeue(_queueEntries, _action);
-
- assertEquals("Dequeue of persistent messages from durable/non-durable queues must cause messages to be dequeued", 2, _storeTransaction.getNumberOfDequeuedMessages());
- assertEquals("Unexpected transaction state", TransactionState.COMMITTED, _storeTransaction.getState());
- assertFalse("Rollback action must not be fired", _action.isRollbackActionFired());
- assertTrue("Post commit action must be fired", _action.isPostCommitActionFired());
- }
-
- /**
- * Tests the case where the store operation throws an exception.
- * Asserts that the transaction is aborted and post rollback action fired.
- */
- public void testStoreDequeuesCauseExceptions() throws Exception
- {
- // Transactions will exist owing to the 1st and 3rd queue entries in the collection
- _queueEntries = createTestQueueEntries(new boolean[] {true}, new boolean[] {true});
-
- _storeTransaction = createTestStoreTransaction(true);
- _transactionLog = MockStoreTransaction.createTestTransactionLog(_storeTransaction);
- _transaction = new AutoCommitTransaction(_transactionLog);
-
- try
- {
- _transaction.dequeue(_queueEntries, _action);
- fail("Exception not thrown");
- }
- catch (RuntimeException re)
- {
- // PASS
- }
-
- assertEquals("Unexpected transaction state", TransactionState.ABORTED, _storeTransaction.getState());
-
- assertTrue("Rollback action must be fired", _action.isRollbackActionFired());
- assertFalse("Post commit action must not be fired", _action.isPostCommitActionFired());
- }
-
- /**
- * Tests the add of a post-commit action. Since AutoCommitTranctions
- * have no long lived transactions, the post commit action is fired immediately.
- */
- public void testPostCommitActionFiredImmediately() throws Exception
- {
-
- _transaction.addPostTransactionAction(_action);
-
- assertTrue("Post commit action must be fired", _action.isPostCommitActionFired());
- assertFalse("Rollback action must be fired", _action.isRollbackActionFired());
- }
-
- private Collection<QueueEntry> createTestQueueEntries(boolean[] queueDurableFlags, boolean[] messagePersistentFlags)
- {
- Collection<QueueEntry> queueEntries = new ArrayList<QueueEntry>();
-
- assertTrue("Boolean arrays must be the same length", queueDurableFlags.length == messagePersistentFlags.length);
-
- for(int i = 0; i < queueDurableFlags.length; i++)
- {
- final AMQQueue queue = createTestAMQQueue(queueDurableFlags[i]);
- final ServerMessage message = createTestMessage(messagePersistentFlags[i]);
-
- queueEntries.add(new MockQueueEntry()
- {
-
- @Override
- public ServerMessage getMessage()
- {
- return message;
- }
-
- @Override
- public AMQQueue getQueue()
- {
- return queue;
- }
-
- });
- }
-
- return queueEntries;
- }
-
- private MockStoreTransaction createTestStoreTransaction(boolean throwException)
- {
- return new MockStoreTransaction(throwException);
- }
-
- private List<AMQQueue> createTestBaseQueues(boolean[] durableFlags)
- {
- List<AMQQueue> queues = new ArrayList<AMQQueue>();
- for (boolean b: durableFlags)
- {
- queues.add(createTestAMQQueue(b));
- }
-
- return queues;
- }
-
- private AMQQueue createTestAMQQueue(final boolean durable)
- {
- return new MockAMQQueue("mockQueue")
- {
- @Override
- public boolean isDurable()
- {
- return durable;
- }
-
- };
- }
-
- private ServerMessage createTestMessage(final boolean persistent)
- {
- return new MockServerMessage(persistent);
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/txn/LocalTransactionTest.java b/java/broker/src/test/java/org/apache/qpid/server/txn/LocalTransactionTest.java
deleted file mode 100644
index e81fd8e3f1..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/txn/LocalTransactionTest.java
+++ /dev/null
@@ -1,557 +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.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;
-import org.apache.qpid.server.queue.MockQueueEntry;
-import org.apache.qpid.server.queue.QueueEntry;
-import org.apache.qpid.server.store.TransactionLog;
-import org.apache.qpid.server.txn.MockStoreTransaction.TransactionState;
-import org.apache.qpid.test.utils.QpidTestCase;
-
-/**
- * A unit test ensuring that LocalTransactionTest creates a long-lived store transaction
- * that spans many dequeue/enqueue operations of enlistable messages. Verifies
- * that the long-lived transaction is properly committed and rolled back, and that
- * post transaction actions are correctly fired.
- *
- */
-public class LocalTransactionTest extends QpidTestCase
-{
- private ServerTransaction _transaction = null; // Class under test
-
- private AMQQueue _queue;
- private List<AMQQueue> _queues;
- private Collection<QueueEntry> _queueEntries;
- private ServerMessage _message;
- private MockAction _action1;
- private MockAction _action2;
- private MockStoreTransaction _storeTransaction;
- private TransactionLog _transactionLog;
-
-
- @Override
- protected void setUp() throws Exception
- {
- super.setUp();
-
- _storeTransaction = createTestStoreTransaction(false);
- _transactionLog = MockStoreTransaction.createTestTransactionLog(_storeTransaction);
- _action1 = new MockAction();
- _action2 = new MockAction();
-
- _transaction = new LocalTransaction(_transactionLog);
-
- }
-
-
- /**
- * Tests the enqueue of a non persistent message to a single non durable queue.
- * Asserts that a store transaction has not been started.
- */
- public void testEnqueueToNonDurableQueueOfNonPersistentMessage() throws Exception
- {
- _message = createTestMessage(false);
- _queue = createTestAMQQueue(false);
-
- _transaction.enqueue(_queue, _message, _action1);
-
- assertEquals("Enqueue of non-persistent message must not cause message to be enqueued", 0, _storeTransaction.getNumberOfEnqueuedMessages());
- assertEquals("Unexpected transaction state", TransactionState.NOT_STARTED, _storeTransaction.getState());
- assertNotFired(_action1);
- }
-
- /**
- * Tests the enqueue of a persistent message to a durable queue.
- * Asserts that a store transaction has been started.
- */
- public void testEnqueueToDurableQueueOfPersistentMessage() throws Exception
- {
- _message = createTestMessage(true);
- _queue = createTestAMQQueue(true);
-
- _transaction.enqueue(_queue, _message, _action1);
-
- assertEquals("Enqueue of persistent message to durable queue must cause message to be enqueued", 1, _storeTransaction.getNumberOfEnqueuedMessages());
- assertEquals("Unexpected transaction state", TransactionState.STARTED, _storeTransaction.getState());
- assertNotFired(_action1);
- }
-
- /**
- * Tests the case where the store operation throws an exception.
- * Asserts that the transaction is aborted.
- */
- public void testStoreEnqueueCausesException() throws Exception
- {
- _message = createTestMessage(true);
- _queue = createTestAMQQueue(true);
-
- _storeTransaction = createTestStoreTransaction(true);
- _transactionLog = MockStoreTransaction.createTestTransactionLog(_storeTransaction);
- _transaction = new LocalTransaction(_transactionLog);
-
- try
- {
- _transaction.enqueue(_queue, _message, _action1);
- fail("Exception not thrown");
- }
- catch (RuntimeException re)
- {
- // PASS
- }
-
- assertTrue("Rollback action must be fired", _action1.isRollbackActionFired());
- assertEquals("Unexpected transaction state", TransactionState.ABORTED, _storeTransaction.getState());
-
- assertFalse("Post commit action must not be fired", _action1.isPostCommitActionFired());
-
- }
-
- /**
- * Tests the enqueue of a non persistent message to a many non durable queues.
- * Asserts that a store transaction has not been started.
- */
- public void testEnqueueToManyNonDurableQueuesOfNonPersistentMessage() throws Exception
- {
- _message = createTestMessage(false);
- _queues = createTestBaseQueues(new boolean[] {false, false, false});
-
- _transaction.enqueue(_queues, _message, _action1);
-
- assertEquals("Enqueue of non-persistent message must not cause message to be enqueued", 0, _storeTransaction.getNumberOfEnqueuedMessages());
- assertEquals("Unexpected transaction state", TransactionState.NOT_STARTED, _storeTransaction.getState());
- assertNotFired(_action1);
- }
-
- /**
- * Tests the enqueue of a persistent message to a many non durable queues.
- * Asserts that a store transaction has not been started.
- */
- public void testEnqueueToManyNonDurableQueuesOfPersistentMessage() throws Exception
- {
- _message = createTestMessage(true);
- _queues = createTestBaseQueues(new boolean[] {false, false, false});
-
- _transaction.enqueue(_queues, _message, _action1);
-
- assertEquals("Enqueue of persistent message to non-durable queues must not cause message to be enqueued", 0, _storeTransaction.getNumberOfEnqueuedMessages());
- assertEquals("Unexpected transaction state", TransactionState.NOT_STARTED, _storeTransaction.getState());
- assertNotFired(_action1);
-
- }
-
- /**
- * Tests the enqueue of a persistent message to many queues, some durable others not.
- * Asserts that a store transaction has been started.
- */
- public void testEnqueueToDurableAndNonDurableQueuesOfPersistentMessage() throws Exception
- {
- _message = createTestMessage(true);
- _queues = createTestBaseQueues(new boolean[] {false, true, false, true});
-
- _transaction.enqueue(_queues, _message, _action1);
-
- assertEquals("Enqueue of persistent message to durable/non-durable queues must cause messages to be enqueued", 2, _storeTransaction.getNumberOfEnqueuedMessages());
- assertEquals("Unexpected transaction state", TransactionState.STARTED, _storeTransaction.getState());
- assertNotFired(_action1);
-
- }
-
- /**
- * Tests the case where the store operation throws an exception.
- * Asserts that the transaction is aborted.
- */
- public void testStoreEnqueuesCausesExceptions() throws Exception
- {
- _message = createTestMessage(true);
- _queues = createTestBaseQueues(new boolean[] {true, true});
-
- _storeTransaction = createTestStoreTransaction(true);
- _transactionLog = MockStoreTransaction.createTestTransactionLog(_storeTransaction);
- _transaction = new LocalTransaction(_transactionLog);
-
- try
- {
- _transaction.enqueue(_queues, _message, _action1);
- fail("Exception not thrown");
- }
- catch (RuntimeException re)
- {
- // PASS
- }
-
- assertTrue("Rollback action must be fired", _action1.isRollbackActionFired());
- assertEquals("Unexpected transaction state", TransactionState.ABORTED, _storeTransaction.getState());
- assertFalse("Post commit action must not be fired", _action1.isPostCommitActionFired());
- }
-
- /**
- * Tests the dequeue of a non persistent message from a single non durable queue.
- * Asserts that a store transaction has not been started.
- */
- public void testDequeueFromNonDurableQueueOfNonPersistentMessage() throws Exception
- {
- _message = createTestMessage(false);
- _queue = createTestAMQQueue(false);
-
- _transaction.dequeue(_queue, _message, _action1);
-
- assertEquals("Dequeue of non-persistent message must not cause message to be enqueued", 0, _storeTransaction.getNumberOfEnqueuedMessages());
- assertEquals("Unexpected transaction state", TransactionState.NOT_STARTED, _storeTransaction.getState());
- assertNotFired(_action1);
-
- }
-
- /**
- * Tests the dequeue of a persistent message from a single non durable queue.
- * Asserts that a store transaction has not been started.
- */
- public void testDequeueFromDurableQueueOfPersistentMessage() throws Exception
- {
- _message = createTestMessage(true);
- _queue = createTestAMQQueue(true);
-
- _transaction.dequeue(_queue, _message, _action1);
-
- assertEquals("Dequeue of non-persistent message must cause message to be dequeued", 1, _storeTransaction.getNumberOfDequeuedMessages());
- assertEquals("Unexpected transaction state", TransactionState.STARTED, _storeTransaction.getState());
- assertNotFired(_action1);
- }
-
- /**
- * Tests the case where the store operation throws an exception.
- * Asserts that the transaction is aborted.
- */
- public void testStoreDequeueCausesException() throws Exception
- {
- _message = createTestMessage(true);
- _queue = createTestAMQQueue(true);
-
- _storeTransaction = createTestStoreTransaction(true);
- _transactionLog = MockStoreTransaction.createTestTransactionLog(_storeTransaction);
- _transaction = new LocalTransaction(_transactionLog);
-
- try
- {
- _transaction.dequeue(_queue, _message, _action1);
- fail("Exception not thrown");
- }
- catch (RuntimeException re)
- {
- // PASS
- }
-
- assertTrue("Rollback action must be fired", _action1.isRollbackActionFired());
- assertEquals("Unexpected transaction state", TransactionState.ABORTED, _storeTransaction.getState());
- assertFalse("Post commit action must not be fired", _action1.isPostCommitActionFired());
-
- }
-
- /**
- * Tests the dequeue of a non persistent message from many non durable queues.
- * Asserts that a store transaction has not been started.
- */
- public void testDequeueFromManyNonDurableQueuesOfNonPersistentMessage() throws Exception
- {
- _queueEntries = createTestQueueEntries(new boolean[] {false, false, false}, new boolean[] {false, false, false});
-
- _transaction.dequeue(_queueEntries, _action1);
-
- assertEquals("Dequeue of non-persistent messages must not cause message to be dequeued", 0, _storeTransaction.getNumberOfDequeuedMessages());
- assertEquals("Unexpected transaction state", TransactionState.NOT_STARTED, _storeTransaction.getState());
- assertNotFired(_action1);
-
- }
-
- /**
- * Tests the dequeue of a persistent message from a many non durable queues.
- * Asserts that a store transaction has not been started.
- */
- public void testDequeueFromManyNonDurableQueuesOfPersistentMessage() throws Exception
- {
- _queueEntries = createTestQueueEntries(new boolean[] {false, false, false}, new boolean[] {true, true, true});
-
- _transaction.dequeue(_queueEntries, _action1);
-
- assertEquals("Dequeue of persistent message from non-durable queues must not cause message to be enqueued", 0, _storeTransaction.getNumberOfDequeuedMessages());
- assertEquals("Unexpected transaction state", TransactionState.NOT_STARTED, _storeTransaction.getState());
- assertNotFired(_action1);
- }
-
- /**
- * Tests the dequeue of a persistent message from many queues, some durable others not.
- * Asserts that a store transaction has not been started.
- */
- public void testDequeueFromDurableAndNonDurableQueuesOfPersistentMessage() throws Exception
- {
- // A transaction will exist owing to the 1st and 3rd.
- _queueEntries = createTestQueueEntries(new boolean[] {true, false, true, true}, new boolean[] {true, true, true, false});
-
- _transaction.dequeue(_queueEntries, _action1);
-
- assertEquals("Dequeue of persistent messages from durable/non-durable queues must cause messages to be dequeued", 2, _storeTransaction.getNumberOfDequeuedMessages());
- assertEquals("Unexpected transaction state", TransactionState.STARTED, _storeTransaction.getState());
- assertNotFired(_action1);
- }
-
- /**
- * Tests the case where the store operation throws an exception.
- * Asserts that the transaction is aborted.
- */
- public void testStoreDequeuesCauseExceptions() throws Exception
- {
- // Transactions will exist owing to the 1st and 3rd queue entries in the collection
- _queueEntries = createTestQueueEntries(new boolean[] {true}, new boolean[] {true});
-
- _storeTransaction = createTestStoreTransaction(true);
- _transactionLog = MockStoreTransaction.createTestTransactionLog(_storeTransaction);
- _transaction = new LocalTransaction(_transactionLog);
-
- try
- {
- _transaction.dequeue(_queueEntries, _action1);
- fail("Exception not thrown");
- }
- catch (RuntimeException re)
- {
- // PASS
- }
-
- assertEquals("Unexpected transaction state", TransactionState.ABORTED, _storeTransaction.getState());
- assertTrue("Rollback action must be fired", _action1.isRollbackActionFired());
- assertFalse("Post commit action must not be fired", _action1.isPostCommitActionFired());
- }
-
- /**
- * Tests the add of a post-commit action. Unlike AutoCommitTranctions, the post transaction actions
- * is added to a list to be fired on commit or rollback.
- */
- public void testAddingPostCommitActionNotFiredImmediately() throws Exception
- {
-
- _transaction.addPostTransactionAction(_action1);
-
- assertNotFired(_action1);
- }
-
-
- /**
- * Tests committing a transaction without work accepted without error and without causing store
- * enqueues or dequeues.
- */
- public void testCommitNoWork() throws Exception
- {
-
- _transaction.commit();
-
- assertEquals("Unexpected number of store dequeues", 0, _storeTransaction.getNumberOfDequeuedMessages());
- assertEquals("Unexpected number of store enqueues", 0, _storeTransaction.getNumberOfEnqueuedMessages());
- assertEquals("Unexpected transaction state", TransactionState.NOT_STARTED, _storeTransaction.getState());
- }
-
- /**
- * Tests rolling back a transaction without work accepted without error and without causing store
- * enqueues or dequeues.
- */
- public void testRollbackNoWork() throws Exception
- {
-
- _transaction.rollback();
-
- assertEquals("Unexpected number of store dequeues", 0, _storeTransaction.getNumberOfDequeuedMessages());
- assertEquals("Unexpected number of store enqueues", 0, _storeTransaction.getNumberOfEnqueuedMessages());
- assertEquals("Unexpected transaction state", TransactionState.NOT_STARTED, _storeTransaction.getState());
- }
-
- /**
- * Tests the dequeuing of a message with a commit. Test ensures that the underlying store transaction is
- * correctly controlled and the post commit action is fired.
- */
- public void testCommitWork() throws Exception
- {
-
- _message = createTestMessage(true);
- _queue = createTestAMQQueue(true);
-
- assertEquals("Unexpected transaction state", TransactionState.NOT_STARTED, _storeTransaction.getState());
- assertFalse("Post commit action must not be fired yet", _action1.isPostCommitActionFired());
-
- _transaction.dequeue(_queue, _message, _action1);
- assertEquals("Unexpected transaction state", TransactionState.STARTED, _storeTransaction.getState());
- assertFalse("Post commit action must not be fired yet", _action1.isPostCommitActionFired());
-
- _transaction.commit();
-
- assertEquals("Unexpected transaction state", TransactionState.COMMITTED, _storeTransaction.getState());
- assertTrue("Post commit action must be fired", _action1.isPostCommitActionFired());
- }
-
- /**
- * Tests the dequeuing of a message with a rollback. Test ensures that the underlying store transaction is
- * correctly controlled and the post rollback action is fired.
- */
- public void testRollbackWork() throws Exception
- {
-
- _message = createTestMessage(true);
- _queue = createTestAMQQueue(true);
-
-
- assertEquals("Unexpected transaction state", TransactionState.NOT_STARTED, _storeTransaction.getState());
- assertFalse("Rollback action must not be fired yet", _action1.isRollbackActionFired());
-
- _transaction.dequeue(_queue, _message, _action1);
-
- assertEquals("Unexpected transaction state", TransactionState.STARTED, _storeTransaction.getState());
- assertFalse("Rollback action must not be fired yet", _action1.isRollbackActionFired());
-
- _transaction.rollback();
-
- assertEquals("Unexpected transaction state", TransactionState.ABORTED, _storeTransaction.getState());
- assertTrue("Rollback action must be fired", _action1.isRollbackActionFired());
-
- }
-
- /**
- * Variation of testCommitWork with an additional post transaction action.
- *
- */
- public void testCommitWorkWithAdditionalPostAction() throws Exception
- {
-
- _message = createTestMessage(true);
- _queue = createTestAMQQueue(true);
-
- _transaction.addPostTransactionAction(_action1);
- _transaction.dequeue(_queue, _message, _action2);
- _transaction.commit();
-
- assertEquals("Unexpected transaction state", TransactionState.COMMITTED, _storeTransaction.getState());
-
- assertTrue("Post commit action1 must be fired", _action1.isPostCommitActionFired());
- assertTrue("Post commit action2 must be fired", _action2.isPostCommitActionFired());
-
- assertFalse("Rollback action1 must not be fired", _action1.isRollbackActionFired());
- assertFalse("Rollback action2 must not be fired", _action1.isRollbackActionFired());
- }
-
- /**
- * Variation of testRollbackWork with an additional post transaction action.
- *
- */
- public void testRollbackWorkWithAdditionalPostAction() throws Exception
- {
-
- _message = createTestMessage(true);
- _queue = createTestAMQQueue(true);
-
- _transaction.addPostTransactionAction(_action1);
- _transaction.dequeue(_queue, _message, _action2);
- _transaction.rollback();
-
- assertEquals("Unexpected transaction state", TransactionState.ABORTED, _storeTransaction.getState());
-
- assertFalse("Post commit action1 must not be fired", _action1.isPostCommitActionFired());
- assertFalse("Post commit action2 must not be fired", _action2.isPostCommitActionFired());
-
- assertTrue("Rollback action1 must be fired", _action1.isRollbackActionFired());
- assertTrue("Rollback action2 must be fired", _action1.isRollbackActionFired());
- }
-
- private Collection<QueueEntry> createTestQueueEntries(boolean[] queueDurableFlags, boolean[] messagePersistentFlags)
- {
- Collection<QueueEntry> queueEntries = new ArrayList<QueueEntry>();
-
- assertTrue("Boolean arrays must be the same length", queueDurableFlags.length == messagePersistentFlags.length);
-
- for(int i = 0; i < queueDurableFlags.length; i++)
- {
- final AMQQueue queue = createTestAMQQueue(queueDurableFlags[i]);
- final ServerMessage message = createTestMessage(messagePersistentFlags[i]);
-
- queueEntries.add(new MockQueueEntry()
- {
-
- @Override
- public ServerMessage getMessage()
- {
- return message;
- }
-
- @Override
- public AMQQueue getQueue()
- {
- return queue;
- }
-
- });
- }
-
- return queueEntries;
- }
-
- private MockStoreTransaction createTestStoreTransaction(boolean throwException)
- {
- return new MockStoreTransaction(throwException);
- }
-
- private List<AMQQueue> createTestBaseQueues(boolean[] durableFlags)
- {
- List<AMQQueue> queues = new ArrayList<AMQQueue>();
- for (boolean b: durableFlags)
- {
- queues.add(createTestAMQQueue(b));
- }
-
- return queues;
- }
-
- private AMQQueue createTestAMQQueue(final boolean durable)
- {
- return new MockAMQQueue("mockQueue")
- {
- @Override
- public boolean isDurable()
- {
- return durable;
- }
-
- };
- }
-
- private ServerMessage createTestMessage(final boolean persistent)
- {
- return new MockServerMessage(persistent);
- }
-
- private void assertNotFired(MockAction action)
- {
- assertFalse("Rollback action must not be fired", action.isRollbackActionFired());
- assertFalse("Post commit action must not be fired", action.isPostCommitActionFired());
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/txn/MockAction.java b/java/broker/src/test/java/org/apache/qpid/server/txn/MockAction.java
deleted file mode 100644
index 975e3e91b9..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/txn/MockAction.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.server.txn;
-
-import org.apache.qpid.server.txn.ServerTransaction.Action;
-
-/**
- * Mock implementation of a ServerTranaction Action
- * allowing its state to be observed.
- *
- */
-class MockAction implements Action
-{
- private boolean _rollbackFired = false;
- private boolean _postCommitFired = false;
-
- @Override
- public void postCommit()
- {
- _postCommitFired = true;
- }
-
- @Override
- public void onRollback()
- {
- _rollbackFired = true;
- }
-
- public boolean isRollbackActionFired()
- {
- return _rollbackFired;
- }
-
- public boolean isPostCommitActionFired()
- {
- return _postCommitFired;
- }
-} \ No newline at end of file
diff --git a/java/broker/src/test/java/org/apache/qpid/server/txn/MockServerMessage.java b/java/broker/src/test/java/org/apache/qpid/server/txn/MockServerMessage.java
deleted file mode 100644
index 64c62fd029..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/txn/MockServerMessage.java
+++ /dev/null
@@ -1,114 +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.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;
-
-/**
- * Mock Server Message allowing its persistent flag to be controlled from test.
- */
-class MockServerMessage implements ServerMessage
-{
- /**
- *
- */
- private final boolean persistent;
-
- /**
- * @param persistent
- */
- MockServerMessage(boolean persistent)
- {
- this.persistent = persistent;
- }
-
- @Override
- public boolean isPersistent()
- {
- return persistent;
- }
-
- @Override
- public MessageReference newReference()
- {
- throw new NotImplementedException();
- }
-
- @Override
- public boolean isImmediate()
- {
- throw new NotImplementedException();
- }
-
- @Override
- public long getSize()
- {
- throw new NotImplementedException();
- }
-
- @Override
- public SessionConfig getSessionConfig()
- {
- throw new NotImplementedException();
- }
-
- @Override
- public String getRoutingKey()
- {
- throw new NotImplementedException();
- }
-
- @Override
- public AMQMessageHeader getMessageHeader()
- {
- throw new NotImplementedException();
- }
-
- @Override
- public long getExpiration()
- {
- throw new NotImplementedException();
- }
-
- @Override
- public int getContent(ByteBuffer buf, int offset)
- {
- throw new NotImplementedException();
- }
-
- @Override
- public long getArrivalTime()
- {
- throw new NotImplementedException();
- }
-
- @Override
- public Long getMessageNumber()
- {
- return 0L;
- }
-} \ No newline at end of file
diff --git a/java/broker/src/test/java/org/apache/qpid/server/txn/MockStoreTransaction.java b/java/broker/src/test/java/org/apache/qpid/server/txn/MockStoreTransaction.java
deleted file mode 100644
index 5700bba9f8..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/txn/MockStoreTransaction.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.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.store.TransactionLog;
-import org.apache.qpid.server.store.TransactionLogRecoveryHandler;
-import org.apache.qpid.server.store.TransactionLogResource;
-import org.apache.qpid.server.store.TransactionLog.StoreFuture;
-import org.apache.qpid.server.store.TransactionLog.Transaction;
-
-/**
- * Mock implementation of a (Store) Transaction allow its state to be observed.
- * Also provide a factory method to produce TestTransactionLog objects suitable
- * for unit test use.
- *
- */
-class MockStoreTransaction implements Transaction
-{
- enum TransactionState {NOT_STARTED, STARTED, COMMITTED, ABORTED};
-
- private TransactionState _state = TransactionState.NOT_STARTED;
-
- private int _numberOfEnqueuedMessages = 0;
- private int _numberOfDequeuedMessages = 0;
- private boolean _throwExceptionOnQueueOp;
-
- public MockStoreTransaction(boolean throwExceptionOnQueueOp)
- {
- _throwExceptionOnQueueOp = throwExceptionOnQueueOp;
- }
-
- public void setState(TransactionState state)
- {
- _state = state;
- }
-
- public TransactionState getState()
- {
- return _state;
- }
-
- @Override
- public void enqueueMessage(TransactionLogResource queue, Long messageId) throws AMQStoreException
- {
- if (_throwExceptionOnQueueOp)
- {
-
- throw new AMQStoreException("Mocked exception");
- }
-
- _numberOfEnqueuedMessages++;
- }
-
- public int getNumberOfDequeuedMessages()
- {
- return _numberOfDequeuedMessages;
- }
-
- public int getNumberOfEnqueuedMessages()
- {
- return _numberOfEnqueuedMessages;
- }
-
-
- @Override
- public void dequeueMessage(TransactionLogResource queue, Long messageId) throws AMQStoreException
- {
- if (_throwExceptionOnQueueOp)
- {
- throw new AMQStoreException("Mocked exception");
- }
-
- _numberOfDequeuedMessages++;
- }
-
- @Override
- public void commitTran() throws AMQStoreException
- {
- _state = TransactionState.COMMITTED;
- }
-
- @Override
- public StoreFuture commitTranAsync() throws AMQStoreException
- {
- throw new NotImplementedException();
- }
-
- @Override
- public void abortTran() throws AMQStoreException
- {
- _state = TransactionState.ABORTED;
- }
-
- public static TransactionLog createTestTransactionLog(final MockStoreTransaction storeTransaction)
- {
- return new TransactionLog()
- {
-
- @Override
- public void configureTransactionLog(String name, TransactionLogRecoveryHandler recoveryHandler,
- Configuration storeConfiguration, LogSubject logSubject) throws Exception
- {
- }
-
- @Override
- public Transaction newTransaction()
- {
- storeTransaction.setState(TransactionState.STARTED);
- return storeTransaction;
- }
-
- };
- }
-} \ No newline at end of file
diff --git a/java/broker/src/test/java/org/apache/qpid/server/util/InternalBrokerBaseCase.java b/java/broker/src/test/java/org/apache/qpid/server/util/InternalBrokerBaseCase.java
deleted file mode 100644
index ff94942457..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/util/InternalBrokerBaseCase.java
+++ /dev/null
@@ -1,365 +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 org.apache.commons.configuration.XMLConfiguration;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.common.AMQPFilterTypes;
-import org.apache.qpid.exchange.ExchangeDefaults;
-import org.apache.qpid.framing.AMQShortString;
-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.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.actors.TestLogActor;
-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.registry.ApplicationRegistry;
-import org.apache.qpid.server.registry.IApplicationRegistry;
-import org.apache.qpid.server.store.MessageStore;
-import org.apache.qpid.server.store.TestableMemoryMessageStore;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-import org.apache.qpid.test.utils.QpidTestCase;
-import org.apache.qpid.util.MockChannel;
-
-
-public class InternalBrokerBaseCase extends QpidTestCase
-{
- private IApplicationRegistry _registry;
- private MessageStore _messageStore;
- private MockChannel _channel;
- private InternalTestProtocolSession _session;
- private VirtualHost _virtualHost;
- private AMQQueue _queue;
- private AMQShortString QUEUE_NAME;
- private ServerConfiguration _configuration;
- private XMLConfiguration _configXml = new XMLConfiguration();
- private boolean _started = false;
-
- public void setUp() throws Exception
- {
- super.setUp();
-
- _configXml.addProperty("virtualhosts.virtualhost.name", "test");
- _configXml.addProperty("virtualhosts.virtualhost.test.store.class", TestableMemoryMessageStore.class.getName());
-
- _configXml.addProperty("virtualhosts.virtualhost(-1).name", getName());
- _configXml.addProperty("virtualhosts.virtualhost(-1)."+getName()+".store.class", TestableMemoryMessageStore.class.getName());
-
- createBroker();
- }
-
- protected void createBroker() throws Exception
- {
- _started = true;
- CurrentActor.set(new TestLogActor(new SystemOutMessageLogger()));
-
- _configuration = new ServerConfiguration(_configXml);
-
- configure();
-
- _registry = new TestApplicationRegistry(_configuration);
- ApplicationRegistry.initialise(_registry);
- _registry.getVirtualHostRegistry().setDefaultVirtualHostName(getName());
- _virtualHost = _registry.getVirtualHostRegistry().getVirtualHost(getName());
-
- QUEUE_NAME = new AMQShortString("test");
- // Create a queue on the test Vhost.. this will aid in diagnosing duff tests
- // as the ExpiredMessage Task will log with the test Name.
- _queue = AMQQueueFactory.createAMQQueueImpl(QUEUE_NAME, false, new AMQShortString("testowner"),
- false, false, _virtualHost, null);
-
- Exchange defaultExchange = _virtualHost.getExchangeRegistry().getDefaultExchange();
- _virtualHost.getBindingFactory().addBinding(QUEUE_NAME.toString(), _queue, defaultExchange, null);
-
- _virtualHost = _registry.getVirtualHostRegistry().getVirtualHost("test");
- _messageStore = _virtualHost.getMessageStore();
-
- _queue = AMQQueueFactory.createAMQQueueImpl(new AMQShortString(getName()), false, new AMQShortString("testowner"),
- false, false, _virtualHost, null);
-
- _virtualHost.getQueueRegistry().registerQueue(_queue);
-
- defaultExchange = _virtualHost.getExchangeRegistry().getDefaultExchange();
-
- _virtualHost.getBindingFactory().addBinding(getName(), _queue, defaultExchange, null);
-
- _session = new InternalTestProtocolSession(_virtualHost);
- CurrentActor.set(_session.getLogActor());
-
- _channel = new MockChannel(_session, 1, _messageStore);
-
- _session.addChannel(_channel);
- }
-
- protected void configure()
- {
- // Allow other tests to override configuration
- }
-
- protected void stopBroker()
- {
- try
- {
- //Remove the ProtocolSession Actor added during createBroker
- CurrentActor.remove();
- }
- finally
- {
- ApplicationRegistry.remove();
- _started = false;
- }
- }
-
-
- public void tearDown() throws Exception
- {
- try
- {
- if (_started)
- {
- stopBroker();
- }
- }
- finally
- {
- super.tearDown();
- // Purge Any erroneously added actors
- CurrentActor.removeAll();
- }
- }
-
- protected void checkStoreContents(int messageCount)
- {
- assertEquals("Message header count incorrect in the MetaDataMap", messageCount, ((TestableMemoryMessageStore) _messageStore).getMessageCount());
-
- //The above publish message is sufficiently small not to fit in the header so no Body is required.
- //assertEquals("Message body count incorrect in the ContentBodyMap", messageCount, ((TestableMemoryMessageStore) _messageStore).getContentBodyMap().size());
- }
-
- protected AMQShortString subscribe(InternalTestProtocolSession session, AMQChannel channel, AMQQueue queue)
- {
- try
- {
- return channel.subscribeToQueue(null, queue, true, null, false, true);
- }
- catch (AMQException e)
- {
- e.printStackTrace();
- fail(e.getMessage());
- }
-
- //Keep the compiler happy
- return null;
- }
-
- protected AMQShortString browse(AMQChannel channel, AMQQueue queue)
- {
- try
- {
- FieldTable filters = new FieldTable();
- filters.put(AMQPFilterTypes.NO_CONSUME.getValue(), true);
-
- return channel.subscribeToQueue(null, queue, true, filters, false, true);
- }
- catch (AMQException e)
- {
- e.printStackTrace();
- fail(e.getMessage());
- }
-
- //Keep the compiler happy
- return null;
- }
-
- public void publishMessages(InternalTestProtocolSession session, AMQChannel channel, int messages) throws AMQException
- {
- MessagePublishInfo info = new MessagePublishInfo()
- {
- public AMQShortString getExchange()
- {
- return ExchangeDefaults.DEFAULT_EXCHANGE_NAME;
- }
-
- public void setExchange(AMQShortString exchange)
- {
-
- }
-
- public boolean isImmediate()
- {
- return false;
- }
-
- public boolean isMandatory()
- {
- return false;
- }
-
- public AMQShortString getRoutingKey()
- {
- return new AMQShortString(getName());
- }
- };
-
- for (int count = 0; count < messages; count++)
- {
- channel.setPublishFrame(info, _virtualHost.getExchangeRegistry().getExchange(info.getExchange()));
-
- //Set the body size
- ContentHeaderBody _headerBody = new ContentHeaderBody();
- _headerBody.bodySize = 0;
-
- //Set Minimum properties
- BasicContentHeaderProperties properties = new BasicContentHeaderProperties();
-
- properties.setExpiration(0L);
- properties.setTimestamp(System.currentTimeMillis());
-
- //Make Message Persistent
- properties.setDeliveryMode((byte) 2);
-
- _headerBody.setProperties(properties);
-
- channel.publishContentHeader(_headerBody);
- }
-
- }
-
- public void acknowledge(AMQChannel channel, long deliveryTag)
- {
- try
- {
- channel.acknowledgeMessage(deliveryTag, false);
- }
- catch (AMQException e)
- {
- e.printStackTrace();
- fail(e.getMessage());
- }
- }
-
- public IApplicationRegistry getRegistry()
- {
- return _registry;
- }
-
- public void setRegistry(IApplicationRegistry registry)
- {
- _registry = registry;
- }
-
- public MessageStore getMessageStore()
- {
- return _messageStore;
- }
-
- public void setMessageStore(MessageStore messageStore)
- {
- _messageStore = messageStore;
- }
-
- public MockChannel getChannel()
- {
- return _channel;
- }
-
- public void setChannel(MockChannel channel)
- {
- _channel = channel;
- }
-
- public InternalTestProtocolSession getSession()
- {
- return _session;
- }
-
- public void setSession(InternalTestProtocolSession session)
- {
- _session = session;
- }
-
- public VirtualHost getVirtualHost()
- {
- return _virtualHost;
- }
-
- public void setVirtualHost(VirtualHost virtualHost)
- {
- _virtualHost = virtualHost;
- }
-
- public AMQQueue getQueue()
- {
- return _queue;
- }
-
- public void setQueue(AMQQueue queue)
- {
- _queue = queue;
- }
-
- public AMQShortString getQUEUE_NAME()
- {
- return QUEUE_NAME;
- }
-
- public void setQUEUE_NAME(AMQShortString QUEUE_NAME)
- {
- this.QUEUE_NAME = QUEUE_NAME;
- }
-
- public ServerConfiguration getConfiguration()
- {
- return _configuration;
- }
-
- public void setConfiguration(ServerConfiguration configuration)
- {
- _configuration = configuration;
- }
-
- public XMLConfiguration getConfigXml()
- {
- return _configXml;
- }
-
- public void setConfigXml(XMLConfiguration configXml)
- {
- _configXml = configXml;
- }
-
- public boolean isStarted()
- {
- return _started;
- }
-
- public void setStarted(boolean started)
- {
- _started = started;
- }
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/util/LoggingProxyTest.java b/java/broker/src/test/java/org/apache/qpid/server/util/LoggingProxyTest.java
deleted file mode 100644
index c7db51016e..0000000000
--- a/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/java/broker/src/test/java/org/apache/qpid/server/util/TestApplicationRegistry.java b/java/broker/src/test/java/org/apache/qpid/server/util/TestApplicationRegistry.java
deleted file mode 100644
index af8997cf40..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/util/TestApplicationRegistry.java
+++ /dev/null
@@ -1,48 +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 org.apache.commons.configuration.ConfigurationException;
-import org.apache.qpid.server.configuration.ServerConfiguration;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-import org.apache.qpid.server.security.auth.database.PropertiesPrincipalDatabaseManager;
-
-import java.util.Properties;
-
-
-public class TestApplicationRegistry extends ApplicationRegistry
-{
- public TestApplicationRegistry(ServerConfiguration config) throws ConfigurationException
- {
- super(config);
- }
-
- protected void createDatabaseManager(ServerConfiguration configuration) throws Exception
- {
- Properties users = new Properties();
- users.put("guest","guest");
- users.put("admin","admin");
- _databaseManager = new PropertiesPrincipalDatabaseManager("testPasswordFile", users);
- }
-
-}
-
-
diff --git a/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/SlowConsumerDetectionConfigurationTest.java b/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/SlowConsumerDetectionConfigurationTest.java
deleted file mode 100644
index cc11d68e07..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/SlowConsumerDetectionConfigurationTest.java
+++ /dev/null
@@ -1,346 +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.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;
-
-import java.util.concurrent.TimeUnit;
-
-/**
- * Provide Unit Test coverage of the virtualhost SlowConsumer Configuration
- * This is what controls how often the plugin will execute
- */
-public class SlowConsumerDetectionConfigurationTest extends InternalBrokerBaseCase
-{
-
- /**
- * Default Testing:
- *
- * Provide a fully complete and valid configuration specifying 'delay' and
- * 'timeunit' and ensure that it is correctly processed.
- *
- * Ensure no exceptions are thrown and that we get the same values back that
- * were put into the configuration.
- */
- public void testConfigLoadingValidConfig()
- {
- SlowConsumerDetectionConfiguration config = new SlowConsumerDetectionConfiguration();
-
- XMLConfiguration xmlconfig = new XMLConfiguration();
-
- long DELAY=10;
- String TIMEUNIT=TimeUnit.MICROSECONDS.toString();
- xmlconfig.addProperty("delay", String.valueOf(DELAY));
- xmlconfig.addProperty("timeunit", TIMEUNIT);
-
- // Create a CompositeConfiguration as this is what the broker uses
- CompositeConfiguration composite = new CompositeConfiguration();
- composite.addConfiguration(xmlconfig);
-
- try
- {
- config.setConfiguration("", composite);
- }
- catch (ConfigurationException e)
- {
- e.printStackTrace();
- fail(e.getMessage());
- }
-
- assertEquals("Delay not correctly returned.", DELAY, config.getDelay());
- assertEquals("TimeUnit not correctly returned.",
- TIMEUNIT, String.valueOf(config.getTimeUnit()));
- }
-
- /**
- * Default Testing:
- *
- * Test Missing TimeUnit value gets default.
- *
- * The TimeUnit value is optional and default to SECONDS.
- *
- * Test that if we do not specify a TimeUnit then we correctly get seconds.
- *
- * Also verify that relying on the default does not impact the setting of
- * the 'delay' value.
- *
- */
- public void testConfigLoadingMissingTimeUnitDefaults()
- {
- SlowConsumerDetectionConfiguration config = new SlowConsumerDetectionConfiguration();
-
- XMLConfiguration xmlconfig = new XMLConfiguration();
-
- long DELAY=10;
- xmlconfig.addProperty("delay", String.valueOf(DELAY));
-
- // Create a CompositeConfiguration as this is what the broker uses
- CompositeConfiguration composite = new CompositeConfiguration();
- composite.addConfiguration(xmlconfig);
- try
- {
- config.setConfiguration("", composite);
- }
- catch (ConfigurationException e)
- {
- e.printStackTrace();
- fail(e.getMessage());
- }
-
- assertEquals("Delay not correctly returned.", DELAY, config.getDelay());
- assertEquals("Default TimeUnit incorrect", TimeUnit.SECONDS, config.getTimeUnit());
- }
-
- /**
- * Input Testing:
- *
- * TimeUnit parsing requires the String value be in UpperCase.
- * Ensure we can handle when the user doesn't know this.
- *
- * Same test as 'testConfigLoadingValidConfig' but checking that
- * the timeunit field is not case sensitive.
- * i.e. the toUpper is being correctly applied.
- */
- public void testConfigLoadingValidConfigStrangeTimeUnit()
- {
- SlowConsumerDetectionConfiguration config = new SlowConsumerDetectionConfiguration();
-
- XMLConfiguration xmlconfig = new XMLConfiguration();
-
- long DELAY=10;
-
- xmlconfig.addProperty("delay", DELAY);
- xmlconfig.addProperty("timeunit", "MiCrOsEcOnDs");
-
- // Create a CompositeConfiguration as this is what the broker uses
- CompositeConfiguration composite = new CompositeConfiguration();
- composite.addConfiguration(xmlconfig);
-
- try
- {
- config.setConfiguration("", composite);
- }
- catch (ConfigurationException e)
- {
- e.printStackTrace();
- fail(e.getMessage());
- }
-
- assertEquals("Delay not correctly returned.", DELAY, config.getDelay());
- assertEquals("TimeUnit not correctly returned.",
- TimeUnit.MICROSECONDS.toString(), String.valueOf(config.getTimeUnit()));
-
- }
-
- /**
- * Failure Testing:
- *
- * Test that delay must be long not a string value.
- * Provide a delay as a written value not a long. 'ten'.
- *
- * This should throw a configuration exception which is being trapped and
- * verified to be the right exception, a NumberFormatException.
- *
- */
- public void testConfigLoadingInValidDelayString()
- {
- SlowConsumerDetectionConfiguration config = new SlowConsumerDetectionConfiguration();
-
- XMLConfiguration xmlconfig = new XMLConfiguration();
-
- xmlconfig.addProperty("delay", "ten");
- xmlconfig.addProperty("timeunit", TimeUnit.MICROSECONDS.toString());
-
- // Create a CompositeConfiguration as this is what the broker uses
- CompositeConfiguration composite = new CompositeConfiguration();
- composite.addConfiguration(xmlconfig);
-
- try
- {
- config.setConfiguration("", composite);
- fail("Configuration should fail to validate");
- }
- catch (ConfigurationException e)
- {
- Throwable cause = e.getCause();
-
- assertEquals("Cause not correct", NumberFormatException.class, cause.getClass());
- }
- }
-
- /**
- * Failure Testing:
- *
- * Test that negative delays are invalid.
- *
- * Delay must be a positive value as negative delay means doesn't make sense.
- *
- * Configuration exception with a useful message should be thrown here.
- *
- */
- public void testConfigLoadingInValidDelayNegative()
- {
- SlowConsumerDetectionConfiguration config = new SlowConsumerDetectionConfiguration();
-
- XMLConfiguration xmlconfig = new XMLConfiguration();
-
- xmlconfig.addProperty("delay", "-10");
- xmlconfig.addProperty("timeunit", TimeUnit.MICROSECONDS.toString());
-
- // Create a CompositeConfiguration as this is what the broker uses
- CompositeConfiguration composite = new CompositeConfiguration();
- composite.addConfiguration(xmlconfig);
-
- try
- {
- config.setConfiguration("", composite);
- fail("Configuration should fail to validate");
- }
- catch (ConfigurationException e)
- {
- Throwable cause = e.getCause();
-
- assertNotNull("Configuration Exception must not be null.", cause);
- assertEquals("Cause not correct",
- ConfigurationException.class, cause.getClass());
- assertEquals("Incorrect message.",
- "SlowConsumerDetectionConfiguration: 'delay' must be a Positive Long value.",
- cause.getMessage());
- }
- }
-
- /**
- * Failure Testing:
- *
- * Test that delay cannot be 0.
- *
- * A zero delay means run constantly. This is not how VirtualHostTasks
- * are designed to be run so we dis-allow the use of 0 delay.
- *
- * Same test as 'testConfigLoadingInValidDelayNegative' but with a 0 value.
- *
- */
- public void testConfigLoadingInValidDelayZero()
- {
- SlowConsumerDetectionConfiguration config = new SlowConsumerDetectionConfiguration();
-
- XMLConfiguration xmlconfig = new XMLConfiguration();
-
- xmlconfig.addProperty("delay", "0");
- xmlconfig.addProperty("timeunit", TimeUnit.MICROSECONDS.toString());
-
- // Create a CompositeConfiguration as this is what the broker uses
- CompositeConfiguration composite = new CompositeConfiguration();
- composite.addConfiguration(xmlconfig);
-
- try
- {
- config.setConfiguration("", composite);
- fail("Configuration should fail to validate");
- }
- catch (ConfigurationException e)
- {
- Throwable cause = e.getCause();
-
- assertNotNull("Configuration Exception must not be null.", cause);
- assertEquals("Cause not correct",
- ConfigurationException.class, cause.getClass());
- assertEquals("Incorrect message.",
- "SlowConsumerDetectionConfiguration: 'delay' must be a Positive Long value.",
- cause.getMessage());
- }
- }
-
- /**
- * Failure Testing:
- *
- * Test that missing delay fails.
- * If we have no delay then we do not pick a default. So a Configuration
- * Exception is thrown.
- *
- * */
- public void testConfigLoadingInValidMissingDelay()
- {
- SlowConsumerDetectionConfiguration config = new SlowConsumerDetectionConfiguration();
-
- XMLConfiguration xmlconfig = new XMLConfiguration();
-
- xmlconfig.addProperty("timeunit", TimeUnit.SECONDS.toString());
-
- // Create a CompositeConfiguration as this is what the broker uses
- CompositeConfiguration composite = new CompositeConfiguration();
- composite.addConfiguration(xmlconfig);
- try
- {
- config.setConfiguration("", composite);
- fail("Configuration should fail to validate");
- }
- catch (ConfigurationException e)
- {
- assertEquals("Incorrect message.", "SlowConsumerDetectionConfiguration: unable to configure invalid delay:null", e.getMessage());
- }
- }
-
- /**
- * Failure Testing:
- *
- * Test that erroneous TimeUnit fails.
- *
- * Valid TimeUnit values vary based on the JVM version i.e. 1.6 added HOURS/DAYS etc.
- *
- * We don't test the values for TimeUnit are accepted other than MILLISECONDS in the
- * positive testing at the start.
- *
- * Here we ensure that an erroneous for TimeUnit correctly throws an exception.
- *
- * We test with 'foo', which will never be a TimeUnit
- *
- */
- public void testConfigLoadingInValidTimeUnit()
- {
- SlowConsumerDetectionConfiguration config = new SlowConsumerDetectionConfiguration();
-
- String TIMEUNIT = "foo";
- XMLConfiguration xmlconfig = new XMLConfiguration();
-
- xmlconfig.addProperty("delay", "10");
- xmlconfig.addProperty("timeunit", TIMEUNIT);
-
- // Create a CompositeConfiguration as this is what the broker uses
- CompositeConfiguration composite = new CompositeConfiguration();
- composite.addConfiguration(xmlconfig);
- try
- {
- config.setConfiguration("", composite);
- fail("Configuration should fail to validate");
- }
- catch (ConfigurationException e)
- {
- assertEquals("Incorrect message.", "Unable to configure Slow Consumer Detection invalid TimeUnit:" + TIMEUNIT, e.getMessage());
- }
- }
-
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/SlowConsumerDetectionPolicyConfigurationTest.java b/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/SlowConsumerDetectionPolicyConfigurationTest.java
deleted file mode 100644
index efb898e365..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/SlowConsumerDetectionPolicyConfigurationTest.java
+++ /dev/null
@@ -1,104 +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.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;
-
-/**
- * Test class to ensure that the policy configuration can be processed.
- */
-public class SlowConsumerDetectionPolicyConfigurationTest extends InternalBrokerBaseCase
-{
-
- /**
- * Input Testing:
- *
- * Test that a given String can be set and retrieved through the configuration
- *
- * No validation is being performed to ensure that the policy exists. Only
- * that a value can be set for the policy.
- *
- */
- public void testConfigLoadingValidConfig()
- {
- SlowConsumerDetectionPolicyConfiguration config = new SlowConsumerDetectionPolicyConfiguration();
-
- XMLConfiguration xmlconfig = new XMLConfiguration();
-
- String policyName = "TestPolicy";
- xmlconfig.addProperty("name", policyName);
-
- // Create a CompositeConfiguration as this is what the broker uses
- CompositeConfiguration composite = new CompositeConfiguration();
- composite.addConfiguration(xmlconfig);
-
- try
- {
- config.setConfiguration("", composite);
- }
- catch (ConfigurationException e)
- {
- e.printStackTrace();
- fail(e.getMessage());
- }
-
- assertEquals("Policy name not retrieved as expected.",
- policyName, config.getPolicyName());
- }
-
- /**
- * Failure Testing:
- *
- * Test that providing a configuration section without the 'name' field
- * causes an exception to be thrown.
- *
- * An empty configuration is provided and the thrown exception message
- * is checked to confirm the right reason.
- *
- */
- public void testConfigLoadingInValidConfig()
- {
- SlowConsumerDetectionPolicyConfiguration config = new SlowConsumerDetectionPolicyConfiguration();
-
- XMLConfiguration xmlconfig = new XMLConfiguration();
-
-
- // Create a CompositeConfiguration as this is what the broker uses
- CompositeConfiguration composite = new CompositeConfiguration();
- composite.addConfiguration(xmlconfig);
-
- try
- {
- config.setConfiguration("", composite);
- fail("Config is invalid so won't validate.");
- }
- catch (ConfigurationException e)
- {
- e.printStackTrace();
- assertEquals("Exception message not as expected.", "No Slow consumer policy defined.", e.getMessage());
- }
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/SlowConsumerDetectionQueueConfigurationTest.java b/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/SlowConsumerDetectionQueueConfigurationTest.java
deleted file mode 100644
index be86037dd8..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/SlowConsumerDetectionQueueConfigurationTest.java
+++ /dev/null
@@ -1,185 +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.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;
-
-/**
- * Unit test the QueueConfiguration processing.
- *
- * This is slightly awkward as the {@link SlowConsumerDetectionQueueConfiguration}
- * requries that a policy be available.
- * <p>
- * So all the Valid test much catch the ensuing {@link ConfigurationException} and
- * validate that the error is due to a lack of a valid policy.
- */
-public class SlowConsumerDetectionQueueConfigurationTest extends InternalBrokerBaseCase
-{
- /**
- * Test a fully loaded configuration file.
- *
- * It is not an error to have all control values specified.
- * <p>
- * Here we need to catch the {@link ConfigurationException} that ensues due to lack
- * of a policy plugin.
- */
- public void testConfigLoadingValidConfig()
- {
- SlowConsumerDetectionQueueConfiguration config = new SlowConsumerDetectionQueueConfiguration();
-
- XMLConfiguration xmlconfig = new XMLConfiguration();
-
- xmlconfig.addProperty("messageAge", "60000");
- xmlconfig.addProperty("depth", "1024");
- xmlconfig.addProperty("messageCount", "10");
-
- // Create a CompositeConfiguration as this is what the broker uses
- CompositeConfiguration composite = new CompositeConfiguration();
- composite.addConfiguration(xmlconfig);
-
- try
- {
- config.setConfiguration("", composite);
- fail("No Policies are avaialbe to load in a unit test");
- }
- catch (ConfigurationException e)
- {
- assertTrue("Exception message incorrect, was: " + e.getMessage(),
- e.getMessage().startsWith("No Slow Consumer Policy specified. Known Policies:["));
- }
- }
-
- /**
- * When we do not specify any control value then a {@link ConfigurationException}
- * must be thrown to remind us.
- */
- public void testConfigLoadingMissingConfig()
- {
- SlowConsumerDetectionQueueConfiguration config = new SlowConsumerDetectionQueueConfiguration();
-
- XMLConfiguration xmlconfig = new XMLConfiguration();
-
- // Create a CompositeConfiguration as this is what the broker uses
- CompositeConfiguration composite = new CompositeConfiguration();
- composite.addConfiguration(xmlconfig);
-
- try
- {
- config.setConfiguration("", composite);
- fail("No Policies are avaialbe to load in a unit test");
- }
- catch (ConfigurationException e)
- {
-
- assertEquals("At least one configuration property('messageAge','depth'" +
- " or 'messageCount') must be specified.", e.getMessage());
- }
- }
-
- /**
- * Setting messageAge on its own is enough to have a valid configuration
- *
- * Here we need to catch the {@link ConfigurationException} that ensues due to lack
- * of a policy plugin.
- */
- public void testConfigLoadingMessageAgeOk()
- {
- SlowConsumerDetectionQueueConfiguration config = new SlowConsumerDetectionQueueConfiguration();
-
- XMLConfiguration xmlconfig = new XMLConfiguration();
- xmlconfig.addProperty("messageAge", "60000");
-
- // Create a CompositeConfiguration as this is what the broker uses
- CompositeConfiguration composite = new CompositeConfiguration();
- composite.addConfiguration(xmlconfig);
-
- try
- {
- config.setConfiguration("", composite);
- fail("No Policies are avaialbe to load in a unit test");
- }
- catch (ConfigurationException e)
- {
- assertTrue("Exception message incorrect, was: " + e.getMessage(),
- e.getMessage().startsWith("No Slow Consumer Policy specified. Known Policies:["));
- }
- }
-
- /**
- * Setting depth on its own is enough to have a valid configuration.
- *
- * Here we need to catch the {@link ConfigurationException} that ensues due to lack
- * of a policy plugin.
- */
- public void testConfigLoadingDepthOk()
- {
- SlowConsumerDetectionQueueConfiguration config = new SlowConsumerDetectionQueueConfiguration();
-
- XMLConfiguration xmlconfig = new XMLConfiguration();
- xmlconfig.addProperty("depth", "1024");
-
- // Create a CompositeConfiguration as this is what the broker uses
- CompositeConfiguration composite = new CompositeConfiguration();
- composite.addConfiguration(xmlconfig);
-
- try
- {
- config.setConfiguration("", composite);
- fail("No Policies are avaialbe to load in a unit test");
- }
- catch (ConfigurationException e)
- {
- assertTrue("Exception message incorrect, was: " + e.getMessage(),
- e.getMessage().startsWith("No Slow Consumer Policy specified. Known Policies:["));
- }
- }
-
- /**
- * Setting messageCount on its own is enough to have a valid configuration.
- *
- * Here we need to catch the {@link ConfigurationException} that ensues due to lack
- * of a policy plugin.
- */
- public void testConfigLoadingMessageCountOk()
- {
- SlowConsumerDetectionQueueConfiguration config = new SlowConsumerDetectionQueueConfiguration();
-
- XMLConfiguration xmlconfig = new XMLConfiguration();
- xmlconfig.addProperty("messageCount", "10");
-
- // Create a CompositeConfiguration as this is what the broker uses
- CompositeConfiguration composite = new CompositeConfiguration();
- composite.addConfiguration(xmlconfig);
-
- try
- {
- config.setConfiguration("", composite);
- fail("No Policies are avaialbe to load in a unit test");
- }
- catch (ConfigurationException e)
- {
- assertTrue("Exception message incorrect, was: " + e.getMessage(),
- e.getMessage().startsWith("No Slow Consumer Policy specified. Known Policies:["));
- }
- }
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/policies/TopicDeletePolicyConfigurationTest.java b/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/policies/TopicDeletePolicyConfigurationTest.java
deleted file mode 100644
index 3d3cc810df..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/policies/TopicDeletePolicyConfigurationTest.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.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;
-
-/**
- * Test to ensure TopicDelete Policy configuration can be loaded.
- */
-public class TopicDeletePolicyConfigurationTest extends InternalBrokerBaseCase
-{
- /**
- * Test without any configuration being provided that the
- * deletePersistent option is disabled.
- */
- public void testNoConfigNoDeletePersistent()
- {
- TopicDeletePolicyConfiguration config = new TopicDeletePolicyConfiguration();
-
- assertFalse("TopicDelete Configuration with no config should not delete persistent queues.",
- config.deletePersistent());
- }
-
- /**
- * Test that with the correct configuration the deletePersistent option can
- * be enabled.
- *
- * Test creates a new Configuration object and passes in the xml snippet
- * that the ConfigurationPlugin would receive during normal execution.
- * This is the XML that would be matched for this plugin:
- * <topicdelete>
- * <delete-persistent>
- * <topicdelete>
- *
- * So it would be subset and passed in as just:
- * <delete-persistent>
- *
- *
- * The property should therefore be enabled.
- *
- */
- public void testConfigDeletePersistent()
- {
- TopicDeletePolicyConfiguration config = new TopicDeletePolicyConfiguration();
-
- XMLConfiguration xmlconfig = new XMLConfiguration();
-
- xmlconfig.addProperty("delete-persistent","");
-
- // Create a CompositeConfiguration as this is what the broker uses
- CompositeConfiguration composite = new CompositeConfiguration();
- composite.addConfiguration(xmlconfig);
-
- try
- {
- config.setConfiguration("",composite);
- }
- catch (ConfigurationException e)
- {
- fail(e.getMessage());
- }
-
- assertTrue("A configured TopicDelete should delete persistent queues.",
- config.deletePersistent());
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/policies/TopicDeletePolicyTest.java b/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/policies/TopicDeletePolicyTest.java
deleted file mode 100644
index a2e83add05..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/policies/TopicDeletePolicyTest.java
+++ /dev/null
@@ -1,293 +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.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;
-import org.apache.qpid.server.exchange.DirectExchange;
-import org.apache.qpid.server.exchange.TopicExchange;
-import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.server.protocol.InternalTestProtocolSession;
-import org.apache.qpid.server.queue.AMQQueue;
-import org.apache.qpid.server.queue.MockAMQQueue;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-import org.apache.qpid.server.util.InternalBrokerBaseCase;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-
-public class TopicDeletePolicyTest extends InternalBrokerBaseCase
-{
-
- TopicDeletePolicyConfiguration _config;
-
- VirtualHost _defaultVhost;
- InternalTestProtocolSession _connection;
-
- public void setUp() throws Exception
- {
- super.setUp();
-
- _defaultVhost = ApplicationRegistry.getInstance().getVirtualHostRegistry().getDefaultVirtualHost();
-
- _connection = new InternalTestProtocolSession(_defaultVhost);
-
- _config = new TopicDeletePolicyConfiguration();
-
- XMLConfiguration config = new XMLConfiguration();
-
- _config.setConfiguration("", config);
- }
-
- private MockAMQQueue createOwnedQueue()
- {
- MockAMQQueue queue = new MockAMQQueue("testQueue");
-
- _defaultVhost.getQueueRegistry().registerQueue(queue);
-
- try
- {
- AMQChannel channel = new AMQChannel(_connection, 0, null);
- _connection.addChannel(channel);
-
- queue.setExclusiveOwningSession(channel);
- }
- catch (AMQException e)
- {
- fail("Unable to create Channel:" + e.getMessage());
- }
-
- return queue;
- }
-
- private void setQueueToAutoDelete(final AMQQueue queue)
- {
- ((MockAMQQueue) queue).setAutoDelete(true);
-
- queue.setDeleteOnNoConsumers(true);
- final AMQProtocolSession.Task deleteQueueTask =
- new AMQProtocolSession.Task()
- {
- public void doTask(AMQProtocolSession session) throws AMQException
- {
- queue.delete();
- }
- };
-
- ((AMQChannel) queue.getExclusiveOwningSession()).getProtocolSession().addSessionCloseTask(deleteQueueTask);
- }
-
- /** Check that a null queue passed in does not upset the policy. */
- public void testNullQueueParameter() throws ConfigurationException
- {
- TopicDeletePolicy policy = new TopicDeletePolicy();
- policy.configure(_config);
-
- try
- {
- policy.performPolicy(null);
- }
- catch (Exception e)
- {
- fail("Exception should not be thrown:" + e.getMessage());
- }
-
- }
-
- /**
- * Set a owning Session to null which means this is not an exclusive queue
- * so the queue should not be deleted
- */
- public void testNonExclusiveQueue()
- {
- TopicDeletePolicy policy = new TopicDeletePolicy();
- policy.configure(_config);
-
- MockAMQQueue queue = createOwnedQueue();
-
- queue.setExclusiveOwningSession(null);
-
- policy.performPolicy(queue);
-
- assertFalse("Queue should not be deleted", queue.isDeleted());
- assertFalse("Connection should not be closed", _connection.isClosed());
- }
-
- /**
- * Test that exclusive JMS Queues are not deleted.
- * Bind the queue to the direct exchange (so it is a JMS Queue).
- *
- * JMS Queues are not to be processed so this should not delete the queue.
- */
- public void testQueuesAreNotProcessed()
- {
- TopicDeletePolicy policy = new TopicDeletePolicy();
- policy.configure(_config);
-
- MockAMQQueue queue = createOwnedQueue();
-
- queue.addBinding(new Binding(null, "bindingKey", queue, new DirectExchange(), null));
-
- policy.performPolicy(queue);
-
- assertFalse("Queue should not be deleted", queue.isDeleted());
- assertFalse("Connection should not be closed", _connection.isClosed());
- }
-
- /**
- * Give a non auto-delete queue is bound to the topic exchange the
- * TopicDeletePolicy will close the connection and delete the queue,
- */
- public void testNonAutoDeleteTopicIsNotClosed()
- {
- TopicDeletePolicy policy = new TopicDeletePolicy();
- policy.configure(_config);
-
- MockAMQQueue queue = createOwnedQueue();
-
- queue.addBinding(new Binding(null, "bindingKey", queue, new TopicExchange(), null));
-
- queue.setAutoDelete(false);
-
- policy.performPolicy(queue);
-
- assertFalse("Queue should not be deleted", queue.isDeleted());
- assertTrue("Connection should be closed", _connection.isClosed());
- }
-
- /**
- * Give a auto-delete queue bound to the topic exchange the TopicDeletePolicy will
- * close the connection and delete the queue
- */
- public void testTopicIsClosed()
- {
- TopicDeletePolicy policy = new TopicDeletePolicy();
- policy.configure(_config);
-
- final MockAMQQueue queue = createOwnedQueue();
-
- queue.addBinding(new Binding(null, "bindingKey", queue, new TopicExchange(), null));
-
- setQueueToAutoDelete(queue);
-
- policy.performPolicy(queue);
-
- assertTrue("Queue should be deleted", queue.isDeleted());
- assertTrue("Connection should be closed", _connection.isClosed());
- }
-
- /**
- * Give a queue bound to the topic exchange the TopicDeletePolicy will
- * close the connection and NOT delete the queue
- */
- public void testNonAutoDeleteTopicIsClosedNotDeleted()
- {
- TopicDeletePolicy policy = new TopicDeletePolicy();
- policy.configure(_config);
-
- MockAMQQueue queue = createOwnedQueue();
-
- queue.addBinding(new Binding(null, "bindingKey", queue, new TopicExchange(), null));
-
- policy.performPolicy(queue);
-
- assertFalse("Queue should not be deleted", queue.isDeleted());
- assertTrue("Connection should be closed", _connection.isClosed());
- }
-
- /**
- * Give a queue bound to the topic exchange the TopicDeletePolicy suitably
- * configured with the delete-persistent tag will close the connection
- * and delete the queue
- */
- public void testPersistentTopicIsClosedAndDeleted()
- {
- //Set the config to delete persistent queues
- _config.getConfig().addProperty("delete-persistent", "");
-
- TopicDeletePolicy policy = new TopicDeletePolicy();
- policy.configure(_config);
-
- assertTrue("Config was not updated to delete Persistent topics",
- _config.deletePersistent());
-
- MockAMQQueue queue = createOwnedQueue();
-
- queue.addBinding(new Binding(null, "bindingKey", queue, new TopicExchange(), null));
-
- policy.performPolicy(queue);
-
- assertTrue("Queue should be deleted", queue.isDeleted());
- assertTrue("Connection should be closed", _connection.isClosed());
- }
-
- /**
- * Give a queue bound to the topic exchange the TopicDeletePolicy not
- * configured to close a persistent queue
- */
- public void testPersistentTopicIsClosedAndDeletedNullConfig()
- {
- TopicDeletePolicy policy = new TopicDeletePolicy();
- // Explicity say we are not configuring the policy.
- policy.configure(null);
-
- MockAMQQueue queue = createOwnedQueue();
-
- queue.addBinding(new Binding(null, "bindingKey", queue, new TopicExchange(), null));
-
- policy.performPolicy(queue);
-
- assertFalse("Queue should not be deleted", queue.isDeleted());
- assertTrue("Connection should be closed", _connection.isClosed());
- }
-
- public void testNonExclusiveQueueNullConfig()
- {
- _config = null;
- testNonExclusiveQueue();
- }
-
- public void testQueuesAreNotProcessedNullConfig()
- {
- _config = null;
- testQueuesAreNotProcessed();
- }
-
- public void testNonAutoDeleteTopicIsNotClosedNullConfig()
- {
- _config = null;
- testNonAutoDeleteTopicIsNotClosed();
- }
-
- public void testTopicIsClosedNullConfig()
- {
- _config = null;
- testTopicIsClosed();
- }
-
- public void testNonAutoDeleteTopicIsClosedNotDeletedNullConfig() throws AMQException
- {
- _config = null;
- testNonAutoDeleteTopicIsClosedNotDeleted();
- }
-
-}
diff --git a/java/broker/src/test/java/org/apache/qpid/util/MockChannel.java b/java/broker/src/test/java/org/apache/qpid/util/MockChannel.java
deleted file mode 100644
index 9bd1e7c5e1..0000000000
--- a/java/broker/src/test/java/org/apache/qpid/util/MockChannel.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.util;
-
-import org.apache.qpid.server.AMQChannel;
-import org.apache.qpid.server.subscription.Subscription;
-import org.apache.qpid.server.store.MessageStore;
-import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.AMQShortString;
-
-public class MockChannel extends AMQChannel
-{
- public MockChannel(AMQProtocolSession session, int channelId, MessageStore messageStore)
- throws AMQException
- {
- super(session, channelId, messageStore);
- }
-
-
-
-}
diff --git a/java/broker/src/velocity/java/org/apache/qpid/server/logging/GenerateLogMessages.java b/java/broker/src/velocity/java/org/apache/qpid/server/logging/GenerateLogMessages.java
deleted file mode 100644
index a39799a6b6..0000000000
--- a/java/broker/src/velocity/java/org/apache/qpid/server/logging/GenerateLogMessages.java
+++ /dev/null
@@ -1,527 +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.logging;
-
-import org.apache.velocity.VelocityContext;
-import org.apache.velocity.app.Velocity;
-
-import java.io.File;
-import java.io.FileWriter;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Locale;
-import java.util.Properties;
-import java.util.ResourceBundle;
-
-public class GenerateLogMessages
-{
- private boolean DEBUG = false;
- private String _tmplDir;
- private String _outputDir;
- private List<String> _logMessages = new LinkedList<String>();
- private String _packageSource;
-
- public static void main(String[] args)
- {
- GenerateLogMessages generator = null;
- try
- {
- generator = new GenerateLogMessages(args);
- }
- catch (IllegalAccessException iae)
- {
- // This occurs when args does not contain Template and output dirs.
- System.exit(-1);
- }
- catch (Exception e)
- {
- //This is thrown by the Velocity Engine initialisation
- e.printStackTrace();
- System.exit(-1);
- }
-
- try
- {
- System.out.println("Running LogMessage Generator");
- generator.run();
- }
- catch (InvalidTypeException e)
- {
- // This occurs when a type other than 'number' appears in the
- // paramater config {0, number...}
- System.err.println(e.getMessage());
- System.exit(-1);
- }
- catch (Exception e)
- {
- e.printStackTrace();
- System.exit(-1);
- }
- }
-
- GenerateLogMessages(String[] args) throws Exception
- {
- processArgs(args);
-
- // We need the template and input files to run.
- if (_tmplDir == null || _outputDir == null || _logMessages.size() == 0 || _packageSource == null)
- {
- showUsage();
- throw new IllegalAccessException();
- }
-
- // Initialise the Velocity Engine, Telling it where our macro lives
- Properties props = new Properties();
- props.setProperty("file.resource.loader.path", _tmplDir);
- Velocity.init(props);
- }
-
- private void showUsage()
- {
- System.out.println("Broker LogMessageGenerator v.2.0");
- System.out.println("Usage: GenerateLogMessages: [-d] -t <Template Dir> -o <Output Root> -s <Source Directory> <List of _logmessage.property files to process>");
- System.out.println(" where -d : Additional debug loggin.\n" +
- " Template Dir: Is the base template to use.");
- System.out.println(" Output Root: The root form where the LogMessage Classes will be placed.");
- System.out.println(" Source Dir : The root form where the logmessasge.property files can be found.");
- System.out.println(" _logmessage.property files must include the full package structure.");
- }
-
- public void run() throws InvalidTypeException, Exception
- {
- for (String file : _logMessages)
- {
- debug("Processing File:" + file);
-
- createMessageClass(file);
- }
- }
-
- /**
- * Process the args for:
- * -t|T value for the template location
- * -o|O value for the output directory
- *
- * @param args the commandline arguments
- */
- private void processArgs(String[] args)
- {
- // Crude but simple...
- for (int i = 0; i < args.length; i++)
- {
- String arg = args[i];
- if (args[i].endsWith("_logmessages.properties"))
- {
- _logMessages.add(args[i]);
- }
- else if (arg.charAt(0) == '-')
- {
- switch (arg.charAt(1))
- {
- case 'o':
- case 'O':
- if (++i < args.length)
- {
- _outputDir = args[i];
- }
- break;
- case 't':
- case 'T':
- if (++i < args.length)
- {
- _tmplDir = args[i];
- }
- break;
- case 's':
- case 'S':
- if (++i < args.length)
- {
- _packageSource = args[i];
- }
- break;
- case 'd':
- case 'D':
- DEBUG=true;
- break;
- }
- }
- }
- }
-
- /**
- * This is the main method that generates the _Messages.java file.
- * The class is generated by extracting the list of messges from the
- * available LogMessages Resource.
- *
- * The extraction is done based on typeIdentifier which is a 3-digit prefix
- * on the messages e.g. BRK for Broker.
- *
- * @throws InvalidTypeException when an unknown parameter type is used in the properties file
- * @throws Exception thrown by velocity if there is an error
- */
- private void createMessageClass(String file)
- throws InvalidTypeException, Exception
- {
- VelocityContext context = new VelocityContext();
-
- String bundle = file.replace(File.separator, ".");
-
- int packageStartIndex = bundle.indexOf(_packageSource) + _packageSource.length() + 2;
-
- bundle = bundle.substring(packageStartIndex, bundle.indexOf(".properties"));
-
- System.out.println("Creating Class for bundle:" + bundle);
-
- ResourceBundle fileBundle = ResourceBundle.getBundle(bundle, Locale.US);
-
- // Pull the bit from /os/path/<className>.logMessages from the bundle name
- String className = file.substring(file.lastIndexOf(File.separator) + 1, file.lastIndexOf("_"));
- debug("Creating ClassName form file:" + className);
-
- String packageString = bundle.substring(0, bundle.indexOf(className));
- String packagePath = packageString.replace(".", File.separator);
-
- debug("Package path:" + packagePath);
-
- File outputDirectory = new File(_outputDir + File.separator + packagePath);
- if (!outputDirectory.exists())
- {
- if (!outputDirectory.mkdirs())
- {
- throw new IllegalAccessException("Unable to create package structure:" + outputDirectory);
- }
- }
-
- // Get the Data for this class and typeIdentifier
- HashMap<String, Object> typeData = prepareType(className, fileBundle);
-
- context.put("package", packageString.substring(0, packageString.lastIndexOf('.')));
- //Store the resource Bundle name for the macro
- context.put("resource", bundle);
-
- // Store this data in the context for the macro to access
- context.put("type", typeData);
-
- // Create the file writer to put the finished file in
- String outputFile = _outputDir + File.separator + packagePath + className + "Messages.java";
- debug("Creating Java file:" + outputFile);
- FileWriter output = new FileWriter(outputFile);
-
- // Run Velocity to create the output file.
- // Fix the default file encoding to 'ISO-8859-1' rather than let
- // Velocity fix it. This is the encoding format for the macro.
- Velocity.mergeTemplate("LogMessages.vm", "ISO-8859-1", context, output);
-
- //Close our file.
- output.flush();
- output.close();
- }
-
- /**
- * This method does the processing and preparation of the data to be added
- * to the Velocity context so that the macro can access and process the data
- *
- * The given messageKey (e.g. 'BRK') uses a 3-digit code used to match
- * the property key from the loaded 'LogMessages' ResourceBundle.
- *
- * This gives a list of messages which are to be associated with the given
- * messageName (e.g. 'Broker')
- *
- * Each of the messages in the list are then processed to identify how many
- * parameters the MessageFormat call is expecting. These parameters are
- * identified by braces ('{}') so a quick count of these can then be used
- * to create a defined parameter list.
- *
- * Rather than defaulting all parameters to String a check is performed to
- * see if a 'number' value has been requested. e.g. {0. number}
- * {@see MessageFormat}. If a parameter has a 'number' type then the
- * parameter will be defined as an Number value. This allows for better
- * type checking during compilation whilst allowing the log message to
- * maintain formatting controls.
- *
- * OPTIONS
- *
- * The returned hashMap contains the following structured data:
- *
- * - name - ClassName ('Broker')
- * - list[logEntryData] - methodName ('BRK_1001')
- * - name ('BRK-1001')
- * - format ('Startup : Version: {0} Build: {1}')
- * - parameters (list)
- * - type ('String'|'Number')
- * - name ('param1')
- * - options (list)
- * - name ('opt1')
- * - value ('AutoDelete')
- *
- * @param messsageName the name to give the Class e.g. 'Broker'
- *
- * @return A HashMap with data for the macro
- *
- * @throws InvalidTypeException when an unknown parameter type is used in the properties file
- */
- private HashMap<String, Object> prepareType(String messsageName, ResourceBundle messages) throws InvalidTypeException
- {
- // Load the LogMessages Resource Bundle
- Enumeration<String> messageKeys = messages.getKeys();
-
- //Create the return map
- HashMap<String, Object> messageTypeData = new HashMap<String, Object>();
- // Store the name to give to this Class <name>Messages.java
- messageTypeData.put("name", messsageName);
-
- // Prepare the list of log messages
- List<HashMap> logMessageList = new LinkedList<HashMap>();
- messageTypeData.put("list", logMessageList);
-
- //Process each of the properties
- while (messageKeys.hasMoreElements())
- {
- HashMap<String, Object> logEntryData = new HashMap<String, Object>();
-
- //Add MessageName to amp
- String message = messageKeys.nextElement();
-
- // Process the log message if it matches the specified key e.g.'BRK_'
- if (!message.equals("package"))
- {
- // Method names can't have a '-' in them so lets make it '_'
- // e.g. RECOVERY-STARTUP -> RECOVERY_STARTUP
- logEntryData.put("methodName", message.replace('-', '_'));
- // Store the real name so we can use that in the actual log.
- logEntryData.put("name", message);
-
- //Retrieve the actual log message string.
- String logMessage = messages.getString(message);
-
- // Store the value of the property so we can add it to the
- // Javadoc of the method.
- logEntryData.put("format", logMessage);
-
- // Add the parameters for this message
- logEntryData.put("parameters", extractParameters(logMessage));
-
- //Add the options for this messages
- logEntryData.put("options", extractOptions(logMessage));
-
- //Add this entry to the list for this class
- logMessageList.add(logEntryData);
- }
- }
-
- return messageTypeData;
- }
-
- /**
- * This method is responsible for extracting the options form the given log
- * message and providing a HashMap with the expected data:
- * - options (list)
- * - name ('opt1')
- * - value ('AutoDelete')
- *
- * The options list that this method provides must contain HashMaps that
- * have two entries. A 'name' and a 'value' these strings are important as
- * they are used in LogMessage.vm to extract the stored String during
- * processing of the template.
- *
- * The 'name' is a unique string that is used to name the boolean parameter
- * and refer to it later in the method body.
- *
- * The 'value' is used to provide documentation in the generated class to
- * aid readability.
- *
- * @param logMessage the message from the properties file
- *
- * @return list of option data
- */
- private List<HashMap<String, String>> extractOptions(String logMessage)
- {
- // Split the string on the start brace '{' this will give us the
- // details for each parameter that this message contains.
- // NOTE: Simply splitting on '[' prevents the use of nested options.
- // Currently there is no demand for nested options
- String[] optionString = logMessage.split("\\[");
- // 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
-
- // Create the parameter list for this item
- List<HashMap<String, String>> options = new LinkedList<HashMap<String, String>>();
-
- // Check that we have some parameters to process
- // Skip 0 as that will not be the first entry
- // Text {n,type,format} [option] text {m} [option with param{p}] more
- if (optionString.length > 1)
- {
- for (int index = 1; index < optionString.length; index++)
- {
- // Use a HashMap to store the type,name of the parameter
- // for easy retrieval in the macro template
- HashMap<String, String> option = new HashMap<String, String>();
-
- // Locate the end of the Option
- // NOTE: it is this simple matching on the first ']' that
- // prevents the nesting of options.
- // Currently there is no demand for nested options
- int end = optionString[index].indexOf("]");
-
- // The parameter type
- String value = optionString[index].substring(0, end);
-
- // Simply name the parameters by index.
- option.put("name", "opt" + index);
-
- //Store the value e.g. AutoDelete
- // We trim as we don't need to include any whitespace that is
- // used for formating. This is only used to aid readability of
- // of the generated code.
- option.put("value", value.trim());
-
- options.add(option);
- }
- }
-
- return options;
- }
-
- /**
- * This method is responsible for extract the parameters that are requried
- * for this log message. The data is returned in a HashMap that has the
- * following structure:
- * - parameters (list)
- * - type ('String'|'Number')
- * - name ('param1')
- *
- * The parameters list that is provided must contain HashMaps that have the
- * two named entries. A 'type' and a 'name' these strings are importans as
- * they are used in LogMessage.vm to extract and the stored String during
- * processing of the template
- *
- * The 'type' and 'name' values are used to populate the method signature.
- * This is what gives us the compile time validation of log messages.
- *
- * The 'name' must be unique as there may be many parameters. The value is
- * also used in the method body to pass the values through to the
- * MessageFormat class for formating the log message.
- *
- * @param logMessage the message from the properties file
- *
- * @return list of option data
- *
- * @throws InvalidTypeException if the FormatType is specified and is not 'number'
- */
- private List<HashMap<String, String>> extractParameters(String logMessage)
- throws InvalidTypeException
- {
- // Split the string on the start brace '{' this will give us the
- // details for each parameter that this message contains.
- 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}
-
- // Create the parameter list for this item
- List<HashMap<String, String>> parameters = new LinkedList<HashMap<String, String>>();
-
- // 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++)
- {
- // Use a HashMap to store the type,name of the parameter
- // for easy retrieval in the macro template
- HashMap<String, String> parameter = new HashMap<String, String>();
-
- // 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
- String type;
-
- //Be default all types are Strings
- if (typeIndex == -1)
- {
- type = "String";
- }
- else
- {
- //Check string ',....}' for existence of number
- // to identify this parameter as an integer
- // This allows for a style value to be present
- // Only check the text inside the braces '{}'
- int typeIndexEnd = parametersString[index].indexOf("}", typeIndex);
- String typeString = parametersString[index].substring(typeIndex, typeIndexEnd);
- if (typeString.contains("number") || typeString.contains("choice"))
- {
- type = "Number";
- }
- else
- {
- throw new InvalidTypeException("Invalid type(" + typeString + ") index (" + parameter.size() + ") in message:" + logMessage);
- }
-
- }
-
- //Store the data
- parameter.put("type", type);
- // Simply name the parameters by index.
- parameter.put("name", "param" + index);
-
- parameters.add(parameter);
- }
- }
-
- return parameters;
- }
-
- /**
- * Just a inner exception to be able to identify when a type that is not
- * 'number' occurs in the message parameter text.
- */
- private static class InvalidTypeException extends Exception
- {
- public InvalidTypeException(String message)
- {
- super(message);
- }
- }
-
- public void debug(String msg)
- {
- if (DEBUG)
- {
- System.out.println(msg);
- }
- }
-
-}
diff --git a/java/broker/src/velocity/templates/org/apache/qpid/server/logging/messages/LogMessages.vm b/java/broker/src/velocity/templates/org/apache/qpid/server/logging/messages/LogMessages.vm
deleted file mode 100644
index fd847fd513..0000000000
--- a/java/broker/src/velocity/templates/org/apache/qpid/server/logging/messages/LogMessages.vm
+++ /dev/null
@@ -1,200 +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 ${package};
-
-import static org.apache.qpid.server.logging.AbstractRootMessageLogger.DEFAULT_LOG_HIERARCHY_PREFIX;
-
-import org.apache.log4j.Logger;
-import org.apache.qpid.server.logging.LogMessage;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-
-import java.text.MessageFormat;
-import java.util.Locale;
-import java.util.ResourceBundle;
-
-/**
- * Generated Using GeneratedLogMessages and LogMessages.vm
- *
- * This file is based on the content of LogMessages.properties
- *
- * It is generated so that we can provide compile time validation of the
- * message parameters.
- *
- * DO NOT EDIT DIRECTLY THIS FILE IS GENERATED.
- *
- */
-public class ${type.name}Messages
-{
- static ResourceBundle _messages;
- static Locale _currentLocale;
-
- public static final String ${type.name.toUpperCase()}_LOG_HIERARCHY = DEFAULT_LOG_HIERARCHY_PREFIX + "${type.name.toLowerCase()}";
-#foreach( $message in ${type.list} )
- public static final String ${message.methodName.toUpperCase()}_LOG_HIERARCHY = DEFAULT_LOG_HIERARCHY_PREFIX + "${type.name.toLowerCase()}.${message.methodName.toLowerCase()}";
-#end
-
- static
- {
- Logger.getLogger(${type.name.toUpperCase()}_LOG_HIERARCHY);
-#foreach( $message in ${type.list} )
- Logger.getLogger(${message.methodName.toUpperCase()}_LOG_HIERARCHY);
-#end
-
- reload();
- }
-
- public static void reload()
- {
- if (ApplicationRegistry.isConfigured())
- {
- _currentLocale = ApplicationRegistry.getInstance().getConfiguration().getLocale();
- }
- else
- {
- _currentLocale = Locale.getDefault();
- }
-
- _messages = ResourceBundle.getBundle("${resource}", _currentLocale);
- }
-
-
-##
-## The list stored under key 'list' in the 'type' HashMap contains all the
-## log messages that this class should contain. So for each entry in the list
-## this template will create a new log method.
-##
-#foreach( $message in ${type.list} )
- /**
- * Log a ${type.name} message of the Format:
- * <pre>${message.format}</pre>
- * Optional values are contained in [square brackets] and are numbered
- * sequentially in the method call.
- *
- */
-## There is a lot in the method header here. To make it more readable/understandable
-## This is the same text laid out to be easier to read:
-## public static LogMessage ${message.methodName} (
-## #foreach($parameter in ${message.parameters})
-## ${parameter.type} ${parameter.name}
-## #if (${velocityCount} != ${message.parameters.size()} )
-## ,
-## #end
-## #end
-## #if(${message.parameters.size()} > 0 && ${message.options.size()} > 0)
-## ,
-## #end
-## #foreach($option in ${message.options})
-## boolean ${option.name}
-## #if (${velocityCount} != ${message.options.size()} )
-## ,
-## #end
-## #end
-## )
-##
-## What is going on is that we set the method name based on the HashMap lookup
-## for 'methodName' Then for each entry(another HashMap) in the list stored
-## in the HashMap under 'parameters' build the argument list of from the 'type'
-## and 'name' values. Ensuring that we add a ', ' between each entry.
-##
-## However, check that we are not at the last entry of the list as we don't
-## want to add ', ' at then end.
-##
-## Before we go on to the options we perform a check to see if we had any
-## parameters. If we did and we have options to add then we add ', ' to keep
-## the syntax correct.
-##
-## We then go on to the options that are again retrieved from the top HashMap
-## with key 'options'. For each option a boolean argument is created and the
-## name is retrieved from the option HashMap with key 'name'
-##
- public static LogMessage ${message.methodName}(#foreach($parameter in ${message.parameters})${parameter.type} ${parameter.name}#if (${velocityCount} != ${message.parameters.size()} ), #end
-#end#if(${message.parameters.size()} > 0 && ${message.options.size()} > 0), #end#foreach($option in ${message.options})boolean ${option.name}#if (${velocityCount} != ${message.options.size()} ), #end#end)
- {
- String rawMessage = _messages.getString("${message.name}");
-## If we have some options then we need to build the message based
-## on those values so only provide that logic if we need it.
-#if(${message.options.size()} > 0)
- StringBuffer msg = new StringBuffer();
-
- // Split the formatted message up on the option values so we can
- // rebuild the message based on the configured options.
- String[] parts = rawMessage.split("\\[");
- msg.append(parts[0]);
-
- int end;
- if (parts.length > 1)
- {
-## For Each Optional value check if it has been enabled and then
-## append it to the log.
-#foreach($option in ${message.options})
-
- // Add Option : ${option.value}
- end = parts[${velocityCount}].indexOf(']');
- if (${option.name})
- {
- msg.append(parts[${velocityCount}].substring(0, end));
- }
-
- // Use 'end + 1' to remove the ']' from the output
- msg.append(parts[${velocityCount}].substring(end + 1));
-#end
- }
-
- rawMessage = msg.toString();
-#end
-
-##
-## If we don't have any parameters then we don't need the overhead of using the
-## message formatter so we can just set our return message to the retreived
-## fixed string. So we don't need to create a new MessageFormat
-##
-## Here we setup rawMessage to be the formatted message ready for direct return
-## with the message.name or further processing to remove options.
-##
-#if(${message.parameters.size()} > 0)
- final Object[] messageArguments = {#foreach($parameter in ${message.parameters})${parameter.name}#if (${velocityCount} != ${message.parameters.size()} ), #end#end};
- // Create a new MessageFormat to ensure thread safety.
- // Sharing a MessageFormat and using applyPattern is not thread safe
- MessageFormat formatter = new MessageFormat(rawMessage, _currentLocale);
-
- final String message = formatter.format(messageArguments);
-#else
-## If we have no parameters then we can skip the formating and set the log
- final String message = rawMessage;
-#end
-
- return new LogMessage()
- {
- public String toString()
- {
- return message;
- }
-
- public String getLogHierarchy()
- {
- return ${message.methodName.toUpperCase()}_LOG_HIERARCHY;
- }
- };
- }
-
-#end
-
-}
diff --git a/java/broker/src/xsl/qmf.xsl b/java/broker/src/xsl/qmf.xsl
deleted file mode 100644
index 3a7e10dac8..0000000000
--- a/java/broker/src/xsl/qmf.xsl
+++ /dev/null
@@ -1,872 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
-<xsl:output omit-xml-declaration="yes" />
-<xsl:template match="/">
-/*
- *
- * 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.qmf.schema;
-
-import 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 org.apache.qpid.transport.codec.BBDecoder;
-
-import java.util.Arrays;
-import java.util.UUID;
-import java.util.Map;
-
- <xsl:apply-templates select="descendant-or-self::node()[name()='schema']" mode="schema"/>
-
-</xsl:template>
-
-<xsl:template match="node()[name()='schema']" mode="schema">
-
-<xsl:variable name="schemaName"><xsl:call-template name="substringAfterLast"><xsl:with-param name="input" select="@package"/><xsl:with-param name="arg">.</xsl:with-param></xsl:call-template></xsl:variable>
-<xsl:variable name="ClassName"><xsl:call-template name="initCap"><xsl:with-param name="input" select="$schemaName"></xsl:with-param></xsl:call-template>Schema</xsl:variable>
-<xsl:variable name="classList"><xsl:apply-templates select="node()[name()='class']" mode="classList"/></xsl:variable>
-<xsl:variable name="eventList"><xsl:apply-templates select="node()[name()='event']" mode="eventList"/></xsl:variable>
-
-public class <xsl:value-of select="$ClassName"/> extends QMFPackage
-{
- private static final byte QMF_VERSION = (byte) '2';
-
- private static final BrokerSchema PACKAGE = new <xsl:value-of select="$ClassName"/>();
- private static final String SCHEMA_NAME = "<xsl:value-of select="@package"/>";
-
-<xsl:text disable-output-escaping="yes">
-
- protected abstract class QMFInfoCommand&lt;T extends QMFObject&gt; extends QMFCommand
- {
- private final T _object;
- private final long _sampleTime;
-
-
- protected QMFInfoCommand(QMFCommand trigger, QMFOperation op, T object, long sampleTime)
- {
- this(trigger.getHeader().getVersion(),
- trigger.getHeader().getSeq(),
- op,
- object,
- sampleTime);
- }
-
- protected QMFInfoCommand(QMFOperation op, T object, long sampleTime)
- {
- this(QMF_VERSION,0,op,object,sampleTime);
- }
-
- private QMFInfoCommand(final byte qmfVersion,
- final int seq,
- final QMFOperation op,
- final T object,
- final long sampleTime)
- {
- super(new QMFCommandHeader(qmfVersion, seq,op));
- _object = object;
- _sampleTime = sampleTime;
- }
-
- public T getObject()
- {
- return _object;
- }
-
- @Override
- public void encode(final BBEncoder encoder)
- {
- super.encode(encoder);
- encoder.writeStr8(SCHEMA_NAME);
- encoder.writeStr8(_object.getQMFClass().getName());
- encoder.writeBin128(new byte[16]);
- encoder.writeUint64(_sampleTime * 1000000L);
- encoder.writeUint64(_object.getCreateTime() * 1000000L);
- encoder.writeUint64(_object.getDeleteTime() * 1000000L);
- encoder.writeBin128(_object.getId());
- }
- }
-
- protected abstract class QMFConfigInfoCommand&lt;T extends QMFObject&gt; extends QMFInfoCommand&lt;T&gt;
- {
- protected QMFConfigInfoCommand(T object, long sampleTime)
- {
- super(QMFOperation.CONFIG_INDICATION, object, sampleTime);
- }
- }
-
- protected abstract class QMFInstrumentInfoCommand&lt;T extends QMFObject&gt; extends QMFInfoCommand&lt;T&gt;
- {
- protected QMFInstrumentInfoCommand(T object, long sampleTime)
- {
- super(QMFOperation.INSTRUMENTATION_INDICATION, object, sampleTime);
- }
- }
-
- protected abstract class QMFGetQueryResponseCommand&lt;T extends QMFObject&gt; extends QMFInfoCommand&lt;T&gt;
- {
- protected QMFGetQueryResponseCommand(T object, QMFGetQueryCommand cmd, long sampleTime)
- {
- super(cmd, QMFOperation.GET_QUERY_RESPONSE, object, sampleTime);
- }
- }
-
-
-</xsl:text>
-
- <xsl:apply-templates select="node()[name()='class']" mode="class"/>
-
- <xsl:apply-templates select="node()[name()='event']" mode="event"/>
-
- private <xsl:value-of select="$ClassName"/>()
- {
- super(SCHEMA_NAME);
- setClasses( Arrays.asList( new QMFClass[] { <xsl:value-of select="$classList"/>, <xsl:value-of select="$eventList"/> } ) );
- }
-<xsl:text disable-output-escaping="yes">
- public &lt;T extends QMFClass&gt; T getQMFClassInstance(Class&lt;T&gt; clazz)
- {
- for(QMFClass c : getClasses())
- {
- if(clazz.isInstance(c))
- {
- return (T) c;
- }
- }
- return null;
- }
-</xsl:text>
-
-
- public static BrokerSchema getPackage()
- {
- return PACKAGE;
- }
-
-}
-</xsl:template>
-
-
-<xsl:template match="node()[name()='class']" mode="class">
- <xsl:variable name="ClassName"><xsl:value-of select="@name"/>Class</xsl:variable>
- <xsl:variable name="name"><xsl:call-template name="initLower"><xsl:with-param name="input" select="@name"/></xsl:call-template></xsl:variable>
- <xsl:variable name="propertyList"><xsl:apply-templates select="node()[name()='property']" mode="propertyList"/></xsl:variable>
- <xsl:variable name="statisticList"><xsl:apply-templates select="node()[name()='statistic']" mode="statisticList"/></xsl:variable>
- <xsl:variable name="methodList"><xsl:apply-templates select="node()[name()='method']" mode="methodList"/></xsl:variable>
-
- public class <xsl:value-of select="$ClassName"/> extends QMFObjectClass<xsl:text disable-output-escaping="yes">&lt;</xsl:text><xsl:value-of select="@name"/>Object, <xsl:value-of select="@name"/>Delegate<xsl:text disable-output-escaping="yes">&gt;</xsl:text>
- {
- <xsl:apply-templates select="node()[name()='property']" mode="property"/>
-
- <xsl:apply-templates select="node()[name()='statistic']" mode="statistic"/>
-
- <xsl:apply-templates select="node()[name()='method']" mode="method"><xsl:with-param name="qmfClass" select="@name"/></xsl:apply-templates>
-
- private <xsl:value-of select="$ClassName"/>()
- {
- super("<xsl:value-of select="$name"/>",
- new byte[16]);
-
- setProperties( Arrays.asList( new QMFProperty[] { <xsl:value-of select="$propertyList"/> } ) );
- setStatistics( Arrays.asList( new QMFStatistic[] { <xsl:value-of select="$statisticList"/> } ) );
- setMethods( Arrays.asList( new QMFMethod[] { <xsl:value-of select="$methodList"/> } ) );
- }
-
- public <xsl:value-of select="@name"/>Object newInstance(final <xsl:value-of select="@name"/>Delegate delegate)
- {
- return new <xsl:value-of select="@name"/>Object(delegate);
- }
-
- }
-
- private final <xsl:value-of select="$ClassName"/> _<xsl:value-of select="$name"/>Class = new <xsl:value-of select="$ClassName"/>();
-
- public interface <xsl:value-of select="@name"/>Delegate extends QMFObject.Delegate
- {<xsl:apply-templates select="node()[name()='property']" mode="propertyGetter"/>
- <xsl:apply-templates select="node()[name()='statistic']" mode="propertyGetter"/>
- <xsl:apply-templates select="node()[name()='method']" mode="methodDefinition"><xsl:with-param name="qmfClass" select="@name"/><xsl:with-param name="delegate">Y</xsl:with-param></xsl:apply-templates>
- }
-
- public final class <xsl:value-of select="@name"/>Object extends QMFObject<xsl:text disable-output-escaping="yes">&lt;</xsl:text><xsl:value-of select="$ClassName"/>, <xsl:value-of select="@name"/>Delegate<xsl:text disable-output-escaping="yes">&gt;</xsl:text>
- {
- protected <xsl:value-of select="@name"/>Object(<xsl:value-of select="@name"/>Delegate delegate)
- {
- super(delegate);
- }
-
- public <xsl:value-of select="@name"/>Class getQMFClass()
- {
- return _<xsl:value-of select="$name"/>Class;
- }
-
- public QMFCommand asConfigInfoCmd(long sampleTime)
- {
- return new QMF<xsl:value-of select="@name"/>ConfigInfoCommand(this,sampleTime);
- }
-
- public QMFCommand asInstrumentInfoCmd(long sampleTime)
- {
- return new QMF<xsl:value-of select="@name"/>InstrumentInfoCommand(this,sampleTime);
- }
-
- public QMFCommand asGetQueryResponseCmd(QMFGetQueryCommand queryCommand, long sampleTime)
- {
- return new QMF<xsl:value-of select="@name"/>GetQueryResponseCommand(this,queryCommand,sampleTime);
- }
-
-
- <xsl:apply-templates select="node()[name()='method']" mode="methodDefinition"><xsl:with-param name="qmfClass" select="@name"/></xsl:apply-templates>
-
- <xsl:apply-templates select="node()[name()='property']" mode="propertyDelegation"/>
- <xsl:apply-templates select="node()[name()='statistic']" mode="propertyDelegation"/>
- }
-
- public final class QMF<xsl:value-of select="@name"/>ConfigInfoCommand extends QMFConfigInfoCommand<xsl:text disable-output-escaping="yes">&lt;</xsl:text><xsl:value-of select="@name"/>Object<xsl:text disable-output-escaping="yes">&gt;</xsl:text>
- {
-
- protected QMF<xsl:value-of select="@name"/>ConfigInfoCommand(<xsl:value-of select="@name"/>Object object, long sampleTime)
- {
- super(object, sampleTime);
- }
-
- @Override
- public void encode(final BBEncoder encoder)
- {
- super.encode(encoder);
- <xsl:apply-templates select="node()[name()='property']" mode="optionalPropertyPresence"/>
- <xsl:apply-templates select="node()[name()='property']" mode="encodeProperty"/>
- }
- }
-
- public final class QMF<xsl:value-of select="@name"/>InstrumentInfoCommand extends QMFInstrumentInfoCommand<xsl:text disable-output-escaping="yes">&lt;</xsl:text><xsl:value-of select="@name"/>Object<xsl:text disable-output-escaping="yes">&gt;</xsl:text>
- {
-
- protected QMF<xsl:value-of select="@name"/>InstrumentInfoCommand(<xsl:value-of select="@name"/>Object object, long sampleTime)
- {
- super(object, sampleTime);
- }
-
- @Override
- public void encode(final BBEncoder encoder)
- {
- super.encode(encoder);
- <xsl:apply-templates select="node()[name()='statistic']" mode="optionalPropertyPresence"><xsl:with-param name="type">statistic</xsl:with-param></xsl:apply-templates>
- <xsl:apply-templates select="node()[name()='statistic']" mode="encodeProperty"/>
- }
- }
-
- public final class QMF<xsl:value-of select="@name"/>GetQueryResponseCommand extends QMFGetQueryResponseCommand<xsl:text disable-output-escaping="yes">&lt;</xsl:text><xsl:value-of select="@name"/>Object<xsl:text disable-output-escaping="yes">&gt;</xsl:text>
- {
-
- protected QMF<xsl:value-of select="@name"/>GetQueryResponseCommand(<xsl:value-of select="@name"/>Object object, QMFGetQueryCommand cmd, long sampleTime)
- {
- super(object, cmd, sampleTime);
- }
-
- @Override
- public void encode(final BBEncoder encoder)
- {
- super.encode(encoder);
- <xsl:apply-templates select="node()[name()='property' or name()='statistic']" mode="optionalPropertyPresence"/>
- <xsl:apply-templates select="node()[name()='property' or name()='statistic']" mode="encodeProperty"/>
- }
- }
-
-
-
-
-</xsl:template>
-
- <xsl:template match="node()[attribute::optional]" mode="optionalPropertyPresence">
- <xsl:param name="type">property</xsl:param>
- <xsl:variable name="var">presence<xsl:value-of select="floor(count(preceding-sibling::node()[name()=$type and attribute::optional]) div 8)"/></xsl:variable>
- <xsl:if test="count(preceding-sibling::node()[name()=$type and attribute::optional]) mod 8 = 0">
- byte <xsl:value-of select="$var"/> = (byte) 0;
- </xsl:if>
- if( getObject().get<xsl:call-template name="initCap"><xsl:with-param name="input"><xsl:value-of select="@name"/></xsl:with-param></xsl:call-template>() != null )
- {
- <xsl:value-of select="$var"/> |= (1 <xsl:text disable-output-escaping="yes">&lt;&lt;</xsl:text> <xsl:value-of select="count(preceding-sibling::node()[name()=$type and attribute::optional])"/>);
- }
- <xsl:if test="count(preceding-sibling::node()[name()=$type and attribute::optional]) mod 8 = 7 or count(following-sibling::node()[name()=$type and attribute::optional]) = 0">
- encoder.writeUint8( <xsl:value-of select="$var"/> );
- </xsl:if>
- </xsl:template>
-
- <xsl:template match="node()" mode="propertyGetter"><xsl:text>
- </xsl:text><xsl:choose>
-
- <xsl:when test="@type='hilo32'">
- <xsl:call-template name="javaType"><xsl:with-param name="type">count32</xsl:with-param><xsl:with-param name="referenceType" select="@references"/></xsl:call-template> get<xsl:call-template name="initCap"><xsl:with-param name="input"><xsl:value-of select="@name"/></xsl:with-param></xsl:call-template>();<xsl:text>
- </xsl:text><xsl:call-template name="javaType"><xsl:with-param name="type">count32</xsl:with-param><xsl:with-param name="referenceType" select="@references"/></xsl:call-template> get<xsl:call-template name="initCap"><xsl:with-param name="input"><xsl:value-of select="@name"/></xsl:with-param></xsl:call-template>High();<xsl:text>
- </xsl:text><xsl:call-template name="javaType"><xsl:with-param name="type">count32</xsl:with-param><xsl:with-param name="referenceType" select="@references"/></xsl:call-template> get<xsl:call-template name="initCap"><xsl:with-param name="input"><xsl:value-of select="@name"/></xsl:with-param></xsl:call-template>Low();</xsl:when>
-
- <xsl:when test="@type='mmaTime'">
- <xsl:call-template name="javaType"><xsl:with-param name="type">deltaTime</xsl:with-param><xsl:with-param name="referenceType" select="@references"/></xsl:call-template> get<xsl:call-template name="initCap"><xsl:with-param name="input"><xsl:value-of select="@name"/></xsl:with-param></xsl:call-template>Samples();<xsl:text>
- </xsl:text><xsl:call-template name="javaType"><xsl:with-param name="type">deltaTime</xsl:with-param><xsl:with-param name="referenceType" select="@references"/></xsl:call-template> get<xsl:call-template name="initCap"><xsl:with-param name="input"><xsl:value-of select="@name"/></xsl:with-param></xsl:call-template>Min();<xsl:text>
- </xsl:text><xsl:call-template name="javaType"><xsl:with-param name="type">deltaTime</xsl:with-param><xsl:with-param name="referenceType" select="@references"/></xsl:call-template> get<xsl:call-template name="initCap"><xsl:with-param name="input"><xsl:value-of select="@name"/></xsl:with-param></xsl:call-template>Max();<xsl:text>
- </xsl:text><xsl:call-template name="javaType"><xsl:with-param name="type">deltaTime</xsl:with-param><xsl:with-param name="referenceType" select="@references"/></xsl:call-template> get<xsl:call-template name="initCap"><xsl:with-param name="input"><xsl:value-of select="@name"/></xsl:with-param></xsl:call-template>Average();</xsl:when>
-
- <xsl:otherwise><xsl:call-template name="javaType"><xsl:with-param name="type" select="@type"/><xsl:with-param name="referenceType" select="@references"/></xsl:call-template> get<xsl:call-template name="initCap"><xsl:with-param name="input"><xsl:value-of select="@name"/></xsl:with-param></xsl:call-template>();</xsl:otherwise>
- </xsl:choose></xsl:template>
-
-
- <xsl:template match="node()" mode="propertyDelegation"><xsl:text>
- </xsl:text><xsl:choose>
- <xsl:when test="@type='hilo32'">
- public <xsl:call-template name="javaType"><xsl:with-param name="type">count32</xsl:with-param><xsl:with-param name="referenceType" select="@references"/></xsl:call-template> get<xsl:call-template name="initCap"><xsl:with-param name="input"><xsl:value-of select="@name"/></xsl:with-param></xsl:call-template>()
- {
- return getDelegate().get<xsl:call-template name="initCap"><xsl:with-param name="input"><xsl:value-of select="@name"/></xsl:with-param></xsl:call-template>();
- }
-
- public <xsl:call-template name="javaType"><xsl:with-param name="type">count32</xsl:with-param><xsl:with-param name="referenceType" select="@references"/></xsl:call-template> get<xsl:call-template name="initCap"><xsl:with-param name="input"><xsl:value-of select="@name"/>High</xsl:with-param></xsl:call-template>()
- {
- return getDelegate().get<xsl:call-template name="initCap"><xsl:with-param name="input"><xsl:value-of select="@name"/>High</xsl:with-param></xsl:call-template>();
- }
-
- public <xsl:call-template name="javaType"><xsl:with-param name="type">count32</xsl:with-param><xsl:with-param name="referenceType" select="@references"/></xsl:call-template> get<xsl:call-template name="initCap"><xsl:with-param name="input"><xsl:value-of select="@name"/>Low</xsl:with-param></xsl:call-template>()
- {
- return getDelegate().get<xsl:call-template name="initCap"><xsl:with-param name="input"><xsl:value-of select="@name"/>Low</xsl:with-param></xsl:call-template>();
- }
-
- </xsl:when>
- <xsl:when test="@type='mmaTime'">
- public <xsl:call-template name="javaType"><xsl:with-param name="type">deltaTime</xsl:with-param><xsl:with-param name="referenceType" select="@references"/></xsl:call-template> get<xsl:call-template name="initCap"><xsl:with-param name="input"><xsl:value-of select="@name"/>Samples</xsl:with-param></xsl:call-template>()
- {
- return getDelegate().get<xsl:call-template name="initCap"><xsl:with-param name="input"><xsl:value-of select="@name"/>Samples</xsl:with-param></xsl:call-template>();
- }
-
- public <xsl:call-template name="javaType"><xsl:with-param name="type">deltaTime</xsl:with-param><xsl:with-param name="referenceType" select="@references"/></xsl:call-template> get<xsl:call-template name="initCap"><xsl:with-param name="input"><xsl:value-of select="@name"/>Min</xsl:with-param></xsl:call-template>()
- {
- return getDelegate().get<xsl:call-template name="initCap"><xsl:with-param name="input"><xsl:value-of select="@name"/>Min</xsl:with-param></xsl:call-template>();
- }
-
- public <xsl:call-template name="javaType"><xsl:with-param name="type">deltaTime</xsl:with-param><xsl:with-param name="referenceType" select="@references"/></xsl:call-template> get<xsl:call-template name="initCap"><xsl:with-param name="input"><xsl:value-of select="@name"/>Max</xsl:with-param></xsl:call-template>()
- {
- return getDelegate().get<xsl:call-template name="initCap"><xsl:with-param name="input"><xsl:value-of select="@name"/>Max</xsl:with-param></xsl:call-template>();
- }
-
- public <xsl:call-template name="javaType"><xsl:with-param name="type">deltaTime</xsl:with-param><xsl:with-param name="referenceType" select="@references"/></xsl:call-template> get<xsl:call-template name="initCap"><xsl:with-param name="input"><xsl:value-of select="@name"/>Average</xsl:with-param></xsl:call-template>()
- {
- return getDelegate().get<xsl:call-template name="initCap"><xsl:with-param name="input"><xsl:value-of select="@name"/>Average</xsl:with-param></xsl:call-template>();
- }
-
- </xsl:when>
- <xsl:otherwise>
- public <xsl:call-template name="javaType"><xsl:with-param name="type" select="@type"/><xsl:with-param name="referenceType" select="@references"/></xsl:call-template> get<xsl:call-template name="initCap"><xsl:with-param name="input"><xsl:value-of select="@name"/></xsl:with-param></xsl:call-template>()
- {
- return getDelegate().get<xsl:call-template name="initCap"><xsl:with-param name="input"><xsl:value-of select="@name"/></xsl:with-param></xsl:call-template>();
- }
-
- </xsl:otherwise>
- </xsl:choose>
- </xsl:template>
-
- <xsl:template match="node()" mode="encodeProperty">
- <xsl:variable name="prop">getObject().get<xsl:call-template name="initCap"><xsl:with-param name="input"><xsl:value-of select="@name"/></xsl:with-param></xsl:call-template>()</xsl:variable>
- <xsl:choose>
- <xsl:when test="@optional">
- if(<xsl:value-of select="$prop"/> != null)
- {
- encoder.<xsl:call-template name="encoderWrite"><xsl:with-param name="var" select="$prop"/><xsl:with-param name="type" select="@type"/></xsl:call-template>;
- }
- </xsl:when>
- <xsl:otherwise>
- <xsl:choose>
- <xsl:when test="@type='hilo32'"><xsl:text>
- </xsl:text>encoder.<xsl:call-template name="encoderWrite"><xsl:with-param name="var" select="$prop"/><xsl:with-param name="type">count32</xsl:with-param></xsl:call-template>;<xsl:text>
- </xsl:text>encoder.<xsl:call-template name="encoderWrite"><xsl:with-param name="var">getObject().get<xsl:call-template name="initCap"><xsl:with-param name="input"><xsl:value-of select="@name"/></xsl:with-param></xsl:call-template>High()</xsl:with-param><xsl:with-param name="type">count32</xsl:with-param></xsl:call-template>;<xsl:text>
- </xsl:text>encoder.<xsl:call-template name="encoderWrite"><xsl:with-param name="var">getObject().get<xsl:call-template name="initCap"><xsl:with-param name="input"><xsl:value-of select="@name"/></xsl:with-param></xsl:call-template>Low()</xsl:with-param><xsl:with-param name="type">count32</xsl:with-param></xsl:call-template>;
- </xsl:when>
-
- <xsl:when test="@type='mmaTime'"><xsl:text>
- </xsl:text>encoder.<xsl:call-template name="encoderWrite"><xsl:with-param name="var">getObject().get<xsl:call-template name="initCap"><xsl:with-param name="input"><xsl:value-of select="@name"/></xsl:with-param></xsl:call-template>Samples()</xsl:with-param><xsl:with-param name="type">deltaTime</xsl:with-param></xsl:call-template>;<xsl:text>
- </xsl:text>encoder.<xsl:call-template name="encoderWrite"><xsl:with-param name="var">getObject().get<xsl:call-template name="initCap"><xsl:with-param name="input"><xsl:value-of select="@name"/></xsl:with-param></xsl:call-template>Min()</xsl:with-param><xsl:with-param name="type">deltaTime</xsl:with-param></xsl:call-template>;<xsl:text>
- </xsl:text>encoder.<xsl:call-template name="encoderWrite"><xsl:with-param name="var">getObject().get<xsl:call-template name="initCap"><xsl:with-param name="input"><xsl:value-of select="@name"/></xsl:with-param></xsl:call-template>Max()</xsl:with-param><xsl:with-param name="type">deltaTime</xsl:with-param></xsl:call-template>;<xsl:text>
- </xsl:text>encoder.<xsl:call-template name="encoderWrite"><xsl:with-param name="var">getObject().get<xsl:call-template name="initCap"><xsl:with-param name="input"><xsl:value-of select="@name"/></xsl:with-param></xsl:call-template>Average()</xsl:with-param><xsl:with-param name="type">deltaTime</xsl:with-param></xsl:call-template>;
- </xsl:when>
-
- <xsl:otherwise><xsl:text>
- </xsl:text>encoder.<xsl:call-template name="encoderWrite"><xsl:with-param name="var" select="$prop"/><xsl:with-param name="type" select="@type"/></xsl:call-template>;
- </xsl:otherwise>
- </xsl:choose>
- </xsl:otherwise>
- </xsl:choose>
-
-
- </xsl:template>
-
- <xsl:template match="node()[name()='property']" mode="property">
- <xsl:variable name="ClassName"><xsl:call-template name="initCap"><xsl:with-param name="input"><xsl:value-of select="@name"/></xsl:with-param></xsl:call-template>Property</xsl:variable>
- public class <xsl:value-of select="$ClassName"/> extends QMFProperty
- {
-
- private <xsl:value-of select="$ClassName"/>()
- {
- super( "<xsl:value-of select="@name"/>",
- QMFType.<xsl:call-template name="qmfType"><xsl:with-param name="type" select="@type"></xsl:with-param></xsl:call-template>,
- QMFProperty.AccessCode.<xsl:call-template name="toUpper"><xsl:with-param name="input" select="@access"></xsl:with-param></xsl:call-template>,
- <xsl:choose><xsl:when test="@index='y'">true</xsl:when><xsl:otherwise>false</xsl:otherwise></xsl:choose>,
- <xsl:choose><xsl:when test="@optional='y'">true</xsl:when><xsl:otherwise>false</xsl:otherwise></xsl:choose>);
-<xsl:if test="@desc">
- setDescription("<xsl:value-of select="@desc"/>");
-</xsl:if>
-<xsl:if test="@min">
- setMin(<xsl:value-of select="@min"/>);
-</xsl:if>
-<xsl:if test="@max">
- setMin(<xsl:value-of select="@max"/>);
-</xsl:if>
-<xsl:if test="@references">
- setReferencedClass("<xsl:call-template name="initLower"><xsl:with-param name="input"><xsl:value-of select="@references"/></xsl:with-param></xsl:call-template>");
-</xsl:if>
-
- <xsl:if test="@unit">
- setUnit("<xsl:value-of select="@unit"/>");
- </xsl:if>
- }
- }
-
- private final <xsl:value-of select="$ClassName"/> _<xsl:call-template name="initLower"><xsl:with-param name="input" select="@name"/></xsl:call-template>Property = new <xsl:value-of select="$ClassName"/>();
- </xsl:template>
-
- <xsl:template match="node()[name()='statistic']" mode="statistic">
- <xsl:choose>
- <xsl:when test="@type='hilo32'">
- <xsl:call-template name="statdef"><xsl:with-param name="name" select="@name"/><xsl:with-param name="type">uint32</xsl:with-param><xsl:with-param name="unit" select="@unit"/><xsl:with-param name="desc" select="@desc"/></xsl:call-template>
- <xsl:call-template name="statdef"><xsl:with-param name="name"><xsl:value-of select="@name"/>High</xsl:with-param><xsl:with-param name="type">uint32</xsl:with-param><xsl:with-param name="unit" select="@unit"/><xsl:with-param name="desc"><xsl:value-of select="@desc"/> (High)</xsl:with-param></xsl:call-template>
- <xsl:call-template name="statdef"><xsl:with-param name="name"><xsl:value-of select="@name"/>Low</xsl:with-param><xsl:with-param name="type">uint32</xsl:with-param><xsl:with-param name="unit" select="@unit"/><xsl:with-param name="desc"><xsl:value-of select="@desc"/> (Low)</xsl:with-param></xsl:call-template>
- </xsl:when>
- <xsl:when test="@type='mmaTime'">
- <xsl:call-template name="statdef"><xsl:with-param name="name"><xsl:value-of select="@name"/>Samples</xsl:with-param><xsl:with-param name="type">deltaTime</xsl:with-param><xsl:with-param name="unit" select="@unit"/><xsl:with-param name="desc"><xsl:value-of select="@desc"/> (Samples)</xsl:with-param></xsl:call-template>
- <xsl:call-template name="statdef"><xsl:with-param name="name"><xsl:value-of select="@name"/>Max</xsl:with-param><xsl:with-param name="type">deltaTime</xsl:with-param><xsl:with-param name="unit" select="@unit"/><xsl:with-param name="desc"><xsl:value-of select="@desc"/> (Max)</xsl:with-param></xsl:call-template>
- <xsl:call-template name="statdef"><xsl:with-param name="name"><xsl:value-of select="@name"/>Min</xsl:with-param><xsl:with-param name="type">deltaTime</xsl:with-param><xsl:with-param name="unit" select="@unit"/><xsl:with-param name="desc"><xsl:value-of select="@desc"/> (Min)</xsl:with-param></xsl:call-template>
- <xsl:call-template name="statdef"><xsl:with-param name="name"><xsl:value-of select="@name"/>Average</xsl:with-param><xsl:with-param name="type">deltaTime</xsl:with-param><xsl:with-param name="unit" select="@unit"/><xsl:with-param name="desc"><xsl:value-of select="@desc"/> (Average)</xsl:with-param></xsl:call-template>
- </xsl:when>
-
- <xsl:otherwise><xsl:call-template name="statdef"><xsl:with-param name="name" select="@name"/><xsl:with-param name="type" select="@type"/><xsl:with-param name="unit" select="@unit"/><xsl:with-param name="desc" select="@desc"/></xsl:call-template></xsl:otherwise>
- </xsl:choose>
-
- </xsl:template>
-
- <xsl:template name="statdef">
- <xsl:param name="name"/>
- <xsl:param name="type"/>
- <xsl:param name="unit"/>
- <xsl:param name="desc"/>
- <xsl:variable name="ClassName"><xsl:call-template name="initCap"><xsl:with-param name="input"><xsl:value-of select="$name"/></xsl:with-param></xsl:call-template>Statistic</xsl:variable>
- public class <xsl:value-of select="$ClassName"/> extends QMFStatistic
- {
-
- private <xsl:value-of select="$ClassName"/>()
- {
- super( "<xsl:value-of select="$name"/>", QMFType.<xsl:call-template name="qmfType"><xsl:with-param name="type" select="$type"></xsl:with-param></xsl:call-template>, <xsl:choose>
- <xsl:when test="$unit">"<xsl:value-of select="$unit"/>"</xsl:when>
- <xsl:otherwise>null</xsl:otherwise>
- </xsl:choose>, <xsl:choose>
- <xsl:when test="$desc">"<xsl:value-of select="$desc"/>"</xsl:when>
- <xsl:otherwise>null</xsl:otherwise>
- </xsl:choose>);
- }
- }
-
- private final <xsl:value-of select="$ClassName"/> _<xsl:call-template name="initLower"><xsl:with-param name="input" select="$name"/></xsl:call-template>Statistic = new <xsl:value-of select="$ClassName"/>();
- </xsl:template>
-
-
- <xsl:template match="node()[name()='method']" mode="method">
- <xsl:param name="qmfClass"/>
- <xsl:variable name="ClassName"><xsl:call-template name="initCap"><xsl:with-param name="input"><xsl:value-of select="@name"/></xsl:with-param></xsl:call-template>Method</xsl:variable>
- public class <xsl:value-of select="$ClassName"/> extends QMFMethod<xsl:text disable-output-escaping="yes">&lt;</xsl:text><xsl:value-of select="$qmfClass"/>Object<xsl:text disable-output-escaping="yes">&gt;</xsl:text>
- {
- private <xsl:value-of select="$ClassName"/>()
- {
- super( "<xsl:value-of select="@name"/>", <xsl:choose>
- <xsl:when test="@desc">"<xsl:value-of select="@desc"/>"</xsl:when>
- <xsl:otherwise>null</xsl:otherwise>
-</xsl:choose>);
-
- <xsl:apply-templates select="node()[name()='arg']" mode="argument"/>
-
- }
-
-
- public <xsl:value-of select="$ClassName"/>Invocation parse(BBDecoder decoder)
- {
- <xsl:apply-templates select="node()[name()='arg' and ( @dir='I' or @dir='IO' ) ]" mode="decodeArg"/>
- return new <xsl:value-of select="$ClassName"/>Invocation(<xsl:apply-templates select="node()[name()='arg' and ( @dir='I' or @dir='IO' ) ]" mode="methodArgList"/>);
- }
- }
-
- private final <xsl:value-of select="$ClassName"/> _<xsl:call-template name="initLower"><xsl:with-param name="input" select="@name"/></xsl:call-template>Method = new <xsl:value-of select="$ClassName"/>();
-
- private class <xsl:value-of select="$ClassName"/>Invocation implements QMFMethodInvocation<xsl:text disable-output-escaping="yes">&lt;</xsl:text><xsl:value-of select="$qmfClass"/>Object<xsl:text disable-output-escaping="yes">&gt;</xsl:text>
- {
- <xsl:apply-templates select="node()[name()='arg' and ( @dir='I' or @dir='IO' ) ]" mode="methodInputArgDecl"/>
-
- private <xsl:value-of select="$ClassName"/>Invocation(<xsl:apply-templates select="node()[name()='arg' and ( @dir='I' or @dir='IO' ) ]" mode="methodArgList"><xsl:with-param name="includeType">yes</xsl:with-param></xsl:apply-templates>)
- {
- <xsl:apply-templates select="node()[name()='arg' and ( @dir='I' or @dir='IO' ) ]" mode="methodInputArgAssign"/>
- }
-
- public QMFMethodResponseCommand execute(<xsl:value-of select="$qmfClass"/>Object obj, QMFMethodRequestCommand cmd)
- {
- return obj.<xsl:value-of select="@name"/>( new <xsl:value-of select="$ClassName"/>ResponseCommandFactory(cmd)<xsl:if test="node()[name()='arg' and ( @dir='I' or @dir='IO' ) ]">, </xsl:if><xsl:apply-templates select="node()[name()='arg' and ( @dir='I' or @dir='IO' ) ]" mode="methodArgList"><xsl:with-param name="prefix">_</xsl:with-param></xsl:apply-templates> );
- }
- }
-
- public final class <xsl:value-of select="$ClassName"/>ResponseCommandFactory
- {
- private final QMFMethodRequestCommand _requestCmd;
- private <xsl:value-of select="$ClassName"/>ResponseCommandFactory(QMFMethodRequestCommand cmd)
- {
- _requestCmd = cmd;
- }
-
- public <xsl:value-of select="$ClassName"/>ResponseCommand createResponseCommand(CompletionCode status)
- {
- return new <xsl:value-of select="$ClassName"/>ResponseCommand(_requestCmd, status, null);
- }
-
- public <xsl:value-of select="$ClassName"/>ResponseCommand createResponseCommand(CompletionCode status, String msg)
- {
- return new <xsl:value-of select="$ClassName"/>ResponseCommand(_requestCmd, status, msg);
- }
-
- public <xsl:value-of select="$ClassName"/>ResponseCommand createResponseCommand( <xsl:apply-templates select="node()[name()='arg' and ( @dir='O' or @dir='IO' ) ]" mode="methodArgList"><xsl:with-param name="includeType">yes</xsl:with-param><xsl:with-param name="direction">O</xsl:with-param></xsl:apply-templates> )
- {
- return new <xsl:value-of select="$ClassName"/>ResponseCommand(_requestCmd<xsl:if test="node()[name()='arg' and ( @dir='O' or @dir='IO' ) ]">, <xsl:apply-templates select="node()[name()='arg' and ( @dir='O' or @dir='IO' ) ]" mode="methodArgList"><xsl:with-param name="direction">O</xsl:with-param></xsl:apply-templates></xsl:if>);
- }
- }
-
- public final class <xsl:value-of select="$ClassName"/>ResponseCommand extends QMFMethodResponseCommand
- {
- <xsl:apply-templates select="node()[name()='arg' and ( @dir='O' or @dir='IO' ) ]" mode="methodInputArgDecl"/>
- private <xsl:value-of select="$ClassName"/>ResponseCommand(QMFMethodRequestCommand cmd<xsl:if test="node()[name()='arg' and ( @dir='O' or @dir='IO' ) ]">, <xsl:apply-templates select="node()[name()='arg' and ( @dir='O' or @dir='IO' ) ]" mode="methodArgList"><xsl:with-param name="includeType">yes</xsl:with-param><xsl:with-param name="direction">O</xsl:with-param></xsl:apply-templates></xsl:if>)
- {
- super(cmd, CompletionCode.OK, "OK");
-
- <xsl:apply-templates select="node()[name()='arg' and ( @dir='O' or @dir='IO' ) ]" mode="methodInputArgAssign"/>
- }
-
- private <xsl:value-of select="$ClassName"/>ResponseCommand(QMFMethodRequestCommand cmd, CompletionCode status, String msg)
- {
- super(cmd, status, msg);
-
- <xsl:apply-templates select="node()[name()='arg' and ( @dir='O' or @dir='IO' ) ]" mode="methodInputArgAssignNull"/>
- }
-
- @Override
- public void encode(final BBEncoder encoder)
- {
- super.encode(encoder);
-
- <xsl:if test="node()[name()='arg' and ( @dir='O' or @dir='IO' ) ]">
- if(getStatus().equals(CompletionCode.OK))
- {
- <xsl:apply-templates select="node()[name()='arg' and ( @dir='O' or @dir='IO' ) ]" mode="encodeArg"/>
- }
- </xsl:if>
- }
- }
-
- </xsl:template>
- <xsl:template match="node()[name()='method']" mode="methodDefinition"><xsl:param name="qmfClass"/><xsl:param name="delegate">N</xsl:param>
- <xsl:variable name="ClassName"><xsl:call-template name="initCap"><xsl:with-param name="input"><xsl:value-of select="@name"/></xsl:with-param></xsl:call-template>Method</xsl:variable><xsl:text>
- </xsl:text><xsl:if test="$delegate='N'">public </xsl:if><xsl:value-of select="$qmfClass"/>Class.<xsl:value-of select="$ClassName"/>ResponseCommand <xsl:call-template name="initLower"><xsl:with-param name="input" select="@name"/></xsl:call-template>(<xsl:value-of select="$qmfClass"/>Class.<xsl:value-of select="$ClassName"/>ResponseCommandFactory factory<xsl:if test="node()[name()='arg' and ( @dir='I' or @dir='IO' ) ]">, <xsl:apply-templates select="node()[name()='arg' and ( @dir='I' or @dir='IO' ) ]" mode="methodArgList"><xsl:with-param name="includeType">yes</xsl:with-param></xsl:apply-templates> </xsl:if>)<xsl:if test="$delegate='N'">
- {
- return getDelegate().<xsl:call-template name="initLower"><xsl:with-param name="input" select="@name"/></xsl:call-template>(factory<xsl:if test="node()[name()='arg' and ( @dir='I' or @dir='IO' ) ]">, <xsl:apply-templates select="node()[name()='arg' and ( @dir='I' or @dir='IO' ) ]" mode="methodArgList"/></xsl:if> );
- }
- </xsl:if><xsl:if test="$delegate='Y'">;</xsl:if>
- </xsl:template>
- <xsl:template match="node()[name()='arg']" mode="argument">
- QMFMethod.Argument <xsl:value-of select="@name"/> = new QMFMethod.Argument("<xsl:value-of select="@name"/>", QMFType.<xsl:call-template name="qmfType"><xsl:with-param name="type" select="@type"/></xsl:call-template>);
-<xsl:if test="@desc">
- <xsl:text> </xsl:text>
- <xsl:value-of select="@name"/>.setDescription("<xsl:value-of select="@desc" disable-output-escaping="yes"/>");
-</xsl:if>
-<xsl:if test="@dir">
- <xsl:text> </xsl:text>
- <xsl:value-of select="@name"/>.setDirection(QMFMethod.Direction.<xsl:value-of select="@dir"/>); </xsl:if>
- addArgument( <xsl:value-of select="@name"/> );
- </xsl:template>
- <xsl:template match="node()[name()='arg']" mode="decodeArg">
- <xsl:call-template name="javaType"><xsl:with-param name="type" select="@type"></xsl:with-param></xsl:call-template><xsl:text> </xsl:text><xsl:value-of select="@name"/> = decoder.<xsl:call-template name="decoderRead"><xsl:with-param name="type" select="@type"/></xsl:call-template>;
- </xsl:template>
- <xsl:template match="node()[name()='arg']" mode="encodeArg">
- encoder.<xsl:call-template name="encoderWrite"><xsl:with-param name="type" select="@type"/><xsl:with-param name="var">_<xsl:value-of select="@name"/></xsl:with-param></xsl:call-template>;
- </xsl:template>
- <xsl:template match="node()[name()='arg']" mode="methodArgList"><xsl:param name="includeType"/><xsl:param name="direction">I</xsl:param><xsl:param name="prefix"></xsl:param>
- <xsl:if test="$includeType"><xsl:call-template name="javaType"><xsl:with-param name="type" select="@type"/></xsl:call-template></xsl:if><xsl:text> </xsl:text><xsl:value-of select="$prefix"/><xsl:value-of select="@name"/><xsl:if test="following-sibling::node()[name()='arg' and ( @dir=$direction or @dir='IO' ) ]">, </xsl:if>
- </xsl:template>
- <xsl:template match="node()[name()='arg']" mode="methodInputArgDecl">
- private final <xsl:call-template name="javaType"><xsl:with-param name="type" select="@type"/></xsl:call-template> _<xsl:value-of select="@name"/>;
- </xsl:template>
- <xsl:template match="node()[name()='arg']" mode="methodInputArgAssign">
- _<xsl:value-of select="@name"/> = <xsl:value-of select="@name"/>;
- </xsl:template>
- <xsl:template match="node()[name()='arg']" mode="methodInputArgAssignNull">
- _<xsl:value-of select="@name"/> = null;
- </xsl:template>
-
-
- <xsl:template match="node()[name()='class']" mode="classList">_<xsl:call-template name="initLower"><xsl:with-param name="input" select="@name"/></xsl:call-template>Class<xsl:if test="following-sibling::node()[name()='class']">, </xsl:if></xsl:template>
- <xsl:template match="node()[name()='event']" mode="eventList">_<xsl:call-template name="initLower"><xsl:with-param name="input" select="@name"/></xsl:call-template>EventClass<xsl:if test="following-sibling::node()[name()='event']">, </xsl:if></xsl:template>
- <xsl:template match="node()[name()='property']" mode="propertyList">_<xsl:call-template name="initLower"><xsl:with-param name="input" select="@name"/></xsl:call-template>Property<xsl:if test="following-sibling::node()[name()='property']">, </xsl:if></xsl:template>
- <xsl:template match="node()[name()='statistic']" mode="statisticList"><xsl:variable name="field">_<xsl:call-template name="initLower"><xsl:with-param name="input" select="@name"/></xsl:call-template></xsl:variable><xsl:choose><xsl:when test="@type!='mmaTime'"><xsl:value-of select="$field"/>Statistic<xsl:if test="@type='hilo32'">, <xsl:value-of select="$field"/>HighStatistic, <xsl:value-of select="$field"/>LowStatistic</xsl:if></xsl:when><xsl:otherwise><xsl:value-of select="$field"/>SamplesStatistic, <xsl:value-of select="$field"/>MaxStatistic, <xsl:value-of select="$field"/>MinStatistic, <xsl:value-of select="$field"/>AverageStatistic</xsl:otherwise></xsl:choose><xsl:if test="following-sibling::node()[name()='statistic']">, </xsl:if></xsl:template>
- <xsl:template match="node()[name()='method']" mode="methodList">_<xsl:call-template name="initLower"><xsl:with-param name="input" select="@name"/></xsl:call-template>Method<xsl:if test="following-sibling::node()[name()='method']">, </xsl:if></xsl:template>
-
-
- <xsl:template match="node()[name()='event']" mode="event">
- <xsl:variable name="ClassName"><xsl:call-template name="initCap"><xsl:with-param name="input" select="@name"/></xsl:call-template>EventClass</xsl:variable>
- <xsl:variable name="cmdName"><xsl:call-template name="initCap"><xsl:with-param name="input" select="@name"/></xsl:call-template>Event</xsl:variable>
- <xsl:variable name="name"><xsl:call-template name="initLower"><xsl:with-param name="input" select="@name"/></xsl:call-template></xsl:variable>
-
- <xsl:variable name="argsList"><xsl:call-template name="argList"><xsl:with-param name="args" select="@args"></xsl:with-param></xsl:call-template></xsl:variable>
-
- public class <xsl:value-of select="$ClassName"/> extends QMFEventClass
- {
-<!-- <xsl:apply-templates select="node()[name()='property']" mode="property"/> -->
-
- <xsl:apply-templates select="preceding-sibling::node()[name()='eventArguments']" mode="eventArg"><xsl:with-param name="args" select="@args"/></xsl:apply-templates>
-
- private <xsl:value-of select="$ClassName"/>()
- {
- super("<xsl:value-of select="$name"/>",
- new byte[16]);
-
- setProperties( Arrays.asList( new QMFProperty[] { <xsl:value-of select="$argsList"/> } ) );
- }
-
- public QMFEventSeverity getSeverity()
- {
- return QMFEventSeverity.<xsl:call-template name="severity"><xsl:with-param name="severity" select="@sev"/></xsl:call-template>;
- }
-
- public QMFEventCommand<xsl:text disable-output-escaping="yes">&lt;</xsl:text><xsl:value-of select="$ClassName"/><xsl:text disable-output-escaping="yes">&gt;</xsl:text> newEvent(<xsl:apply-templates select="preceding-sibling::node()[name()='eventArguments']" mode="eventArg"><xsl:with-param name="args" select="@args"/><xsl:with-param name="tmpl">argParamList</xsl:with-param><xsl:with-param name="separator">, </xsl:with-param></xsl:apply-templates>)
- {
- return new <xsl:value-of select="$cmdName"/>(<xsl:apply-templates select="preceding-sibling::node()[name()='eventArguments']" mode="eventArg"><xsl:with-param name="args" select="@args"/><xsl:with-param name="tmpl">argList</xsl:with-param><xsl:with-param name="separator">, </xsl:with-param></xsl:apply-templates>);
- }
-
-
-
- }
-
- private final <xsl:value-of select="$ClassName"/> _<xsl:value-of select="$name"/>EventClass = new <xsl:value-of select="$ClassName"/>();
-
- private final class <xsl:value-of select="$cmdName"/> extends QMFEventCommand<xsl:text disable-output-escaping="yes">&lt;</xsl:text><xsl:value-of select="$ClassName"/><xsl:text disable-output-escaping="yes">&gt;</xsl:text>
- {
- <xsl:apply-templates select="preceding-sibling::node()[name()='eventArguments']" mode="eventArg"><xsl:with-param name="args" select="@args"/><xsl:with-param name="tmpl">argMemberDef</xsl:with-param></xsl:apply-templates>
-
- private <xsl:value-of select="$cmdName"/>(<xsl:apply-templates select="preceding-sibling::node()[name()='eventArguments']" mode="eventArg"><xsl:with-param name="args" select="@args"/><xsl:with-param name="tmpl">argParamList</xsl:with-param><xsl:with-param name="separator">, </xsl:with-param></xsl:apply-templates>)
- {
- <xsl:apply-templates select="preceding-sibling::node()[name()='eventArguments']" mode="eventArg"><xsl:with-param name="args" select="@args"/><xsl:with-param name="tmpl">argMemberAssign</xsl:with-param></xsl:apply-templates>
- }
-
- public <xsl:value-of select="$ClassName"/> getEventClass()
- {
- return _<xsl:value-of select="$name"/>EventClass;
- }
-
- public void encode(final BBEncoder encoder)
- {
- super.encode(encoder);
- <xsl:apply-templates select="preceding-sibling::node()[name()='eventArguments']" mode="eventArg"><xsl:with-param name="args" select="@args"/><xsl:with-param name="tmpl">argEncode</xsl:with-param><xsl:with-param name="separator"><xsl:text>
- </xsl:text></xsl:with-param></xsl:apply-templates>
-
- }
- }
- </xsl:template>
-
- <xsl:template name="eventArguments" mode="eventArg" match="node()[name()='eventArguments']">
- <xsl:param name="args"></xsl:param>
- <xsl:param name="tmpl">propertyClass</xsl:param>
- <xsl:param name="separator"></xsl:param>
- <xsl:variable name="arg"><xsl:choose>
- <xsl:when test="contains($args,',')"><xsl:value-of select="normalize-space(substring-before($args,','))"/></xsl:when>
- <xsl:otherwise><xsl:value-of select="$args"/></xsl:otherwise>
- </xsl:choose></xsl:variable>
- <xsl:variable name="tail" select="normalize-space(substring-after($args,','))"></xsl:variable>
- <xsl:if test="string-length($arg)>0">
- <xsl:apply-templates mode="eventArg" select="node()[name()='arg' and @name=$arg]"><xsl:with-param name="tmpl" select="$tmpl"/></xsl:apply-templates>
- </xsl:if>
- <xsl:if test="string-length($tail)>0"><xsl:value-of select="$separator"/><xsl:apply-templates select="." mode="eventArg"><xsl:with-param name="args" select="$tail"/><xsl:with-param name="tmpl" select="$tmpl"/><xsl:with-param name="separator" select="$separator"/></xsl:apply-templates></xsl:if>
- </xsl:template>
-
- <xsl:template mode="eventArg" match="node()[name()='arg']">
- <xsl:param name="tmpl"/>
- <xsl:choose>
- <xsl:when test="$tmpl='propertyClass'"><xsl:apply-templates mode="propertyClass" select="."/></xsl:when>
- </xsl:choose>
- <xsl:choose>
- <xsl:when test="$tmpl='argParamList'"><xsl:apply-templates mode="argParamList" select="."/></xsl:when>
- </xsl:choose>
- <xsl:choose>
- <xsl:when test="$tmpl='argList'"><xsl:apply-templates mode="argList" select="."/></xsl:when>
- </xsl:choose>
- <xsl:choose>
- <xsl:when test="$tmpl='argMemberDef'"><xsl:apply-templates mode="argMemberDef" select="."/></xsl:when>
- </xsl:choose>
- <xsl:choose>
- <xsl:when test="$tmpl='argMemberAssign'"><xsl:apply-templates mode="argMemberAssign" select="."/></xsl:when>
- </xsl:choose>
- <xsl:choose>
- <xsl:when test="$tmpl='argEncode'"><xsl:apply-templates mode="argEncode" select="."/></xsl:when>
- </xsl:choose>
- </xsl:template>
-
- <xsl:template name="arg" mode="propertyClass" match="node()[name()='arg']">
-<xsl:variable name="propClassName"><xsl:call-template name="initCap"><xsl:with-param name="input" select="@name"/></xsl:call-template>Arg</xsl:variable>
- public class <xsl:value-of select="$propClassName"/> extends QMFProperty
- {
- private <xsl:value-of select="$propClassName"/>()
- {
- super( "<xsl:value-of select="@name"/>",
- QMFType.<xsl:call-template name="qmfType"><xsl:with-param name="type" select="@type"></xsl:with-param></xsl:call-template>,
- QMFProperty.AccessCode.RO,false,false);
-
- <xsl:if test="@desc">
- setDescription("<xsl:value-of select="@desc"/>");
- </xsl:if>
- }
- }
-
- private final <xsl:value-of select="$propClassName"/> _<xsl:value-of select="@name"/>Arg = new <xsl:value-of select="$propClassName"/>();
- </xsl:template>
-
- <xsl:template mode="argMemberDef" match="node()[name()='arg']"><xsl:text>
- private final </xsl:text><xsl:call-template name="javaType"><xsl:with-param name="type" select="@type"></xsl:with-param></xsl:call-template><xsl:text> _</xsl:text><xsl:value-of select="@name"/>;</xsl:template>
- <xsl:template mode="argParamList" match="node()[name()='arg']"><xsl:call-template name="javaType"><xsl:with-param name="type" select="@type"/></xsl:call-template><xsl:text> </xsl:text><xsl:value-of select="@name"/></xsl:template>
- <xsl:template mode="argList" match="node()[name()='arg']"><xsl:value-of select="@name"/></xsl:template>
- <xsl:template mode="argMemberAssign" match="node()[name()='arg']"><xsl:text>
- _</xsl:text><xsl:value-of select="@name"/> = <xsl:value-of select="@name"/>;</xsl:template>
- <xsl:template mode="argEncode" match="node()[name()='arg']">encoder.<xsl:call-template name="encoderWrite"><xsl:with-param name="type" select="@type"/><xsl:with-param name="var">_<xsl:value-of select="@name"/></xsl:with-param></xsl:call-template>;</xsl:template>
-
- <xsl:template name="argList">
- <xsl:param name="args"/>
- <xsl:variable name="arg"><xsl:choose>
- <xsl:when test="contains($args,',')"><xsl:value-of select="normalize-space(substring-before($args,','))"/></xsl:when>
- <xsl:otherwise><xsl:value-of select="$args"/></xsl:otherwise>
- </xsl:choose></xsl:variable>
- <xsl:variable name="tail" select="normalize-space(substring-after($args,','))"></xsl:variable>
- <xsl:if test="string-length($arg)>0">_<xsl:value-of select="$arg"/>Arg</xsl:if>
- <xsl:if test="string-length($tail)>0">, <xsl:call-template name="argList"><xsl:with-param name="args" select="$tail"/></xsl:call-template></xsl:if>
- </xsl:template>
-
-
- <xsl:template name="qmfType"><xsl:param name="type"/>
-<xsl:choose><xsl:when test="$type='absTime'">ABSTIME</xsl:when>
-<xsl:when test="$type='bool'">BOOLEAN</xsl:when>
-<xsl:when test="$type='map'">MAP</xsl:when>
-<xsl:when test="$type='objId'">OBJECTREFERENCE</xsl:when>
-<xsl:when test="$type='sstr'">STR8</xsl:when>
-<xsl:when test="$type='lstr'">STR16</xsl:when>
-<xsl:when test="$type='uint16'">UINT16</xsl:when>
-<xsl:when test="$type='uint32'">UINT32</xsl:when>
-<xsl:when test="$type='uint64'">UINT64</xsl:when>
-<xsl:when test="$type='uuid'">UUID</xsl:when>
-<xsl:when test="$type='deltaTime'">DELTATIME</xsl:when>
-<xsl:when test="$type='count32'">UINT32</xsl:when>
-<xsl:when test="$type='count64'">UINT64</xsl:when>
- <xsl:otherwise><xsl:value-of select="$type"/></xsl:otherwise>
-</xsl:choose>
-</xsl:template>
-
-
- <xsl:template name="javaType"><xsl:param name="type"/><xsl:param name="referenceType">UUID</xsl:param>
- <xsl:choose><xsl:when test="$type='absTime'">Long</xsl:when>
- <xsl:when test="$type='bool'">Boolean</xsl:when>
- <xsl:when test="$type='map'">Map</xsl:when>
- <xsl:when test="$type='objId'"><xsl:value-of select="$referenceType"/>Object</xsl:when>
- <xsl:when test="$type='sstr'">String</xsl:when>
- <xsl:when test="$type='lstr'">String</xsl:when>
- <xsl:when test="$type='uint16'">Integer</xsl:when>
- <xsl:when test="$type='uint32'">Long</xsl:when>
- <xsl:when test="$type='uint64'">Long</xsl:when>
- <xsl:when test="$type='uuid'">UUID</xsl:when>
- <xsl:when test="$type='deltaTime'">Long</xsl:when>
- <xsl:when test="$type='count32'">Long</xsl:when>
- <xsl:when test="$type='count64'">Long</xsl:when>
- <xsl:otherwise><xsl:value-of select="$type"/></xsl:otherwise>
- </xsl:choose>
- </xsl:template>
-
- <xsl:template name="encoderWrite"><xsl:param name="type"/><xsl:param name="var"/>
- <xsl:choose><xsl:when test="$type='absTime'">writeUint64( <xsl:value-of select="$var"/> )</xsl:when>
- <xsl:when test="$type='bool'">writeInt8( <xsl:value-of select="$var"/> ? (byte) -1 : (byte) 0)</xsl:when>
- <xsl:when test="$type='map'">writeMap( <xsl:value-of select="$var"/> )</xsl:when>
- <xsl:when test="$type='objId'">writeBin128( <xsl:value-of select="$var"/>.getId() )</xsl:when>
- <xsl:when test="$type='sstr'">writeStr8( <xsl:value-of select="$var"/> )</xsl:when>
- <xsl:when test="$type='lstr'">writeStr16( <xsl:value-of select="$var"/> )</xsl:when>
- <xsl:when test="$type='uint16'">writeUint16( <xsl:value-of select="$var"/> )</xsl:when>
- <xsl:when test="$type='uint32'">writeUint32( <xsl:value-of select="$var"/> )</xsl:when>
- <xsl:when test="$type='uint64'">writeUint64( <xsl:value-of select="$var"/> )</xsl:when>
- <xsl:when test="$type='uuid'">writeUuid( <xsl:value-of select="$var"/> )</xsl:when>
- <xsl:when test="$type='deltaTime'">writeUint64( <xsl:value-of select="$var"/> )</xsl:when>
- <xsl:when test="$type='count32'">writeUint32( <xsl:value-of select="$var"/> )</xsl:when>
- <xsl:when test="$type='count64'">writeUint64( <xsl:value-of select="$var"/> )</xsl:when>
- <xsl:otherwise><xsl:value-of select="$type"/></xsl:otherwise>
- </xsl:choose>
- </xsl:template>
-
- <xsl:template name="decoderRead"><xsl:param name="type"/>
- <xsl:choose><xsl:when test="$type='absTime'">readUint64()</xsl:when>
- <xsl:when test="$type='bool'">readInt8() != 0</xsl:when>
- <xsl:when test="$type='map'">readMap()</xsl:when>
- <xsl:when test="$type='objId'">readBin128()</xsl:when>
- <xsl:when test="$type='sstr'">readStr8()</xsl:when>
- <xsl:when test="$type='lstr'">readStr16()</xsl:when>
- <xsl:when test="$type='uint16'">readUint16()</xsl:when>
- <xsl:when test="$type='uint32'">readUint32()</xsl:when>
- <xsl:when test="$type='uint64'">readUint64()</xsl:when>
- <xsl:when test="$type='uuid'">readUuid()</xsl:when>
- <xsl:when test="$type='deltaTime'">readUint64()</xsl:when>
- <xsl:when test="$type='count32'">readUint32()</xsl:when>
- <xsl:when test="$type='count64'">readUint64()</xsl:when>
- <xsl:otherwise><xsl:value-of select="$type"/></xsl:otherwise>
- </xsl:choose>
- </xsl:template>
-
-
-<xsl:template name="severity">
- <xsl:param name="severity"/>
- <xsl:choose>
- <xsl:when test="$severity='emerg'">EMERGENCY</xsl:when>
- <xsl:when test="$severity='alert'">ALERT</xsl:when>
- <xsl:when test="$severity='crit'">CRITICAL</xsl:when>
- <xsl:when test="$severity='error'">ERROR</xsl:when>
- <xsl:when test="$severity='warn'">WARN</xsl:when>
- <xsl:when test="$severity='notice'">NOTICE</xsl:when>
- <xsl:when test="$severity='inform'">INFORM</xsl:when>
- <xsl:when test="$severity='debug'">DEBUG</xsl:when>
- </xsl:choose>
-
-</xsl:template>
-
-<xsl:template name="substringAfterLast"><xsl:param name="input"/><xsl:param name="arg"/>
-<xsl:choose>
- <xsl:when test="contains($input,$arg)"><xsl:call-template name="substringAfterLast"><xsl:with-param name="input"><xsl:value-of select="substring-after($input,$arg)"/></xsl:with-param><xsl:with-param name="arg"><xsl:value-of select="$arg"/></xsl:with-param></xsl:call-template></xsl:when>
- <xsl:otherwise><xsl:value-of select="$input"/></xsl:otherwise>
-</xsl:choose>
-</xsl:template>
-<xsl:template name="initCap"><xsl:param name="input"/><xsl:value-of select="translate(substring($input,1,1),'abcdefghijklmnopqrstuvwxyz','ABCDEFGHIJKLMNOPQRSTUVWXYZ')"/><xsl:value-of select="substring($input,2)"/></xsl:template>
-<xsl:template name="initLower"><xsl:param name="input"/><xsl:value-of select="translate(substring($input,1,1),'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')"/><xsl:value-of select="substring($input,2)"/></xsl:template>
-<xsl:template name="toUpper"><xsl:param name="input"/><xsl:value-of select="translate($input,'abcdefghijklmnopqrstuvwxyz','ABCDEFGHIJKLMNOPQRSTUVWXYZ')"/></xsl:template>
-</xsl:stylesheet>
diff --git a/java/build.deps b/java/build.deps
deleted file mode 100644
index 73c35940cb..0000000000
--- a/java/build.deps
+++ /dev/null
@@ -1,145 +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.
-#
-
-backport-util-concurrent=lib/backport-util-concurrent-2.2.jar
-
-commons-beanutils-core=lib/commons-beanutils-core-1.8.0.jar
-commons-cli=lib/commons-cli-1.0.jar
-commons-codec=lib/commons-codec-1.3.jar
-commons-collections=lib/commons-collections-3.2.jar
-commons-configuration=lib/commons-configuration-1.6.jar
-commons-digester=lib/commons-digester-1.8.1.jar
-commons-lang=lib/commons-lang-2.2.jar
-commons-logging=lib/commons-logging-1.0.4.jar
-
-derby-db=lib/derby-10.6.1.0.jar
-
-geronimo-jms=lib/geronimo-jms_1.1_spec-1.0.jar
-
-junit=lib/junit-3.8.1.jar
-
-log4j=lib/log4j-1.2.12.jar
-
-mina-core=lib/mina-core-1.0.1.jar
-mina-filter-ssl=lib/mina-filter-ssl-1.0.1.jar
-
-slf4j-api=lib/slf4j-api-1.6.1.jar
-slf4j-log4j=lib/slf4j-log4j12-1.6.1.jar
-
-xalan=lib/xalan-2.7.0.jar
-
-jetty=lib/jetty-6.1.14.jar
-jetty-util=lib/jetty-util-6.1.14.jar
-jetty-servlet-tester=lib/jetty-servlet-tester-6.1.14.jar
-servlet-api=lib/servlet-api.jar
-
-osgi-core=lib/org.osgi.core-1.0.0.jar
-felix-framework=lib/org.apache.felix.framework-2.0.5.jar
-
-felix.libs=${osgi-core} ${felix-framework}
-
-commons-configuration.libs = ${commons-beanutils-core} ${commons-digester} \
- ${commons-codec} ${commons-lang} ${commons-collections} ${commons-configuration}
-
-common.libs=${slf4j-api} ${backport-util-concurrent} ${mina-core} ${mina-filter-ssl}
-client.libs=${geronimo-jms}
-tools.libs=${commons-configuration.libs} ${log4j}
-broker.libs=${commons-cli} ${commons-logging} ${log4j} ${slf4j-log4j} \
- ${xalan} ${felix.libs} ${derby-db} ${commons-configuration.libs}
-
-broker-plugins.libs=${felix.libs} ${log4j} ${commons-configuration.libs}
-
-junit-toolkit.libs=${log4j} ${junit} ${slf4j-api}
-test.libs=${slf4j-log4j} ${junit-toolkit.libs}
-testkit.libs=${log4j}
-
-ibm-icu=lib/com.ibm.icu_3.8.1.v20080530.jar
-ecl-core-jface=lib/org.eclipse.jface_3.4.1.M20080827-2000.jar
-ecl-core-jface-databinding=lib/org.eclipse.jface.databinding_1.2.1.M20080827-0800a.jar
-ecl-core-commands=lib/org.eclipse.core.commands_3.4.0.I20080509-2000.jar
-ecl-core-contenttype=lib/org.eclipse.core.contenttype_3.3.0.v20080604-1400.jar
-ecl-core-databinding=lib/org.eclipse.core.databinding_1.1.1.M20080827-0800b.jar
-ecl-core-expressions=lib/org.eclipse.core.expressions_3.4.0.v20080603-2000.jar
-ecl-core-jobs=lib/org.eclipse.core.jobs_3.4.0.v20080512.jar
-ecl-core-runtime=lib/org.eclipse.core.runtime_3.4.0.v20080512.jar
-ecl-core-runtime-compat-registry=lib/org.eclipse.core.runtime.compatibility.registry_3.2.200.v20080610/**
-ecl-equinox-app=lib/org.eclipse.equinox.app_1.1.0.v20080421-2006.jar
-ecl-equinox-common=lib/org.eclipse.equinox.common_3.4.0.v20080421-2006.jar
-ecl-equinox-launcher=lib/org.eclipse.equinox.launcher_1.0.101.R34x_v20080819.jar
-ecl-equinox-prefs=lib/org.eclipse.equinox.preferences_3.2.201.R34x_v20080709.jar
-ecl-equinox-registry=lib/org.eclipse.equinox.registry_3.4.0.v20080516-0950.jar
-ecl-help=lib/org.eclipse.help_3.3.101.v20080702_34x.jar
-ecl-osgi=lib/org.eclipse.osgi_3.4.2.R34x_v20080826-1230.jar
-ecl-swt=lib/org.eclipse.swt_3.4.1.v3449c.jar
-ecl-ui=lib/org.eclipse.ui_3.4.1.M20080910-0800.jar
-ecl-ui-forms=lib/org.eclipse.ui.forms_3.3.101.v20080708_34x.jar
-ecl-ui-workbench=lib/org.eclipse.ui.workbench_3.4.1.M20080827-0800a.jar
-apache-commons-codec=lib/org.apache.commons.codec_1.3.0.v20080530-1600.jar
-
-ecl-swt-win32-win32-x86=lib/org.eclipse.swt.win32.win32.x86_3.4.1.v3449c.jar
-ecl-equinox-launcher-win32-win32-x86=lib/org.eclipse.equinox.launcher.win32.win32.x86_1.0.101.R34x_v20080731/**
-ecl-swt-linux-gtk-x86=lib/org.eclipse.swt.gtk.linux.x86_3.4.1.v3449c.jar
-ecl-equinox-launcher-linux-gtk-x86=lib/org.eclipse.equinox.launcher.gtk.linux.x86_1.0.101.R34x_v20080805/**
-ecl-swt-linux-gtk-x86_64=lib/org.eclipse.swt.gtk.linux.x86_64_3.4.1.v3449c.jar
-ecl-equinox-launcher-linux-gtk-x86_64=lib/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.0.101.R34x_v20080731/**
-ecl-swt-macosx-carbon=lib/org.eclipse.swt.carbon.macosx_3.4.1.v3449c.jar
-ecl-equinox-launcher-macosx-carbon=lib/org.eclipse.equinox.launcher.carbon.macosx_1.0.101.R34x_v20080731/**
-ecl-swt-solaris-gtk-sparc=lib/org.eclipse.swt.gtk.solaris.sparc_3.4.1.v3449c.jar
-ecl-equinox-launcher-solaris-gtk-sparc=lib/org.eclipse.equinox.launcher.gtk.solaris.sparc_1.0.101.R34x_v20080731/**
-
-management-common.libs=
-
-management-eclipse-plugin-win32-win32-x86.libs=${management-eclipse-plugin.core-libs} \
- ${ecl-swt-win32-win32-x86} ${ecl-equinox-launcher-win32-win32-x86}
-management-eclipse-plugin-linux-gtk-x86.libs=${management-eclipse-plugin.core-libs} \
- ${ecl-swt-linux-gtk-x86} ${ecl-equinox-launcher-linux-gtk-x86}
-management-eclipse-plugin-linux-gtk-x86_64.libs=${management-eclipse-plugin.core-libs} \
- ${ecl-swt-linux-gtk-x86_64} ${ecl-equinox-launcher-linux-gtk-x86_64}
-management-eclipse-plugin-macosx.libs=${management-eclipse-plugin.core-libs} \
- ${ecl-swt-macosx-carbon} ${ecl-equinox-launcher-macosx-carbon}
-management-eclipse-plugin-solaris-gtk-sparc.libs=${management-eclipse-plugin.core-libs} \
- ${ecl-swt-solaris-gtk-sparc} ${ecl-equinox-launcher-solaris-gtk-sparc}
-
-management-eclipse-plugin.core-libs=${ibm-icu} ${ecl-core-jface} ${ecl-core-jface-databinding} \
- ${ecl-core-commands} ${ecl-core-contenttype} ${ecl-core-databinding} ${ecl-core-expressions} \
- ${ecl-core-jobs} ${ecl-core-runtime} ${ecl-core-runtime-compat-registry} ${ecl-equinox-app} \
- ${ecl-equinox-common} ${ecl-equinox-launcher} ${ecl-equinox-prefs} ${ecl-equinox-registry} \
- ${ecl-help} ${ecl-osgi} ${ecl-swt} ${ecl-ui} ${ecl-ui-forms} ${ecl-ui-workbench} ${apache-commons-codec}
-
-management-eclipse-plugin.platform-libs=${ecl-equinox-launcher-win32-win32-x86} \
- ${ecl-equinox-launcher-linux-gtk-x86} ${ecl-equinox-launcher-macosx-carbon} \
- ${ecl-swt-win32-win32-x86} ${ecl-swt-linux-gtk-x86} ${ecl-swt-macosx-carbon} \
- ${ecl-swt-linux-gtk-x86_64} ${ecl-equinox-launcher-linux-gtk-x86_64} \
- ${ecl-swt-solaris-gtk-sparc} ${ecl-equinox-launcher-solaris-gtk-sparc}
-
-management-eclipse-plugin.libs=${management-eclipse-plugin.core-libs} ${management-eclipse-plugin.platform-libs}
-
-common.test.libs=${test.libs}
-broker.test.libs=${test.libs}
-client.test.libs=${test.libs}
-client-example.test.libs=${test.libs}
-tools.test.libs=
-testkit.test.libs=${test.libs}
-systests.libs=${test.libs}
-
-broker-plugins.test.libs=${test.libs}
-broker-plugins-experimental-info.test.libs=${test.libs} ${servlet-api} ${jetty} ${jetty-util} ${jetty-servlet-tester}
-
-management-eclipse-plugin.test.libs=${systests.libs}
-management-common.test.libs=${test.libs}
diff --git a/java/build.xml b/java/build.xml
deleted file mode 100644
index 8651404cb7..0000000000
--- a/java/build.xml
+++ /dev/null
@@ -1,297 +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.
- -
- -->
-<project name="AMQ Java" default="build">
-
- <import file="common.xml"/>
-
-
- <findSubProjects name="broker-plugins" dir="broker-plugins"/>
- <findSubProjects name="management" dir="management" excludes="common,example"/>
-
- <property name="modules.core" value="junit-toolkit common management/common broker client tools"/>
- <property name="modules.examples" value="client/example management/example"/>
- <property name="modules.tests" value="systests perftests integrationtests testkit"/>
- <property name="modules.management" value="${management}"/>
- <property name="modules.plugin" value="${broker-plugins}"/>
- <property name="modules" value="${modules.core} ${modules.examples}
- ${modules.management} ${modules.tests} ${modules.plugin}"/>
-
- <property name="qpid.jar" location="${build.lib}/qpid-all.jar"/>
- <basename property="qpid.jar.name" file="${qpid.jar}"/>
-
- <property name="resources" value="${project.root}/resources"/>
-
- <map property="release.excludes" value="${modules}">
- <globmapper from="*" to="*/\*\*"/>
- </map>
-
-
- <property name="release.zip" location="${release}/${project.namever}-java.zip"/>
- <property name="release.tar" location="${release}/${project.namever}-java.tar"/>
- <property name="release.tgz" location="${release}/${project.namever}-java.tar.gz"/>
- <property name="release.bz2" location="${release}/${project.namever}-java.tar.bz2"/>
-
- <macrodef name="iterate">
- <attribute name="target"/>
- <attribute name="modules" default="${modules}"/>
- <element name="elements" implicit="true" optional="true"/>
- <sequential>
- <subant target="@{target}" antfile="build.xml">
- <filelist dir="." files="@{modules}"/>
- <elements/>
- </subant>
- </sequential>
- </macrodef>
-
- <target name="pom" description="generate poms">
- <iterate target="pom"/>
- </target>
-
- <target name="release-mvn" description="Install the artifacts into the local repository">
- <iterate target="release-mvn"/>
- </target>
-
- <target name="compile" description="compile sources">
- <iterate target="compile"/>
- </target>
-
- <target name="compile-tests" description="compile unit tests">
- <iterate target="compile-tests"/>
- </target>
-
- <target name="test" description="execute tests">
-
- <delete file="${build.failed}"/>
-
- <iterate target="test">
- <property name="test.failures.ignore" value="true"/>
- </iterate>
-
- <condition property="failed">
- <available file="${build.failed}"/>
- </condition>
-
- <fail if="failed" message="TEST SUITE FAILED"/>
-
- </target>
-
- <target name="report-module" description="generate junitreport for modules">
- <iterate target="report-module"/>
- </target>
-
- <target name="jar" description="create module jars">
- <iterate target="jar"/>
- </target>
-
- <target name="jar-tests" description="create unit test jars">
- <iterate target="jar-tests"/>
- </target>
-
- <target name="libs" description="copy dependencies into build tree">
- <iterate target="libs"/>
- </target>
-
- <target name="doc" description="generate api-doc">
- <iterate target="doc"/>
- </target>
-
- <target name="test-doc" description="generate api-doc">
- <iterate target="test-doc"/>
- </target>
-
- <target name="bundle" description="create OSGi bundles">
- <iterate target="bundle"/>
- </target>
-
- <target name="release-bin" description="build a binary release artifact" depends="build,bundle">
- <iterate target="release-bin"/>
- </target>
-
-
- <target name="check-manifest">
- <uptodate property="manifest.done" targetfile="${qpid.jar}">
- <srcfiles dir="${build.lib}" includes="**/*.jar" excludes="**/${qpid.jar.name}"/>
- </uptodate>
- </target>
-
- <target name="manifest" depends="check-manifest" unless="manifest.done">
- <path id="class.path">
- <fileset dir="${build.lib}" >
- <include name="*.jar"/>
- <exclude name="${qpid.jar.name}"/>
- </fileset>
- </path>
- <pathconvert property="qpid.jar.classpath" pathsep=" " dirsep="/">
- <path refid="class.path"/>
- <globmapper from="${build.lib}${file.separator}*" to="*"/>
- </pathconvert>
-
- <jar destfile="${qpid.jar}">
- <manifest>
- <attribute name="Class-Path" value="${qpid.jar.classpath}"/>
- </manifest>
- <metainf dir="${project.root}/resources/"/>
- </jar>
-
- <touch file="${qpid.jar}"/>
- </target>
-
- <target name="build" description="build the project">
- <iterate target="build"/>
- <antcall target="manifest"/>
- </target>
-
- <target name="prepare">
- <mkdir dir="${release}"/>
- </target>
-
- <target name="zip" depends="build,prepare" description="build release archive">
- <zip destfile="${release.zip}">
- <zipfileset dir="${build}" prefix="${project.namever}" filemode="755">
- <include name="bin/*"/>
- <exclude name="bin/*.txt"/>
- </zipfileset>
-
- <zipfileset dir="${build}" prefix="${project.namever}" filemode="644">
- <include name="bin/*.txt"/>
- </zipfileset>
-
- <zipfileset dir="${build}" prefix="${project.namever}" excludes="${release.excludes}" filemode="644" dirmode="755">
- <exclude name="bin/**"/>
- <exclude name="scratch/**"/>
- </zipfileset>
-
- <zipfileset dir="${resources}" prefix="${project.namever}" filemode="644"/>
- </zip>
- </target>
-
- <target name="tar" depends="zip" description="build release archive">
- <tar destfile="${release.tar}" longfile="gnu" >
- <zipfileset src="${release.zip}"/>
- </tar>
- </target>
-
- <target name="gzip" depends="tar" description="build release archive">
- <gzip src="${release.tar}" destfile="${release.tgz}"/>
- </target>
-
- <target name="bzip2" depends="tar" description="build release archive">
- <bzip2 src="${release.tar}" destfile="${release.bz2}"/>
- </target>
-
- <target name="release" depends="zip,gzip" description="build all release archives except .bz2"/>
-
- <target name="release-all" depends="zip,gzip,bzip2" description="build all release archives"/>
-
-
- <target name="clean" description="remove build and release artifacts">
- <iterate target="clean"/>
- <delete dir="${build}"/>
- <delete dir="${release}"/>
- <delete dir="${tasks.classes}"/>
- </target>
-
- <target name="coverage-report" description="generate coverage report" depends="cobertura-init">
- <cobertura-merge datafile="${build.coveragereport}/cobertura.ser">
- <!-- merge all module coverage reports -->
- <fileset dir="${build}">
- <include name="**/*.ser"/>
- </fileset>
- </cobertura-merge>
- <cobertura-report format="xml"
- destdir="${build.coveragereport}"
- datafile="${build.coveragereport}/cobertura.ser"
- >
- <fileset dir="${project.root}/common/src/main/java" includes="**/*.java" />
- <fileset dir="${project.root}/build/scratch/common/src" includes="**/*.java" />
- <fileset dir="${project.root}/broker/src/main/java" includes="**/*.java" />
- <fileset dir="${project.root}/build/scratch/broker/src" includes="**/*.java" />
- <fileset dir="${project.root}/client/src/main/java" includes="**/*.java" />
- <fileset dir="${project.root}/build/scratch/client/src" includes="**/*.java" />
- </cobertura-report>
- <cobertura-report format="html"
- destdir="${build.coveragereport}"
- datafile="${build.coveragereport}/cobertura.ser"
- >
- <fileset dir="${project.root}/common/src/main/java" includes="**/*.java" />
- <fileset dir="${project.root}/build/scratch/common/src" includes="**/*.java" />
- <fileset dir="${project.root}/broker/src/main/java" includes="**/*.java" />
- <fileset dir="${project.root}/build/scratch/broker/src" includes="**/*.java" />
- <fileset dir="${project.root}/client/src/main/java" includes="**/*.java" />
- <fileset dir="${project.root}/build/scratch/client/src" includes="**/*.java" />
- </cobertura-report>
- </target>
-
- <target name="instrument" description="instrument for artifacts">
- <iterate target="instrument"/>
- </target>
-
- <target name="cover-test" description="run tests and generate coverage information" depends="build">
- <iterate target="cover-test" modules="broker client common"/>
- </target>
-
- <target name="test-interop" depends="build,compile-tests"
- description="run JMS examples against the corresponding c++ and python examples">
- <property name="qpid.src.home" location=".."/>
- <echo-prop name="qpid.src.home"/>
- <exec executable="/bin/sh" failonerror="true">
- <env key="QPID_SRC_HOME" value="${qpid.src.home}"/>
- <arg value="-c"/>
- <arg value="${project.root}/client/example/bin/verify_all"/>
- </exec>
- </target>
-
- <target name="testkit" depends="build,compile-tests">
- <jython path="${mllib.dir}">
- <args>
- <arg value="${mllib.dir}/qpid-python-test"/>
- <arg value="-m ${basedir}/testkit/testkit"/>
- </args>
- </jython>
- </target>
-
- <target name="findbugs" depends="findbugs-init,build">
-
- <mkdir dir="${build.findbugs}"/>
-
- <findbugs home="${findbugs.dir}"
- output="html"
- outputFile="${build.findbugs}/report.html"
- stylesheet="fancy-hist.xsl"
- jvmargs="-Xmx512m"
- projectName="Qpid">
- <auxAnalyzePath>
- <fileset dir="${build.lib}" includes="qpid*.jar" excludes="*test*.jar *junit*.jar *example*.jar qpid-all.jar"/>
- </auxAnalyzePath>
- <auxClassPath>
- <fileset dir="${build.lib}" includes="**/*.jar" />
- <fileset dir="${basedir}/lib" includes="org.eclipse*.jar com.ibm.*.jar"/>
- </auxClassPath>
- <sourcePath>
- <fileset dir="${basedir}" includes="**/src/**/org/.." />
- </sourcePath>
- </findbugs>
- </target>
-
- <target name="eclipse" description="build eclipse project and classpath files">
- <iterate target="eclipse"/>
- </target>
-</project>
diff --git a/java/client/README.txt b/java/client/README.txt
deleted file mode 100644
index 57a98cc978..0000000000
--- a/java/client/README.txt
+++ /dev/null
@@ -1,51 +0,0 @@
-Documentation
-=============
-
-You can access documentation for the client via our website at:
-http://qpid.apache.org/documentation
-
-and via our wiki at:
-http://cwiki.apache.org/confluence/display/qpid/Qpid+Java+Documentation
-
-The client uses the Java Message Service (JMS) 1.1 API, information on which is
-widely available using your favoured search engine.
-
-
-Running the Examples:
-=====================
-
-1. From the client Binary distribution:
-
-From the <installation path>/qpid-client-<version> directory, there are examples
-provided in source form in the example/src sub-directory. These are also
-provided in binary form in the example/lib directory in order that they can be
-run more easily.
-
-E.g, in order to run the Hello example, you would add the client+example library
-files to the java classpath and launch the example like follows:
-
-java -cp "lib/qpid-all.jar:example/lib/qpid-client-examples-<version>.jar" \
- org.apache.qpid.example.Hello
-
-NOTE: The client uses the SL4FJ API for its logging. You must supply a logging
-implementation of your choice (eg Log4J) and its associated SLF4J binding, by
-also adding them to the Java classpath as well as the client libraries
-themselves. Failure to do so will result in a warning being output and use of
-NoOp logging by the client.
-
-More information on using SLF4J is available at http://www.slf4j.org/manual.html
-which details some of the supported logging implementations and their
-associated SLF4 bindings as available in the SLF4J distribution.
-
-
-
-2. From the Source distribution / repository:
-
-Run 'ant build' in the parent directory from where this file is stored, ie:
-<installation path>/qpid/java
-
-This will build the various Java modules, leaving binary .jar files output in:
-<installation path>/qpid/java/build/lib
-
-Taking the above the 'distribution directory', consult the README.txt file at:
-<installation path>/qpid/java/client/example/src/main/java
diff --git a/java/client/build.xml b/java/client/build.xml
deleted file mode 100644
index d52de8dca6..0000000000
--- a/java/client/build.xml
+++ /dev/null
@@ -1,72 +0,0 @@
-<!--
- -
- - Licensed to the Apache Software Foundation (ASF) under one
- - or more contributor license agreements. See the NOTICE file
- - distributed with this work for additional information
- - regarding copyright ownership. The ASF licenses this file
- - to you under the Apache License, Version 2.0 (the
- - "License"); you may not use this file except in compliance
- - with the License. You may obtain a copy of the License at
- -
- - http://www.apache.org/licenses/LICENSE-2.0
- -
- - Unless required by applicable law or agreed to in writing,
- - software distributed under the License is distributed on an
- - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- - KIND, either express or implied. See the License for the
- - specific language governing permissions and limitations
- - under the License.
- -
- -->
-<project name="AMQ Client" default="build">
-
- <property name="module.depends" value="common"/>
- <property name="module.test.depends" value="common/test" />
- <property name="module.genpom" value="true"/>
- <property name="module.genpom.args" value="-Sgeronimo-jms_1.1_spec=provided"/>
-
- <import file="../module.xml"/>
-
- <property name="example.src.dir" value="${project.root}/client/example/src/main/java" />
- <property name="example.jar.file" value="${build.lib}/qpid-client-example-${project.version}.jar" />
-
- <property name="output.dir" value="${module.precompiled}/org/apache/qpid/filter/selector"/>
-
- <target name="precompile">
- <mkdir dir="${output.dir}"/>
- <javacc target="src/main/grammar/SelectorParser.jj"
- outputdirectory="${output.dir}"
- javacchome="${project.root}/lib"/>
- </target>
-
-
- <uptodate property="doc-release.done" targetfile="${module.release}/api/index.html">
- <srcfiles dir="${module.src}" includes="**/*.java"/>
- </uptodate>
-
- <target name="doc-release" depends="build" unless="doc-release.done">
- <javadoc destdir="${module.release}/api" sourcepathref="module.src.path"
- classpathref="module.class.path" packagenames="org.apache.qpid.jms"/>
- </target>
-
- <target name="release-bin-copy-examples">
- <copy todir="${module.release}/example/src" failonerror="true">
- <fileset dir="${example.src.dir}" excludes="runSample.sh README.txt" />
- </copy>
- <copy todir="${module.release}/example/lib" failonerror="true">
- <fileset file="${example.jar.file}"/>
- </copy>
- </target>
-
- <target name="release-bin-copy-readme">
- <copy todir="${module.release}" overwrite="true" failonerror="true">
- <fileset file="${basedir}/README.txt" />
- </copy>
- </target>
-
- <target name="release-bin-other" depends="release-bin-copy-examples,release-bin-copy-readme"/>
-
- <target name="release-bin" depends="release-bin-tasks"/>
-
- <target name="bundle" depends="bundle-tasks"/>
-</project>
diff --git a/java/client/example/build.xml b/java/client/example/build.xml
deleted file mode 100644
index 8b0d59bd8a..0000000000
--- a/java/client/example/build.xml
+++ /dev/null
@@ -1,28 +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.
- -
- -->
-<project name="AMQ Client" default="build">
-
- <property name="module.depends" value="client common"/>
- <property name="module.test.depends" value=""/>
-
- <import file="../../module.xml"/>
-
-</project>
diff --git a/java/client/example/src/main/java/README.txt b/java/client/example/src/main/java/README.txt
deleted file mode 100644
index 757054e492..0000000000
--- a/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 <class name> <arguments> \ No newline at end of file
diff --git a/java/client/example/src/main/java/org/apache/qpid/example/Drain.java b/java/client/example/src/main/java/org/apache/qpid/example/Drain.java
deleted file mode 100644
index b43031ad23..0000000000
--- a/java/client/example/src/main/java/org/apache/qpid/example/Drain.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.example;
-
-import javax.jms.Connection;
-import javax.jms.Destination;
-import javax.jms.Message;
-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
-{
-
- static final Option FOREVER = new Option("f",
- "forever",
- "ignore timeout and wait forever",
- null,
- null,
- Boolean.class);
-
- static final Option COUNT = new Option ("c",
- "count",
- "read c messages, then exit",
- "COUNT",
- "0",
- Integer.class);
-
-
- static
- {
- optDefs.add(BROKER);
- optDefs.add(HELP);
- optDefs.add(TIMEOUT);
- optDefs.add(FOREVER);
- optDefs.add(COUNT);
- optDefs.add(CON_OPTIONS);
- optDefs.add(BROKER_OPTIONS);
- }
-
- public Drain(String[] args, String usage, String desc) throws Exception
- {
- super(args, usage, desc);
-
- Connection con = createConnection();
- con.start();
- Session ssn = con.createSession(false,Session.AUTO_ACKNOWLEDGE);
- Destination dest = new AMQAnyDestination(address);
- MessageConsumer consumer = ssn.createConsumer(dest);
- Message msg;
-
- long timeout = -1;
- int count = 0;
- int i = 0;
-
- if (containsOp(TIMEOUT)) { timeout = Integer.parseInt(getOp(TIMEOUT))*1000; }
- if (containsOp(FOREVER)) { timeout = 0; }
- if (containsOp(COUNT)) { count = Integer.parseInt(getOp(COUNT)); }
-
- while ((msg = consumer.receive(timeout)) != null)
- {
- System.out.println("\n------------- Msg -------------");
- System.out.println(msg);
- System.out.println("-------------------------------\n");
-
- if (count > 0) {
- if (++i == count) {
- break;
- }
- }
- }
-
- ssn.close();
- con.close();
- }
-
- public static void main(String[] args) throws Exception
- {
- String u = "Usage: drain [OPTIONS] 'ADDRESS'";
- String d = "Drains messages from the specified address.";
-
- new Drain(args,u,d);
- }
-}
diff --git a/java/client/example/src/main/java/org/apache/qpid/example/Hello.java b/java/client/example/src/main/java/org/apache/qpid/example/Hello.java
deleted file mode 100644
index 949ee4dac6..0000000000
--- a/java/client/example/src/main/java/org/apache/qpid/example/Hello.java
+++ /dev/null
@@ -1,74 +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.example;
-
-import javax.jms.*;
-import javax.naming.Context;
-import javax.naming.InitialContext;
-import java.util.Properties;
-
-
-public class Hello
-{
-
- public Hello()
- {
- }
-
- public static void main(String[] args)
- {
- Hello hello = new Hello();
- hello.runTest();
- }
-
- private void runTest()
- {
- try {
- Properties properties = new Properties();
- properties.load(this.getClass().getResourceAsStream("hello.properties"));
- Context context = new InitialContext(properties);
-
- ConnectionFactory connectionFactory = (ConnectionFactory) context.lookup("qpidConnectionfactory");
- Connection connection = connectionFactory.createConnection();
- connection.start();
-
- Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- Destination destination = (Destination) context.lookup("topicExchange");
-
- MessageProducer messageProducer = session.createProducer(destination);
- MessageConsumer messageConsumer = session.createConsumer(destination);
-
- TextMessage message = session.createTextMessage("Hello world!");
- messageProducer.send(message);
-
- message = (TextMessage)messageConsumer.receive();
- System.out.println(message.getText());
-
- connection.close();
- context.close();
- }
- catch (Exception exp)
- {
- exp.printStackTrace();
- }
- }
-}
diff --git a/java/client/example/src/main/java/org/apache/qpid/example/MapReceiver.java b/java/client/example/src/main/java/org/apache/qpid/example/MapReceiver.java
deleted file mode 100644
index 89db04f8d3..0000000000
--- a/java/client/example/src/main/java/org/apache/qpid/example/MapReceiver.java
+++ /dev/null
@@ -1,52 +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.example;
-
-import javax.jms.Connection;
-import javax.jms.Destination;
-import javax.jms.MapMessage;
-import javax.jms.MessageConsumer;
-import javax.jms.Session;
-
-import org.apache.qpid.client.AMQAnyDestination;
-import org.apache.qpid.client.AMQConnection;
-
-
-public class MapReceiver {
-
- public static void main(String[] args) throws Exception
- {
- Connection connection =
- new AMQConnection("amqp://guest:guest@test/?brokerlist='tcp://localhost:5672'");
-
- connection.start();
-
- Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- Destination queue = new AMQAnyDestination("ADDR:message_queue; {create: always}");
- MessageConsumer consumer = session.createConsumer(queue);
-
- MapMessage m = (MapMessage)consumer.receive();
- System.out.println(m);
- connection.close();
- }
-
-} \ No newline at end of file
diff --git a/java/client/example/src/main/java/org/apache/qpid/example/MapSender.java b/java/client/example/src/main/java/org/apache/qpid/example/MapSender.java
deleted file mode 100644
index 0ce9383add..0000000000
--- a/java/client/example/src/main/java/org/apache/qpid/example/MapSender.java
+++ /dev/null
@@ -1,83 +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.example;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.jms.Connection;
-import javax.jms.Destination;
-import javax.jms.MapMessage;
-import javax.jms.MessageProducer;
-import javax.jms.Session;
-
-import org.apache.qpid.client.AMQAnyDestination;
-import org.apache.qpid.client.AMQConnection;
-
-
-public class MapSender {
-
- public static void main(String[] args) throws Exception
- {
- Connection connection =
- new AMQConnection("amqp://guest:guest@test/?brokerlist='tcp://localhost:5672'");
-
- Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- Destination queue = new AMQAnyDestination("ADDR:message_queue; {create: always}");
- MessageProducer producer = session.createProducer(queue);
-
- MapMessage m = session.createMapMessage();
- m.setIntProperty("Id", 987654321);
- m.setStringProperty("name", "Widget");
- m.setDoubleProperty("price", 0.99);
-
- List<String> colors = new ArrayList<String>();
- colors.add("red");
- colors.add("green");
- colors.add("white");
- m.setObject("colours", colors);
-
- Map<String,Double> dimensions = new HashMap<String,Double>();
- dimensions.put("length",10.2);
- dimensions.put("width",5.1);
- dimensions.put("depth",2.0);
- m.setObject("dimensions",dimensions);
-
- List<List<Integer>> parts = new ArrayList<List<Integer>>();
- parts.add(Arrays.asList(new Integer[] {1,2,5}));
- parts.add(Arrays.asList(new Integer[] {8,2,5}));
- m.setObject("parts", parts);
-
- Map<String,Object> specs = new HashMap<String,Object>();
- specs.put("colours", colors);
- specs.put("dimensions", dimensions);
- specs.put("parts", parts);
- m.setObject("specs",specs);
-
- producer.send(m);
- connection.close();
- }
-
-} \ No newline at end of file
diff --git a/java/client/example/src/main/java/org/apache/qpid/example/OptionParser.java b/java/client/example/src/main/java/org/apache/qpid/example/OptionParser.java
deleted file mode 100644
index f4e17c5c4c..0000000000
--- a/java/client/example/src/main/java/org/apache/qpid/example/OptionParser.java
+++ /dev/null
@@ -1,335 +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.example;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.jms.Connection;
-
-import org.apache.qpid.client.AMQConnection;
-
-public class OptionParser
-{
- static final Option BROKER = new Option("b",
- "broker",
- "connect to specified broker",
- "USER:PASS@HOST:PORT",
- "guest:guest@localhost:5672",
- String.class);
-
- static final Option HELP = new Option("h",
- "help",
- "show this help message and exit",
- null,
- null,
- Boolean.class);
-
- static final Option TIMEOUT = new Option("t",
- "timeout",
- "timeout in seconds to wait before exiting",
- "TIMEOUT",
- "0",
- Integer.class);
-
- static final Option CON_OPTIONS = new Option(null,
- "con-option",
- "JMS Connection URL options. Ex sync_ack=true sync_publish=all ",
- "NAME=VALUE",
- null,
- String.class);
-
-
- static final Option BROKER_OPTIONS = new Option(null,
- "broker-option",
- "JMS Broker URL options. Ex ssl=true sasl_mechs=GSSAPI ",
- "NAME=VALUE",
- null,
- String.class);
-
-
- protected Map<String,Object> optMap = new HashMap<String,Object>();
- protected static final List<Option> optDefs = new ArrayList<Option>();
-
- protected String usage;
- protected String desc;
- protected String address;
-
- public OptionParser(String[] args, String usage, String desc)
- {
- this.usage = usage;
- this.desc = desc;
-
- if (args.length == 0 ||
- (args.length == 1 && (args[0].equals("-h") || args[0].equals("--help"))))
- {
- printHelp();
- }
-
- address = args[args.length -1];
- String[] ops = new String[args.length -1];
- System.arraycopy(args, 0, ops, 0, ops.length);
- parseOpts(ops);
-
- System.out.println(optMap);
-
- if (isHelp())
- {
- printHelp();
- }
- }
-
- public boolean isHelp()
- {
- return optMap.containsKey("h") || optMap.containsKey("help");
- }
-
- public void printHelp()
- {
- System.out.println(String.format("%s\n",usage));
- System.out.println(String.format("%s\n",desc));
- System.out.println(String.format("%s\n","Options:"));
-
- for (Option op : optDefs)
- {
- String valueLabel = op.getValueLabel() != null ? "=" + op.getValueLabel() : "";
- String shortForm = op.getShortForm() != null ? "-" + op.getShortForm() + valueLabel : "";
- String longForm = op.getLongForm() != null ? "--" + op.getLongForm() + valueLabel : "";
- String desc = op.getDesc();
- String defaultValue = op.getDefaultValue() != null ?
- " (default " + op.getDefaultValue() + ")" : "";
-
- if (!shortForm.equals(""))
- {
- longForm = shortForm + ", " + longForm;
- }
- System.out.println(
- String.format("%-54s%s%s", longForm,desc,defaultValue));
- }
-
- System.exit(0);
- }
-
- private void parseOpts(String[] args)
- {
- String prevOpt = null;
- for(String op: args)
- {
- // covers both -h and --help formats
- if (op.startsWith("-"))
- {
- String key = op.substring(op.startsWith("--")? 2:1 ,
- (op.indexOf('=') > 0) ?
- op.indexOf('='):
- op.length());
-
- boolean match = false;
- for (Option option: optDefs)
- {
-
- if ((op.startsWith("-") && option.shortForm != null && option.shortForm.equals(key)) ||
- (op.startsWith("--") && option.longForm != null && option.longForm.equals(key)) )
- {
- match = true;
- break;
- }
- }
-
- if (!match)
- {
- System.out.println(op + " is not a valid option");
- System.exit(0);
- }
-
- if (op.indexOf('=') > 0)
- {
- String val = extractValue(op.substring(op.indexOf('=')+1));
- if (optMap.containsKey(key))
- {
- optMap.put(key, optMap.get(key) + "," + val);
- }
- else
- {
- optMap.put(key, val);
- }
- }
- else
- {
- if (! optMap.containsKey(key)){ optMap.put(key, ""); }
- prevOpt = key;
- }
- }
- else if (prevOpt != null) // this is to catch broker localhost:5672 instead broker=localhost:5672
- {
- String val = extractValue(op);
- if (optMap.containsKey(prevOpt) && !optMap.get(prevOpt).toString().equals(""))
- {
- optMap.put(prevOpt, optMap.get(prevOpt) + "," + val);
- }
- else
- {
- optMap.put(prevOpt, val);
- }
- prevOpt = null;
- }
- else
- {
- System.out.println(optMap);
- throw new IllegalArgumentException(op + " is not a valid option");
- }
- }
- }
-
- private String extractValue(String op)
- {
- if (op.startsWith("'"))
- {
- if (!op.endsWith("'"))
- throw new IllegalArgumentException(" The option " + op + " needs to be inside quotes");
-
- return op.substring(1,op.length() -1);
- }
- else
- {
- return op;
- }
- }
-
- protected boolean containsOp(Option op)
- {
- return optMap.containsKey(op.shortForm) || optMap.containsKey(op.longForm);
- }
-
- protected String getOp(Option op)
- {
- if (optMap.containsKey(op.shortForm))
- {
- return (String)optMap.get(op.shortForm);
- }
- else if (optMap.containsKey(op.longForm))
- {
- return (String)optMap.get(op.longForm);
- }
- else
- {
- return op.getDefaultValue();
- }
- }
-
- protected Connection createConnection() throws Exception
- {
- StringBuffer buf;
- buf = new StringBuffer();
- buf.append("amqp://");
- String userPass = "guest:guest";
- String broker = "localhost:5672";
- if(containsOp(BROKER))
- {
- try
- {
- String b = getOp(BROKER);
- userPass = b.substring(0,b.indexOf('@'));
- broker = b.substring(b.indexOf('@')+1);
- }
- catch (StringIndexOutOfBoundsException e)
- {
- Exception ex = new Exception("Error parsing broker string " + getOp(BROKER));
- ex.initCause(e);
- throw ex;
- }
-
- }
-
- if(containsOp(BROKER_OPTIONS))
- {
- String bOps = getOp(BROKER_OPTIONS);
- bOps = bOps.replaceAll(",", "'&");
- bOps = bOps.replaceAll("=", "='");
- broker = broker + "?" + bOps + "'";
- }
- buf.append(userPass);
- buf.append("@test/test?brokerlist='tcp://");
- buf.append(broker).append("'");
- if(containsOp(CON_OPTIONS))
- {
- String bOps = getOp(CON_OPTIONS);
- bOps = bOps.replaceAll(",", "'&");
- bOps = bOps.replaceAll("=", "='");
- buf.append("&").append(bOps).append("'");
- }
-
- Connection con = new AMQConnection(buf.toString());
- return con;
- }
-
- static class Option
- {
- private String shortForm;
- private String longForm;
- private String desc;
- private String valueLabel;
- private String defaultValue;
- private Class type;
-
- public Option(String shortForm, String longForm, String desc,
- String valueLabel, String defaultValue, Class type)
- {
- this.shortForm = shortForm;
- this.longForm = longForm;
- this.defaultValue = defaultValue;
- this.type = type;
- this.desc = desc;
- this.valueLabel = valueLabel;
- }
-
- public String getShortForm()
- {
- return shortForm;
- }
-
- public String getLongForm()
- {
- return longForm;
- }
-
- public String getDefaultValue()
- {
- return defaultValue;
- }
-
- public Class getType()
- {
- return type;
- }
-
- public String getDesc()
- {
- return desc;
- }
-
- public String getValueLabel()
- {
- return valueLabel;
- }
- }
-}
diff --git a/java/client/example/src/main/java/org/apache/qpid/example/Spout.java b/java/client/example/src/main/java/org/apache/qpid/example/Spout.java
deleted file mode 100644
index 5da319a658..0000000000
--- a/java/client/example/src/main/java/org/apache/qpid/example/Spout.java
+++ /dev/null
@@ -1,148 +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.example;
-
-import javax.jms.Connection;
-import javax.jms.Destination;
-import javax.jms.MapMessage;
-import javax.jms.Message;
-import javax.jms.MessageProducer;
-import javax.jms.Session;
-
-import org.apache.qpid.client.AMQAnyDestination;
-
-public class Spout extends OptionParser
-{
-
- static final Option COUNT = new Option("c",
- "count",
- "stop after count messages have been sent, zero disables",
- "COUNT",
- "1",
- Integer.class);
-
- static final Option ID = new Option("i",
- "id",
- "use the supplied id instead of generating one",
- null,
- null,
- Boolean.class);
-
- static final Option CONTENT = new Option(null,
- "content",
- "specify textual content",
- "TEXT",
- null,
- Boolean.class);
-
- static final Option MSG_PROPERTY = new Option("P",
- "property",
- "specify message property",
- "NAME=VALUE",
- null,
- Boolean.class);
-
- static final Option MAP_ENTRY = new Option("M",
- "map",
- "specify entry for map content",
- "KEY=VALUE",
- null,
- Boolean.class);
-
- static
- {
- optDefs.add(BROKER);
- optDefs.add(HELP);
- optDefs.add(TIMEOUT);
- optDefs.add(COUNT);
- optDefs.add(MSG_PROPERTY);
- optDefs.add(MAP_ENTRY);
- optDefs.add(CONTENT);
- optDefs.add(CON_OPTIONS);
- optDefs.add(BROKER_OPTIONS);
- }
-
- public Spout(String[] args, String usage, String desc) throws Exception
- {
- super(args, usage, desc);
-
- Connection con = createConnection();
- con.start();
- Session ssn = con.createSession(false,Session.AUTO_ACKNOWLEDGE);
- Destination dest = new AMQAnyDestination(address);
- MessageProducer producer = ssn.createProducer(dest);
-
- int count = Integer.parseInt(getOp(COUNT));
-
- for (int i=0; i < count; i++)
- {
- Message msg = createMessage(ssn);
- producer.send(msg);
- System.out.println("\n------------- Msg -------------");
- System.out.println(msg);
- System.out.println("-------------------------------\n");
- }
- ssn.close();
- con.close();
- }
-
- private Message createMessage(Session ssn) throws Exception
- {
- if (containsOp(MAP_ENTRY))
- {
- MapMessage msg = ssn.createMapMessage();
- for (String pair: getOp(MAP_ENTRY).split(","))
- {
- msg.setString(pair.substring(0, pair.indexOf('=')),
- pair.substring(pair.indexOf('=') + 1));
- }
- setProperties(msg);
- return msg;
- }
- else
- {
- Message msg =
- ssn.createTextMessage(containsOp(CONTENT) ? getOp(CONTENT) : "");
- setProperties(msg);
- return msg;
- }
- }
-
- private void setProperties(Message m) throws Exception
- {
- if(containsOp(MSG_PROPERTY))
- {
- for (String pair: getOp(MSG_PROPERTY).split(","))
- {
- m.setStringProperty(pair.substring(0, pair.indexOf('=')),
- pair.substring(pair.indexOf('=') + 1));
- }
- }
- }
-
- public static void main(String[] args) throws Exception
- {
- String u = "Usage: spout [OPTIONS] 'ADDRESS'";
- String d = "Send messages to the specified address.";
-
- new Spout(args,u,d);
- }
-}
diff --git a/java/client/example/src/main/java/org/apache/qpid/example/hello.properties b/java/client/example/src/main/java/org/apache/qpid/example/hello.properties
deleted file mode 100644
index 27ea66b318..0000000000
--- a/java/client/example/src/main/java/org/apache/qpid/example/hello.properties
+++ /dev/null
@@ -1,27 +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.
-#
-java.naming.factory.initial = org.apache.qpid.jndi.PropertiesFileInitialContextFactory
-
-# register some connection factories
-# connectionfactory.[jndiname] = [ConnectionURL]
-connectionfactory.qpidConnectionfactory = amqp://guest:guest@clientid/test?brokerlist='tcp://localhost:5672'
-
-# Register an AMQP destination in JNDI
-# destination.[jniName] = [Address Format]
-destination.topicExchange = amq.topic
diff --git a/java/client/example/src/main/java/org/apache/qpid/example/publisher/FileMessageDispatcher.java b/java/client/example/src/main/java/org/apache/qpid/example/publisher/FileMessageDispatcher.java
deleted file mode 100644
index 1849f733e9..0000000000
--- a/java/client/example/src/main/java/org/apache/qpid/example/publisher/FileMessageDispatcher.java
+++ /dev/null
@@ -1,163 +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.example.publisher;
-
-import java.io.File;
-
-import javax.jms.JMSException;
-
-
-import org.apache.qpid.example.shared.FileUtils;
-import org.apache.qpid.example.shared.Statics;
-import org.slf4j.LoggerFactory;
-import org.slf4j.Logger;
-
-/**
- * Class that sends message files to the Publisher to distribute
- * using files as input
- * Must set properties for host in properties file or uses in vm broker
- */
-public class FileMessageDispatcher
-{
-
- protected static final Logger _logger = LoggerFactory.getLogger(FileMessageDispatcher.class);
-
- protected static Publisher _publisher = null;
-
- /**
- * To use this main method you need to specify a path or file to use for input
- * This class then uses file contents from the dir/file specified to generate
- * messages to publish
- * Intended to be a very simple way to get going with publishing using the broker
- * @param args - must specify one value, the path to file(s) for publisher
- */
- public static void main(String[] args)
- {
-
- // Check command line args ok - must provide a path or file for us to dispatch
- if (args.length == 0)
- {
- System.out.println("Usage: FileMessageDispatcher <filesToDispatch>" + "");
- }
- else
- {
- try
- {
- // publish message(s) from file(s) to configured queue
- publish(args[0]);
-
- // Move payload file(s) to archive location as no error
- FileUtils.moveFileToNewDir(args[0], System.getProperties().getProperty(Statics.ARCHIVE_PATH));
- }
- catch (Exception e)
- {
- // log error and exit
- _logger.error("Error trying to dispatch message: " + e);
- System.exit(1);
- }
- finally
- {
- // clean up before exiting
- if (getPublisher() != null)
- {
- getPublisher().cleanup();
- }
- }
- }
-
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Finished dispatching message");
- }
-
- System.exit(0);
- }
-
- /**
- * Publish the content of a file or files from a directory as messages
- * @param path - from main args
- * @throws JMSException
- * @throws MessageFactoryException - if cannot create message from file content
- */
- public static void publish(String path) throws JMSException, MessageFactoryException
- {
- File tempFile = new File(path);
- if (tempFile.isDirectory())
- {
- // while more files in dir publish them
- File[] files = tempFile.listFiles();
-
- if ((files == null) || (files.length == 0))
- {
- _logger.info("FileMessageDispatcher - No files to publish in input directory: " + tempFile);
- }
- else
- {
- for (File file : files)
- {
- // Create message factory passing in payload path
- FileMessageFactory factory = new FileMessageFactory(getPublisher().getSession(), file.toString());
-
- // Send the message generated from the payload using the _publisher
- getPublisher().sendMessage(factory.createEventMessage());
-
- }
- }
- }
- else
- {
- // handle a single file
- // Create message factory passing in payload path
- FileMessageFactory factory = new FileMessageFactory(getPublisher().getSession(), tempFile.toString());
-
- // Send the message generated from the payload using the _publisher
- getPublisher().sendMessage(factory.createEventMessage());
- }
- }
-
- /**
- * Cleanup before exit
- */
- public static void cleanup()
- {
- if (getPublisher() != null)
- {
- getPublisher().cleanup();
- }
- }
-
- /**
- * @return A Publisher instance
- */
- private static Publisher getPublisher()
- {
- if (_publisher != null)
- {
- return _publisher;
- }
-
- // Create a _publisher
- _publisher = new Publisher();
-
- return _publisher;
- }
-
-}
diff --git a/java/client/example/src/main/java/org/apache/qpid/example/publisher/FileMessageFactory.java b/java/client/example/src/main/java/org/apache/qpid/example/publisher/FileMessageFactory.java
deleted file mode 100644
index 04339b2498..0000000000
--- a/java/client/example/src/main/java/org/apache/qpid/example/publisher/FileMessageFactory.java
+++ /dev/null
@@ -1,138 +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.example.publisher;
-
-import org.apache.qpid.util.FileUtils;
-import org.apache.qpid.example.shared.Statics;
-
-import java.io.*;
-import javax.jms.*;
-
-public class FileMessageFactory
-{
- protected final Session _session;
- protected final String _payload;
- protected final String _filename;
-
- /**
- * Contructs and instance using a filename from which content will be used to create message
- * @param session
- * @param filename
- * @throws MessageFactoryException
- */
- public FileMessageFactory(Session session, String filename) throws MessageFactoryException
- {
- try
- {
- _filename = filename;
- _payload = FileUtils.readFileAsString(filename);
- _session = session;
- }
- catch (Exception e)
- {
- MessageFactoryException mfe = new MessageFactoryException(e.toString(), e);
- throw mfe;
- }
- }
-
- /**
- * Creates a text message and sets filename property on it
- * The filename property is purely intended to provide visibility
- * of file content passing trhough the broker using example classes
- * @return Message - a TextMessage with content from file
- * @throws JMSException
- */
- public Message createEventMessage() throws JMSException
- {
- TextMessage msg = _session.createTextMessage();
- msg.setText(_payload);
- msg.setStringProperty(Statics.FILENAME_PROPERTY, new File(_filename).getName());
-
- return msg;
- }
-
- /**
- * Creates message from a string for use by the monitor
- * @param session
- * @param textMsg - message content
- * @return Message - TextMessage with content from String
- * @throws JMSException
- */
- public static Message createSimpleEventMessage(Session session, String textMsg) throws JMSException
- {
- TextMessage msg = session.createTextMessage();
- msg.setText(textMsg);
-
- return msg;
- }
-
- public Message createShutdownMessage() throws JMSException
- {
- return _session.createTextMessage("SHUTDOWN");
- }
-
- public Message createReportRequestMessage() throws JMSException
- {
- return _session.createTextMessage("REPORT");
- }
-
- public Message createReportResponseMessage(String msg) throws JMSException
- {
- return _session.createTextMessage(msg);
- }
-
- public boolean isShutdown(Message m)
- {
- return checkText(m, "SHUTDOWN");
- }
-
- public boolean isReport(Message m)
- {
- return checkText(m, "REPORT");
- }
-
- public Object getReport(Message m)
- {
- try
- {
- return ((TextMessage) m).getText();
- }
- catch (JMSException e)
- {
- e.printStackTrace(System.out);
-
- return e.toString();
- }
- }
-
- private static boolean checkText(Message m, String s)
- {
- try
- {
- return (m instanceof TextMessage) && ((TextMessage) m).getText().equals(s);
- }
- catch (JMSException e)
- {
- e.printStackTrace(System.out);
-
- return false;
- }
- }
-}
diff --git a/java/client/example/src/main/java/org/apache/qpid/example/publisher/MessageFactoryException.java b/java/client/example/src/main/java/org/apache/qpid/example/publisher/MessageFactoryException.java
deleted file mode 100644
index d709da6432..0000000000
--- a/java/client/example/src/main/java/org/apache/qpid/example/publisher/MessageFactoryException.java
+++ /dev/null
@@ -1,29 +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.example.publisher;
-
-public class MessageFactoryException extends Exception
-{
- public MessageFactoryException(String msg, Throwable t)
- {
- super(msg, t);
- }
-}
diff --git a/java/client/example/src/main/java/org/apache/qpid/example/publisher/MonitorMessageDispatcher.java b/java/client/example/src/main/java/org/apache/qpid/example/publisher/MonitorMessageDispatcher.java
deleted file mode 100644
index 3d16e01af4..0000000000
--- a/java/client/example/src/main/java/org/apache/qpid/example/publisher/MonitorMessageDispatcher.java
+++ /dev/null
@@ -1,141 +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.example.publisher;
-
-
-import org.slf4j.LoggerFactory;
-import org.slf4j.Logger;
-
-import javax.jms.DeliveryMode;
-import javax.jms.JMSException;
-
-/**
- * Class that sends heartbeat messages to allow monitoring of message consumption Sends regular (currently 20 seconds
- * apart) heartbeat message
- */
-public class MonitorMessageDispatcher
-{
-
- private static final Logger _logger = LoggerFactory.getLogger(MonitorMessageDispatcher.class);
-
- protected static MonitorPublisher _monitorPublisher = null;
-
- protected static final String DEFAULT_MONITOR_PUB_NAME = "MonitorPublisher";
-
- /**
- * Easy entry point for running a message dispatcher for monitoring consumption
- * Sends 1000 messages with no delay
- *
- * @param args
- */
- public static void main(String[] args)
- {
- //Switch on logging appropriately for your app
- try
- {
- int i =0;
- while (i < 1000)
- {
- try
- {
- //endlessly publish messages to monitor queue
- publish();
-
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Dispatched monitor message");
- }
-
- //sleep for twenty seconds and then publish again - change if appropriate
- //Thread.sleep(1000);
- i++ ;
- }
- catch (UndeliveredMessageException a)
- {
- //trigger application specific failure handling here
- _logger.error("Problem delivering monitor message");
- break;
- }
- }
- }
- catch (Exception e)
- {
- _logger.error("Error trying to dispatch AMS monitor message: " + e);
- System.exit(1);
- }
- finally
- {
- if (getMonitorPublisher() != null)
- {
- getMonitorPublisher().cleanup();
- }
- }
-
- System.exit(1);
- }
-
- /**
- * Publish heartbeat message
- *
- * @throws JMSException
- * @throws UndeliveredMessageException
- */
- public static void publish() throws JMSException, UndeliveredMessageException
- {
- //Send the message generated from the payload using the _publisher
-// getMonitorPublisher().sendImmediateMessage
-// (FileMessageFactory.createSimpleEventMessage(getMonitorPublisher().getSession(),"monitor:" +System.currentTimeMillis()));
-
- getMonitorPublisher().sendMessage
- (getMonitorPublisher()._session,
- FileMessageFactory.createSimpleEventMessage(getMonitorPublisher().getSession(), "monitor:" + System.currentTimeMillis()),
- DeliveryMode.PERSISTENT, false, true);
-
- }
-
- /** Cleanup publishers */
- public static void cleanup()
- {
- if (getMonitorPublisher() != null)
- {
- getMonitorPublisher().cleanup();
- }
-
- if (getMonitorPublisher() != null)
- {
- getMonitorPublisher().cleanup();
- }
- }
-
- //Returns a _publisher for the monitor queue
- private static MonitorPublisher getMonitorPublisher()
- {
- if (_monitorPublisher != null)
- {
- return _monitorPublisher;
- }
-
- //Create a _publisher using failover details and constant for monitor queue
- _monitorPublisher = new MonitorPublisher();
-
- _monitorPublisher.setName(MonitorMessageDispatcher.DEFAULT_MONITOR_PUB_NAME);
- return _monitorPublisher;
- }
-
-}
diff --git a/java/client/example/src/main/java/org/apache/qpid/example/publisher/MonitorPublisher.java b/java/client/example/src/main/java/org/apache/qpid/example/publisher/MonitorPublisher.java
deleted file mode 100644
index 750f57d9dc..0000000000
--- a/java/client/example/src/main/java/org/apache/qpid/example/publisher/MonitorPublisher.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.example.publisher;
-
-import org.apache.qpid.client.BasicMessageProducer;
-import org.slf4j.LoggerFactory;
-import org.slf4j.Logger;
-
-import javax.jms.DeliveryMode;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.Session;
-
-/**
- * Subclass of Publisher which uses QPID functionality to send a heartbeat message Note immediate flag not available via
- * JMS MessageProducer
- */
-public class MonitorPublisher extends Publisher
-{
-
- private static final Logger _log = LoggerFactory.getLogger(Publisher.class);
-
- BasicMessageProducer _producer;
-
- public MonitorPublisher()
- {
- super();
- }
-
- /*
- * Publishes a message using given details
- */
- public boolean sendMessage(Session session, Message message, int deliveryMode,
- boolean immediate, boolean commit) throws UndeliveredMessageException
- {
- try
- {
- _producer = (BasicMessageProducer) session.createProducer(_destination);
-
- _producer.send(message, deliveryMode, immediate);
-
- if (commit)
- {
- //commit the message send and close the transaction
- _session.commit();
- }
-
- }
- catch (JMSException e)
- {
- //Have to assume our commit failed but do not rollback here as channel closed
- _log.error("JMSException", e);
- e.printStackTrace();
- throw new UndeliveredMessageException("Cannot deliver immediate message", e);
- }
-
- _log.info(_name + " finished sending message: " + message);
- return true;
- }
-
- /*
- * Publishes a non-persistent message using transacted session
- */
- public boolean sendImmediateMessage(Message message) throws UndeliveredMessageException
- {
- try
- {
- _producer = (BasicMessageProducer) _session.createProducer(_destination);
-
- //Send message via our producer which is not persistent and is immediate
- //NB: not available via jms interface MessageProducer
- _producer.send(message, DeliveryMode.NON_PERSISTENT, true);
-
- //commit the message send and close the transaction
- _session.commit();
-
- }
- catch (JMSException e)
- {
- //Have to assume our commit failed but do not rollback here as channel closed
- _log.error("JMSException", e);
- e.printStackTrace();
- throw new UndeliveredMessageException("Cannot deliver immediate message", e);
- }
-
- _log.info(_name + " finished sending message: " + message);
- return true;
- }
-}
diff --git a/java/client/example/src/main/java/org/apache/qpid/example/publisher/MultiMessageDispatcher.java b/java/client/example/src/main/java/org/apache/qpid/example/publisher/MultiMessageDispatcher.java
deleted file mode 100644
index a92efe99ac..0000000000
--- a/java/client/example/src/main/java/org/apache/qpid/example/publisher/MultiMessageDispatcher.java
+++ /dev/null
@@ -1,141 +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.example.publisher;
-
-import java.io.File;
-
-import javax.jms.JMSException;
-import javax.jms.TextMessage;
-
-
-import org.apache.qpid.example.shared.FileUtils;
-import org.apache.qpid.example.shared.Statics;
-import org.slf4j.LoggerFactory;
-import org.slf4j.Logger;
-
-/**
- * Class that sends parameterised number of message files to the Publisher
- * Must set properties for host in properties file or uses in vm broker
- */
-public class MultiMessageDispatcher
-{
-
- protected static final Logger _logger = LoggerFactory.getLogger(FileMessageDispatcher.class);
-
- protected static Publisher _publisher = null;
-
- /**
- * To use this main method you need to specify a path or file to use for input
- * This class then uses file contents from the dir/file specified to generate
- * messages to publish
- * Intended to be a very simple way to get going with publishing using the broker
- * @param args - must specify one value, the path to file(s) for publisher
- */
- public static void main(String[] args)
- {
-
- // Check command line args ok - must provide a path or file for us to dispatch
- if (args.length < 2)
- {
- System.out.println("Usage: MultiMessageDispatcher <numberOfMessagesToSend> <topic(true|false)>" + "");
- }
- else
- {
- boolean topicPublisher = true;
-
- try
- {
- // publish message(s)
- topicPublisher = new Boolean(args[1]).booleanValue();
- publish(new Integer(args[0]).intValue(),topicPublisher);
-
- // Move payload file(s) to archive location as no error
- FileUtils.moveFileToNewDir(args[0], System.getProperties().getProperty(Statics.ARCHIVE_PATH));
- }
- catch (Exception e)
- {
- // log error and exit
- _logger.error("Error trying to dispatch message: " + e);
- System.exit(1);
- }
- finally
- {
-
- cleanup(topicPublisher);
- }
- }
-
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Finished dispatching message");
- }
-
- System.exit(0);
- }
-
- /**
- * Publish the content of a file or files from a directory as messages
- * @param numMessages - from main args
- * @throws javax.jms.JMSException
- * @throws org.apache.qpid.example.publisher.MessageFactoryException - if cannot create message from file content
- */
- public static void publish(int numMessages, boolean topicPublisher) throws JMSException, MessageFactoryException
- {
- {
- // Send the message generated from the payload using the _publisher
- getPublisher(topicPublisher).sendMessage(numMessages);
- }
- }
-
- /**
- * Cleanup before exit
- */
- public static void cleanup(boolean topicPublisher)
- {
- if (getPublisher(topicPublisher) != null)
- {
- getPublisher(topicPublisher).cleanup();
- }
- }
-
- /**
- * @return A Publisher instance
- */
- private static Publisher getPublisher(boolean topic)
- {
- if (_publisher != null)
- {
- return _publisher;
- }
-
- if (!topic)
- {
- // Create a _publisher
- _publisher = new Publisher();
- }
- else
- {
- _publisher = new TopicPublisher();
- }
- return _publisher;
- }
-
-} \ No newline at end of file
diff --git a/java/client/example/src/main/java/org/apache/qpid/example/publisher/Publisher.java b/java/client/example/src/main/java/org/apache/qpid/example/publisher/Publisher.java
deleted file mode 100644
index b5f44557a4..0000000000
--- a/java/client/example/src/main/java/org/apache/qpid/example/publisher/Publisher.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.example.publisher;
-
-import org.apache.qpid.client.AMQConnectionFactory;
-
-import javax.jms.*;
-
-import javax.naming.InitialContext;
-
-import org.apache.qpid.example.shared.InitialContextHelper;
-import org.slf4j.LoggerFactory;
-import org.slf4j.Logger;
-
-public class Publisher
-{
- private static final Logger _log = LoggerFactory.getLogger(Publisher.class);
-
- protected InitialContextHelper _contextHelper;
-
- protected Connection _connection;
-
- protected Session _session;
-
- protected MessageProducer _producer;
-
- protected String _destinationDir;
-
- protected String _name = "Publisher";
-
- protected Destination _destination;
-
- protected static final String _defaultDestinationDir = "/tmp";
-
- /**
- * Creates a Publisher instance using properties from example.properties
- * See InitialContextHelper for details of how context etc created
- */
- public Publisher()
- {
- try
- {
- //get an initial context from default properties
- _contextHelper = new InitialContextHelper(null);
- InitialContext ctx = _contextHelper.getInitialContext();
-
- //then create a connection using the AMQConnectionFactory
- AMQConnectionFactory cf = (AMQConnectionFactory) ctx.lookup("local");
- _connection = cf.createConnection();
-
- _connection.setExceptionListener(new ExceptionListener()
- {
- public void onException(JMSException jmse)
- {
- // The connection may have broken invoke reconnect code if available.
- // The connection may have broken invoke reconnect code if available.
- System.err.println("ExceptionListener caught: " + jmse);
- //System.exit(0);
- }
- });
-
- //create a transactional session
- _session = _connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
-
- //lookup the example queue and use it
- //Queue is non-exclusive and not deleted when last consumer detaches
- _destination = (Queue) ctx.lookup("MyQueue");
-
- //create a message producer
- _producer = _session.createProducer(_destination);
-
- //set destination dir for files that have been processed
- _destinationDir = _defaultDestinationDir;
-
- _connection.start();
- }
- catch (Exception e)
- {
- e.printStackTrace();
- _log.error("Exception", e);
- }
- }
-
- /**
- * Creates and sends the number of messages specified in the param
- */
- public void sendMessage(int numMessages)
- {
- try
- {
- TextMessage txtMessage = _session.createTextMessage("msg");
- for (int i=0;i<numMessages;i++)
- {
- sendMessage(txtMessage);
- _log.info("Sent: " + i);
- }
- }
- catch (JMSException j)
- {
- _log.error("Exception in sendMessage" + j);
- }
-
-
- }
-
- /**
- * Publishes a non-persistent message using transacted session
- * Note that persistent is the default mode for send - so need to specify for transient
- */
- public boolean sendMessage(Message message)
- {
- try
- {
- //Send message via our producer which is not persistent
- _producer.send(message, DeliveryMode.PERSISTENT, _producer.getPriority(), _producer.getTimeToLive());
-
- //commit the message send and close the transaction
- _session.commit();
-
- }
- catch (JMSException e)
- {
- //Have to assume our commit failed and rollback here
- try
- {
- _session.rollback();
- _log.error("JMSException", e);
- e.printStackTrace();
- return false;
- }
- catch (JMSException j)
- {
- _log.error("Unable to rollback publish transaction ",e);
- return false;
- }
- }
-
- //_log.info(_name + " finished sending message: " + message);
- return true;
- }
-
- /**
- * Cleanup resources before exit
- */
- public void cleanup()
- {
- try
- {
- if (_connection != null)
- {
- _connection.stop();
- _connection.close();
- }
- _connection = null;
- _producer = null;
- }
- catch(Exception e)
- {
- _log.error("Error trying to cleanup publisher " + e);
- System.exit(1);
- }
- }
-
- /**
- * Exposes session
- * @return Session
- */
- public Session getSession()
- {
- return _session;
- }
-
- public String getDestinationDir()
- {
- return _destinationDir;
- }
-
- public void setDestinationDir(String destinationDir)
- {
- _destinationDir = destinationDir;
- }
-
- public String getName()
- {
- return _name;
- }
-
- public void setName(String _name) {
- this._name = _name;
- }
-}
-
diff --git a/java/client/example/src/main/java/org/apache/qpid/example/publisher/TopicPublisher.java b/java/client/example/src/main/java/org/apache/qpid/example/publisher/TopicPublisher.java
deleted file mode 100644
index 8645e41101..0000000000
--- a/java/client/example/src/main/java/org/apache/qpid/example/publisher/TopicPublisher.java
+++ /dev/null
@@ -1,59 +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.example.publisher;
-
-import org.apache.qpid.client.BasicMessageProducer;
-import org.apache.qpid.example.shared.InitialContextHelper;
-import org.slf4j.LoggerFactory;
-import org.slf4j.Logger;
-
-import javax.jms.*;
-import javax.naming.InitialContext;
-
-/**
- * Subclass of Publisher which sends messages to a topic destination defined in example.properties
- */
-public class TopicPublisher extends Publisher
-{
-
- private static final Logger _log = LoggerFactory.getLogger(Publisher.class);
-
- public TopicPublisher()
- {
- super();
-
- try
- {
- _contextHelper = new InitialContextHelper(null);
- InitialContext ctx = _contextHelper.getInitialContext();
-
- //lookup the example topic and use it
- _destination = (Topic) ctx.lookup("MyTopic");
-
- //create a message producer
- _producer = _session.createProducer(_destination);
- }
- catch (Exception e)
- {
- //argh
- _log.error("Exception trying to construct TopicPublisher" + e);
- }
-
- }
-} \ No newline at end of file
diff --git a/java/client/example/src/main/java/org/apache/qpid/example/publisher/UndeliveredMessageException.java b/java/client/example/src/main/java/org/apache/qpid/example/publisher/UndeliveredMessageException.java
deleted file mode 100644
index 245008b68a..0000000000
--- a/java/client/example/src/main/java/org/apache/qpid/example/publisher/UndeliveredMessageException.java
+++ /dev/null
@@ -1,32 +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.example.publisher;
-
-/**
- * Exception thrown by monitor when cannot send a message marked for immediate delivery
- */
-public class UndeliveredMessageException extends Exception
-{
- public UndeliveredMessageException(String msg, Throwable t)
- {
- super(msg, t);
- }
-}
diff --git a/java/client/example/src/main/java/org/apache/qpid/example/pubsub/Client.java b/java/client/example/src/main/java/org/apache/qpid/example/pubsub/Client.java
deleted file mode 100644
index e32ee0ba73..0000000000
--- a/java/client/example/src/main/java/org/apache/qpid/example/pubsub/Client.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- *
- */
-package org.apache.qpid.example.pubsub;
-
-import javax.jms.Connection;
-import javax.jms.Destination;
-import javax.jms.JMSException;
-import javax.jms.Session;
-import javax.naming.NamingException;
-
-/**
- * An abstract base class that wraps up the creation of a JMS client utilising JNDI
- */
-public abstract class Client
-{
- protected ConnectionSetup _setup;
-
- protected Connection _connection;
- protected Destination _destination;
- protected Session _session;
-
- public Client(String destination)
- {
- if (destination == null)
- {
- destination = ConnectionSetup.TOPIC_JNDI_NAME;
- }
-
- try
- {
- _setup = new ConnectionSetup();
- }
- catch (NamingException e)
- {
- //ignore
- }
-
- if (_setup != null)
- {
- try
- {
- _connection = _setup.getConnectionFactory().createConnection();
- _destination = _setup.getDestination(destination);
- }
- catch (JMSException e)
- {
- System.err.println(e.getMessage());
- }
- }
- }
-
- public abstract void start();
-
-} \ No newline at end of file
diff --git a/java/client/example/src/main/java/org/apache/qpid/example/pubsub/ConnectionSetup.java b/java/client/example/src/main/java/org/apache/qpid/example/pubsub/ConnectionSetup.java
deleted file mode 100644
index 88ee9ed2c5..0000000000
--- a/java/client/example/src/main/java/org/apache/qpid/example/pubsub/ConnectionSetup.java
+++ /dev/null
@@ -1,123 +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.example.pubsub;
-
-import javax.jms.ConnectionFactory;
-import javax.jms.Destination;
-import javax.naming.Context;
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-import java.util.Properties;
-
-/**
- * This ConnectionSetup is a wrapper around JNDI it creates a number of entries.
- *
- * It is equivalent to a PropertyFile of value:
- *
- * connectionfactory.local=amqp://guest:guest@clientid/test?brokerlist='localhost'
- * connectionfactory.vm=amqp://guest:guest@clientid/test?brokerlist='vm://:1'
- *
- * queue.queue=example.MyQueue
- * topic.topic=example.hierarical.topic
- *
- */
-public class ConnectionSetup
-{
- final static String INITIAL_CONTEXT_FACTORY = "org.apache.qpid.jndi.PropertiesFileInitialContextFactory";
-
- final static String CONNECTION_JNDI_NAME = "local";
- final static String CONNECTION_NAME = "amqp://guest:guest@clientid/test?brokerlist='localhost'";
-
- public static final String QUEUE_JNDI_NAME = "queue";
- final static String QUEUE_NAME = "example.MyQueue";
-
- public static final String TOPIC_JNDI_NAME = "topic";
- final static String TOPIC_NAME = "usa.news";
-
- private Context _ctx;
-
- public ConnectionSetup() throws NamingException
- {
-
- // Set the properties ...
- Properties properties = new Properties();
- properties.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);
- properties.put("connectionfactory." + CONNECTION_JNDI_NAME, CONNECTION_NAME);
- properties.put("connectionfactory." + "vm", "amqp://guest:guest@clientid/test?brokerlist='vm://:1'");
-
- properties.put("queue." + QUEUE_JNDI_NAME, QUEUE_NAME);
- properties.put("topic." + TOPIC_JNDI_NAME, TOPIC_NAME);
- // Create the initial context
- _ctx = new InitialContext(properties);
-
- }
-
- public ConnectionSetup(Properties properties) throws NamingException
- {
- _ctx = new InitialContext(properties);
- }
-
- public ConnectionFactory getConnectionFactory()
- {
-
- // Perform the lookups
- try
- {
- return (ConnectionFactory) _ctx.lookup(CONNECTION_JNDI_NAME);
- }
- catch (NamingException e)
- {
- //ignore
- }
- return null;
- }
-
- public Destination getDestination(String jndiName)
- {
- // Perform the lookups
- try
- {
- return (Destination) _ctx.lookup(jndiName);
- }
- catch (ClassCastException cce)
- {
- //ignore
- }
- catch (NamingException ne)
- {
- //ignore
- }
- return null;
- }
-
-
- public void close()
- {
- try
- {
- _ctx.close();
- }
- catch (NamingException e)
- {
- //ignore
- }
- }
-}
diff --git a/java/client/example/src/main/java/org/apache/qpid/example/pubsub/Publisher.java b/java/client/example/src/main/java/org/apache/qpid/example/pubsub/Publisher.java
deleted file mode 100644
index ac3829d49e..0000000000
--- a/java/client/example/src/main/java/org/apache/qpid/example/pubsub/Publisher.java
+++ /dev/null
@@ -1,81 +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.example.pubsub;
-
-import javax.jms.JMSException;
-import javax.jms.MessageProducer;
-import javax.jms.Session;
-
-/**
- * A simple Publisher example.
- *
- * The class can take two arguments.
- * java Publisher <destination> <msgCount>
- * Where:
- * destination is either 'topic' or 'queue' (Default: topic)
- * msgCount is the number of messages to send (Default : 100)
- *
- */
-public class Publisher extends Client
-{
- int _msgCount;
-
- public Publisher(String destination, int msgCount)
- {
- super(destination);
- _msgCount = msgCount;
- }
-
- public void start()
- {
- try
- {
- _session = _connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- MessageProducer _producer = _session.createProducer(_destination);
-
- for (int msgCount = 0; msgCount < _msgCount; msgCount++)
- {
- _producer.send(_session.createTextMessage("msg:" + msgCount));
- System.out.println("Sent:" + msgCount);
- }
-
- System.out.println("Done.");
- _connection.close();
- }
- catch (JMSException e)
- {
- e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
- }
- }
-
-
- public static void main(String[] args)
- {
-
- String destination = args.length > 2 ? args[1] : "usa.news";
-
- int msgCount = args.length > 2 ? Integer.parseInt(args[2]) : 100;
-
- new Publisher(destination, msgCount).start();
- }
-
-}
diff --git a/java/client/example/src/main/java/org/apache/qpid/example/pubsub/Subscriber.java b/java/client/example/src/main/java/org/apache/qpid/example/pubsub/Subscriber.java
deleted file mode 100644
index f2d736701f..0000000000
--- a/java/client/example/src/main/java/org/apache/qpid/example/pubsub/Subscriber.java
+++ /dev/null
@@ -1,98 +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.example.pubsub;
-
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageListener;
-import javax.jms.Session;
-import javax.jms.TextMessage;
-import javax.jms.Topic;
-import java.util.concurrent.CountDownLatch;
-
-
-/**
- * Simple client that listens for the specified number of msgs on the given Destinaton
- *
- * The class can take two arguments.
- * java Subscriber <destination> <msgCount>
- * Where:
- * destination is either 'topic' or 'queue' (Default: topic)
- * msgCount is the number of messages to send (Default : 100)
- */
-public class Subscriber extends Client implements MessageListener
-{
-
- CountDownLatch _count;
-
- public Subscriber(String destination, int msgCount)
- {
- super(destination);
- _count = new CountDownLatch(msgCount);
- }
-
-
- public void start()
- {
- try
- {
- _session = _connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- _session.createDurableSubscriber((Topic) _setup.getDestination(ConnectionSetup.TOPIC_JNDI_NAME),
- "exampleClient").setMessageListener(this);
- _connection.start();
- _count.await();
-
- System.out.println("Done");
-
- _connection.close();
- }
- catch (JMSException e)
- {
- e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
- }
- catch (InterruptedException e)
- {
- e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
- }
- }
-
- public static void main(String[] args)
- {
- String destination = args.length > 2 ? args[1] : null;
- int msgCount = args.length > 2 ? Integer.parseInt(args[2]) : 100;
-
- new Subscriber(destination, msgCount).start();
- }
-
- public void onMessage(Message message)
- {
- try
- {
- _count.countDown();
- System.out.println("Received msg:" + ((TextMessage) message).getText());
- }
- catch (JMSException e)
- {
- e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
- }
- }
-}
diff --git a/java/client/example/src/main/java/org/apache/qpid/example/shared/ConnectionException.java b/java/client/example/src/main/java/org/apache/qpid/example/shared/ConnectionException.java
deleted file mode 100644
index 1a3d596a24..0000000000
--- a/java/client/example/src/main/java/org/apache/qpid/example/shared/ConnectionException.java
+++ /dev/null
@@ -1,29 +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.example.shared;
-
-public class ConnectionException extends Exception
-{
- public ConnectionException(String msg, Throwable t)
- {
- super(msg, t);
- }
-}
diff --git a/java/client/example/src/main/java/org/apache/qpid/example/shared/ContextException.java b/java/client/example/src/main/java/org/apache/qpid/example/shared/ContextException.java
deleted file mode 100644
index 2987a9559b..0000000000
--- a/java/client/example/src/main/java/org/apache/qpid/example/shared/ContextException.java
+++ /dev/null
@@ -1,29 +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.example.shared;
-
-public class ContextException extends Exception
-{
- public ContextException(String msg, Throwable t)
- {
- super(msg, t);
- }
-}
diff --git a/java/client/example/src/main/java/org/apache/qpid/example/shared/FileUtils.java b/java/client/example/src/main/java/org/apache/qpid/example/shared/FileUtils.java
deleted file mode 100644
index 54446cb6a7..0000000000
--- a/java/client/example/src/main/java/org/apache/qpid/example/shared/FileUtils.java
+++ /dev/null
@@ -1,168 +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.example.shared;
-
-import java.io.*;
-
-/**
- * Class that provides file related utility methods for utility use
- */
-public class FileUtils {
-
-
- //Reads file content into String
- public static String getFileContent(String filePath) throws IOException
- {
-
- BufferedReader reader = null;
- String tempData = "";
- String eol = "\n\r";
-
- try
- {
- String line;
- reader = new BufferedReader(new FileReader(filePath));
- while ((line = reader.readLine()) != null)
- {
- if (!tempData.equals(""))
- {
- tempData = tempData + eol + line;
- }
- else
- {
- tempData = line;
- }
- }
- }
- finally
- {
- if (reader != null)
- {
- reader.close();
- }
- }
- return tempData;
- }
-
- /*
- * Reads xml from a file and returns it as an array of chars
- */
- public static char[] getFileAsCharArray(String filePath) throws IOException
- {
- BufferedReader reader = null;
- char[] tempChars = null;
- String tempData = "";
-
- try
- {
- String line;
- reader = new BufferedReader(new FileReader(filePath));
- while ((line = reader.readLine()) != null)
- {
- tempData = tempData + line;
- }
- tempChars = tempData.toCharArray();
- }
- finally
- {
- if (reader != null)
- {
- reader.close();
- }
- }
- return tempChars;
- }
-
- /*
- * Write String content to filename provided
- */
- public static void writeStringToFile(String content, String path) throws IOException
- {
-
- BufferedWriter writer = new BufferedWriter(new FileWriter(new File(path)));
- writer.write(content);
- writer.flush();
- writer.close();
- }
-
- /*
- * Allows moving of files to a new dir and preserves the last bit of the name only
- */
- public static void moveFileToNewDir(String path, String newDir) throws IOException
- {
- //get file name from current path
- //while more files in dir publish them
- File pathFile = new File(path);
- if (pathFile.isDirectory())
- {
- File[] files = pathFile.listFiles();
- for (File file : files)
- {
- moveFileToNewDir(file,newDir);
- }
- }
- }
-
- /*
- * Allows moving of a file to a new dir and preserves the last bit of the name only
- */
- public static void moveFileToNewDir(File fileToMove, String newDir) throws IOException
- {
- moveFile(fileToMove,getArchiveFileName(fileToMove,newDir));
- }
-
- /*
- * Moves file from a given path to a new path with String params
- */
- public static void moveFile(String fromPath, String dest) throws IOException
- {
- moveFile(new File(fromPath),new File(dest));
- }
-
- /*
- * Moves file from a given path to a new path with mixed params
- */
- public static void moveFile(File fileToMove, String dest) throws IOException
- {
- moveFile(fileToMove,new File(dest));
- }
-
- /*
- * Moves file from a given path to a new path with File params
- */
- public static void moveFile(File fileToMove, File dest) throws IOException
- {
- fileToMove.renameTo(dest);
- }
-
- /*
- * Deletes a given file
- */
- public static void deleteFile(String filePath) throws IOException
- {
- new File(filePath).delete();
- }
-
- private static String getArchiveFileName(File fileToMove, String archiveDir)
- {
- //get file name from current path
- String fileName = fileToMove.getName();
- return archiveDir + File.separator + fileName;
- }
-}
diff --git a/java/client/example/src/main/java/org/apache/qpid/example/shared/InitialContextHelper.java b/java/client/example/src/main/java/org/apache/qpid/example/shared/InitialContextHelper.java
deleted file mode 100644
index 16a185133a..0000000000
--- a/java/client/example/src/main/java/org/apache/qpid/example/shared/InitialContextHelper.java
+++ /dev/null
@@ -1,81 +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.example.shared;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Properties;
-
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-
-import org.slf4j.LoggerFactory;
-import org.slf4j.Logger;
-
-/**
- * Class that provides helper methods for JNDI
- */
-public class InitialContextHelper
-{
-
- public static final String _defaultPropertiesName = "example.properties";
- protected Properties _fileProperties;
- protected InitialContext _initialContext;
- protected static final Logger _log = LoggerFactory.getLogger(InitialContextHelper.class);
-
- public InitialContextHelper(String propertiesName) throws ContextException
- {
- try
- {
- if ((propertiesName == null) || (propertiesName.length() == 0))
- {
- propertiesName = _defaultPropertiesName;
- }
-
- _fileProperties = new Properties();
- ClassLoader cl = this.getClass().getClassLoader();
-
- // NB: Need to change path to reflect package if moving classes around !
- InputStream is = cl.getResourceAsStream("org/apache/qpid/example/shared/" + propertiesName);
- _fileProperties.load(is);
- _initialContext = new InitialContext(_fileProperties);
- }
- catch (IOException e)
- {
- throw new ContextException(e.toString(), e);
- }
- catch (NamingException n)
- {
- throw new ContextException(n.toString(), n);
- }
- }
-
- public Properties getFileProperties()
- {
- return _fileProperties;
- }
-
- public InitialContext getInitialContext()
- {
- return _initialContext;
- }
-
-}
diff --git a/java/client/example/src/main/java/org/apache/qpid/example/shared/Statics.java b/java/client/example/src/main/java/org/apache/qpid/example/shared/Statics.java
deleted file mode 100644
index c056f8a7da..0000000000
--- a/java/client/example/src/main/java/org/apache/qpid/example/shared/Statics.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.example.shared;
-
-/**
- * Constants used by AMS Publisher/Subscriber classes
- */
-public class Statics {
-
- public static final String TOPIC_NAME = "EXAMPLE_TOPIC";
-
- public static final String QUEUE_NAME = "EXAMPLE_QUEUE";
-
- public static final String MONITOR_QUEUE_SUFFIX = "_MONITOR";
-
- public static final String HOST_PROPERTY = "host";
-
- public static final String PORT_PROPERTY = "port";
-
- public static final String USER_PROPERTY = "user";
-
- public static final String PWD_PROPERTY = "pwd";
-
- public static final String TOPIC_PROPERTY = "topic";
-
- public static final String QUEUE_PROPERTY = "queue";
-
- public static final String VIRTUAL_PATH_PROPERTY = "virtualpath";
-
- public static final String ARCHIVE_PATH = "archivepath";
-
- public static final String CLIENT_PROPERTY = "client";
-
- public static final String FILENAME_PROPERTY = "filename";
-
- public static final String DEFAULT_USER = "guest";
-
- public static final String DEFAULT_PWD = "guest";
-
-
-}
diff --git a/java/client/example/src/main/java/org/apache/qpid/example/shared/example.properties b/java/client/example/src/main/java/org/apache/qpid/example/shared/example.properties
deleted file mode 100644
index c76acbd8b9..0000000000
--- a/java/client/example/src/main/java/org/apache/qpid/example/shared/example.properties
+++ /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.
-
-
-java.naming.factory.initial = org.apache.qpid.jndi.PropertiesFileInitialContextFactory
-
-# use the following property to configure the default connector
-#java.naming.provider.url - ignored.
-
-# register some connection factories
-# connectionfactory.[jndiname] = [ConnectionURL]
-connectionfactory.local = amqp://guest:guest@clientid/test?brokerlist='tcp://localhost:5672'
-
-# register some queues in JNDI using the form
-# queue.[jndiName] = [physicalName]
-queue.MyQueue = example.MyQueue
-
-# register some topics in JNDI using the form
-# topic.[jndiName] = [physicalName]
-topic.ibmStocks = stocks.nyse.ibm
-topic.MyTopic = example.MyTopic
-
-# Register an AMQP destination in JNDI
-# NOTE: Qpid currently only supports direct,topics and headers
-# destination.[jniName] = [BindingURL]
-destination.direct = direct://amq.direct//directQueue
diff --git a/java/client/example/src/main/java/org/apache/qpid/example/simple/reqresp/Client.java b/java/client/example/src/main/java/org/apache/qpid/example/simple/reqresp/Client.java
deleted file mode 100644
index 8a0ff88448..0000000000
--- a/java/client/example/src/main/java/org/apache/qpid/example/simple/reqresp/Client.java
+++ /dev/null
@@ -1,263 +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.example.simple.reqresp;
-
-import javax.jms.Connection;
-import javax.jms.ConnectionFactory;
-import javax.jms.Destination;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageListener;
-import javax.jms.MessageProducer;
-import javax.jms.Queue;
-import javax.jms.Session;
-import javax.jms.TextMessage;
-import javax.naming.Context;
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-import java.util.Properties;
-import java.util.concurrent.CountDownLatch;
-
-public class Client implements MessageListener
-{
- final String BROKER = "localhost";
-
- final String INITIAL_CONTEXT_FACTORY = "org.apache.qpid.jndi.PropertiesFileInitialContextFactory";
-
- final String CONNECTION_JNDI_NAME = "local";
- final String CONNECTION_NAME = "amqp://guest:guest@clientid/test?brokerlist='" + BROKER + "'";
-
- final String QUEUE_JNDI_NAME = "queue";
- final String QUEUE_NAME = "example.RequestQueue";
-
-
- private InitialContext _ctx;
-
- private CountDownLatch _shutdownHook = new CountDownLatch(1);
-
- public Client()
- {
- setupJNDI();
-
- Connection connection;
- Session session;
- Destination responseQueue;
-
- //Setup the connection. Create producer to sent message and consumer to receive the repsonse.
- MessageProducer _producer;
- try
- {
- connection = ((ConnectionFactory) lookupJNDI(CONNECTION_JNDI_NAME)).createConnection();
-
- session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- Destination requestQueue = (Queue) lookupJNDI(QUEUE_JNDI_NAME);
-
- closeJNDI();
-
- //Setup a message _producer to send message to the queue the server is consuming from
- _producer = session.createProducer(requestQueue);
-
- //Create a temporary queue that this client will listen for responses on then create a consumer
- //that consumes message from this temporary queue.
- responseQueue = session.createTemporaryQueue();
-
- MessageConsumer responseConsumer = session.createConsumer(responseQueue);
-
- //Set a listener to asynchronously deal with responses.
- responseConsumer.setMessageListener(this);
-
- // Now the connection is setup up start it.
- connection.start();
- }
- catch (JMSException e)
- {
- System.err.println("Unable to setup connection, client and producer on broker");
- return;
- }
-
- // Setup the message to send
- TextMessage txtMessage;
- try
- {
- //Now create the actual message you want to send
- txtMessage = session.createTextMessage("Request Process");
-
- //Set the reply to field to the temp queue you created above, this is the queue the server will respond to
- txtMessage.setJMSReplyTo(responseQueue);
-
- //Set a correlation ID so when you get a response you know which sent message the response is for
- //If there is never more than one outstanding message to the server then the
- //same correlation ID can be used for all the messages...if there is more than one outstanding
- //message to the server you would presumably want to associate the correlation ID with this message
-
- txtMessage.setJMSCorrelationID(txtMessage.getJMSMessageID());
- }
- catch (JMSException e)
- {
- System.err.println("Unable to create message");
- return;
-
- }
-
- try
- {
- _producer.send(txtMessage);
- }
- catch (JMSException e)
- {
- //Handle the exception appropriately
- }
-
- try
- {
- System.out.println("Sent Request Message ID :" + txtMessage.getJMSMessageID());
- }
- catch (JMSException e)
- {
- //Handle exception more appropriately.
- }
-
- //Wait for the return message to arrive
- try
- {
- _shutdownHook.await();
- }
- catch (InterruptedException e)
- {
- // Ignore this as we are quitting anyway.
- }
-
- //Close the connection
- try
- {
- connection.close();
- }
- catch (JMSException e)
- {
- System.err.println("A problem occured while shutting down the connection : " + e);
- }
- }
-
-
- /**
- * Implementation of the Message Listener interface.
- * This is where message will be asynchronously delivered.
- *
- * @param message
- */
- public void onMessage(Message message)
- {
- String messageText;
- try
- {
- if (message instanceof TextMessage)
- {
- TextMessage textMessage = (TextMessage) message;
- messageText = textMessage.getText();
- System.out.println("messageText = " + messageText);
- System.out.println("Correlation ID " + message.getJMSCorrelationID());
-
- _shutdownHook.countDown();
- }
- else
- {
- System.err.println("Unexpected message delivered");
- }
- }
- catch (JMSException e)
- {
- //Handle the exception appropriately
- }
- }
-
- /**
- * Lookup the specified name in the JNDI Context.
- *
- * @param name The string name of the object to lookup
- *
- * @return The object or null if nothing exists for specified name
- */
- private Object lookupJNDI(String name)
- {
- try
- {
- return _ctx.lookup(name);
- }
- catch (NamingException e)
- {
- System.err.println("Error looking up '" + name + "' in JNDI Context:" + e);
- }
-
- return null;
- }
-
- /**
- * Setup the JNDI context.
- *
- * In this case we are simply using a Properties object to store the pairing information.
- *
- * Further details can be found on the wiki site here:
- *
- * @see : http://cwiki.apache.org/qpid/how-to-use-jndi.html
- */
- private void setupJNDI()
- {
- // Set the properties ...
- Properties properties = new Properties();
- properties.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);
- properties.put("connectionfactory." + CONNECTION_JNDI_NAME, CONNECTION_NAME);
- properties.put("queue." + QUEUE_JNDI_NAME, QUEUE_NAME);
-
- // Create the initial context
- Context ctx = null;
- try
- {
- _ctx = new InitialContext(properties);
- }
- catch (NamingException e)
- {
- System.err.println("Error Setting up JNDI Context:" + e);
- }
- }
-
- /** Close the JNDI Context to keep everything happy. */
- private void closeJNDI()
- {
- try
- {
- _ctx.close();
- }
- catch (NamingException e)
- {
- System.err.println("Unable to close JNDI Context : " + e);
- }
- }
-
-
- public static void main(String[] args)
- {
- new Client();
- }
-}
-
diff --git a/java/client/example/src/main/java/org/apache/qpid/example/simple/reqresp/Server.java b/java/client/example/src/main/java/org/apache/qpid/example/simple/reqresp/Server.java
deleted file mode 100644
index 9c284eee97..0000000000
--- a/java/client/example/src/main/java/org/apache/qpid/example/simple/reqresp/Server.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.example.simple.reqresp;
-
-import javax.jms.Connection;
-import javax.jms.ConnectionFactory;
-import javax.jms.Destination;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageListener;
-import javax.jms.MessageProducer;
-import javax.jms.Queue;
-import javax.jms.Session;
-import javax.jms.TextMessage;
-import javax.naming.Context;
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-import java.util.Properties;
-import java.util.concurrent.CountDownLatch;
-import java.io.BufferedReader;
-import java.io.BufferedInputStream;
-import java.io.Reader;
-import java.io.InputStreamReader;
-import java.io.IOException;
-
-public class Server implements MessageListener
-{
- final String BROKER = "localhost";
-
- final String INITIAL_CONTEXT_FACTORY = "org.apache.qpid.jndi.PropertiesFileInitialContextFactory";
-
- final String CONNECTION_JNDI_NAME = "local";
- final String CONNECTION_NAME = "amqp://guest:guest@clientid/test?brokerlist='" + BROKER + "'";
-
- final String QUEUE_JNDI_NAME = "queue";
- final String QUEUE_NAME = "example.RequestQueue";
-
-
- private InitialContext _ctx;
- private Session _session;
- private MessageProducer _replyProducer;
- private CountDownLatch _shutdownHook = new CountDownLatch(1);
-
- public Server()
- {
- setupJNDI();
-
- Connection connection;
- try
- {
- connection = ((ConnectionFactory) lookupJNDI(CONNECTION_JNDI_NAME)).createConnection();
-
- _session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- Destination requestQueue = (Queue) lookupJNDI(QUEUE_JNDI_NAME);
-
- closeJNDI();
-
- //Setup a message producer to respond to messages from clients, we will get the destination
- //to send to from the JMSReplyTo header field from a Message so we MUST set the destination here to null.
- this._replyProducer = _session.createProducer(null);
-
- //Set up a consumer to consume messages off of the request queue
- MessageConsumer consumer = _session.createConsumer(requestQueue);
- consumer.setMessageListener(this);
-
- //Now start the connection
- connection.start();
- }
- catch (JMSException e)
- {
- //Handle the exception appropriately
- System.err.println("JMSException occured setting up server :" + e);
- return;
- }
-
- System.out.println("Server process started and waiting for messages.");
-
- //Wait to process an single message then quit.
- while (_shutdownHook.getCount() != 0)
- {
- try
- {
- _shutdownHook.await();
- }
- catch (InterruptedException e)
- {
- // Ignore this as we are quitting anyway.
- }
- }
-
- //Close the connection
- try
- {
- connection.close();
- }
- catch (JMSException e)
- {
- System.err.println("A problem occured while shutting down the connection : " + e);
- }
- }
-
- public void onMessage(Message message)
- {
- try
- {
- TextMessage response = this._session.createTextMessage();
-
- //Check we have the right message type.
- if (message instanceof TextMessage)
- {
- TextMessage txtMsg = (TextMessage) message;
- String messageText = txtMsg.getText();
-
- //Perform the request
- System.out.println("Received request:" + messageText + " for message :" + message.getJMSMessageID());
-
- //Set the response back to the client
- response.setText("Response to Request:" + messageText);
- }
-
- //Set the correlation ID from the received message to be the correlation id of the response message
- //this lets the client identify which message this is a response to if it has more than
- //one outstanding message to the server
- response.setJMSCorrelationID(message.getJMSMessageID());
-
- try
- {
- System.out.println("Received message press enter to send response....");
- new BufferedReader(new InputStreamReader(System.in)).readLine();
- }
- catch (IOException e)
- {
- //Error attemptying to pause
- }
-
- //Send the response to the Destination specified by the JMSReplyTo field of the received message.
- _replyProducer.send(message.getJMSReplyTo(), response);
- }
- catch (JMSException e)
- {
- //Handle the exception appropriately
- }
-
- _shutdownHook.countDown();
- }
-
- /**
- * Lookup the specified name in the JNDI Context.
- *
- * @param name The string name of the object to lookup
- *
- * @return The object or null if nothing exists for specified name
- */
- private Object lookupJNDI(String name)
- {
- try
- {
- return _ctx.lookup(name);
- }
- catch (NamingException e)
- {
- System.err.println("Error looking up '" + name + "' in JNDI Context:" + e);
- }
-
- return null;
- }
-
- /**
- * Setup the JNDI context.
- *
- * In this case we are simply using a Properties object to store the pairing information.
- *
- * Further details can be found on the wiki site here:
- *
- * @see : http://cwiki.apache.org/qpid/how-to-use-jndi.html
- */
- private void setupJNDI()
- {
- // Set the properties ...
- Properties properties = new Properties();
- properties.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);
- properties.put("connectionfactory." + CONNECTION_JNDI_NAME, CONNECTION_NAME);
- properties.put("queue." + QUEUE_JNDI_NAME, QUEUE_NAME);
-
- // Create the initial context
- Context ctx = null;
- try
- {
- _ctx = new InitialContext(properties);
- }
- catch (NamingException e)
- {
- System.err.println("Error Setting up JNDI Context:" + e);
- }
- }
-
- /** Close the JNDI Context to keep everything happy. */
- private void closeJNDI()
- {
- try
- {
- _ctx.close();
- }
- catch (NamingException e)
- {
- System.err.println("Unable to close JNDI Context : " + e);
- }
- }
-
-
- public static void main(String[] args)
- {
- new Server();
- }
-}
diff --git a/java/client/example/src/main/java/org/apache/qpid/example/subscriber/MonitoredSubscriber.java b/java/client/example/src/main/java/org/apache/qpid/example/subscriber/MonitoredSubscriber.java
deleted file mode 100644
index e4eb5ac7f5..0000000000
--- a/java/client/example/src/main/java/org/apache/qpid/example/subscriber/MonitoredSubscriber.java
+++ /dev/null
@@ -1,139 +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.example.subscriber;
-
-import org.apache.qpid.example.shared.Statics;
-import org.slf4j.LoggerFactory;
-import org.slf4j.Logger;
-
-import javax.jms.*;
-/**
- * Subclass of Subscriber which consumes a heartbeat message
- */
-
-public class MonitoredSubscriber extends Subscriber
-{
- protected String _monitorDestinationName;
-
- private static final Logger _logger = LoggerFactory.getLogger(MonitoredSubscriber.class);
-
- private MessageConsumer _monitorConsumer;
-
- public MonitoredSubscriber()
- {
- super();
- //lookup queue name and append suffix
- _monitorDestinationName = _destination.toString() + Statics.MONITOR_QUEUE_SUFFIX;
- }
-
- /**
- * MessageListener implementation for this subscriber
- */
- public static class MonitorMessageListener implements MessageListener
- {
- private String _name;
-
- public MonitorMessageListener(String name)
- {
- _name = name;
-
- }
-
- /**
- * Listens for heartbeat messages and acknowledges them
- * @param message
- */
- public void onMessage(javax.jms.Message message)
- {
- _logger.info(_name + " monitor got message '" + message + "'");
-
- try
- {
- _logger.debug("Monitor acknowledging recieved message");
-
- //Now acknowledge the message to clear it from our queue
- message.acknowledge();
- }
- catch(JMSException j)
- {
- _logger.error("Monitor caught JMSException trying to acknowledge message receipt");
- j.printStackTrace();
- }
- catch(Exception e)
- {
- _logger.error("Monitor caught unexpected exception trying to handle message");
- e.printStackTrace();
- }
- }
- }
-
- /**
- * Subscribes to Queue and attaches additional monitor listener
- */
- public void subscribeAndMonitor()
- {
- try
- {
- _connection = _connectionFactory.createConnection();
-
- //create a transactional session
- Session session = _connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
-
- //Queue is non-exclusive and not deleted when last consumer detaches
- Destination destination = session.createQueue(_monitorDestinationName);
-
- //Create a consumer with a destination of our queue which will use defaults for prefetch etc
- _monitorConsumer = session.createConsumer(destination);
-
- //give the monitor message listener a name of it's own
- _monitorConsumer.setMessageListener(new MonitoredSubscriber.MonitorMessageListener
- ("MonitorListener " + System.currentTimeMillis()));
-
- MonitoredSubscriber._logger.info("Starting monitored subscription ...");
-
- _connection.start();
-
- //and now start ordinary consumption too
- subscribe();
- }
- catch (Throwable t)
- {
- _logger.error("Fatal error: " + t);
- t.printStackTrace();
- }
- }
-
- /**
- * Stop consuming
- */
- public void stopMonitor()
- {
- try
- {
- _monitorConsumer.close();
- _monitorConsumer = null;
- stop();
- }
- catch(JMSException j)
- {
- _logger.error("JMSException trying to Subscriber.stop: " + j.getStackTrace());
- }
- }
-
-}
diff --git a/java/client/example/src/main/java/org/apache/qpid/example/subscriber/MonitoredSubscriptionWrapper.java b/java/client/example/src/main/java/org/apache/qpid/example/subscriber/MonitoredSubscriptionWrapper.java
deleted file mode 100644
index 5e78107182..0000000000
--- a/java/client/example/src/main/java/org/apache/qpid/example/subscriber/MonitoredSubscriptionWrapper.java
+++ /dev/null
@@ -1,47 +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.example.subscriber;
-
-
-/**
- * Allows you to simply start a monitored subscriber
- */
-public class MonitoredSubscriptionWrapper {
-
- private static MonitoredSubscriber _subscriber;
-
- /**
- * Create a monitored subscriber and start it
- * @param args - no params required
- */
- public static void main(String args[])
- {
- _subscriber = new MonitoredSubscriber();
-
- _subscriber.subscribe();
- }
-
- /**
- * Stop subscribing now ...
- */
- public static void stop()
- {
- _subscriber.stop();
- }
-}
diff --git a/java/client/example/src/main/java/org/apache/qpid/example/subscriber/Subscriber.java b/java/client/example/src/main/java/org/apache/qpid/example/subscriber/Subscriber.java
deleted file mode 100644
index c36668575f..0000000000
--- a/java/client/example/src/main/java/org/apache/qpid/example/subscriber/Subscriber.java
+++ /dev/null
@@ -1,182 +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.example.subscriber;
-
-import org.apache.qpid.client.AMQConnectionFactory;
-
-import javax.jms.*;
-import javax.jms.Connection;
-import javax.jms.MessageConsumer;
-import javax.jms.Session;
-import javax.naming.InitialContext;
-
-import org.apache.qpid.example.shared.InitialContextHelper;
-import org.slf4j.LoggerFactory;
-import org.slf4j.Logger;
-
-/**
- * Subscriber which consumes messages from a queue
- */
-
-public class Subscriber
-{
- private static final Logger _log = LoggerFactory.getLogger(Subscriber.class);
-
- protected Connection _connection;
-
- protected MessageConsumer _consumer;
-
- protected InitialContextHelper _contextHelper;
-
- protected AMQConnectionFactory _connectionFactory;
-
- protected Destination _destination;
-
- public Subscriber()
- {
- try
- {
- //get an initial context from default properties
- _contextHelper = new InitialContextHelper(null);
- InitialContext ctx = _contextHelper.getInitialContext();
-
- //then create a connection using the AMQConnectionFactory
- _connectionFactory = (AMQConnectionFactory) ctx.lookup("local");
-
- //lookup queue from context
- _destination = (Destination) ctx.lookup("MyQueue");
-
- }
- catch (Exception e)
- {
- e.printStackTrace();
- _log.error("Exception", e);
- }
- }
-
- /**
- * Listener class that handles messages
- */
- public static class ExampleMessageListener implements MessageListener
- {
- private String _name;
-
- public ExampleMessageListener(String name)
- {
- _name = name;
- }
-
- /**
- * Listens for message callbacks, handles and then acknowledges them
- * @param message - the message received
- */
- public void onMessage(javax.jms.Message message)
- {
- _log.info(_name + " got message '" + message + "'");
-
- try
- {
- //NB: Handle your message appropriately for your application here
- //do some stuff
-
- _log.debug("Acknowledging recieved message");
-
- //Now acknowledge the message to clear it from our queue
- message.acknowledge();
- }
- catch(JMSException j)
- {
- _log.error("JMSException trying to acknowledge message receipt");
- j.printStackTrace();
- }
- catch(Exception e)
- {
- _log.error("Unexpected exception trying to handle message");
- e.printStackTrace();
- }
- }
- }
-
- /**
- * Subscribes to example Queue and attaches listener
- */
- public void subscribe()
- {
- _log.info("Starting subscription ...");
-
- try
- {
- _connection = _connectionFactory.createConnection();
-
- //Non transactional session using client acknowledgement
- Session session = _connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
-
- //Create a consumer with a destination of our queue which will use defaults for prefetch etc
- _consumer = session.createConsumer(_destination);
-
- //give the message listener a name of it's own
- _consumer.setMessageListener(new ExampleMessageListener("MessageListener " + System.currentTimeMillis()));
-
- _connection.start();
- }
- catch (Throwable t)
- {
- _log.error("Fatal error: " + t);
- t.printStackTrace();
- }
-
- _log.info("Waiting for messages ...");
-
- //wait for messages and sleep to survive failover
- try
- {
- while(true)
- {
- Thread.sleep(Long.MAX_VALUE);
- }
- }
- catch (Exception e)
- {
- _log.warn("Exception while Subscriber sleeping",e);
- }
- }
-
- /**
- * Stop consuming and close connection
- */
- public void stop()
- {
- try
- {
- _consumer.close();
- _consumer = null;
- _connection.stop();
- _connection.close();
- }
- catch(JMSException j)
- {
- _log.error("JMSException trying to Subscriber.stop: " + j.getStackTrace());
- }
- }
-
-}
-
-
-
-
diff --git a/java/client/example/src/main/java/org/apache/qpid/example/subscriber/SubscriptionWrapper.java b/java/client/example/src/main/java/org/apache/qpid/example/subscriber/SubscriptionWrapper.java
deleted file mode 100644
index f8fbf63037..0000000000
--- a/java/client/example/src/main/java/org/apache/qpid/example/subscriber/SubscriptionWrapper.java
+++ /dev/null
@@ -1,46 +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.example.subscriber;
-
-/**
- * Allows you to simply start a subscriber
- */
-public class SubscriptionWrapper {
-
- private static Subscriber _subscriber;
-
- /**
- * Create a subscriber and start it
- * @param args
- */
- public static void main(String args[])
- {
- _subscriber = new Subscriber();
-
- _subscriber.subscribe();
- }
-
- /**
- * Stop subscribing now ...
- */
- public static void stop()
- {
- _subscriber.stop();
- }
-}
diff --git a/java/client/example/src/main/java/org/apache/qpid/example/transport/ExistingSocketConnectorDemo.java b/java/client/example/src/main/java/org/apache/qpid/example/transport/ExistingSocketConnectorDemo.java
deleted file mode 100644
index d7eb138523..0000000000
--- a/java/client/example/src/main/java/org/apache/qpid/example/transport/ExistingSocketConnectorDemo.java
+++ /dev/null
@@ -1,171 +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.example.transport;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.transport.TransportConnection;
-import org.apache.qpid.jms.ConnectionListener;
-import org.apache.qpid.url.URLSyntaxException;
-
-import javax.jms.Connection;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-import javax.jms.Session;
-import java.io.IOException;
-import java.net.InetSocketAddress;
-import java.net.Socket;
-import java.nio.channels.SocketChannel;
-import java.util.UUID;
-
-/**
- * This is a simple application that demonstrates how you can use the Qpid AMQP interfaces to use existing sockets as
- * the transport for the Client API.
- *
- * The Demo here runs twice:
- * 1. Just to show a simple publish and receive.
- * 2. To demonstrate how to use existing sockets and utilise the underlying client failover mechnaism.
- */
-public class ExistingSocketConnectorDemo implements ConnectionListener
-{
- private static boolean DEMO_FAILOVER = false;
-
- public static void main(String[] args) throws IOException, URLSyntaxException, AMQException, JMSException
- {
- System.out.println("Testing socket connection to localhost:5672.");
-
- new ExistingSocketConnectorDemo();
-
- System.out.println("Testing socket connection failover between localhost:5672 and localhost:5673.");
-
- DEMO_FAILOVER = true;
-
- new ExistingSocketConnectorDemo();
- }
-
- Connection _connection;
- MessageProducer _producer;
- Session _session;
-
- String Socket1_ID = UUID.randomUUID().toString();
- String Socket2_ID = UUID.randomUUID().toString();
-
-
-
- /** Here we can see the broker we are connecting to is set to be 'socket:///' signifying we will provide the socket. */
- public final String CONNECTION = "amqp://guest:guest@id/test?brokerlist='socket://" + Socket1_ID + ";socket://" + Socket2_ID + "'";
-
-
- public ExistingSocketConnectorDemo() throws IOException, URLSyntaxException, AMQException, JMSException
- {
-
- Socket socket = SocketChannel.open().socket();
- socket.connect(new InetSocketAddress("localhost", 5672));
-
- TransportConnection.registerOpenSocket(Socket1_ID, socket);
-
-
- _connection = new AMQConnection(CONNECTION);
-
- _session = _connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- MessageConsumer consumer = _session.createConsumer(_session.createQueue("Queue"));
-
- _producer = _session.createProducer(_session.createQueue("Queue"));
-
- _connection.start();
-
- if (!DEMO_FAILOVER)
- {
- _producer.send(_session.createTextMessage("Simple Test"));
- }
- else
- {
- // Using the Qpid interfaces we can set a listener that allows us to demonstrate failover
- ((AMQConnection) _connection).setConnectionListener(this);
-
- System.out.println("Testing failover: Please ensure second broker running on localhost:5673 and shutdown broker on 5672.");
- }
-
- //We do a blocking receive here so that we can demonstrate failover.
- Message message = consumer.receive();
-
- System.out.println("Recevied :" + message);
-
- _connection.close();
- }
-
- // ConnectionListener Interface
-
- public void bytesSent(long count)
- {
- //not used in this example
- }
- public void bytesReceived(long count)
- {
- //not used in this example
- }
-
- public boolean preFailover(boolean redirect)
- {
- /**
- * This method is called before the underlying client library starts to reconnect. This gives us the opportunity
- * to set a new socket for the failover to occur on.
- */
- try
- {
- Socket socket = SocketChannel.open().socket();
-
- socket.connect(new InetSocketAddress("localhost", 5673));
-
- // This is the new method to pass in an open socket for the connection to use.
- TransportConnection.registerOpenSocket(Socket2_ID, socket);
- }
- catch (IOException e)
- {
- e.printStackTrace();
- return false;
- }
- return true;
- }
-
- public boolean preResubscribe()
- {
- //not used in this example - but must return true to allow the resubscription of existing clients.
- return true;
- }
-
- public void failoverComplete()
- {
- // Now that failover has completed we can send a message that the receiving thread will pick up
- try
- {
- _producer.send(_session.createTextMessage("Simple Failover Test"));
- }
- catch (JMSException e)
- {
- e.printStackTrace();
- }
- }
-}
diff --git a/java/client/example/src/main/java/runSample.sh b/java/client/example/src/main/java/runSample.sh
deleted file mode 100755
index 66338556a5..0000000000
--- a/java/client/example/src/main/java/runSample.sh
+++ /dev/null
@@ -1,72 +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.
-#
-
-
-# Work out the CLASSPATH divider
-UNAME=`uname -s`
-case $UNAME in
- CYGWIN*)
- DIVIDER=";"
- ;;
- *)
- DIVIDER=":"
-;;
-esac
-
-if test "'x$QPID_HOME'" != "'x'"
-then
- QPID_HOME=$QPID_HOME
-else
- QPID_HOME="/usr/share/java/"
-fi
-echo "Using QPID_HOME: $QPID_HOME"
-
-if test "'x$QPID_SAMPLE'" != "'x'"
-then
- QPID_SAMPLE=$QPID_SAMPLE
-else
- QPID_SAMPLE=$PWD
-fi
-echo "Using QPID_SAMPLE: $QPID_SAMPLE"
-
-
-# set the CLASSPATH
-CLASSPATH=`find "$QPID_HOME" -name '*.jar' | tr '\n' "$DIVIDER"`
-
-
-# compile the samples
-javac -cp "$CLASSPATH" -sourcepath "$QPID_SAMPLE" -d . `find $QPID_SAMPLE -name '*.java'`
-
-# Add output classes to CLASSPATH
-CLASSPATH="$CLASSPATH$DIVIDER$."
-
-# Set VM parameters
-QPID_PARAM="$QPID_PARAM -Dlog4j.configuration=file://$PWD/log4j.xml"
-
-
-# Check if the user supplied a sample classname
-if test "'x$1'" = "'x'"
-then
- echo "No sample classname specified"
- exit;
-else
- java -cp $CLASSPATH $QPID_PARAM $*
-fi
diff --git a/java/client/src/main/grammar/SelectorParser.jj b/java/client/src/main/grammar/SelectorParser.jj
deleted file mode 100644
index 4bf9a968d7..0000000000
--- a/java/client/src/main/grammar/SelectorParser.jj
+++ /dev/null
@@ -1,609 +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 <http://www.activemq.org/site/home.html>
- //
-
-// ----------------------------------------------------------------------------
-// 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.filter.selector;
-
-import java.io.StringReader;
-import java.util.ArrayList;
-
-import org.apache.qpid.AMQInternalException;
-import org.apache.qpid.filter.ArithmeticExpression;
-import org.apache.qpid.filter.BooleanExpression;
-import org.apache.qpid.filter.ComparisonExpression;
-import org.apache.qpid.filter.ConstantExpression;
-import org.apache.qpid.filter.Expression;
-import org.apache.qpid.filter.LogicExpression;
-import org.apache.qpid.filter.PropertyExpression;
-import org.apache.qpid.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 AMQInternalException {
- this.ReInit(new StringReader(sql));
-
- try {
- return this.JmsSelector();
- }
- catch (Throwable e) {
- throw new AMQInternalException(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:
-{
- <LINE_COMMENT: "--" (~["\n","\r"])* ("\n"|"\r"|"\r\n") >
-}
-
-SKIP:
-{
- <BLOCK_COMMENT: "/*" (~["*"])* "*" ("*" | (~["*","/"] (~["*"])* "*"))* "/">
-}
-
-/* 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" >
-}
-
-/* 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"])* (<EXPONENT>)? // matches: 5.5 or 5. or 5.5E10 or 5.E10
- | "." (["0"-"9"])+ (<EXPONENT>)? // matches: .5 or .5E10
- | (["0"-"9"])+ <EXPONENT> // 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()
- (
- <OR> right = andExpression()
- {
- left = LogicExpression.createOR(asBooleanExpression(left), asBooleanExpression(right));
- }
- )*
- )
- {
- return left;
- }
-
-}
-
-
-Expression andExpression() :
-{
- Expression left;
- Expression right;
-}
-{
- (
- left = equalityExpression()
- (
- <AND> 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)
- <IS> <NULL>
- {
- left = ComparisonExpression.createIsNull(left);
- }
- |
- <IS> <NOT> <NULL>
- {
- 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;
- }
- <LIKE> t = stringLitteral()
- [ <ESCAPE> u = stringLitteral() ]
- {
- left = ComparisonExpression.createLike(left, t, u);
- }
- |
- LOOKAHEAD(2)
- {
- u=null;
- }
- <NOT> <LIKE> t = stringLitteral() [ <ESCAPE> u = stringLitteral() ]
- {
- left = ComparisonExpression.createNotLike(left, t, u);
- }
- |
- <BETWEEN> low = addExpression() <AND> high = addExpression()
- {
- left = ComparisonExpression.createBetween(left, low, high);
- }
- |
- LOOKAHEAD(2)
- <NOT> <BETWEEN> low = addExpression() <AND> high = addExpression()
- {
- left = ComparisonExpression.createNotBetween(left, low, high);
- }
- |
- <IN>
- "("
- t = stringLitteral()
- {
- list = new ArrayList();
- list.add( t );
- }
- (
- ","
- t = stringLitteral()
- {
- list.add( t );
- }
-
- )*
- ")"
- {
- left = ComparisonExpression.createInFilter(left, list);
- }
- |
- LOOKAHEAD(2)
- <NOT> <IN>
- "("
- 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);
- }
- |
- <NOT> left=unaryExpr()
- {
- left = UnaryExpression.createNOT( asBooleanExpression(left) );
- }
- |
- 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 = <DECIMAL_LITERAL>
- {
- left = ConstantExpression.createFromDecimal(t.image);
- }
- )
- |
- (
- t = <HEX_LITERAL>
- {
- left = ConstantExpression.createFromHex(t.image);
- }
- )
- |
- (
- t = <OCTAL_LITERAL>
- {
- left = ConstantExpression.createFromOctal(t.image);
- }
- )
- |
- (
- t = <FLOATING_POINT_LITERAL>
- {
- left = ConstantExpression.createFloat(t.image);
- }
- )
- |
- (
- <TRUE>
- {
- left = ConstantExpression.TRUE;
- }
- )
- |
- (
- <FALSE>
- {
- left = ConstantExpression.FALSE;
- }
- )
- |
- (
- <NULL>
- {
- left = ConstantExpression.NULL;
- }
- )
- )
- {
- return left;
- }
-}
-
-String stringLitteral() :
-{
- Token t;
- StringBuffer rc = new StringBuffer();
- boolean first=true;
-}
-{
- t = <STRING_LITERAL>
- {
- // 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 = <ID>
- {
- left = new PropertyExpression(t.image);
- }
- |
- t = <QUOTED_ID>
- {
- // 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/java/client/src/main/java/client.bnd b/java/client/src/main/java/client.bnd
deleted file mode 100755
index d2bc4f8d50..0000000000
--- a/java/client/src/main/java/client.bnd
+++ /dev/null
@@ -1,26 +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.
-#
-
-ver: 0.11.0
-
-Bundle-SymbolicName: qpid-client
-Bundle-Version: ${ver}
-Export-Package: *;version=${ver}
-Bundle-RequiredExecutionEnvironment: J2SE-1.5
-
diff --git a/java/client/src/main/java/client.log4j b/java/client/src/main/java/client.log4j
deleted file mode 100644
index 19cc946118..0000000000
--- a/java/client/src/main/java/client.log4j
+++ /dev/null
@@ -1,33 +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.
-#
-log4j.rootLogger=${root.logging.level}
-
-
-#log4j.logger.org.apache.qpid=${amqj.logging.level}, console
-#log4j.additivity.org.apache.qpid=false
-
-log4j.logger.org.apache.qpid=ERROR, console
-log4j.additivity.org.apache.qpid=false
-
-#log4j.logger.org.apache.qpid.client.message.AbstractBytesTypedMessage=DEBUG, console
-
-log4j.appender.console=org.apache.log4j.ConsoleAppender
-log4j.appender.console.Threshold=all
-log4j.appender.console.layout=org.apache.log4j.PatternLayout
-log4j.appender.console.layout.ConversionPattern=%t %d %p [%c{4}] %m%n
diff --git a/java/client/src/main/java/org/apache/mina/transport/socket/nio/ExistingSocketConnector.java b/java/client/src/main/java/org/apache/mina/transport/socket/nio/ExistingSocketConnector.java
deleted file mode 100644
index 98716c0c3c..0000000000
--- a/java/client/src/main/java/org/apache/mina/transport/socket/nio/ExistingSocketConnector.java
+++ /dev/null
@@ -1,478 +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.mina.transport.socket.nio;
-
-import edu.emory.mathcs.backport.java.util.concurrent.Executor;
-import org.apache.mina.common.ConnectFuture;
-import org.apache.mina.common.ExceptionMonitor;
-import org.apache.mina.common.IoConnector;
-import org.apache.mina.common.IoConnectorConfig;
-import org.apache.mina.common.IoHandler;
-import org.apache.mina.common.IoServiceConfig;
-import org.apache.mina.common.support.BaseIoConnector;
-import org.apache.mina.common.support.DefaultConnectFuture;
-import org.apache.mina.util.NamePreservingRunnable;
-import org.apache.mina.util.NewThreadExecutor;
-import org.apache.mina.util.Queue;
-
-import java.io.IOException;
-import java.net.ConnectException;
-import java.net.Socket;
-import java.net.SocketAddress;
-import java.nio.channels.SelectionKey;
-import java.nio.channels.Selector;
-import java.nio.channels.SocketChannel;
-import java.util.Iterator;
-import java.util.Set;
-
-/**
- * {@link IoConnector} for socket transport (TCP/IP).
- *
- * @author The Apache Directory Project (mina-dev@directory.apache.org)
- * @version $Rev: 627427 $, $Date: 2008-02-13 14:39:10 +0000 (Wed, 13 Feb 2008) $
- */
-public class ExistingSocketConnector extends BaseIoConnector
-{
- /** @noinspection StaticNonFinalField */
- private static volatile int nextId = 0;
-
- private final Object lock = new Object();
- private final int id = nextId++;
- private final String threadName = "SocketConnector-" + id;
- private SocketConnectorConfig defaultConfig = new SocketConnectorConfig();
- private final Queue connectQueue = new Queue();
- private final SocketIoProcessor[] ioProcessors;
- private final int processorCount;
- private final Executor executor;
-
- /** @noinspection FieldAccessedSynchronizedAndUnsynchronized */
- private Selector selector;
- private Worker worker;
- private int processorDistributor = 0;
- private int workerTimeout = 60; // 1 min.
- private Socket _openSocket = null;
-
- /** Create a connector with a single processing thread using a NewThreadExecutor */
- public ExistingSocketConnector()
- {
- this(1, new NewThreadExecutor());
- }
-
- /**
- * Create a connector with the desired number of processing threads
- *
- * @param processorCount Number of processing threads
- * @param executor Executor to use for launching threads
- */
- public ExistingSocketConnector(int processorCount, Executor executor)
- {
- if (processorCount < 1)
- {
- throw new IllegalArgumentException("Must have at least one processor");
- }
-
- this.executor = executor;
- this.processorCount = processorCount;
- ioProcessors = new SocketIoProcessor[processorCount];
-
- for (int i = 0; i < processorCount; i++)
- {
- ioProcessors[i] = new SocketIoProcessor("SocketConnectorIoProcessor-" + id + "." + i, executor);
- }
- }
-
- /**
- * How many seconds to keep the connection thread alive between connection requests
- *
- * @return Number of seconds to keep connection thread alive
- */
- public int getWorkerTimeout()
- {
- return workerTimeout;
- }
-
- /**
- * Set how many seconds the connection worker thread should remain alive once idle before terminating itself.
- *
- * @param workerTimeout Number of seconds to keep thread alive. Must be >=0
- */
- public void setWorkerTimeout(int workerTimeout)
- {
- if (workerTimeout < 0)
- {
- throw new IllegalArgumentException("Must be >= 0");
- }
- this.workerTimeout = workerTimeout;
- }
-
- public ConnectFuture connect(SocketAddress address, IoHandler handler, IoServiceConfig config)
- {
- return connect(address, null, handler, config);
- }
-
- public ConnectFuture connect(SocketAddress address, SocketAddress localAddress,
- IoHandler handler, IoServiceConfig config)
- {
- /** Changes here from the Mina OpenSocketConnector.
- * Ignoreing all address as they are not needed */
-
- if (handler == null)
- {
- throw new NullPointerException("handler");
- }
-
-
- if (config == null)
- {
- config = getDefaultConfig();
- }
-
- if (_openSocket == null)
- {
- throw new IllegalArgumentException("Specifed Socket not active");
- }
-
- boolean success = false;
-
- try
- {
- DefaultConnectFuture future = new DefaultConnectFuture();
- newSession(_openSocket, handler, config, future);
- success = true;
- return future;
- }
- catch (IOException e)
- {
- return DefaultConnectFuture.newFailedFuture(e);
- }
- finally
- {
- if (!success && _openSocket != null)
- {
- try
- {
- _openSocket.close();
- }
- catch (IOException e)
- {
- ExceptionMonitor.getInstance().exceptionCaught(e);
- }
- }
- }
- }
-
- public IoServiceConfig getDefaultConfig()
- {
- return defaultConfig;
- }
-
- /**
- * Sets the config this connector will use by default.
- *
- * @param defaultConfig the default config.
- *
- * @throws NullPointerException if the specified value is <code>null</code>.
- */
- public void setDefaultConfig(SocketConnectorConfig defaultConfig)
- {
- if (defaultConfig == null)
- {
- throw new NullPointerException("defaultConfig");
- }
- this.defaultConfig = defaultConfig;
- }
-
- private synchronized void startupWorker() throws IOException
- {
- if (worker == null)
- {
- selector = Selector.open();
- worker = new Worker();
- executor.execute(new NamePreservingRunnable(worker));
- }
- }
-
- private void registerNew()
- {
- if (connectQueue.isEmpty())
- {
- return;
- }
-
- for (; ;)
- {
- ConnectionRequest req;
- synchronized (connectQueue)
- {
- req = (ConnectionRequest) connectQueue.pop();
- }
-
- if (req == null)
- {
- break;
- }
-
- SocketChannel ch = req.channel;
- try
- {
- ch.register(selector, SelectionKey.OP_CONNECT, req);
- }
- catch (IOException e)
- {
- req.setException(e);
- }
- }
- }
-
- private void processSessions(Set keys)
- {
- Iterator it = keys.iterator();
-
- while (it.hasNext())
- {
- SelectionKey key = (SelectionKey) it.next();
-
- if (!key.isConnectable())
- {
- continue;
- }
-
- SocketChannel ch = (SocketChannel) key.channel();
- ConnectionRequest entry = (ConnectionRequest) key.attachment();
-
- boolean success = false;
- try
- {
- ch.finishConnect();
- newSession(ch, entry.handler, entry.config, entry);
- success = true;
- }
- catch (Throwable e)
- {
- entry.setException(e);
- }
- finally
- {
- key.cancel();
- if (!success)
- {
- try
- {
- ch.close();
- }
- catch (IOException e)
- {
- ExceptionMonitor.getInstance().exceptionCaught(e);
- }
- }
- }
- }
-
- keys.clear();
- }
-
- private void processTimedOutSessions(Set keys)
- {
- long currentTime = System.currentTimeMillis();
- Iterator it = keys.iterator();
-
- while (it.hasNext())
- {
- SelectionKey key = (SelectionKey) it.next();
-
- if (!key.isValid())
- {
- continue;
- }
-
- ConnectionRequest entry = (ConnectionRequest) key.attachment();
-
- if (currentTime >= entry.deadline)
- {
- entry.setException(new ConnectException());
- try
- {
- key.channel().close();
- }
- catch (IOException e)
- {
- ExceptionMonitor.getInstance().exceptionCaught(e);
- }
- finally
- {
- key.cancel();
- }
- }
- }
- }
-
- private void newSession(Socket socket, IoHandler handler, IoServiceConfig config, ConnectFuture connectFuture)
- throws IOException
- {
- SocketSessionImpl session = new SocketSessionImpl(this,
- nextProcessor(),
- getListeners(),
- config,
- socket.getChannel(),
- handler,
- socket.getRemoteSocketAddress());
-
- newSession(session, config, connectFuture);
- }
-
- private void newSession(SocketChannel ch, IoHandler handler, IoServiceConfig config, ConnectFuture connectFuture)
- throws IOException
-
- {
- SocketSessionImpl session = new SocketSessionImpl(this,
- nextProcessor(),
- getListeners(),
- config,
- ch,
- handler,
- ch.socket().getRemoteSocketAddress());
-
- newSession(session, config, connectFuture);
- }
-
- private void newSession(SocketSessionImpl session, IoServiceConfig config, ConnectFuture connectFuture)
- throws IOException
- {
- try
- {
- getFilterChainBuilder().buildFilterChain(session.getFilterChain());
- config.getFilterChainBuilder().buildFilterChain(session.getFilterChain());
- config.getThreadModel().buildFilterChain(session.getFilterChain());
- }
- catch (Throwable e)
- {
- throw (IOException) new IOException("Failed to create a session.").initCause(e);
- }
- session.getIoProcessor().addNew(session);
- connectFuture.setSession(session);
- }
-
- private SocketIoProcessor nextProcessor()
- {
- return ioProcessors[processorDistributor++ % processorCount];
- }
-
- public void setOpenSocket(Socket openSocket)
- {
- _openSocket = openSocket;
- }
-
- private class Worker implements Runnable
- {
- private long lastActive = System.currentTimeMillis();
-
- public void run()
- {
- Thread.currentThread().setName(ExistingSocketConnector.this.threadName);
-
- for (; ;)
- {
- try
- {
- int nKeys = selector.select(1000);
-
- registerNew();
-
- if (nKeys > 0)
- {
- processSessions(selector.selectedKeys());
- }
-
- processTimedOutSessions(selector.keys());
-
- if (selector.keys().isEmpty())
- {
- if (System.currentTimeMillis() - lastActive > workerTimeout * 1000L)
- {
- synchronized (lock)
- {
- if (selector.keys().isEmpty() &&
- connectQueue.isEmpty())
- {
- worker = null;
- try
- {
- selector.close();
- }
- catch (IOException e)
- {
- ExceptionMonitor.getInstance().exceptionCaught(e);
- }
- finally
- {
- selector = null;
- }
- break;
- }
- }
- }
- }
- else
- {
- lastActive = System.currentTimeMillis();
- }
- }
- catch (IOException e)
- {
- ExceptionMonitor.getInstance().exceptionCaught(e);
-
- try
- {
- Thread.sleep(1000);
- }
- catch (InterruptedException e1)
- {
- ExceptionMonitor.getInstance().exceptionCaught(e1);
- }
- }
- }
- }
- }
-
- private class ConnectionRequest extends DefaultConnectFuture
- {
- private final SocketChannel channel;
- private final long deadline;
- private final IoHandler handler;
- private final IoServiceConfig config;
-
- private ConnectionRequest(SocketChannel channel, IoHandler handler, IoServiceConfig config)
- {
- this.channel = channel;
- long timeout;
- if (config instanceof IoConnectorConfig)
- {
- timeout = ((IoConnectorConfig) config).getConnectTimeoutMillis();
- }
- else
- {
- timeout = ((IoConnectorConfig) getDefaultConfig()).getConnectTimeoutMillis();
- }
- this.deadline = System.currentTimeMillis() + timeout;
- this.handler = handler;
- this.config = config;
- }
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/AMQAnyDestination.java b/java/client/src/main/java/org/apache/qpid/client/AMQAnyDestination.java
deleted file mode 100644
index 999b22299c..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/AMQAnyDestination.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.client;
-
-import java.net.URISyntaxException;
-
-import javax.jms.JMSException;
-import javax.jms.Queue;
-import javax.jms.Topic;
-
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.messaging.Address;
-import org.apache.qpid.url.BindingURL;
-
-/**
- * In order to support JMS 1.0 the Qpid implementation maps the
- * direct exchange to JMS Queue and topic exchange to JMS Topic.
- *
- * The JMS 1.1 spec provides a javax.Destination as an abstraction
- * to represent any type of destination.
- * The abstract class AMQDestination has most of the functionality
- * to support any destination defined in AMQP 0-10 spec.
- */
-public class AMQAnyDestination extends AMQDestination implements Queue, Topic
-{
- public AMQAnyDestination(BindingURL binding)
- {
- super(binding);
- }
-
- public AMQAnyDestination(String str) throws URISyntaxException
- {
- super(str);
- }
-
- public AMQAnyDestination(Address addr) throws Exception
- {
- super(addr);
- }
-
- public AMQAnyDestination(AMQShortString exchangeName,AMQShortString exchangeClass,
- AMQShortString routingKey,boolean isExclusive,
- boolean isAutoDelete, AMQShortString queueName,
- boolean isDurable, AMQShortString[] bindingKeys)
- {
- super(exchangeName, exchangeClass, routingKey, isExclusive, isAutoDelete, queueName, isDurable, bindingKeys);
- }
-
- @Override
- public boolean isNameRequired()
- {
- return getAMQQueueName() == null;
- }
-
- public String getTopicName() throws JMSException
- {
- if (getRoutingKey() != null)
- {
- return getRoutingKey().asString();
- }
- else if (getSubject() != null)
- {
- return getSubject();
- }
- else
- {
- return null;
- }
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/AMQAuthenticationException.java b/java/client/src/main/java/org/apache/qpid/client/AMQAuthenticationException.java
deleted file mode 100644
index 6bae0166d1..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/AMQAuthenticationException.java
+++ /dev/null
@@ -1,42 +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.client;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.protocol.AMQConstant;
-
-/**
- * AMQAuthenticationException represents all failures to authenticate access to a broker.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Represent failure to authenticate the client.
- * </table>
- *
- * @todo Will this alwyas have the same status code, NOT_ALLOWED 530? Might set this up to always use that code.
- */
-public class AMQAuthenticationException extends AMQException
-{
- public AMQAuthenticationException(AMQConstant error, String msg, Throwable cause)
- {
- super(error, msg, cause);
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/AMQBrokerDetails.java b/java/client/src/main/java/org/apache/qpid/client/AMQBrokerDetails.java
deleted file mode 100644
index b31dd2bc91..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/AMQBrokerDetails.java
+++ /dev/null
@@ -1,414 +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.client;
-
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.apache.qpid.jms.BrokerDetails;
-import org.apache.qpid.jms.ConnectionURL;
-import org.apache.qpid.url.URLHelper;
-import org.apache.qpid.url.URLSyntaxException;
-
-public class AMQBrokerDetails implements BrokerDetails
-{
- private String _host;
- private int _port;
- private String _transport;
-
- private Map<String, String> _options = new HashMap<String, String>();
-
- private SSLConfiguration _sslConfiguration;
-
- public AMQBrokerDetails(){}
-
- public AMQBrokerDetails(String url) throws URLSyntaxException
- {
-
- // URL should be of format tcp://host:port?option='value',option='value'
- try
- {
- URI connection = new URI(url);
-
- String transport = connection.getScheme();
-
- // Handles some defaults to minimise changes to existing broker URLS e.g. localhost
- if (transport != null)
- {
- //todo this list of valid transports should be enumerated somewhere
- if ((!(transport.equalsIgnoreCase(BrokerDetails.VM) ||
- transport.equalsIgnoreCase(BrokerDetails.TCP) ||
- transport.equalsIgnoreCase(BrokerDetails.SOCKET))))
- {
- if (transport.equalsIgnoreCase("localhost"))
- {
- connection = new URI(DEFAULT_TRANSPORT + "://" + url);
- transport = connection.getScheme();
- }
- else
- {
- if (url.charAt(transport.length()) == ':' && url.charAt(transport.length() + 1) != '/')
- {
- //Then most likely we have a host:port value
- connection = new URI(DEFAULT_TRANSPORT + "://" + url);
- transport = connection.getScheme();
- }
- else
- {
- throw URLHelper.parseError(0, transport.length(), "Unknown transport", url);
- }
- }
- }
- else if (url.indexOf("//") == -1)
- {
- throw new URLSyntaxException(url, "Missing '//' after the transport In broker URL",transport.length()+1,1);
- }
- }
- else
- {
- //Default the transport
- connection = new URI(DEFAULT_TRANSPORT + "://" + url);
- transport = connection.getScheme();
- }
-
- if (transport == null)
- {
- throw URLHelper.parseError(-1, "Unknown transport in broker URL:'"
- + url + "' Format: " + URL_FORMAT_EXAMPLE, "");
- }
-
- setTransport(transport);
-
- String host = connection.getHost();
-
- // Fix for Java 1.5
- if (host == null)
- {
- host = "";
-
- String auth = connection.getAuthority();
- if (auth != null)
- {
- // contains both host & port myhost:5672
- if (auth.contains(":"))
- {
- host = auth.substring(0,auth.indexOf(":"));
- }
- else
- {
- host = auth;
- }
- }
-
- }
-
- setHost(host);
-
- int port = connection.getPort();
-
- if (port == -1)
- {
- // Fix for when there is port data but it is not automatically parseable by getPort().
- String auth = connection.getAuthority();
-
- if (auth != null && auth.contains(":"))
- {
- int start = auth.indexOf(":") + 1;
- int end = start;
- boolean looking = true;
- boolean found = false;
- // Throw an URL exception if the port number is not specified
- if (start == auth.length())
- {
- throw URLHelper.parseError(connection.toString().indexOf(auth) + end - 1,
- connection.toString().indexOf(auth) + end, "Port number must be specified",
- connection.toString());
- }
- //Walk the authority looking for a port value.
- while (looking)
- {
- try
- {
- end++;
- Integer.parseInt(auth.substring(start, end));
-
- if (end >= auth.length())
- {
- looking = false;
- found = true;
- }
- }
- catch (NumberFormatException nfe)
- {
- looking = false;
- }
-
- }
- if (found)
- {
- setPort(Integer.parseInt(auth.substring(start, end)));
- }
- else
- {
- throw URLHelper.parseError(connection.toString().indexOf(connection.getAuthority()) + end - 1,
- "Illegal character in port number", connection.toString());
- }
-
- }
- else
- {
- setPort(DEFAULT_PORT);
- }
- }
- else
- {
- if (!_transport.equalsIgnoreCase(SOCKET))
- {
- setPort(port);
- }
- }
-
- String queryString = connection.getQuery();
-
- URLHelper.parseOptions(_options, queryString);
-
- //Fragment is #string (not used)
- }
- catch (URISyntaxException uris)
- {
- if (uris instanceof URLSyntaxException)
- {
- throw(URLSyntaxException) uris;
- }
-
- throw URLHelper.parseError(uris.getIndex(), uris.getReason(), uris.getInput());
- }
- }
-
- public AMQBrokerDetails(String host, int port, SSLConfiguration sslConfiguration)
- {
- _host = host;
- _port = port;
- _sslConfiguration = sslConfiguration;
- }
-
- public String getHost()
- {
- return _host;
- }
-
- public void setHost(String _host)
- {
- this._host = _host;
- }
-
- public int getPort()
- {
- return _port;
- }
-
- public void setPort(int _port)
- {
- this._port = _port;
- }
-
- public String getTransport()
- {
- return _transport;
- }
-
- public void setTransport(String _transport)
- {
- this._transport = _transport;
- }
-
-
- public String getProperty(String key)
- {
- return _options.get(key);
- }
-
- public void setProperty(String key, String value)
- {
- _options.put(key, value);
- }
-
- public long getTimeout()
- {
- if (_options.containsKey(OPTIONS_CONNECT_TIMEOUT))
- {
- try
- {
- return Long.parseLong(_options.get(OPTIONS_CONNECT_TIMEOUT));
- }
- catch (NumberFormatException nfe)
- {
- //Do nothing as we will use the default below.
- }
- }
-
- return BrokerDetails.DEFAULT_CONNECT_TIMEOUT;
- }
-
- public boolean getBooleanProperty(String propName)
- {
- if (_options.containsKey(propName))
- {
- return Boolean.parseBoolean(_options.get(propName));
- }
-
- return false;
- }
-
- public void setTimeout(long timeout)
- {
- setProperty(OPTIONS_CONNECT_TIMEOUT, Long.toString(timeout));
- }
-
- public SSLConfiguration getSSLConfiguration()
- {
- return _sslConfiguration;
- }
-
- public void setSSLConfiguration(SSLConfiguration sslConfig)
- {
- _sslConfiguration = sslConfig;
- }
-
- public String toString()
- {
- StringBuffer sb = new StringBuffer();
-
- sb.append(_transport);
- sb.append("://");
-
- if (!(_transport.equalsIgnoreCase(VM)))
- {
- sb.append(_host);
- }
-
- if (!(_transport.equalsIgnoreCase(SOCKET)))
- {
- sb.append(':');
- sb.append(_port);
- }
-
- sb.append(printOptionsURL());
-
- return sb.toString();
- }
-
- public boolean equals(Object o)
- {
- if (!(o instanceof BrokerDetails))
- {
- return false;
- }
-
- BrokerDetails bd = (BrokerDetails) o;
-
- return _host.equalsIgnoreCase(bd.getHost()) &&
- (_port == bd.getPort()) &&
- _transport.equalsIgnoreCase(bd.getTransport()) &&
- compareSSLConfigurations(bd.getSSLConfiguration());
- //todo do we need to compare all the options as well?
- }
-
- @Override
- public int hashCode()
- {
- int result = _host != null ? _host.hashCode() : 0;
- result = 31 * result + _port;
- result = 31 * result + (_transport != null ? _transport.hashCode() : 0);
- return result;
- }
-
- private String printOptionsURL()
- {
- StringBuffer optionsURL = new StringBuffer();
-
- optionsURL.append('?');
-
- if (!(_options.isEmpty()))
- {
-
- for (String key : _options.keySet())
- {
- optionsURL.append(key);
-
- optionsURL.append("='");
-
- optionsURL.append(_options.get(key));
-
- optionsURL.append("'");
-
- optionsURL.append(URLHelper.DEFAULT_OPTION_SEPERATOR);
- }
- }
-
- //removeKey the extra DEFAULT_OPTION_SEPERATOR or the '?' if there are no options
- optionsURL.deleteCharAt(optionsURL.length() - 1);
-
- return optionsURL.toString();
- }
-
- // Do we need to do a more in-depth comparison?
- private boolean compareSSLConfigurations(SSLConfiguration other)
- {
- boolean retval = false;
- if (_sslConfiguration == null &&
- other == null)
- {
- retval = true;
- }
- else if (_sslConfiguration != null &&
- other != null)
- {
- retval = true;
- }
-
- return retval;
- }
-
- public static String checkTransport(String broker)
- {
- if ((!broker.contains("://")))
- {
- return "tcp://" + broker;
- }
- else
- {
- return broker;
- }
- }
-
- public Map<String, String> getProperties()
- {
- return _options;
- }
-
- public void setProperties(Map<String, String> props)
- {
- _options = props;
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/AMQConnection.java b/java/client/src/main/java/org/apache/qpid/client/AMQConnection.java
deleted file mode 100644
index ab59fee020..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/AMQConnection.java
+++ /dev/null
@@ -1,1493 +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.client;
-
-import java.io.IOException;
-import java.lang.reflect.InvocationTargetException;
-import java.net.ConnectException;
-import java.net.UnknownHostException;
-import java.nio.channels.UnresolvedAddressException;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.TimeUnit;
-
-import javax.jms.ConnectionConsumer;
-import javax.jms.ConnectionMetaData;
-import javax.jms.Destination;
-import javax.jms.ExceptionListener;
-import javax.jms.IllegalStateException;
-import javax.jms.JMSException;
-import javax.jms.Queue;
-import javax.jms.QueueConnection;
-import javax.jms.QueueSession;
-import javax.jms.ServerSessionPool;
-import javax.jms.Topic;
-import javax.jms.TopicConnection;
-import javax.jms.TopicSession;
-import javax.naming.NamingException;
-import javax.naming.Reference;
-import javax.naming.Referenceable;
-import javax.naming.StringRefAddr;
-
-import org.apache.qpid.AMQConnectionFailureException;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.AMQProtocolException;
-import org.apache.qpid.AMQUnresolvedAddressException;
-import org.apache.qpid.AMQDisconnectedException;
-import org.apache.qpid.client.failover.FailoverException;
-import org.apache.qpid.client.failover.FailoverProtectedOperation;
-import org.apache.qpid.client.protocol.AMQProtocolHandler;
-import org.apache.qpid.configuration.ClientProperties;
-import org.apache.qpid.exchange.ExchangeDefaults;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.BasicQosBody;
-import org.apache.qpid.framing.BasicQosOkBody;
-import org.apache.qpid.framing.ChannelOpenBody;
-import org.apache.qpid.framing.ChannelOpenOkBody;
-import org.apache.qpid.framing.ProtocolVersion;
-import org.apache.qpid.framing.TxSelectBody;
-import org.apache.qpid.framing.TxSelectOkBody;
-import org.apache.qpid.jms.BrokerDetails;
-import org.apache.qpid.jms.Connection;
-import org.apache.qpid.jms.ConnectionListener;
-import org.apache.qpid.jms.ConnectionURL;
-import org.apache.qpid.jms.FailoverPolicy;
-import org.apache.qpid.protocol.AMQConstant;
-import org.apache.qpid.url.URLSyntaxException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class AMQConnection extends Closeable implements Connection, QueueConnection, TopicConnection, Referenceable
-{
- private static final Logger _logger = LoggerFactory.getLogger(AMQConnection.class);
-
-
- /**
- * This is the "root" mutex that must be held when doing anything that could be impacted by failover. This must be
- * held by any child objects of this connection such as the session, producers and consumers.
- */
- private final Object _failoverMutex = new Object();
-
- private final Object _sessionCreationLock = new Object();
-
- /**
- * A channel is roughly analogous to a session. The server can negotiate the maximum number of channels per session
- * and we must prevent the client from opening too many.
- */
- private long _maximumChannelCount;
-
- /** The maximum size of frame supported by the server */
- private long _maximumFrameSize;
-
- /**
- * The protocol handler dispatches protocol events for this connection. For example, when the connection is dropped
- * the handler deals with this. It also deals with the initial dispatch of any protocol frames to their appropriate
- * handler.
- */
- protected AMQProtocolHandler _protocolHandler;
-
- /** Maps from session id (Integer) to AMQSession instance */
- private final ChannelToSessionMap _sessions = new ChannelToSessionMap();
-
- private String _clientName;
-
- /** The user name to use for authentication */
- private String _username;
-
- /** The password to use for authentication */
- private String _password;
-
- /** The virtual path to connect to on the AMQ server */
- private String _virtualHost;
-
- protected ExceptionListener _exceptionListener;
-
- private ConnectionListener _connectionListener;
-
- private ConnectionURL _connectionURL;
-
- /**
- * Whether this connection is started, i.e. whether messages are flowing to consumers. It has no meaning for message
- * publication.
- */
- protected volatile boolean _started;
-
- /** Policy dictating how to failover */
- protected FailoverPolicy _failoverPolicy;
-
- /*
- * _Connected should be refactored with a suitable wait object.
- */
- protected boolean _connected;
-
- /*
- * The connection meta data
- */
- private QpidConnectionMetaData _connectionMetaData;
-
- /** Configuration info for SSL */
- private SSLConfiguration _sslConfiguration;
-
- private AMQShortString _defaultTopicExchangeName = ExchangeDefaults.TOPIC_EXCHANGE_NAME;
- private AMQShortString _defaultQueueExchangeName = ExchangeDefaults.DIRECT_EXCHANGE_NAME;
- private AMQShortString _temporaryTopicExchangeName = ExchangeDefaults.TOPIC_EXCHANGE_NAME;
- private AMQShortString _temporaryQueueExchangeName = ExchangeDefaults.DIRECT_EXCHANGE_NAME;
-
- /** Thread Pool for executing connection level processes. Such as returning bounced messages. */
- private final ExecutorService _taskPool = Executors.newCachedThreadPool();
- private static final long DEFAULT_TIMEOUT = 1000 * 30;
-
- protected AMQConnectionDelegate _delegate;
-
- // this connection maximum number of prefetched messages
- private int _maxPrefetch;
-
- //Indicates whether persistent messages are synchronized
- private boolean _syncPersistence;
-
- //Indicates whether we need to sync on every message ack
- private boolean _syncAck;
-
- //Indicates the sync publish options (persistent|all)
- //By default it's async publish
- private String _syncPublish = "";
-
- // Indicates whether to use the old map message format or the
- // new amqp-0-10 encoded format.
- private boolean _useLegacyMapMessageFormat;
-
- /**
- * @param broker brokerdetails
- * @param username username
- * @param password password
- * @param clientName clientid
- * @param virtualHost virtualhost
- *
- * @throws AMQException
- * @throws URLSyntaxException
- */
- public AMQConnection(String broker, String username, String password, String clientName, String virtualHost)
- throws AMQException, URLSyntaxException
- {
- this(new AMQConnectionURL(
- ConnectionURL.AMQ_PROTOCOL + "://" + username + ":" + password + "@"
- + ((clientName == null) ? "" : clientName) + "/" + virtualHost + "?brokerlist='"
- + AMQBrokerDetails.checkTransport(broker) + "'"), null);
- }
-
- /**
- * @param broker brokerdetails
- * @param username username
- * @param password password
- * @param clientName clientid
- * @param virtualHost virtualhost
- *
- * @throws AMQException
- * @throws URLSyntaxException
- */
- public AMQConnection(String broker, String username, String password, String clientName, String virtualHost,
- SSLConfiguration sslConfig) throws AMQException, URLSyntaxException
- {
- this(new AMQConnectionURL(
- ConnectionURL.AMQ_PROTOCOL + "://" + username + ":" + password + "@"
- + ((clientName == null) ? "" : clientName) + "/" + virtualHost + "?brokerlist='"
- + AMQBrokerDetails.checkTransport(broker) + "'"), sslConfig);
- }
-
- public AMQConnection(String host, int port, String username, String password, String clientName, String virtualHost)
- throws AMQException, URLSyntaxException
- {
- this(host, port, false, username, password, clientName, virtualHost, null);
- }
-
- public AMQConnection(String host, int port, String username, String password, String clientName, String virtualHost,
- SSLConfiguration sslConfig) throws AMQException, URLSyntaxException
- {
- this(host, port, false, username, password, clientName, virtualHost, sslConfig);
- }
-
- public AMQConnection(String host, int port, boolean useSSL, String username, String password, String clientName,
- String virtualHost, SSLConfiguration sslConfig) throws AMQException, URLSyntaxException
- {
- this(new AMQConnectionURL(
- useSSL
- ? (ConnectionURL.AMQ_PROTOCOL + "://" + username + ":" + password + "@"
- + ((clientName == null) ? "" : clientName) + virtualHost + "?brokerlist='tcp://" + host + ":" + port
- + "'" + "," + BrokerDetails.OPTIONS_SSL + "='true'")
- : (ConnectionURL.AMQ_PROTOCOL + "://" + username + ":" + password + "@"
- + ((clientName == null) ? "" : clientName) + virtualHost + "?brokerlist='tcp://" + host + ":" + port
- + "'" + "," + BrokerDetails.OPTIONS_SSL + "='false'")), sslConfig);
- }
-
- public AMQConnection(String connection) throws AMQException, URLSyntaxException
- {
- this(new AMQConnectionURL(connection), null);
- }
-
- public AMQConnection(String connection, SSLConfiguration sslConfig) throws AMQException, URLSyntaxException
- {
- this(new AMQConnectionURL(connection), sslConfig);
- }
-
- /**
- * @todo Some horrible stuff going on here with setting exceptions to be non-null to detect if an exception
- * was thrown during the connection! Intention not clear. Use a flag anyway, not exceptions... Will fix soon.
- */
- public AMQConnection(ConnectionURL connectionURL, SSLConfiguration sslConfig) throws AMQException
- {
- // set this connection maxPrefetch
- if (connectionURL.getOption(ConnectionURL.OPTIONS_MAXPREFETCH) != null)
- {
- _maxPrefetch = Integer.parseInt(connectionURL.getOption(ConnectionURL.OPTIONS_MAXPREFETCH));
- }
- else
- {
- // use the defaul value set for all connections
- _maxPrefetch = Integer.parseInt(System.getProperties().getProperty(ClientProperties.MAX_PREFETCH_PROP_NAME,
- ClientProperties.MAX_PREFETCH_DEFAULT));
- }
-
- if (connectionURL.getOption(ConnectionURL.OPTIONS_SYNC_PERSISTENCE) != null)
- {
- _syncPersistence =
- Boolean.parseBoolean(connectionURL.getOption(ConnectionURL.OPTIONS_SYNC_PERSISTENCE));
- _logger.warn("sync_persistence is a deprecated property, " +
- "please use sync_publish={persistent|all} instead");
- }
- else
- {
- // use the defaul value set for all connections
- _syncPersistence = Boolean.getBoolean(ClientProperties.SYNC_PERSISTENT_PROP_NAME);
- if (_syncPersistence)
- {
- _logger.warn("sync_persistence is a deprecated property, " +
- "please use sync_publish={persistent|all} instead");
- }
- }
-
- if (connectionURL.getOption(ConnectionURL.OPTIONS_SYNC_ACK) != null)
- {
- _syncAck = Boolean.parseBoolean(connectionURL.getOption(ConnectionURL.OPTIONS_SYNC_ACK));
- }
- else
- {
- // use the defaul value set for all connections
- _syncAck = Boolean.getBoolean(ClientProperties.SYNC_ACK_PROP_NAME);
- }
-
- if (connectionURL.getOption(ConnectionURL.OPTIONS_SYNC_PUBLISH) != null)
- {
- _syncPublish = connectionURL.getOption(ConnectionURL.OPTIONS_SYNC_PUBLISH);
- }
- else
- {
- // use the default value set for all connections
- _syncPublish = System.getProperty((ClientProperties.SYNC_PUBLISH_PROP_NAME),_syncPublish);
- }
-
- if (connectionURL.getOption(ConnectionURL.OPTIONS_USE_LEGACY_MAP_MESSAGE_FORMAT) != null)
- {
- _useLegacyMapMessageFormat = Boolean.parseBoolean(
- connectionURL.getOption(ConnectionURL.OPTIONS_USE_LEGACY_MAP_MESSAGE_FORMAT));
- }
- else
- {
- // use the default value set for all connections
- _useLegacyMapMessageFormat = Boolean.getBoolean(ClientProperties.USE_LEGACY_MAP_MESSAGE_FORMAT);
- }
-
- String amqpVersion = System.getProperty((ClientProperties.AMQP_VERSION), "0-10");
- _logger.debug("AMQP version " + amqpVersion);
-
- _failoverPolicy = new FailoverPolicy(connectionURL, this);
- BrokerDetails brokerDetails = _failoverPolicy.getCurrentBrokerDetails();
- if (brokerDetails.getTransport().equals(BrokerDetails.VM) || "0-8".equals(amqpVersion))
- {
- _delegate = new AMQConnectionDelegate_8_0(this);
- }
- else if ("0-9".equals(amqpVersion))
- {
- _delegate = new AMQConnectionDelegate_0_9(this);
- }
- else if ("0-91".equals(amqpVersion) || "0-9-1".equals(amqpVersion))
- {
- _delegate = new AMQConnectionDelegate_9_1(this);
- }
- else
- {
- _delegate = new AMQConnectionDelegate_0_10(this);
- }
-
- if (_logger.isInfoEnabled())
- {
- _logger.info("Connection:" + connectionURL);
- }
-
- _sslConfiguration = sslConfig;
- if (connectionURL == null)
- {
- throw new IllegalArgumentException("Connection must be specified");
- }
-
- _connectionURL = connectionURL;
-
- _clientName = connectionURL.getClientName();
- _username = connectionURL.getUsername();
- _password = connectionURL.getPassword();
-
- setVirtualHost(connectionURL.getVirtualHost());
-
- if (connectionURL.getDefaultQueueExchangeName() != null)
- {
- _defaultQueueExchangeName = connectionURL.getDefaultQueueExchangeName();
- }
-
- if (connectionURL.getDefaultTopicExchangeName() != null)
- {
- _defaultTopicExchangeName = connectionURL.getDefaultTopicExchangeName();
- }
-
- if (connectionURL.getTemporaryQueueExchangeName() != null)
- {
- _temporaryQueueExchangeName = connectionURL.getTemporaryQueueExchangeName();
- }
-
- if (connectionURL.getTemporaryTopicExchangeName() != null)
- {
- _temporaryTopicExchangeName = connectionURL.getTemporaryTopicExchangeName();
- }
-
- _protocolHandler = new AMQProtocolHandler(this);
-
- _logger.info("Connecting with ProtocolHandler Version:"+_protocolHandler.getProtocolVersion());
-
- // We are not currently connected
- _connected = false;
-
- boolean retryAllowed = true;
- Exception connectionException = null;
- while (!_connected && retryAllowed && brokerDetails != null)
- {
- ProtocolVersion pe = null;
- try
- {
- pe = makeBrokerConnection(brokerDetails);
- }
- catch (Exception e)
- {
- if (_logger.isInfoEnabled())
- {
- _logger.info("Unable to connect to broker at " +
- _failoverPolicy.getCurrentBrokerDetails(),
- e);
- }
- connectionException = e;
- }
-
- if (pe != null)
- {
- // reset the delegate to the version returned by the
- // broker
- initDelegate(pe);
- }
- else if (!_connected)
- {
- retryAllowed = _failoverPolicy.failoverAllowed();
- brokerDetails = _failoverPolicy.getNextBrokerDetails();
- }
- }
-
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Are we connected:" + _connected);
- }
-
- if (!_connected)
- {
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Last attempted ProtocolHandler Version:"+_protocolHandler.getProtocolVersion());
- }
-
- String message = null;
-
- if (connectionException != null)
- {
- if (connectionException.getCause() != null)
- {
- message = connectionException.getCause().getMessage();
- }
- else
- {
- message = connectionException.getMessage();
- }
- }
-
- if ((message == null) || message.equals(""))
- {
- if (message == null)
- {
- message = "Unable to Connect";
- }
- else // can only be "" if getMessage() returned it therfore lastException != null
- {
- message = "Unable to Connect:" + connectionException.getClass();
- }
- }
-
- for (Throwable th = connectionException; th != null; th = th.getCause())
- {
- if (th instanceof UnresolvedAddressException ||
- th instanceof UnknownHostException)
- {
- throw new AMQUnresolvedAddressException
- (message,
- _failoverPolicy.getCurrentBrokerDetails().toString(),
- connectionException);
- }
- }
-
- throw new AMQConnectionFailureException(message, connectionException);
- }
-
- _logger.info("Connected with ProtocolHandler Version:"+_protocolHandler.getProtocolVersion());
-
- _sessions.setMaxChannelID(_delegate.getMaxChannelID());
- _sessions.setMinChannelID(_delegate.getMinChannelID());
-
- _connectionMetaData = new QpidConnectionMetaData(this);
- }
-
- protected boolean checkException(Throwable thrown)
- {
- Throwable cause = thrown.getCause();
-
- if (cause == null)
- {
- cause = thrown;
- }
-
- return ((cause instanceof ConnectException) || (cause instanceof UnresolvedAddressException));
- }
-
- private void initDelegate(ProtocolVersion pe) throws AMQProtocolException
- {
- try
- {
- String delegateClassName = String.format
- ("org.apache.qpid.client.AMQConnectionDelegate_%s_%s",
- pe.getMajorVersion(), pe.getMinorVersion());
- _logger.info("Looking up delegate '" + delegateClassName + "' Based on PE:" + pe);
- Class c = Class.forName(delegateClassName);
- Class partypes[] = new Class[1];
- partypes[0] = AMQConnection.class;
- _delegate = (AMQConnectionDelegate) c.getConstructor(partypes).newInstance(this);
- //Update our session to use this new protocol version
- _protocolHandler.getProtocolSession().setProtocolVersion(_delegate.getProtocolVersion());
-
- }
- catch (ClassNotFoundException e)
- {
- throw new AMQProtocolException
- (AMQConstant.UNSUPPORTED_CLIENT_PROTOCOL_ERROR,
- String.format("Protocol: %s.%s is rquired by the broker but is not " +
- "currently supported by this client library implementation",
- pe.getMajorVersion(), pe.getMinorVersion()),
- e);
- }
- catch (NoSuchMethodException e)
- {
- throw new RuntimeException("unable to locate constructor for delegate", e);
- }
- catch (InstantiationException e)
- {
- throw new RuntimeException("error instantiating delegate", e);
- }
- catch (IllegalAccessException e)
- {
- throw new RuntimeException("error accessing delegate", e);
- }
- catch (InvocationTargetException e)
- {
- throw new RuntimeException("error invoking delegate", e);
- }
- }
-
- protected AMQConnection(String username, String password, String clientName, String virtualHost)
- {
- _clientName = clientName;
- _username = username;
- _password = password;
- setVirtualHost(virtualHost);
- }
-
- private void setVirtualHost(String virtualHost)
- {
- if (virtualHost != null && virtualHost.startsWith("/"))
- {
- virtualHost = virtualHost.substring(1);
- }
-
- _virtualHost = virtualHost;
- }
-
- public boolean attemptReconnection(String host, int port)
- {
- BrokerDetails bd = new AMQBrokerDetails(host, port, _sslConfiguration);
-
- _failoverPolicy.setBroker(bd);
-
- try
- {
- makeBrokerConnection(bd);
-
- return true;
- }
- catch (Exception e)
- {
- if (_logger.isInfoEnabled())
- {
- _logger.info("Unable to connect to broker at " + bd);
- }
-
- attemptReconnection();
- }
-
- return false;
- }
-
- public boolean attemptReconnection()
- {
- BrokerDetails broker = null;
- while (_failoverPolicy.failoverAllowed() && (broker = _failoverPolicy.getNextBrokerDetails()) != null)
- {
- try
- {
- makeBrokerConnection(broker);
- return true;
- }
- catch (Exception e)
- {
- if (!(e instanceof AMQException))
- {
- if (_logger.isInfoEnabled())
- {
- _logger.info("Unable to connect to broker at " + _failoverPolicy.getCurrentBrokerDetails(), e);
- }
- }
- else
- {
- if (_logger.isInfoEnabled())
- {
- _logger.info(e.getMessage() + ":Unable to connect to broker at "
- + _failoverPolicy.getCurrentBrokerDetails());
- }
- }
- }
- }
-
- // connection unsuccessful
- return false;
- }
-
- public ProtocolVersion makeBrokerConnection(BrokerDetails brokerDetail) throws IOException, AMQException
- {
- return _delegate.makeBrokerConnection(brokerDetail);
- }
-
- public <T, E extends Exception> T executeRetrySupport(FailoverProtectedOperation<T,E> operation) throws E
- {
- return _delegate.executeRetrySupport(operation);
- }
-
- /**
- * Get the details of the currently active broker
- *
- * @return null if no broker is active (i.e. no successful connection has been made, or the BrokerDetail instance
- * otherwise
- */
- public BrokerDetails getActiveBrokerDetails()
- {
- return _failoverPolicy.getCurrentBrokerDetails();
- }
-
- public boolean failoverAllowed()
- {
- if (!_connected)
- {
- return false;
- }
- else
- {
- return _failoverPolicy.failoverAllowed();
- }
- }
-
- public org.apache.qpid.jms.Session createSession(final boolean transacted, final int acknowledgeMode) throws JMSException
- {
- return createSession(transacted, acknowledgeMode, _maxPrefetch);
- }
-
- public org.apache.qpid.jms.Session createSession(final boolean transacted, final int acknowledgeMode, final int prefetch)
- throws JMSException
- {
- return createSession(transacted, acknowledgeMode, prefetch, prefetch);
- }
-
- public org.apache.qpid.jms.Session createSession(final boolean transacted, final int acknowledgeMode,
- final int prefetchHigh, final int prefetchLow) throws JMSException
- {
- synchronized (_sessionCreationLock)
- {
- checkNotClosed();
- return _delegate.createSession(transacted, acknowledgeMode, prefetchHigh, prefetchLow);
- }
- }
-
- private void createChannelOverWire(int channelId, int prefetchHigh, int prefetchLow, boolean transacted)
- throws AMQException, FailoverException
- {
-
- ChannelOpenBody channelOpenBody = getProtocolHandler().getMethodRegistry().createChannelOpenBody(null);
-
- // TODO: Be aware of possible changes to parameter order as versions change.
-
- _protocolHandler.syncWrite(channelOpenBody.generateFrame(channelId), ChannelOpenOkBody.class);
-
- BasicQosBody basicQosBody = getProtocolHandler().getMethodRegistry().createBasicQosBody(0, prefetchHigh, false);
-
- // todo send low water mark when protocol allows.
- // todo Be aware of possible changes to parameter order as versions change.
- _protocolHandler.syncWrite(basicQosBody.generateFrame(channelId), BasicQosOkBody.class);
-
- if (transacted)
- {
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Issuing TxSelect for " + channelId);
- }
-
- TxSelectBody body = getProtocolHandler().getMethodRegistry().createTxSelectBody();
-
- // TODO: Be aware of possible changes to parameter order as versions change.
- _protocolHandler.syncWrite(body.generateFrame(channelId), TxSelectOkBody.class);
- }
- }
-
- private void reopenChannel(int channelId, int prefetchHigh, int prefetchLow, boolean transacted)
- throws AMQException, FailoverException
- {
- try
- {
- createChannelOverWire(channelId, prefetchHigh, prefetchLow, transacted);
- }
- catch (AMQException e)
- {
- deregisterSession(channelId);
- throw new AMQException(null, "Error reopening channel " + channelId + " after failover: " + e, e);
- }
- }
-
- public void setFailoverPolicy(FailoverPolicy policy)
- {
- _failoverPolicy = policy;
- }
-
- public FailoverPolicy getFailoverPolicy()
- {
- return _failoverPolicy;
- }
-
- /**
- * Returns an AMQQueueSessionAdaptor which wraps an AMQSession and throws IllegalStateExceptions where specified in
- * the JMS spec
- *
- * @param transacted
- * @param acknowledgeMode
- *
- * @return QueueSession
- *
- * @throws JMSException
- */
- public QueueSession createQueueSession(boolean transacted, int acknowledgeMode) throws JMSException
- {
- return new AMQQueueSessionAdaptor(createSession(transacted, acknowledgeMode));
- }
-
- /**
- * Returns an AMQTopicSessionAdapter which wraps an AMQSession and throws IllegalStateExceptions where specified in
- * the JMS spec
- *
- * @param transacted
- * @param acknowledgeMode
- *
- * @return TopicSession
- *
- * @throws JMSException
- */
- public TopicSession createTopicSession(boolean transacted, int acknowledgeMode) throws JMSException
- {
- return new AMQTopicSessionAdaptor(createSession(transacted, acknowledgeMode));
- }
-
- public boolean channelLimitReached()
- {
- return _sessions.size() >= _maximumChannelCount;
- }
-
- public String getClientID() throws JMSException
- {
- checkNotClosed();
-
- return _clientName;
- }
-
- public void setClientID(String clientID) throws JMSException
- {
- checkNotClosed();
- // in AMQP it is not possible to change the client ID. If one is not specified
- // upon connection construction, an id is generated automatically. Therefore
- // we can always throw an exception.
- if (!Boolean.getBoolean(ClientProperties.IGNORE_SET_CLIENTID_PROP_NAME))
- {
- throw new IllegalStateException("Client name cannot be changed after being set");
- }
- else
- {
- _logger.info("Operation setClientID is ignored using ID: " + getClientID());
- }
- }
-
- public ConnectionMetaData getMetaData() throws JMSException
- {
- checkNotClosed();
-
- return _connectionMetaData;
-
- }
-
- public ExceptionListener getExceptionListener() throws JMSException
- {
- checkNotClosed();
-
- return _exceptionListener;
- }
-
- public void setExceptionListener(ExceptionListener listener) throws JMSException
- {
- checkNotClosed();
- _exceptionListener = listener;
- }
-
- /**
- * Start the connection, i.e. start flowing messages. Note that this method must be called only from a single thread
- * and is not thread safe (which is legal according to the JMS specification).
- *
- * @throws JMSException
- */
- public void start() throws JMSException
- {
- checkNotClosed();
- if (!_started)
- {
- _started = true;
- final Iterator it = _sessions.values().iterator();
- while (it.hasNext())
- {
- final AMQSession s = (AMQSession) (it.next());
- try
- {
- s.start();
- }
- catch (AMQException e)
- {
- throw new JMSAMQException(e);
- }
- }
-
- }
- }
-
- public void stop() throws JMSException
- {
- checkNotClosed();
- if (_started)
- {
- for (Iterator i = _sessions.values().iterator(); i.hasNext();)
- {
- try
- {
- ((AMQSession) i.next()).stop();
- }
- catch (AMQException e)
- {
- throw new JMSAMQException(e);
- }
- }
-
- _started = false;
- }
- }
-
- public void close() throws JMSException
- {
- close(DEFAULT_TIMEOUT);
- }
-
- public void close(long timeout) throws JMSException
- {
- close(new ArrayList<AMQSession>(_sessions.values()), timeout);
- }
-
- public void close(List<AMQSession> sessions, long timeout) throws JMSException
- {
- if (!_closed.getAndSet(true))
- {
- _closing.set(true);
- try{
- doClose(sessions, timeout);
- }finally{
- _closing.set(false);
- }
- }
- }
-
- private void doClose(List<AMQSession> sessions, long timeout) throws JMSException
- {
- synchronized (_sessionCreationLock)
- {
- if (!sessions.isEmpty())
- {
- AMQSession session = sessions.remove(0);
- synchronized (session.getMessageDeliveryLock())
- {
- doClose(sessions, timeout);
- }
- }
- else
- {
- synchronized (getFailoverMutex())
- {
- try
- {
- long startCloseTime = System.currentTimeMillis();
-
- closeAllSessions(null, timeout, startCloseTime);
-
- //This MUST occur after we have successfully closed all Channels/Sessions
- _taskPool.shutdown();
-
- if (!_taskPool.isTerminated())
- {
- try
- {
- // adjust timeout
- long taskPoolTimeout = adjustTimeout(timeout, startCloseTime);
-
- _taskPool.awaitTermination(taskPoolTimeout, TimeUnit.MILLISECONDS);
- }
- catch (InterruptedException e)
- {
- _logger.info("Interrupted while shutting down connection thread pool.");
- }
- }
-
- // adjust timeout
- timeout = adjustTimeout(timeout, startCloseTime);
- _delegate.closeConnection(timeout);
-
- //If the taskpool hasn't shutdown by now then give it shutdownNow.
- // This will interupt any running tasks.
- if (!_taskPool.isTerminated())
- {
- List<Runnable> tasks = _taskPool.shutdownNow();
- for (Runnable r : tasks)
- {
- _logger.warn("Connection close forced taskpool to prevent execution:" + r);
- }
- }
- }
- catch (AMQException e)
- {
- _logger.error("error:", e);
- JMSException jmse = new JMSException("Error closing connection: " + e);
- jmse.setLinkedException(e);
- jmse.initCause(e);
- throw jmse;
- }
- }
- }
- }
- }
-
- private long adjustTimeout(long timeout, long startTime)
- {
- long now = System.currentTimeMillis();
- timeout -= now - startTime;
- if (timeout < 0)
- {
- timeout = 0;
- }
-
- return timeout;
- }
-
- /**
- * Marks all sessions and their children as closed without sending any protocol messages. Useful when you need to
- * mark objects "visible" in userland as closed after failover or other significant event that impacts the
- * connection. <p/> The caller must hold the failover mutex before calling this method.
- */
- private void markAllSessionsClosed()
- {
- final LinkedList sessionCopy = new LinkedList(_sessions.values());
- final Iterator it = sessionCopy.iterator();
- while (it.hasNext())
- {
- final AMQSession session = (AMQSession) it.next();
-
- session.markClosed();
- }
-
- _sessions.clear();
- }
-
- /**
- * Close all the sessions, either due to normal connection closure or due to an error occurring.
- *
- * @param cause if not null, the error that is causing this shutdown <p/> The caller must hold the failover mutex
- * before calling this method.
- */
- private void closeAllSessions(Throwable cause, long timeout, long starttime) throws JMSException
- {
- final LinkedList sessionCopy = new LinkedList(_sessions.values());
- final Iterator it = sessionCopy.iterator();
- JMSException sessionException = null;
- while (it.hasNext())
- {
- final AMQSession session = (AMQSession) it.next();
- if (cause != null)
- {
- session.closed(cause);
- }
- else
- {
- try
- {
- if (starttime != -1)
- {
- timeout = adjustTimeout(timeout, starttime);
- }
-
- session.close(timeout);
- }
- catch (JMSException e)
- {
- _logger.error("Error closing session: " + e);
- sessionException = e;
- }
- }
- }
-
- _sessions.clear();
- if (sessionException != null)
- {
- throw sessionException;
- }
- }
-
- public ConnectionConsumer createConnectionConsumer(Destination destination, String messageSelector,
- ServerSessionPool sessionPool, int maxMessages) throws JMSException
- {
- checkNotClosed();
-
- return null;
- }
-
- public ConnectionConsumer createConnectionConsumer(Queue queue, String messageSelector, ServerSessionPool sessionPool,
- int maxMessages) throws JMSException
- {
- checkNotClosed();
-
- return null;
- }
-
- public ConnectionConsumer createConnectionConsumer(Topic topic, String messageSelector, ServerSessionPool sessionPool,
- int maxMessages) throws JMSException
- {
- checkNotClosed();
-
- return null;
- }
-
- public ConnectionConsumer createDurableConnectionConsumer(Topic topic, String subscriptionName, String messageSelector,
- ServerSessionPool sessionPool, int maxMessages) throws JMSException
- {
- // TODO Auto-generated method stub
- checkNotClosed();
-
- return null;
- }
-
- public long getMaximumChannelCount() throws JMSException
- {
- checkNotClosed();
-
- return _maximumChannelCount;
- }
-
- public void setConnectionListener(ConnectionListener listener)
- {
- _connectionListener = listener;
- }
-
- public ConnectionListener getConnectionListener()
- {
- return _connectionListener;
- }
-
- public void setMaximumChannelCount(long maximumChannelCount)
- {
- _maximumChannelCount = maximumChannelCount;
- }
-
- public void setMaximumFrameSize(long frameMax)
- {
- _maximumFrameSize = frameMax;
- }
-
- public long getMaximumFrameSize()
- {
- return _maximumFrameSize;
- }
-
- public ChannelToSessionMap getSessions()
- {
- return _sessions;
- }
-
- public String getUsername()
- {
- return _username;
- }
-
- public void setUsername(String id)
- {
- _username = id;
- }
-
- public String getPassword()
- {
- return _password;
- }
-
- public String getVirtualHost()
- {
- return _virtualHost;
- }
-
- public AMQProtocolHandler getProtocolHandler()
- {
- return _protocolHandler;
- }
-
- public boolean started()
- {
- return _started;
- }
-
- public void bytesSent(long writtenBytes)
- {
- if (_connectionListener != null)
- {
- _connectionListener.bytesSent(writtenBytes);
- }
- }
-
- public void bytesReceived(long receivedBytes)
- {
- if (_connectionListener != null)
- {
- _connectionListener.bytesReceived(receivedBytes);
- }
- }
-
- /**
- * Fire the preFailover event to the registered connection listener (if any)
- *
- * @param redirect true if this is the result of a redirect request rather than a connection error
- *
- * @return true if no listener or listener does not veto change
- */
- public boolean firePreFailover(boolean redirect)
- {
- boolean proceed = true;
- if (_connectionListener != null)
- {
- proceed = _connectionListener.preFailover(redirect);
- }
-
- return proceed;
- }
-
- /**
- * Fire the preResubscribe event to the registered connection listener (if any). If the listener vetoes
- * resubscription then all the sessions are closed.
- *
- * @return true if no listener or listener does not veto resubscription.
- *
- * @throws JMSException
- */
- public boolean firePreResubscribe() throws JMSException
- {
- if (_connectionListener != null)
- {
- boolean resubscribe = _connectionListener.preResubscribe();
- if (!resubscribe)
- {
- markAllSessionsClosed();
- }
-
- return resubscribe;
- }
- else
- {
- return true;
- }
- }
-
- /** Fires a failover complete event to the registered connection listener (if any). */
- public void fireFailoverComplete()
- {
- if (_connectionListener != null)
- {
- _connectionListener.failoverComplete();
- }
- }
-
- /**
- * In order to protect the consistency of the connection and its child sessions, consumers and producers, the
- * "failover mutex" must be held when doing any operations that could be corrupted during failover.
- *
- * @return a mutex. Guaranteed never to change for the lifetime of this connection even if failover occurs.
- */
- public final Object getFailoverMutex()
- {
- return _failoverMutex;
- }
-
- public void failoverPrep()
- {
- _delegate.failoverPrep();
- }
-
- public void resubscribeSessions() throws JMSException, AMQException, FailoverException
- {
- _delegate.resubscribeSessions();
- }
-
- /**
- * If failover is taking place this will block until it has completed. If failover is not taking place it will
- * return immediately.
- *
- * @throws InterruptedException
- */
- public void blockUntilNotFailingOver() throws InterruptedException
- {
- _protocolHandler.blockUntilNotFailingOver();
- }
-
- /**
- * Invoked by the AMQProtocolSession when a protocol session exception has occurred. This method sends the exception
- * to a JMS exception listener, if configured, and propagates the exception to sessions, which in turn will
- * propagate to consumers. This allows synchronous consumers to have exceptions thrown to them.
- *
- * @param cause the exception
- */
- public void exceptionReceived(Throwable cause)
- {
-
- if (_logger.isDebugEnabled())
- {
- _logger.debug("exceptionReceived done by:" + Thread.currentThread().getName(), cause);
- }
-
- final JMSException je;
- if (cause instanceof JMSException)
- {
- je = (JMSException) cause;
- }
- else
- {
- AMQConstant code = null;
-
- if (cause instanceof AMQException)
- {
- code = ((AMQException) cause).getErrorCode();
- }
-
- if (code != null)
- {
- je = new JMSException(Integer.toString(code.getCode()), "Exception thrown against " + toString() + ": " + cause);
- }
- else
- {
- //Should never get here as all AMQEs are required to have an ErrorCode!
- // Other than AMQDisconnectedEx!
-
- if (cause instanceof AMQDisconnectedException)
- {
- Exception last = _protocolHandler.getStateManager().getLastException();
- if (last != null)
- {
- _logger.info("StateManager had an exception for us to use a cause of our Disconnected Exception");
- cause = last;
- }
- }
- je = new JMSException("Exception thrown against " + toString() + ": " + cause);
- }
-
- if (cause instanceof Exception)
- {
- je.setLinkedException((Exception) cause);
- }
-
- je.initCause(cause);
- }
-
- boolean closer = false;
-
- // in the case of an IOException, MINA has closed the protocol session so we set _closed to true
- // so that any generic client code that tries to close the connection will not mess up this error
- // handling sequence
- if (cause instanceof IOException || cause instanceof AMQDisconnectedException)
- {
- // If we have an IOE/AMQDisconnect there is no connection to close on.
- _closing.set(false);
- closer = !_closed.getAndSet(true);
-
- _protocolHandler.getProtocolSession().notifyError(je);
- }
-
- // get the failover mutex before trying to close
- synchronized (getFailoverMutex())
- {
- // decide if we are going to close the session
- if (hardError(cause))
- {
- closer = (!_closed.getAndSet(true)) || closer;
- {
- _logger.info("Closing AMQConnection due to :" + cause);
- }
- }
- else
- {
- _logger.info("Not a hard-error connection not closing: " + cause);
- }
-
- // deliver the exception if there is a listener
- if (_exceptionListener != null)
- {
- _exceptionListener.onException(je);
- }
- else
- {
- _logger.error("Throwable Received but no listener set: " + cause);
- }
-
- // if we are closing the connection, close sessions first
- if (closer)
- {
- try
- {
- closeAllSessions(cause, -1, -1); // FIXME: when doing this end up with RejectedExecutionException from executor.
- }
- catch (JMSException e)
- {
- _logger.error("Error closing all sessions: " + e, e);
- }
- }
- }
- }
-
- private boolean hardError(Throwable cause)
- {
- if (cause instanceof AMQException)
- {
- return ((AMQException) cause).isHardError();
- }
-
- return true;
- }
-
- void registerSession(int channelId, AMQSession session)
- {
- _sessions.put(channelId, session);
- }
-
- public void deregisterSession(int channelId)
- {
- _sessions.remove(channelId);
- }
-
- public String toString()
- {
- StringBuffer buf = new StringBuffer("AMQConnection:\n");
- if (_failoverPolicy.getCurrentBrokerDetails() == null)
- {
- buf.append("No active broker connection");
- }
- else
- {
- BrokerDetails bd = _failoverPolicy.getCurrentBrokerDetails();
- buf.append("Host: ").append(String.valueOf(bd.getHost()));
- buf.append("\nPort: ").append(String.valueOf(bd.getPort()));
- }
-
- buf.append("\nVirtual Host: ").append(String.valueOf(_virtualHost));
- buf.append("\nClient ID: ").append(String.valueOf(_clientName));
- buf.append("\nActive session count: ").append((_sessions == null) ? 0 : _sessions.size());
-
- return buf.toString();
- }
-
- public String toURL()
- {
- return _connectionURL.toString();
- }
-
- public Reference getReference() throws NamingException
- {
- return new Reference(AMQConnection.class.getName(), new StringRefAddr(AMQConnection.class.getName(), toURL()),
- AMQConnectionFactory.class.getName(), null); // factory location
- }
-
- public SSLConfiguration getSSLConfiguration()
- {
- return _sslConfiguration;
- }
-
- public AMQShortString getDefaultTopicExchangeName()
- {
- return _defaultTopicExchangeName;
- }
-
- public void setDefaultTopicExchangeName(AMQShortString defaultTopicExchangeName)
- {
- _defaultTopicExchangeName = defaultTopicExchangeName;
- }
-
- public AMQShortString getDefaultQueueExchangeName()
- {
- return _defaultQueueExchangeName;
- }
-
- public void setDefaultQueueExchangeName(AMQShortString defaultQueueExchangeName)
- {
- _defaultQueueExchangeName = defaultQueueExchangeName;
- }
-
- public AMQShortString getTemporaryTopicExchangeName()
- {
- return _temporaryTopicExchangeName;
- }
-
- public AMQShortString getTemporaryQueueExchangeName()
- {
- return _temporaryQueueExchangeName; // To change body of created methods use File | Settings | File Templates.
- }
-
- public void setTemporaryTopicExchangeName(AMQShortString temporaryTopicExchangeName)
- {
- _temporaryTopicExchangeName = temporaryTopicExchangeName;
- }
-
- public void setTemporaryQueueExchangeName(AMQShortString temporaryQueueExchangeName)
- {
- _temporaryQueueExchangeName = temporaryQueueExchangeName;
- }
-
- public void performConnectionTask(Runnable task)
- {
- _taskPool.execute(task);
- }
-
- public AMQSession getSession(int channelId)
- {
- return _sessions.get(channelId);
- }
-
- public ProtocolVersion getProtocolVersion()
- {
- return _delegate.getProtocolVersion();
- }
-
- public boolean isFailingOver()
- {
- return (_protocolHandler.getFailoverLatch() != null);
- }
-
- /**
- * Get the maximum number of messages that this connection can pre-fetch.
- *
- * @return The maximum number of messages that this connection can pre-fetch.
- */
- public long getMaxPrefetch()
- {
- return _maxPrefetch;
- }
-
- /**
- * Indicates whether persistent messages are synchronized
- *
- * @return true if persistent messages are synchronized false otherwise
- */
- public boolean getSyncPersistence()
- {
- return _syncPersistence;
- }
-
- /**
- * Indicates whether we need to sync on every message ack
- */
- public boolean getSyncAck()
- {
- return _syncAck;
- }
-
- public String getSyncPublish()
- {
- return _syncPublish;
- }
-
- public int getNextChannelID()
- {
- return _sessions.getNextChannelId();
- }
-
- public boolean isUseLegacyMapMessageFormat()
- {
- return _useLegacyMapMessageFormat;
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/AMQConnectionDelegate.java b/java/client/src/main/java/org/apache/qpid/client/AMQConnectionDelegate.java
deleted file mode 100644
index 9560bd5c7c..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/AMQConnectionDelegate.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.
- *
- */
-package org.apache.qpid.client;
-
-import java.io.IOException;
-
-import javax.jms.JMSException;
-import javax.jms.XASession;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.failover.FailoverException;
-import org.apache.qpid.client.failover.FailoverProtectedOperation;
-import org.apache.qpid.framing.ProtocolVersion;
-import org.apache.qpid.jms.BrokerDetails;
-import org.apache.qpid.jms.Session;
-
-public interface AMQConnectionDelegate
-{
- ProtocolVersion makeBrokerConnection(BrokerDetails brokerDetail) throws IOException, AMQException;
-
- Session createSession(final boolean transacted, final int acknowledgeMode,
- final int prefetchHigh, final int prefetchLow) throws JMSException;
-
- /**
- * Create an XASession with default prefetch values of:
- * High = MaxPrefetch
- * Low = MaxPrefetch / 2
- * @return XASession
- * @throws JMSException thrown if there is a problem creating the session.
- */
- XASession createXASession() throws JMSException;
-
- XASession createXASession(int prefetchHigh, int prefetchLow) throws JMSException;
-
- void failoverPrep();
-
- void resubscribeSessions() throws JMSException, AMQException, FailoverException;
-
- void closeConnection(long timeout) throws JMSException, AMQException;
-
- <T, E extends Exception> T executeRetrySupport(FailoverProtectedOperation<T,E> operation) throws E;
-
- int getMaxChannelID();
-
- int getMinChannelID();
-
- ProtocolVersion getProtocolVersion();
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/AMQConnectionDelegate_0_10.java b/java/client/src/main/java/org/apache/qpid/client/AMQConnectionDelegate_0_10.java
deleted file mode 100644
index d50c9e16fe..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/AMQConnectionDelegate_0_10.java
+++ /dev/null
@@ -1,460 +0,0 @@
-package org.apache.qpid.client;
-/*
- *
- * 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 java.io.IOException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.CountDownLatch;
-
-import javax.jms.ExceptionListener;
-import javax.jms.JMSException;
-import javax.jms.XASession;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.failover.FailoverException;
-import org.apache.qpid.client.failover.FailoverProtectedOperation;
-import org.apache.qpid.configuration.ClientProperties;
-import org.apache.qpid.framing.ProtocolVersion;
-import org.apache.qpid.jms.BrokerDetails;
-import org.apache.qpid.jms.ChannelLimitReachedException;
-import org.apache.qpid.jms.Session;
-import org.apache.qpid.protocol.AMQConstant;
-import org.apache.qpid.transport.Connection;
-import org.apache.qpid.transport.ConnectionClose;
-import org.apache.qpid.transport.ConnectionException;
-import org.apache.qpid.transport.ConnectionListener;
-import org.apache.qpid.transport.ConnectionSettings;
-import org.apache.qpid.transport.ProtocolVersionException;
-import org.apache.qpid.transport.TransportException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class AMQConnectionDelegate_0_10 implements AMQConnectionDelegate, ConnectionListener
-{
- /**
- * This class logger.
- */
- private static final Logger _logger = LoggerFactory.getLogger(AMQConnectionDelegate_0_10.class);
-
- /**
- * The AMQ Connection.
- */
- private AMQConnection _conn;
-
- /**
- * The QpidConeection instance that is mapped with thie JMS connection.
- */
- org.apache.qpid.transport.Connection _qpidConnection;
- private ConnectionException exception = null;
-
- static
- {
- // Register any configured SASL client factories.
- org.apache.qpid.client.security.DynamicSaslRegistrar.registerSaslProviders();
- }
-
- //--- constructor
- public AMQConnectionDelegate_0_10(AMQConnection conn)
- {
- _conn = conn;
- _qpidConnection = new Connection();
- _qpidConnection.addConnectionListener(this);
- }
-
- /**
- * create a Session and start it if required.
- */
- public Session createSession(boolean transacted, int acknowledgeMode, int prefetchHigh, int prefetchLow)
- throws JMSException
- {
- _conn.checkNotClosed();
-
- if (_conn.channelLimitReached())
- {
- throw new ChannelLimitReachedException(_conn.getMaximumChannelCount());
- }
-
- int channelId = _conn.getNextChannelID();
- AMQSession session;
- try
- {
- session = new AMQSession_0_10(_qpidConnection, _conn, channelId, transacted, acknowledgeMode, prefetchHigh,
- prefetchLow);
- _conn.registerSession(channelId, session);
- if (_conn._started)
- {
- session.start();
- }
- }
- catch (Exception e)
- {
- _logger.error("exception creating session:", e);
- throw new JMSAMQException("cannot create session", e);
- }
- return session;
- }
-
- /**
- * Create an XASession with default prefetch values of:
- * High = MaxPrefetch
- * Low = MaxPrefetch / 2
- * @return XASession
- * @throws JMSException
- */
- public XASession createXASession() throws JMSException
- {
- return createXASession((int) _conn.getMaxPrefetch(), (int) _conn.getMaxPrefetch() / 2);
- }
-
- /**
- * create an XA Session and start it if required.
- */
- public XASession createXASession(int prefetchHigh, int prefetchLow) throws JMSException
- {
- _conn.checkNotClosed();
-
- if (_conn.channelLimitReached())
- {
- throw new ChannelLimitReachedException(_conn.getMaximumChannelCount());
- }
-
- int channelId = _conn.getNextChannelID();
- XASessionImpl session;
- try
- {
- session = new XASessionImpl(_qpidConnection, _conn, channelId, prefetchHigh, prefetchLow);
- _conn.registerSession(channelId, session);
- if (_conn._started)
- {
- session.start();
- }
- }
- catch (Exception e)
- {
- throw new JMSAMQException("cannot create session", e);
- }
- return session;
- }
-
-
- /**
- * Make a connection with the broker
- *
- * @param brokerDetail The detail of the broker to connect to.
- * @throws IOException
- * @throws AMQException
- */
- public ProtocolVersion makeBrokerConnection(BrokerDetails brokerDetail) throws IOException, AMQException
- {
- try
- {
- if (_logger.isDebugEnabled())
- {
- _logger.debug("connecting to host: " + brokerDetail.getHost()
- + " port: " + brokerDetail.getPort() + " vhost: "
- + _conn.getVirtualHost() + " username: "
- + _conn.getUsername() + " password: "
- + _conn.getPassword());
- }
-
- ConnectionSettings conSettings = new ConnectionSettings();
- retriveConnectionSettings(conSettings,brokerDetail);
- _qpidConnection.connect(conSettings);
-
- _conn._connected = true;
- _conn.setUsername(_qpidConnection.getUserID());
- _conn.setMaximumChannelCount(_qpidConnection.getChannelMax());
- _conn._failoverPolicy.attainedConnection();
- }
- catch (ProtocolVersionException pe)
- {
- return new ProtocolVersion(pe.getMajor(), pe.getMinor());
- }
- catch (ConnectionException ce)
- {
- AMQConstant code = AMQConstant.REPLY_SUCCESS;
- if (ce.getClose() != null && ce.getClose().getReplyCode() != null)
- {
- code = AMQConstant.getConstant(ce.getClose().getReplyCode().getValue());
- }
- String msg = "Cannot connect to broker: " + ce.getMessage();
- throw new AMQException(code, msg, ce);
- }
-
- return null;
- }
-
- public void failoverPrep()
- {
- List<AMQSession> sessions = new ArrayList<AMQSession>(_conn.getSessions().values());
- for (AMQSession s : sessions)
- {
- s.failoverPrep();
- }
- }
-
- public void resubscribeSessions() throws JMSException, AMQException, FailoverException
- {
- _logger.info("Resuming connection");
- getQpidConnection().resume();
- List<AMQSession> sessions = new ArrayList<AMQSession>(_conn.getSessions().values());
- _logger.info(String.format("Resubscribing sessions = %s sessions.size=%d", sessions, sessions.size()));
- for (AMQSession s : sessions)
- {
- s.resubscribe();
- }
- }
-
- public void closeConnection(long timeout) throws JMSException, AMQException
- {
- try
- {
- _qpidConnection.close();
- }
- catch (TransportException e)
- {
- throw new AMQException(e.getMessage(), e);
- }
- }
-
- public void opened(Connection conn) {}
-
- public void exception(Connection conn, ConnectionException exc)
- {
- if (exception != null)
- {
- _logger.error("previous exception", exception);
- }
-
- exception = exc;
- }
-
- public void closed(Connection conn)
- {
- ConnectionException exc = exception;
- exception = null;
-
- if (exc == null)
- {
- return;
- }
-
- ConnectionClose close = exc.getClose();
- if (close == null)
- {
- _conn.getProtocolHandler().setFailoverLatch(new CountDownLatch(1));
-
- try
- {
- if (_conn.firePreFailover(false) && _conn.attemptReconnection())
- {
- _conn.failoverPrep();
- _conn.resubscribeSessions();
- _conn.fireFailoverComplete();
- return;
- }
- }
- catch (Exception e)
- {
- _logger.error("error during failover", e);
- }
- finally
- {
- _conn.getProtocolHandler().getFailoverLatch().countDown();
- _conn.getProtocolHandler().setFailoverLatch(null);
- }
- }
-
- ExceptionListener listener = _conn._exceptionListener;
- if (listener == null)
- {
- _logger.error("connection exception: " + conn, exc);
- }
- else
- {
- String code = null;
- if (close != null)
- {
- code = close.getReplyCode().toString();
- }
-
- JMSException ex = new JMSException(exc.getMessage(), code);
- ex.setLinkedException(exc);
- ex.initCause(exc);
- listener.onException(ex);
- }
- }
-
- public <T, E extends Exception> T executeRetrySupport(FailoverProtectedOperation<T,E> operation) throws E
- {
- try
- {
- return operation.execute();
- }
- catch (FailoverException e)
- {
- throw new RuntimeException(e);
- }
- }
-
- public int getMaxChannelID()
- {
- //For a negotiated channelMax N, there are channels 0 to N-1 available.
- return _qpidConnection.getChannelMax() - 1;
- }
-
- public int getMinChannelID()
- {
- return Connection.MIN_USABLE_CHANNEL_NUM;
- }
-
- public ProtocolVersion getProtocolVersion()
- {
- return ProtocolVersion.v0_10;
- }
-
- private void retriveConnectionSettings(ConnectionSettings conSettings, BrokerDetails brokerDetail)
- {
-
- conSettings.setHost(brokerDetail.getHost());
- conSettings.setPort(brokerDetail.getPort());
- conSettings.setVhost(_conn.getVirtualHost());
- conSettings.setUsername(_conn.getUsername());
- conSettings.setPassword(_conn.getPassword());
-
- // ------------ sasl options ---------------
- if (brokerDetail.getProperty(BrokerDetails.OPTIONS_SASL_MECHS) != null)
- {
- conSettings.setSaslMechs(
- brokerDetail.getProperty(BrokerDetails.OPTIONS_SASL_MECHS));
- }
-
- // Sun SASL Kerberos client uses the
- // protocol + servername as the service key.
-
- if (brokerDetail.getProperty(BrokerDetails.OPTIONS_SASL_PROTOCOL_NAME) != null)
- {
- conSettings.setSaslProtocol(
- brokerDetail.getProperty(BrokerDetails.OPTIONS_SASL_PROTOCOL_NAME));
- }
-
-
- if (brokerDetail.getProperty(BrokerDetails.OPTIONS_SASL_SERVER_NAME) != null)
- {
- conSettings.setSaslServerName(
- brokerDetail.getProperty(BrokerDetails.OPTIONS_SASL_SERVER_NAME));
- }
-
- conSettings.setUseSASLEncryption(
- brokerDetail.getBooleanProperty(BrokerDetails.OPTIONS_SASL_ENCRYPTION));
-
- // ------------- ssl options ---------------------
- conSettings.setUseSSL(brokerDetail.getBooleanProperty(BrokerDetails.OPTIONS_SSL));
-
- if (brokerDetail.getProperty(BrokerDetails.OPTIONS_TRUST_STORE) != null)
- {
- conSettings.setTrustStorePath(
- brokerDetail.getProperty(BrokerDetails.OPTIONS_TRUST_STORE));
- }
-
- if (brokerDetail.getProperty(BrokerDetails.OPTIONS_TRUST_STORE_PASSWORD) != null)
- {
- conSettings.setTrustStorePassword(
- brokerDetail.getProperty(BrokerDetails.OPTIONS_TRUST_STORE_PASSWORD));
- }
-
- if (brokerDetail.getProperty(BrokerDetails.OPTIONS_KEY_STORE) != null)
- {
- conSettings.setKeyStorePath(
- brokerDetail.getProperty(BrokerDetails.OPTIONS_KEY_STORE));
- }
-
- if (brokerDetail.getProperty(BrokerDetails.OPTIONS_KEY_STORE_PASSWORD) != null)
- {
- conSettings.setKeyStorePassword(
- brokerDetail.getProperty(BrokerDetails.OPTIONS_KEY_STORE_PASSWORD));
- }
-
- if (brokerDetail.getProperty(BrokerDetails.OPTIONS_SSL_CERT_ALIAS) != null)
- {
- conSettings.setCertAlias(
- brokerDetail.getProperty(BrokerDetails.OPTIONS_SSL_CERT_ALIAS));
- }
- // ----------------------------
-
- conSettings.setVerifyHostname(brokerDetail.getBooleanProperty(BrokerDetails.OPTIONS_SSL_VERIFY_HOSTNAME));
-
- // Pass client name from connection URL
- Map<String, Object> clientProps = new HashMap<String, Object>();
- try
- {
- clientProps.put("clientName", _conn.getClientID());
- conSettings.setClientProperties(clientProps);
- }
- catch (JMSException e)
- {
- // Ignore
- }
-
- if (brokerDetail.getProperty(BrokerDetails.OPTIONS_TCP_NO_DELAY) != null)
- {
- conSettings.setTcpNodelay(
- brokerDetail.getBooleanProperty(BrokerDetails.OPTIONS_TCP_NO_DELAY));
- }
-
- conSettings.setHeartbeatInterval(getHeartbeatInterval(brokerDetail));
- }
-
- // The idle_timeout prop is in milisecs while
- // the new heartbeat prop is in secs
- private int getHeartbeatInterval(BrokerDetails brokerDetail)
- {
- int heartbeat = 0;
- if (brokerDetail.getProperty(BrokerDetails.OPTIONS_IDLE_TIMEOUT) != null)
- {
- _logger.warn("Broker property idle_timeout=<mili_secs> is deprecated, please use heartbeat=<secs>");
- heartbeat = Integer.parseInt(brokerDetail.getProperty(BrokerDetails.OPTIONS_IDLE_TIMEOUT))/1000;
- }
- else if (brokerDetail.getProperty(BrokerDetails.OPTIONS_HEARTBEAT) != null)
- {
- heartbeat = Integer.parseInt(brokerDetail.getProperty(BrokerDetails.OPTIONS_HEARTBEAT));
- }
- else if (Integer.getInteger(ClientProperties.IDLE_TIMEOUT_PROP_NAME) != null)
- {
- heartbeat = Integer.getInteger(ClientProperties.IDLE_TIMEOUT_PROP_NAME)/1000;
- _logger.warn("JVM arg -Didle_timeout=<mili_secs> is deprecated, please use -Dqpid.heartbeat=<secs>");
- }
- else
- {
- heartbeat = Integer.getInteger(ClientProperties.HEARTBEAT,ClientProperties.HEARTBEAT_DEFAULT);
- }
- return heartbeat;
- }
-
- protected org.apache.qpid.transport.Connection getQpidConnection()
- {
- return _qpidConnection;
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/AMQConnectionDelegate_0_9.java b/java/client/src/main/java/org/apache/qpid/client/AMQConnectionDelegate_0_9.java
deleted file mode 100755
index 70ecedfd8b..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/AMQConnectionDelegate_0_9.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.client;
-
-import org.apache.qpid.framing.ProtocolVersion;
-
-
-public class AMQConnectionDelegate_0_9 extends AMQConnectionDelegate_8_0
-{
-
- public AMQConnectionDelegate_0_9(AMQConnection conn)
- {
- super(conn);
- }
-
- @Override
- public ProtocolVersion getProtocolVersion()
- {
- return ProtocolVersion.v0_9;
- }
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/AMQConnectionDelegate_8_0.java b/java/client/src/main/java/org/apache/qpid/client/AMQConnectionDelegate_8_0.java
deleted file mode 100644
index 40b332d216..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/AMQConnectionDelegate_8_0.java
+++ /dev/null
@@ -1,325 +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.client;
-
-import java.io.IOException;
-import java.net.ConnectException;
-import java.nio.channels.UnresolvedAddressException;
-import java.text.MessageFormat;
-import java.util.ArrayList;
-import java.util.EnumSet;
-import java.util.Iterator;
-import java.util.Set;
-
-import javax.jms.JMSException;
-import javax.jms.XASession;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.failover.FailoverException;
-import org.apache.qpid.client.failover.FailoverProtectedOperation;
-import org.apache.qpid.client.failover.FailoverRetrySupport;
-import org.apache.qpid.client.protocol.AMQProtocolSession;
-import org.apache.qpid.client.state.AMQState;
-import org.apache.qpid.client.state.StateWaiter;
-import org.apache.qpid.client.transport.TransportConnection;
-import org.apache.qpid.framing.BasicQosBody;
-import org.apache.qpid.framing.BasicQosOkBody;
-import org.apache.qpid.framing.ChannelOpenBody;
-import org.apache.qpid.framing.ChannelOpenOkBody;
-import org.apache.qpid.framing.ProtocolVersion;
-import org.apache.qpid.framing.TxSelectBody;
-import org.apache.qpid.framing.TxSelectOkBody;
-import org.apache.qpid.jms.BrokerDetails;
-import org.apache.qpid.jms.ChannelLimitReachedException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class AMQConnectionDelegate_8_0 implements AMQConnectionDelegate
-{
- private static final Logger _logger = LoggerFactory.getLogger(AMQConnectionDelegate_8_0.class);
- private AMQConnection _conn;
-
-
- public void closeConnection(long timeout) throws JMSException, AMQException
- {
- _conn.getProtocolHandler().closeConnection(timeout);
-
- }
-
- public AMQConnectionDelegate_8_0(AMQConnection conn)
- {
- _conn = conn;
- }
-
- protected boolean checkException(Throwable thrown)
- {
- Throwable cause = thrown.getCause();
-
- if (cause == null)
- {
- cause = thrown;
- }
-
- return ((cause instanceof ConnectException) || (cause instanceof UnresolvedAddressException));
- }
-
- public ProtocolVersion makeBrokerConnection(BrokerDetails brokerDetail) throws AMQException, IOException
- {
- final Set<AMQState> openOrClosedStates =
- EnumSet.of(AMQState.CONNECTION_OPEN, AMQState.CONNECTION_CLOSED);
-
-
- StateWaiter waiter = _conn._protocolHandler.createWaiter(openOrClosedStates);
-
- // TODO: use system property thingy for this
- if (System.getProperty("UseTransportIo", "false").equals("false"))
- {
- TransportConnection.getInstance(brokerDetail).connect(_conn._protocolHandler, brokerDetail);
- }
- else
- {
- _conn.getProtocolHandler().createIoTransportSession(brokerDetail);
- }
- _conn._protocolHandler.getProtocolSession().init();
- // this blocks until the connection has been set up or when an error
- // has prevented the connection being set up
-
- AMQState state = waiter.await();
-
- if(state == AMQState.CONNECTION_OPEN)
- {
- _conn._failoverPolicy.attainedConnection();
- _conn._connected = true;
- return null;
- }
- else
- {
- return _conn._protocolHandler.getSuggestedProtocolVersion();
- }
-
- }
-
- public org.apache.qpid.jms.Session createSession(final boolean transacted, final int acknowledgeMode, final int prefetch)
- throws JMSException
- {
- return createSession(transacted, acknowledgeMode, prefetch, prefetch);
- }
-
- public XASession createXASession(int prefetchHigh, int prefetchLow) throws JMSException
- {
- throw new UnsupportedOperationException("0_8 version does not provide XA support");
- }
-
- public org.apache.qpid.jms.Session createSession(final boolean transacted, final int acknowledgeMode,
- final int prefetchHigh, final int prefetchLow) throws JMSException
- {
- _conn.checkNotClosed();
-
- if (_conn.channelLimitReached())
- {
- throw new ChannelLimitReachedException(_conn.getMaximumChannelCount());
- }
-
- return new FailoverRetrySupport<org.apache.qpid.jms.Session, JMSException>(
- new FailoverProtectedOperation<org.apache.qpid.jms.Session, JMSException>()
- {
- public org.apache.qpid.jms.Session execute() throws JMSException, FailoverException
- {
- int channelId = _conn.getNextChannelID();
-
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Write channel open frame for channel id " + channelId);
- }
-
- // We must create the session and register it before actually sending the frame to the server to
- // open it, so that there is no window where we could receive data on the channel and not be set
- // up to handle it appropriately.
- AMQSession session =
- new AMQSession_0_8(_conn, channelId, transacted, acknowledgeMode, prefetchHigh,
- prefetchLow);
- // _protocolHandler.addSessionByChannel(channelId, session);
- _conn.registerSession(channelId, session);
-
- boolean success = false;
- try
- {
- createChannelOverWire(channelId, prefetchHigh, prefetchLow, transacted);
- success = true;
- }
- catch (AMQException e)
- {
- JMSException jmse = new JMSException("Error creating session: " + e);
- jmse.setLinkedException(e);
- jmse.initCause(e);
- throw jmse;
- }
- finally
- {
- if (!success)
- {
- _conn.deregisterSession(channelId);
- }
- }
-
- if (_conn._started)
- {
- try
- {
- session.start();
- }
- catch (AMQException e)
- {
- throw new JMSAMQException(e);
- }
- }
-
- return session;
- }
- }, _conn).execute();
- }
-
- /**
- * Create an XASession with default prefetch values of:
- * High = MaxPrefetch
- * Low = MaxPrefetch / 2
- * @return XASession
- * @throws JMSException thrown if there is a problem creating the session.
- */
- public XASession createXASession() throws JMSException
- {
- return createXASession((int) _conn.getMaxPrefetch(), (int) _conn.getMaxPrefetch() / 2);
- }
-
- private void createChannelOverWire(int channelId, int prefetchHigh, int prefetchLow, boolean transacted)
- throws AMQException, FailoverException
- {
- ChannelOpenBody channelOpenBody = _conn.getProtocolHandler().getMethodRegistry().createChannelOpenBody(null);
- // TODO: Be aware of possible changes to parameter order as versions change.
- _conn._protocolHandler.syncWrite(channelOpenBody.generateFrame(channelId), ChannelOpenOkBody.class);
-
- // todo send low water mark when protocol allows.
- // todo Be aware of possible changes to parameter order as versions change.
- BasicQosBody basicQosBody = _conn.getProtocolHandler().getMethodRegistry().createBasicQosBody(0,prefetchHigh,false);
- _conn._protocolHandler.syncWrite(basicQosBody.generateFrame(channelId),BasicQosOkBody.class);
-
- if (transacted)
- {
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Issuing TxSelect for " + channelId);
- }
- TxSelectBody body = _conn.getProtocolHandler().getMethodRegistry().createTxSelectBody();
-
- // TODO: Be aware of possible changes to parameter order as versions change.
- _conn._protocolHandler.syncWrite(body.generateFrame(channelId), TxSelectOkBody.class);
- }
- }
-
- public void failoverPrep()
- {
- // do nothing
- }
-
- /**
- * For all sessions, and for all consumers in those sessions, resubscribe. This is called during failover handling.
- * The caller must hold the failover mutex before calling this method.
- */
- public void resubscribeSessions() throws JMSException, AMQException, FailoverException
- {
- ArrayList sessions = new ArrayList(_conn.getSessions().values());
- _logger.info(MessageFormat.format("Resubscribing sessions = {0} sessions.size={1}", sessions, sessions.size())); // FIXME: removeKey?
- for (Iterator it = sessions.iterator(); it.hasNext();)
- {
- AMQSession s = (AMQSession) it.next();
- // _protocolHandler.addSessionByChannel(s.getChannelId(), s);
- reopenChannel(s.getChannelId(), s.getDefaultPrefetchHigh(), s.getDefaultPrefetchLow(), s.getTransacted());
- s.resubscribe();
- }
- }
-
- private void reopenChannel(int channelId, int prefetchHigh, int prefetchLow, boolean transacted)
- throws AMQException, FailoverException
- {
- try
- {
- createChannelOverWire(channelId, prefetchHigh, prefetchLow, transacted);
- }
- catch (AMQException e)
- {
- _conn.deregisterSession(channelId);
- throw new AMQException(null, "Error reopening channel " + channelId + " after failover: " + e, e);
- }
- }
-
- public <T, E extends Exception> T executeRetrySupport(FailoverProtectedOperation<T,E> operation) throws E
- {
- while (true)
- {
- try
- {
- _conn.blockUntilNotFailingOver();
- }
- catch (InterruptedException e)
- {
- _logger.debug("Interrupted: " + e, e);
-
- return null;
- }
-
- synchronized (_conn.getFailoverMutex())
- {
- try
- {
- return operation.execute();
- }
- catch (FailoverException e)
- {
- _logger.debug("Failover exception caught during operation: " + e, e);
- }
- catch (IllegalStateException e)
- {
- if (!(e.getMessage().startsWith("Fail-over interupted no-op failover support")))
- {
- throw e;
- }
- }
- }
- }
- }
-
- public int getMaxChannelID()
- {
- ConnectionTuneParameters params = _conn.getProtocolHandler().getProtocolSession().getConnectionTuneParameters();
-
- return params == null ? AMQProtocolSession.MAX_CHANNEL_MAX : params.getChannelMax();
- }
-
- public int getMinChannelID()
- {
- return AMQProtocolSession.MIN_USABLE_CHANNEL_NUM;
- }
-
- public ProtocolVersion getProtocolVersion()
- {
- return ProtocolVersion.v8_0;
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/AMQConnectionDelegate_9_1.java b/java/client/src/main/java/org/apache/qpid/client/AMQConnectionDelegate_9_1.java
deleted file mode 100755
index 442dd7b286..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/AMQConnectionDelegate_9_1.java
+++ /dev/null
@@ -1,39 +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.client;
-
-import org.apache.qpid.framing.ProtocolVersion;
-
-
-public class AMQConnectionDelegate_9_1 extends AMQConnectionDelegate_8_0
-{
-
- public AMQConnectionDelegate_9_1(AMQConnection conn)
- {
- super(conn);
- }
-
- @Override
- public ProtocolVersion getProtocolVersion()
- {
- return ProtocolVersion.v0_91;
- }
-} \ No newline at end of file
diff --git a/java/client/src/main/java/org/apache/qpid/client/AMQConnectionFactory.java b/java/client/src/main/java/org/apache/qpid/client/AMQConnectionFactory.java
deleted file mode 100644
index ec4c668d7e..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/AMQConnectionFactory.java
+++ /dev/null
@@ -1,566 +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.client;
-
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.util.Hashtable;
-import java.util.UUID;
-
-import javax.jms.*;
-import javax.naming.Context;
-import javax.naming.Name;
-import javax.naming.NamingException;
-import javax.naming.RefAddr;
-import javax.naming.Reference;
-import javax.naming.Referenceable;
-import javax.naming.StringRefAddr;
-import javax.naming.spi.ObjectFactory;
-
-import org.apache.qpid.jms.ConnectionURL;
-import org.apache.qpid.url.AMQBindingURL;
-import org.apache.qpid.url.URLSyntaxException;
-
-
-public class AMQConnectionFactory implements ConnectionFactory, QueueConnectionFactory, TopicConnectionFactory,
- ObjectFactory, Referenceable, XATopicConnectionFactory,
- XAQueueConnectionFactory, XAConnectionFactory
-{
- private String _host;
- private int _port;
- private String _defaultUsername;
- private String _defaultPassword;
- private String _virtualPath;
-
- private ConnectionURL _connectionDetails;
- private SSLConfiguration _sslConfig;
-
- public AMQConnectionFactory()
- {
- }
-
- /**
- * This is the Only constructor used!
- * It is used form the context and from the JNDI objects.
- */
- public AMQConnectionFactory(String url) throws URLSyntaxException
- {
- _connectionDetails = new AMQConnectionURL(url);
- }
-
- /**
- * This constructor is never used!
- */
- public AMQConnectionFactory(ConnectionURL url)
- {
- _connectionDetails = url;
- }
-
- /**
- * This constructor is never used!
- */
- public AMQConnectionFactory(String broker, String username, String password, String clientName, String virtualHost)
- throws URLSyntaxException
- {
- this(new AMQConnectionURL(
- ConnectionURL.AMQ_PROTOCOL + "://" + username + ":" + password + "@" + clientName + "/" + virtualHost + "?brokerlist='" + broker + "'"));
- }
-
- /**
- * This constructor is never used!
- */
- public AMQConnectionFactory(String host, int port, String virtualPath)
- {
- this(host, port, "guest", "guest", virtualPath);
- }
-
- /**
- * This constructor is never used!
- */
- public AMQConnectionFactory(String host, int port, String defaultUsername, String defaultPassword,
- String virtualPath)
- {
- _host = host;
- _port = port;
- _defaultUsername = defaultUsername;
- _defaultPassword = defaultPassword;
- _virtualPath = virtualPath;
-
-//todo when setting Host/Port has been resolved then we can use this otherwise those methods won't work with the following line.
-// _connectionDetails = new AMQConnectionURL(
-// ConnectionURL.AMQ_PROTOCOL + "://" +
-// _defaultUsername + ":" + _defaultPassword + "@" +
-// virtualPath + "?brokerlist='tcp://" + host + ":" + port + "'");
- }
-
- /**
- * @return The _defaultPassword.
- */
- public final String getDefaultPassword(String password)
- {
- if (_connectionDetails != null)
- {
- return _connectionDetails.getPassword();
- }
- else
- {
- return _defaultPassword;
- }
- }
-
- /**
- * @param password The _defaultPassword to set.
- */
- public final void setDefaultPassword(String password)
- {
- if (_connectionDetails != null)
- {
- _connectionDetails.setPassword(password);
- }
- _defaultPassword = password;
- }
-
- /**
- * Getter for SSLConfiguration
- *
- * @return SSLConfiguration if set, otherwise null
- */
- public final SSLConfiguration getSSLConfiguration()
- {
- return _sslConfig;
- }
-
- /**
- * Setter for SSLConfiguration
- *
- * @param sslConfig config to store
- */
- public final void setSSLConfiguration(SSLConfiguration sslConfig)
- {
- _sslConfig = sslConfig;
- }
-
- /**
- * @return The _defaultPassword.
- */
- public final String getDefaultUsername(String password)
- {
- if (_connectionDetails != null)
- {
- return _connectionDetails.getUsername();
- }
- else
- {
- return _defaultUsername;
- }
- }
-
- /**
- * @param username The _defaultUsername to set.
- */
- public final void setDefaultUsername(String username)
- {
- if (_connectionDetails != null)
- {
- _connectionDetails.setUsername(username);
- }
- _defaultUsername = username;
- }
-
- /**
- * @return The _host .
- */
- public final String getHost()
- {
- //todo this doesn't make sense in a multi broker URL as we have no current as that is done by AMQConnection
- return _host;
- }
-
- /**
- * @param host The _host to set.
- */
- public final void setHost(String host)
- {
- //todo if _connectionDetails is set then run _connectionDetails.addBrokerDetails()
- // Should perhaps have this method changed to setBroker(host,port)
- _host = host;
- }
-
- /**
- * @return _port The _port to set.
- */
- public final int getPort()
- {
- //todo see getHost
- return _port;
- }
-
- /**
- * @param port The port to set.
- */
- public final void setPort(int port)
- {
- //todo see setHost
- _port = port;
- }
-
- /**
- * @return he _virtualPath.
- */
- public final String getVirtualPath()
- {
- if (_connectionDetails != null)
- {
- return _connectionDetails.getVirtualHost();
- }
- else
- {
- return _virtualPath;
- }
- }
-
- /**
- * @param path The _virtualPath to set.
- */
- public final void setVirtualPath(String path)
- {
- if (_connectionDetails != null)
- {
- _connectionDetails.setVirtualHost(path);
- }
-
- _virtualPath = path;
- }
-
- public static String getUniqueClientID()
- {
- try
- {
- InetAddress addr = InetAddress.getLocalHost();
- return addr.getHostName() + System.currentTimeMillis();
- }
- catch (UnknownHostException e)
- {
- return "UnknownHost" + UUID.randomUUID();
- }
- }
-
- public Connection createConnection() throws JMSException
- {
- try
- {
- if (_connectionDetails != null)
- {
- if (_connectionDetails.getClientName() == null || _connectionDetails.getClientName().equals(""))
- {
- _connectionDetails.setClientName(getUniqueClientID());
- }
- return new AMQConnection(_connectionDetails, _sslConfig);
- }
- else
- {
- return new AMQConnection(_host, _port, _defaultUsername, _defaultPassword, getUniqueClientID(),
- _virtualPath);
- }
- }
- catch (Exception e)
- {
- JMSException jmse = new JMSException("Error creating connection: " + e.getMessage());
- jmse.setLinkedException(e);
- jmse.initCause(e);
- throw jmse;
- }
-
-
- }
-
- public Connection createConnection(String userName, String password) throws JMSException
- {
- return createConnection(userName, password, null);
- }
-
- public Connection createConnection(String userName, String password, String id) throws JMSException
- {
- try
- {
- if (_connectionDetails != null)
- {
- _connectionDetails.setUsername(userName);
- _connectionDetails.setPassword(password);
-
- if (id != null && !id.equals(""))
- {
- _connectionDetails.setClientName(id);
- }
- else if (_connectionDetails.getClientName() == null || _connectionDetails.getClientName().equals(""))
- {
- _connectionDetails.setClientName(getUniqueClientID());
- }
- return new AMQConnection(_connectionDetails, _sslConfig);
- }
- else
- {
- return new AMQConnection(_host, _port, userName, password, (id != null ? id : getUniqueClientID()), _virtualPath);
- }
- }
- catch (Exception e)
- {
- JMSException jmse = new JMSException("Error creating connection: " + e.getMessage());
- jmse.setLinkedException(e);
- jmse.initCause(e);
- throw jmse;
- }
- }
-
- public QueueConnection createQueueConnection() throws JMSException
- {
- return (QueueConnection) createConnection();
- }
-
- public QueueConnection createQueueConnection(String username, String password) throws JMSException
- {
- return (QueueConnection) createConnection(username, password);
- }
-
- public TopicConnection createTopicConnection() throws JMSException
- {
- return (TopicConnection) createConnection();
- }
-
- public TopicConnection createTopicConnection(String username, String password) throws JMSException
- {
- return (TopicConnection) createConnection(username, password);
- }
-
-
- public ConnectionURL getConnectionURL()
- {
- return _connectionDetails;
- }
-
- public String getConnectionURLString()
- {
- return _connectionDetails.toString();
- }
-
-
- public final void setConnectionURLString(String url) throws URLSyntaxException
- {
- _connectionDetails = new AMQConnectionURL(url);
- }
-
- /**
- * JNDI interface to create objects from References.
- *
- * @param obj The Reference from JNDI
- * @param name
- * @param ctx
- * @param env
- *
- * @return AMQConnection,AMQTopic,AMQQueue, or AMQConnectionFactory.
- *
- * @throws Exception
- */
- public Object getObjectInstance(Object obj, Name name, Context ctx, Hashtable env) throws Exception
- {
- if (obj instanceof Reference)
- {
- Reference ref = (Reference) obj;
-
- if (ref.getClassName().equals(AMQConnection.class.getName()))
- {
- RefAddr addr = ref.get(AMQConnection.class.getName());
-
- if (addr != null)
- {
- return new AMQConnection((String) addr.getContent());
- }
- }
-
- if (ref.getClassName().equals(AMQQueue.class.getName()))
- {
- RefAddr addr = ref.get(AMQQueue.class.getName());
-
- if (addr != null)
- {
- return new AMQQueue(new AMQBindingURL((String) addr.getContent()));
- }
- }
-
- if (ref.getClassName().equals(AMQTopic.class.getName()))
- {
- RefAddr addr = ref.get(AMQTopic.class.getName());
-
- if (addr != null)
- {
- return new AMQTopic(new AMQBindingURL((String) addr.getContent()));
- }
- }
-
- if (ref.getClassName().equals(AMQConnectionFactory.class.getName()))
- {
- RefAddr addr = ref.get(AMQConnectionFactory.class.getName());
-
- if (addr != null)
- {
- return new AMQConnectionFactory((String) addr.getContent());
- }
- }
-
- }
- return null;
- }
-
-
- public Reference getReference() throws NamingException
- {
- return new Reference(
- AMQConnectionFactory.class.getName(),
- new StringRefAddr(AMQConnectionFactory.class.getName(), _connectionDetails.getURL()),
- AMQConnectionFactory.class.getName(), null); // factory location
- }
-
- // ---------------------------------------------------------------------------------------------------
- // the following methods are provided for XA compatibility
- // Those methods are only supported by 0_10 and above
- // ---------------------------------------------------------------------------------------------------
-
- /**
- * Creates a XAConnection with the default user identity.
- * <p> The XAConnection is created in stopped mode. No messages
- * will be delivered until the <code>Connection.start</code> method
- * is explicitly called.
- *
- * @return A newly created XAConnection
- * @throws JMSException If creating the XAConnection fails due to some internal error.
- * @throws JMSSecurityException If client authentication fails due to an invalid user name or password.
- */
- public XAConnection createXAConnection() throws JMSException
- {
- try
- {
- return new XAConnectionImpl(_connectionDetails, _sslConfig);
- }
- catch (Exception e)
- {
- JMSException jmse = new JMSException("Error creating connection: " + e.getMessage());
- jmse.setLinkedException(e);
- jmse.initCause(e);
- throw jmse;
- }
- }
-
- /**
- * Creates a XAConnection with the specified user identity.
- * <p> The XAConnection is created in stopped mode. No messages
- * will be delivered until the <code>Connection.start</code> method
- * is explicitly called.
- *
- * @param username the caller's user name
- * @param password the caller's password
- * @return A newly created XAConnection.
- * @throws JMSException If creating the XAConnection fails due to some internal error.
- * @throws JMSSecurityException If client authentication fails due to an invalid user name or password.
- */
- public XAConnection createXAConnection(String username, String password) throws JMSException
- {
- if (_connectionDetails != null)
- {
- _connectionDetails.setUsername(username);
- _connectionDetails.setPassword(password);
-
- if (_connectionDetails.getClientName() == null || _connectionDetails.getClientName().equals(""))
- {
- _connectionDetails.setClientName(getUniqueClientID());
- }
- }
- else
- {
- throw new JMSException("A URL must be specified to access XA connections");
- }
- return createXAConnection();
- }
-
-
- /**
- * Creates a XATopicConnection with the default user identity.
- * <p> The XATopicConnection is created in stopped mode. No messages
- * will be delivered until the <code>Connection.start</code> method
- * is explicitly called.
- *
- * @return A newly created XATopicConnection
- * @throws JMSException If creating the XATopicConnection fails due to some internal error.
- * @throws JMSSecurityException If client authentication fails due to an invalid user name or password.
- */
- public XATopicConnection createXATopicConnection() throws JMSException
- {
- return (XATopicConnection) createXAConnection();
- }
-
- /**
- * Creates a XATopicConnection with the specified user identity.
- * <p> The XATopicConnection is created in stopped mode. No messages
- * will be delivered until the <code>Connection.start</code> method
- * is explicitly called.
- *
- * @param username the caller's user name
- * @param password the caller's password
- * @return A newly created XATopicConnection.
- * @throws JMSException If creating the XATopicConnection fails due to some internal error.
- * @throws JMSSecurityException If client authentication fails due to an invalid user name or password.
- */
- public XATopicConnection createXATopicConnection(String username, String password) throws JMSException
- {
- return (XATopicConnection) createXAConnection(username, password);
- }
-
- /**
- * Creates a XAQueueConnection with the default user identity.
- * <p> The XAQueueConnection is created in stopped mode. No messages
- * will be delivered until the <code>Connection.start</code> method
- * is explicitly called.
- *
- * @return A newly created XAQueueConnection
- * @throws JMSException If creating the XAQueueConnection fails due to some internal error.
- * @throws JMSSecurityException If client authentication fails due to an invalid user name or password.
- */
- public XAQueueConnection createXAQueueConnection() throws JMSException
- {
- return (XAQueueConnection) createXAConnection();
- }
-
- /**
- * Creates a XAQueueConnection with the specified user identity.
- * <p> The XAQueueConnection is created in stopped mode. No messages
- * will be delivered until the <code>Connection.start</code> method
- * is explicitly called.
- *
- * @param username the caller's user name
- * @param password the caller's password
- * @return A newly created XAQueueConnection.
- * @throws JMSException If creating the XAQueueConnection fails due to some internal error.
- * @throws JMSSecurityException If client authentication fails due to an invalid user name or password.
- */
- public XAQueueConnection createXAQueueConnection(String username, String password) throws JMSException
- {
- return (XAQueueConnection) createXAConnection(username, password);
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/AMQConnectionURL.java b/java/client/src/main/java/org/apache/qpid/client/AMQConnectionURL.java
deleted file mode 100644
index 93b4c51a8f..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/AMQConnectionURL.java
+++ /dev/null
@@ -1,311 +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.client;
-
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.qpid.client.url.URLParser;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.ProtocolVersion;
-import org.apache.qpid.jms.BrokerDetails;
-import org.apache.qpid.jms.ConnectionURL;
-import org.apache.qpid.url.URLHelper;
-import org.apache.qpid.url.URLSyntaxException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class AMQConnectionURL implements ConnectionURL
-{
- private static final Logger _logger = LoggerFactory.getLogger(AMQConnectionURL.class);
-
- private String _url;
- private String _failoverMethod;
- private Map<String, String> _failoverOptions;
- private Map<String, String> _options;
- private List<BrokerDetails> _brokers;
- private String _clientName;
- private String _username;
- private String _password;
- private String _virtualHost;
- private AMQShortString _defaultQueueExchangeName;
- private AMQShortString _defaultTopicExchangeName;
- private AMQShortString _temporaryTopicExchangeName;
- private AMQShortString _temporaryQueueExchangeName;
-
- public AMQConnectionURL(String fullURL) throws URLSyntaxException
- {
- if (fullURL == null) throw new IllegalArgumentException("URL cannot be null");
- _url = fullURL;
- _options = new HashMap<String, String>();
- _brokers = new LinkedList<BrokerDetails>();
- _failoverOptions = new HashMap<String, String>();
- new URLParser(this);
- }
-
- public String getURL()
- {
- return _url;
- }
-
- public Map<String,String> getOptions()
- {
- return _options;
- }
-
- public String getFailoverMethod()
- {
- return _failoverMethod;
- }
-
- public void setFailoverMethod(String failoverMethod)
- {
- _failoverMethod = failoverMethod;
- }
-
- public Map<String,String> getFailoverOptions()
- {
- return _failoverOptions;
- }
-
- public String getFailoverOption(String key)
- {
- return _failoverOptions.get(key);
- }
-
- public void setFailoverOption(String key, String value)
- {
- _failoverOptions.put(key, value);
- }
-
- public int getBrokerCount()
- {
- return _brokers.size();
- }
-
- public BrokerDetails getBrokerDetails(int index)
- {
- if (index < _brokers.size())
- {
- return _brokers.get(index);
- }
- else
- {
- return null;
- }
- }
-
- public void addBrokerDetails(BrokerDetails broker)
- {
- if (!(_brokers.contains(broker)))
- {
- _brokers.add(broker);
- }
- }
-
- public void setBrokerDetails(List<BrokerDetails> brokers)
- {
- _brokers = brokers;
- }
-
- public List<BrokerDetails> getAllBrokerDetails()
- {
- return _brokers;
- }
-
- public String getClientName()
- {
- return _clientName;
- }
-
- public void setClientName(String clientName)
- {
- _clientName = clientName;
- }
-
- public String getUsername()
- {
- return _username;
- }
-
- public void setUsername(String username)
- {
- _username = username;
- }
-
- public String getPassword()
- {
- return _password;
- }
-
- public void setPassword(String password)
- {
- _password = password;
- }
-
- public String getVirtualHost()
- {
- return _virtualHost;
- }
-
- public void setVirtualHost(String virtuaHost)
- {
- _virtualHost = virtuaHost;
- }
-
- public String getOption(String key)
- {
- return _options.get(key);
- }
-
- public void setOption(String key, String value)
- {
- _options.put(key, value);
- }
-
- public AMQShortString getDefaultQueueExchangeName()
- {
- return _defaultQueueExchangeName;
- }
-
- public void setDefaultQueueExchangeName(AMQShortString defaultQueueExchangeName)
- {
- _defaultQueueExchangeName = defaultQueueExchangeName;
- }
-
- public AMQShortString getDefaultTopicExchangeName()
- {
- return _defaultTopicExchangeName;
- }
-
- public void setDefaultTopicExchangeName(AMQShortString defaultTopicExchangeName)
- {
- _defaultTopicExchangeName = defaultTopicExchangeName;
- }
-
- public AMQShortString getTemporaryQueueExchangeName()
- {
- return _temporaryQueueExchangeName;
- }
-
- public void setTemporaryQueueExchangeName(AMQShortString temporaryQueueExchangeName)
- {
- _temporaryQueueExchangeName = temporaryQueueExchangeName;
- }
-
- public AMQShortString getTemporaryTopicExchangeName()
- {
- return _temporaryTopicExchangeName;
- }
-
- public void setTemporaryTopicExchangeName(AMQShortString temporaryTopicExchangeName)
- {
- _temporaryTopicExchangeName = temporaryTopicExchangeName;
- }
-
- public String toString()
- {
- StringBuffer sb = new StringBuffer();
-
- sb.append(AMQ_PROTOCOL);
- sb.append("://");
-
- if (_username != null)
- {
- sb.append(_username);
-
- if (_password != null)
- {
- sb.append(':');
- sb.append("********");
- }
-
- sb.append('@');
- }
-
- sb.append(_clientName);
-
- sb.append(_virtualHost);
-
- sb.append(optionsToString());
-
- return sb.toString();
- }
-
- private String optionsToString()
- {
- StringBuffer sb = new StringBuffer("?");
-
- if (!_options.isEmpty())
- {
- for (Map.Entry<String, String> option : _options.entrySet())
- {
- sb.append(option.getKey()).append("='").append(option.getValue()).append("'");
- sb.append(URLHelper.DEFAULT_OPTION_SEPERATOR);
- }
- }
-
- sb.append(OPTIONS_BROKERLIST).append("='");
- for (BrokerDetails service : _brokers)
- {
- sb.append(service.toString());
- sb.append(URLHelper.BROKER_SEPARATOR);
- }
-
- sb.deleteCharAt(sb.length() - 1);
- sb.append("'");
-
- if (_failoverMethod != null)
- {
- sb.append(URLHelper.DEFAULT_OPTION_SEPERATOR);
- sb.append(OPTIONS_FAILOVER + "='");
- sb.append(_failoverMethod);
- sb.append(URLHelper.printOptions(_failoverOptions));
- sb.append("'");
- }
-
- for (String key : _options.keySet())
- {
- if (!key.equals(OPTIONS_FAILOVER) || !key.equals(OPTIONS_BROKERLIST))
- {
- sb.append(URLHelper.DEFAULT_OPTION_SEPERATOR).append(key).append("='");
- sb.append(_options.get(key)).append("'");
- }
- }
-
- return sb.toString();
- }
-
- public static void main(String[] args) throws URLSyntaxException
- {
- String url2 =
- "amqp://ritchiem:bob@temp/testHost?brokerlist='tcp://localhost:5672;tcp://fancyserver:3000/',failover='roundrobin'";
- // "amqp://user:pass@clientid/virtualhost?brokerlist='tcp://host:1?option1=\'value\',option2=\'value\';vm://:3?option1=\'value\'',failover='method?option1=\'value\',option2='value''";
-
- ConnectionURL connectionurl2 = new AMQConnectionURL(url2);
-
- System.out.println(url2);
- System.out.println(connectionurl2);
-
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/AMQDestination.java b/java/client/src/main/java/org/apache/qpid/client/AMQDestination.java
deleted file mode 100644
index eb9682a3cf..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/AMQDestination.java
+++ /dev/null
@@ -1,941 +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.client;
-
-import java.net.URISyntaxException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-import javax.jms.Destination;
-import javax.naming.NamingException;
-import javax.naming.Reference;
-import javax.naming.Referenceable;
-import javax.naming.StringRefAddr;
-
-import org.apache.qpid.client.messaging.address.AddressHelper;
-import org.apache.qpid.client.messaging.address.Link;
-import org.apache.qpid.client.messaging.address.Node;
-import org.apache.qpid.client.messaging.address.QpidExchangeOptions;
-import org.apache.qpid.client.messaging.address.QpidQueueOptions;
-import org.apache.qpid.configuration.ClientProperties;
-import org.apache.qpid.exchange.ExchangeDefaults;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.messaging.Address;
-import org.apache.qpid.url.AMQBindingURL;
-import org.apache.qpid.url.BindingURL;
-import org.apache.qpid.url.URLHelper;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-
-public abstract class AMQDestination implements Destination, Referenceable
-{
- private static final Logger _logger = LoggerFactory.getLogger(AMQDestination.class);
-
- protected AMQShortString _exchangeName;
-
- protected AMQShortString _exchangeClass;
-
- protected boolean _isDurable;
-
- protected boolean _isExclusive;
-
- protected boolean _isAutoDelete;
-
- private boolean _browseOnly;
-
- private boolean _isAddressResolved;
-
- private AMQShortString _queueName;
-
- private AMQShortString _routingKey;
-
- private AMQShortString[] _bindingKeys;
-
- private String _url;
- private AMQShortString _urlAsShortString;
-
- private boolean _checkedForQueueBinding;
-
- private boolean _exchangeExistsChecked;
-
- private byte[] _byteEncoding;
- private static final int IS_DURABLE_MASK = 0x1;
- private static final int IS_EXCLUSIVE_MASK = 0x2;
- private static final int IS_AUTODELETE_MASK = 0x4;
-
- public static final int QUEUE_TYPE = 1;
- public static final int TOPIC_TYPE = 2;
- public static final int UNKNOWN_TYPE = 3;
-
- // ----- Fields required to support new address syntax -------
-
- public enum DestSyntax {
- BURL,ADDR;
-
- public static DestSyntax getSyntaxType(String s)
- {
- if (("BURL").equals(s))
- {
- return BURL;
- }
- else if (("ADDR").equals(s))
- {
- return ADDR;
- }
- else
- {
- throw new IllegalArgumentException("Invalid Destination Syntax Type" +
- " should be one of {BURL|ADDR}");
- }
- }
- }
-
- public enum AddressOption {
- ALWAYS, NEVER, SENDER, RECEIVER;
-
- public static AddressOption getOption(String str)
- {
- if ("always".equals(str)) return ALWAYS;
- else if ("never".equals(str)) return NEVER;
- else if ("sender".equals(str)) return SENDER;
- else if ("receiver".equals(str)) return RECEIVER;
- else throw new IllegalArgumentException(str + " is not an allowed value");
- }
- }
-
- protected final static DestSyntax defaultDestSyntax;
-
- protected DestSyntax _destSyntax = DestSyntax.ADDR;
-
- protected AddressHelper _addrHelper;
- protected Address _address;
- protected int _addressType = AMQDestination.UNKNOWN_TYPE;
- protected String _name;
- protected String _subject;
- protected AddressOption _create = AddressOption.NEVER;
- protected AddressOption _assert = AddressOption.NEVER;
- protected AddressOption _delete = AddressOption.NEVER;
-
- protected Node _targetNode;
- protected Node _sourceNode;
- protected Link _targetLink;
- protected Link _link;
-
- // ----- / Fields required to support new address syntax -------
-
- static
- {
- defaultDestSyntax = DestSyntax.getSyntaxType(
- System.getProperty(ClientProperties.DEST_SYNTAX,
- DestSyntax.ADDR.toString()));
-
-
- }
-
- public static DestSyntax getDefaultDestSyntax()
- {
- return defaultDestSyntax;
- }
-
- protected AMQDestination(Address address) throws Exception
- {
- this._address = address;
- getInfoFromAddress();
- _destSyntax = DestSyntax.ADDR;
- _logger.debug("Based on " + address + " the selected destination syntax is " + _destSyntax);
- }
-
- public static DestSyntax getDestType(String str)
- {
- if (str.startsWith("BURL:") ||
- (!str.startsWith("ADDR:") && defaultDestSyntax == DestSyntax.BURL))
- {
- return DestSyntax.BURL;
- }
- else
- {
- return DestSyntax.ADDR;
- }
- }
-
- public static String stripSyntaxPrefix(String str)
- {
- if (str.startsWith("BURL:") || str.startsWith("ADDR:"))
- {
- return str.substring(5,str.length());
- }
- else
- {
- return str;
- }
- }
-
- protected AMQDestination(String str) throws URISyntaxException
- {
- _destSyntax = getDestType(str);
- str = stripSyntaxPrefix(str);
- if (_destSyntax == DestSyntax.BURL)
- {
- getInfoFromBindingURL(new AMQBindingURL(str));
- }
- else
- {
- this._address = createAddressFromString(str);
- try
- {
- getInfoFromAddress();
- }
- catch(Exception e)
- {
- URISyntaxException ex = new URISyntaxException(str,"Error parsing address");
- ex.initCause(e);
- throw ex;
- }
- }
- _logger.debug("Based on " + str + " the selected destination syntax is " + _destSyntax);
- }
-
- //retained for legacy support
- protected AMQDestination(BindingURL binding)
- {
- getInfoFromBindingURL(binding);
- _destSyntax = DestSyntax.BURL;
- _logger.debug("Based on " + binding + " the selected destination syntax is " + _destSyntax);
- }
-
- protected void getInfoFromBindingURL(BindingURL binding)
- {
- _exchangeName = binding.getExchangeName();
- _exchangeClass = binding.getExchangeClass();
-
- _isExclusive = Boolean.parseBoolean(binding.getOption(BindingURL.OPTION_EXCLUSIVE));
- _isAutoDelete = Boolean.parseBoolean(binding.getOption(BindingURL.OPTION_AUTODELETE));
- _isDurable = Boolean.parseBoolean(binding.getOption(BindingURL.OPTION_DURABLE));
- _browseOnly = Boolean.parseBoolean(binding.getOption(BindingURL.OPTION_BROWSE));
- _queueName = binding.getQueueName() == null ? null : binding.getQueueName();
- _routingKey = binding.getRoutingKey() == null ? null : binding.getRoutingKey();
- _bindingKeys = binding.getBindingKeys() == null || binding.getBindingKeys().length == 0 ? new AMQShortString[0] : binding.getBindingKeys();
- }
-
- protected AMQDestination(AMQShortString exchangeName, AMQShortString exchangeClass, AMQShortString routingKey, AMQShortString queueName)
- {
- this(exchangeName, exchangeClass, routingKey, false, false, queueName, null);
- }
-
- protected AMQDestination(AMQShortString exchangeName, AMQShortString exchangeClass, AMQShortString routingKey, AMQShortString queueName, AMQShortString[] bindingKeys)
- {
- this(exchangeName, exchangeClass, routingKey, false, false, queueName,bindingKeys);
- }
-
- protected AMQDestination(AMQShortString exchangeName, AMQShortString exchangeClass, AMQShortString destinationName)
- {
- this(exchangeName, exchangeClass, destinationName, false, false, null,null);
- }
-
- protected AMQDestination(AMQShortString exchangeName, AMQShortString exchangeClass, AMQShortString routingKey, boolean isExclusive,
- boolean isAutoDelete, AMQShortString queueName)
- {
- this(exchangeName, exchangeClass, routingKey, isExclusive, isAutoDelete, queueName, false,null);
- }
-
- protected AMQDestination(AMQShortString exchangeName, AMQShortString exchangeClass, AMQShortString routingKey, boolean isExclusive,
- boolean isAutoDelete, AMQShortString queueName,AMQShortString[] bindingKeys)
- {
- this(exchangeName, exchangeClass, routingKey, isExclusive, isAutoDelete, queueName, false,bindingKeys);
- }
-
- protected AMQDestination(AMQShortString exchangeName, AMQShortString exchangeClass, AMQShortString routingKey, boolean isExclusive,
- boolean isAutoDelete, AMQShortString queueName, boolean isDurable){
- this (exchangeName, exchangeClass, routingKey, isExclusive,isAutoDelete,queueName,isDurable,null);
- }
-
- protected AMQDestination(AMQShortString exchangeName, AMQShortString exchangeClass, AMQShortString routingKey, boolean isExclusive,
- boolean isAutoDelete, AMQShortString queueName, boolean isDurable,AMQShortString[] bindingKeys)
- {
- this (exchangeName, exchangeClass, routingKey, isExclusive,isAutoDelete,queueName,isDurable,bindingKeys, false);
- }
-
- protected AMQDestination(AMQShortString exchangeName, AMQShortString exchangeClass, AMQShortString routingKey, boolean isExclusive,
- boolean isAutoDelete, AMQShortString queueName, boolean isDurable,AMQShortString[] bindingKeys, boolean browseOnly)
- {
- if ( (ExchangeDefaults.DIRECT_EXCHANGE_CLASS.equals(exchangeClass) ||
- ExchangeDefaults.TOPIC_EXCHANGE_CLASS.equals(exchangeClass))
- && routingKey == null)
- {
- throw new IllegalArgumentException("routing/binding key must not be null");
- }
- if (exchangeName == null)
- {
- throw new IllegalArgumentException("Exchange name must not be null");
- }
- if (exchangeClass == null)
- {
- throw new IllegalArgumentException("Exchange class must not be null");
- }
- _exchangeName = exchangeName;
- _exchangeClass = exchangeClass;
- _routingKey = routingKey;
- _isExclusive = isExclusive;
- _isAutoDelete = isAutoDelete;
- _queueName = queueName;
- _isDurable = isDurable;
- _bindingKeys = bindingKeys == null || bindingKeys.length == 0 ? new AMQShortString[0] : bindingKeys;
- _destSyntax = DestSyntax.BURL;
- _browseOnly = browseOnly;
-
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Based on " + toString() + " the selected destination syntax is " + _destSyntax);
- }
- }
-
- public DestSyntax getDestSyntax()
- {
- return _destSyntax;
- }
-
- protected void setDestSyntax(DestSyntax syntax)
- {
- _destSyntax = syntax;
- }
-
- public AMQShortString getEncodedName()
- {
- if(_urlAsShortString == null)
- {
- toURL();
- }
- return _urlAsShortString;
- }
-
- public boolean isDurable()
- {
- return _isDurable;
- }
-
- public AMQShortString getExchangeName()
- {
- return _exchangeName;
- }
-
- public AMQShortString getExchangeClass()
- {
- return _exchangeClass;
- }
-
- public boolean isTopic()
- {
- return ExchangeDefaults.TOPIC_EXCHANGE_CLASS.equals(_exchangeClass);
- }
-
- public boolean isQueue()
- {
- return ExchangeDefaults.DIRECT_EXCHANGE_CLASS.equals(_exchangeClass);
- }
-
- public String getQueueName()
- {
- return _queueName == null ? null : _queueName.toString();
- }
-
- public AMQShortString getAMQQueueName()
- {
- return _queueName;
- }
-
- public void setQueueName(AMQShortString queueName)
- {
-
- _queueName = queueName;
- // calculated URL now out of date
- _url = null;
- _urlAsShortString = null;
- _byteEncoding = null;
- }
-
- public AMQShortString getRoutingKey()
- {
- return _routingKey;
- }
-
- public AMQShortString[] getBindingKeys()
- {
- if (_bindingKeys != null && _bindingKeys.length > 0)
- {
- return _bindingKeys;
- }
- else
- {
- // catering to the common use case where the
- //routingKey is the same as the bindingKey.
- return new AMQShortString[]{_routingKey};
- }
- }
-
- public boolean isExclusive()
- {
- return _isExclusive;
- }
-
- public boolean isAutoDelete()
- {
- return _isAutoDelete;
- }
-
- public abstract boolean isNameRequired();
-
- public String toString()
- {
- if (_destSyntax == DestSyntax.BURL)
- {
- return toURL();
- }
- else
- {
- return _address.toString();
- }
-
- }
-
- public boolean isCheckedForQueueBinding()
- {
- return _checkedForQueueBinding;
- }
-
- public void setCheckedForQueueBinding(boolean checkedForQueueBinding)
- {
- _checkedForQueueBinding = checkedForQueueBinding;
- }
-
-
- public boolean isExchangeExistsChecked()
- {
- return _exchangeExistsChecked;
- }
-
- public void setExchangeExistsChecked(final boolean exchangeExistsChecked)
- {
- _exchangeExistsChecked = exchangeExistsChecked;
- }
-
- public String toURL()
- {
- String url = _url;
- if(url == null)
- {
-
-
- StringBuffer sb = new StringBuffer();
-
- sb.append(_exchangeClass);
- sb.append("://");
- sb.append(_exchangeName);
-
- sb.append("/"+_routingKey+"/");
-
- if (_queueName != null)
- {
- sb.append(_queueName);
- }
-
- sb.append('?');
-
- if (_routingKey != null)
- {
- sb.append(BindingURL.OPTION_ROUTING_KEY);
- sb.append("='");
- sb.append(_routingKey).append("'");
- sb.append(URLHelper.DEFAULT_OPTION_SEPERATOR);
- }
-
- // We can't allow both routingKey and bindingKey
- if (_routingKey == null && _bindingKeys != null && _bindingKeys.length>0)
- {
-
- for (AMQShortString bindingKey:_bindingKeys)
- {
- sb.append(BindingURL.OPTION_BINDING_KEY);
- sb.append("='");
- sb.append(bindingKey);
- sb.append("'");
- sb.append(URLHelper.DEFAULT_OPTION_SEPERATOR);
-
- }
- }
-
- if (_isDurable)
- {
- sb.append(BindingURL.OPTION_DURABLE);
- sb.append("='true'");
- sb.append(URLHelper.DEFAULT_OPTION_SEPERATOR);
- }
-
- if (_isExclusive)
- {
- sb.append(BindingURL.OPTION_EXCLUSIVE);
- sb.append("='true'");
- sb.append(URLHelper.DEFAULT_OPTION_SEPERATOR);
- }
-
- if (_isAutoDelete)
- {
- sb.append(BindingURL.OPTION_AUTODELETE);
- sb.append("='true'");
- sb.append(URLHelper.DEFAULT_OPTION_SEPERATOR);
- }
-
- //removeKey the last char '?' if there is no options , ',' if there are.
- sb.deleteCharAt(sb.length() - 1);
- url = sb.toString();
- _url = url;
- _urlAsShortString = new AMQShortString(url);
- }
- return url;
- }
-
- public byte[] toByteEncoding()
- {
- byte[] encoding = _byteEncoding;
- if(encoding == null)
- {
- int size = _exchangeClass.length() + 1 +
- _exchangeName.length() + 1 +
- 0 + // in place of the destination name
- (_queueName == null ? 0 : _queueName.length()) + 1 +
- 1;
- encoding = new byte[size];
- int pos = 0;
-
- pos = _exchangeClass.writeToByteArray(encoding, pos);
- pos = _exchangeName.writeToByteArray(encoding, pos);
-
- encoding[pos++] = (byte)0;
-
- if(_queueName == null)
- {
- encoding[pos++] = (byte)0;
- }
- else
- {
- pos = _queueName.writeToByteArray(encoding,pos);
- }
- byte options = 0;
- if(_isDurable)
- {
- options |= IS_DURABLE_MASK;
- }
- if(_isExclusive)
- {
- options |= IS_EXCLUSIVE_MASK;
- }
- if(_isAutoDelete)
- {
- options |= IS_AUTODELETE_MASK;
- }
- encoding[pos] = options;
-
-
- _byteEncoding = encoding;
-
- }
- return encoding;
- }
-
- public boolean equals(Object o)
- {
- if (this == o)
- {
- return true;
- }
- if (o == null || getClass() != o.getClass())
- {
- return false;
- }
-
- final AMQDestination that = (AMQDestination) o;
-
- if (!_exchangeClass.equals(that._exchangeClass))
- {
- return false;
- }
- if (!_exchangeName.equals(that._exchangeName))
- {
- return false;
- }
- if ((_queueName == null && that._queueName != null) ||
- (_queueName != null && !_queueName.equals(that._queueName)))
- {
- return false;
- }
-
- return true;
- }
-
- public int hashCode()
- {
- int result;
- result = _exchangeName == null ? "".hashCode() : _exchangeName.hashCode();
- result = 29 * result + (_exchangeClass == null ? "".hashCode() :_exchangeClass.hashCode());
- //result = 29 * result + _destinationName.hashCode();
- if (_queueName != null)
- {
- result = 29 * result + _queueName.hashCode();
- }
-
- return result;
- }
-
- public Reference getReference() throws NamingException
- {
- return new Reference(
- this.getClass().getName(),
- new StringRefAddr(this.getClass().getName(), toURL()),
- AMQConnectionFactory.class.getName(),
- null); // factory location
- }
-
-
- public static Destination createDestination(byte[] byteEncodedDestination)
- {
- AMQShortString exchangeClass;
- AMQShortString exchangeName;
- AMQShortString routingKey;
- AMQShortString queueName;
- boolean isDurable;
- boolean isExclusive;
- boolean isAutoDelete;
-
- int pos = 0;
- exchangeClass = AMQShortString.readFromByteArray(byteEncodedDestination, pos);
- pos+= exchangeClass.length() + 1;
- exchangeName = AMQShortString.readFromByteArray(byteEncodedDestination, pos);
- pos+= exchangeName.length() + 1;
- routingKey = AMQShortString.readFromByteArray(byteEncodedDestination, pos);
- pos+= (routingKey == null ? 0 : routingKey.length()) + 1;
- queueName = AMQShortString.readFromByteArray(byteEncodedDestination, pos);
- pos+= (queueName == null ? 0 : queueName.length()) + 1;
- int options = byteEncodedDestination[pos];
- isDurable = (options & IS_DURABLE_MASK) != 0;
- isExclusive = (options & IS_EXCLUSIVE_MASK) != 0;
- isAutoDelete = (options & IS_AUTODELETE_MASK) != 0;
-
- if (exchangeClass.equals(ExchangeDefaults.DIRECT_EXCHANGE_CLASS))
- {
- return new AMQQueue(exchangeName,routingKey,queueName,isExclusive,isAutoDelete,isDurable);
- }
- else if (exchangeClass.equals(ExchangeDefaults.TOPIC_EXCHANGE_CLASS))
- {
- return new AMQTopic(exchangeName,routingKey,isAutoDelete,queueName,isDurable);
- }
- else if (exchangeClass.equals(ExchangeDefaults.HEADERS_EXCHANGE_CLASS))
- {
- return new AMQHeadersExchange(routingKey);
- }
- else
- {
- return new AMQAnyDestination(exchangeName,exchangeClass,
- routingKey,isExclusive,
- isAutoDelete,queueName,
- isDurable, new AMQShortString[0]);
- }
-
- }
-
- public static Destination createDestination(BindingURL binding)
- {
- AMQShortString type = binding.getExchangeClass();
-
- if (type.equals(ExchangeDefaults.DIRECT_EXCHANGE_CLASS))
- {
- return new AMQQueue(binding);
- }
- else if (type.equals(ExchangeDefaults.TOPIC_EXCHANGE_CLASS))
- {
- return new AMQTopic(binding);
- }
- else if (type.equals(ExchangeDefaults.HEADERS_EXCHANGE_CLASS))
- {
- return new AMQHeadersExchange(binding);
- }
- else
- {
- return new AMQAnyDestination(binding);
- }
- }
-
- public static Destination createDestination(String str) throws Exception
- {
- DestSyntax syntax = getDestType(str);
- str = stripSyntaxPrefix(str);
- if (syntax == DestSyntax.BURL)
- {
- return createDestination(new AMQBindingURL(str));
- }
- else
- {
- Address address = createAddressFromString(str);
- return new AMQAnyDestination(address);
- }
- }
-
- // ----- new address syntax -----------
-
- public static class Binding
- {
- String exchange;
- String bindingKey;
- String queue;
- Map<String,Object> args;
-
- public Binding(String exchange,
- String queue,
- String bindingKey,
- Map<String,Object> args)
- {
- this.exchange = exchange;
- this.queue = queue;
- this.bindingKey = bindingKey;
- this.args = args;
- }
-
- public String getExchange()
- {
- return exchange;
- }
-
- public String getQueue()
- {
- return queue;
- }
-
- public String getBindingKey()
- {
- return bindingKey;
- }
-
- public Map<String, Object> getArgs()
- {
- return args;
- }
- }
-
- public Address getAddress() {
- return _address;
- }
-
- protected void setAddress(Address addr) {
- _address = addr;
- }
-
- public int getAddressType(){
- return _addressType;
- }
-
- public void setAddressType(int addressType){
- _addressType = addressType;
- }
-
- public String getAddressName() {
- return _name;
- }
-
- public void setAddressName(String name){
- _name = name;
- }
-
- public String getSubject() {
- return _subject;
- }
-
- public void setSubject(String subject) {
- _subject = subject;
- }
-
- public AddressOption getCreate() {
- return _create;
- }
-
- public void setCreate(AddressOption option) {
- _create = option;
- }
-
- public AddressOption getAssert() {
- return _assert;
- }
-
- public void setAssert(AddressOption option) {
- _assert = option;
- }
-
- public AddressOption getDelete() {
- return _delete;
- }
-
- public void setDelete(AddressOption option) {
- _delete = option;
- }
-
- public Node getTargetNode()
- {
- return _targetNode;
- }
-
- public void setTargetNode(Node node)
- {
- _targetNode = node;
- }
-
- public Node getSourceNode()
- {
- return _sourceNode;
- }
-
- public void setSourceNode(Node node)
- {
- _sourceNode = node;
- }
-
- public Link getLink()
- {
- return _link;
- }
-
- public void setLink(Link link)
- {
- _link = link;
- }
-
- public void setExchangeName(AMQShortString name)
- {
- this._exchangeName = name;
- }
-
- public void setExchangeClass(AMQShortString type)
- {
- this._exchangeClass = type;
- }
-
- public void setRoutingKey(AMQShortString rk)
- {
- this._routingKey = rk;
- }
-
- public boolean isAddressResolved()
- {
- return _isAddressResolved;
- }
-
- public void setAddressResolved(boolean addressResolved)
- {
- _isAddressResolved = addressResolved;
- }
-
- private static Address createAddressFromString(String str)
- {
- return Address.parse(str);
- }
-
- private void getInfoFromAddress() throws Exception
- {
- _name = _address.getName();
- _subject = _address.getSubject();
-
- _addrHelper = new AddressHelper(_address);
-
- _create = _addrHelper.getCreate() != null ?
- AddressOption.getOption(_addrHelper.getCreate()):AddressOption.NEVER;
-
- _assert = _addrHelper.getAssert() != null ?
- AddressOption.getOption(_addrHelper.getAssert()):AddressOption.NEVER;
-
- _delete = _addrHelper.getDelete() != null ?
- AddressOption.getOption(_addrHelper.getDelete()):AddressOption.NEVER;
-
- _browseOnly = _addrHelper.isBrowseOnly();
-
- _addressType = _addrHelper.getTargetNodeType();
- _targetNode = _addrHelper.getTargetNode(_addressType);
- _sourceNode = _addrHelper.getSourceNode(_addressType);
- _link = _addrHelper.getLink();
- }
-
- // This method is needed if we didn't know the node type at the beginning.
- // Therefore we have to query the broker to figure out the type.
- // Once the type is known we look for the necessary properties.
- public void rebuildTargetAndSourceNodes(int addressType)
- {
- _targetNode = _addrHelper.getTargetNode(addressType);
- _sourceNode = _addrHelper.getSourceNode(addressType);
- }
-
- // ----- / new address syntax -----------
-
- public boolean isBrowseOnly()
- {
- return _browseOnly;
- }
-
- public void setBrowseOnly(boolean b)
- {
- _browseOnly = b;
- }
-
- public AMQDestination copyDestination()
- {
- AMQDestination dest =
- new AMQAnyDestination(_exchangeName,
- _exchangeClass,
- _routingKey,
- _isExclusive,
- _isAutoDelete,
- _queueName,
- _isDurable,
- _bindingKeys
- );
-
- dest.setDestSyntax(_destSyntax);
- dest.setAddress(_address);
- dest.setAddressName(_name);
- dest.setSubject(_subject);
- dest.setCreate(_create);
- dest.setAssert(_assert);
- dest.setDelete(_create);
- dest.setBrowseOnly(_browseOnly);
- dest.setAddressType(_addressType);
- dest.setTargetNode(_targetNode);
- dest.setSourceNode(_sourceNode);
- dest.setLink(_link);
- dest.setAddressResolved(_isAddressResolved);
- return dest;
- }
-
- protected void setAutoDelete(boolean b)
- {
- _isAutoDelete = b;
- }
-
- protected void setDurable(boolean b)
- {
- _isDurable = b;
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/AMQHeadersExchange.java b/java/client/src/main/java/org/apache/qpid/client/AMQHeadersExchange.java
deleted file mode 100644
index b9e9a33cd6..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/AMQHeadersExchange.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.client;
-
-import org.apache.qpid.exchange.ExchangeDefaults;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.url.BindingURL;
-
-/**
- * A destination backed by a headers exchange
- */
-public class AMQHeadersExchange extends AMQDestination
-{
- public AMQHeadersExchange(BindingURL binding)
- {
- this(binding.getExchangeName());
- }
-
- public AMQHeadersExchange(String name)
- {
- this(new AMQShortString(name));
- }
-
- public AMQHeadersExchange(AMQShortString queueName)
- {
- super(queueName, ExchangeDefaults.HEADERS_EXCHANGE_CLASS, queueName, true, true, null);
- }
-
- public boolean isNameRequired()
- {
- //Not sure what the best approach is here, probably to treat this like a topic
- //and allow server to generate names. As it is AMQ specific it doesn't need to
- //fit the JMS API expectations so this is not as yet critical.
- return getAMQQueueName() == null;
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/AMQNoConsumersException.java b/java/client/src/main/java/org/apache/qpid/client/AMQNoConsumersException.java
deleted file mode 100644
index 08867b5de7..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/AMQNoConsumersException.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.client;
-
-import org.apache.qpid.AMQUndeliveredException;
-import org.apache.qpid.protocol.AMQConstant;
-
-/**
- * AMQNoConsumersException indicates failure to pass an immediate message to a consumer.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Represents failure to pass an immediate message to a consumer.
- * <tr><td>
- */
-public class AMQNoConsumersException extends AMQUndeliveredException
-{
- public AMQNoConsumersException(String msg, Object bounced, Throwable cause)
- {
- super(AMQConstant.NO_CONSUMERS, msg, bounced, cause);
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/AMQNoRouteException.java b/java/client/src/main/java/org/apache/qpid/client/AMQNoRouteException.java
deleted file mode 100644
index 42ed9c3df7..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/AMQNoRouteException.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.client;
-
-import org.apache.qpid.AMQUndeliveredException;
-import org.apache.qpid.protocol.AMQConstant;
-
-/**
- * AMQNoRouteException indicates that a mandatory message could not be routed.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Represents failure to route a mandatory message.
- * <tr><td>
- */
-public class AMQNoRouteException extends AMQUndeliveredException
-{
- public AMQNoRouteException(String msg, Object bounced, Throwable cause)
- {
- super(AMQConstant.NO_ROUTE, msg, bounced, cause);
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/AMQQueue.java b/java/client/src/main/java/org/apache/qpid/client/AMQQueue.java
deleted file mode 100644
index 5bd1bd629a..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/AMQQueue.java
+++ /dev/null
@@ -1,172 +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.client;
-
-import java.net.URISyntaxException;
-
-import javax.jms.Queue;
-
-import org.apache.qpid.exchange.ExchangeDefaults;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.url.BindingURL;
-
-public class AMQQueue extends AMQDestination implements Queue
-{
-
- public AMQQueue(String address) throws URISyntaxException
- {
- super(address);
- }
-
- /**
- * Create a reference to a non temporary queue using a BindingURL object.
- * Note this does not actually imply the queue exists.
- * @param binding a BindingURL object
- */
- public AMQQueue(BindingURL binding)
- {
- super(binding);
- }
-
- /**
- * Create a reference to a non temporary queue. Note this does not actually imply the queue exists.
- * @param name the name of the queue
- */
- public AMQQueue(AMQShortString exchangeName, String name)
- {
- this(exchangeName, new AMQShortString(name));
- }
-
-
- /**
- * Create a reference to a non temporary queue. Note this does not actually imply the queue exists.
- * @param name the name of the queue
- */
- public AMQQueue(AMQShortString exchangeName, AMQShortString name)
- {
- this(exchangeName, name, false);
- }
-
- public AMQQueue(AMQShortString exchangeName, AMQShortString routingKey, AMQShortString queueName)
- {
- super(exchangeName, ExchangeDefaults.DIRECT_EXCHANGE_CLASS, routingKey, false,
- false, queueName, false);
- }
-
- public AMQQueue(AMQShortString exchangeName, AMQShortString routingKey, AMQShortString queueName,AMQShortString[] bindingKeys)
- {
- super(exchangeName, ExchangeDefaults.DIRECT_EXCHANGE_CLASS, routingKey, false,
- false, queueName, false,bindingKeys);
- }
-
- /**
- * Create a reference to a non temporary queue. Note this does not actually imply the queue exists.
- * @param name the name of the queue
- */
- public AMQQueue(String exchangeName, String name)
- {
- this(new AMQShortString(exchangeName), new AMQShortString(name), false);
- }
-
-
- public AMQQueue(AMQConnection connection, String name)
- {
- this(connection.getDefaultQueueExchangeName(),name);
- }
-
- public AMQQueue(AMQConnection connection, String name, boolean temporary)
- {
- this(connection.getDefaultQueueExchangeName(), new AMQShortString(name),temporary);
- }
-
-
- /**
- * Create a queue with a specified name.
- *
- * @param name the destination name (used in the routing key)
- * @param temporary if true the broker will generate a queue name, also if true then the queue is autodeleted
- * and exclusive
- */
- public AMQQueue(String exchangeName, String name, boolean temporary)
- {
- this(new AMQShortString(exchangeName), new AMQShortString(name),temporary);
- }
-
-
- /**
- * Create a queue with a specified name.
- *
- * @param name the destination name (used in the routing key)
- * @param temporary if true the broker will generate a queue name, also if true then the queue is autodeleted
- * and exclusive
- */
- public AMQQueue(AMQShortString exchangeName, AMQShortString name, boolean temporary)
- {
- // queue name is set to null indicating that the broker assigns a name in the case of temporary queues
- // temporary queues are typically used as response queues
- this(exchangeName, name, temporary?null:name, temporary, temporary, !temporary);
-
- }
-
- /**
- * Create a reference to a queue. Note this does not actually imply the queue exists.
- * @param exchangeName the exchange name we want to send the message to
- * @param routingKey the routing key
- * @param queueName the queue name
- * @param exclusive true if the queue should only permit a single consumer
- * @param autoDelete true if the queue should be deleted automatically when the last consumers detaches
- */
- public AMQQueue(AMQShortString exchangeName, AMQShortString routingKey, AMQShortString queueName, boolean exclusive, boolean autoDelete)
- {
- this(exchangeName, routingKey, queueName, exclusive, autoDelete, false);
- }
-
- public AMQQueue(AMQShortString exchangeName, AMQShortString routingKey, AMQShortString queueName, boolean exclusive, boolean autoDelete, boolean durable)
- {
- this(exchangeName,routingKey,queueName,exclusive,autoDelete,durable,null);
- }
-
- public AMQQueue(AMQShortString exchangeName, AMQShortString routingKey, AMQShortString queueName, boolean exclusive, boolean autoDelete, boolean durable,AMQShortString[] bindingKeys)
- {
- super(exchangeName, ExchangeDefaults.DIRECT_EXCHANGE_CLASS, routingKey, exclusive,
- autoDelete, queueName, durable, bindingKeys);
- }
-
- public AMQShortString getRoutingKey()
- {
- //return getAMQQueueName();
- if (getAMQQueueName() != null && getAMQQueueName().equals(super.getRoutingKey()))
- {
- return getAMQQueueName();
- }
- else
- {
- return super.getRoutingKey();
- }
- }
-
- public boolean isNameRequired()
- {
- //If the name is null, we require one to be generated by the client so that it will#
- //remain valid if we failover (see BLZ-24)
- return getQueueName() == null;
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/AMQQueueBrowser.java b/java/client/src/main/java/org/apache/qpid/client/AMQQueueBrowser.java
deleted file mode 100644
index d96544adf8..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/AMQQueueBrowser.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.
- *
- */
-package org.apache.qpid.client;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.jms.IllegalStateException;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.Queue;
-import javax.jms.QueueBrowser;
-import java.util.ArrayList;
-import java.util.Enumeration;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-public class AMQQueueBrowser implements QueueBrowser
-{
- private static final Logger _logger = LoggerFactory.getLogger(AMQQueueBrowser.class);
-
- private AtomicBoolean _isClosed = new AtomicBoolean();
- private final AMQSession _session;
- private final AMQQueue _queue;
- private final ArrayList<BasicMessageConsumer> _consumers = new ArrayList<BasicMessageConsumer>();
- private final String _messageSelector;
-
- AMQQueueBrowser(AMQSession session, AMQQueue queue, String messageSelector) throws JMSException
- {
- _session = session;
- _queue = queue;
- _messageSelector = ((messageSelector == null) || (messageSelector.trim().length() == 0)) ? null : messageSelector;
- // Create Consumer to verify message selector.
- BasicMessageConsumer consumer =
- (BasicMessageConsumer) _session.createBrowserConsumer(_queue, _messageSelector, false);
- // Close this consumer as we are not looking to consume only to establish that, at least for now,
- // the QB can be created
- consumer.close();
- }
-
- public Queue getQueue() throws JMSException
- {
- checkState();
-
- return _queue;
- }
-
- private void checkState() throws JMSException
- {
- if (_isClosed.get())
- {
- throw new IllegalStateException("Queue Browser");
- }
-
- if (_session.isClosed())
- {
- throw new IllegalStateException("Session is closed");
- }
-
- }
-
- public String getMessageSelector() throws JMSException
- {
-
- checkState();
-
- return _messageSelector;
- }
-
- public Enumeration getEnumeration() throws JMSException
- {
- checkState();
- final BasicMessageConsumer consumer =
- (BasicMessageConsumer) _session.createBrowserConsumer(_queue, _messageSelector, false);
-
- _consumers.add(consumer);
-
- return new QueueBrowserEnumeration(consumer);
- }
-
- public void close() throws JMSException
- {
- for (BasicMessageConsumer consumer : _consumers)
- {
- consumer.close();
- }
-
- _consumers.clear();
- }
-
- private class QueueBrowserEnumeration implements Enumeration
- {
- Message _nextMessage;
- private BasicMessageConsumer _consumer;
-
- public QueueBrowserEnumeration(BasicMessageConsumer consumer) throws JMSException
- {
- _nextMessage = consumer == null ? null : consumer.receiveBrowse();
- _logger.info("QB:created with first element:" + _nextMessage);
- _consumer = consumer;
- }
-
- public boolean hasMoreElements()
- {
- _logger.info("QB:hasMoreElements:" + (_nextMessage != null));
- return (_nextMessage != null);
- }
-
- public Object nextElement()
- {
- Message msg = _nextMessage;
- try
- {
- _logger.info("QB:nextElement about to receive");
- _nextMessage = _consumer.receiveBrowse();
- _logger.info("QB:nextElement received:" + _nextMessage);
- }
- catch (JMSException e)
- {
- _logger.warn("Exception caught while queue browsing", e);
- _nextMessage = null;
- }
- return msg;
- }
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/AMQQueueSessionAdaptor.java b/java/client/src/main/java/org/apache/qpid/client/AMQQueueSessionAdaptor.java
deleted file mode 100644
index a8c83d8868..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/AMQQueueSessionAdaptor.java
+++ /dev/null
@@ -1,204 +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.client;
-
-import java.io.Serializable;
-
-import javax.jms.BytesMessage;
-import javax.jms.Destination;
-import javax.jms.IllegalStateException;
-import javax.jms.JMSException;
-import javax.jms.MapMessage;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageListener;
-import javax.jms.MessageProducer;
-import javax.jms.ObjectMessage;
-import javax.jms.Queue;
-import javax.jms.QueueBrowser;
-import javax.jms.QueueReceiver;
-import javax.jms.QueueSender;
-import javax.jms.QueueSession;
-import javax.jms.Session;
-import javax.jms.StreamMessage;
-import javax.jms.TemporaryQueue;
-import javax.jms.TemporaryTopic;
-import javax.jms.TextMessage;
-import javax.jms.Topic;
-import javax.jms.TopicSubscriber;
-
-/**
- * Need this adaptor class to conform to JMS spec and throw IllegalStateException
- * from createDurableSubscriber, unsubscribe, createTopic & createTemporaryTopic
- */
-public class AMQQueueSessionAdaptor implements QueueSession, AMQSessionAdapter
-{
- //holds a session for delegation
- protected final AMQSession _session;
-
- /**
- * Construct an adaptor with a session to wrap
- * @param session
- */
- public AMQQueueSessionAdaptor(Session session)
- {
- _session = (AMQSession) session;
- }
-
- public TemporaryQueue createTemporaryQueue() throws JMSException {
- return _session.createTemporaryQueue();
- }
-
- public Queue createQueue(String string) throws JMSException {
- return _session.createQueue(string);
- }
-
- public QueueReceiver createReceiver(Queue queue) throws JMSException {
- return _session.createReceiver(queue);
- }
-
- public QueueReceiver createReceiver(Queue queue, String string) throws JMSException {
- return _session.createReceiver(queue, string);
- }
-
- public QueueSender createSender(Queue queue) throws JMSException {
- return _session.createSender(queue);
- }
-
- public QueueBrowser createBrowser(Queue queue) throws JMSException {
- return _session.createBrowser(queue);
- }
-
- public QueueBrowser createBrowser(Queue queue, String string) throws JMSException {
- return _session.createBrowser(queue, string);
- }
-
- public BytesMessage createBytesMessage() throws JMSException {
- return _session.createBytesMessage();
- }
-
- public MapMessage createMapMessage() throws JMSException {
- return _session.createMapMessage();
- }
-
- public Message createMessage() throws JMSException {
- return _session.createMessage();
- }
-
- public ObjectMessage createObjectMessage() throws JMSException {
- return _session.createObjectMessage();
- }
-
- public ObjectMessage createObjectMessage(Serializable serializable) throws JMSException {
- return _session.createObjectMessage(serializable);
- }
-
- public StreamMessage createStreamMessage() throws JMSException {
- return _session.createStreamMessage();
- }
-
- public TextMessage createTextMessage() throws JMSException {
- return _session.createTextMessage();
- }
-
- public TextMessage createTextMessage(String string) throws JMSException {
- return _session.createTextMessage(string);
- }
-
- public boolean getTransacted() throws JMSException {
- return _session.getTransacted();
- }
-
- public int getAcknowledgeMode() throws JMSException {
- return _session.getAcknowledgeMode();
- }
-
- public void commit() throws JMSException {
- _session.commit();
- }
-
- public void rollback() throws JMSException {
- _session.rollback();
- }
-
- public void close() throws JMSException {
- _session.close();
- }
-
- public void recover() throws JMSException {
- _session.recover();
- }
-
- public MessageListener getMessageListener() throws JMSException {
- return _session.getMessageListener();
- }
-
- public void setMessageListener(MessageListener messageListener) throws JMSException {
- _session.setMessageListener(messageListener);
- }
-
- public void run() {
- _session.run();
- }
-
- public MessageProducer createProducer(Destination destination) throws JMSException {
- return _session.createProducer(destination);
- }
-
- public MessageConsumer createConsumer(Destination destination) throws JMSException {
- return _session.createConsumer(destination);
- }
-
- public MessageConsumer createConsumer(Destination destination, String string) throws JMSException {
- return _session.createConsumer(destination,string);
- }
-
- public MessageConsumer createConsumer(Destination destination, String string, boolean b) throws JMSException {
- return _session.createConsumer(destination,string,b);
- }
-
- //The following methods cannot be called from a QueueSession as per JMS spec
-
- public Topic createTopic(String string) throws JMSException {
- throw new IllegalStateException("Cannot call createTopic from QueueSession");
- }
-
- public TopicSubscriber createDurableSubscriber(Topic topic, String string) throws JMSException {
- throw new IllegalStateException("Cannot call createDurableSubscriber from QueueSession");
- }
-
- public TopicSubscriber createDurableSubscriber(Topic topic, String string, String string1, boolean b) throws JMSException {
- throw new IllegalStateException("Cannot call createDurableSubscriber from QueueSession");
- }
-
- public TemporaryTopic createTemporaryTopic() throws JMSException {
- throw new IllegalStateException("Cannot call createTemporaryTopic from QueueSession");
- }
-
- public void unsubscribe(String string) throws JMSException {
- throw new IllegalStateException("Cannot call unsubscribe from QueueSession");
- }
-
- public AMQSession getSession()
- {
- return _session;
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/AMQSession.java b/java/client/src/main/java/org/apache/qpid/client/AMQSession.java
deleted file mode 100644
index 25562cfff7..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/AMQSession.java
+++ /dev/null
@@ -1,3489 +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.client;
-
-import java.io.Serializable;
-import java.net.URISyntaxException;
-import java.text.MessageFormat;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentLinkedQueue;
-import java.util.concurrent.CopyOnWriteArrayList;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.concurrent.atomic.AtomicLong;
-import java.util.concurrent.locks.Lock;
-import java.util.concurrent.locks.ReentrantLock;
-
-import javax.jms.BytesMessage;
-import javax.jms.Destination;
-import javax.jms.IllegalStateException;
-import javax.jms.InvalidDestinationException;
-import javax.jms.InvalidSelectorException;
-import javax.jms.JMSException;
-import javax.jms.MapMessage;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageListener;
-import javax.jms.MessageProducer;
-import javax.jms.ObjectMessage;
-import javax.jms.Queue;
-import javax.jms.QueueBrowser;
-import javax.jms.QueueReceiver;
-import javax.jms.QueueSender;
-import javax.jms.QueueSession;
-import javax.jms.StreamMessage;
-import javax.jms.TemporaryQueue;
-import javax.jms.TemporaryTopic;
-import javax.jms.TextMessage;
-import javax.jms.Topic;
-import javax.jms.TopicPublisher;
-import javax.jms.TopicSession;
-import javax.jms.TopicSubscriber;
-import javax.jms.TransactionRolledBackException;
-
-import org.apache.qpid.AMQChannelClosedException;
-import org.apache.qpid.AMQDisconnectedException;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.AMQInvalidArgumentException;
-import org.apache.qpid.AMQInvalidRoutingKeyException;
-import org.apache.qpid.client.AMQDestination.AddressOption;
-import org.apache.qpid.client.AMQDestination.DestSyntax;
-import org.apache.qpid.client.failover.FailoverException;
-import org.apache.qpid.client.failover.FailoverNoopSupport;
-import org.apache.qpid.client.failover.FailoverProtectedOperation;
-import org.apache.qpid.client.failover.FailoverRetrySupport;
-import org.apache.qpid.client.message.AMQMessageDelegateFactory;
-import org.apache.qpid.client.message.AMQPEncodedMapMessage;
-import org.apache.qpid.client.message.AbstractJMSMessage;
-import org.apache.qpid.client.message.CloseConsumerMessage;
-import org.apache.qpid.client.message.JMSBytesMessage;
-import org.apache.qpid.client.message.JMSMapMessage;
-import org.apache.qpid.client.message.JMSObjectMessage;
-import org.apache.qpid.client.message.JMSStreamMessage;
-import org.apache.qpid.client.message.JMSTextMessage;
-import org.apache.qpid.client.message.MessageFactoryRegistry;
-import org.apache.qpid.client.message.UnprocessedMessage;
-import org.apache.qpid.client.protocol.AMQProtocolHandler;
-import org.apache.qpid.client.state.AMQState;
-import org.apache.qpid.client.state.AMQStateManager;
-import org.apache.qpid.client.util.FlowControllingBlockingQueue;
-import org.apache.qpid.common.AMQPFilterTypes;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.FieldTable;
-import org.apache.qpid.framing.FieldTableFactory;
-import org.apache.qpid.framing.MethodRegistry;
-import org.apache.qpid.jms.Session;
-import org.apache.qpid.thread.Threading;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td>
- * </table>
- *
- * @todo Different FailoverSupport implementation are needed on the same method call, in different situations. For
- * example, when failing-over and reestablishing the bindings, the bind cannot be interrupted by a second
- * fail-over, if it fails with an exception, the fail-over process should also fail. When binding outside of
- * the fail-over process, the retry handler could be used to automatically retry the operation once the connection
- * has been reestablished. All fail-over protected operations should be placed in private methods, with
- * FailoverSupport passed in by the caller to provide the correct support for the calling context. Sometimes the
- * fail-over process sets a nowait flag and uses an async method call instead.
- * @todo Two new objects created on every failover supported method call. Consider more efficient ways of doing this,
- * after looking at worse bottlenecks first.
- */
-public abstract class AMQSession<C extends BasicMessageConsumer, P extends BasicMessageProducer> extends Closeable implements Session, QueueSession, TopicSession
-{
- public static final class IdToConsumerMap<C extends BasicMessageConsumer>
- {
- private final BasicMessageConsumer[] _fastAccessConsumers = new BasicMessageConsumer[16];
- private final ConcurrentHashMap<Integer, C> _slowAccessConsumers = new ConcurrentHashMap<Integer, C>();
-
- public C get(int id)
- {
- if ((id & 0xFFFFFFF0) == 0)
- {
- return (C) _fastAccessConsumers[id];
- }
- else
- {
- return _slowAccessConsumers.get(id);
- }
- }
-
- public C put(int id, C consumer)
- {
- C oldVal;
- if ((id & 0xFFFFFFF0) == 0)
- {
- oldVal = (C) _fastAccessConsumers[id];
- _fastAccessConsumers[id] = consumer;
- }
- else
- {
- oldVal = _slowAccessConsumers.put(id, consumer);
- }
-
- return oldVal;
-
- }
-
- public C remove(int id)
- {
- C consumer;
- if ((id & 0xFFFFFFF0) == 0)
- {
- consumer = (C) _fastAccessConsumers[id];
- _fastAccessConsumers[id] = null;
- }
- else
- {
- consumer = _slowAccessConsumers.remove(id);
- }
-
- return consumer;
-
- }
-
- public Collection<C> values()
- {
- ArrayList<C> values = new ArrayList<C>();
-
- for (int i = 0; i < 16; i++)
- {
- if (_fastAccessConsumers[i] != null)
- {
- values.add((C) _fastAccessConsumers[i]);
- }
- }
- values.addAll(_slowAccessConsumers.values());
-
- return values;
- }
-
- public void clear()
- {
- _slowAccessConsumers.clear();
- for (int i = 0; i < 16; i++)
- {
- _fastAccessConsumers[i] = null;
- }
- }
- }
-
- final AMQSession<C, P> _thisSession = this;
-
- /** Used for debugging. */
- private static final Logger _logger = LoggerFactory.getLogger(AMQSession.class);
-
- /**
- * The default value for immediate flag used by producers created by this session is false. That is, a consumer does
- * not need to be attached to a queue.
- */
- protected final boolean DEFAULT_IMMEDIATE = Boolean.parseBoolean(System.getProperty("qpid.default_immediate", "false"));
-
- /**
- * The default value for mandatory flag used by producers created by this session is true. That is, server will not
- * silently drop messages where no queue is connected to the exchange for the message.
- */
- protected final boolean DEFAULT_MANDATORY = Boolean.parseBoolean(System.getProperty("qpid.default_mandatory", "true"));
-
- protected final boolean DEFAULT_WAIT_ON_SEND = Boolean.parseBoolean(System.getProperty("qpid.default_wait_on_send", "false"));
-
- /**
- * The period to wait while flow controlled before sending a log message confirming that the session is still
- * waiting on flow control being revoked
- */
- protected final long FLOW_CONTROL_WAIT_PERIOD = Long.getLong("qpid.flow_control_wait_notify_period",5000L);
-
- /**
- * The period to wait while flow controlled before declaring a failure
- */
- public static final long DEFAULT_FLOW_CONTROL_WAIT_FAILURE = 120000L;
- protected final long FLOW_CONTROL_WAIT_FAILURE = Long.getLong("qpid.flow_control_wait_failure",
- DEFAULT_FLOW_CONTROL_WAIT_FAILURE);
-
- protected final boolean DECLARE_QUEUES =
- Boolean.parseBoolean(System.getProperty("qpid.declare_queues", "true"));
-
- protected final boolean DECLARE_EXCHANGES =
- Boolean.parseBoolean(System.getProperty("qpid.declare_exchanges", "true"));
-
- protected final boolean USE_AMQP_ENCODED_MAP_MESSAGE;
-
- /** System property to enable strict AMQP compliance. */
- public static final String STRICT_AMQP = "STRICT_AMQP";
-
- /** Strict AMQP default setting. */
- public static final String STRICT_AMQP_DEFAULT = "false";
-
- /** System property to enable failure if strict AMQP compliance is violated. */
- public static final String STRICT_AMQP_FATAL = "STRICT_AMQP_FATAL";
-
- /** Strickt AMQP failure default. */
- public static final String STRICT_AMQP_FATAL_DEFAULT = "true";
-
- /** System property to enable immediate message prefetching. */
- public static final String IMMEDIATE_PREFETCH = "IMMEDIATE_PREFETCH";
-
- /** Immediate message prefetch default. */
- public static final String IMMEDIATE_PREFETCH_DEFAULT = "false";
-
- /** The connection to which this session belongs. */
- protected AMQConnection _connection;
-
- /** Used to indicate whether or not this is a transactional session. */
- protected boolean _transacted;
-
- /** Holds the sessions acknowledgement mode. */
- protected final int _acknowledgeMode;
-
- /** Holds this session unique identifier, used to distinguish it from other sessions. */
- protected int _channelId;
-
- private int _ticket;
-
- /** Holds the high mark for prefetched message, at which the session is suspended. */
- private int _prefetchHighMark;
-
- /** Holds the low mark for prefetched messages, below which the session is resumed. */
- private int _prefetchLowMark;
-
- /** Holds the message listener, if any, which is attached to this session. */
- private MessageListener _messageListener = null;
-
- /** Used to indicate that this session has been started at least once. */
- private AtomicBoolean _startedAtLeastOnce = new AtomicBoolean(false);
-
- /**
- * Used to reference durable subscribers so that requests for unsubscribe can be handled correctly. Note this only
- * keeps a record of subscriptions which have been created in the current instance. It does not remember
- * subscriptions between executions of the client.
- */
- protected final ConcurrentHashMap<String, TopicSubscriberAdaptor<C>> _subscriptions =
- new ConcurrentHashMap<String, TopicSubscriberAdaptor<C>>();
-
- /**
- * Holds a mapping from message consumers to their identifying names, so that their subscriptions may be looked
- * up in the {@link #_subscriptions} map.
- */
- protected final ConcurrentHashMap<C, String> _reverseSubscriptionMap = new ConcurrentHashMap<C, String>();
-
- /**
- * Locks to keep access to subscriber details atomic.
- * <p>
- * Added for QPID2418
- */
- protected final Lock _subscriberDetails = new ReentrantLock(true);
- protected final Lock _subscriberAccess = new ReentrantLock(true);
-
- /**
- * Used to hold incoming messages.
- *
- * @todo Weaken the type once {@link FlowControllingBlockingQueue} implements Queue.
- */
- protected final FlowControllingBlockingQueue _queue;
-
- /** Holds the highest received delivery tag. */
- private final AtomicLong _highestDeliveryTag = new AtomicLong(-1);
- private final AtomicLong _rollbackMark = new AtomicLong(-1);
-
- /** All the not yet acknowledged message tags */
- protected ConcurrentLinkedQueue<Long> _unacknowledgedMessageTags = new ConcurrentLinkedQueue<Long>();
-
- /** All the delivered message tags */
- protected ConcurrentLinkedQueue<Long> _deliveredMessageTags = new ConcurrentLinkedQueue<Long>();
-
- /** Holds the dispatcher thread for this session. */
- protected Dispatcher _dispatcher;
-
- protected Thread _dispatcherThread;
-
- /** Holds the message factory factory for this session. */
- protected MessageFactoryRegistry _messageFactoryRegistry;
-
- /** Holds all of the producers created by this session, keyed by their unique identifiers. */
- private Map<Long, MessageProducer> _producers = new ConcurrentHashMap<Long, MessageProducer>();
-
- /**
- * Used as a source of unique identifiers so that the consumers can be tagged to match them to BasicConsume
- * methods.
- */
- private int _nextTag = 1;
-
- /**
- * Maps from identifying tags to message consumers, in order to pass dispatch incoming messages to the right
- * consumer.
- */
- protected final IdToConsumerMap<C> _consumers = new IdToConsumerMap<C>();
-
- /**
- * Contains a list of consumers which have been removed but which might still have
- * messages to acknowledge, eg in client ack or transacted modes
- */
- private CopyOnWriteArrayList<C> _removedConsumers = new CopyOnWriteArrayList<C>();
-
- /** Provides a count of consumers on destinations, in order to be able to know if a destination has consumers. */
- private ConcurrentHashMap<Destination, AtomicInteger> _destinationConsumerCount =
- new ConcurrentHashMap<Destination, AtomicInteger>();
-
- /**
- * Used as a source of unique identifiers for producers within the session.
- *
- * <p/> Access to this id does not require to be synchronized since according to the JMS specification only one
- * thread of control is allowed to create producers for any given session instance.
- */
- private long _nextProducerId;
-
- /**
- * Set when recover is called. This is to handle the case where recover() is called by application code during
- * onMessage() processing to ensure that an auto ack is not sent.
- */
- private boolean _inRecovery;
-
- /** Used to indicates that the connection to which this session belongs, has been stopped. */
- private boolean _connectionStopped;
-
- /** Used to indicate that this session has a message listener attached to it. */
- private boolean _hasMessageListeners;
-
- /** Used to indicate that this session has been suspended. */
- private boolean _suspended;
-
- /**
- * Used to protect the suspension of this session, so that critical code can be executed during suspension,
- * without the session being resumed by other threads.
- */
- private final Object _suspensionLock = new Object();
-
- /**
- * Used to ensure that only the first call to start the dispatcher can unsuspend the channel.
- *
- * @todo This is accessed only within a synchronized method, so does not need to be atomic.
- */
- protected final AtomicBoolean _firstDispatcher = new AtomicBoolean(true);
-
- /** Used to indicate that the session should start pre-fetching messages as soon as it is started. */
- protected final boolean _immediatePrefetch;
-
- /** Indicates that warnings should be generated on violations of the strict AMQP. */
- protected final boolean _strictAMQP;
-
- /** Indicates that runtime exceptions should be generated on vilations of the strict AMQP. */
- protected final boolean _strictAMQPFATAL;
- private final Object _messageDeliveryLock = new Object();
-
- /** Session state : used to detect if commit is a) required b) allowed , i.e. does the tx span failover. */
- private boolean _dirty;
- /** Has failover occured on this session with outstanding actions to commit? */
- private boolean _failedOverDirty;
-
- private static final class FlowControlIndicator
- {
- private volatile boolean _flowControl = true;
-
- public synchronized void setFlowControl(boolean flowControl)
- {
- _flowControl = flowControl;
- notify();
- }
-
- public boolean getFlowControl()
- {
- return _flowControl;
- }
- }
-
- /** Flow control */
- private FlowControlIndicator _flowControl = new FlowControlIndicator();
-
- /**
- * Creates a new session on a connection.
- *
- * @param con The connection on which to create the session.
- * @param channelId The unique identifier for the session.
- * @param transacted Indicates whether or not the session is transactional.
- * @param acknowledgeMode The acknowledgement mode for the session.
- * @param messageFactoryRegistry The message factory factory for the session.
- * @param defaultPrefetchHighMark The maximum number of messages to prefetched before suspending the session.
- * @param defaultPrefetchLowMark The number of prefetched messages at which to resume the session.
- */
- protected AMQSession(AMQConnection con, int channelId, boolean transacted, int acknowledgeMode,
- MessageFactoryRegistry messageFactoryRegistry, int defaultPrefetchHighMark, int defaultPrefetchLowMark)
- {
- USE_AMQP_ENCODED_MAP_MESSAGE = con == null ? true : !con.isUseLegacyMapMessageFormat();
- _strictAMQP = Boolean.parseBoolean(System.getProperties().getProperty(STRICT_AMQP, STRICT_AMQP_DEFAULT));
- _strictAMQPFATAL =
- Boolean.parseBoolean(System.getProperties().getProperty(STRICT_AMQP_FATAL, STRICT_AMQP_FATAL_DEFAULT));
- _immediatePrefetch =
- _strictAMQP
- || Boolean.parseBoolean(System.getProperties().getProperty(IMMEDIATE_PREFETCH, IMMEDIATE_PREFETCH_DEFAULT));
-
- _connection = con;
- _transacted = transacted;
- if (transacted)
- {
- _acknowledgeMode = javax.jms.Session.SESSION_TRANSACTED;
- }
- else
- {
- _acknowledgeMode = acknowledgeMode;
- }
-
- _channelId = channelId;
- _messageFactoryRegistry = messageFactoryRegistry;
- _prefetchHighMark = defaultPrefetchHighMark;
- _prefetchLowMark = defaultPrefetchLowMark;
-
- if (_acknowledgeMode == NO_ACKNOWLEDGE)
- {
- _queue =
- new FlowControllingBlockingQueue(_prefetchHighMark, _prefetchLowMark,
- new FlowControllingBlockingQueue.ThresholdListener()
- {
- private final AtomicBoolean _suspendState = new AtomicBoolean();
-
- public void aboveThreshold(int currentValue)
- {
- // If the session has been closed don't waste time creating a thread to do
- // flow control
- if (!(_thisSession.isClosed() || _thisSession.isClosing()))
- {
- // Only execute change if previous state
- // was False
- if (!_suspendState.getAndSet(true))
- {
- if (_logger.isDebugEnabled())
- {
- _logger.debug(
- "Above threshold(" + _prefetchHighMark
- + ") so suspending channel. Current value is " + currentValue);
- }
- try
- {
- Threading.getThreadFactory().createThread(new SuspenderRunner(_suspendState)).start();
- }
- catch (Exception e)
- {
- throw new RuntimeException("Failed to create thread", e);
- }
- }
- }
- }
-
- public void underThreshold(int currentValue)
- {
- // If the session has been closed don't waste time creating a thread to do
- // flow control
- if (!(_thisSession.isClosed() || _thisSession.isClosing()))
- {
- // Only execute change if previous state
- // was true
- if (_suspendState.getAndSet(false))
- {
- if (_logger.isDebugEnabled())
- {
-
- _logger.debug(
- "Below threshold(" + _prefetchLowMark
- + ") so unsuspending channel. Current value is " + currentValue);
- }
- try
- {
- Threading.getThreadFactory().createThread(new SuspenderRunner(_suspendState)).start();
- }
- catch (Exception e)
- {
- throw new RuntimeException("Failed to create thread", e);
- }
- }
- }
- }
- });
- }
- else
- {
- _queue = new FlowControllingBlockingQueue(_prefetchHighMark, null);
- }
-
- // Add creation logging to tie in with the existing close logging
- if (_logger.isInfoEnabled())
- {
- _logger.info("Created session:" + this);
- }
- }
-
- /**
- * Creates a new session on a connection with the default message factory factory.
- *
- * @param con The connection on which to create the session.
- * @param channelId The unique identifier for the session.
- * @param transacted Indicates whether or not the session is transactional.
- * @param acknowledgeMode The acknowledgement mode for the session.
- * @param defaultPrefetchHigh The maximum number of messages to prefetched before suspending the session.
- * @param defaultPrefetchLow The number of prefetched messages at which to resume the session.
- */
- AMQSession(AMQConnection con, int channelId, boolean transacted, int acknowledgeMode, int defaultPrefetchHigh,
- int defaultPrefetchLow)
- {
- this(con, channelId, transacted, acknowledgeMode, MessageFactoryRegistry.newDefaultRegistry(), defaultPrefetchHigh,
- defaultPrefetchLow);
- }
-
- // ===== JMS Session methods.
-
- /**
- * Closes the session with no timeout.
- *
- * @throws JMSException If the JMS provider fails to close the session due to some internal error.
- */
- public void close() throws JMSException
- {
- close(-1);
- }
-
- public abstract AMQException getLastException();
-
- public void checkNotClosed() throws JMSException
- {
- try
- {
- super.checkNotClosed();
- }
- catch (IllegalStateException ise)
- {
- AMQException ex = getLastException();
- if (ex != null)
- {
- IllegalStateException ssnClosed = new IllegalStateException(
- "Session has been closed", ex.getErrorCode().toString());
-
- ssnClosed.setLinkedException(ex);
- ssnClosed.initCause(ex);
- throw ssnClosed;
- }
- else
- {
- throw ise;
- }
- }
- }
-
- public BytesMessage createBytesMessage() throws JMSException
- {
- checkNotClosed();
- JMSBytesMessage msg = new JMSBytesMessage(getMessageDelegateFactory());
- msg.setAMQSession(this);
- return msg;
- }
-
- /**
- * Acknowledges all unacknowledged messages on the session, for all message consumers on the session.
- *
- * @throws IllegalStateException If the session is closed.
- */
- public void acknowledge() throws IllegalStateException
- {
- if (isClosed())
- {
- throw new IllegalStateException("Session is already closed");
- }
- else if (hasFailedOver())
- {
- throw new IllegalStateException("has failed over");
- }
-
- while (true)
- {
- Long tag = _unacknowledgedMessageTags.poll();
- if (tag == null)
- {
- break;
- }
- acknowledgeMessage(tag, false);
- }
- }
-
- /**
- * Acknowledge one or many messages.
- *
- * @param deliveryTag The tag of the last message to be acknowledged.
- * @param multiple <tt>true</tt> to acknowledge all messages up to and including the one specified by the
- * delivery tag, <tt>false</tt> to just acknowledge that message.
- *
- * @todo Be aware of possible changes to parameter order as versions change.
- */
- public abstract void acknowledgeMessage(long deliveryTag, boolean multiple);
-
- public MethodRegistry getMethodRegistry()
- {
- MethodRegistry methodRegistry = getProtocolHandler().getMethodRegistry();
- return methodRegistry;
- }
-
- /**
- * Binds the named queue, with the specified routing key, to the named exchange.
- *
- * <p/>Note that this operation automatically retries in the event of fail-over.
- *
- * @param queueName The name of the queue to bind.
- * @param routingKey The routing key to bind the queue with.
- * @param arguments Additional arguments.
- * @param exchangeName The exchange to bind the queue on.
- *
- * @throws AMQException If the queue cannot be bound for any reason.
- * @todo Be aware of possible changes to parameter order as versions change.
- * @todo Document the additional arguments that may be passed in the field table. Are these for headers exchanges?
- */
- public void bindQueue(final AMQShortString queueName, final AMQShortString routingKey, final FieldTable arguments,
- final AMQShortString exchangeName, final AMQDestination destination) throws AMQException
- {
- bindQueue(queueName, routingKey, arguments, exchangeName, destination, false);
- }
-
- public void bindQueue(final AMQShortString queueName, final AMQShortString routingKey, final FieldTable arguments,
- final AMQShortString exchangeName, final AMQDestination destination,
- final boolean nowait) throws AMQException
- {
- /*new FailoverRetrySupport<Object, AMQException>(new FailoverProtectedOperation<Object, AMQException>()*/
- new FailoverNoopSupport<Object, AMQException>(new FailoverProtectedOperation<Object, AMQException>()
- {
- public Object execute() throws AMQException, FailoverException
- {
- sendQueueBind(queueName, routingKey, arguments, exchangeName, destination, nowait);
- return null;
- }
- }, _connection).execute();
- }
-
- public void addBindingKey(C consumer, AMQDestination amqd, String routingKey) throws AMQException
- {
- if (consumer.getQueuename() != null)
- {
- bindQueue(consumer.getQueuename(), new AMQShortString(routingKey), new FieldTable(), amqd.getExchangeName(), amqd);
- }
- }
-
- public abstract void sendQueueBind(final AMQShortString queueName, final AMQShortString routingKey, final FieldTable arguments,
- final AMQShortString exchangeName, AMQDestination destination,
- final boolean nowait) throws AMQException, FailoverException;
-
- /**
- * Closes the session.
- *
- * <p/>Note that this operation succeeds automatically if a fail-over interrupts the synchronous request to close
- * the channel. This is because the channel is marked as closed before the request to close it is made, so the
- * fail-over should not re-open it.
- *
- * @param timeout The timeout in milliseconds to wait for the session close acknowledgement from the broker.
- *
- * @throws JMSException If the JMS provider fails to close the session due to some internal error.
- * @todo Be aware of possible changes to parameter order as versions change.
- * @todo Not certain about the logic of ignoring the failover exception, because the channel won't be
- * re-opened. May need to examine this more carefully.
- * @todo Note that taking the failover mutex doesn't prevent this operation being interrupted by a failover,
- * because the failover process sends the failover event before acquiring the mutex itself.
- */
- public void close(long timeout) throws JMSException
- {
- close(timeout, true);
- }
-
- private void close(long timeout, boolean sendClose) throws JMSException
- {
- if (_logger.isInfoEnabled())
- {
- // StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
- _logger.info("Closing session: " + this); // + ":"
- // Arrays.asList(stackTrace).subList(3, stackTrace.length - 1));
- }
-
- // Ensure we only try and close an open session.
- if (!_closed.getAndSet(true))
- {
- _closing.set(true);
- synchronized (getFailoverMutex())
- {
- // We must close down all producers and consumers in an orderly fashion. This is the only method
- // that can be called from a different thread of control from the one controlling the session.
- synchronized (_messageDeliveryLock)
- {
- // we pass null since this is not an error case
- closeProducersAndConsumers(null);
-
- try
- {
- // If the connection is open or we are in the process
- // of closing the connection then send a cance
- // no point otherwise as the connection will be gone
- if (!_connection.isClosed() || _connection.isClosing())
- {
- if (sendClose)
- {
- sendClose(timeout);
- }
- }
- }
- catch (AMQException e)
- {
- JMSException jmse = new JMSException("Error closing session: " + e);
- jmse.setLinkedException(e);
- jmse.initCause(e);
- throw jmse;
- }
- // This is ignored because the channel is already marked as closed so the fail-over process will
- // not re-open it.
- catch (FailoverException e)
- {
- _logger.debug(
- "Got FailoverException during channel close, ignored as channel already marked as closed.");
- }
- finally
- {
- _connection.deregisterSession(_channelId);
- }
- }
- }
- }
- }
-
- public abstract void sendClose(long timeout) throws AMQException, FailoverException;
-
- /**
- * Called when the server initiates the closure of the session unilaterally.
- *
- * @param e the exception that caused this session to be closed. Null causes the
- */
- public void closed(Throwable e) throws JMSException
- {
- // This method needs to be improved. Throwables only arrive here from the mina : exceptionRecived
- // calls through connection.closeAllSessions which is also called by the public connection.close()
- // with a null cause
- // When we are closing the Session due to a protocol session error we simply create a new AMQException
- // with the correct error code and text this is cleary WRONG as the instanceof check below will fail.
- // We need to determin here if the connection should be
-
- if (e instanceof AMQDisconnectedException)
- {
- if (_dispatcher != null)
- {
- // Failover failed and ain't coming back. Knife the dispatcher.
- _dispatcherThread.interrupt();
- }
-
- }
-
- //if we don't have an exception then we can perform closing operations
- _closing.set(e == null);
-
- if (!_closed.getAndSet(true))
- {
- synchronized (_messageDeliveryLock)
- {
- // An AMQException has an error code and message already and will be passed in when closure occurs as a
- // result of a channel close request
- AMQException amqe;
- if (e instanceof AMQException)
- {
- amqe = (AMQException) e;
- }
- else
- {
- amqe = new AMQException("Closing session forcibly", e);
- }
-
- _connection.deregisterSession(_channelId);
- closeProducersAndConsumers(amqe);
- }
- }
- }
-
- /**
- * Commits all messages done in this transaction and releases any locks currently held.
- *
- * <p/>If the commit fails, because the commit itself is interrupted by a fail-over between requesting that the
- * commit be done, and receiving an acknowledgement that it has been done, then a JMSException will be thrown.
- * The client will be unable to determine whether or not the commit actually happened on the broker in this case.
- *
- * @throws JMSException If the JMS provider fails to commit the transaction due to some internal error. This does
- * not mean that the commit is known to have failed, merely that it is not known whether it
- * failed or not.
- * @todo Be aware of possible changes to parameter order as versions change.
- */
- public void commit() throws JMSException
- {
- checkTransacted();
-
- try
- {
- //Check that we are clean to commit.
- if (_failedOverDirty)
- {
- rollback();
-
- throw new TransactionRolledBackException("Connection failover has occured since last send. " +
- "Forced rollback");
- }
-
-
- // Acknowledge all delivered messages
- while (true)
- {
- Long tag = _deliveredMessageTags.poll();
- if (tag == null)
- {
- break;
- }
-
- acknowledgeMessage(tag, false);
- }
- // Commits outstanding messages and acknowledgments
- sendCommit();
- markClean();
- }
- catch (AMQException e)
- {
- throw new JMSAMQException("Failed to commit: " + e.getMessage() + ":" + e.getCause(), e);
- }
- catch (FailoverException e)
- {
- throw new JMSAMQException("Fail-over interrupted commit. Status of the commit is uncertain.", e);
- }
- }
-
- public abstract void sendCommit() throws AMQException, FailoverException;
-
-
- public void confirmConsumerCancelled(int consumerTag)
- {
-
- // Remove the consumer from the map
- C consumer = _consumers.get(consumerTag);
- if (consumer != null)
- {
- if (!consumer.isNoConsume()) // Normal Consumer
- {
- // Clean the Maps up first
- // Flush any pending messages for this consumerTag
- if (_dispatcher != null)
- {
- _logger.info("Dispatcher is not null");
- }
- else
- {
- _logger.info("Dispatcher is null so created stopped dispatcher");
- startDispatcherIfNecessary(true);
- }
-
- _dispatcher.rejectPending(consumer);
- }
- else // Queue Browser
- {
- // Just close the consumer
- // fixme the CancelOK is being processed before the arriving messages..
- // The dispatcher is still to process them so the server sent in order but the client
- // has yet to receive before the close comes in.
-
- // consumer.markClosed();
-
- if (consumer.isAutoClose())
- {
- // There is a small window where the message is between the two queues in the dispatcher.
- if (consumer.isClosed())
- {
- if (_logger.isInfoEnabled())
- {
- _logger.info("Closing consumer:" + consumer.debugIdentity());
- }
-
- deregisterConsumer(consumer);
- }
- else
- {
- _queue.add(new CloseConsumerMessage(consumer));
- }
- }
- }
- }
- }
-
- public QueueBrowser createBrowser(Queue queue) throws JMSException
- {
- if (isStrictAMQP())
- {
- throw new UnsupportedOperationException();
- }
-
- return createBrowser(queue, null);
- }
-
- public QueueBrowser createBrowser(Queue queue, String messageSelector) throws JMSException
- {
- if (isStrictAMQP())
- {
- throw new UnsupportedOperationException();
- }
-
- checkNotClosed();
- checkValidQueue(queue);
-
- return new AMQQueueBrowser(this, (AMQQueue) queue, messageSelector);
- }
-
- public MessageConsumer createBrowserConsumer(Destination destination, String messageSelector, boolean noLocal)
- throws JMSException
- {
- checkValidDestination(destination);
-
- return createConsumerImpl(destination, _prefetchHighMark, _prefetchLowMark, noLocal, false,
- messageSelector, null, true, true);
- }
-
- public MessageConsumer createConsumer(Destination destination) throws JMSException
- {
- checkValidDestination(destination);
-
- return createConsumerImpl(destination, _prefetchHighMark, _prefetchLowMark, false, (destination instanceof Topic), null, null,
- ((destination instanceof AMQDestination) && ((AMQDestination)destination).isBrowseOnly()), false);
- }
-
- public C createExclusiveConsumer(Destination destination) throws JMSException
- {
- checkValidDestination(destination);
-
- return createConsumerImpl(destination, _prefetchHighMark, _prefetchLowMark, false, true, null, null,
- ((destination instanceof AMQDestination) && ((AMQDestination)destination).isBrowseOnly()), false);
- }
-
- public MessageConsumer createConsumer(Destination destination, String messageSelector) throws JMSException
- {
- checkValidDestination(destination);
-
- return createConsumerImpl(destination, _prefetchHighMark, _prefetchLowMark, false, (destination instanceof Topic),
- messageSelector, null, ((destination instanceof AMQDestination) && ((AMQDestination)destination).isBrowseOnly()), false);
- }
-
- public MessageConsumer createConsumer(Destination destination, String messageSelector, boolean noLocal)
- throws JMSException
- {
- checkValidDestination(destination);
-
- return createConsumerImpl(destination, _prefetchHighMark, _prefetchLowMark, noLocal, (destination instanceof Topic),
- messageSelector, null, ((destination instanceof AMQDestination) && ((AMQDestination)destination).isBrowseOnly()), false);
- }
-
- public MessageConsumer createExclusiveConsumer(Destination destination, String messageSelector, boolean noLocal)
- throws JMSException
- {
- checkValidDestination(destination);
-
- return createConsumerImpl(destination, _prefetchHighMark, _prefetchLowMark, noLocal, true,
- messageSelector, null, false, false);
- }
-
- public MessageConsumer createConsumer(Destination destination, int prefetch, boolean noLocal, boolean exclusive,
- String selector) throws JMSException
- {
- checkValidDestination(destination);
-
- return createConsumerImpl(destination, prefetch, prefetch / 2, noLocal, exclusive, selector, null, ((destination instanceof AMQDestination) && ((AMQDestination)destination).isBrowseOnly()), false);
- }
-
- public MessageConsumer createConsumer(Destination destination, int prefetchHigh, int prefetchLow, boolean noLocal,
- boolean exclusive, String selector) throws JMSException
- {
- checkValidDestination(destination);
-
- return createConsumerImpl(destination, prefetchHigh, prefetchLow, noLocal, exclusive, selector, null, ((destination instanceof AMQDestination) && ((AMQDestination)destination).isBrowseOnly()), false);
- }
-
- public MessageConsumer createConsumer(Destination destination, int prefetch, boolean noLocal, boolean exclusive,
- String selector, FieldTable rawSelector) throws JMSException
- {
- checkValidDestination(destination);
-
- return createConsumerImpl(destination, prefetch, prefetch / 2, noLocal, exclusive, selector, rawSelector, ((destination instanceof AMQDestination) && ((AMQDestination)destination).isBrowseOnly()), false);
- }
-
- public MessageConsumer createConsumer(Destination destination, int prefetchHigh, int prefetchLow, boolean noLocal,
- boolean exclusive, String selector, FieldTable rawSelector) throws JMSException
- {
- checkValidDestination(destination);
-
- return createConsumerImpl(destination, prefetchHigh, prefetchLow, noLocal, exclusive, selector, rawSelector, ((destination instanceof AMQDestination) && ((AMQDestination)destination).isBrowseOnly()),
- false);
- }
-
- public TopicSubscriber createDurableSubscriber(Topic topic, String name) throws JMSException
- {
- // Delegate the work to the {@link #createDurableSubscriber(Topic, String, String, boolean)} method
- return createDurableSubscriber(topic, name, null, false);
- }
-
- public TopicSubscriber createDurableSubscriber(Topic topic, String name, String selector, boolean noLocal)
- throws JMSException
- {
- checkNotClosed();
- Topic origTopic = checkValidTopic(topic, true);
-
- AMQTopic dest = AMQTopic.createDurableTopic(origTopic, name, _connection);
- if (dest.getDestSyntax() == DestSyntax.ADDR &&
- !dest.isAddressResolved())
- {
- try
- {
- handleAddressBasedDestination(dest,false,true);
- if (dest.getAddressType() != AMQDestination.TOPIC_TYPE)
- {
- throw new JMSException("Durable subscribers can only be created for Topics");
- }
- dest.getSourceNode().setDurable(true);
- }
- catch(AMQException e)
- {
- JMSException ex = new JMSException("Error when verifying destination");
- ex.initCause(e);
- ex.setLinkedException(e);
- throw ex;
- }
- }
-
- String messageSelector = ((selector == null) || (selector.trim().length() == 0)) ? null : selector;
-
- _subscriberDetails.lock();
- try
- {
- TopicSubscriberAdaptor<C> subscriber = _subscriptions.get(name);
-
- // Not subscribed to this name in the current session
- if (subscriber == null)
- {
- // After the address is resolved routing key will not be null.
- AMQShortString topicName = dest.getRoutingKey();
-
- if (_strictAMQP)
- {
- if (_strictAMQPFATAL)
- {
- throw new UnsupportedOperationException("JMS Durable not currently supported by AMQP.");
- }
- else
- {
- _logger.warn("Unable to determine if subscription already exists for '" + topicName
- + "' for creation durableSubscriber. Requesting queue deletion regardless.");
- }
-
- deleteQueue(dest.getAMQQueueName());
- }
- else
- {
- Map<String,Object> args = new HashMap<String,Object>();
-
- // We must always send the selector argument even if empty, so that we can tell when a selector is removed from a
- // durable topic subscription that the broker arguments don't match any more. This is because it is not otherwise
- // possible to determine when querying the broker whether there are no arguments or just a non-matching selector
- // argument, as specifying null for the arguments when querying means they should not be checked at all
- args.put(AMQPFilterTypes.JMS_SELECTOR.getValue().toString(), messageSelector == null ? "" : messageSelector);
-
- // if the queue is bound to the exchange but NOT for this topic and selector, then the JMS spec
- // says we must trash the subscription.
- boolean isQueueBound = isQueueBound(dest.getExchangeName(), dest.getAMQQueueName());
- boolean isQueueBoundForTopicAndSelector =
- isQueueBound(dest.getExchangeName().asString(), dest.getAMQQueueName().asString(), topicName.asString(), args);
-
- if (isQueueBound && !isQueueBoundForTopicAndSelector)
- {
- deleteQueue(dest.getAMQQueueName());
- }
- }
- }
- else
- {
- // Subscribed with the same topic and no current / previous or same selector
- if (subscriber.getTopic().equals(topic)
- && ((messageSelector == null && subscriber.getMessageSelector() == null)
- || (messageSelector != null && messageSelector.equals(subscriber.getMessageSelector()))))
- {
- throw new IllegalStateException("Already subscribed to topic " + topic + " with subscription name " + name
- + (messageSelector != null ? " and selector " + messageSelector : ""));
- }
- else
- {
- unsubscribe(name, true);
- }
-
- }
-
- _subscriberAccess.lock();
- try
- {
- C consumer = (C) createConsumer(dest, messageSelector, noLocal);
- subscriber = new TopicSubscriberAdaptor<C>(dest, consumer);
-
- // Save subscription information
- _subscriptions.put(name, subscriber);
- _reverseSubscriptionMap.put(subscriber.getMessageConsumer(), name);
- }
- finally
- {
- _subscriberAccess.unlock();
- }
-
- return subscriber;
- }
- finally
- {
- _subscriberDetails.unlock();
- }
- }
-
- public MapMessage createMapMessage() throws JMSException
- {
- checkNotClosed();
- if (USE_AMQP_ENCODED_MAP_MESSAGE)
- {
- AMQPEncodedMapMessage msg = new AMQPEncodedMapMessage(getMessageDelegateFactory());
- msg.setAMQSession(this);
- return msg;
- }
- else
- {
- JMSMapMessage msg = new JMSMapMessage(getMessageDelegateFactory());
- msg.setAMQSession(this);
- return msg;
- }
- }
-
- public javax.jms.Message createMessage() throws JMSException
- {
- return createBytesMessage();
- }
-
- public ObjectMessage createObjectMessage() throws JMSException
- {
- checkNotClosed();
- JMSObjectMessage msg = new JMSObjectMessage(getMessageDelegateFactory());
- msg.setAMQSession(this);
- return msg;
- }
-
- public ObjectMessage createObjectMessage(Serializable object) throws JMSException
- {
- ObjectMessage msg = createObjectMessage();
- msg.setObject(object);
-
- return msg;
- }
-
- public P createProducer(Destination destination) throws JMSException
- {
- return createProducerImpl(destination, DEFAULT_MANDATORY, DEFAULT_IMMEDIATE);
- }
-
- public P createProducer(Destination destination, boolean immediate) throws JMSException
- {
- return createProducerImpl(destination, DEFAULT_MANDATORY, immediate);
- }
-
- public P createProducer(Destination destination, boolean mandatory, boolean immediate)
- throws JMSException
- {
- return createProducerImpl(destination, mandatory, immediate);
- }
-
- public P createProducer(Destination destination, boolean mandatory, boolean immediate,
- boolean waitUntilSent) throws JMSException
- {
- return createProducerImpl(destination, mandatory, immediate, waitUntilSent);
- }
-
- public TopicPublisher createPublisher(Topic topic) throws JMSException
- {
- checkNotClosed();
-
- return new TopicPublisherAdapter((P) createProducer(topic, false, false), topic);
- }
-
- public Queue createQueue(String queueName) throws JMSException
- {
- checkNotClosed();
- try
- {
- if (queueName.indexOf('/') == -1 && queueName.indexOf(';') == -1)
- {
- DestSyntax syntax = AMQDestination.getDestType(queueName);
- if (syntax == AMQDestination.DestSyntax.BURL)
- {
- // For testing we may want to use the prefix
- return new AMQQueue(getDefaultQueueExchangeName(),
- new AMQShortString(AMQDestination.stripSyntaxPrefix(queueName)));
- }
- else
- {
- AMQQueue queue = new AMQQueue(queueName);
- return queue;
-
- }
- }
- else
- {
- return new AMQQueue(queueName);
- }
- }
- catch (URISyntaxException urlse)
- {
- _logger.error("", urlse);
- JMSException jmse = new JMSException(urlse.getReason());
- jmse.setLinkedException(urlse);
- jmse.initCause(urlse);
- throw jmse;
- }
-
- }
-
- /**
- * Declares the named queue.
- *
- * <p/>Note that this operation automatically retries in the event of fail-over.
- *
- * @param name The name of the queue to declare.
- * @param autoDelete
- * @param durable Flag to indicate that the queue is durable.
- * @param exclusive Flag to indicate that the queue is exclusive to this client.
- *
- * @throws AMQException If the queue cannot be declared for any reason.
- * @todo Be aware of possible changes to parameter order as versions change.
- */
- public void createQueue(final AMQShortString name, final boolean autoDelete, final boolean durable,
- final boolean exclusive) throws AMQException
- {
- createQueue(name, autoDelete, durable, exclusive, null);
- }
-
- /**
- * Declares the named queue.
- *
- * <p/>Note that this operation automatically retries in the event of fail-over.
- *
- * @param name The name of the queue to declare.
- * @param autoDelete
- * @param durable Flag to indicate that the queue is durable.
- * @param exclusive Flag to indicate that the queue is exclusive to this client.
- * @param arguments Arguments used to set special properties of the queue
- *
- * @throws AMQException If the queue cannot be declared for any reason.
- * @todo Be aware of possible changes to parameter order as versions change.
- */
- public void createQueue(final AMQShortString name, final boolean autoDelete, final boolean durable,
- final boolean exclusive, final Map<String, Object> arguments) throws AMQException
- {
- new FailoverRetrySupport<Object, AMQException>(new FailoverProtectedOperation<Object, AMQException>()
- {
- public Object execute() throws AMQException, FailoverException
- {
- sendCreateQueue(name, autoDelete, durable, exclusive, arguments);
- return null;
- }
- }, _connection).execute();
- }
-
- public abstract void sendCreateQueue(AMQShortString name, final boolean autoDelete, final boolean durable,
- final boolean exclusive, final Map<String, Object> arguments) throws AMQException, FailoverException;
-
- /**
- * Creates a QueueReceiver
- *
- * @param destination
- *
- * @return QueueReceiver - a wrapper around our MessageConsumer
- *
- * @throws JMSException
- */
- public QueueReceiver createQueueReceiver(Destination destination) throws JMSException
- {
- checkValidDestination(destination);
- Queue dest = validateQueue(destination);
- C consumer = (C) createConsumer(dest);
-
- return new QueueReceiverAdaptor(dest, consumer);
- }
-
- /**
- * Creates a QueueReceiver using a message selector
- *
- * @param destination
- * @param messageSelector
- *
- * @return QueueReceiver - a wrapper around our MessageConsumer
- *
- * @throws JMSException
- */
- public QueueReceiver createQueueReceiver(Destination destination, String messageSelector) throws JMSException
- {
- checkValidDestination(destination);
- Queue dest = validateQueue(destination);
- C consumer = (C) createConsumer(dest, messageSelector);
-
- return new QueueReceiverAdaptor(dest, consumer);
- }
-
- /**
- * Creates a QueueReceiver wrapping a MessageConsumer
- *
- * @param queue
- *
- * @return QueueReceiver
- *
- * @throws JMSException
- */
- public QueueReceiver createReceiver(Queue queue) throws JMSException
- {
- checkNotClosed();
- Queue dest = validateQueue(queue);
- C consumer = (C) createConsumer(dest);
-
- return new QueueReceiverAdaptor(dest, consumer);
- }
-
- /**
- * Creates a QueueReceiver wrapping a MessageConsumer using a message selector
- *
- * @param queue
- * @param messageSelector
- *
- * @return QueueReceiver
- *
- * @throws JMSException
- */
- public QueueReceiver createReceiver(Queue queue, String messageSelector) throws JMSException
- {
- checkNotClosed();
- Queue dest = validateQueue(queue);
- C consumer = (C) createConsumer(dest, messageSelector);
-
- return new QueueReceiverAdaptor(dest, consumer);
- }
-
- private Queue validateQueue(Destination dest) throws InvalidDestinationException
- {
- if (dest instanceof AMQDestination && dest instanceof javax.jms.Queue)
- {
- return (Queue)dest;
- }
- else
- {
- throw new InvalidDestinationException("The destination object used is not from this provider or of type javax.jms.Queue");
- }
- }
-
- public QueueSender createSender(Queue queue) throws JMSException
- {
- checkNotClosed();
-
- // return (QueueSender) createProducer(queue);
- return new QueueSenderAdapter(createProducer(queue), queue);
- }
-
- public StreamMessage createStreamMessage() throws JMSException
- {
- // This method needs to be improved. Throwables only arrive here from the mina : exceptionRecived
- // calls through connection.closeAllSessions which is also called by the public connection.close()
- // with a null cause
- // When we are closing the Session due to a protocol session error we simply create a new AMQException
- // with the correct error code and text this is cleary WRONG as the instanceof check below will fail.
- // We need to determin here if the connection should be
-
- synchronized (getFailoverMutex())
- {
- checkNotClosed();
-
- JMSStreamMessage msg = new JMSStreamMessage(getMessageDelegateFactory());
- msg.setAMQSession(this);
- return msg;
- }
- }
-
- /**
- * Creates a non-durable subscriber
- *
- * @param topic
- *
- * @return TopicSubscriber - a wrapper round our MessageConsumer
- *
- * @throws JMSException
- */
- public TopicSubscriber createSubscriber(Topic topic) throws JMSException
- {
- checkNotClosed();
- Topic dest = checkValidTopic(topic);
-
- // AMQTopic dest = new AMQTopic(topic.getTopicName());
- return new TopicSubscriberAdaptor(dest, (C) createExclusiveConsumer(dest));
- }
-
- /**
- * Creates a non-durable subscriber with a message selector
- *
- * @param topic
- * @param messageSelector
- * @param noLocal
- *
- * @return TopicSubscriber - a wrapper round our MessageConsumer
- *
- * @throws JMSException
- */
- public TopicSubscriber createSubscriber(Topic topic, String messageSelector, boolean noLocal) throws JMSException
- {
- checkNotClosed();
- Topic dest = checkValidTopic(topic);
-
- // AMQTopic dest = new AMQTopic(topic.getTopicName());
- return new TopicSubscriberAdaptor(dest, (C) createExclusiveConsumer(dest, messageSelector, noLocal));
- }
-
- public TemporaryQueue createTemporaryQueue() throws JMSException
- {
- checkNotClosed();
- try
- {
- AMQTemporaryQueue result = new AMQTemporaryQueue(this);
-
- // this is done so that we can produce to a temporary queue before we create a consumer
- result.setQueueName(result.getRoutingKey());
- createQueue(result.getAMQQueueName(), result.isAutoDelete(),
- result.isDurable(), result.isExclusive());
- bindQueue(result.getAMQQueueName(), result.getRoutingKey(),
- new FieldTable(), result.getExchangeName(), result);
- return result;
- }
- catch (Exception e)
- {
- JMSException jmse = new JMSException("Cannot create temporary queue");
- jmse.setLinkedException(e);
- jmse.initCause(e);
- throw jmse;
- }
- }
-
- public TemporaryTopic createTemporaryTopic() throws JMSException
- {
- checkNotClosed();
-
- return new AMQTemporaryTopic(this);
- }
-
- public TextMessage createTextMessage() throws JMSException
- {
- synchronized (getFailoverMutex())
- {
- checkNotClosed();
-
- JMSTextMessage msg = new JMSTextMessage(getMessageDelegateFactory());
- msg.setAMQSession(this);
- return msg;
- }
- }
-
- protected Object getFailoverMutex()
- {
- return _connection.getFailoverMutex();
- }
-
- public TextMessage createTextMessage(String text) throws JMSException
- {
-
- TextMessage msg = createTextMessage();
- msg.setText(text);
-
- return msg;
- }
-
- public Topic createTopic(String topicName) throws JMSException
- {
- checkNotClosed();
- try
- {
- if (topicName.indexOf('/') == -1 && topicName.indexOf(';') == -1)
- {
- DestSyntax syntax = AMQDestination.getDestType(topicName);
- // for testing we may want to use the prefix to indicate our choice.
- topicName = AMQDestination.stripSyntaxPrefix(topicName);
- if (syntax == AMQDestination.DestSyntax.BURL)
- {
- return new AMQTopic(getDefaultTopicExchangeName(), new AMQShortString(topicName));
- }
- else
- {
- return new AMQTopic("ADDR:" + getDefaultTopicExchangeName() + "/" + topicName);
- }
- }
- else
- {
- return new AMQTopic(topicName);
- }
-
- }
- catch (URISyntaxException urlse)
- {
- _logger.error("", urlse);
- JMSException jmse = new JMSException(urlse.getReason());
- jmse.setLinkedException(urlse);
- jmse.initCause(urlse);
- throw jmse;
- }
- }
-
- public void declareExchange(AMQShortString name, AMQShortString type, boolean nowait) throws AMQException
- {
- declareExchange(name, type, getProtocolHandler(), nowait);
- }
-
- abstract public void sync() throws AMQException;
-
- public int getAcknowledgeMode() throws JMSException
- {
- checkNotClosed();
-
- return _acknowledgeMode;
- }
-
- public AMQConnection getAMQConnection()
- {
- return _connection;
- }
-
- public int getChannelId()
- {
- return _channelId;
- }
-
- public int getDefaultPrefetch()
- {
- return _prefetchHighMark;
- }
-
- public int getDefaultPrefetchHigh()
- {
- return _prefetchHighMark;
- }
-
- public int getDefaultPrefetchLow()
- {
- return _prefetchLowMark;
- }
-
- public AMQShortString getDefaultQueueExchangeName()
- {
- return _connection.getDefaultQueueExchangeName();
- }
-
- public AMQShortString getDefaultTopicExchangeName()
- {
- return _connection.getDefaultTopicExchangeName();
- }
-
- public MessageListener getMessageListener() throws JMSException
- {
- // checkNotClosed();
- return _messageListener;
- }
-
- public AMQShortString getTemporaryQueueExchangeName()
- {
- return _connection.getTemporaryQueueExchangeName();
- }
-
- public AMQShortString getTemporaryTopicExchangeName()
- {
- return _connection.getTemporaryTopicExchangeName();
- }
-
- public int getTicket()
- {
- return _ticket;
- }
-
- public boolean getTransacted() throws JMSException
- {
- checkNotClosed();
-
- return _transacted;
- }
-
- public boolean hasConsumer(Destination destination)
- {
- AtomicInteger counter = _destinationConsumerCount.get(destination);
-
- return (counter != null) && (counter.get() != 0);
- }
-
- public boolean isStrictAMQP()
- {
- return _strictAMQP;
- }
-
- public boolean isSuspended()
- {
- return _suspended;
- }
-
- protected void addUnacknowledgedMessage(long id)
- {
- _unacknowledgedMessageTags.add(id);
- }
-
- protected void addDeliveredMessage(long id)
- {
- _deliveredMessageTags.add(id);
- }
-
- /**
- * Invoked by the MINA IO thread (indirectly) when a message is received from the transport. Puts the message onto
- * the queue read by the dispatcher.
- *
- * @param message the message that has been received
- */
- public void messageReceived(UnprocessedMessage message)
- {
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Message[" + message.toString() + "] received in session");
- }
- _highestDeliveryTag.set(message.getDeliveryTag());
- _queue.add(message);
- }
-
- public void declareAndBind(AMQDestination amqd)
- throws
- AMQException
- {
- AMQProtocolHandler protocolHandler = getProtocolHandler();
- declareExchange(amqd, protocolHandler, false);
- AMQShortString queueName = declareQueue(amqd, protocolHandler, false);
- bindQueue(queueName, amqd.getRoutingKey(), new FieldTable(), amqd.getExchangeName(), amqd);
- }
-
- /**
- * Stops message delivery in this session, and restarts message delivery with the oldest unacknowledged message.
- *
- * <p/>All consumers deliver messages in a serial order. Acknowledging a received message automatically acknowledges
- * all messages that have been delivered to the client.
- *
- * <p/>Restarting a session causes it to take the following actions:
- *
- * <ul>
- * <li>Stop message delivery.</li>
- * <li>Mark all messages that might have been delivered but not acknowledged as "redelivered".
- * <li>Restart the delivery sequence including all unacknowledged messages that had been previously delivered.
- * Redelivered messages do not have to be delivered in exactly their original delivery order.</li>
- * </ul>
- *
- * <p/>If the recover operation is interrupted by a fail-over, between asking that the broker begin recovery and
- * receiving acknowledgment that it has then a JMSException will be thrown. In this case it will not be possible
- * for the client to determine whether the broker is going to recover the session or not.
- *
- * @throws JMSException If the JMS provider fails to stop and restart message delivery due to some internal error.
- * Not that this does not necessarily mean that the recovery has failed, but simply that it is
- * not possible to tell if it has or not.
- * @todo Be aware of possible changes to parameter order as versions change.
- *
- * Strategy for handling recover.
- * Flush any acks not yet sent.
- * Stop the message flow.
- * Clear the dispatch queue and the consumer queues.
- * Release/Reject all messages received but not yet acknowledged.
- * Start the message flow.
- */
- public void recover() throws JMSException
- {
- // Ensure that the session is open.
- checkNotClosed();
-
- // Ensure that the session is not transacted.
- checkNotTransacted();
-
- // flush any acks we are holding in the buffer.
- flushAcknowledgments();
-
- // this is set only here, and the before the consumer's onMessage is called it is set to false
- _inRecovery = true;
- try
- {
-
- boolean isSuspended = isSuspended();
-
- if (!isSuspended)
- {
- suspendChannel(true);
- }
-
- syncDispatchQueue();
-
- if (_dispatcher != null)
- {
- _dispatcher.recover();
- }
-
- sendRecover();
-
- markClean();
-
- // Set inRecovery to false before you start message flow again again.
- _inRecovery = false;
-
- if (!isSuspended)
- {
- suspendChannel(false);
- }
- }
- catch (AMQException e)
- {
- throw new JMSAMQException("Recover failed: " + e.getMessage(), e);
- }
- catch (FailoverException e)
- {
- throw new JMSAMQException("Recovery was interrupted by fail-over. Recovery status is not known.", e);
- }
-
- }
-
- protected abstract void sendRecover() throws AMQException, FailoverException;
-
- protected abstract void flushAcknowledgments();
-
- public void rejectMessage(UnprocessedMessage message, boolean requeue)
- {
-
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Rejecting Unacked message:" + message.getDeliveryTag());
- }
-
- rejectMessage(message.getDeliveryTag(), requeue);
- }
-
- public void rejectMessage(AbstractJMSMessage message, boolean requeue)
- {
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Rejecting Abstract message:" + message.getDeliveryTag());
- }
-
- rejectMessage(message.getDeliveryTag(), requeue);
-
- }
-
- public abstract void rejectMessage(long deliveryTag, boolean requeue);
-
- /**
- * Commits all messages done in this transaction and releases any locks currently held.
- *
- * <p/>If the rollback fails, because the rollback itself is interrupted by a fail-over between requesting that the
- * rollback be done, and receiving an acknowledgement that it has been done, then a JMSException will be thrown.
- * The client will be unable to determine whether or not the rollback actually happened on the broker in this case.
- *
- * @throws JMSException If the JMS provider fails to rollback the transaction due to some internal error. This does
- * not mean that the rollback is known to have failed, merely that it is not known whether it
- * failed or not.
- * @todo Be aware of possible changes to parameter order as versions change.
- */
- public void rollback() throws JMSException
- {
- synchronized (_suspensionLock)
- {
- checkTransacted();
-
- try
- {
- boolean isSuspended = isSuspended();
-
- if (!isSuspended)
- {
- suspendChannel(true);
- }
-
- // Let the dispatcher know that all the incomming messages
- // should be rolled back(reject/release)
- _rollbackMark.set(_highestDeliveryTag.get());
-
- syncDispatchQueue();
-
- _dispatcher.rollback();
-
- releaseForRollback();
-
- sendRollback();
-
- markClean();
-
- if (!isSuspended)
- {
- suspendChannel(false);
- }
- }
- catch (AMQException e)
- {
- throw new JMSAMQException("Failed to rollback: " + e, e);
- }
- catch (FailoverException e)
- {
- throw new JMSAMQException("Fail-over interrupted rollback. Status of the rollback is uncertain.", e);
- }
- }
- }
-
- public abstract void releaseForRollback();
-
- public abstract void sendRollback() throws AMQException, FailoverException;
-
- public void run()
- {
- throw new java.lang.UnsupportedOperationException();
- }
-
- public void setMessageListener(MessageListener listener) throws JMSException
- {
- // checkNotClosed();
- //
- // if (_dispatcher != null && !_dispatcher.connectionStopped())
- // {
- // throw new javax.njms.IllegalStateException("Attempt to set listener while session is started.");
- // }
- //
- // // We are stopped
- // for (Iterator<BasicMessageConsumer> i = _consumers.values().iterator(); i.hasNext();)
- // {
- // BasicMessageConsumer consumer = i.next();
- //
- // if (consumer.isReceiving())
- // {
- // throw new javax.njms.IllegalStateException("Another thread is already receiving synchronously.");
- // }
- // }
- //
- // _messageListener = listener;
- //
- // for (Iterator<BasicMessageConsumer> i = _consumers.values().iterator(); i.hasNext();)
- // {
- // i.next().setMessageListener(_messageListener);
- // }
-
- }
-
- /**
- * @see #unsubscribe(String, boolean)
- */
- public void unsubscribe(String name) throws JMSException
- {
- unsubscribe(name, false);
- }
-
- /**
- * Unsubscribe from a subscription.
- *
- * @param name the name of the subscription to unsubscribe
- * @param safe allows safe unsubscribe operation that will not throw an {@link InvalidDestinationException} if the
- * queue is not bound, possibly due to the subscription being closed.
- * @throws JMSException on
- * @throws InvalidDestinationException
- */
- private void unsubscribe(String name, boolean safe) throws JMSException
- {
- TopicSubscriberAdaptor<C> subscriber;
-
- _subscriberDetails.lock();
- try
- {
- checkNotClosed();
- subscriber = _subscriptions.get(name);
- if (subscriber != null)
- {
- // Remove saved subscription information
- _subscriptions.remove(name);
- _reverseSubscriptionMap.remove(subscriber.getMessageConsumer());
- }
- }
- finally
- {
- _subscriberDetails.unlock();
- }
-
- if (subscriber != null)
- {
- subscriber.close();
-
- // send a queue.delete for the subscription
- deleteQueue(AMQTopic.getDurableTopicQueueName(name, _connection));
- }
- else
- {
- if (_strictAMQP)
- {
- if (_strictAMQPFATAL)
- {
- throw new UnsupportedOperationException("JMS Durable not currently supported by AMQP.");
- }
- else
- {
- _logger.warn("Unable to determine if subscription already exists for '" + name + "' for unsubscribe."
- + " Requesting queue deletion regardless.");
- }
-
- deleteQueue(AMQTopic.getDurableTopicQueueName(name, _connection));
- }
- else // Queue Browser
- {
-
- if (isQueueBound(getDefaultTopicExchangeName(), AMQTopic.getDurableTopicQueueName(name, _connection)))
- {
- deleteQueue(AMQTopic.getDurableTopicQueueName(name, _connection));
- }
- else if (!safe)
- {
- throw new InvalidDestinationException("Unknown subscription name: " + name);
- }
- }
- }
- }
-
- protected C createConsumerImpl(final Destination destination, final int prefetchHigh,
- final int prefetchLow, final boolean noLocal, final boolean exclusive, String selector, final FieldTable rawSelector,
- final boolean noConsume, final boolean autoClose) throws JMSException
- {
- checkTemporaryDestination(destination);
-
- final String messageSelector;
-
- if (_strictAMQP && !((selector == null) || selector.equals("")))
- {
- if (_strictAMQPFATAL)
- {
- throw new UnsupportedOperationException("Selectors not currently supported by AMQP.");
- }
- else
- {
- messageSelector = null;
- }
- }
- else
- {
- messageSelector = selector;
- }
-
- return new FailoverRetrySupport<C, JMSException>(
- new FailoverProtectedOperation<C, JMSException>()
- {
- public C execute() throws JMSException, FailoverException
- {
- checkNotClosed();
-
- AMQDestination amqd = (AMQDestination) destination;
-
- // TODO: Define selectors in AMQP
- // TODO: construct the rawSelector from the selector string if rawSelector == null
- final FieldTable ft = FieldTableFactory.newFieldTable();
- // if (rawSelector != null)
- // ft.put("headers", rawSelector.getDataAsBytes());
- // rawSelector is used by HeadersExchange and is not a JMS Selector
- if (rawSelector != null)
- {
- ft.addAll(rawSelector);
- }
-
- // We must always send the selector argument even if empty, so that we can tell when a selector is removed from a
- // durable topic subscription that the broker arguments don't match any more. This is because it is not otherwise
- // possible to determine when querying the broker whether there are no arguments or just a non-matching selector
- // argument, as specifying null for the arguments when querying means they should not be checked at all
- ft.put(AMQPFilterTypes.JMS_SELECTOR.getValue(), messageSelector == null ? "" : messageSelector);
-
- C consumer = createMessageConsumer(amqd, prefetchHigh, prefetchLow,
- noLocal, exclusive, messageSelector, ft, noConsume, autoClose);
-
- if (_messageListener != null)
- {
- consumer.setMessageListener(_messageListener);
- }
-
- try
- {
- registerConsumer(consumer, false);
- }
- catch (AMQInvalidArgumentException ise)
- {
- JMSException jmse = new InvalidSelectorException(ise.getMessage());
- jmse.setLinkedException(ise);
- jmse.initCause(ise);
- throw jmse;
- }
- catch (AMQInvalidRoutingKeyException e)
- {
- JMSException jmse = new InvalidDestinationException("Invalid routing key:" + amqd.getRoutingKey().toString());
- jmse.setLinkedException(e);
- jmse.initCause(e);
- throw jmse;
- }
- catch (AMQException e)
- {
- if (e instanceof AMQChannelClosedException)
- {
- close(-1, false);
- }
-
- JMSException ex = new JMSException("Error registering consumer: " + e);
- ex.setLinkedException(e);
- ex.initCause(e);
- throw ex;
- }
-
- return consumer;
- }
- }, _connection).execute();
- }
-
- public abstract C createMessageConsumer(final AMQDestination destination, final int prefetchHigh,
- final int prefetchLow, final boolean noLocal, final boolean exclusive, String selector, final FieldTable arguments,
- final boolean noConsume, final boolean autoClose) throws JMSException;
-
- /**
- * Called by the MessageConsumer when closing, to deregister the consumer from the map from consumerTag to consumer
- * instance.
- *
- * @param consumer the consum
- */
- void deregisterConsumer(C consumer)
- {
- if (_consumers.remove(consumer.getConsumerTag()) != null)
- {
- _subscriberAccess.lock();
- try
- {
- String subscriptionName = _reverseSubscriptionMap.remove(consumer);
- if (subscriptionName != null)
- {
- _subscriptions.remove(subscriptionName);
- }
- }
- finally
- {
- _subscriberAccess.unlock();
- }
-
- Destination dest = consumer.getDestination();
- synchronized (dest)
- {
- // Provide additional NPE check
- // This would occur if the consumer was closed before it was
- // fully opened.
- if (_destinationConsumerCount.get(dest) != null)
- {
- if (_destinationConsumerCount.get(dest).decrementAndGet() == 0)
- {
- _destinationConsumerCount.remove(dest);
- }
- }
- }
-
- // Consumers that are closed in a transaction must be stored
- // so that messages they have received can be acknowledged on commit
- if (_transacted)
- {
- _removedConsumers.add(consumer);
- }
- }
- }
-
- void deregisterProducer(long producerId)
- {
- _producers.remove(new Long(producerId));
- }
-
- boolean isInRecovery()
- {
- return _inRecovery;
- }
-
- boolean isQueueBound(AMQShortString exchangeName, AMQShortString queueName) throws JMSException
- {
- return isQueueBound(exchangeName, queueName, null);
- }
-
- /**
- * Tests whether or not the specified queue is bound to the specified exchange under a particular routing key.
- *
- * <p/>Note that this operation automatically retries in the event of fail-over.
- *
- * @param exchangeName The exchange name to test for binding against.
- * @param queueName The queue name to check if bound.
- * @param routingKey The routing key to check if the queue is bound under.
- *
- * @return <tt>true</tt> if the queue is bound to the exchange and routing key, <tt>false</tt> if not.
- *
- * @throws JMSException If the query fails for any reason.
- * @todo Be aware of possible changes to parameter order as versions change.
- */
- public abstract boolean isQueueBound(final AMQShortString exchangeName, final AMQShortString queueName, final AMQShortString routingKey)
- throws JMSException;
-
- public abstract boolean isQueueBound(final AMQDestination destination) throws JMSException;
-
- public abstract boolean isQueueBound(String exchangeName, String queueName, String bindingKey, Map<String,Object> args) throws JMSException;
-
- /**
- * Called to mark the session as being closed. Useful when the session needs to be made invalid, e.g. after failover
- * when the client has veoted resubscription. <p/> The caller of this method must already hold the failover mutex.
- */
- void markClosed()
- {
- _closed.set(true);
- _connection.deregisterSession(_channelId);
- markClosedProducersAndConsumers();
-
- }
-
- void failoverPrep()
- {
- syncDispatchQueue();
- }
-
- void syncDispatchQueue()
- {
- if (Thread.currentThread() == _dispatcherThread)
- {
- while (!_closed.get() && !_queue.isEmpty())
- {
- Dispatchable disp;
- try
- {
- disp = (Dispatchable) _queue.take();
- }
- catch (InterruptedException e)
- {
- throw new RuntimeException(e);
- }
-
- // Check just in case _queue becomes empty, it shouldn't but
- // better than an NPE.
- if (disp == null)
- {
- _logger.debug("_queue became empty during sync.");
- break;
- }
-
- disp.dispatch(AMQSession.this);
- }
- }
- else
- {
- startDispatcherIfNecessary();
-
- final CountDownLatch signal = new CountDownLatch(1);
-
- _queue.add(new Dispatchable()
- {
- public void dispatch(AMQSession ssn)
- {
- signal.countDown();
- }
- });
-
- try
- {
- signal.await();
- }
- catch (InterruptedException e)
- {
- throw new RuntimeException(e);
- }
- }
- }
-
- /**
- * Resubscribes all producers and consumers. This is called when performing failover.
- *
- * @throws AMQException
- */
- void resubscribe() throws AMQException
- {
- if (_dirty)
- {
- _failedOverDirty = true;
- }
-
- _rollbackMark.set(-1);
- resubscribeProducers();
- resubscribeConsumers();
- }
-
- void setHasMessageListeners()
- {
- _hasMessageListeners = true;
- }
-
- void setInRecovery(boolean inRecovery)
- {
- _inRecovery = inRecovery;
- }
-
- boolean isStarted()
- {
- return _startedAtLeastOnce.get();
- }
-
- /**
- * Starts the session, which ensures that it is not suspended and that its event dispatcher is running.
- *
- * @throws AMQException If the session cannot be started for any reason.
- * @todo This should be controlled by _stopped as it pairs with the stop method fixme or check the
- * FlowControlledBlockingQueue _queue to see if we have flow controlled. will result in sending Flow messages
- * for each subsequent call to flow.. only need to do this if we have called stop.
- */
- void start() throws AMQException
- {
- // Check if the session has perviously been started and suspended, in which case it must be unsuspended.
- if (_startedAtLeastOnce.getAndSet(true))
- {
- suspendChannel(false);
- }
-
- // If the event dispatcher is not running then start it too.
- if (hasMessageListeners())
- {
- startDispatcherIfNecessary();
- }
- }
-
- void startDispatcherIfNecessary()
- {
- //If we are the dispatcher then we don't need to check we are started
- if (Thread.currentThread() == _dispatcherThread)
- {
- return;
- }
-
- // If IMMEDIATE_PREFETCH is not set then we need to start fetching
- // This is final per session so will be multi-thread safe.
- if (!_immediatePrefetch)
- {
- // We do this now if this is the first call on a started connection
- if (isSuspended() && _startedAtLeastOnce.get() && _firstDispatcher.getAndSet(false))
- {
- try
- {
- suspendChannel(false);
- }
- catch (AMQException e)
- {
- _logger.info("Unsuspending channel threw an exception:" + e);
- }
- }
- }
-
- startDispatcherIfNecessary(false);
- }
-
- synchronized void startDispatcherIfNecessary(boolean initiallyStopped)
- {
- if (_dispatcher == null)
- {
- _dispatcher = new Dispatcher();
- try
- {
- _dispatcherThread = Threading.getThreadFactory().createThread(_dispatcher);
-
- }
- catch(Exception e)
- {
- throw new Error("Error creating Dispatcher thread",e);
- }
- _dispatcherThread.setName("Dispatcher-Channel-" + _channelId);
- _dispatcherThread.setDaemon(true);
- _dispatcher.setConnectionStopped(initiallyStopped);
- _dispatcherThread.start();
- if (_dispatcherLogger.isInfoEnabled())
- {
- _dispatcherLogger.info(_dispatcherThread.getName() + " created");
- }
- }
- else
- {
- _dispatcher.setConnectionStopped(initiallyStopped);
- }
- }
-
- void stop() throws AMQException
- {
- // Stop the server delivering messages to this session.
- suspendChannel(true);
-
- if (_dispatcher != null)
- {
- _dispatcher.setConnectionStopped(true);
- }
- }
-
- /*
- * Binds the named queue, with the specified routing key, to the named exchange.
- *
- * <p/>Note that this operation automatically retries in the event of fail-over.
- *
- * @param queueName The name of the queue to bind.
- * @param routingKey The routing key to bind the queue with.
- * @param arguments Additional arguments.
- * @param exchangeName The exchange to bind the queue on.
- *
- * @throws AMQException If the queue cannot be bound for any reason.
- */
- /*private void bindQueue(AMQDestination amqd, AMQShortString queueName, AMQProtocolHandler protocolHandler, FieldTable ft)
- throws AMQException, FailoverException
- {
- AMQFrame queueBind =
- QueueBindBody.createAMQFrame(_channelId, getProtocolMajorVersion(), getProtocolMinorVersion(), ft, // arguments
- amqd.getExchangeName(), // exchange
- false, // nowait
- queueName, // queue
- amqd.getRoutingKey(), // routingKey
- getTicket()); // ticket
-
- protocolHandler.syncWrite(queueBind, QueueBindOkBody.class);
- }*/
-
- private void checkNotTransacted() throws JMSException
- {
- if (getTransacted())
- {
- throw new IllegalStateException("Session is transacted");
- }
- }
-
- private void checkTemporaryDestination(Destination destination) throws JMSException
- {
- if ((destination instanceof TemporaryDestination))
- {
- _logger.debug("destination is temporary");
- final TemporaryDestination tempDest = (TemporaryDestination) destination;
- if (tempDest.getSession() != this)
- {
- _logger.debug("destination is on different session");
- throw new JMSException("Cannot consume from a temporary destination created on another session");
- }
-
- if (tempDest.isDeleted())
- {
- _logger.debug("destination is deleted");
- throw new JMSException("Cannot consume from a deleted destination");
- }
- }
- }
-
- protected void checkTransacted() throws JMSException
- {
- if (!getTransacted())
- {
- throw new IllegalStateException("Session is not transacted");
- }
- }
-
- private void checkValidDestination(Destination destination) throws InvalidDestinationException
- {
- if (destination == null)
- {
- throw new javax.jms.InvalidDestinationException("Invalid Queue");
- }
- }
-
- private void checkValidQueue(Queue queue) throws InvalidDestinationException
- {
- if (queue == null)
- {
- throw new javax.jms.InvalidDestinationException("Invalid Queue");
- }
- }
-
- /*
- * I could have combined the last 3 methods, but this way it improves readability
- */
- protected Topic checkValidTopic(Topic topic, boolean durable) throws JMSException
- {
- if (topic == null)
- {
- throw new javax.jms.InvalidDestinationException("Invalid Topic");
- }
-
- if ((topic instanceof TemporaryDestination) && (((TemporaryDestination) topic).getSession() != this))
- {
- throw new javax.jms.InvalidDestinationException(
- "Cannot create a subscription on a temporary topic created in another session");
- }
-
- if ((topic instanceof TemporaryDestination) && durable)
- {
- throw new javax.jms.InvalidDestinationException
- ("Cannot create a durable subscription with a temporary topic: " + topic);
- }
-
- if (!(topic instanceof AMQDestination && topic instanceof javax.jms.Topic))
- {
- throw new javax.jms.InvalidDestinationException(
- "Cannot create a subscription on topic created for another JMS Provider, class of topic provided is: "
- + topic.getClass().getName());
- }
-
- return topic;
- }
-
- protected Topic checkValidTopic(Topic topic) throws JMSException
- {
- return checkValidTopic(topic, false);
- }
-
- /**
- * Called to close message consumers cleanly. This may or may <b>not</b> be as a result of an error.
- *
- * @param error not null if this is a result of an error occurring at the connection level
- */
- private void closeConsumers(Throwable error) throws JMSException
- {
- // we need to clone the list of consumers since the close() method updates the _consumers collection
- // which would result in a concurrent modification exception
- final ArrayList<C> clonedConsumers = new ArrayList<C>(_consumers.values());
-
- final Iterator<C> it = clonedConsumers.iterator();
- while (it.hasNext())
- {
- final C con = it.next();
- if (error != null)
- {
- con.notifyError(error);
- }
- else
- {
- con.close(false);
- }
- }
- // at this point the _consumers map will be empty
- if (_dispatcher != null)
- {
- _dispatcher.close();
- _dispatcher = null;
- }
- }
-
- /**
- * Called to close message producers cleanly. This may or may <b>not</b> be as a result of an error. There is
- * currently no way of propagating errors to message producers (this is a JMS limitation).
- */
- private void closeProducers() throws JMSException
- {
- // we need to clone the list of producers since the close() method updates the _producers collection
- // which would result in a concurrent modification exception
- final ArrayList clonedProducers = new ArrayList(_producers.values());
-
- final Iterator it = clonedProducers.iterator();
- while (it.hasNext())
- {
- final P prod = (P) it.next();
- prod.close();
- }
- // at this point the _producers map is empty
- }
-
- /**
- * Close all producers or consumers. This is called either in the error case or when closing the session normally.
- *
- * @param amqe the exception, may be null to indicate no error has occurred
- */
- private void closeProducersAndConsumers(AMQException amqe) throws JMSException
- {
- JMSException jmse = null;
- try
- {
- closeProducers();
- }
- catch (JMSException e)
- {
- _logger.error("Error closing session: " + e, e);
- jmse = e;
- }
-
- try
- {
- closeConsumers(amqe);
- }
- catch (JMSException e)
- {
- _logger.error("Error closing session: " + e, e);
- if (jmse == null)
- {
- jmse = e;
- }
- }
-
- if (jmse != null)
- {
- throw jmse;
- }
- }
-
- /**
- * Register to consume from the queue.
- *
- * @param queueName
- */
- private void consumeFromQueue(C consumer, AMQShortString queueName,
- AMQProtocolHandler protocolHandler, boolean nowait, String messageSelector) throws AMQException, FailoverException
- {
- int tagId = _nextTag++;
-
- consumer.setConsumerTag(tagId);
- // we must register the consumer in the map before we actually start listening
- _consumers.put(tagId, consumer);
-
- synchronized (consumer.getDestination())
- {
- _destinationConsumerCount.putIfAbsent(consumer.getDestination(), new AtomicInteger());
- _destinationConsumerCount.get(consumer.getDestination()).incrementAndGet();
- }
-
-
- try
- {
- sendConsume(consumer, queueName, protocolHandler, nowait, messageSelector, tagId);
- }
- catch (AMQException e)
- {
- // clean-up the map in the event of an error
- _consumers.remove(tagId);
- throw e;
- }
- }
-
- public abstract void sendConsume(C consumer, AMQShortString queueName,
- AMQProtocolHandler protocolHandler, boolean nowait, String messageSelector, int tag) throws AMQException, FailoverException;
-
- private P createProducerImpl(Destination destination, boolean mandatory, boolean immediate)
- throws JMSException
- {
- return createProducerImpl(destination, mandatory, immediate, DEFAULT_WAIT_ON_SEND);
- }
-
- private P createProducerImpl(final Destination destination, final boolean mandatory,
- final boolean immediate, final boolean waitUntilSent) throws JMSException
- {
- return new FailoverRetrySupport<P, JMSException>(
- new FailoverProtectedOperation<P, JMSException>()
- {
- public P execute() throws JMSException, FailoverException
- {
- checkNotClosed();
- long producerId = getNextProducerId();
- P producer = createMessageProducer(destination, mandatory,
- immediate, waitUntilSent, producerId);
- registerProducer(producerId, producer);
-
- return producer;
- }
- }, _connection).execute();
- }
-
- public abstract P createMessageProducer(final Destination destination, final boolean mandatory,
- final boolean immediate, final boolean waitUntilSent, long producerId) throws JMSException;
-
- private void declareExchange(AMQDestination amqd, AMQProtocolHandler protocolHandler, boolean nowait) throws AMQException
- {
- declareExchange(amqd.getExchangeName(), amqd.getExchangeClass(), protocolHandler, nowait);
- }
-
- /**
- * Returns the number of messages currently queued for the given destination.
- *
- * <p/>Note that this operation automatically retries in the event of fail-over.
- *
- * @param amqd The destination to be checked
- *
- * @return the number of queued messages.
- *
- * @throws AMQException If the queue cannot be declared for any reason.
- */
- public long getQueueDepth(final AMQDestination amqd)
- throws AMQException
- {
- return new FailoverNoopSupport<Long, AMQException>(
- new FailoverProtectedOperation<Long, AMQException>()
- {
- public Long execute() throws AMQException, FailoverException
- {
- return requestQueueDepth(amqd);
- }
- }, _connection).execute();
-
- }
-
- protected abstract Long requestQueueDepth(AMQDestination amqd) throws AMQException, FailoverException;
-
- /**
- * Declares the named exchange and type of exchange.
- *
- * <p/>Note that this operation automatically retries in the event of fail-over.
- *
- * @param name The name of the exchange to declare.
- * @param type The type of the exchange to declare.
- * @param protocolHandler The protocol handler to process the communication through.
- * @param nowait
- *
- * @throws AMQException If the exchange cannot be declared for any reason.
- * @todo Be aware of possible changes to parameter order as versions change.
- */
- private void declareExchange(final AMQShortString name, final AMQShortString type,
- final AMQProtocolHandler protocolHandler, final boolean nowait) throws AMQException
- {
- new FailoverNoopSupport<Object, AMQException>(new FailoverProtectedOperation<Object, AMQException>()
- {
- public Object execute() throws AMQException, FailoverException
- {
- sendExchangeDeclare(name, type, protocolHandler, nowait);
- return null;
- }
- }, _connection).execute();
- }
-
- public abstract void sendExchangeDeclare(final AMQShortString name, final AMQShortString type, final AMQProtocolHandler protocolHandler,
- final boolean nowait) throws AMQException, FailoverException;
-
- /**
- * Declares a queue for a JMS destination.
- *
- * <p/>Note that for queues but not topics the name is generated in the client rather than the server. This allows
- * the name to be reused on failover if required. In general, the destination indicates whether it wants a name
- * generated or not.
- *
- * <p/>Note that this operation automatically retries in the event of fail-over.
- *
- * @param amqd The destination to declare as a queue.
- * @param protocolHandler The protocol handler to communicate through.
- *
- * @return The name of the decalred queue. This is useful where the broker is generating a queue name on behalf of
- * the client.
- *
- * @throws AMQException If the queue cannot be declared for any reason.
- * @todo Verify the destiation is valid or throw an exception.
- * @todo Be aware of possible changes to parameter order as versions change.
- */
- protected AMQShortString declareQueue(final AMQDestination amqd, final AMQProtocolHandler protocolHandler,
- final boolean noLocal) throws AMQException
- {
- return declareQueue(amqd, protocolHandler, noLocal, false);
- }
-
- protected AMQShortString declareQueue(final AMQDestination amqd, final AMQProtocolHandler protocolHandler,
- final boolean noLocal, final boolean nowait)
- throws AMQException
- {
- /*return new FailoverRetrySupport<AMQShortString, AMQException>(*/
- return new FailoverNoopSupport<AMQShortString, AMQException>(
- new FailoverProtectedOperation<AMQShortString, AMQException>()
- {
- public AMQShortString execute() throws AMQException, FailoverException
- {
- // Generate the queue name if the destination indicates that a client generated name is to be used.
- if (amqd.isNameRequired())
- {
- amqd.setQueueName(protocolHandler.generateQueueName());
- }
-
- sendQueueDeclare(amqd, protocolHandler, nowait);
-
- return amqd.getAMQQueueName();
- }
- }, _connection).execute();
- }
-
- public abstract void sendQueueDeclare(final AMQDestination amqd, final AMQProtocolHandler protocolHandler,
- final boolean nowait) throws AMQException, FailoverException;
-
- /**
- * Undeclares the specified queue.
- *
- * <p/>Note that this operation automatically retries in the event of fail-over.
- *
- * @param queueName The name of the queue to delete.
- *
- * @throws JMSException If the queue could not be deleted for any reason.
- * @todo Be aware of possible changes to parameter order as versions change.
- */
- protected void deleteQueue(final AMQShortString queueName) throws JMSException
- {
- try
- {
- new FailoverRetrySupport<Object, AMQException>(new FailoverProtectedOperation<Object, AMQException>()
- {
- public Object execute() throws AMQException, FailoverException
- {
- sendQueueDelete(queueName);
- return null;
- }
- }, _connection).execute();
- }
- catch (AMQException e)
- {
- throw new JMSAMQException("The queue deletion failed: " + e.getMessage(), e);
- }
- }
-
- public abstract void sendQueueDelete(final AMQShortString queueName) throws AMQException, FailoverException;
-
- private long getNextProducerId()
- {
- return ++_nextProducerId;
- }
-
- protected AMQProtocolHandler getProtocolHandler()
- {
- return _connection.getProtocolHandler();
- }
-
- public byte getProtocolMajorVersion()
- {
- return getProtocolHandler().getProtocolMajorVersion();
- }
-
- public byte getProtocolMinorVersion()
- {
- return getProtocolHandler().getProtocolMinorVersion();
- }
-
- protected boolean hasMessageListeners()
- {
- return _hasMessageListeners;
- }
-
- private void markClosedConsumers() throws JMSException
- {
- if (_dispatcher != null)
- {
- _dispatcher.close();
- _dispatcher = null;
- }
- // we need to clone the list of consumers since the close() method updates the _consumers collection
- // which would result in a concurrent modification exception
- final ArrayList<C> clonedConsumers = new ArrayList<C>(_consumers.values());
-
- final Iterator<C> it = clonedConsumers.iterator();
- while (it.hasNext())
- {
- final C con = it.next();
- con.markClosed();
- }
- // at this point the _consumers map will be empty
- }
-
- private void markClosedProducersAndConsumers()
- {
- try
- {
- // no need for a markClosed* method in this case since there is no protocol traffic closing a producer
- closeProducers();
- }
- catch (JMSException e)
- {
- _logger.error("Error closing session: " + e, e);
- }
-
- try
- {
- markClosedConsumers();
- }
- catch (JMSException e)
- {
- _logger.error("Error closing session: " + e, e);
- }
- }
-
- /**
- * Callers must hold the failover mutex before calling this method.
- *
- * @param consumer
- *
- * @throws AMQException
- */
- private void registerConsumer(C consumer, boolean nowait) throws AMQException // , FailoverException
- {
- AMQDestination amqd = consumer.getDestination();
-
- AMQProtocolHandler protocolHandler = getProtocolHandler();
-
- if (amqd.getDestSyntax() == DestSyntax.ADDR)
- {
- handleAddressBasedDestination(amqd,true,nowait);
- }
- else
- {
- if (DECLARE_EXCHANGES)
- {
- declareExchange(amqd, protocolHandler, nowait);
- }
-
- if (DECLARE_QUEUES || amqd.isNameRequired())
- {
- declareQueue(amqd, protocolHandler, consumer.isNoLocal(), nowait);
- }
- bindQueue(amqd.getAMQQueueName(), amqd.getRoutingKey(), consumer.getArguments(), amqd.getExchangeName(), amqd, nowait);
- }
-
- AMQShortString queueName = amqd.getAMQQueueName();
-
- // store the consumer queue name
- consumer.setQueuename(queueName);
-
- // If IMMEDIATE_PREFETCH is not required then suspsend the channel to delay prefetch
- if (!_immediatePrefetch)
- {
- // The dispatcher will be null if we have just created this session
- // so suspend the channel before we register our consumer so that we don't
- // start prefetching until a receive/mListener is set.
- if (_dispatcher == null)
- {
- if (!isSuspended())
- {
- try
- {
- suspendChannel(true);
- _logger.info(
- "Prefetching delayed existing messages will not flow until requested via receive*() or setML().");
- }
- catch (AMQException e)
- {
- _logger.info("Suspending channel threw an exception:" + e);
- }
- }
- }
- }
- else
- {
- _logger.info("Immediately prefetching existing messages to new consumer.");
- }
-
- try
- {
- consumeFromQueue(consumer, queueName, protocolHandler, nowait, consumer._messageSelector);
- }
- catch (FailoverException e)
- {
- throw new AMQException(null, "Fail-over exception interrupted basic consume.", e);
- }
- }
-
- public abstract void handleAddressBasedDestination(AMQDestination dest,
- boolean isConsumer,
- boolean noWait) throws AMQException;
-
- private void registerProducer(long producerId, MessageProducer producer)
- {
- _producers.put(new Long(producerId), producer);
- }
-
- private void rejectAllMessages(boolean requeue)
- {
- rejectMessagesForConsumerTag(0, requeue, true);
- }
-
- /**
- * @param consumerTag The consumerTag to prune from queue or all if null
- * @param requeue Should the removed messages be requeued (or discarded. Possibly to DLQ)
- * @param rejectAllConsumers
- */
-
- private void rejectMessagesForConsumerTag(int consumerTag, boolean requeue, boolean rejectAllConsumers)
- {
- Iterator messages = _queue.iterator();
- if (_logger.isInfoEnabled())
- {
- _logger.info("Rejecting messages from _queue for Consumer tag(" + consumerTag + ") (PDispatchQ) requeue:"
- + requeue);
-
- if (messages.hasNext())
- {
- _logger.info("Checking all messages in _queue for Consumer tag(" + consumerTag + ")");
- }
- else
- {
- _logger.info("No messages in _queue to reject");
- }
- }
- while (messages.hasNext())
- {
- UnprocessedMessage message = (UnprocessedMessage) messages.next();
-
- if (rejectAllConsumers || (message.getConsumerTag() == consumerTag))
- {
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Removing message(" + System.identityHashCode(message) + ") from _queue DT:"
- + message.getDeliveryTag());
- }
-
- messages.remove();
-
- rejectMessage(message, requeue);
-
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Rejected the message(" + message.toString() + ") for consumer :" + consumerTag);
- }
- }
- }
- }
-
- private void resubscribeConsumers() throws AMQException
- {
- ArrayList<C> consumers = new ArrayList<C>(_consumers.values());
- _consumers.clear();
-
- for (C consumer : consumers)
- {
- consumer.failedOverPre();
- registerConsumer(consumer, true);
- consumer.failedOverPost();
- }
- }
-
- private void resubscribeProducers() throws AMQException
- {
- ArrayList producers = new ArrayList(_producers.values());
- _logger.info(MessageFormat.format("Resubscribing producers = {0} producers.size={1}", producers, producers.size())); // FIXME: removeKey
- for (Iterator it = producers.iterator(); it.hasNext();)
- {
- P producer = (P) it.next();
- producer.resubscribe();
- }
- }
-
- /**
- * Suspends or unsuspends this session.
- *
- * @param suspend <tt>true</tt> indicates that the session should be suspended, <tt>false<tt> indicates that it
- * should be unsuspended.
- *
- * @throws AMQException If the session cannot be suspended for any reason.
- * @todo Be aware of possible changes to parameter order as versions change.
- */
- protected void suspendChannel(boolean suspend) throws AMQException // , FailoverException
- {
- synchronized (_suspensionLock)
- {
- try
- {
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Setting channel flow : " + (suspend ? "suspended" : "unsuspended"));
- }
-
- _suspended = suspend;
- sendSuspendChannel(suspend);
- }
- catch (FailoverException e)
- {
- throw new AMQException(null, "Fail-over interrupted suspend/unsuspend channel.", e);
- }
- }
- }
-
- public abstract void sendSuspendChannel(boolean suspend) throws AMQException, FailoverException;
-
- Object getMessageDeliveryLock()
- {
- return _messageDeliveryLock;
- }
-
- /**
- * Indicates whether this session consumers pre-fetche messages
- *
- * @return true if this session consumers pre-fetche messages false otherwise
- */
- public boolean prefetch()
- {
- return getAMQConnection().getMaxPrefetch() > 0;
- }
-
- /** Signifies that the session has pending sends to commit. */
- public void markDirty()
- {
- _dirty = true;
- }
-
- /** Signifies that the session has no pending sends to commit. */
- public void markClean()
- {
- _dirty = false;
- _failedOverDirty = false;
- }
-
- /**
- * Check to see if failover has occured since the last call to markClean(commit or rollback).
- *
- * @return boolean true if failover has occured.
- */
- public boolean hasFailedOver()
- {
- return _failedOverDirty;
- }
-
- /**
- * Check to see if any message have been sent in this transaction and have not been commited.
- *
- * @return boolean true if a message has been sent but not commited
- */
- public boolean isDirty()
- {
- return _dirty;
- }
-
- public void setTicket(int ticket)
- {
- _ticket = ticket;
- }
-
- public void setFlowControl(final boolean active)
- {
- _flowControl.setFlowControl(active);
- _logger.warn("Broker enforced flow control " + (active ? "no longer in effect" : "has been enforced"));
- }
-
- public void checkFlowControl() throws InterruptedException, JMSException
- {
- long expiryTime = 0L;
- synchronized (_flowControl)
- {
- while (!_flowControl.getFlowControl() &&
- (expiryTime == 0L ? (expiryTime = System.currentTimeMillis() + FLOW_CONTROL_WAIT_FAILURE)
- : expiryTime) >= System.currentTimeMillis() )
- {
-
- _flowControl.wait(FLOW_CONTROL_WAIT_PERIOD);
- _logger.warn("Message send delayed by " + (System.currentTimeMillis() + FLOW_CONTROL_WAIT_FAILURE - expiryTime)/1000 + "s due to broker enforced flow control");
- }
- if(!_flowControl.getFlowControl())
- {
- _logger.error("Message send failed due to timeout waiting on broker enforced flow control");
- throw new JMSException("Unable to send message for " + FLOW_CONTROL_WAIT_FAILURE/1000 + " seconds due to broker enforced flow control");
- }
- }
-
- }
-
- public interface Dispatchable
- {
- void dispatch(AMQSession ssn);
- }
-
- public void dispatch(UnprocessedMessage message)
- {
- if (_dispatcher == null)
- {
- throw new java.lang.IllegalStateException("dispatcher is not started");
- }
-
- _dispatcher.dispatchMessage(message);
- }
-
- /** Used for debugging in the dispatcher. */
- private static final Logger _dispatcherLogger = LoggerFactory.getLogger("org.apache.qpid.client.AMQSession.Dispatcher");
-
- /** Responsible for decoding a message fragment and passing it to the appropriate message consumer. */
- class Dispatcher implements Runnable
- {
-
- /** Track the 'stopped' state of the dispatcher, a session starts in the stopped state. */
- private final AtomicBoolean _closed = new AtomicBoolean(false);
-
- private final Object _lock = new Object();
- private String dispatcherID = "" + System.identityHashCode(this);
-
- public Dispatcher()
- {
- }
-
- public void close()
- {
- _closed.set(true);
- _dispatcherThread.interrupt();
-
- // fixme awaitTermination
-
- }
-
- public void rejectPending(C consumer)
- {
- synchronized (_lock)
- {
- boolean stopped = _dispatcher.connectionStopped();
-
- if (!stopped)
- {
- _dispatcher.setConnectionStopped(true);
- }
-
- // Reject messages on pre-receive queue
- consumer.rollbackPendingMessages();
-
- // Reject messages on pre-dispatch queue
- rejectMessagesForConsumerTag(consumer.getConsumerTag(), true, false);
- //Let the dispatcher deal with this when it gets to them.
-
- // closeConsumer
- consumer.markClosed();
-
- _dispatcher.setConnectionStopped(stopped);
-
- }
- }
-
- public void rollback()
- {
-
- synchronized (_lock)
- {
- boolean isStopped = connectionStopped();
-
- if (!isStopped)
- {
- setConnectionStopped(true);
- }
-
- _rollbackMark.set(_highestDeliveryTag.get());
-
- _dispatcherLogger.debug("Session Pre Dispatch Queue cleared");
-
- for (C consumer : _consumers.values())
- {
- if (!consumer.isNoConsume())
- {
- consumer.rollback();
- }
- else
- {
- // should perhaps clear the _SQ here.
- // consumer._synchronousQueue.clear();
- consumer.clearReceiveQueue();
- }
-
- }
-
- for (int i = 0; i < _removedConsumers.size(); i++)
- {
- // Sends acknowledgement to server
- _removedConsumers.get(i).rollback();
- _removedConsumers.remove(i);
- }
-
- setConnectionStopped(isStopped);
- }
-
- }
-
- public void recover()
- {
-
- synchronized (_lock)
- {
- boolean isStopped = connectionStopped();
-
- if (!isStopped)
- {
- setConnectionStopped(true);
- }
-
- _dispatcherLogger.debug("Session clearing the consumer queues");
-
- for (C consumer : _consumers.values())
- {
- List<Long> tags = consumer.drainReceiverQueueAndRetrieveDeliveryTags();
- _unacknowledgedMessageTags.addAll(tags);
- }
-
- setConnectionStopped(isStopped);
- }
-
- }
-
-
- public void run()
- {
- if (_dispatcherLogger.isInfoEnabled())
- {
- _dispatcherLogger.info(_dispatcherThread.getName() + " started");
- }
-
- UnprocessedMessage message;
-
- // Allow disptacher to start stopped
- synchronized (_lock)
- {
- while (!_closed.get() && connectionStopped())
- {
- try
- {
- _lock.wait();
- }
- catch (InterruptedException e)
- {
- // ignore
- }
- }
- }
-
- try
- {
- Dispatchable disp;
- while (!_closed.get() && ((disp = (Dispatchable) _queue.take()) != null))
- {
- disp.dispatch(AMQSession.this);
- }
- }
- catch (InterruptedException e)
- {
- // ignore
- }
-
- if (_dispatcherLogger.isInfoEnabled())
- {
- _dispatcherLogger.info(_dispatcherThread.getName() + " thread terminating for channel " + _channelId + ":" + _thisSession);
- }
-
- }
-
- // only call while holding lock
- final boolean connectionStopped()
- {
- return _connectionStopped;
- }
-
- boolean setConnectionStopped(boolean connectionStopped)
- {
- boolean currently;
- synchronized (_lock)
- {
- currently = _connectionStopped;
- _connectionStopped = connectionStopped;
- _lock.notify();
-
- if (_dispatcherLogger.isDebugEnabled())
- {
- _dispatcherLogger.debug("Set Dispatcher Connection " + (connectionStopped ? "Stopped" : "Started")
- + ": Currently " + (currently ? "Stopped" : "Started"));
- }
- }
-
- return currently;
- }
-
- private void dispatchMessage(UnprocessedMessage message)
- {
- long deliveryTag = message.getDeliveryTag();
-
- synchronized (_lock)
- {
-
- try
- {
- while (connectionStopped())
- {
- _lock.wait();
- }
- }
- catch (InterruptedException e)
- {
- // pass
- }
-
- if (!(message instanceof CloseConsumerMessage)
- && tagLE(deliveryTag, _rollbackMark.get()))
- {
- rejectMessage(message, true);
- }
- else if (isInRecovery())
- {
- _unacknowledgedMessageTags.add(deliveryTag);
- }
- else
- {
- synchronized (_messageDeliveryLock)
- {
- notifyConsumer(message);
- }
- }
- }
-
- long current = _rollbackMark.get();
- if (updateRollbackMark(current, deliveryTag))
- {
- _rollbackMark.compareAndSet(current, deliveryTag);
- }
- }
-
- private void notifyConsumer(UnprocessedMessage message)
- {
- final C consumer = _consumers.get(message.getConsumerTag());
-
- if ((consumer == null) || consumer.isClosed())
- {
- if (_dispatcherLogger.isInfoEnabled())
- {
- if (consumer == null)
- {
- _dispatcherLogger.info("Dispatcher(" + dispatcherID + ")Received a message("
- + System.identityHashCode(message) + ")" + "["
- + message.getDeliveryTag() + "] from queue "
- + message.getConsumerTag() + " )without a handler - rejecting(requeue)...");
- }
- else
- {
- if (consumer.isNoConsume())
- {
- _dispatcherLogger.info("Received a message("
- + System.identityHashCode(message) + ")" + "["
- + message.getDeliveryTag() + "] from queue " + " consumer("
- + message.getConsumerTag() + ") is closed and a browser so dropping...");
- //DROP MESSAGE
- return;
-
- }
- else
- {
- _dispatcherLogger.info("Received a message("
- + System.identityHashCode(message) + ")" + "["
- + message.getDeliveryTag() + "] from queue " + " consumer("
- + message.getConsumerTag() + ") is closed rejecting(requeue)...");
- }
- }
- }
- // Don't reject if we're already closing
- if (!_closed.get())
- {
- rejectMessage(message, true);
- }
- }
- else
- {
- consumer.notifyMessage(message);
- }
- }
- }
-
- protected abstract boolean tagLE(long tag1, long tag2);
-
- protected abstract boolean updateRollbackMark(long current, long deliveryTag);
-
- public abstract AMQMessageDelegateFactory getMessageDelegateFactory();
-
- /*public void requestAccess(AMQShortString realm, boolean exclusive, boolean passive, boolean active, boolean write,
- boolean read) throws AMQException
- {
- getProtocolHandler().writeCommandFrameAndWaitForReply(AccessRequestBody.createAMQFrame(getChannelId(),
- getProtocolMajorVersion(), getProtocolMinorVersion(), active, exclusive, passive, read, realm, write),
- new BlockingMethodFrameListener(_channelId)
- {
-
- public boolean processMethod(int channelId, AMQMethodBody frame) // throws AMQException
- {
- if (frame instanceof AccessRequestOkBody)
- {
- setTicket(((AccessRequestOkBody) frame).getTicket());
-
- return true;
- }
- else
- {
- return false;
- }
- }
- });
- }*/
-
- private class SuspenderRunner implements Runnable
- {
- private AtomicBoolean _suspend;
-
- public SuspenderRunner(AtomicBoolean suspend)
- {
- _suspend = suspend;
- }
-
- public void run()
- {
- try
- {
- synchronized (_suspensionLock)
- {
- // If the session has closed by the time we get here
- // then we should not attempt to write to the sesion/channel.
- if (!(_thisSession.isClosed() || _thisSession.isClosing()))
- {
- suspendChannel(_suspend.get());
- }
- }
- }
- catch (AMQException e)
- {
- _logger.warn("Unable to " + (_suspend.get() ? "suspend" : "unsuspend") + " session " + _thisSession + " due to: " + e);
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Is the _queue empty?" + _queue.isEmpty());
- _logger.debug("Is the dispatcher closed?" + (_dispatcher == null ? "it's Null" : _dispatcher._closed));
- }
- }
- }
- }
-
- /**
- * Checks if the Session and its parent connection are closed
- *
- * @return <tt>true</tt> if this is closed, <tt>false</tt> otherwise.
- */
- @Override
- public boolean isClosed()
- {
- return _closed.get() || _connection.isClosed();
- }
-
- /**
- * Checks if the Session and its parent connection are capable of performing
- * closing operations
- *
- * @return <tt>true</tt> if we are closing, <tt>false</tt> otherwise.
- */
- @Override
- public boolean isClosing()
- {
- return _closing.get()|| _connection.isClosing();
- }
-
- public boolean isDeclareExchanges()
- {
- return DECLARE_EXCHANGES;
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/AMQSessionAdapter.java b/java/client/src/main/java/org/apache/qpid/client/AMQSessionAdapter.java
deleted file mode 100644
index 7e257e0c20..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/AMQSessionAdapter.java
+++ /dev/null
@@ -1,26 +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.client;
-
-public interface AMQSessionAdapter
-{
- public AMQSession getSession();
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/AMQSessionDirtyException.java b/java/client/src/main/java/org/apache/qpid/client/AMQSessionDirtyException.java
deleted file mode 100644
index a1b240ed54..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/AMQSessionDirtyException.java
+++ /dev/null
@@ -1,42 +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.client;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.protocol.AMQConstant;
-
-/**
- * AMQSessionDirtyException represents all failures to send data on a transacted session that is
- * no longer in a state that the client expects. i.e. failover has occured so previously sent messages
- * will not be part of the transaction.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Represent attempt to perform additional sends on a dirty session.
- * </table>
- */
-public class AMQSessionDirtyException extends AMQException
-{
- public AMQSessionDirtyException(String msg)
- {
- super(AMQConstant.RESOURCE_ERROR, msg, null);
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/AMQSession_0_10.java b/java/client/src/main/java/org/apache/qpid/client/AMQSession_0_10.java
deleted file mode 100644
index 1ea92c67f7..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/AMQSession_0_10.java
+++ /dev/null
@@ -1,1372 +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.client;
-
-import static org.apache.qpid.transport.Option.BATCH;
-import static org.apache.qpid.transport.Option.NONE;
-import static org.apache.qpid.transport.Option.SYNC;
-import static org.apache.qpid.transport.Option.UNRELIABLE;
-
-import java.lang.ref.WeakReference;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Timer;
-import java.util.TimerTask;
-import java.util.UUID;
-
-import javax.jms.Destination;
-import javax.jms.JMSException;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.AMQDestination.AddressOption;
-import org.apache.qpid.client.AMQDestination.Binding;
-import org.apache.qpid.client.AMQDestination.DestSyntax;
-import org.apache.qpid.client.failover.FailoverException;
-import org.apache.qpid.client.failover.FailoverNoopSupport;
-import org.apache.qpid.client.failover.FailoverProtectedOperation;
-import org.apache.qpid.client.message.AMQMessageDelegateFactory;
-import org.apache.qpid.client.message.FieldTableSupport;
-import org.apache.qpid.client.message.MessageFactoryRegistry;
-import org.apache.qpid.client.message.UnprocessedMessage_0_10;
-import org.apache.qpid.client.messaging.address.Link;
-import org.apache.qpid.client.messaging.address.Link.Reliability;
-import org.apache.qpid.client.messaging.address.Node.ExchangeNode;
-import org.apache.qpid.client.messaging.address.Node.QueueNode;
-import org.apache.qpid.client.protocol.AMQProtocolHandler;
-import org.apache.qpid.exchange.ExchangeDefaults;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.FieldTable;
-import org.apache.qpid.protocol.AMQConstant;
-import org.apache.qpid.transport.ExchangeBoundResult;
-import org.apache.qpid.transport.ExchangeQueryResult;
-import org.apache.qpid.transport.ExecutionErrorCode;
-import org.apache.qpid.transport.ExecutionException;
-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.MessageTransfer;
-import org.apache.qpid.transport.Option;
-import org.apache.qpid.transport.QueueQueryResult;
-import org.apache.qpid.transport.Range;
-import org.apache.qpid.transport.RangeSet;
-import org.apache.qpid.transport.Session;
-import org.apache.qpid.transport.SessionException;
-import org.apache.qpid.transport.SessionListener;
-import org.apache.qpid.util.Serial;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * This is a 0.10 Session
- */
-public class AMQSession_0_10 extends AMQSession<BasicMessageConsumer_0_10, BasicMessageProducer_0_10>
- implements SessionListener
-{
-
- /**
- * This class logger
- */
- private static final Logger _logger = LoggerFactory.getLogger(AMQSession_0_10.class);
-
- private static Timer timer = new Timer("ack-flusher", true);
- private static class Flusher extends TimerTask
- {
-
- private WeakReference<AMQSession_0_10> session;
- public Flusher(AMQSession_0_10 session)
- {
- this.session = new WeakReference<AMQSession_0_10>(session);
- }
-
- public void run() {
- AMQSession_0_10 ssn = session.get();
- if (ssn == null)
- {
- cancel();
- }
- else
- {
- try
- {
- ssn.flushAcknowledgments(true);
- }
- catch (Throwable t)
- {
- _logger.error("error flushing acks", t);
- }
- }
- }
- }
-
-
- /**
- * The underlying QpidSession
- */
- private Session _qpidSession;
-
- /**
- * The latest qpid Exception that has been raised.
- */
- private Object _currentExceptionLock = new Object();
- private AMQException _currentException;
-
- // a ref on the qpid connection
- protected org.apache.qpid.transport.Connection _qpidConnection;
-
- private long maxAckDelay = Long.getLong("qpid.session.max_ack_delay", 1000);
- private TimerTask flushTask = null;
- private RangeSet unacked = new RangeSet();
- private int unackedCount = 0;
-
- /**
- * USed to store the range of in tx messages
- */
- private RangeSet _txRangeSet = new RangeSet();
- private int _txSize = 0;
- //--- constructors
-
- /**
- * Creates a new session on a connection.
- *
- * @param con The connection on which to create the session.
- * @param channelId The unique identifier for the session.
- * @param transacted Indicates whether or not the session is transactional.
- * @param acknowledgeMode The acknowledgement mode for the session.
- * @param messageFactoryRegistry The message factory factory for the session.
- * @param defaultPrefetchHighMark The maximum number of messages to prefetched before suspending the session.
- * @param defaultPrefetchLowMark The number of prefetched messages at which to resume the session.
- * @param qpidConnection The qpid connection
- */
- AMQSession_0_10(org.apache.qpid.transport.Connection qpidConnection, AMQConnection con, int channelId,
- boolean transacted, int acknowledgeMode, MessageFactoryRegistry messageFactoryRegistry,
- int defaultPrefetchHighMark, int defaultPrefetchLowMark)
- {
-
- super(con, channelId, transacted, acknowledgeMode, messageFactoryRegistry, defaultPrefetchHighMark,
- defaultPrefetchLowMark);
- _qpidConnection = qpidConnection;
- _qpidSession = _qpidConnection.createSession(1);
- _qpidSession.setSessionListener(this);
- if (_transacted)
- {
- _qpidSession.txSelect();
- _qpidSession.setTransacted(true);
- }
-
- if (maxAckDelay > 0)
- {
- flushTask = new Flusher(this);
- timer.schedule(flushTask, new Date(), maxAckDelay);
- }
- }
-
- /**
- * Creates a new session on a connection with the default 0-10 message factory.
- *
- * @param con The connection on which to create the session.
- * @param channelId The unique identifier for the session.
- * @param transacted Indicates whether or not the session is transactional.
- * @param acknowledgeMode The acknowledgement mode for the session.
- * @param defaultPrefetchHigh The maximum number of messages to prefetched before suspending the session.
- * @param defaultPrefetchLow The number of prefetched messages at which to resume the session.
- * @param qpidConnection The connection
- */
- AMQSession_0_10(org.apache.qpid.transport.Connection qpidConnection, AMQConnection con, int channelId,
- boolean transacted, int acknowledgeMode, int defaultPrefetchHigh, int defaultPrefetchLow)
- {
-
- this(qpidConnection, con, channelId, transacted, acknowledgeMode, MessageFactoryRegistry.newDefaultRegistry(),
- defaultPrefetchHigh, defaultPrefetchLow);
- }
-
- private void addUnacked(int id)
- {
- synchronized (unacked)
- {
- unacked.add(id);
- unackedCount++;
- }
- }
-
- private void clearUnacked()
- {
- synchronized (unacked)
- {
- unacked.clear();
- unackedCount = 0;
- }
- }
-
- //------- overwritten methods of class AMQSession
-
- void failoverPrep()
- {
- super.failoverPrep();
- clearUnacked();
- }
-
- /**
- * Acknowledge one or many messages.
- *
- * @param deliveryTag The tag of the last message to be acknowledged.
- * @param multiple <tt>true</tt> to acknowledge all messages up to and including the one specified by the
- * delivery tag, <tt>false</tt> to just acknowledge that message.
- */
-
- public void acknowledgeMessage(long deliveryTag, boolean multiple)
- {
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Sending ack for delivery tag " + deliveryTag + " on session " + _channelId);
- }
- // acknowledge this message
- if (multiple)
- {
- for (Long messageTag : _unacknowledgedMessageTags)
- {
- if( messageTag <= deliveryTag )
- {
- addUnacked(messageTag.intValue());
- _unacknowledgedMessageTags.remove(messageTag);
- }
- }
- //empty the list of unack messages
-
- }
- else
- {
- addUnacked((int) deliveryTag);
- _unacknowledgedMessageTags.remove(deliveryTag);
- }
-
- long prefetch = getAMQConnection().getMaxPrefetch();
-
- if (unackedCount >= prefetch/2 || maxAckDelay <= 0)
- {
- flushAcknowledgments();
- }
- }
-
- protected void flushAcknowledgments()
- {
- flushAcknowledgments(false);
- }
-
- void flushAcknowledgments(boolean setSyncBit)
- {
- synchronized (unacked)
- {
- if (unackedCount > 0)
- {
- messageAcknowledge
- (unacked, _acknowledgeMode != org.apache.qpid.jms.Session.NO_ACKNOWLEDGE,setSyncBit);
- clearUnacked();
- }
- }
- }
-
- void messageAcknowledge(RangeSet ranges, boolean accept)
- {
- messageAcknowledge(ranges,accept,false);
- }
-
- void messageAcknowledge(RangeSet ranges, boolean accept,boolean setSyncBit)
- {
- Session ssn = getQpidSession();
- for (Range range : ranges)
- {
- ssn.processed(range);
- }
- ssn.flushProcessed(accept ? BATCH : NONE);
- if (accept)
- {
- ssn.messageAccept(ranges, UNRELIABLE,setSyncBit? SYNC : NONE);
- }
- }
-
- /**
- * Bind a queue with an exchange.
- *
- * @param queueName Specifies the name of the queue to bind. If the queue name is empty,
- * refers to the current
- * queue for the session, which is the last declared queue.
- * @param exchangeName The exchange name.
- * @param routingKey Specifies the routing key for the binding.
- * @param arguments 0_8 specific
- */
- public void sendQueueBind(final AMQShortString queueName, final AMQShortString routingKey,
- final FieldTable arguments, final AMQShortString exchangeName,
- final AMQDestination destination, final boolean nowait)
- throws AMQException
- {
- if (destination.getDestSyntax() == DestSyntax.BURL)
- {
- Map args = FieldTableSupport.convertToMap(arguments);
-
- for (AMQShortString rk: destination.getBindingKeys())
- {
- _logger.debug("Binding queue : " + queueName.toString() +
- " exchange: " + exchangeName.toString() +
- " using binding key " + rk.asString());
- getQpidSession().exchangeBind(queueName.toString(),
- exchangeName.toString(),
- rk.toString(),
- args);
- }
- }
- else
- {
- List<Binding> bindings = new ArrayList<Binding>();
- bindings.addAll(destination.getSourceNode().getBindings());
- bindings.addAll(destination.getTargetNode().getBindings());
-
- String defaultExchange = destination.getAddressType() == AMQDestination.TOPIC_TYPE ?
- destination.getAddressName(): "amq.topic";
-
- for (Binding binding: bindings)
- {
- String queue = binding.getQueue() == null?
- queueName.asString(): binding.getQueue();
-
- String exchange = binding.getExchange() == null ?
- defaultExchange :
- binding.getExchange();
-
- _logger.debug("Binding queue : " + queue +
- " exchange: " + exchange +
- " using binding key " + binding.getBindingKey() +
- " with args " + printMap(binding.getArgs()));
- getQpidSession().exchangeBind(queue,
- exchange,
- binding.getBindingKey(),
- binding.getArgs());
- }
- }
-
- if (!nowait)
- {
- // We need to sync so that we get notify of an error.
- sync();
- }
- }
-
-
- /**
- * Close this session.
- *
- * @param timeout no used / 0_8 specific
- * @throws AMQException
- * @throws FailoverException
- */
- public void sendClose(long timeout) throws AMQException, FailoverException
- {
- if (flushTask != null)
- {
- flushTask.cancel();
- flushTask = null;
- }
- flushAcknowledgments();
- try
- {
- getQpidSession().sync();
- getQpidSession().close();
- }
- catch (SessionException se)
- {
- setCurrentException(se);
- }
-
- AMQException amqe = getCurrentException();
- if (amqe != null)
- {
- throw amqe;
- }
- }
-
-
- /**
- * Commit the receipt and the delivery of all messages exchanged by this session resources.
- */
- public void sendCommit() throws AMQException, FailoverException
- {
- getQpidSession().setAutoSync(true);
- try
- {
- getQpidSession().txCommit();
- }
- finally
- {
- getQpidSession().setAutoSync(false);
- }
- // We need to sync so that we get notify of an error.
- sync();
- }
-
- /**
- * Create a queue with a given name.
- *
- * @param name The queue name
- * @param autoDelete If this field is set and the exclusive field is also set,
- * then the queue is deleted when the connection closes.
- * @param durable If set when creating a new queue,
- * the queue will be marked as durable.
- * @param exclusive Exclusive queues can only be used from one connection at a time.
- * @param arguments Exclusive queues can only be used from one connection at a time.
- * @throws AMQException
- * @throws FailoverException
- */
- public void sendCreateQueue(AMQShortString name, final boolean autoDelete, final boolean durable,
- final boolean exclusive, Map<String, Object> arguments) throws AMQException, FailoverException
- {
- getQpidSession().queueDeclare(name.toString(), null, arguments, durable ? Option.DURABLE : Option.NONE,
- autoDelete ? Option.AUTO_DELETE : Option.NONE,
- exclusive ? Option.EXCLUSIVE : Option.NONE);
- // We need to sync so that we get notify of an error.
- sync();
- }
-
- /**
- * This method asks the broker to redeliver all unacknowledged messages
- *
- * @throws AMQException
- * @throws FailoverException
- */
- public void sendRecover() throws AMQException, FailoverException
- {
- // release all unacked messages
- RangeSet ranges = new RangeSet();
- while (true)
- {
- Long tag = _unacknowledgedMessageTags.poll();
- if (tag == null)
- {
- break;
- }
- ranges.add((int) (long) tag);
- }
- getQpidSession().messageRelease(ranges, Option.SET_REDELIVERED);
- // We need to sync so that we get notify of an error.
- sync();
- }
-
-
- public void releaseForRollback()
- {
- getQpidSession().messageRelease(_txRangeSet, Option.SET_REDELIVERED);
- _txRangeSet.clear();
- _txSize = 0;
- }
-
- /**
- * Release (0_8 notion of Reject) an acquired message
- *
- * @param deliveryTag the message ID
- * @param requeue always true
- */
- public void rejectMessage(long deliveryTag, boolean requeue)
- {
- // The value of requeue is always true
- RangeSet ranges = new RangeSet();
- ranges.add((int) deliveryTag);
- getQpidSession().messageRelease(ranges, Option.SET_REDELIVERED);
- //I don't think we need to sync
- }
-
- /**
- * Create an 0_10 message consumer
- */
- public BasicMessageConsumer_0_10 createMessageConsumer(final AMQDestination destination, final int prefetchHigh,
- final int prefetchLow, final boolean noLocal,
- final boolean exclusive, String messageSelector,
- final FieldTable ft, final boolean noConsume,
- final boolean autoClose) throws JMSException
- {
-
- final AMQProtocolHandler protocolHandler = getProtocolHandler();
- return new BasicMessageConsumer_0_10(_channelId, _connection, destination, messageSelector, noLocal,
- _messageFactoryRegistry, this, protocolHandler, ft, prefetchHigh,
- prefetchLow, exclusive, _acknowledgeMode, noConsume, autoClose);
- }
-
- /**
- * Bind a queue with an exchange.
- */
-
- public boolean isQueueBound(final AMQShortString exchangeName, final AMQShortString queueName, final AMQShortString routingKey)
- throws JMSException
- {
- return isQueueBound(exchangeName,queueName,routingKey,null);
- }
-
- public boolean isQueueBound(final AMQDestination destination) throws JMSException
- {
- return isQueueBound(destination.getExchangeName(),destination.getAMQQueueName(),destination.getRoutingKey(),destination.getBindingKeys());
- }
-
- public boolean isQueueBound(final AMQShortString exchangeName, final AMQShortString queueName, final AMQShortString routingKey,AMQShortString[] bindingKeys)
- throws JMSException
- {
- String rk = null;
- if (bindingKeys != null && bindingKeys.length>0)
- {
- rk = bindingKeys[0].toString();
- }
- else if (routingKey != null)
- {
- rk = routingKey.toString();
- }
-
- return isQueueBound(exchangeName.toString(),queueName.toString(),rk,null);
- }
-
- public boolean isQueueBound(final String exchangeName, final String queueName, final String bindingKey,Map<String,Object> args)
- throws JMSException
- {
- boolean res;
- ExchangeBoundResult bindingQueryResult =
- getQpidSession().exchangeBound(exchangeName,queueName, bindingKey, args).get();
-
- if (bindingKey == null)
- {
- res = !(bindingQueryResult.getExchangeNotFound() || bindingQueryResult.getQueueNotFound());
- }
- else
- {
- if (args == null)
- {
- res = !(bindingQueryResult.getKeyNotMatched() || bindingQueryResult.getQueueNotFound() || bindingQueryResult
- .getQueueNotMatched());
- }
- else
- {
- res = !(bindingQueryResult.getKeyNotMatched() || bindingQueryResult.getQueueNotFound() || bindingQueryResult
- .getQueueNotMatched() || bindingQueryResult.getArgsNotMatched());
- }
- }
- return res;
- }
-
- /**
- * This method is invoked when a consumer is created
- * Registers the consumer with the broker
- */
- public void sendConsume(BasicMessageConsumer_0_10 consumer, AMQShortString queueName, AMQProtocolHandler protocolHandler,
- boolean nowait, String messageSelector, int tag)
- throws AMQException, FailoverException
- {
- boolean preAcquire;
-
- long capacity = getCapacity(consumer.getDestination());
-
- try
- {
- boolean isTopic;
- Map<String, Object> arguments = FieldTable.convertToMap(consumer.getArguments());
-
- if (consumer.getDestination().getDestSyntax() == AMQDestination.DestSyntax.BURL)
- {
- isTopic = consumer.getDestination() instanceof AMQTopic ||
- consumer.getDestination().getExchangeClass().equals(ExchangeDefaults.TOPIC_EXCHANGE_CLASS) ;
-
- preAcquire = isTopic || (!consumer.isNoConsume() &&
- (consumer.getMessageSelector() == null || consumer.getMessageSelector().equals("")));
- }
- else
- {
- isTopic = consumer.getDestination().getAddressType() == AMQDestination.TOPIC_TYPE;
-
- preAcquire = !consumer.isNoConsume() &&
- (isTopic || consumer.getMessageSelector() == null ||
- consumer.getMessageSelector().equals(""));
-
- arguments.putAll(
- (Map<? extends String, ? extends Object>) consumer.getDestination().getLink().getSubscription().getArgs());
- }
-
- boolean acceptModeNone = getAcknowledgeMode() == NO_ACKNOWLEDGE;
-
- if (consumer.getDestination().getLink() != null)
- {
- acceptModeNone = consumer.getDestination().getLink().getReliability() == Link.Reliability.UNRELIABLE;
- }
-
- getQpidSession().messageSubscribe
- (queueName.toString(), String.valueOf(tag),
- acceptModeNone ? MessageAcceptMode.NONE : MessageAcceptMode.EXPLICIT,
- preAcquire ? MessageAcquireMode.PRE_ACQUIRED : MessageAcquireMode.NOT_ACQUIRED, null, 0, arguments,
- consumer.isExclusive() ? Option.EXCLUSIVE : Option.NONE);
- }
- catch (JMSException e)
- {
- throw new AMQException(AMQConstant.INTERNAL_ERROR, "problem when registering consumer", e);
- }
-
- String consumerTag = ((BasicMessageConsumer_0_10)consumer).getConsumerTagString();
-
- if (capacity == 0)
- {
- getQpidSession().messageSetFlowMode(consumerTag, MessageFlowMode.CREDIT);
- }
- else
- {
- getQpidSession().messageSetFlowMode(consumerTag, MessageFlowMode.WINDOW);
- }
- getQpidSession().messageFlow(consumerTag, MessageCreditUnit.BYTE, 0xFFFFFFFF,
- Option.UNRELIABLE);
-
- if(capacity > 0 && _dispatcher != null && (isStarted() || _immediatePrefetch))
- {
- // set the flow
- getQpidSession().messageFlow(consumerTag,
- MessageCreditUnit.MESSAGE,
- capacity,
- Option.UNRELIABLE);
- }
-
- if (!nowait)
- {
- sync();
- }
- }
-
- private long getCapacity(AMQDestination destination)
- {
- long capacity = 0;
- if (destination.getDestSyntax() == DestSyntax.ADDR &&
- destination.getLink().getConsumerCapacity() > 0)
- {
- capacity = destination.getLink().getConsumerCapacity();
- }
- else if (prefetch())
- {
- capacity = getAMQConnection().getMaxPrefetch();
- }
- return capacity;
- }
-
- /**
- * Create an 0_10 message producer
- */
- public BasicMessageProducer_0_10 createMessageProducer(final Destination destination, final boolean mandatory,
- final boolean immediate, final boolean waitUntilSent,
- long producerId) throws JMSException
- {
- try
- {
- return new BasicMessageProducer_0_10(_connection, (AMQDestination) destination, _transacted, _channelId, this,
- getProtocolHandler(), producerId, immediate, mandatory, waitUntilSent);
- }
- catch (AMQException e)
- {
- JMSException ex = new JMSException("Error creating producer");
- ex.initCause(e);
- ex.setLinkedException(e);
-
- throw ex;
- }
-
- }
-
- /**
- * creates an exchange if it does not already exist
- */
- public void sendExchangeDeclare(final AMQShortString name,
- final AMQShortString type,
- final AMQProtocolHandler protocolHandler, final boolean nowait)
- throws AMQException, FailoverException
- {
- sendExchangeDeclare(name.asString(), type.asString(), null, null,
- nowait);
- }
-
- public void sendExchangeDeclare(final String name, final String type,
- final String alternateExchange, final Map<String, Object> args,
- final boolean nowait) throws AMQException
- {
- getQpidSession().exchangeDeclare(
- name,
- type,
- alternateExchange,
- args,
- name.toString().startsWith("amq.") ? Option.PASSIVE
- : Option.NONE);
- // We need to sync so that we get notify of an error.
- if (!nowait)
- {
- sync();
- }
- }
-
- /**
- * deletes an exchange
- */
- public void sendExchangeDelete(final String name, final boolean nowait)
- throws AMQException, FailoverException
- {
- getQpidSession().exchangeDelete(name);
- // We need to sync so that we get notify of an error.
- if (!nowait)
- {
- sync();
- }
- }
-
- /**
- * Declare a queue with the given queueName
- */
- public void sendQueueDeclare(final AMQDestination amqd, final AMQProtocolHandler protocolHandler,
- final boolean nowait)
- throws AMQException, FailoverException
- {
- // do nothing this is only used by 0_8
- }
-
- /**
- * Declare a queue with the given queueName
- */
- public AMQShortString send0_10QueueDeclare(final AMQDestination amqd, final AMQProtocolHandler protocolHandler,
- final boolean noLocal, final boolean nowait)
- throws AMQException
- {
- AMQShortString queueName;
- if (amqd.getAMQQueueName() == null)
- {
- // generate a name for this queue
- queueName = new AMQShortString("TempQueue" + UUID.randomUUID());
- amqd.setQueueName(queueName);
- }
- else
- {
- queueName = amqd.getAMQQueueName();
- }
-
- if (amqd.getDestSyntax() == DestSyntax.BURL)
- {
- Map<String,Object> arguments = new HashMap<String,Object>();
- if (noLocal)
- {
- arguments.put("no-local", true);
- }
-
- getQpidSession().queueDeclare(queueName.toString(), "" , arguments,
- amqd.isAutoDelete() ? Option.AUTO_DELETE : Option.NONE,
- amqd.isDurable() ? Option.DURABLE : Option.NONE,
- amqd.isExclusive() ? Option.EXCLUSIVE : Option.NONE);
- }
- else
- {
- QueueNode node = (QueueNode)amqd.getSourceNode();
- getQpidSession().queueDeclare(queueName.toString(), node.getAlternateExchange() ,
- node.getDeclareArgs(),
- node.isAutoDelete() ? Option.AUTO_DELETE : Option.NONE,
- node.isDurable() ? Option.DURABLE : Option.NONE,
- node.isExclusive() ? Option.EXCLUSIVE : Option.NONE);
- }
-
- // passive --> false
- if (!nowait)
- {
- // We need to sync so that we get notify of an error.
- sync();
- }
- return queueName;
- }
-
- /**
- * deletes a queue
- */
- public void sendQueueDelete(final AMQShortString queueName) throws AMQException, FailoverException
- {
- getQpidSession().queueDelete(queueName.toString());
- // ifEmpty --> false
- // ifUnused --> false
- // We need to sync so that we get notify of an error.
- sync();
- }
-
- /**
- * Activate/deactivate the message flow for all the consumers of this session.
- */
- public void sendSuspendChannel(boolean suspend) throws AMQException, FailoverException
- {
- if (suspend)
- {
- for (BasicMessageConsumer consumer : _consumers.values())
- {
- getQpidSession().messageStop(String.valueOf(consumer.getConsumerTag()),
- Option.UNRELIABLE);
- }
- }
- else
- {
- for (BasicMessageConsumer_0_10 consumer : _consumers.values())
- {
- String consumerTag = String.valueOf(consumer.getConsumerTag());
- //only set if msg list is null
- try
- {
- long capacity = getCapacity(consumer.getDestination());
-
- if (capacity == 0)
- {
- if (consumer.getMessageListener() != null)
- {
- getQpidSession().messageFlow(consumerTag,
- MessageCreditUnit.MESSAGE, 1,
- Option.UNRELIABLE);
- }
- }
- else
- {
- getQpidSession()
- .messageFlow(consumerTag, MessageCreditUnit.MESSAGE,
- capacity,
- Option.UNRELIABLE);
- }
- getQpidSession()
- .messageFlow(consumerTag, MessageCreditUnit.BYTE, 0xFFFFFFFF,
- Option.UNRELIABLE);
- }
- catch (Exception e)
- {
- throw new AMQException(AMQConstant.INTERNAL_ERROR, "Error while trying to get the listener", e);
- }
- }
- }
- // We need to sync so that we get notify of an error.
- sync();
- }
-
-
- public void sendRollback() throws AMQException, FailoverException
- {
- getQpidSession().txRollback();
- // We need to sync so that we get notify of an error.
- sync();
- }
-
- //------ Private methods
- /**
- * Access to the underlying Qpid Session
- *
- * @return The associated Qpid Session.
- */
- protected Session getQpidSession()
- {
- return _qpidSession;
- }
-
-
- /**
- * Get the latest thrown exception.
- *
- * @throws SessionException get the latest thrown error.
- */
- public AMQException getCurrentException()
- {
- AMQException amqe = null;
- synchronized (_currentExceptionLock)
- {
- if (_currentException != null)
- {
- amqe = _currentException;
- _currentException = null;
- }
- }
- return amqe;
- }
-
- public void opened(Session ssn) {}
-
- public void resumed(Session ssn)
- {
- _qpidConnection = ssn.getConnection();
- }
-
- public void message(Session ssn, MessageTransfer xfr)
- {
- messageReceived(new UnprocessedMessage_0_10(xfr));
- }
-
- public void exception(Session ssn, SessionException exc)
- {
- setCurrentException(exc);
- }
-
- public void closed(Session ssn)
- {
- try
- {
- super.closed(null);
- if (flushTask != null)
- {
- flushTask.cancel();
- flushTask = null;
- }
- } catch (Exception e)
- {
- _logger.error("Error closing JMS session", e);
- }
- }
-
- public AMQException getLastException()
- {
- return getCurrentException();
- }
-
- protected AMQShortString declareQueue(final AMQDestination amqd, final AMQProtocolHandler protocolHandler,
- final boolean noLocal, final boolean nowait)
- throws AMQException
- {
- /*return new FailoverRetrySupport<AMQShortString, AMQException>(*/
- return new FailoverNoopSupport<AMQShortString, AMQException>(
- new FailoverProtectedOperation<AMQShortString, AMQException>()
- {
- public AMQShortString execute() throws AMQException, FailoverException
- {
- // Generate the queue name if the destination indicates that a client generated name is to be used.
- if (amqd.isNameRequired())
- {
- String binddingKey = "";
- for(AMQShortString key : amqd.getBindingKeys())
- {
- binddingKey = binddingKey + "_" + key.toString();
- }
- amqd.setQueueName(new AMQShortString( binddingKey + "@"
- + amqd.getExchangeName().toString() + "_" + UUID.randomUUID()));
- }
- return send0_10QueueDeclare(amqd, protocolHandler, noLocal, nowait);
- }
- }, _connection).execute();
- }
-
- protected Long requestQueueDepth(AMQDestination amqd)
- {
- flushAcknowledgments();
- return getQpidSession().queueQuery(amqd.getQueueName()).get().getMessageCount();
- }
-
-
- /**
- * Store non committed messages for this session
- * With 0.10 messages are consumed with window mode, we must send a completion
- * before the window size is reached so credits don't dry up.
- * @param id
- */
- @Override protected void addDeliveredMessage(long id)
- {
- _txRangeSet.add((int) id);
- _txSize++;
- // this is a heuristic, we may want to have that configurable
- if (_connection.getMaxPrefetch() == 1 ||
- _connection.getMaxPrefetch() != 0 && _txSize % (_connection.getMaxPrefetch() / 2) == 0)
- {
- // send completed so consumer credits don't dry up
- messageAcknowledge(_txRangeSet, false);
- }
- }
-
- @Override public void commit() throws JMSException
- {
- checkTransacted();
- try
- {
- if( _txSize > 0 )
- {
- messageAcknowledge(_txRangeSet, true);
- _txRangeSet.clear();
- _txSize = 0;
- }
- sendCommit();
- }
- catch (AMQException e)
- {
- throw new JMSAMQException("Failed to commit: " + e.getMessage(), e);
- }
- catch (FailoverException e)
- {
- throw new JMSAMQException("Fail-over interrupted commit. Status of the commit is uncertain.", e);
- }
- }
-
- protected final boolean tagLE(long tag1, long tag2)
- {
- return Serial.le((int) tag1, (int) tag2);
- }
-
- protected final boolean updateRollbackMark(long currentMark, long deliveryTag)
- {
- return Serial.lt((int) currentMark, (int) deliveryTag);
- }
-
- public void sync() throws AMQException
- {
- try
- {
- getQpidSession().sync();
- }
- catch (SessionException se)
- {
- setCurrentException(se);
- }
-
- AMQException amqe = getCurrentException();
- if (amqe != null)
- {
- throw amqe;
- }
- }
-
- public void setCurrentException(SessionException se)
- {
- synchronized (_currentExceptionLock)
- {
- ExecutionException ee = se.getException();
- int code = AMQConstant.INTERNAL_ERROR.getCode();
- if (ee != null)
- {
- code = ee.getErrorCode().getValue();
- }
- AMQException amqe = new AMQException(AMQConstant.getConstant(code), se.getMessage(), se.getCause());
- _currentException = amqe;
- }
- _connection.exceptionReceived(_currentException);
- }
-
- public AMQMessageDelegateFactory getMessageDelegateFactory()
- {
- return AMQMessageDelegateFactory.FACTORY_0_10;
- }
-
- public boolean isExchangeExist(AMQDestination dest,ExchangeNode node,boolean assertNode)
- {
- boolean match = true;
- ExchangeQueryResult result = getQpidSession().exchangeQuery(dest.getAddressName(), Option.NONE).get();
- match = !result.getNotFound();
-
- if (match)
- {
- if (assertNode)
- {
- match = (result.getDurable() == node.isDurable()) &&
- (node.getExchangeType() != null &&
- node.getExchangeType().equals(result.getType())) &&
- (matchProps(result.getArguments(),node.getDeclareArgs()));
- }
- else if (node.getExchangeType() != null)
- {
- // even if assert is false, better to verify this
- match = node.getExchangeType().equals(result.getType());
- if (!match)
- {
- _logger.debug("Exchange type doesn't match. Expected : " + node.getExchangeType() +
- " actual " + result.getType());
- }
- }
- else
- {
- _logger.debug("Setting Exchange type " + result.getType());
- node.setExchangeType(result.getType());
- dest.setExchangeClass(new AMQShortString(result.getType()));
- }
- }
-
- return match;
- }
-
- public boolean isQueueExist(AMQDestination dest,QueueNode node,boolean assertNode) throws AMQException
- {
- boolean match = true;
- try
- {
- QueueQueryResult result = getQpidSession().queueQuery(dest.getAddressName(), Option.NONE).get();
- match = dest.getAddressName().equals(result.getQueue());
-
- if (match && assertNode)
- {
- match = (result.getDurable() == node.isDurable()) &&
- (result.getAutoDelete() == node.isAutoDelete()) &&
- (result.getExclusive() == node.isExclusive()) &&
- (matchProps(result.getArguments(),node.getDeclareArgs()));
- }
- else if (match)
- {
- // should I use the queried details to update the local data structure.
- }
- }
- catch(SessionException e)
- {
- if (e.getException().getErrorCode() == ExecutionErrorCode.RESOURCE_DELETED)
- {
- match = false;
- }
- else
- {
- throw new AMQException(AMQConstant.getConstant(e.getException().getErrorCode().getValue()),
- "Error querying queue",e);
- }
- }
-
- return match;
- }
-
- private boolean matchProps(Map<String,Object> target,Map<String,Object> source)
- {
- boolean match = true;
- for (String key: source.keySet())
- {
- match = target.containsKey(key) &&
- target.get(key).equals(source.get(key));
-
- if (!match)
- {
- StringBuffer buf = new StringBuffer();
- buf.append("Property given in address did not match with the args sent by the broker.");
- buf.append(" Expected { ").append(key).append(" : ").append(source.get(key)).append(" }, ");
- buf.append(" Actual { ").append(key).append(" : ").append(target.get(key)).append(" }");
- _logger.debug(buf.toString());
- return match;
- }
- }
-
- return match;
- }
-
- /**
- * 1. Try to resolve the address type (queue or exchange)
- * 2. if type == queue,
- * 2.1 verify queue exists or create if create == true
- * 2.2 If not throw exception
- *
- * 3. if type == exchange,
- * 3.1 verify exchange exists or create if create == true
- * 3.2 if not throw exception
- * 3.3 if exchange exists (or created) create subscription queue.
- */
-
- @SuppressWarnings("deprecation")
- public void handleAddressBasedDestination(AMQDestination dest,
- boolean isConsumer,
- boolean noWait) throws AMQException
- {
- if (dest.isAddressResolved())
- {
- if (isConsumer && AMQDestination.TOPIC_TYPE == dest.getAddressType())
- {
- createSubscriptionQueue(dest);
- }
- }
- else
- {
- boolean assertNode = (dest.getAssert() == AddressOption.ALWAYS) ||
- (isConsumer && dest.getAssert() == AddressOption.RECEIVER) ||
- (!isConsumer && dest.getAssert() == AddressOption.SENDER);
-
- boolean createNode = (dest.getCreate() == AddressOption.ALWAYS) ||
- (isConsumer && dest.getCreate() == AddressOption.RECEIVER) ||
- (!isConsumer && dest.getCreate() == AddressOption.SENDER);
-
-
-
- int type = resolveAddressType(dest);
-
- if (type == AMQDestination.QUEUE_TYPE &&
- dest.getLink().getReliability() == Reliability.UNSPECIFIED)
- {
- dest.getLink().setReliability(Reliability.AT_LEAST_ONCE);
- }
- else if (type == AMQDestination.TOPIC_TYPE &&
- dest.getLink().getReliability() == Reliability.UNSPECIFIED)
- {
- dest.getLink().setReliability(Reliability.UNRELIABLE);
- }
- else if (type == AMQDestination.TOPIC_TYPE &&
- dest.getLink().getReliability() == Reliability.AT_LEAST_ONCE)
- {
- throw new AMQException("AT-LEAST-ONCE is not yet supported for Topics");
- }
-
- switch (type)
- {
- case AMQDestination.QUEUE_TYPE:
- {
- if (isQueueExist(dest,(QueueNode)dest.getSourceNode(),assertNode))
- {
- setLegacyFiledsForQueueType(dest);
- break;
- }
- else if(createNode)
- {
- setLegacyFiledsForQueueType(dest);
- send0_10QueueDeclare(dest,null,false,noWait);
- sendQueueBind(dest.getAMQQueueName(), dest.getRoutingKey(),
- null,dest.getExchangeName(),dest, false);
- break;
- }
- }
-
- case AMQDestination.TOPIC_TYPE:
- {
- if (isExchangeExist(dest,(ExchangeNode)dest.getTargetNode(),assertNode))
- {
- setLegacyFiledsForTopicType(dest);
- verifySubject(dest);
- if (isConsumer && !isQueueExist(dest,(QueueNode)dest.getSourceNode(),true))
- {
- createSubscriptionQueue(dest);
- }
- break;
- }
- else if(createNode)
- {
- setLegacyFiledsForTopicType(dest);
- verifySubject(dest);
- sendExchangeDeclare(dest.getAddressName(),
- dest.getExchangeClass().asString(),
- dest.getTargetNode().getAlternateExchange(),
- dest.getTargetNode().getDeclareArgs(),
- false);
- if (isConsumer && !isQueueExist(dest,(QueueNode)dest.getSourceNode(),true))
- {
- createSubscriptionQueue(dest);
- }
- break;
- }
- }
-
- default:
- throw new AMQException(
- "The name '" + dest.getAddressName() +
- "' supplied in the address doesn't resolve to an exchange or a queue");
- }
- dest.setAddressResolved(true);
- }
- }
-
- public int resolveAddressType(AMQDestination dest) throws AMQException
- {
- int type = dest.getAddressType();
- String name = dest.getAddressName();
- if (type != AMQDestination.UNKNOWN_TYPE)
- {
- return type;
- }
- else
- {
- ExchangeBoundResult result = getQpidSession().exchangeBound(name,name,null,null).get();
- if (result.getQueueNotFound() && result.getExchangeNotFound()) {
- //neither a queue nor an exchange exists with that name; treat it as a queue
- type = AMQDestination.QUEUE_TYPE;
- } else if (result.getExchangeNotFound()) {
- //name refers to a queue
- type = AMQDestination.QUEUE_TYPE;
- } else if (result.getQueueNotFound()) {
- //name refers to an exchange
- type = AMQDestination.TOPIC_TYPE;
- } else {
- //both a queue and exchange exist for that name
- throw new AMQException("Ambiguous address, please specify queue or topic as node type");
- }
- dest.setAddressType(type);
- dest.rebuildTargetAndSourceNodes(type);
- return type;
- }
- }
-
- private void verifySubject(AMQDestination dest) throws AMQException
- {
- if (dest.getSubject() == null || dest.getSubject().trim().equals(""))
- {
-
- if ("topic".equals(dest.getExchangeClass().toString()))
- {
- dest.setRoutingKey(new AMQShortString("#"));
- dest.setSubject(dest.getRoutingKey().toString());
- }
- else
- {
- dest.setRoutingKey(new AMQShortString(""));
- dest.setSubject("");
- }
- }
- }
-
- private void createSubscriptionQueue(AMQDestination dest) throws AMQException
- {
- QueueNode node = (QueueNode)dest.getSourceNode(); // source node is never null
-
- if (dest.getQueueName() == null)
- {
- if (dest.getLink() != null && dest.getLink().getName() != null)
- {
- dest.setQueueName(new AMQShortString(dest.getLink().getName()));
- }
- }
- node.setExclusive(true);
- node.setAutoDelete(!node.isDurable());
- send0_10QueueDeclare(dest,null,false,true);
- node.addBinding(new Binding(dest.getAddressName(),
- dest.getQueueName(),// should have one by now
- dest.getSubject(),
- Collections.<String,Object>emptyMap()));
- sendQueueBind(dest.getAMQQueueName(), dest.getRoutingKey(),
- null,dest.getExchangeName(),dest, false);
- }
-
- public void setLegacyFiledsForQueueType(AMQDestination dest)
- {
- // legacy support
- dest.setQueueName(new AMQShortString(dest.getAddressName()));
- dest.setExchangeName(new AMQShortString(""));
- dest.setExchangeClass(new AMQShortString(""));
- dest.setRoutingKey(dest.getAMQQueueName());
- }
-
- public void setLegacyFiledsForTopicType(AMQDestination dest)
- {
- // legacy support
- dest.setExchangeName(new AMQShortString(dest.getAddressName()));
- ExchangeNode node = (ExchangeNode)dest.getTargetNode();
- dest.setExchangeClass(node.getExchangeType() == null?
- ExchangeDefaults.TOPIC_EXCHANGE_CLASS:
- new AMQShortString(node.getExchangeType()));
- dest.setRoutingKey(new AMQShortString(dest.getSubject()));
- }
-
- /** This should be moved to a suitable utility class */
- private String printMap(Map<String,Object> map)
- {
- StringBuilder sb = new StringBuilder();
- sb.append("<");
- if (map != null)
- {
- for(String key : map.keySet())
- {
- sb.append(key).append(" = ").append(map.get(key)).append(" ");
- }
- }
- sb.append(">");
- return sb.toString();
- }
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/AMQSession_0_8.java b/java/client/src/main/java/org/apache/qpid/client/AMQSession_0_8.java
deleted file mode 100644
index c010e4c7ed..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/AMQSession_0_8.java
+++ /dev/null
@@ -1,619 +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.client;
-
-
-import java.util.Map;
-
-import javax.jms.Destination;
-import javax.jms.JMSException;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.AMQUndeliveredException;
-import org.apache.qpid.client.failover.FailoverException;
-import org.apache.qpid.client.failover.FailoverProtectedOperation;
-import org.apache.qpid.client.failover.FailoverRetrySupport;
-import org.apache.qpid.client.message.AMQMessageDelegateFactory;
-import org.apache.qpid.client.message.AbstractJMSMessage;
-import org.apache.qpid.client.message.MessageFactoryRegistry;
-import org.apache.qpid.client.message.ReturnMessage;
-import org.apache.qpid.client.message.UnprocessedMessage;
-import org.apache.qpid.client.protocol.AMQProtocolHandler;
-import org.apache.qpid.client.state.AMQState;
-import org.apache.qpid.client.state.AMQStateManager;
-import org.apache.qpid.client.state.listener.SpecificMethodFrameListener;
-import org.apache.qpid.common.AMQPFilterTypes;
-import org.apache.qpid.framing.AMQFrame;
-import org.apache.qpid.framing.AMQMethodBody;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.BasicAckBody;
-import org.apache.qpid.framing.BasicConsumeBody;
-import org.apache.qpid.framing.BasicConsumeOkBody;
-import org.apache.qpid.framing.BasicQosBody;
-import org.apache.qpid.framing.BasicQosOkBody;
-import org.apache.qpid.framing.BasicRecoverBody;
-import org.apache.qpid.framing.BasicRecoverOkBody;
-import org.apache.qpid.framing.BasicRecoverSyncBody;
-import org.apache.qpid.framing.BasicRecoverSyncOkBody;
-import org.apache.qpid.framing.BasicRejectBody;
-import org.apache.qpid.framing.ChannelCloseOkBody;
-import org.apache.qpid.framing.ChannelFlowBody;
-import org.apache.qpid.framing.ChannelFlowOkBody;
-import org.apache.qpid.framing.ExchangeBoundOkBody;
-import org.apache.qpid.framing.ExchangeDeclareBody;
-import org.apache.qpid.framing.ExchangeDeclareOkBody;
-import org.apache.qpid.framing.FieldTable;
-import org.apache.qpid.framing.FieldTableFactory;
-import org.apache.qpid.framing.ProtocolVersion;
-import org.apache.qpid.framing.QueueBindOkBody;
-import org.apache.qpid.framing.QueueDeclareBody;
-import org.apache.qpid.framing.QueueDeclareOkBody;
-import org.apache.qpid.framing.QueueDeleteBody;
-import org.apache.qpid.framing.QueueDeleteOkBody;
-import org.apache.qpid.framing.TxCommitOkBody;
-import org.apache.qpid.framing.TxRollbackBody;
-import org.apache.qpid.framing.TxRollbackOkBody;
-import org.apache.qpid.framing.amqp_0_9.MethodRegistry_0_9;
-import org.apache.qpid.framing.amqp_0_91.MethodRegistry_0_91;
-import org.apache.qpid.jms.Session;
-import org.apache.qpid.protocol.AMQConstant;
-import org.apache.qpid.protocol.AMQMethodEvent;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public final class AMQSession_0_8 extends AMQSession<BasicMessageConsumer_0_8, BasicMessageProducer_0_8>
-{
-
- /** Used for debugging. */
- private static final Logger _logger = LoggerFactory.getLogger(AMQSession.class);
-
- /**
- * Creates a new session on a connection.
- *
- * @param con The connection on which to create the session.
- * @param channelId The unique identifier for the session.
- * @param transacted Indicates whether or not the session is transactional.
- * @param acknowledgeMode The acknoledgement mode for the session.
- * @param messageFactoryRegistry The message factory factory for the session.
- * @param defaultPrefetchHighMark The maximum number of messages to prefetched before suspending the session.
- * @param defaultPrefetchLowMark The number of prefetched messages at which to resume the session.
- */
- AMQSession_0_8(AMQConnection con, int channelId, boolean transacted, int acknowledgeMode,
- MessageFactoryRegistry messageFactoryRegistry, int defaultPrefetchHighMark, int defaultPrefetchLowMark)
- {
-
- super(con,channelId,transacted,acknowledgeMode,messageFactoryRegistry,defaultPrefetchHighMark,defaultPrefetchLowMark);
- }
-
- /**
- * Creates a new session on a connection with the default message factory factory.
- *
- * @param con The connection on which to create the session.
- * @param channelId The unique identifier for the session.
- * @param transacted Indicates whether or not the session is transactional.
- * @param acknowledgeMode The acknoledgement mode for the session.
- * @param defaultPrefetchHigh The maximum number of messages to prefetched before suspending the session.
- * @param defaultPrefetchLow The number of prefetched messages at which to resume the session.
- */
- AMQSession_0_8(AMQConnection con, int channelId, boolean transacted, int acknowledgeMode, int defaultPrefetchHigh,
- int defaultPrefetchLow)
- {
- this(con, channelId, transacted, acknowledgeMode, MessageFactoryRegistry.newDefaultRegistry(), defaultPrefetchHigh,
- defaultPrefetchLow);
- }
-
- private ProtocolVersion getProtocolVersion()
- {
- return getProtocolHandler().getProtocolVersion();
- }
-
- public void acknowledgeMessage(long deliveryTag, boolean multiple)
- {
- BasicAckBody body = getMethodRegistry().createBasicAckBody(deliveryTag, multiple);
-
- final AMQFrame ackFrame = body.generateFrame(_channelId);
-
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Sending ack for delivery tag " + deliveryTag + " on channel " + _channelId);
- }
-
- getProtocolHandler().writeFrame(ackFrame);
- _unacknowledgedMessageTags.remove(deliveryTag);
- }
-
- public void sendQueueBind(final AMQShortString queueName, final AMQShortString routingKey, final FieldTable arguments,
- final AMQShortString exchangeName, final AMQDestination dest,
- final boolean nowait) throws AMQException, FailoverException
- {
- getProtocolHandler().syncWrite(getProtocolHandler().getMethodRegistry().createQueueBindBody
- (getTicket(),queueName,exchangeName,routingKey,false,arguments).
- generateFrame(_channelId), QueueBindOkBody.class);
- }
-
- public void sendClose(long timeout) throws AMQException, FailoverException
- {
- // we also need to check the state manager for 08/09 as the
- // _connection variable may not be updated in time by the error receiving
- // thread.
- // We can't close the session if we are alreadying in the process of
- // closing/closed the connection.
-
- if (!(getProtocolHandler().getStateManager().getCurrentState().equals(AMQState.CONNECTION_CLOSED)
- || getProtocolHandler().getStateManager().getCurrentState().equals(AMQState.CONNECTION_CLOSING)))
- {
-
- getProtocolHandler().closeSession(this);
- getProtocolHandler().syncWrite(getProtocolHandler().getMethodRegistry().createChannelCloseBody(AMQConstant.REPLY_SUCCESS.getCode(),
- new AMQShortString("JMS client closing channel"), 0, 0).generateFrame(_channelId),
- ChannelCloseOkBody.class, timeout);
- // When control resumes at this point, a reply will have been received that
- // indicates the broker has closed the channel successfully.
- }
- }
-
- public void sendCommit() throws AMQException, FailoverException
- {
- final AMQProtocolHandler handler = getProtocolHandler();
-
- handler.syncWrite(getProtocolHandler().getMethodRegistry().createTxCommitBody().generateFrame(_channelId), TxCommitOkBody.class);
- }
-
- public void sendCreateQueue(AMQShortString name, final boolean autoDelete, final boolean durable, final boolean exclusive, final Map<String, Object> arguments) throws AMQException,
- FailoverException
- {
- FieldTable table = null;
- if(arguments != null && !arguments.isEmpty())
- {
- table = new FieldTable();
- for(Map.Entry<String, Object> entry : arguments.entrySet())
- {
- table.setObject(entry.getKey(), entry.getValue());
- }
- }
- QueueDeclareBody body = getMethodRegistry().createQueueDeclareBody(getTicket(),name,false,durable,exclusive,autoDelete,false,table);
- AMQFrame queueDeclare = body.generateFrame(_channelId);
- getProtocolHandler().syncWrite(queueDeclare, QueueDeclareOkBody.class);
- }
-
- public void sendRecover() throws AMQException, FailoverException
- {
- _unacknowledgedMessageTags.clear();
-
- if (isStrictAMQP())
- {
- // We can't use the BasicRecoverBody-OK method as it isn't part of the spec.
-
- BasicRecoverBody body = getMethodRegistry().createBasicRecoverBody(false);
- _connection.getProtocolHandler().writeFrame(body.generateFrame(_channelId));
- _logger.warn("Session Recover cannot be guaranteed with STRICT_AMQP. Messages may arrive out of order.");
- }
- else
- {
- // in Qpid the 0-8 spec was hacked to have a recover-ok method... this is bad
- // in 0-9 we used the cleaner addition of a new sync recover method with its own ok
- if(getProtocolHandler().getProtocolVersion().equals(ProtocolVersion.v8_0))
- {
- BasicRecoverBody body = getMethodRegistry().createBasicRecoverBody(false);
- _connection.getProtocolHandler().syncWrite(body.generateFrame(_channelId), BasicRecoverOkBody.class);
- }
- else if(getProtocolVersion().equals(ProtocolVersion.v0_9))
- {
- BasicRecoverSyncBody body = ((MethodRegistry_0_9)getMethodRegistry()).createBasicRecoverSyncBody(false);
- _connection.getProtocolHandler().syncWrite(body.generateFrame(_channelId), BasicRecoverSyncOkBody.class);
- }
- else if(getProtocolVersion().equals(ProtocolVersion.v0_91))
- {
- BasicRecoverSyncBody body = ((MethodRegistry_0_91)getMethodRegistry()).createBasicRecoverSyncBody(false);
- _connection.getProtocolHandler().syncWrite(body.generateFrame(_channelId), BasicRecoverSyncOkBody.class);
- }
- else
- {
- throw new RuntimeException("Unsupported version of the AMQP Protocol: " + getProtocolVersion());
- }
- }
- }
-
- public void releaseForRollback()
- {
- // Reject all the messages that have been received in this session and
- // have not yet been acknowledged. Should look to remove
- // _deliveredMessageTags and use _txRangeSet as used by 0-10.
- // Otherwise messages will be able to arrive out of order to a second
- // consumer on the queue. Whilst this is within the JMS spec it is not
- // user friendly and avoidable.
- while (true)
- {
- Long tag = _deliveredMessageTags.poll();
- if (tag == null)
- {
- break;
- }
-
- rejectMessage(tag, true);
- }
- }
-
- public void rejectMessage(long deliveryTag, boolean requeue)
- {
- if ((_acknowledgeMode == CLIENT_ACKNOWLEDGE) || (_acknowledgeMode == SESSION_TRANSACTED))
- {
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Rejecting delivery tag:" + deliveryTag + ":SessionHC:" + this.hashCode());
- }
-
- BasicRejectBody body = getMethodRegistry().createBasicRejectBody(deliveryTag, requeue);
- AMQFrame frame = body.generateFrame(_channelId);
-
- _connection.getProtocolHandler().writeFrame(frame);
- }
- }
-
- public boolean isQueueBound(final AMQDestination destination) throws JMSException
- {
- return isQueueBound(destination.getExchangeName(),destination.getAMQQueueName(),destination.getAMQQueueName());
- }
-
-
- public boolean isQueueBound(final AMQShortString exchangeName, final AMQShortString queueName, final AMQShortString routingKey)
- throws JMSException
- {
- try
- {
- AMQMethodEvent response = new FailoverRetrySupport<AMQMethodEvent, AMQException>(
- new FailoverProtectedOperation<AMQMethodEvent, AMQException>()
- {
- public AMQMethodEvent execute() throws AMQException, FailoverException
- {
- AMQFrame boundFrame = getProtocolHandler().getMethodRegistry().createExchangeBoundBody
- (exchangeName, routingKey, queueName).generateFrame(_channelId);
-
- return getProtocolHandler().syncWrite(boundFrame, ExchangeBoundOkBody.class);
-
- }
- }, _connection).execute();
-
- // Extract and return the response code from the query.
- ExchangeBoundOkBody responseBody = (ExchangeBoundOkBody) response.getMethod();
-
- return (responseBody.getReplyCode() == 0);
- }
- catch (AMQException e)
- {
- throw new JMSAMQException("Queue bound query failed: " + e.getMessage(), e);
- }
- }
-
- @Override public void sendConsume(BasicMessageConsumer_0_8 consumer,
- AMQShortString queueName,
- AMQProtocolHandler protocolHandler,
- boolean nowait,
- String messageSelector,
- int tag) throws AMQException, FailoverException
- {
- FieldTable arguments = FieldTableFactory.newFieldTable();
- if ((messageSelector != null) && !messageSelector.equals(""))
- {
- arguments.put(AMQPFilterTypes.JMS_SELECTOR.getValue(), messageSelector);
- }
-
- if (consumer.isAutoClose())
- {
- arguments.put(AMQPFilterTypes.AUTO_CLOSE.getValue(), Boolean.TRUE);
- }
-
- if (consumer.isNoConsume())
- {
- arguments.put(AMQPFilterTypes.NO_CONSUME.getValue(), Boolean.TRUE);
- }
-
- BasicConsumeBody body = getMethodRegistry().createBasicConsumeBody(getTicket(),
- queueName,
- new AMQShortString(String.valueOf(tag)),
- consumer.isNoLocal(),
- consumer.getAcknowledgeMode() == Session.NO_ACKNOWLEDGE,
- consumer.isExclusive(),
- nowait,
- arguments);
-
-
- AMQFrame jmsConsume = body.generateFrame(_channelId);
-
- if (nowait)
- {
- protocolHandler.writeFrame(jmsConsume);
- }
- else
- {
- protocolHandler.syncWrite(jmsConsume, BasicConsumeOkBody.class);
- }
- }
-
- public void sendExchangeDeclare(final AMQShortString name, final AMQShortString type, final AMQProtocolHandler protocolHandler,
- final boolean nowait) throws AMQException, FailoverException
- {
- ExchangeDeclareBody body = getMethodRegistry().createExchangeDeclareBody(getTicket(),name,type,
- name.toString().startsWith("amq."),
- false,false,false,false,null);
- AMQFrame exchangeDeclare = body.generateFrame(_channelId);
-
- protocolHandler.syncWrite(exchangeDeclare, ExchangeDeclareOkBody.class);
- }
-
- public void sendQueueDeclare(final AMQDestination amqd, final AMQProtocolHandler protocolHandler,
- final boolean nowait) throws AMQException, FailoverException
- {
- QueueDeclareBody body = getMethodRegistry().createQueueDeclareBody(getTicket(),amqd.getAMQQueueName(),false,amqd.isDurable(),amqd.isExclusive(),amqd.isAutoDelete(),false,null);
-
- AMQFrame queueDeclare = body.generateFrame(_channelId);
-
- protocolHandler.syncWrite(queueDeclare, QueueDeclareOkBody.class);
- }
-
- public void sendQueueDelete(final AMQShortString queueName) throws AMQException, FailoverException
- {
- QueueDeleteBody body = getMethodRegistry().createQueueDeleteBody(getTicket(),
- queueName,
- false,
- false,
- true);
- AMQFrame queueDeleteFrame = body.generateFrame(_channelId);
-
- getProtocolHandler().syncWrite(queueDeleteFrame, QueueDeleteOkBody.class);
- }
-
- public void sendSuspendChannel(boolean suspend) throws AMQException, FailoverException
- {
- ChannelFlowBody body = getMethodRegistry().createChannelFlowBody(!suspend);
- AMQFrame channelFlowFrame = body.generateFrame(_channelId);
- _connection.getProtocolHandler().syncWrite(channelFlowFrame, ChannelFlowOkBody.class);
- }
-
- public BasicMessageConsumer_0_8 createMessageConsumer(final AMQDestination destination, final int prefetchHigh,
- final int prefetchLow, final boolean noLocal, final boolean exclusive, String messageSelector, final FieldTable arguments,
- final boolean noConsume, final boolean autoClose) throws JMSException
- {
-
- final AMQProtocolHandler protocolHandler = getProtocolHandler();
- return new BasicMessageConsumer_0_8(_channelId, _connection, destination, messageSelector, noLocal,
- _messageFactoryRegistry,this, protocolHandler, arguments, prefetchHigh, prefetchLow,
- exclusive, _acknowledgeMode, noConsume, autoClose);
- }
-
-
- public BasicMessageProducer_0_8 createMessageProducer(final Destination destination, final boolean mandatory,
- final boolean immediate, final boolean waitUntilSent, long producerId) throws JMSException
- {
- try
- {
- return new BasicMessageProducer_0_8(_connection, (AMQDestination) destination, _transacted, _channelId,
- this, getProtocolHandler(), producerId, immediate, mandatory, waitUntilSent);
- }
- catch (AMQException e)
- {
- JMSException ex = new JMSException("Error creating producer");
- ex.initCause(e);
- ex.setLinkedException(e);
-
- throw ex;
- }
- }
-
-
- @Override public void messageReceived(UnprocessedMessage message)
- {
-
- if (message instanceof ReturnMessage)
- {
- // Return of the bounced message.
- returnBouncedMessage((ReturnMessage) message);
- }
- else
- {
- super.messageReceived(message);
- }
- }
-
- private void returnBouncedMessage(final ReturnMessage msg)
- {
- _connection.performConnectionTask(new Runnable()
- {
- public void run()
- {
- try
- {
- // Bounced message is processed here, away from the mina thread
- AbstractJMSMessage bouncedMessage =
- _messageFactoryRegistry.createMessage(0, false, msg.getExchange(),
- msg.getRoutingKey(), msg.getContentHeader(), msg.getBodies());
- AMQConstant errorCode = AMQConstant.getConstant(msg.getReplyCode());
- AMQShortString reason = msg.getReplyText();
- _logger.debug("Message returned with error code " + errorCode + " (" + reason + ")");
-
- // @TODO should this be moved to an exception handler of sorts. Somewhere errors are converted to correct execeptions.
- if (errorCode == AMQConstant.NO_CONSUMERS)
- {
- _connection.exceptionReceived(new AMQNoConsumersException("Error: " + reason, bouncedMessage, null));
- }
- else if (errorCode == AMQConstant.NO_ROUTE)
- {
- _connection.exceptionReceived(new AMQNoRouteException("Error: " + reason, bouncedMessage, null));
- }
- else
- {
- _connection.exceptionReceived(
- new AMQUndeliveredException(errorCode, "Error: " + reason, bouncedMessage, null));
- }
-
- }
- catch (Exception e)
- {
- _logger.error(
- "Caught exception trying to raise undelivered message exception (dump follows) - ignoring...",
- e);
- }
- }
- });
- }
-
-
-
-
- public void sendRollback() throws AMQException, FailoverException
- {
- TxRollbackBody body = getMethodRegistry().createTxRollbackBody();
- AMQFrame frame = body.generateFrame(getChannelId());
- getProtocolHandler().syncWrite(frame, TxRollbackOkBody.class);
- }
-
- public void setPrefetchLimits(final int messagePrefetch, final long sizePrefetch) throws AMQException
- {
- new FailoverRetrySupport<Object, AMQException>(
- new FailoverProtectedOperation<Object, AMQException>()
- {
- public Object execute() throws AMQException, FailoverException
- {
-
- BasicQosBody basicQosBody = getProtocolHandler().getMethodRegistry().createBasicQosBody(sizePrefetch, messagePrefetch, false);
-
- // todo send low water mark when protocol allows.
- // todo Be aware of possible changes to parameter order as versions change.
- getProtocolHandler().syncWrite(basicQosBody.generateFrame(getChannelId()), BasicQosOkBody.class);
-
- return null;
- }
- }, _connection).execute();
- }
-
- class QueueDeclareOkHandler extends SpecificMethodFrameListener
- {
-
- private long _messageCount;
- private long _consumerCount;
-
- public QueueDeclareOkHandler()
- {
- super(getChannelId(), QueueDeclareOkBody.class);
- }
-
- public boolean processMethod(int channelId, AMQMethodBody frame) //throws AMQException
- {
- boolean matches = super.processMethod(channelId, frame);
- if (matches)
- {
- QueueDeclareOkBody declareOk = (QueueDeclareOkBody) frame;
- _messageCount = declareOk.getMessageCount();
- _consumerCount = declareOk.getConsumerCount();
- }
- return matches;
- }
-
- }
-
- protected Long requestQueueDepth(AMQDestination amqd) throws AMQException, FailoverException
- {
- AMQFrame queueDeclare =
- getMethodRegistry().createQueueDeclareBody(getTicket(),
- amqd.getAMQQueueName(),
- true,
- amqd.isDurable(),
- amqd.isExclusive(),
- amqd.isAutoDelete(),
- false,
- null).generateFrame(_channelId);
- QueueDeclareOkHandler okHandler = new QueueDeclareOkHandler();
- getProtocolHandler().writeCommandFrameAndWaitForReply(queueDeclare, okHandler);
- return okHandler._messageCount;
- }
-
- protected final boolean tagLE(long tag1, long tag2)
- {
- return tag1 <= tag2;
- }
-
- protected final boolean updateRollbackMark(long currentMark, long deliveryTag)
- {
- return false;
- }
-
- public AMQMessageDelegateFactory getMessageDelegateFactory()
- {
- return AMQMessageDelegateFactory.FACTORY_0_8;
- }
-
- public void sync() throws AMQException
- {
- declareExchange(new AMQShortString("amq.direct"), new AMQShortString("direct"), false);
- }
-
- public void handleAddressBasedDestination(AMQDestination dest,
- boolean isConsumer,
- boolean noWait) throws AMQException
- {
- throw new UnsupportedOperationException("The new addressing based sytanx is "
- + "not supported for AMQP 0-8/0-9 versions");
- }
-
- protected void flushAcknowledgments()
- {
-
- }
-
- public boolean isQueueBound(String exchangeName, String queueName,
- String bindingKey, Map<String, Object> args) throws JMSException
- {
- return isQueueBound(exchangeName == null ? null : new AMQShortString(exchangeName),
- queueName == null ? null : new AMQShortString(queueName),
- bindingKey == null ? null : new AMQShortString(bindingKey));
- }
-
-
- public AMQException getLastException()
- {
- // if the Connection has closed then we should throw any exception that
- // has occurred that we were not waiting for
- AMQStateManager manager = _connection.getProtocolHandler()
- .getStateManager();
-
- Exception e = manager.getLastException();
- if (manager.getCurrentState().equals(AMQState.CONNECTION_CLOSED)
- && e != null)
- {
- if (e instanceof AMQException)
- {
- return (AMQException) e;
- }
- else
- {
- AMQException amqe = new AMQException(AMQConstant
- .getConstant(AMQConstant.INTERNAL_ERROR.getCode()),
- e.getMessage(), e.getCause());
- return amqe;
- }
- }
- else
- {
- return null;
- }
- }
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/AMQTemporaryQueue.java b/java/client/src/main/java/org/apache/qpid/client/AMQTemporaryQueue.java
deleted file mode 100644
index f54cb782c8..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/AMQTemporaryQueue.java
+++ /dev/null
@@ -1,69 +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.client;
-
-import javax.jms.JMSException;
-import javax.jms.TemporaryQueue;
-
-import org.apache.qpid.framing.AMQShortString;
-
-import java.util.Random;
-import java.util.UUID;
-
-/** AMQ implementation of a TemporaryQueue. */
-final class AMQTemporaryQueue extends AMQQueue implements TemporaryQueue, TemporaryDestination
-{
-
-
- private final AMQSession _session;
- private boolean _deleted;
-
- /** Create a new instance of an AMQTemporaryQueue */
- public AMQTemporaryQueue(AMQSession session)
- {
- super(session.getTemporaryQueueExchangeName(), new AMQShortString("TempQueue" + UUID.randomUUID()), true);
- _session = session;
- }
-
- /** @see javax.jms.TemporaryQueue#delete() */
- public synchronized void delete() throws JMSException
- {
- if (_session.hasConsumer(this))
- {
- throw new JMSException("Temporary Queue has consumers so cannot be deleted");
- }
- _deleted = true;
-
- // Currently TemporaryQueue is set to be auto-delete which means that the queue will be deleted
- // by the server when there are no more subscriptions to that queue. This is probably not
- // quite right for JMSCompliance.
- }
-
- public AMQSession getSession()
- {
- return _session;
- }
-
- public boolean isDeleted()
- {
- return _deleted;
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/AMQTemporaryTopic.java b/java/client/src/main/java/org/apache/qpid/client/AMQTemporaryTopic.java
deleted file mode 100644
index 7b5781530b..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/AMQTemporaryTopic.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.client;
-
-import org.apache.qpid.framing.AMQShortString;
-
-import javax.jms.JMSException;
-import javax.jms.TemporaryTopic;
-import java.util.UUID;
-
-/**
- * AMQ implementation of TemporaryTopic.
- */
-class AMQTemporaryTopic extends AMQTopic implements TemporaryTopic, TemporaryDestination
-{
-
- private final AMQSession _session;
- private boolean _deleted;
- /**
- * Create new temporary topic.
- */
- public AMQTemporaryTopic(AMQSession session)
- {
- super(session.getTemporaryTopicExchangeName(),new AMQShortString("tmp_" + UUID.randomUUID()));
- _session = session;
- }
-
- /**
- * @see javax.jms.TemporaryTopic#delete()
- */
- public void delete() throws JMSException
- {
- if(_session.hasConsumer(this))
- {
- throw new JMSException("Temporary Topic has consumers so cannot be deleted");
- }
-
- _deleted = true;
- // Currently TemporaryQueue is set to be auto-delete which means that the queue will be deleted
- // by the server when there are no more subscriptions to that queue. This is probably not
- // quite right for JMSCompliance.
- }
-
- public AMQSession getSession()
- {
- return _session;
- }
-
- public boolean isDeleted()
- {
- return _deleted;
- }
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/AMQTopic.java b/java/client/src/main/java/org/apache/qpid/client/AMQTopic.java
deleted file mode 100644
index 780dbcafc2..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/AMQTopic.java
+++ /dev/null
@@ -1,224 +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.client;
-
-import java.net.URISyntaxException;
-
-import javax.jms.InvalidDestinationException;
-import javax.jms.JMSException;
-import javax.jms.Topic;
-
-import org.apache.qpid.exchange.ExchangeDefaults;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.messaging.Address;
-import org.apache.qpid.url.BindingURL;
-
-public class AMQTopic extends AMQDestination implements Topic
-{
- public AMQTopic(String address) throws URISyntaxException
- {
- super(address);
- }
-
- public AMQTopic(Address address) throws Exception
- {
- super(address);
- }
-
- /**
- * Constructor for use in creating a topic using a BindingURL.
- *
- * @param binding The binding url object.
- */
- public AMQTopic(BindingURL binding)
- {
- super(binding);
- }
-
- public AMQTopic(AMQShortString exchange, AMQShortString routingKey, AMQShortString queueName)
- {
- super(exchange, ExchangeDefaults.TOPIC_EXCHANGE_CLASS, routingKey, true, true, queueName, false);
- }
-
- public AMQTopic(AMQShortString exchange, AMQShortString routingKey, AMQShortString queueName,AMQShortString[] bindingKeys)
- {
- super(exchange, ExchangeDefaults.TOPIC_EXCHANGE_CLASS, routingKey, true, true, queueName, false,bindingKeys);
- }
-
- public AMQTopic(AMQConnection conn, String routingKey)
- {
- this(conn.getDefaultTopicExchangeName(), new AMQShortString(routingKey));
- }
-
-
- public AMQTopic(AMQShortString exchangeName, String routingKey)
- {
- this(exchangeName, new AMQShortString(routingKey));
- }
-
- public AMQTopic(AMQShortString exchangeName, AMQShortString routingKey)
- {
- this(exchangeName, routingKey, null);
- }
-
- public AMQTopic(AMQShortString exchangeName, AMQShortString name, boolean isAutoDelete, AMQShortString queueName, boolean isDurable)
- {
- super(exchangeName, ExchangeDefaults.TOPIC_EXCHANGE_CLASS, name, true, isAutoDelete, queueName, isDurable);
- }
-
- protected AMQTopic(AMQShortString exchangeName, AMQShortString exchangeClass, AMQShortString routingKey, boolean isExclusive,
- boolean isAutoDelete, AMQShortString queueName, boolean isDurable)
- {
- super(exchangeName, exchangeClass, routingKey, isExclusive, isAutoDelete, queueName, isDurable );
- }
-
- protected AMQTopic(AMQShortString exchangeName, AMQShortString exchangeClass, AMQShortString routingKey, boolean isExclusive,
- boolean isAutoDelete, AMQShortString queueName, boolean isDurable,AMQShortString[] bindingKeys)
- {
- super(exchangeName, exchangeClass, routingKey, isExclusive, isAutoDelete, queueName, isDurable,bindingKeys);
- }
-
- public static AMQTopic createDurableTopic(Topic topic, String subscriptionName, AMQConnection connection)
- throws JMSException
- {
- if (topic instanceof AMQDestination && topic instanceof javax.jms.Topic)
- {
- AMQDestination qpidTopic = (AMQDestination)topic;
- if (qpidTopic.getDestSyntax() == DestSyntax.ADDR)
- {
- try
- {
- AMQTopic t = new AMQTopic(qpidTopic.getAddress());
- AMQShortString queueName = getDurableTopicQueueName(subscriptionName, connection);
- // link is never null if dest was created using an address string.
- t.getLink().setName(queueName.asString());
- t.getSourceNode().setAutoDelete(false);
- t.getSourceNode().setDurable(true);
-
- // The legacy fields are also populated just in case.
- t.setQueueName(queueName);
- t.setAutoDelete(false);
- t.setDurable(true);
- return t;
- }
- catch(Exception e)
- {
- JMSException ex = new JMSException("Error creating durable topic");
- ex.initCause(e);
- ex.setLinkedException(e);
- throw ex;
- }
- }
- else
- {
- return new AMQTopic(qpidTopic.getExchangeName(), qpidTopic.getRoutingKey(), false,
- getDurableTopicQueueName(subscriptionName, connection),
- true);
- }
- }
- else
- {
- throw new InvalidDestinationException("The destination object used is not from this provider or of type javax.jms.Topic");
- }
- }
-
- public static AMQShortString getDurableTopicQueueName(String subscriptionName, AMQConnection connection) throws JMSException
- {
- return new AMQShortString(connection.getClientID() + ":" + subscriptionName);
- }
-
- public String getTopicName() throws JMSException
- {
- if (getRoutingKey() != null)
- {
- return getRoutingKey().asString();
- }
- else if (getSubject() != null)
- {
- return getSubject();
- }
- else
- {
- return null;
- }
- }
-
- @Override
- public AMQShortString getExchangeName()
- {
- if (super.getExchangeName() == null && super.getAddressName() != null)
- {
- return new AMQShortString(super.getAddressName());
- }
- else
- {
- return _exchangeName;
- }
- }
-
- public AMQShortString getRoutingKey()
- {
- if (super.getRoutingKey() != null)
- {
- return super.getRoutingKey();
- }
- else if (getSubject() != null)
- {
- return new AMQShortString(getSubject());
- }
- else
- {
- setRoutingKey(new AMQShortString(""));
- setSubject("");
- return super.getRoutingKey();
- }
- }
-
- public boolean isNameRequired()
- {
- return !isDurable();
- }
-
- /**
- * Override since the queue is always private and we must ensure it remains null. If not,
- * reuse of the topic when registering consumers will make all consumers listen on the same (private) queue rather
- * than getting their own (private) queue.
- * <p/>
- * This is relatively nasty but it is difficult to come up with a more elegant solution, given
- * the requirement in the case on AMQQueue and possibly other AMQDestination subclasses to
- * use the underlying queue name even where it is server generated.
- */
- public void setQueueName(String queueName)
- {
- }
-
- public boolean equals(Object o)
- {
- return (o instanceof AMQTopic)
- && ((AMQTopic)o).getExchangeName().equals(getExchangeName())
- && ((AMQTopic)o).getRoutingKey().equals(getRoutingKey());
- }
-
- public int hashCode()
- {
- return getExchangeName().hashCode() + getRoutingKey().hashCode();
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/AMQTopicSessionAdaptor.java b/java/client/src/main/java/org/apache/qpid/client/AMQTopicSessionAdaptor.java
deleted file mode 100644
index ec482a8f79..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/AMQTopicSessionAdaptor.java
+++ /dev/null
@@ -1,226 +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.client;
-
-import java.io.Serializable;
-
-import javax.jms.BytesMessage;
-import javax.jms.Destination;
-import javax.jms.IllegalStateException;
-import javax.jms.JMSException;
-import javax.jms.MapMessage;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageListener;
-import javax.jms.MessageProducer;
-import javax.jms.ObjectMessage;
-import javax.jms.Queue;
-import javax.jms.QueueBrowser;
-import javax.jms.Session;
-import javax.jms.StreamMessage;
-import javax.jms.TemporaryQueue;
-import javax.jms.TemporaryTopic;
-import javax.jms.TextMessage;
-import javax.jms.Topic;
-import javax.jms.TopicPublisher;
-import javax.jms.TopicSession;
-import javax.jms.TopicSubscriber;
-
-public class AMQTopicSessionAdaptor implements TopicSession, AMQSessionAdapter
-{
- protected final AMQSession _session;
-
- public AMQTopicSessionAdaptor(Session session)
- {
- _session = (AMQSession) session;
- }
-
- public Topic createTopic(String string) throws JMSException
- {
- return _session.createTopic(string);
- }
-
- public TopicSubscriber createSubscriber(Topic topic) throws JMSException
- {
- return _session.createSubscriber(topic);
- }
-
- public TopicSubscriber createSubscriber(Topic topic, String string, boolean b) throws JMSException
- {
- return _session.createSubscriber(topic, string, b);
- }
-
- public TopicSubscriber createDurableSubscriber(Topic topic, String string) throws JMSException
- {
- return _session.createDurableSubscriber(topic, string);
- }
-
- public TopicSubscriber createDurableSubscriber(Topic topic, String string, String string1, boolean b) throws JMSException
- {
- return _session.createDurableSubscriber(topic, string, string1, b);
- }
-
- public TopicPublisher createPublisher(Topic topic) throws JMSException
- {
- return _session.createPublisher(topic);
- }
-
- public TemporaryTopic createTemporaryTopic() throws JMSException
- {
- return _session.createTemporaryTopic();
- }
-
- public void unsubscribe(String string) throws JMSException
- {
- _session.unsubscribe(string);
- }
-
- public BytesMessage createBytesMessage() throws JMSException
- {
- return _session.createBytesMessage();
- }
-
- public MapMessage createMapMessage() throws JMSException
- {
- return _session.createMapMessage();
- }
-
- public Message createMessage() throws JMSException
- {
- return _session.createMessage();
- }
-
- public ObjectMessage createObjectMessage() throws JMSException
- {
- return _session.createObjectMessage();
- }
-
- public ObjectMessage createObjectMessage(Serializable serializable) throws JMSException
- {
- return _session.createObjectMessage(serializable);
- }
-
- public StreamMessage createStreamMessage() throws JMSException
- {
- return _session.createStreamMessage();
- }
-
- public TextMessage createTextMessage() throws JMSException
- {
- return _session.createTextMessage();
- }
-
- public TextMessage createTextMessage(String string) throws JMSException
- {
- return _session.createTextMessage(string);
- }
-
- public boolean getTransacted() throws JMSException
- {
- return _session.getTransacted();
- }
-
- public int getAcknowledgeMode() throws JMSException
- {
- return _session.getAcknowledgeMode();
- }
-
- public void commit() throws JMSException
- {
- _session.commit();
- }
-
- public void rollback() throws JMSException
- {
- _session.rollback();
- }
-
- public void close() throws JMSException
- {
- _session.close();
- }
-
- public void recover() throws JMSException
- {
- _session.recover();
- }
-
- public MessageListener getMessageListener() throws JMSException
- {
- return _session.getMessageListener();
- }
-
- public void setMessageListener(MessageListener messageListener) throws JMSException
- {
- _session.setMessageListener(messageListener);
- }
-
- public void run()
- {
- _session.run();
- }
-
- public MessageProducer createProducer(Destination destination) throws JMSException
- {
- return _session.createProducer(destination);
- }
-
- public MessageConsumer createConsumer(Destination destination) throws JMSException
- {
- return _session.createConsumer(destination);
- }
-
- public MessageConsumer createConsumer(Destination destination, String string) throws JMSException
- {
- return _session.createConsumer(destination, string);
- }
-
- public MessageConsumer createConsumer(Destination destination, String string, boolean b) throws JMSException
- {
- return _session.createConsumer(destination, string, b);
- }
-
- //The following methods cannot be called from a TopicSession as per JMS spec
- public Queue createQueue(String string) throws JMSException
- {
- throw new IllegalStateException("Cannot call createQueue from TopicSession");
- }
-
- public QueueBrowser createBrowser(Queue queue) throws JMSException
- {
- throw new IllegalStateException("Cannot call createBrowser from TopicSession");
- }
-
- public QueueBrowser createBrowser(Queue queue, String string) throws JMSException
- {
- throw new IllegalStateException("Cannot call createBrowser from TopicSession");
- }
-
- public TemporaryQueue createTemporaryQueue() throws JMSException
- {
- throw new IllegalStateException("Cannot call createTemporaryQueue from TopicSession");
- }
-
- public AMQSession getSession()
- {
- return _session;
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/AMQUndefinedDestination.java b/java/client/src/main/java/org/apache/qpid/client/AMQUndefinedDestination.java
deleted file mode 100644
index fa2afb3ee4..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/AMQUndefinedDestination.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.client;
-
-import org.apache.qpid.framing.AMQShortString;
-
-public class AMQUndefinedDestination extends AMQDestination
-{
-
- private static final AMQShortString UNKNOWN_EXCHANGE_CLASS = new AMQShortString("unknown");
-
-
- public AMQUndefinedDestination(AMQShortString exchange, AMQShortString routingKey, AMQShortString queueName)
- {
- super(exchange, UNKNOWN_EXCHANGE_CLASS, routingKey, queueName);
- }
-
- public boolean isNameRequired()
- {
- return getAMQQueueName() == null;
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/BasicMessageConsumer.java b/java/client/src/main/java/org/apache/qpid/client/BasicMessageConsumer.java
deleted file mode 100644
index 5d32863f2f..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/BasicMessageConsumer.java
+++ /dev/null
@@ -1,1079 +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.client;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.failover.FailoverException;
-import org.apache.qpid.client.message.*;
-import org.apache.qpid.client.protocol.AMQProtocolHandler;
-import org.apache.qpid.framing.*;
-import org.apache.qpid.jms.MessageConsumer;
-import org.apache.qpid.jms.Session;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageListener;
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.List;
-import java.util.SortedSet;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.TreeSet;
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.ConcurrentLinkedQueue;
-import java.util.concurrent.LinkedBlockingQueue;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicReference;
-
-public abstract class BasicMessageConsumer<U> extends Closeable implements MessageConsumer
-{
- private static final Logger _logger = LoggerFactory.getLogger(BasicMessageConsumer.class);
-
- /** The connection being used by this consumer */
- protected final AMQConnection _connection;
-
- protected final String _messageSelector;
-
- private final boolean _noLocal;
-
- protected AMQDestination _destination;
-
- /**
- * When true indicates that a blocking receive call is in progress
- */
- private final AtomicBoolean _receiving = new AtomicBoolean(false);
- /**
- * Holds an atomic reference to the listener installed.
- */
- private final AtomicReference<MessageListener> _messageListener = new AtomicReference<MessageListener>();
-
- /** The consumer tag allows us to close the consumer by sending a jmsCancel method to the broker */
- protected int _consumerTag;
-
- /** We need to know the channel id when constructing frames */
- protected final int _channelId;
-
- /**
- * Used in the blocking receive methods to receive a message from the Session thread. <p/> Or to notify of errors
- * <p/> Argument true indicates we want strict FIFO semantics
- */
- protected final BlockingQueue _synchronousQueue;
-
- protected final MessageFactoryRegistry _messageFactory;
-
- protected final AMQSession _session;
-
- protected final AMQProtocolHandler _protocolHandler;
-
- /**
- * We need to store the "raw" field table so that we can resubscribe in the event of failover being required
- */
- private final FieldTable _arguments;
-
- /**
- * We store the high water prefetch field in order to be able to reuse it when resubscribing in the event of
- * failover
- */
- private final int _prefetchHigh;
-
- /**
- * We store the low water prefetch field in order to be able to reuse it when resubscribing in the event of
- * failover
- */
- private final int _prefetchLow;
-
- /**
- * We store the exclusive field in order to be able to reuse it when resubscribing in the event of failover
- */
- protected boolean _exclusive;
-
- /**
- * The acknowledge mode in force for this consumer. Note that the AMQP protocol allows different ack modes per
- * consumer whereas JMS defines this at the session level, hence why we associate it with the consumer in our
- * implementation.
- */
- protected final int _acknowledgeMode;
-
- /**
- * Number of messages unacknowledged in DUPS_OK_ACKNOWLEDGE mode
- */
- private int _outstanding;
-
- /**
- * Switch to enable sending of acknowledgements when using DUPS_OK_ACKNOWLEDGE mode. Enabled when _outstannding
- * number of msgs >= _prefetchHigh and disabled at < _prefetchLow
- */
- private boolean _dups_ok_acknowledge_send;
-
- /**
- * List of tags delievered, The last of which which should be acknowledged on commit in transaction mode.
- */
- private ConcurrentLinkedQueue<Long> _receivedDeliveryTags = new ConcurrentLinkedQueue<Long>();
-
- /** The last tag that was "multiple" acknowledged on this session (if transacted) */
- private long _lastAcked;
-
- /** set of tags which have previously been acked; but not part of the multiple ack (transacted mode only) */
- private final SortedSet<Long> _previouslyAcked = new TreeSet<Long>();
-
- private final Object _commitLock = new Object();
-
- /**
- * The thread that was used to call receive(). This is important for being able to interrupt that thread if a
- * receive() is in progress.
- */
- private Thread _receivingThread;
-
-
- /**
- * Used to store this consumer queue name
- * Usefull when more than binding key should be used
- */
- private AMQShortString _queuename;
-
- /**
- * autoClose denotes that the consumer will automatically cancel itself when there are no more messages to receive
- * on the queue. This is used for queue browsing.
- */
- private final boolean _autoClose;
-
- private final boolean _noConsume;
- private List<StackTraceElement> _closedStack = null;
-
-
-
- protected BasicMessageConsumer(int channelId, AMQConnection connection, AMQDestination destination,
- String messageSelector, boolean noLocal, MessageFactoryRegistry messageFactory,
- AMQSession session, AMQProtocolHandler protocolHandler,
- FieldTable arguments, int prefetchHigh, int prefetchLow,
- boolean exclusive, int acknowledgeMode, boolean noConsume, boolean autoClose)
- {
- _channelId = channelId;
- _connection = connection;
- _messageSelector = messageSelector;
- _noLocal = noLocal;
- _destination = destination;
- _messageFactory = messageFactory;
- _session = session;
- _protocolHandler = protocolHandler;
- _arguments = arguments;
- _prefetchHigh = prefetchHigh;
- _prefetchLow = prefetchLow;
- _exclusive = exclusive;
-
- _synchronousQueue = new LinkedBlockingQueue();
- _autoClose = autoClose;
- _noConsume = noConsume;
-
- // Force queue browsers not to use acknowledge modes.
- if (_noConsume)
- {
- _acknowledgeMode = Session.NO_ACKNOWLEDGE;
- }
- else
- {
- _acknowledgeMode = acknowledgeMode;
- }
- }
-
- public AMQDestination getDestination()
- {
- return _destination;
- }
-
- public String getMessageSelector() throws JMSException
- {
- checkPreConditions();
-
- return _messageSelector;
- }
-
- public MessageListener getMessageListener() throws JMSException
- {
- checkPreConditions();
-
- return _messageListener.get();
- }
-
- public int getAcknowledgeMode()
- {
- return _acknowledgeMode;
- }
-
- protected boolean isMessageListenerSet()
- {
- return _messageListener.get() != null;
- }
-
- public void setMessageListener(final MessageListener messageListener) throws JMSException
- {
- checkPreConditions();
-
- // if the current listener is non-null and the session is not stopped, then
- // it is an error to call this method.
-
- // i.e. it is only valid to call this method if
- //
- // (a) the connection is stopped, in which case the dispatcher is not running
- // OR
- // (b) the listener is null AND we are not receiving synchronously at present
- //
-
- if (!_session.getAMQConnection().started())
- {
- _messageListener.set(messageListener);
- _session.setHasMessageListeners();
-
- if (_logger.isDebugEnabled())
- {
- _logger.debug(
- "Session stopped : Message listener(" + messageListener + ") set for destination " + _destination);
- }
- }
- else
- {
- if (_receiving.get())
- {
- throw new javax.jms.IllegalStateException("Another thread is already receiving synchronously.");
- }
-
- if (!_messageListener.compareAndSet(null, messageListener))
- {
- throw new javax.jms.IllegalStateException("Attempt to alter listener while session is started.");
- }
-
- _logger.debug("Message listener set for destination " + _destination);
-
- if (messageListener != null)
- {
- //todo: handle case where connection has already been started, and the dispatcher has alreaded started
- // putting values on the _synchronousQueue
-
- synchronized (_session)
- {
- _messageListener.set(messageListener);
- _session.setHasMessageListeners();
- _session.startDispatcherIfNecessary();
-
- // If we already have messages on the queue, deliver them to the listener
- Object o = _synchronousQueue.poll();
- while (o != null)
- {
- notifyMessage((AbstractJMSMessage) o);
- o = _synchronousQueue.poll();
- }
- }
- }
- }
- }
-
- protected void preApplicationProcessing(AbstractJMSMessage jmsMsg) throws JMSException
- {
- if (_session.getAcknowledgeMode() == Session.CLIENT_ACKNOWLEDGE)
- {
- _session.addUnacknowledgedMessage(jmsMsg.getDeliveryTag());
- }
-
- _session.setInRecovery(false);
- preDeliver(jmsMsg);
- }
-
- /**
- * @param immediate if true then return immediately if the connection is failing over
- *
- * @return boolean if the acquisition was successful
- *
- * @throws JMSException if a listener has already been set or another thread is receiving
- * @throws InterruptedException if interrupted
- */
- private boolean acquireReceiving(boolean immediate) throws JMSException, InterruptedException
- {
- if (_connection.isFailingOver())
- {
- if (immediate)
- {
- return false;
- }
- else
- {
- _connection.blockUntilNotFailingOver();
- }
- }
-
- if (!_receiving.compareAndSet(false, true))
- {
- throw new javax.jms.IllegalStateException("Another thread is already receiving.");
- }
-
- if (isMessageListenerSet())
- {
- throw new javax.jms.IllegalStateException("A listener has already been set.");
- }
-
- _receivingThread = Thread.currentThread();
- return true;
- }
-
- private void releaseReceiving()
- {
- _receiving.set(false);
- _receivingThread = null;
- }
-
- public FieldTable getArguments()
- {
- return _arguments;
- }
-
- public int getPrefetch()
- {
- return _prefetchHigh;
- }
-
- public int getPrefetchHigh()
- {
- return _prefetchHigh;
- }
-
- public int getPrefetchLow()
- {
- return _prefetchLow;
- }
-
- public boolean isNoLocal()
- {
- return _noLocal;
- }
-
- public boolean isExclusive()
- {
- return _exclusive;
- }
-
- public boolean isReceiving()
- {
- return _receiving.get();
- }
-
- public Message receive() throws JMSException
- {
- return receive(0);
- }
-
- public Message receive(long l) throws JMSException
- {
-
- checkPreConditions();
-
- try
- {
- acquireReceiving(false);
- }
- catch (InterruptedException e)
- {
- _logger.warn("Interrupted acquire: " + e);
- if (isClosed())
- {
- return null;
- }
- }
-
- _session.startDispatcherIfNecessary();
-
- try
- {
- Object o = getMessageFromQueue(l);
- final AbstractJMSMessage m = returnMessageOrThrow(o);
- if (m != null)
- {
- preApplicationProcessing(m);
- postDeliver(m);
- }
- return m;
- }
- catch (InterruptedException e)
- {
- _logger.warn("Interrupted: " + e);
-
- return null;
- }
- finally
- {
- releaseReceiving();
- }
- }
-
- public Object getMessageFromQueue(long l) throws InterruptedException
- {
- Object o;
- if (l > 0)
- {
- o = _synchronousQueue.poll(l, TimeUnit.MILLISECONDS);
- }
- else if (l < 0)
- {
- o = _synchronousQueue.poll();
- }
- else
- {
- o = _synchronousQueue.take();
- }
- return o;
- }
-
- abstract Message receiveBrowse() throws JMSException;
-
- public Message receiveNoWait() throws JMSException
- {
- checkPreConditions();
-
- try
- {
- if (!acquireReceiving(true))
- {
- //If we couldn't acquire the receiving thread then return null.
- // This will occur if failing over.
- return null;
- }
- }
- catch (InterruptedException e)
- {
- /*
- * This seems slightly shoddy but should never actually be executed
- * since we told acquireReceiving to return immediately and it shouldn't
- * block on anything.
- */
-
- return null;
- }
-
- _session.startDispatcherIfNecessary();
-
- try
- {
- Object o = getMessageFromQueue(-1);
- final AbstractJMSMessage m = returnMessageOrThrow(o);
- if (m != null)
- {
- preApplicationProcessing(m);
- postDeliver(m);
- }
-
- return m;
- }
- catch (InterruptedException e)
- {
- _logger.warn("Interrupted: " + e);
-
- return null;
- }
- finally
- {
- releaseReceiving();
- }
- }
-
- /**
- * We can get back either a Message or an exception from the queue. This method examines the argument and deals with
- * it by throwing it (if an exception) or returning it (in any other case).
- *
- * @param o the object to return or throw
- * @return a message only if o is a Message
- * @throws JMSException if the argument is a throwable. If it is a JMSException it is rethrown as is, but if not a
- * JMSException is created with the linked exception set appropriately
- */
- private AbstractJMSMessage returnMessageOrThrow(Object o) throws JMSException
- {
- // errors are passed via the queue too since there is no way of interrupting the poll() via the API.
- if (o instanceof Throwable)
- {
- JMSException e = new JMSException("Message consumer forcibly closed due to error: " + o);
- e.initCause((Throwable) o);
- if (o instanceof Exception)
- {
- e.setLinkedException((Exception) o);
- }
-
- throw e;
- }
- else if (o instanceof CloseConsumerMessage)
- {
- _closed.set(true);
- deregisterConsumer();
- return null;
- }
- else
- {
- return (AbstractJMSMessage) o;
- }
- }
-
- public void close() throws JMSException
- {
- close(true);
- }
-
- public void close(boolean sendClose) throws JMSException
- {
- if (_logger.isInfoEnabled())
- {
- _logger.info("Closing consumer:" + debugIdentity());
- }
-
- if (!_closed.getAndSet(true))
- {
- _closing.set(true);
- if (_logger.isDebugEnabled())
- {
- StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
- if (_closedStack != null)
- {
- _logger.debug(_consumerTag + " previously:" + _closedStack.toString());
- }
- else
- {
- _closedStack = Arrays.asList(stackTrace).subList(3, stackTrace.length - 1);
- }
- }
-
- if (sendClose)
- {
- // The Synchronized block only needs to protect network traffic.
- synchronized (_connection.getFailoverMutex())
- {
- try
- {
- // If the session is open or we are in the process
- // of closing the session then send a cance
- // no point otherwise as the connection will be gone
- if (!_session.isClosed() || _session.isClosing())
- {
- sendCancel();
- cleanupQueue();
- }
- }
- catch (AMQException e)
- {
- throw new JMSAMQException("Error closing consumer: " + e, e);
- }
- catch (FailoverException e)
- {
- throw new JMSAMQException("FailoverException interrupted basic cancel.", e);
- }
- }
- }
- else
- {
- // FIXME: wow this is ugly
- // //fixme this probably is not right
- // if (!isNoConsume())
- { // done in BasicCancelOK Handler but not sending one so just deregister.
- deregisterConsumer();
- }
- }
-
- // This will occur if session.close is called closing all consumers we may be blocked waiting for a receive
- // so we need to let it know it is time to close.
- if ((_messageListener != null) && _receiving.get())
- {
- if (_logger.isInfoEnabled())
- {
- _logger.info("Interrupting thread: " + _receivingThread);
- }
-
- _receivingThread.interrupt();
- }
- }
- }
-
- abstract void sendCancel() throws AMQException, FailoverException;
-
- abstract void cleanupQueue() throws AMQException, FailoverException;
-
- /**
- * Called when you need to invalidate a consumer. Used for example when failover has occurred and the client has
- * vetoed automatic resubscription. The caller must hold the failover mutex.
- */
- void markClosed()
- {
- // synchronized (_closed)
- {
- _closed.set(true);
-
- if (_logger.isDebugEnabled())
- {
- if (_closedStack != null)
- {
- StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
- _logger.debug(_consumerTag + " markClosed():"
- + Arrays.asList(stackTrace).subList(3, stackTrace.length - 1));
- _logger.debug(_consumerTag + " previously:" + _closedStack.toString());
- }
- else
- {
- StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
- _closedStack = Arrays.asList(stackTrace).subList(3, stackTrace.length - 1);
- }
- }
- }
-
- deregisterConsumer();
- }
-
- /**
- * @param closeMessage
- * this message signals that we should close the browser
- */
- public void notifyCloseMessage(CloseConsumerMessage closeMessage)
- {
- if (isMessageListenerSet())
- {
- // Currently only possible to get this msg type with a browser.
- // If we get the message here then we should probably just close
- // this consumer.
- // Though an AutoClose consumer with message listener is quite odd..
- // Just log out the fact so we know where we are
- _logger.warn("Using an AutoCloseconsumer with message listener is not supported.");
- }
- else
- {
- try
- {
- _synchronousQueue.put(closeMessage);
- }
- catch (InterruptedException e)
- {
- _logger.info(" SynchronousQueue.put interupted. Usually result of connection closing,"
- + "but we shouldn't have close yet");
- }
- }
- }
-
-
- /**
- * Called from the AMQSession when a message has arrived for this consumer. This methods handles both the case of a
- * message listener or a synchronous receive() caller.
- *
- * @param messageFrame the raw unprocessed mesage
- */
- void notifyMessage(U messageFrame)
- {
- if (messageFrame instanceof CloseConsumerMessage)
- {
- notifyCloseMessage((CloseConsumerMessage) messageFrame);
- return;
- }
-
-
-
- try
- {
- AbstractJMSMessage jmsMessage = createJMSMessageFromUnprocessedMessage(_session.getMessageDelegateFactory(), messageFrame);
-
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Message is of type: " + jmsMessage.getClass().getName());
- }
- notifyMessage(jmsMessage);
- }
- catch (Exception e)
- {
- if (e instanceof InterruptedException)
- {
- _logger.info("SynchronousQueue.put interupted. Usually result of connection closing");
- }
- else
- {
- _logger.error("Caught exception (dump follows) - ignoring...", e);
- }
- }
- }
-
- public abstract AbstractJMSMessage createJMSMessageFromUnprocessedMessage(AMQMessageDelegateFactory delegateFactory, U messageFrame)
- throws Exception;
-
- /** @param jmsMessage this message has already been processed so can't redo preDeliver */
- public void notifyMessage(AbstractJMSMessage jmsMessage)
- {
- try
- {
- if (isMessageListenerSet())
- {
- preApplicationProcessing(jmsMessage);
- getMessageListener().onMessage(jmsMessage);
- postDeliver(jmsMessage);
- }
- else
- {
- // we should not be allowed to add a message is the
- // consumer is closed
- _synchronousQueue.put(jmsMessage);
- }
- }
- catch (Exception e)
- {
- if (e instanceof InterruptedException)
- {
- _logger.info("reNotification : SynchronousQueue.put interupted. Usually result of connection closing");
- }
- else
- {
- _logger.error("reNotification : Caught exception (dump follows) - ignoring...", e);
- }
- }
- }
-
- void preDeliver(AbstractJMSMessage msg)
- {
- switch (_acknowledgeMode)
- {
-
- case Session.PRE_ACKNOWLEDGE:
- _session.acknowledgeMessage(msg.getDeliveryTag(), false);
- break;
-
- case Session.CLIENT_ACKNOWLEDGE:
- // we set the session so that when the user calls acknowledge() it can call the method on session
- // to send out the appropriate frame
- msg.setAMQSession(_session);
- break;
- case Session.SESSION_TRANSACTED:
- if (isNoConsume())
- {
- _session.acknowledgeMessage(msg.getDeliveryTag(), false);
- }
- else
- {
- _session.addDeliveredMessage(msg.getDeliveryTag());
- _session.markDirty();
- }
-
- break;
- }
-
- }
-
- void postDeliver(AbstractJMSMessage msg) throws JMSException
- {
- switch (_acknowledgeMode)
- {
-
- case Session.CLIENT_ACKNOWLEDGE:
- if (isNoConsume())
- {
- _session.acknowledgeMessage(msg.getDeliveryTag(), false);
- }
- _session.markDirty();
- break;
-
- case Session.DUPS_OK_ACKNOWLEDGE:
- case Session.AUTO_ACKNOWLEDGE:
- // we do not auto ack a message if the application code called recover()
- if (!_session.isInRecovery())
- {
- _session.acknowledgeMessage(msg.getDeliveryTag(), false);
- }
-
- break;
- }
- }
-
-
- /**
- * Acknowledge up to last message delivered (if any). Used when commiting.
- *
- * @return the lastDeliveryTag to acknowledge
- */
- Long getLastDelivered()
- {
- if (!_receivedDeliveryTags.isEmpty())
- {
- Long lastDeliveryTag = _receivedDeliveryTags.poll();
-
- while (!_receivedDeliveryTags.isEmpty())
- {
- lastDeliveryTag = _receivedDeliveryTags.poll();
- }
-
- assert _receivedDeliveryTags.isEmpty();
-
- return lastDeliveryTag;
- }
-
- return null;
- }
-
- /**
- * Acknowledge up to last message delivered (if any). Used when commiting.
- */
- void acknowledgeDelivered()
- {
- synchronized(_commitLock)
- {
- ArrayList<Long> tagsToAck = new ArrayList<Long>();
-
- while (!_receivedDeliveryTags.isEmpty())
- {
- tagsToAck.add(_receivedDeliveryTags.poll());
- }
-
- Collections.sort(tagsToAck);
-
- long prevAcked = _lastAcked;
- long oldAckPoint = -1;
-
- while(oldAckPoint != prevAcked)
- {
- oldAckPoint = prevAcked;
-
- Iterator<Long> tagsToAckIterator = tagsToAck.iterator();
-
- while(tagsToAckIterator.hasNext() && tagsToAckIterator.next() == prevAcked+1)
- {
- tagsToAckIterator.remove();
- prevAcked++;
- }
-
- Iterator<Long> previousAckIterator = _previouslyAcked.iterator();
- while(previousAckIterator.hasNext() && previousAckIterator.next() == prevAcked+1)
- {
- previousAckIterator.remove();
- prevAcked++;
- }
-
- }
- if(prevAcked != _lastAcked)
- {
- _session.acknowledgeMessage(prevAcked, true);
- _lastAcked = prevAcked;
- }
-
- Iterator<Long> tagsToAckIterator = tagsToAck.iterator();
-
- while(tagsToAckIterator.hasNext())
- {
- Long tag = tagsToAckIterator.next();
- _session.acknowledgeMessage(tag, false);
- _previouslyAcked.add(tag);
- }
- }
- }
-
-
- void notifyError(Throwable cause)
- {
- // synchronized (_closed)
- {
- _closed.set(true);
- if (_logger.isDebugEnabled())
- {
- StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
- if (_closedStack != null)
- {
- _logger.debug(_consumerTag + " notifyError():"
- + Arrays.asList(stackTrace).subList(3, stackTrace.length - 1));
- _logger.debug(_consumerTag + " previously" + _closedStack.toString());
- }
- else
- {
- _closedStack = Arrays.asList(stackTrace).subList(3, stackTrace.length - 1);
- }
- }
- }
- // QPID-293 can "request redelivery of this error through dispatcher"
-
- // we have no way of propagating the exception to a message listener - a JMS limitation - so we
- // deal with the case where we have a synchronous receive() waiting for a message to arrive
- if (!isMessageListenerSet())
- {
- // offer only succeeds if there is a thread waiting for an item from the queue
- if (_synchronousQueue.offer(cause))
- {
- _logger.debug("Passed exception to synchronous queue for propagation to receive()");
- }
- }
-
- deregisterConsumer();
- }
-
- /**
- * Perform cleanup to deregister this consumer. This occurs when closing the consumer in both the clean case and in
- * the case of an error occurring.
- */
- private void deregisterConsumer()
- {
- _session.deregisterConsumer(this);
- }
-
- public int getConsumerTag()
- {
- return _consumerTag;
- }
-
- public void setConsumerTag(int consumerTag)
- {
- _consumerTag = consumerTag;
- }
-
- public AMQSession getSession()
- {
- return _session;
- }
-
- private void checkPreConditions() throws JMSException
- {
-
- this.checkNotClosed();
-
- if ((_session == null) || _session.isClosed())
- {
- throw new javax.jms.IllegalStateException("Invalid Session");
- }
- }
-
- public boolean isAutoClose()
- {
- return _autoClose;
- }
-
- public boolean isNoConsume()
- {
- return _noConsume || _destination.isBrowseOnly() ;
- }
-
- public void rollback()
- {
- rollbackPendingMessages();
- }
-
- public void rollbackPendingMessages()
- {
- if (_synchronousQueue.size() > 0)
- {
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Rejecting the messages(" + _synchronousQueue
- .size() + ") in _syncQueue (PRQ)" + "for consumer with tag:" + _consumerTag);
- }
-
- Iterator iterator = _synchronousQueue.iterator();
-
- int initialSize = _synchronousQueue.size();
-
- boolean removed = false;
- while (iterator.hasNext())
- {
-
- Object o = iterator.next();
- if (o instanceof AbstractJMSMessage)
- {
- _session.rejectMessage(((AbstractJMSMessage) o), true);
-
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Rejected message:" + ((AbstractJMSMessage) o).getDeliveryTag());
- }
-
- iterator.remove();
- removed = true;
-
- }
- else
- {
- _logger.error("Queue contained a :" + o.getClass()
- + " unable to reject as it is not an AbstractJMSMessage. Will be cleared");
- iterator.remove();
- removed = true;
- }
- }
-
- if (removed && (initialSize == _synchronousQueue.size()))
- {
- _logger.error("Queue had content removed but didn't change in size." + initialSize);
- }
-
-
- if (_synchronousQueue.size() != 0)
- {
- _logger.warn("Queue was not empty after rejecting all messages Remaining:" + _synchronousQueue.size());
- rollback();
- }
-
- clearReceiveQueue();
- }
- }
-
- public String debugIdentity()
- {
- return String.valueOf(_consumerTag) + "[" + System.identityHashCode(this) + "]";
- }
-
- public void clearReceiveQueue()
- {
- _synchronousQueue.clear();
- }
-
-
- public List<Long> drainReceiverQueueAndRetrieveDeliveryTags()
- {
- Iterator<AbstractJMSMessage> iterator = _synchronousQueue.iterator();
- List<Long> tags = new ArrayList<Long>(_synchronousQueue.size());
-
- while (iterator.hasNext())
- {
-
- AbstractJMSMessage msg = iterator.next();
- tags.add(msg.getDeliveryTag());
- iterator.remove();
- }
- return tags;
- }
-
- public AMQShortString getQueuename()
- {
- return _queuename;
- }
-
- public void setQueuename(AMQShortString queuename)
- {
- this._queuename = queuename;
- }
-
- public void addBindingKey(AMQDestination amqd, String routingKey) throws AMQException
- {
- _session.addBindingKey(this,amqd,routingKey);
- }
-
- /** to be called when a failover has occured */
- public void failedOverPre()
- {
- clearReceiveQueue();
- // TGM FIXME: think this should just be removed
- // clearUnackedMessages();
- }
-
- public void failedOverPost() {}
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/BasicMessageConsumer_0_10.java b/java/client/src/main/java/org/apache/qpid/client/BasicMessageConsumer_0_10.java
deleted file mode 100644
index 964c238946..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/BasicMessageConsumer_0_10.java
+++ /dev/null
@@ -1,529 +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.client;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.qpid.client.AMQDestination.AddressOption;
-import org.apache.qpid.client.AMQDestination.DestSyntax;
-import org.apache.qpid.client.failover.FailoverException;
-import org.apache.qpid.client.message.*;
-import org.apache.qpid.client.messaging.address.Node.QueueNode;
-import org.apache.qpid.client.protocol.AMQProtocolHandler;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.FieldTable;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.AMQInternalException;
-import org.apache.qpid.protocol.AMQConstant;
-import org.apache.qpid.transport.*;
-import org.apache.qpid.filter.MessageFilter;
-import org.apache.qpid.filter.JMSSelectorFilter;
-
-import javax.jms.InvalidSelectorException;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageListener;
-import java.util.Iterator;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-/**
- * This is a 0.10 message consumer.
- */
-public class BasicMessageConsumer_0_10 extends BasicMessageConsumer<UnprocessedMessage_0_10>
-{
-
- /**
- * This class logger
- */
- protected final Logger _logger = LoggerFactory.getLogger(getClass());
-
- /**
- * The message selector filter associated with this consumer message selector
- */
- private MessageFilter _filter = null;
-
- /**
- * The underlying QpidSession
- */
- private AMQSession_0_10 _0_10session;
-
- /**
- * Indicates whether this consumer receives pre-acquired messages
- */
- private boolean _preAcquire = true;
-
- /**
- * Indicate whether this consumer is started.
- */
- private boolean _isStarted = false;
-
- /**
- * Specify whether this consumer is performing a sync receive
- */
- private final AtomicBoolean _syncReceive = new AtomicBoolean(false);
- private String _consumerTagString;
-
- private long capacity = 0;
-
- //--- constructor
- protected BasicMessageConsumer_0_10(int channelId, AMQConnection connection, AMQDestination destination,
- String messageSelector, boolean noLocal, MessageFactoryRegistry messageFactory,
- AMQSession session, AMQProtocolHandler protocolHandler,
- FieldTable arguments, int prefetchHigh, int prefetchLow,
- boolean exclusive, int acknowledgeMode, boolean noConsume, boolean autoClose)
- throws JMSException
- {
- super(channelId, connection, destination, messageSelector, noLocal, messageFactory, session, protocolHandler,
- arguments, prefetchHigh, prefetchLow, exclusive, acknowledgeMode, noConsume, autoClose);
- _0_10session = (AMQSession_0_10) session;
- if (messageSelector != null && !messageSelector.equals(""))
- {
- try
- {
- _filter = new JMSSelectorFilter(messageSelector);
- }
- catch (AMQInternalException e)
- {
- throw new InvalidSelectorException("cannot create consumer because of selector issue");
- }
- if (destination instanceof AMQQueue)
- {
- _preAcquire = false;
- }
- }
- _isStarted = connection.started();
-
- // Destination setting overrides connection defaults
- if (destination.getDestSyntax() == DestSyntax.ADDR &&
- destination.getLink().getConsumerCapacity() > 0)
- {
- capacity = destination.getLink().getConsumerCapacity();
- }
- else if (getSession().prefetch())
- {
- capacity = _0_10session.getAMQConnection().getMaxPrefetch();
- }
-
- if (destination.isAddressResolved() && AMQDestination.TOPIC_TYPE == destination.getAddressType())
- {
- boolean namedQueue = destination.getLink() != null && destination.getLink().getName() != null ;
-
- if (!namedQueue)
- {
- _destination = destination.copyDestination();
- _destination.setQueueName(null);
- }
- }
- }
-
-
- @Override public void setConsumerTag(int consumerTag)
- {
- super.setConsumerTag(consumerTag);
- _consumerTagString = String.valueOf(consumerTag);
- }
-
- public String getConsumerTagString()
- {
- return _consumerTagString;
- }
-
- /**
- *
- * This is invoked by the session thread when emptying the session message queue.
- * We first check if the message is valid (match the selector) and then deliver it to the
- * message listener or to the sync consumer queue.
- *
- * @param jmsMessage this message has already been processed so can't redo preDeliver
- */
- @Override public void notifyMessage(AbstractJMSMessage jmsMessage)
- {
- try
- {
- if (checkPreConditions(jmsMessage))
- {
- if (isMessageListenerSet() && capacity == 0)
- {
- _0_10session.getQpidSession().messageFlow(getConsumerTagString(),
- MessageCreditUnit.MESSAGE, 1,
- Option.UNRELIABLE);
- }
- _logger.debug("messageOk, trying to notify");
- super.notifyMessage(jmsMessage);
- }
- }
- catch (AMQException e)
- {
- _logger.error("Receivecd an Exception when receiving message",e);
- getSession().getAMQConnection().exceptionReceived(e);
- }
- }
-
- //----- overwritten methods
-
- /**
- * This method is invoked when this consumer is stopped.
- * It tells the broker to stop delivering messages to this consumer.
- */
- @Override void sendCancel() throws AMQException
- {
- _0_10session.getQpidSession().messageCancel(getConsumerTagString());
- try
- {
- _0_10session.getQpidSession().sync();
- getSession().confirmConsumerCancelled(getConsumerTag()); // confirm cancel
- }
- catch (SessionException se)
- {
- _0_10session.setCurrentException(se);
- }
-
- AMQException amqe = _0_10session.getCurrentException();
- if (amqe != null)
- {
- throw amqe;
- }
- }
-
- @Override void notifyMessage(UnprocessedMessage_0_10 messageFrame)
- {
- super.notifyMessage(messageFrame);
- }
-
- @Override protected void preApplicationProcessing(AbstractJMSMessage jmsMsg) throws JMSException
- {
- super.preApplicationProcessing(jmsMsg);
- if (!_session.getTransacted() && _session.getAcknowledgeMode() != org.apache.qpid.jms.Session.CLIENT_ACKNOWLEDGE)
- {
- _session.addUnacknowledgedMessage(jmsMsg.getDeliveryTag());
- }
- }
-
- @Override public AbstractJMSMessage createJMSMessageFromUnprocessedMessage(
- AMQMessageDelegateFactory delegateFactory, UnprocessedMessage_0_10 msg) throws Exception
- {
- AMQMessageDelegate_0_10.updateExchangeTypeMapping(msg.getMessageTransfer().getHeader(), ((AMQSession_0_10)getSession()).getQpidSession());
- return _messageFactory.createMessage(msg.getMessageTransfer());
- }
-
- // private methods
- /**
- * Check whether a message can be delivered to this consumer.
- *
- * @param message The message to be checked.
- * @return true if the message matches the selector and can be acquired, false otherwise.
- * @throws AMQException If the message preConditions cannot be checked due to some internal error.
- */
- private boolean checkPreConditions(AbstractJMSMessage message) throws AMQException
- {
- boolean messageOk = true;
- // TODO Use a tag for fiding out if message filtering is done here or by the broker.
- try
- {
- if (_messageSelector != null && !_messageSelector.equals(""))
- {
- messageOk = _filter.matches(message);
- }
- }
- catch (Exception e)
- {
- throw new AMQException(AMQConstant.INTERNAL_ERROR, "Error when evaluating message selector", e);
- }
-
- if (_logger.isDebugEnabled())
- {
- _logger.debug("messageOk " + messageOk);
- _logger.debug("_preAcquire " + _preAcquire);
- }
- if (!messageOk)
- {
- if (_preAcquire)
- {
- // this is the case for topics
- // We need to ack this message
- if (_logger.isDebugEnabled())
- {
- _logger.debug("filterMessage - trying to ack message");
- }
- acknowledgeMessage(message);
- }
- else
- {
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Message not OK, releasing");
- }
- releaseMessage(message);
- }
- // if we are syncrhonously waiting for a message
- // and messages are not prefetched we then need to request another one
- if(capacity == 0)
- {
- _0_10session.getQpidSession().messageFlow(getConsumerTagString(),
- MessageCreditUnit.MESSAGE, 1,
- Option.UNRELIABLE);
- }
- }
- // now we need to acquire this message if needed
- // this is the case of queue with a message selector set
- if (!_preAcquire && messageOk && !isNoConsume())
- {
- if (_logger.isDebugEnabled())
- {
- _logger.debug("filterMessage - trying to acquire message");
- }
- messageOk = acquireMessage(message);
- _logger.debug("filterMessage - message acquire status : " + messageOk);
- }
- return messageOk;
- }
-
-
- /**
- * Acknowledge a message
- *
- * @param message The message to be acknowledged
- * @throws AMQException If the message cannot be acquired due to some internal error.
- */
- private void acknowledgeMessage(AbstractJMSMessage message) throws AMQException
- {
- if (!_preAcquire)
- {
- RangeSet ranges = new RangeSet();
- ranges.add((int) message.getDeliveryTag());
- _0_10session.messageAcknowledge
- (ranges,
- _acknowledgeMode != org.apache.qpid.jms.Session.NO_ACKNOWLEDGE);
-
- AMQException amqe = _0_10session.getCurrentException();
- if (amqe != null)
- {
- throw amqe;
- }
- }
- }
-
- /**
- * Release a message
- *
- * @param message The message to be released
- * @throws AMQException If the message cannot be released due to some internal error.
- */
- private void releaseMessage(AbstractJMSMessage message) throws AMQException
- {
- if (_preAcquire)
- {
- RangeSet ranges = new RangeSet();
- ranges.add((int) message.getDeliveryTag());
- _0_10session.getQpidSession().messageRelease(ranges);
- _0_10session.sync();
- }
- }
-
- /**
- * Acquire a message
- *
- * @param message The message to be acquired
- * @return true if the message has been acquired, false otherwise.
- * @throws AMQException If the message cannot be acquired due to some internal error.
- */
- private boolean acquireMessage(AbstractJMSMessage message) throws AMQException
- {
- boolean result = false;
- if (!_preAcquire)
- {
- RangeSet ranges = new RangeSet();
- ranges.add((int) message.getDeliveryTag());
-
- Acquired acq = _0_10session.getQpidSession().messageAcquire(ranges).get();
-
- RangeSet acquired = acq.getTransfers();
- if (acquired != null && acquired.size() > 0)
- {
- result = true;
- }
- }
- return result;
- }
-
-
- public void setMessageListener(final MessageListener messageListener) throws JMSException
- {
- super.setMessageListener(messageListener);
- if (messageListener != null && capacity == 0)
- {
- _0_10session.getQpidSession().messageFlow(getConsumerTagString(),
- MessageCreditUnit.MESSAGE, 1,
- Option.UNRELIABLE);
- }
- if (messageListener != null && !_synchronousQueue.isEmpty())
- {
- Iterator messages=_synchronousQueue.iterator();
- while (messages.hasNext())
- {
- AbstractJMSMessage message=(AbstractJMSMessage) messages.next();
- messages.remove();
- _session.rejectMessage(message, true);
- }
- }
- }
-
- public void failedOverPost()
- {
- if (_0_10session.isStarted() && _syncReceive.get())
- {
- _0_10session.getQpidSession().messageFlow
- (getConsumerTagString(), MessageCreditUnit.MESSAGE, 1,
- Option.UNRELIABLE);
- }
- }
-
- /**
- * When messages are not prefetched we need to request a message from the
- * broker.
- * Note that if the timeout is too short a message may be queued in _synchronousQueue until
- * this consumer closes or request it.
- * @param l
- * @return
- * @throws InterruptedException
- */
- public Object getMessageFromQueue(long l) throws InterruptedException
- {
- if (capacity == 0)
- {
- _syncReceive.set(true);
- }
- if (_0_10session.isStarted() && capacity == 0 && _synchronousQueue.isEmpty())
- {
- _0_10session.getQpidSession().messageFlow(getConsumerTagString(),
- MessageCreditUnit.MESSAGE, 1,
- Option.UNRELIABLE);
- }
- Object o = super.getMessageFromQueue(l);
- if (o == null && _0_10session.isStarted())
- {
-
- _0_10session.getQpidSession().messageFlush
- (getConsumerTagString(), Option.UNRELIABLE, Option.SYNC);
- _0_10session.getQpidSession().sync();
- _0_10session.getQpidSession().messageFlow
- (getConsumerTagString(), MessageCreditUnit.BYTE,
- 0xFFFFFFFF, Option.UNRELIABLE);
-
- if (capacity > 0)
- {
- _0_10session.getQpidSession().messageFlow
- (getConsumerTagString(),
- MessageCreditUnit.MESSAGE,
- capacity,
- Option.UNRELIABLE);
- }
- _0_10session.syncDispatchQueue();
- o = super.getMessageFromQueue(-1);
- }
- if (capacity == 0)
- {
- _syncReceive.set(false);
- }
- return o;
- }
-
- void postDeliver(AbstractJMSMessage msg) throws JMSException
- {
- super.postDeliver(msg);
- if (_acknowledgeMode == org.apache.qpid.jms.Session.NO_ACKNOWLEDGE && !_session.isInRecovery())
- {
- _session.acknowledgeMessage(msg.getDeliveryTag(), false);
- }
-
- if (_acknowledgeMode == org.apache.qpid.jms.Session.AUTO_ACKNOWLEDGE &&
- !_session.isInRecovery() &&
- _session.getAMQConnection().getSyncAck())
- {
- ((AMQSession_0_10) getSession()).flushAcknowledgments();
- ((AMQSession_0_10) getSession()).getQpidSession().sync();
- }
- }
-
- Message receiveBrowse() throws JMSException
- {
- return receiveNoWait();
- }
-
- @Override public void rollbackPendingMessages()
- {
- if (_synchronousQueue.size() > 0)
- {
- RangeSet ranges = new RangeSet();
- Iterator iterator = _synchronousQueue.iterator();
- while (iterator.hasNext())
- {
-
- Object o = iterator.next();
- if (o instanceof AbstractJMSMessage)
- {
- ranges.add((int) ((AbstractJMSMessage) o).getDeliveryTag());
- iterator.remove();
- }
- else
- {
- _logger.error("Queue contained a :" + o.getClass()
- + " unable to reject as it is not an AbstractJMSMessage. Will be cleared");
- iterator.remove();
- }
- }
-
- _0_10session.getQpidSession().messageRelease(ranges, Option.SET_REDELIVERED);
- clearReceiveQueue();
- }
- }
-
- public boolean isExclusive()
- {
- AMQDestination dest = this.getDestination();
- if (dest.getDestSyntax() == AMQDestination.DestSyntax.ADDR)
- {
- if (dest.getAddressType() == AMQDestination.TOPIC_TYPE)
- {
- return true;
- }
- else
- {
- return dest.getLink().getSubscription().isExclusive();
- }
- }
- else
- {
- return _exclusive;
- }
- }
-
- void cleanupQueue() throws AMQException, FailoverException
- {
- AMQDestination dest = this.getDestination();
- if (dest != null && dest.getDestSyntax() == AMQDestination.DestSyntax.ADDR)
- {
- if (dest.getDelete() == AddressOption.ALWAYS ||
- dest.getDelete() == AddressOption.RECEIVER )
- {
- ((AMQSession_0_10) getSession()).getQpidSession().queueDelete(
- this.getDestination().getQueueName());
- }
- }
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/BasicMessageConsumer_0_8.java b/java/client/src/main/java/org/apache/qpid/client/BasicMessageConsumer_0_8.java
deleted file mode 100644
index 00acd5e866..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/BasicMessageConsumer_0_8.java
+++ /dev/null
@@ -1,95 +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.client;
-
-import javax.jms.InvalidSelectorException;
-import javax.jms.JMSException;
-import javax.jms.Message;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.AMQInternalException;
-import org.apache.qpid.client.failover.FailoverException;
-import org.apache.qpid.client.message.*;
-import org.apache.qpid.client.protocol.AMQProtocolHandler;
-import org.apache.qpid.filter.JMSSelectorFilter;
-import org.apache.qpid.framing.*;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class BasicMessageConsumer_0_8 extends BasicMessageConsumer<UnprocessedMessage_0_8>
-{
- protected final Logger _logger = LoggerFactory.getLogger(getClass());
-
- protected BasicMessageConsumer_0_8(int channelId, AMQConnection connection, AMQDestination destination,
- String messageSelector, boolean noLocal, MessageFactoryRegistry messageFactory, AMQSession session,
- AMQProtocolHandler protocolHandler, FieldTable arguments, int prefetchHigh, int prefetchLow,
- boolean exclusive, int acknowledgeMode, boolean noConsume, boolean autoClose) throws JMSException
- {
- super(channelId, connection, destination,messageSelector,noLocal,messageFactory,session,
- protocolHandler, arguments, prefetchHigh, prefetchLow, exclusive,
- acknowledgeMode, noConsume, autoClose);
- try
- {
-
- if (messageSelector != null && messageSelector.length() > 0)
- {
- JMSSelectorFilter _filter = new JMSSelectorFilter(messageSelector);
- }
- }
- catch (AMQInternalException e)
- {
- throw new InvalidSelectorException("cannot create consumer because of selector issue");
- }
- }
-
- void sendCancel() throws AMQException, FailoverException
- {
- BasicCancelBody body = getSession().getMethodRegistry().createBasicCancelBody(new AMQShortString(String.valueOf(_consumerTag)), false);
-
- final AMQFrame cancelFrame = body.generateFrame(_channelId);
-
- _protocolHandler.syncWrite(cancelFrame, BasicCancelOkBody.class);
-
- if (_logger.isDebugEnabled())
- {
- _logger.debug("CancelOk'd for consumer:" + debugIdentity());
- }
- }
-
- public AbstractJMSMessage createJMSMessageFromUnprocessedMessage(AMQMessageDelegateFactory delegateFactory, UnprocessedMessage_0_8 messageFrame)throws Exception
- {
-
- return _messageFactory.createMessage(messageFrame.getDeliveryTag(),
- messageFrame.isRedelivered(), messageFrame.getExchange(),
- messageFrame.getRoutingKey(), messageFrame.getContentHeader(), messageFrame.getBodies());
-
- }
-
- Message receiveBrowse() throws JMSException
- {
- return receive();
- }
-
- void cleanupQueue() throws AMQException, FailoverException
- {
-
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/BasicMessageProducer.java b/java/client/src/main/java/org/apache/qpid/client/BasicMessageProducer.java
deleted file mode 100644
index 8756ac4d05..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/BasicMessageProducer.java
+++ /dev/null
@@ -1,601 +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.client;
-
-import java.io.UnsupportedEncodingException;
-import java.util.UUID;
-
-import javax.jms.BytesMessage;
-import javax.jms.DeliveryMode;
-import javax.jms.Destination;
-import javax.jms.InvalidDestinationException;
-import javax.jms.JMSException;
-import javax.jms.MapMessage;
-import javax.jms.Message;
-import javax.jms.ObjectMessage;
-import javax.jms.StreamMessage;
-import javax.jms.TextMessage;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.message.AbstractJMSMessage;
-import org.apache.qpid.client.message.MessageConverter;
-import org.apache.qpid.client.protocol.AMQProtocolHandler;
-import org.apache.qpid.framing.ContentBody;
-import org.apache.qpid.util.UUIDGen;
-import org.apache.qpid.util.UUIDs;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public abstract class BasicMessageProducer extends Closeable implements org.apache.qpid.jms.MessageProducer
-{
- enum PublishMode { ASYNC_PUBLISH_ALL, SYNC_PUBLISH_PERSISTENT, SYNC_PUBLISH_ALL };
-
- protected final Logger _logger = LoggerFactory.getLogger(getClass());
-
- private AMQConnection _connection;
-
- /**
- * If true, messages will not get a timestamp.
- */
- protected boolean _disableTimestamps;
-
- /**
- * Priority of messages created by this producer.
- */
- private int _messagePriority = Message.DEFAULT_PRIORITY;
-
- /**
- * Time to live of messages. Specified in milliseconds but AMQ has 1 second resolution.
- */
- private long _timeToLive;
-
- /**
- * Delivery mode used for this producer.
- */
- private int _deliveryMode = DeliveryMode.PERSISTENT;
-
- /**
- * The Destination used for this consumer, if specified upon creation.
- */
- protected AMQDestination _destination;
-
- /**
- * Default encoding used for messages produced by this producer.
- */
- private String _encoding;
-
- /**
- * Default encoding used for message produced by this producer.
- */
- private String _mimeType;
-
- protected AMQProtocolHandler _protocolHandler;
-
- /**
- * True if this producer was created from a transacted session
- */
- private boolean _transacted;
-
- protected int _channelId;
-
- /**
- * This is an id generated by the session and is used to tie individual producers to the session. This means we
- * can deregister a producer with the session when the producer is clsoed. We need to be able to tie producers
- * to the session so that when an error is propagated to the session it can close the producer (meaning that
- * a client that happens to hold onto a producer reference will get an error if he tries to use it subsequently).
- */
- private long _producerId;
-
- /**
- * The session used to create this producer
- */
- protected AMQSession _session;
-
- private final boolean _immediate;
-
- private final boolean _mandatory;
-
- private final boolean _waitUntilSent;
-
- private boolean _disableMessageId;
-
- private UUIDGen _messageIdGenerator = UUIDs.newGenerator();
-
- protected String _userID; // ref user id used in the connection.
-
- private static final ContentBody[] NO_CONTENT_BODIES = new ContentBody[0];
-
- protected PublishMode publishMode = PublishMode.ASYNC_PUBLISH_ALL;
-
- protected BasicMessageProducer(AMQConnection connection, AMQDestination destination, boolean transacted, int channelId,
- AMQSession session, AMQProtocolHandler protocolHandler, long producerId, boolean immediate, boolean mandatory,
- boolean waitUntilSent) throws AMQException
- {
- _connection = connection;
- _destination = destination;
- _transacted = transacted;
- _protocolHandler = protocolHandler;
- _channelId = channelId;
- _session = session;
- _producerId = producerId;
- if (destination != null && !(destination instanceof AMQUndefinedDestination))
- {
- declareDestination(destination);
- }
-
- _immediate = immediate;
- _mandatory = mandatory;
- _waitUntilSent = waitUntilSent;
- _userID = connection.getUsername();
- setPublishMode();
- }
-
- void setPublishMode()
- {
- // Publish mode could be configured at destination level as well.
- // Will add support for this when we provide a more robust binding URL
-
- String syncPub = _connection.getSyncPublish();
- // Support for deprecated option sync_persistence
- if (syncPub.equals("persistent") || _connection.getSyncPersistence())
- {
- publishMode = PublishMode.SYNC_PUBLISH_PERSISTENT;
- }
- else if (syncPub.equals("all"))
- {
- publishMode = PublishMode.SYNC_PUBLISH_ALL;
- }
-
- _logger.info("MessageProducer " + toString() + " using publish mode : " + publishMode);
- }
-
- void resubscribe() throws AMQException
- {
- if (_destination != null && !(_destination instanceof AMQUndefinedDestination))
- {
- declareDestination(_destination);
- }
- }
-
- abstract void declareDestination(AMQDestination destination) throws AMQException;
-
- public void setDisableMessageID(boolean b) throws JMSException
- {
- checkPreConditions();
- checkNotClosed();
- _disableMessageId = b;
- }
-
- public boolean getDisableMessageID() throws JMSException
- {
- checkNotClosed();
-
- return _disableMessageId;
- }
-
- public void setDisableMessageTimestamp(boolean b) throws JMSException
- {
- checkPreConditions();
- _disableTimestamps = b;
- }
-
- public boolean getDisableMessageTimestamp() throws JMSException
- {
- checkNotClosed();
-
- return _disableTimestamps;
- }
-
- public void setDeliveryMode(int i) throws JMSException
- {
- checkPreConditions();
- if ((i != DeliveryMode.NON_PERSISTENT) && (i != DeliveryMode.PERSISTENT))
- {
- throw new JMSException("DeliveryMode must be either NON_PERSISTENT or PERSISTENT. Value of " + i
- + " is illegal");
- }
-
- _deliveryMode = i;
- }
-
- public int getDeliveryMode() throws JMSException
- {
- checkNotClosed();
-
- return _deliveryMode;
- }
-
- public void setPriority(int i) throws JMSException
- {
- checkPreConditions();
- if ((i < 0) || (i > 9))
- {
- throw new IllegalArgumentException("Priority of " + i + " is illegal. Value must be in range 0 to 9");
- }
-
- _messagePriority = i;
- }
-
- public int getPriority() throws JMSException
- {
- checkNotClosed();
-
- return _messagePriority;
- }
-
- public void setTimeToLive(long l) throws JMSException
- {
- checkPreConditions();
- if (l < 0)
- {
- throw new IllegalArgumentException("Time to live must be non-negative - supplied value was " + l);
- }
-
- _timeToLive = l;
- }
-
- public long getTimeToLive() throws JMSException
- {
- checkNotClosed();
-
- return _timeToLive;
- }
-
- public Destination getDestination() throws JMSException
- {
- checkNotClosed();
-
- return _destination;
- }
-
- public void close()
- {
- _closed.set(true);
- _session.deregisterProducer(_producerId);
- }
-
- public void send(Message message) throws JMSException
- {
- checkPreConditions();
- checkInitialDestination();
-
-
- synchronized (_connection.getFailoverMutex())
- {
- sendImpl(_destination, message, _deliveryMode, _messagePriority, _timeToLive, _mandatory, _immediate);
- }
- }
-
- public void send(Message message, int deliveryMode) throws JMSException
- {
- checkPreConditions();
- checkInitialDestination();
-
- synchronized (_connection.getFailoverMutex())
- {
- sendImpl(_destination, message, deliveryMode, _messagePriority, _timeToLive, _mandatory, _immediate);
- }
- }
-
- public void send(Message message, int deliveryMode, boolean immediate) throws JMSException
- {
- checkPreConditions();
- checkInitialDestination();
- synchronized (_connection.getFailoverMutex())
- {
- sendImpl(_destination, message, deliveryMode, _messagePriority, _timeToLive, _mandatory, immediate);
- }
- }
-
- public void send(Message message, int deliveryMode, int priority, long timeToLive) throws JMSException
- {
- checkPreConditions();
- checkInitialDestination();
- synchronized (_connection.getFailoverMutex())
- {
- sendImpl(_destination, message, deliveryMode, priority, timeToLive, _mandatory, _immediate);
- }
- }
-
- public void send(Destination destination, Message message) throws JMSException
- {
- checkPreConditions();
- checkDestination(destination);
- synchronized (_connection.getFailoverMutex())
- {
- validateDestination(destination);
- sendImpl((AMQDestination) destination, message, _deliveryMode, _messagePriority, _timeToLive, _mandatory,
- _immediate);
- }
- }
-
- public void send(Destination destination, Message message, int deliveryMode, int priority, long timeToLive)
- throws JMSException
- {
- checkPreConditions();
- checkDestination(destination);
- synchronized (_connection.getFailoverMutex())
- {
- validateDestination(destination);
- sendImpl((AMQDestination) destination, message, deliveryMode, priority, timeToLive, _mandatory, _immediate);
- }
- }
-
- public void send(Destination destination, Message message, int deliveryMode, int priority, long timeToLive,
- boolean mandatory) throws JMSException
- {
- checkPreConditions();
- checkDestination(destination);
- synchronized (_connection.getFailoverMutex())
- {
- validateDestination(destination);
- sendImpl((AMQDestination) destination, message, deliveryMode, priority, timeToLive, mandatory, _immediate);
- }
- }
-
- public void send(Destination destination, Message message, int deliveryMode, int priority, long timeToLive,
- boolean mandatory, boolean immediate) throws JMSException
- {
- checkPreConditions();
- checkDestination(destination);
- synchronized (_connection.getFailoverMutex())
- {
- validateDestination(destination);
- sendImpl((AMQDestination) destination, message, deliveryMode, priority, timeToLive, mandatory, immediate);
- }
- }
-
- public void send(Destination destination, Message message, int deliveryMode, int priority, long timeToLive,
- boolean mandatory, boolean immediate, boolean waitUntilSent) throws JMSException
- {
- checkPreConditions();
- checkDestination(destination);
- synchronized (_connection.getFailoverMutex())
- {
- validateDestination(destination);
- sendImpl((AMQDestination) destination, message, deliveryMode, priority, timeToLive, mandatory, immediate,
- waitUntilSent);
- }
- }
-
- private AbstractJMSMessage convertToNativeMessage(Message message) throws JMSException
- {
- if (message instanceof AbstractJMSMessage)
- {
- return (AbstractJMSMessage) message;
- }
- else
- {
- AbstractJMSMessage newMessage;
-
- if (message instanceof BytesMessage)
- {
- newMessage = new MessageConverter(_session, (BytesMessage) message).getConvertedMessage();
- }
- else if (message instanceof MapMessage)
- {
- newMessage = new MessageConverter(_session, (MapMessage) message).getConvertedMessage();
- }
- else if (message instanceof ObjectMessage)
- {
- newMessage = new MessageConverter(_session, (ObjectMessage) message).getConvertedMessage();
- }
- else if (message instanceof TextMessage)
- {
- newMessage = new MessageConverter(_session, (TextMessage) message).getConvertedMessage();
- }
- else if (message instanceof StreamMessage)
- {
- newMessage = new MessageConverter(_session, (StreamMessage) message).getConvertedMessage();
- }
- else
- {
- newMessage = new MessageConverter(_session, message).getConvertedMessage();
- }
-
- if (newMessage != null)
- {
- return newMessage;
- }
- else
- {
- throw new JMSException("Unable to send message, due to class conversion error: "
- + message.getClass().getName());
- }
- }
- }
-
- private void validateDestination(Destination destination) throws JMSException
- {
- if (!(destination instanceof AMQDestination))
- {
- throw new JMSException("Unsupported destination class: "
- + ((destination != null) ? destination.getClass() : null));
- }
-
- AMQDestination amqDestination = (AMQDestination) destination;
- if(!amqDestination.isExchangeExistsChecked())
- {
- try
- {
- declareDestination(amqDestination);
- }
- catch(Exception e)
- {
- JMSException ex = new JMSException("Error validating destination");
- ex.initCause(e);
- ex.setLinkedException(e);
-
- throw ex;
- }
- amqDestination.setExchangeExistsChecked(true);
- }
- }
-
- protected void sendImpl(AMQDestination destination, Message message, int deliveryMode, int priority, long timeToLive,
- boolean mandatory, boolean immediate) throws JMSException
- {
- sendImpl(destination, message, deliveryMode, priority, timeToLive, mandatory, immediate, _waitUntilSent);
- }
-
- /**
- * The caller of this method must hold the failover mutex.
- *
- * @param destination
- * @param origMessage
- * @param deliveryMode
- * @param priority
- * @param timeToLive
- * @param mandatory
- * @param immediate
- *
- * @throws JMSException
- */
- protected void sendImpl(AMQDestination destination, Message origMessage, int deliveryMode, int priority, long timeToLive,
- boolean mandatory, boolean immediate, boolean wait) throws JMSException
- {
- checkTemporaryDestination(destination);
- origMessage.setJMSDestination(destination);
-
- AbstractJMSMessage message = convertToNativeMessage(origMessage);
-
- if (_transacted)
- {
- if (_session.hasFailedOver() && _session.isDirty())
- {
- throw new JMSAMQException("Failover has occurred and session is dirty so unable to send.",
- new AMQSessionDirtyException("Failover has occurred and session is dirty " +
- "so unable to send."));
- }
- }
-
- UUID messageId = null;
- if (_disableMessageId)
- {
- message.setJMSMessageID((UUID)null);
- }
- else
- {
- messageId = _messageIdGenerator.generate();
- message.setJMSMessageID(messageId);
- }
-
- sendMessage(destination, origMessage, message, messageId, deliveryMode, priority, timeToLive, mandatory, immediate, wait);
-
- if (message != origMessage)
- {
- _logger.debug("Updating original message");
- origMessage.setJMSPriority(message.getJMSPriority());
- origMessage.setJMSTimestamp(message.getJMSTimestamp());
- _logger.debug("Setting JMSExpiration:" + message.getJMSExpiration());
- origMessage.setJMSExpiration(message.getJMSExpiration());
- origMessage.setJMSMessageID(message.getJMSMessageID());
- }
-
- if (_transacted)
- {
- _session.markDirty();
- }
- }
-
- abstract void sendMessage(AMQDestination destination, Message origMessage, AbstractJMSMessage message,
- UUID messageId, int deliveryMode, int priority, long timeToLive, boolean mandatory,
- boolean immediate, boolean wait) throws JMSException;
-
- private void checkTemporaryDestination(AMQDestination destination) throws JMSException
- {
- if (destination instanceof TemporaryDestination)
- {
- _logger.debug("destination is temporary destination");
- TemporaryDestination tempDest = (TemporaryDestination) destination;
- if (tempDest.getSession().isClosed())
- {
- _logger.debug("session is closed");
- throw new JMSException("Session for temporary destination has been closed");
- }
-
- if (tempDest.isDeleted())
- {
- _logger.debug("destination is deleted");
- throw new JMSException("Cannot send to a deleted temporary destination");
- }
- }
- }
-
- public void setMimeType(String mimeType) throws JMSException
- {
- checkNotClosed();
- _mimeType = mimeType;
- }
-
- public void setEncoding(String encoding) throws JMSException, UnsupportedEncodingException
- {
- checkNotClosed();
- _encoding = encoding;
- }
-
- private void checkPreConditions() throws javax.jms.IllegalStateException, JMSException
- {
- checkNotClosed();
-
- if ((_session == null) || _session.isClosed())
- {
- throw new javax.jms.IllegalStateException("Invalid Session");
- }
- if(_session.getAMQConnection().isClosed())
- {
- throw new javax.jms.IllegalStateException("Connection closed");
- }
- }
-
- private void checkInitialDestination()
- {
- if (_destination == null)
- {
- throw new UnsupportedOperationException("Destination is null");
- }
- }
-
- private void checkDestination(Destination suppliedDestination) throws InvalidDestinationException
- {
- if ((_destination != null) && (suppliedDestination != null))
- {
- throw new UnsupportedOperationException(
- "This message producer was created with a Destination, therefore you cannot use an unidentified Destination");
- }
-
- if (suppliedDestination == null)
- {
- throw new InvalidDestinationException("Supplied Destination was invalid");
- }
-
- }
-
- public AMQSession getSession()
- {
- return _session;
- }
-
- public boolean isBound(AMQDestination destination) throws JMSException
- {
- return _session.isQueueBound(destination.getExchangeName(), null, destination.getRoutingKey());
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/BasicMessageProducer_0_10.java b/java/client/src/main/java/org/apache/qpid/client/BasicMessageProducer_0_10.java
deleted file mode 100644
index 62d1d1698c..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/BasicMessageProducer_0_10.java
+++ /dev/null
@@ -1,269 +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.client;
-
-import static org.apache.qpid.transport.Option.NONE;
-import static org.apache.qpid.transport.Option.SYNC;
-import static org.apache.qpid.transport.Option.UNRELIABLE;
-
-import java.nio.ByteBuffer;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.UUID;
-
-import javax.jms.DeliveryMode;
-import javax.jms.JMSException;
-import javax.jms.Message;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.AMQDestination.AddressOption;
-import org.apache.qpid.client.AMQDestination.DestSyntax;
-import org.apache.qpid.client.message.AMQMessageDelegate_0_10;
-import org.apache.qpid.client.message.AbstractJMSMessage;
-import org.apache.qpid.client.messaging.address.Link.Reliability;
-import org.apache.qpid.client.messaging.address.Node.QueueNode;
-import org.apache.qpid.client.protocol.AMQProtocolHandler;
-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.MessageDeliveryMode;
-import org.apache.qpid.transport.MessageDeliveryPriority;
-import org.apache.qpid.transport.MessageProperties;
-import org.apache.qpid.transport.Option;
-import org.apache.qpid.util.Strings;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * This is a 0_10 message producer.
- */
-public class BasicMessageProducer_0_10 extends BasicMessageProducer
-{
- private static final Logger _logger = LoggerFactory.getLogger(BasicMessageProducer_0_10.class);
- private byte[] userIDBytes;
-
- BasicMessageProducer_0_10(AMQConnection connection, AMQDestination destination, boolean transacted, int channelId,
- AMQSession session, AMQProtocolHandler protocolHandler, long producerId,
- boolean immediate, boolean mandatory, boolean waitUntilSent) throws AMQException
- {
- super(connection, destination, transacted, channelId, session, protocolHandler, producerId, immediate,
- mandatory, waitUntilSent);
-
- userIDBytes = Strings.toUTF8(_userID);
- }
-
- void declareDestination(AMQDestination destination) throws AMQException
- {
- if (destination.getDestSyntax() == DestSyntax.BURL)
- {
- if (getSession().isDeclareExchanges())
- {
- String name = destination.getExchangeName().toString();
- ((AMQSession_0_10) getSession()).getQpidSession().exchangeDeclare
- (name,
- destination.getExchangeClass().toString(),
- null, null,
- name.startsWith("amq.") ? Option.PASSIVE : Option.NONE);
- }
- }
- else
- {
- try
- {
- getSession().handleAddressBasedDestination(destination,false,false);
- }
- catch(Exception e)
- {
- AMQException ex = new AMQException("Exception occured while verifying destination",e);
- throw ex;
- }
- }
- }
-
- //--- Overwritten methods
-
- /**
- * Sends a message to a given destination
- */
- void sendMessage(AMQDestination destination, Message origMessage, AbstractJMSMessage message,
- UUID messageId, int deliveryMode, int priority, long timeToLive, boolean mandatory,
- boolean immediate, boolean wait) throws JMSException
- {
- message.prepareForSending();
-
- AMQMessageDelegate_0_10 delegate = (AMQMessageDelegate_0_10) message.getDelegate();
-
- DeliveryProperties deliveryProp = delegate.getDeliveryProperties();
- MessageProperties messageProps = delegate.getMessageProperties();
-
- // On the receiving side, this will be read in to the JMSXUserID as well.
- messageProps.setUserId(userIDBytes);
-
- if (messageId != null)
- {
- messageProps.setMessageId(messageId);
- }
- else if (messageProps.hasMessageId())
- {
- messageProps.clearMessageId();
- }
-
- long currentTime = 0;
- if (timeToLive > 0 || !_disableTimestamps)
- {
- currentTime = System.currentTimeMillis();
- }
-
- if (timeToLive > 0)
- {
- deliveryProp.setTtl(timeToLive);
- message.setJMSExpiration(currentTime + timeToLive);
- }
-
- if (!_disableTimestamps)
- {
-
- deliveryProp.setTimestamp(currentTime);
- message.setJMSTimestamp(currentTime);
- }
-
- if (!deliveryProp.hasDeliveryMode() || deliveryProp.getDeliveryMode().getValue() != deliveryMode)
- {
- MessageDeliveryMode mode;
- switch (deliveryMode)
- {
- case DeliveryMode.PERSISTENT:
- mode = MessageDeliveryMode.PERSISTENT;
- break;
- case DeliveryMode.NON_PERSISTENT:
- mode = MessageDeliveryMode.NON_PERSISTENT;
- break;
- default:
- throw new IllegalArgumentException("illegal delivery mode: " + deliveryMode);
- }
- deliveryProp.setDeliveryMode(mode);
- message.setJMSDeliveryMode(deliveryMode);
- }
- if (!deliveryProp.hasPriority() || deliveryProp.getPriority().getValue() != priority)
- {
- deliveryProp.setPriority(MessageDeliveryPriority.get((short) priority));
- message.setJMSPriority(priority);
- }
- String exchangeName = destination.getExchangeName() == null ? "" : destination.getExchangeName().toString();
- if ( deliveryProp.getExchange() == null || ! deliveryProp.getExchange().equals(exchangeName))
- {
- deliveryProp.setExchange(exchangeName);
- }
- String routingKey = destination.getRoutingKey().toString();
- if (deliveryProp.getRoutingKey() == null || ! deliveryProp.getRoutingKey().equals(routingKey))
- {
- deliveryProp.setRoutingKey(routingKey);
- }
-
- if (destination.getDestSyntax() == AMQDestination.DestSyntax.ADDR &&
- (destination.getSubject() != null ||
- (messageProps.getApplicationHeaders() != null && messageProps.getApplicationHeaders().get("qpid.subject") != null))
- )
- {
- Map<String,Object> appProps = messageProps.getApplicationHeaders();
- if (appProps == null)
- {
- appProps = new HashMap<String,Object>();
- messageProps.setApplicationHeaders(appProps);
- }
-
- if (appProps.get("qpid.subject") == null)
- {
- // use default subject in address string
- appProps.put("qpid.subject",destination.getSubject());
- }
-
- if (destination.getTargetNode().getType() == AMQDestination.TOPIC_TYPE)
- {
- deliveryProp.setRoutingKey((String)
- messageProps.getApplicationHeaders().get("qpid.subject"));
- }
- }
-
- messageProps.setContentLength(message.getContentLength());
-
- // send the message
- try
- {
- org.apache.qpid.transport.Session ssn = (org.apache.qpid.transport.Session)
- ((AMQSession_0_10) getSession()).getQpidSession();
-
- // if true, we need to sync the delivery of this message
- boolean sync = false;
-
- sync = ( (publishMode == PublishMode.SYNC_PUBLISH_ALL) ||
- (publishMode == PublishMode.SYNC_PUBLISH_PERSISTENT &&
- deliveryMode == DeliveryMode.PERSISTENT)
- );
-
- boolean unreliable = (destination.getDestSyntax() == DestSyntax.ADDR) &&
- (destination.getLink().getReliability() == Reliability.UNRELIABLE);
-
- org.apache.mina.common.ByteBuffer data = message.getData();
- ByteBuffer buffer = data == null ? ByteBuffer.allocate(0) : data.buf().slice();
-
- ssn.messageTransfer(destination.getExchangeName() == null ? "" : destination.getExchangeName().toString(),
- MessageAcceptMode.NONE,
- MessageAcquireMode.PRE_ACQUIRED,
- new Header(deliveryProp, messageProps),
- buffer, sync ? SYNC : NONE, unreliable ? UNRELIABLE : NONE);
- if (sync)
- {
- ssn.sync();
- ((AMQSession_0_10) getSession()).getCurrentException();
- }
-
- }
- catch (Exception e)
- {
- JMSException jmse = new JMSException("Exception when sending message");
- jmse.setLinkedException(e);
- jmse.initCause(e);
- throw jmse;
- }
- }
-
-
- public boolean isBound(AMQDestination destination) throws JMSException
- {
- return _session.isQueueBound(destination);
- }
-
- @Override
- public void close()
- {
- super.close();
- AMQDestination dest = _destination;
- if (dest != null && dest.getDestSyntax() == AMQDestination.DestSyntax.ADDR)
- {
- if (dest.getDelete() == AddressOption.ALWAYS ||
- dest.getDelete() == AddressOption.SENDER )
- {
- ((AMQSession_0_10) getSession()).getQpidSession().queueDelete(
- _destination.getQueueName());
- }
- }
- }
-}
-
diff --git a/java/client/src/main/java/org/apache/qpid/client/BasicMessageProducer_0_8.java b/java/client/src/main/java/org/apache/qpid/client/BasicMessageProducer_0_8.java
deleted file mode 100644
index 27f7486890..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/BasicMessageProducer_0_8.java
+++ /dev/null
@@ -1,229 +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.client;
-
-import java.util.UUID;
-
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.Topic;
-import javax.jms.Queue;
-
-import org.apache.mina.common.ByteBuffer;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.message.AbstractJMSMessage;
-import org.apache.qpid.client.message.AMQMessageDelegate;
-import org.apache.qpid.client.message.AMQMessageDelegate_0_8;
-import org.apache.qpid.client.protocol.AMQProtocolHandler;
-import org.apache.qpid.framing.AMQFrame;
-import org.apache.qpid.framing.BasicConsumeBody;
-import org.apache.qpid.framing.BasicContentHeaderProperties;
-import org.apache.qpid.framing.BasicPublishBody;
-import org.apache.qpid.framing.CompositeAMQDataBlock;
-import org.apache.qpid.framing.ContentBody;
-import org.apache.qpid.framing.ContentHeaderBody;
-import org.apache.qpid.framing.ExchangeDeclareBody;
-
-public class BasicMessageProducer_0_8 extends BasicMessageProducer
-{
-
- BasicMessageProducer_0_8(AMQConnection connection, AMQDestination destination, boolean transacted, int channelId,
- AMQSession session, AMQProtocolHandler protocolHandler, long producerId, boolean immediate, boolean mandatory,
- boolean waitUntilSent) throws AMQException
- {
- super(connection, destination,transacted,channelId,session, protocolHandler, producerId, immediate, mandatory,waitUntilSent);
- }
-
- void declareDestination(AMQDestination destination)
- {
-
- ExchangeDeclareBody body = getSession().getMethodRegistry().createExchangeDeclareBody(_session.getTicket(),
- destination.getExchangeName(),
- destination.getExchangeClass(),
- false,
- false,
- false,
- false,
- true,
- null);
- // Declare the exchange
- // Note that the durable and internal arguments are ignored since passive is set to false
-
- AMQFrame declare = body.generateFrame(_channelId);
-
- _protocolHandler.writeFrame(declare);
- }
-
- void sendMessage(AMQDestination destination, Message origMessage, AbstractJMSMessage message,
- UUID messageId, int deliveryMode,int priority, long timeToLive, boolean mandatory,
- boolean immediate, boolean wait) throws JMSException
- {
- BasicPublishBody body = getSession().getMethodRegistry().createBasicPublishBody(_session.getTicket(),
- destination.getExchangeName(),
- destination.getRoutingKey(),
- mandatory,
- immediate);
-
- AMQFrame publishFrame = body.generateFrame(_channelId);
-
- message.prepareForSending();
- ByteBuffer payload = message.getData();
- AMQMessageDelegate_0_8 delegate = (AMQMessageDelegate_0_8) message.getDelegate();
- BasicContentHeaderProperties contentHeaderProperties = delegate.getContentHeaderProperties();
-
- contentHeaderProperties.setUserId(_userID);
-
- //Set the JMS_QPID_DESTTYPE for 0-8/9 messages
- int type;
- if (destination instanceof Topic)
- {
- type = AMQDestination.TOPIC_TYPE;
- }
- else if (destination instanceof Queue)
- {
- type = AMQDestination.QUEUE_TYPE;
- }
- else
- {
- type = AMQDestination.UNKNOWN_TYPE;
- }
-
- //Set JMS_QPID_DESTTYPE
- delegate.getContentHeaderProperties().getHeaders().setInteger(CustomJMSXProperty.JMS_QPID_DESTTYPE.getShortStringName(), type);
-
- if (!_disableTimestamps)
- {
- final long currentTime = System.currentTimeMillis();
- contentHeaderProperties.setTimestamp(currentTime);
-
- if (timeToLive > 0)
- {
- contentHeaderProperties.setExpiration(currentTime + timeToLive);
- }
- else
- {
- contentHeaderProperties.setExpiration(0);
- }
- }
-
- contentHeaderProperties.setDeliveryMode((byte) deliveryMode);
- contentHeaderProperties.setPriority((byte) priority);
-
- final int size = (payload != null) ? payload.limit() : 0;
- final int contentBodyFrameCount = calculateContentBodyFrameCount(payload);
- final AMQFrame[] frames = new AMQFrame[2 + contentBodyFrameCount];
-
- if (payload != null)
- {
- createContentBodies(payload, frames, 2, _channelId);
- }
-
- if ((contentBodyFrameCount != 0) && _logger.isDebugEnabled())
- {
- _logger.debug("Sending content body frames to " + destination);
- }
-
-
- // TODO: This is a hacky way of getting the AMQP class-id for the Basic class
- int classIfForBasic = getSession().getMethodRegistry().createBasicQosOkBody().getClazz();
-
- AMQFrame contentHeaderFrame =
- ContentHeaderBody.createAMQFrame(_channelId,
- classIfForBasic, 0, contentHeaderProperties, size);
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Sending content header frame to " + destination);
- }
-
- frames[0] = publishFrame;
- frames[1] = contentHeaderFrame;
- CompositeAMQDataBlock compositeFrame = new CompositeAMQDataBlock(frames);
-
- try
- {
- _session.checkFlowControl();
- }
- catch (InterruptedException e)
- {
- JMSException jmse = new JMSException("Interrupted while waiting for flow control to be removed");
- jmse.setLinkedException(e);
- jmse.initCause(e);
- throw jmse;
- }
-
- _protocolHandler.writeFrame(compositeFrame, wait);
- }
-
- /**
- * Create content bodies. This will split a large message into numerous bodies depending on the negotiated
- * maximum frame size.
- *
- * @param payload
- * @param frames
- * @param offset
- * @param channelId @return the array of content bodies
- */
- private void createContentBodies(ByteBuffer payload, AMQFrame[] frames, int offset, int channelId)
- {
-
- if (frames.length == (offset + 1))
- {
- frames[offset] = ContentBody.createAMQFrame(channelId, new ContentBody(payload));
- }
- else
- {
-
- final long framePayloadMax = _session.getAMQConnection().getMaximumFrameSize() - 1;
- long remaining = payload.remaining();
- for (int i = offset; i < frames.length; i++)
- {
- payload.position((int) framePayloadMax * (i - offset));
- int length = (remaining >= framePayloadMax) ? (int) framePayloadMax : (int) remaining;
- payload.limit(payload.position() + length);
- frames[i] = ContentBody.createAMQFrame(channelId, new ContentBody(payload.slice()));
-
- remaining -= length;
- }
- }
-
- }
-
- private int calculateContentBodyFrameCount(ByteBuffer payload)
- {
- // we substract one from the total frame maximum size to account for the end of frame marker in a body frame
- // (0xCE byte).
- int frameCount;
- if ((payload == null) || (payload.remaining() == 0))
- {
- frameCount = 0;
- }
- else
- {
- int dataLength = payload.remaining();
- final long framePayloadMax = _session.getAMQConnection().getMaximumFrameSize() - 1;
- int lastFrame = ((dataLength % framePayloadMax) > 0) ? 1 : 0;
- frameCount = (int) (dataLength / framePayloadMax) + lastFrame;
- }
-
- return frameCount;
- }
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/ChannelToSessionMap.java b/java/client/src/main/java/org/apache/qpid/client/ChannelToSessionMap.java
deleted file mode 100644
index 2fdb35de49..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/ChannelToSessionMap.java
+++ /dev/null
@@ -1,167 +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.client;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.LinkedHashMap;
-import java.util.concurrent.atomic.AtomicInteger;
-
-public final class ChannelToSessionMap
-{
- private final AMQSession[] _fastAccessSessions = new AMQSession[16];
- private final LinkedHashMap<Integer, AMQSession> _slowAccessSessions = new LinkedHashMap<Integer, AMQSession>();
- private int _size = 0;
- private static final int FAST_CHANNEL_ACCESS_MASK = 0xFFFFFFF0;
- private AtomicInteger _idFactory = new AtomicInteger(0);
- private int _maxChannelID;
- private int _minChannelID;
-
- public AMQSession get(int channelId)
- {
- if ((channelId & FAST_CHANNEL_ACCESS_MASK) == 0)
- {
- return _fastAccessSessions[channelId];
- }
- else
- {
- return _slowAccessSessions.get(channelId);
- }
- }
-
- public AMQSession put(int channelId, AMQSession session)
- {
- AMQSession oldVal;
- if ((channelId & FAST_CHANNEL_ACCESS_MASK) == 0)
- {
- oldVal = _fastAccessSessions[channelId];
- _fastAccessSessions[channelId] = session;
- }
- else
- {
- oldVal = _slowAccessSessions.put(channelId, session);
- }
- if ((oldVal != null) && (session == null))
- {
- _size--;
- }
- else if ((oldVal == null) && (session != null))
- {
- _size++;
- }
-
- return session;
-
- }
-
- public AMQSession remove(int channelId)
- {
- AMQSession session;
- if ((channelId & FAST_CHANNEL_ACCESS_MASK) == 0)
- {
- session = _fastAccessSessions[channelId];
- _fastAccessSessions[channelId] = null;
- }
- else
- {
- session = _slowAccessSessions.remove(channelId);
- }
-
- if (session != null)
- {
- _size--;
- }
- return session;
-
- }
-
- public Collection<AMQSession> values()
- {
- ArrayList<AMQSession> values = new ArrayList<AMQSession>(size());
-
- for (int i = 0; i < 16; i++)
- {
- if (_fastAccessSessions[i] != null)
- {
- values.add(_fastAccessSessions[i]);
- }
- }
- values.addAll(_slowAccessSessions.values());
-
- return values;
- }
-
- public int size()
- {
- return _size;
- }
-
- public void clear()
- {
- _size = 0;
- _slowAccessSessions.clear();
- for (int i = 0; i < 16; i++)
- {
- _fastAccessSessions[i] = null;
- }
- }
-
- /*
- * Synchronized on whole method so that we don't need to consider the
- * increment-then-reset path in too much detail
- */
- public synchronized int getNextChannelId()
- {
- int id = _minChannelID;
-
- boolean done = false;
- while (!done)
- {
- id = _idFactory.getAndIncrement();
- if (id == _maxChannelID)
- {
- //go back to the start
- _idFactory.set(_minChannelID);
- }
- if ((id & FAST_CHANNEL_ACCESS_MASK) == 0)
- {
- done = (_fastAccessSessions[id] == null);
- }
- else
- {
- done = (!_slowAccessSessions.keySet().contains(id));
- }
- }
-
- return id;
- }
-
- public void setMaxChannelID(int maxChannelID)
- {
- _maxChannelID = maxChannelID;
- }
-
- public void setMinChannelID(int minChannelID)
- {
- _minChannelID = minChannelID;
- _idFactory.set(_minChannelID);
- }
-} \ No newline at end of file
diff --git a/java/client/src/main/java/org/apache/qpid/client/Closeable.java b/java/client/src/main/java/org/apache/qpid/client/Closeable.java
deleted file mode 100644
index e6771e122c..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/Closeable.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.client;
-
-import javax.jms.IllegalStateException;
-import javax.jms.JMSException;
-
-import java.util.concurrent.atomic.AtomicBoolean;
-
-/**
- * Captures the 'closed' state of an object, that is initially open, can be tested to see if it is closed, and provides
- * a 'close' method to close it.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Mark an object as closed.
- * <tr><td> Check if an object is closed.
- * <tr><td> Raise a JMS exception if an object is closed.
- * </table>
- *
- * @todo Might be better to make this an interface. This whole class doesn't really encapsulate a terribly neat
- * piece of re-usable functionality. A simple interface defining a close method would suffice.
- *
- * @todo The convenience method {@link #checkNotClosed} is not that helpfull, what if the caller wants to do something
- * other than throw an exception? It doesn't really represent a very usefull re-usable piece of code. Consider
- * inlining it and dropping the method.
- */
-public abstract class Closeable
-{
- /**
- * We use an atomic boolean so that we do not have to synchronized access to this flag. Synchronizing access to this
- * flag would mean have a synchronized block in every method.
- */
- protected final AtomicBoolean _closed = new AtomicBoolean(false);
-
- /**
- * Are we in the process of closing. We have this distinction so we can
- * still signal we are in the process of closing so other objects can tell
- * the difference and tidy up.
- */
- protected final AtomicBoolean _closing = new AtomicBoolean(false);
-
- /**
- * Checks if this is closed, and raises a JMSException if it is.
- *
- * @throws JMSException If this is closed.
- */
- protected void checkNotClosed() throws JMSException
- {
- if (isClosed())
- {
- throw new IllegalStateException("Object " + toString() + " has been closed");
- }
- }
-
- /**
- * Checks if this is closed.
- *
- * @return <tt>true</tt> if this is closed, <tt>false</tt> otherwise.
- */
- public boolean isClosed()
- {
- return _closed.get();
- }
-
- /**
- * Checks if this is closis.
- *
- * @return <tt>true</tt> if we are closing, <tt>false</tt> otherwise.
- */
- public boolean isClosing()
- {
- return _closing.get();
- }
-
-
- /**
- * Closes this object.
- *
- * @throws JMSException If this cannot be closed for any reason.
- */
- public abstract void close() throws JMSException;
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/ConnectionTuneParameters.java b/java/client/src/main/java/org/apache/qpid/client/ConnectionTuneParameters.java
deleted file mode 100644
index b1ec7216bc..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/ConnectionTuneParameters.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.client;
-
-public class ConnectionTuneParameters
-{
- private long _frameMax;
-
- private int _channelMax;
-
- private int _heartbeat;
-
- private long _txnLimit;
-
- public long getFrameMax()
- {
- return _frameMax;
- }
-
- public void setFrameMax(long frameMax)
- {
- _frameMax = frameMax;
- }
-
- public int getChannelMax()
- {
- return _channelMax;
- }
-
- public void setChannelMax(int channelMax)
- {
- _channelMax = channelMax;
- }
-
- public int getHeartbeat()
- {
- return _heartbeat;
- }
-
- public void setHeartbeat(int hearbeat)
- {
- _heartbeat = hearbeat;
- }
-
- public long getTxnLimit()
- {
- return _txnLimit;
- }
-
- public void setTxnLimit(long txnLimit)
- {
- _txnLimit = txnLimit;
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/CustomJMSXProperty.java b/java/client/src/main/java/org/apache/qpid/client/CustomJMSXProperty.java
deleted file mode 100644
index 7cc548915c..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/CustomJMSXProperty.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.
- *
- */
-package org.apache.qpid.client;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Enumeration;
-
-import org.apache.qpid.framing.AMQShortString;
-
-public enum CustomJMSXProperty
-{
- JMS_AMQP_NULL,
- JMS_QPID_DESTTYPE,
- JMSXGroupID,
- JMSXGroupSeq,
- JMSXUserID;
-
-
- private final AMQShortString _nameAsShortString;
-
- CustomJMSXProperty()
- {
- _nameAsShortString = new AMQShortString(toString());
- }
-
- public AMQShortString getShortStringName()
- {
- return _nameAsShortString;
- }
-
- private static Enumeration _names;
-
- public static synchronized Enumeration asEnumeration()
- {
- if(_names == null)
- {
- CustomJMSXProperty[] properties = values();
- ArrayList<String> nameList = new ArrayList<String>(properties.length);
- for(CustomJMSXProperty property : properties)
- {
- nameList.add(property.toString());
- }
- _names = Collections.enumeration(nameList);
- }
- return _names;
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/DispatcherCallback.java b/java/client/src/main/java/org/apache/qpid/client/DispatcherCallback.java
deleted file mode 100644
index 81a55006ed..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/DispatcherCallback.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.client;
-
-import java.util.Queue;
-
-public abstract class DispatcherCallback
-{
- BasicMessageConsumer _consumer;
-
- public DispatcherCallback(BasicMessageConsumer mc)
- {
- _consumer = mc;
- }
-
- abstract public void whilePaused(Queue<MessageConsumerPair> reprocessQueue);
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/JMSAMQException.java b/java/client/src/main/java/org/apache/qpid/client/JMSAMQException.java
deleted file mode 100644
index 1151a97cf4..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/JMSAMQException.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.client;
-
-import org.apache.qpid.AMQException;
-
-import javax.jms.JMSException;
-
-/**
- * JMSException does not accept wrapped exceptions in its constructor. Presumably this is because it is a relatively old
- * Java exception class, before this was added as a default to Throwable. This exception class accepts wrapped exceptions
- * as well as error messages, through its constructor, but is a JMSException.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Accept wrapped exceptions as a JMSException.
- * </table>
- */
-public class JMSAMQException extends JMSException
-{
- /**
- * Creates a JMSException, wrapping another exception class.
- *
- * @param message The error message.
- * @param cause The underlying exception that caused this one. May be null if none is to be set.
- */
- public JMSAMQException(String message, Exception cause)
- {
- super(message);
-
- if (cause != null)
- {
- setLinkedException(cause);
- initCause(cause);
- }
- }
-
- /**
- * @param cause The underlying exception.
- *
- * @deprecated Use the other constructor and write a helpfull message. This one will be deleted.
- */
- public JMSAMQException(AMQException cause)
- {
- super(cause.getMessage(), String.valueOf(cause.getErrorCode()));
- setLinkedException(cause);
- initCause(cause);
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/JmsNotImplementedException.java b/java/client/src/main/java/org/apache/qpid/client/JmsNotImplementedException.java
deleted file mode 100644
index 903514c35f..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/JmsNotImplementedException.java
+++ /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.
- *
- */
-package org.apache.qpid.client;
-
-import javax.jms.JMSException;
-
-public class JmsNotImplementedException extends JMSException
-{
- public JmsNotImplementedException()
- {
- super("Not implemented");
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/MessageConsumerPair.java b/java/client/src/main/java/org/apache/qpid/client/MessageConsumerPair.java
deleted file mode 100644
index 585d6db3fd..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/MessageConsumerPair.java
+++ /dev/null
@@ -1,43 +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.client;
-
-public class MessageConsumerPair
-{
- BasicMessageConsumer _consumer;
- Object _item;
-
- public MessageConsumerPair(BasicMessageConsumer consumer, Object item)
- {
- _consumer = consumer;
- _item = item;
- }
-
- public BasicMessageConsumer getConsumer()
- {
- return _consumer;
- }
-
- public Object getItem()
- {
- return _item;
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/QpidConnectionMetaData.java b/java/client/src/main/java/org/apache/qpid/client/QpidConnectionMetaData.java
deleted file mode 100644
index 3bb5707417..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/QpidConnectionMetaData.java
+++ /dev/null
@@ -1,97 +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.client;
-
-import java.util.Enumeration;
-
-import javax.jms.ConnectionMetaData;
-import javax.jms.JMSException;
-
-import org.apache.qpid.common.QpidProperties;
-
-public class QpidConnectionMetaData implements ConnectionMetaData
-{
-
-
- QpidConnectionMetaData(AMQConnection conn)
- {
- }
-
- public int getJMSMajorVersion() throws JMSException
- {
- return 1;
- }
-
- public int getJMSMinorVersion() throws JMSException
- {
- return 1;
- }
-
- public String getJMSProviderName() throws JMSException
- {
- return "Apache " + QpidProperties.getProductName();
- }
-
- public String getJMSVersion() throws JMSException
- {
- return "1.1";
- }
-
- public Enumeration getJMSXPropertyNames() throws JMSException
- {
- return CustomJMSXProperty.asEnumeration();
- }
-
- public int getProviderMajorVersion() throws JMSException
- {
- return 0;
- }
-
- public int getProviderMinorVersion() throws JMSException
- {
- return 8;
- }
-
- public String getProviderVersion() throws JMSException
- {
- return QpidProperties.getProductName() + " (Client: [" + getClientVersion() + "] ; Broker [" + getBrokerVersion() + "] ; Protocol: [ "
- + getProtocolVersion() + "] )";
- }
-
- private String getProtocolVersion()
- {
- // TODO - Implement based on connection negotiated protocol
- return "0.8";
- }
-
- public String getBrokerVersion()
- {
- // TODO - get broker version
- return "<unkown>";
- }
-
- public String getClientVersion()
- {
- return QpidProperties.getBuildVersion();
- }
-
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/QueueReceiverAdaptor.java b/java/client/src/main/java/org/apache/qpid/client/QueueReceiverAdaptor.java
deleted file mode 100644
index 7059588367..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/QueueReceiverAdaptor.java
+++ /dev/null
@@ -1,115 +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.client;
-
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageListener;
-import javax.jms.Queue;
-import javax.jms.QueueReceiver;
-
-/**
- * Class that wraps a MessageConsumer for backwards JMS compatibility
- * Returned by methods in AMQSession etc
- */
-public class QueueReceiverAdaptor implements QueueReceiver {
-
- protected MessageConsumer _consumer;
- protected Queue _queue;
-
- protected QueueReceiverAdaptor(Queue queue, MessageConsumer consumer)
- {
- _consumer = consumer;
- _queue = queue;
- }
-
- public String getMessageSelector() throws JMSException
- {
- checkPreConditions();
- return _consumer.getMessageSelector();
- }
-
- public MessageListener getMessageListener() throws JMSException
- {
- checkPreConditions();
- return _consumer.getMessageListener();
- }
-
- public void setMessageListener(MessageListener messageListener) throws JMSException
- {
- checkPreConditions();
- _consumer.setMessageListener(messageListener);
- }
-
- public Message receive() throws JMSException
- {
- checkPreConditions();
- return _consumer.receive();
- }
-
- public Message receive(long l) throws JMSException
- {
- checkPreConditions();
- return _consumer.receive(l);
- }
-
- public Message receiveNoWait() throws JMSException
- {
- checkPreConditions();
- return _consumer.receiveNoWait();
- }
-
- public void close() throws JMSException
- {
- _consumer.close();
- }
-
- /**
- * Return the queue associated with this receiver
- * @return
- * @throws JMSException
- */
- public Queue getQueue() throws JMSException
- {
- checkPreConditions();
- return _queue;
- }
-
- private void checkPreConditions() throws javax.jms.IllegalStateException {
- BasicMessageConsumer msgConsumer = (BasicMessageConsumer)_consumer;
-
- if (msgConsumer.isClosed() ){
- throw new javax.jms.IllegalStateException("Consumer is closed");
- }
-
- if(_queue == null){
- throw new UnsupportedOperationException("Queue is null");
- }
-
- AMQSession session = msgConsumer.getSession();
-
- if(session == null || session.isClosed()){
- throw new javax.jms.IllegalStateException("Invalid Session");
- }
- }
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/QueueSenderAdapter.java b/java/client/src/main/java/org/apache/qpid/client/QueueSenderAdapter.java
deleted file mode 100644
index 295c6a4091..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/QueueSenderAdapter.java
+++ /dev/null
@@ -1,227 +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.client;
-
-import javax.jms.Destination;
-import javax.jms.InvalidDestinationException;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.Queue;
-import javax.jms.QueueSender;
-
-public class QueueSenderAdapter implements QueueSender
-{
-
- private BasicMessageProducer _delegate;
- private Queue _queue;
- private boolean closed = false;
-
- public QueueSenderAdapter(BasicMessageProducer msgProducer, Queue queue)
- {
- _delegate = msgProducer;
- _queue = queue;
- }
-
- public Queue getQueue() throws JMSException
- {
- checkPreConditions();
-
- return _queue;
- }
-
- public void send(Message msg) throws JMSException
- {
- checkQueuePreConditions(_queue);
- _delegate.send(msg);
- }
-
- public void send(Queue queue, Message msg) throws JMSException
- {
- checkQueuePreConditions(queue);
- _delegate.send(queue, msg);
- }
-
- public void publish(Message msg, int deliveryMode, int priority, long timeToLive) throws JMSException
- {
- checkQueuePreConditions(_queue);
- _delegate.send(msg, deliveryMode, priority, timeToLive);
- }
-
- public void send(Queue queue, Message msg, int deliveryMode, int priority, long timeToLive) throws JMSException
- {
- checkQueuePreConditions(queue);
- _delegate.send(queue, msg, deliveryMode, priority, timeToLive);
- }
-
- public void close() throws JMSException
- {
- _delegate.close();
- closed = true;
- }
-
- public int getDeliveryMode() throws JMSException
- {
- checkPreConditions();
-
- return _delegate.getDeliveryMode();
- }
-
- public Destination getDestination() throws JMSException
- {
- checkPreConditions();
-
- return _delegate.getDestination();
- }
-
- public boolean getDisableMessageID() throws JMSException
- {
- checkPreConditions();
-
- return _delegate.getDisableMessageID();
- }
-
- public boolean getDisableMessageTimestamp() throws JMSException
- {
- checkPreConditions();
-
- return _delegate.getDisableMessageTimestamp();
- }
-
- public int getPriority() throws JMSException
- {
- checkPreConditions();
-
- return _delegate.getPriority();
- }
-
- public long getTimeToLive() throws JMSException
- {
- checkPreConditions();
-
- return _delegate.getTimeToLive();
- }
-
- public void send(Destination dest, Message msg) throws JMSException
- {
- checkQueuePreConditions((Queue) dest);
- _delegate.send(dest, msg);
- }
-
- public void send(Message msg, int deliveryMode, int priority, long timeToLive) throws JMSException
- {
- checkQueuePreConditions(_queue);
- _delegate.send(msg, deliveryMode, priority, timeToLive);
- }
-
- public void send(Destination dest, Message msg, int deliveryMode, int priority, long timeToLive) throws JMSException
- {
- checkQueuePreConditions((Queue) dest);
- _delegate.send(dest, msg, deliveryMode, priority, timeToLive);
- }
-
- public void setDeliveryMode(int deliveryMode) throws JMSException
- {
- checkPreConditions();
- _delegate.setDeliveryMode(deliveryMode);
- }
-
- public void setDisableMessageID(boolean disableMessageID) throws JMSException
- {
- checkPreConditions();
- _delegate.setDisableMessageID(disableMessageID);
- }
-
- public void setDisableMessageTimestamp(boolean disableMessageTimestamp) throws JMSException
- {
- checkPreConditions();
- _delegate.setDisableMessageTimestamp(disableMessageTimestamp);
- }
-
- public void setPriority(int priority) throws JMSException
- {
- checkPreConditions();
- _delegate.setPriority(priority);
- }
-
- public void setTimeToLive(long timeToLive) throws JMSException
- {
- checkPreConditions();
- _delegate.setTimeToLive(timeToLive);
- }
-
- private void checkPreConditions() throws JMSException
- {
- if (closed)
- {
- throw new javax.jms.IllegalStateException("Publisher is closed");
- }
-
- AMQSession session = ((BasicMessageProducer) _delegate).getSession();
-
- if ((session == null) || session.isClosed())
- {
- throw new javax.jms.IllegalStateException("Invalid Session");
- }
- }
-
- private void checkQueuePreConditions(Queue queue) throws JMSException
- {
- checkPreConditions() ;
-
- if (queue == null)
- {
- throw new UnsupportedOperationException("Queue is null.");
- }
-
- if (!(queue instanceof AMQDestination))
- {
- throw new InvalidDestinationException("Queue: " + queue + " is not a valid Qpid queue");
- }
-
- AMQDestination destination = (AMQDestination) queue;
- if (!destination.isCheckedForQueueBinding() && checkQueueBeforePublish())
- {
- if (_delegate.getSession().isStrictAMQP())
- {
- _delegate._logger.warn("AMQP does not support destination validation before publish, ");
- destination.setCheckedForQueueBinding(true);
- }
- else
- {
- if (_delegate.isBound(destination))
- {
- destination.setCheckedForQueueBinding(true);
- }
- else
- {
- throw new InvalidDestinationException("Queue: " + queue
- + " is not a valid destination (no bindings on server");
- }
- }
- }
- }
-
- private boolean checkQueueBeforePublish()
- {
- return "true".equalsIgnoreCase(System.getProperty("org.apache.qpid.client.verifyQueueBindingBeforePublish", "true"));
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/SSLConfiguration.java b/java/client/src/main/java/org/apache/qpid/client/SSLConfiguration.java
deleted file mode 100644
index 2280cc9870..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/SSLConfiguration.java
+++ /dev/null
@@ -1,61 +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.client;
-
-public class SSLConfiguration {
-
- private String _keystorePath;
-
- private String _keystorePassword;
-
- private String _certType = "SunX509";
-
- public void setKeystorePath(String path)
- {
- _keystorePath = path;
- }
-
- public String getKeystorePath()
- {
- return _keystorePath;
- }
-
- public void setKeystorePassword(String password)
- {
- _keystorePassword = password;
- }
-
- public String getKeystorePassword()
- {
- return _keystorePassword;
- }
-
- public void setCertType(String type)
- {
- _certType = type;
- }
-
- public String getCertType()
- {
- return _certType;
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/TemporaryDestination.java b/java/client/src/main/java/org/apache/qpid/client/TemporaryDestination.java
deleted file mode 100644
index 7f8e80c73a..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/TemporaryDestination.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.client;
-
-import javax.jms.Destination;
-import javax.jms.JMSException;
-
-/**
- * Provides support for covenience interface implemented by both AMQTemporaryTopic and AMQTemporaryQueue
- * so that operations related to their "temporary-ness" can be abstracted out.
- */
-interface TemporaryDestination extends Destination
-{
-
- public void delete() throws JMSException;
- public AMQSession getSession();
- public boolean isDeleted();
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/TopicPublisherAdapter.java b/java/client/src/main/java/org/apache/qpid/client/TopicPublisherAdapter.java
deleted file mode 100644
index 81b9940ed5..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/TopicPublisherAdapter.java
+++ /dev/null
@@ -1,205 +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.client;
-
-import javax.jms.Destination;
-import javax.jms.IllegalStateException;
-import javax.jms.InvalidDestinationException;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.Topic;
-import javax.jms.TopicPublisher;
-
-public class TopicPublisherAdapter implements TopicPublisher
-{
-
- private BasicMessageProducer _delegate;
- private Topic _topic;
-
- public TopicPublisherAdapter(BasicMessageProducer msgProducer, Topic topic)
- {
- _delegate = msgProducer;
- _topic = topic;
- }
-
- public Topic getTopic() throws JMSException
- {
- checkPreConditions();
- return _topic;
- }
-
- public void publish(Message msg) throws JMSException
- {
- checkPreConditions();
- checkTopic(_topic);
- _delegate.send(msg);
- }
-
- public void publish(Topic topic, Message msg) throws JMSException
- {
- checkPreConditions();
- checkTopic(topic);
- _delegate.send(topic, msg);
- }
-
- public void publish(Message msg, int deliveryMode, int priority, long timeToLive)
- throws JMSException
- {
- checkPreConditions();
- checkTopic(_topic);
- _delegate.send(msg, deliveryMode, priority, timeToLive);
- }
-
- public int getDeliveryMode() throws JMSException {
- checkPreConditions();
- return _delegate.getDeliveryMode();
- }
-
- public void publish(Topic topic, Message msg, int deliveryMode, int priority, long timeToLive)
- throws JMSException
- {
- checkPreConditions();
- checkTopic(topic);
- _delegate.send(topic, msg, deliveryMode, priority, timeToLive);
- }
-
- public void close() throws JMSException
- {
- _delegate.close();
- }
-
- public boolean getDisableMessageID() throws JMSException {
- checkPreConditions();
- return _delegate.getDisableMessageID();
- }
-
- public boolean getDisableMessageTimestamp() throws JMSException {
- checkPreConditions();
- return _delegate.getDisableMessageTimestamp();
- }
-
- public Destination getDestination() throws JMSException
- {
- checkPreConditions();
- return _delegate.getDestination();
- }
-
- public int getPriority() throws JMSException {
- checkPreConditions();
- return _delegate.getPriority();
- }
-
- public long getTimeToLive() throws JMSException {
- checkPreConditions();
- return _delegate.getTimeToLive();
- }
-
- public void send(Message msg) throws JMSException
- {
- checkPreConditions();
- checkTopic(_topic);
- _delegate.send(msg);
- }
-
- public void send(Destination dest, Message msg) throws JMSException
- {
- checkPreConditions();
- checkTopic(_topic);
- _delegate.send(dest, msg);
- }
-
- public void send(Message msg, int deliveryMode, int priority, long timeToLive)
- throws JMSException
- {
- checkPreConditions();
- checkTopic(_topic);
- _delegate.send(msg, deliveryMode, priority, timeToLive);
- }
-
- public void send(Destination dest, Message msg, int deliveryMode, int priority, long timeToLive) throws JMSException
- {
- checkPreConditions();
- checkTopic(dest);
- _delegate.send(dest, msg, deliveryMode, priority, timeToLive);
- }
-
- public void setDeliveryMode(int deliveryMode) throws JMSException
- {
- checkPreConditions();
- _delegate.setDeliveryMode(deliveryMode);
- }
-
- public void setDisableMessageID(boolean disableMessageID) throws JMSException
- {
- checkPreConditions();
- _delegate.setDisableMessageID(disableMessageID);
- }
-
- public void setDisableMessageTimestamp(boolean disableMessageTimestamp) throws JMSException
- {
- checkPreConditions();
- _delegate.setDisableMessageTimestamp(disableMessageTimestamp);
- }
-
- public void setPriority(int priority) throws JMSException
- {
- checkPreConditions();
- _delegate.setPriority(priority);
- }
-
- public void setTimeToLive(long timeToLive) throws JMSException
- {
- checkPreConditions();
- _delegate.setTimeToLive(timeToLive);
- }
-
- private void checkPreConditions() throws IllegalStateException
- {
- if (_delegate.isClosed())
- {
- throw new javax.jms.IllegalStateException("Publisher is _closed");
- }
-
- AMQSession session = _delegate.getSession();
- if (session == null || session.isClosed())
- {
- throw new javax.jms.IllegalStateException("Invalid Session");
- }
- }
-
- private void checkTopic(Destination topic) throws InvalidDestinationException
- {
- if (topic == null)
- {
- throw new UnsupportedOperationException("Topic is null");
- }
- if (!(topic instanceof Topic))
- {
- throw new InvalidDestinationException("Destination " + topic + " is not a topic");
- }
- if(!(topic instanceof AMQDestination))
- {
- throw new InvalidDestinationException("Destination " + topic + " is not a Qpid topic");
- }
-
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/TopicSubscriberAdaptor.java b/java/client/src/main/java/org/apache/qpid/client/TopicSubscriberAdaptor.java
deleted file mode 100644
index 9bdef22f96..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/TopicSubscriberAdaptor.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.client;
-
-import org.apache.qpid.AMQException;
-
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageListener;
-import javax.jms.Topic;
-import javax.jms.TopicSubscriber;
-
-/**
- * Wraps a MessageConsumer to fulfill the extended TopicSubscriber contract
- *
- */
-class TopicSubscriberAdaptor<C extends BasicMessageConsumer> implements TopicSubscriber
-{
- private final Topic _topic;
- private final C _consumer;
- private final boolean _noLocal;
-
- TopicSubscriberAdaptor(Topic topic, C consumer, boolean noLocal)
- {
- _topic = topic;
- _consumer = consumer;
- _noLocal = noLocal;
- }
-
- TopicSubscriberAdaptor(Topic topic, C consumer)
- {
- this(topic, consumer, consumer.isNoLocal());
- }
-
- public Topic getTopic() throws JMSException
- {
- checkPreConditions();
- return _topic;
- }
-
- public boolean getNoLocal() throws JMSException
- {
- checkPreConditions();
- return _noLocal;
- }
-
- public String getMessageSelector() throws JMSException
- {
- checkPreConditions();
- return _consumer.getMessageSelector();
- }
-
- public MessageListener getMessageListener() throws JMSException
- {
- checkPreConditions();
- return _consumer.getMessageListener();
- }
-
- public void setMessageListener(MessageListener messageListener) throws JMSException
- {
- checkPreConditions();
- _consumer.setMessageListener(messageListener);
- }
-
- public Message receive() throws JMSException
- {
- checkPreConditions();
- return _consumer.receive();
- }
-
- public Message receive(long l) throws JMSException
- {
- return _consumer.receive(l);
- }
-
- public Message receiveNoWait() throws JMSException
- {
- checkPreConditions();
- return _consumer.receiveNoWait();
- }
-
- public void close() throws JMSException
- {
- _consumer.close();
- }
-
- private void checkPreConditions() throws javax.jms.IllegalStateException{
- C msgConsumer = _consumer;
-
- if (msgConsumer.isClosed() ){
- throw new javax.jms.IllegalStateException("Consumer is closed");
- }
-
- if(_topic == null){
- throw new UnsupportedOperationException("Topic is null");
- }
-
- AMQSession session = msgConsumer.getSession();
-
- if(session == null || session.isClosed()){
- throw new javax.jms.IllegalStateException("Invalid Session");
- }
- }
-
- C getMessageConsumer()
- {
- return _consumer;
- }
-
- public void addBindingKey(Topic topic, String bindingKey) throws AMQException
- {
- _consumer.addBindingKey((AMQDestination) topic, bindingKey);
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/XAConnectionImpl.java b/java/client/src/main/java/org/apache/qpid/client/XAConnectionImpl.java
deleted file mode 100644
index 43025bd724..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/XAConnectionImpl.java
+++ /dev/null
@@ -1,78 +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.client;
-
-import org.apache.qpid.jms.ConnectionURL;
-import org.apache.qpid.AMQException;
-
-import javax.jms.*;
-
-/**
- * This class implements the javax.njms.XAConnection interface
- */
-public class XAConnectionImpl extends AMQConnection implements XAConnection, XAQueueConnection, XATopicConnection
-{
- //-- constructor
- /**
- * Create a XAConnection from a connectionURL
- */
- public XAConnectionImpl(ConnectionURL connectionURL, SSLConfiguration sslConfig) throws AMQException
- {
- super(connectionURL, sslConfig);
- }
-
- //-- interface XAConnection
- /**
- * Creates an XASession.
- *
- * @return A newly created XASession.
- * @throws JMSException If the XAConnectiono fails to create an XASession due to
- * some internal error.
- */
- public synchronized XASession createXASession() throws JMSException
- {
- checkNotClosed();
- return _delegate.createXASession();
- }
-
- //-- Interface XAQueueConnection
- /**
- * Creates an XAQueueSession.
- *
- * @return A newly created XASession.
- * @throws JMSException If the XAQueueConnectionImpl fails to create an XASession due to
- * some internal error.
- */
- public XAQueueSession createXAQueueSession() throws JMSException
- {
- return (XAQueueSession) createXASession();
- }
-
- //-- Interface XATopicConnection
- /**
- * Creates an XAQueueSession.
- *
- * @return A newly created XASession.
- * @throws JMSException If the XAQueueConnectionImpl fails to create an XASession due to
- * some internal error.
- */
- public XATopicSession createXATopicSession() throws JMSException
- {
- return (XATopicSession) createXASession();
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/XAResourceImpl.java b/java/client/src/main/java/org/apache/qpid/client/XAResourceImpl.java
deleted file mode 100644
index 8a75082202..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/XAResourceImpl.java
+++ /dev/null
@@ -1,522 +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.client;
-
-import javax.transaction.xa.XAException;
-import javax.transaction.xa.XAResource;
-import javax.transaction.xa.Xid;
-
-import org.apache.qpid.AMQInvalidArgumentException;
-import org.apache.qpid.dtx.XidImpl;
-import org.apache.qpid.transport.*;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * This is an implementation of javax.njms.XAResource.
- */
-public class XAResourceImpl implements XAResource
-{
- /**
- * this XAResourceImpl's logger
- */
- private static final Logger _logger = LoggerFactory.getLogger(XAResourceImpl.class);
-
- /**
- * Reference to the associated XASession
- */
- private XASessionImpl _xaSession = null;
-
- /**
- * The XID of this resource
- */
- private Xid _xid;
-
- /**
- * The time for this resource
- */
- private int _timeout;
-
- //--- constructor
-
- /**
- * Create an XAResource associated with a XASession
- *
- * @param xaSession The session XAresource
- */
- protected XAResourceImpl(XASessionImpl xaSession)
- {
- _xaSession = xaSession;
- }
-
- //--- The XAResource
- /**
- * Commits the global transaction specified by xid.
- *
- * @param xid A global transaction identifier
- * @param b If true, use a one-phase commit protocol to commit the work done on behalf of xid.
- * @throws XAException An error has occurred. An error has occurred. Possible XAExceptions are XA_HEURHAZ,
- * XA_HEURCOM, XA_HEURRB, XA_HEURMIX, XAER_RMERR, XAER_RMFAIL, XAER_NOTA, XAER_INVAL, or XAER_PROTO.
- */
- public void commit(Xid xid, boolean b) throws XAException
- {
- if (_logger.isDebugEnabled())
- {
- _logger.debug("commit tx branch with xid: ", xid);
- }
- Future<XaResult> future =
- _xaSession.getQpidSession().dtxCommit(convertXid(xid), b ? Option.ONE_PHASE : Option.NONE);
-
- // now wait on the future for the result
- XaResult result = null;
- try
- {
- result = future.get();
- }
- catch (SessionException e)
- {
- // we need to restore the qpid session that has been closed
- _xaSession.createSession();
- convertExecutionErrorToXAErr(e.getException().getErrorCode());
- }
- finally
- {
- _xid = null;
- }
- checkStatus(result.getStatus());
- }
-
- /**
- * Ends the work performed on behalf of a transaction branch.
- * The resource manager disassociates the XA resource from the transaction branch specified
- * and lets the transaction complete.
- * <ul>
- * <li> If TMSUSPEND is specified in the flags, the transaction branch is temporarily suspended in an incomplete state.
- * The transaction context is in a suspended state and must be resumed via the start method with TMRESUME specified.
- * <li> If TMFAIL is specified, the portion of work has failed. The resource manager may mark the transaction as rollback-only
- * <li> If TMSUCCESS is specified, the portion of work has completed successfully.
- * /ul>
- *
- * @param xid A global transaction identifier that is the same as the identifier used previously in the start method
- * @param flag One of TMSUCCESS, TMFAIL, or TMSUSPEND.
- * @throws XAException An error has occurred. An error has occurred. Possible XAException values are XAER_RMERR,
- * XAER_RMFAILED, XAER_NOTA, XAER_INVAL, XAER_PROTO, or XA_RB*.
- */
- public void end(Xid xid, int flag) throws XAException
- {
- if (_logger.isDebugEnabled())
- {
- _logger.debug("end tx branch with xid: ", xid);
- }
- switch (flag)
- {
- case(XAResource.TMSUCCESS):
- break;
- case(XAResource.TMFAIL):
- break;
- case(XAResource.TMSUSPEND):
- break;
- default:
- throw new XAException(XAException.XAER_INVAL);
- }
- _xaSession.flushAcknowledgments();
- Future<XaResult> future = _xaSession.getQpidSession()
- .dtxEnd(convertXid(xid),
- flag == XAResource.TMFAIL ? Option.FAIL : Option.NONE,
- flag == XAResource.TMSUSPEND ? Option.SUSPEND : Option.NONE);
- // now wait on the future for the result
- XaResult result = null;
- try
- {
- result = future.get();
- }
- catch (SessionException e)
- {
- // we need to restore the qpid session that has been closed
- _xaSession.createSession();
- convertExecutionErrorToXAErr(e.getException().getErrorCode());
- }
- checkStatus(result.getStatus());
- }
-
-
- /**
- * Tells the resource manager to forget about a heuristically completed transaction branch.
- *
- * @param xid String(xid.getGlobalTransactionId() A global transaction identifier
- * @throws XAException An error has occurred. Possible exception values are XAER_RMERR, XAER_RMFAIL,
- * XAER_NOTA, XAER_INVAL, or XAER_PROTO.
- */
- public void forget(Xid xid) throws XAException
- {
- if (_logger.isDebugEnabled())
- {
- _logger.debug("forget tx branch with xid: ", xid);
- }
- _xaSession.getQpidSession().dtxForget(convertXid(xid));
- try
- {
- _xaSession.getQpidSession().sync();
- }
- catch (SessionException e)
- {
- // we need to restore the qpid session that has been closed
- _xaSession.createSession();
- convertExecutionErrorToXAErr(e.getException().getErrorCode());
- }
- finally
- {
- _xid = null;
- }
- }
-
-
- /**
- * Obtains the current transaction timeout value set for this XAResource instance.
- * If XAResource.setTransactionTimeout was not used prior to invoking this method,
- * the return value is the default timeout i.e. 0;
- *
- * @return The transaction timeout value in seconds.
- * @throws XAException An error has occurred. Possible exception values are XAER_RMERR, XAER_RMFAIL.
- */
- public int getTransactionTimeout() throws XAException
- {
- return _timeout;
- }
-
- /**
- * This method is called to determine if the resource manager instance represented
- * by the target object is the same as the resouce manager instance represented by
- * the parameter xaResource.
- *
- * @param xaResource An XAResource object whose resource manager instance is to
- * be compared with the resource manager instance of the target object
- * @return <code>true</code> if it's the same RM instance; otherwise <code>false</code>.
- * @throws XAException An error has occurred. Possible exception values are XAER_RMERR, XAER_RMFAIL.
- */
- public boolean isSameRM(XAResource xaResource) throws XAException
- {
- // TODO : get the server identity of xaResource and compare it with our own one
- return false;
- }
-
- /**
- * Prepare for a transaction commit of the transaction specified in <code>Xid</code>.
- *
- * @param xid A global transaction identifier.
- * @return A value indicating the resource manager's vote on the outcome of the transaction.
- * The possible values are: XA_RDONLY or XA_OK.
- * @throws XAException An error has occurred. Possible exception values are: XAER_RMERR or XAER_NOTA
- */
- public int prepare(Xid xid) throws XAException
- {
- if (_logger.isDebugEnabled())
- {
- _logger.debug("prepare ", xid);
- }
- Future<XaResult> future = _xaSession.getQpidSession().dtxPrepare(convertXid(xid));
- XaResult result = null;
- try
- {
- result = future.get();
- }
- catch (SessionException e)
- {
- // we need to restore the qpid session that has been closed
- _xaSession.createSession();
- convertExecutionErrorToXAErr(e.getException().getErrorCode());
- }
- DtxXaStatus status = result.getStatus();
- int outcome = XAResource.XA_OK;
- switch (status)
- {
- case XA_OK:
- break;
- case XA_RDONLY:
- outcome = XAResource.XA_RDONLY;
- break;
- default:
- checkStatus(status);
- }
- return outcome;
- }
-
- /**
- * Obtains a list of prepared transaction branches.
- * <p/>
- * The transaction manager calls this method during recovery to obtain the list of transaction branches
- * that are currently in prepared or heuristically completed states.
- *
- * @param flag One of TMSTARTRSCAN, TMENDRSCAN, TMNOFLAGS.
- * TMNOFLAGS must be used when no other flags are set in the parameter.
- * @return zero or more XIDs of the transaction branches that are currently in a prepared or heuristically
- * completed state.
- * @throws XAException An error has occurred. Possible value is XAER_INVAL.
- */
- public Xid[] recover(int flag) throws XAException
- {
- // the flag is ignored
- Future<RecoverResult> future = _xaSession.getQpidSession().dtxRecover();
- RecoverResult res = null;
- try
- {
- res = future.get();
- }
- catch (SessionException e)
- {
- // we need to restore the qpid session that has been closed
- _xaSession.createSession();
- convertExecutionErrorToXAErr( e.getException().getErrorCode());
- }
- Xid[] result = new Xid[res.getInDoubt().size()];
- int i = 0;
- for (Object obj : res.getInDoubt())
- {
- org.apache.qpid.transport.Xid xid = (org.apache.qpid.transport.Xid) obj;
- result[i] = new XidImpl(xid.getBranchId(), (int) xid.getFormat(), xid.getGlobalId());
- i++;
- }
- return result;
- }
-
- /**
- * Informs the resource manager to roll back work done on behalf of a transaction branch
- *
- * @param xid A global transaction identifier.
- * @throws XAException An error has occurred.
- */
- public void rollback(Xid xid) throws XAException
- {
- if (_logger.isDebugEnabled())
- {
- _logger.debug("rollback tx branch with xid: ", xid);
- }
-
- Future<XaResult> future = _xaSession.getQpidSession().dtxRollback(convertXid(xid));
- // now wait on the future for the result
- XaResult result = null;
- try
- {
- result = future.get();
- }
- catch (SessionException e)
- {
- // we need to restore the qpid session that has been closed
- _xaSession.createSession();
- convertExecutionErrorToXAErr( e.getException().getErrorCode());
- }
- finally
- {
- _xid = null;
- }
- checkStatus(result.getStatus());
- }
-
- /**
- * Sets the current transaction timeout value for this XAResource instance.
- * Once set, this timeout value is effective until setTransactionTimeout is
- * invoked again with a different value.
- * To reset the timeout value to the default value used by the resource manager, set the value to zero.
- *
- * @param timeout The transaction timeout value in seconds.
- * @return true if transaction timeout value is set successfully; otherwise false.
- * @throws XAException An error has occurred. Possible exception values are XAER_RMERR, XAER_RMFAIL, or XAER_INVAL.
- */
- public boolean setTransactionTimeout(int timeout) throws XAException
- {
- _timeout = timeout;
- if (timeout != _timeout && _xid != null)
- {
- setDtxTimeout(_timeout);
- }
- return true;
- }
-
- private void setDtxTimeout(int timeout) throws XAException
- {
- _xaSession.getQpidSession()
- .dtxSetTimeout(XidImpl.convert(_xid), timeout);
- }
-
- /**
- * Starts work on behalf of a transaction branch specified in xid.
- * <ul>
- * <li> If TMJOIN is specified, an exception is thrown as it is not supported
- * <li> If TMRESUME is specified, the start applies to resuming a suspended transaction specified in the parameter xid.
- * <li> If neither TMJOIN nor TMRESUME is specified and the transaction specified by xid has previously been seen by the
- * resource manager, the resource manager throws the XAException exception with XAER_DUPID error code.
- * </ul>
- *
- * @param xid A global transaction identifier to be associated with the resource
- * @param flag One of TMNOFLAGS, TMJOIN, or TMRESUME
- * @throws XAException An error has occurred. Possible exceptions
- * are XA_RB*, XAER_RMERR, XAER_RMFAIL, XAER_DUPID, XAER_OUTSIDE, XAER_NOTA, XAER_INVAL, or XAER_PROTO.
- */
- public void start(Xid xid, int flag) throws XAException
- {
- if (_logger.isDebugEnabled())
- {
- _logger.debug("start tx branch with xid: ", xid);
- }
- switch (flag)
- {
- case(XAResource.TMNOFLAGS):
- break;
- case(XAResource.TMJOIN):
- break;
- case(XAResource.TMRESUME):
- break;
- default:
- throw new XAException(XAException.XAER_INVAL);
- }
- Future<XaResult> future = _xaSession.getQpidSession()
- .dtxStart(convertXid(xid),
- flag == XAResource.TMJOIN ? Option.JOIN : Option.NONE,
- flag == XAResource.TMRESUME ? Option.RESUME : Option.NONE);
- // now wait on the future for the result
- XaResult result = null;
- try
- {
- result = future.get();
- }
- catch (SessionException e)
- {
- // we need to restore the qpid session that has been closed
- _xaSession.createSession();
- convertExecutionErrorToXAErr(e.getException().getErrorCode());
- // TODO: The amqp spec does not allow to make the difference
- // between an already known XID and a wrong arguments (join and resume are set)
- // TODO: make sure amqp addresses that
- }
- checkStatus(result.getStatus());
- _xid = xid;
- if (_timeout > 0)
- {
- setDtxTimeout(_timeout);
- }
- }
-
- //------------------------------------------------------------------------
- // Private methods
- //------------------------------------------------------------------------
-
- /**
- * Check xa method outcome and, when required, convert the status into the corresponding xa exception
- * @param status method status code
- * @throws XAException corresponding XA Exception when required
- */
- private void checkStatus(DtxXaStatus status) throws XAException
- {
- switch (status)
- {
- case XA_OK:
- // Do nothing this ok
- break;
- case XA_RBROLLBACK:
- // The tx has been rolled back for an unspecified reason.
- throw new XAException(XAException.XA_RBROLLBACK);
- case XA_RBTIMEOUT:
- // The transaction branch took too long.
- throw new XAException(XAException.XA_RBTIMEOUT);
- case XA_HEURHAZ:
- // The transaction branch may have been heuristically completed.
- throw new XAException(XAException.XA_HEURHAZ);
- case XA_HEURCOM:
- // The transaction branch has been heuristically committed.
- throw new XAException(XAException.XA_HEURCOM);
- case XA_HEURRB:
- // The transaction branch has been heuristically rolled back.
- throw new XAException(XAException.XA_HEURRB);
- case XA_HEURMIX:
- // The transaction branch has been heuristically committed and rolled back.
- throw new XAException(XAException.XA_HEURMIX);
- case XA_RDONLY:
- // The transaction branch was read-only and has been committed.
- throw new XAException(XAException.XA_RDONLY);
- default:
- // this should not happen
- if (_logger.isDebugEnabled())
- {
- _logger.debug("got unexpected status value: ", status);
- }
- //A resource manager error has occured in the transaction branch.
- throw new XAException(XAException.XAER_RMERR);
- }
- }
-
- /**
- * Convert execution error to xa exception.
- * @param error the execution error code
- * @throws XAException
- */
- private void convertExecutionErrorToXAErr(ExecutionErrorCode error) throws XAException
- {
- switch (error)
- {
- case NOT_ALLOWED:
- // The XID already exists.
- throw new XAException(XAException.XAER_DUPID);
- case NOT_FOUND:
- // The XID is not valid.
- try
- {
- throw new XAException(XAException.XAER_NOTA);
- }
- catch (XAException e)
- {
- e.printStackTrace();
- throw e;
- }
- case ILLEGAL_STATE:
- // Routine was invoked in an inproper context.
- throw new XAException(XAException.XAER_PROTO);
- case NOT_IMPLEMENTED:
- // the command is not implemented
- throw new XAException(XAException.XAER_RMERR);
- case COMMAND_INVALID:
- // Invalid call
- throw new XAException(XAException.XAER_INVAL);
- default:
- // this should not happen
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Got unexpected error: " + error);
- }
- //A resource manager error has occured in the transaction branch.
- throw new XAException(XAException.XAER_RMERR);
- }
- }
-
- /**
- * convert a generic xid into qpid format
- * @param xid xid to be converted
- * @return the qpid formated xid
- * @throws XAException when xid is null
- */
- private org.apache.qpid.transport.Xid convertXid(Xid xid) throws XAException
- {
- if (xid == null)
- {
- // Invalid arguments were given.
- throw new XAException(XAException.XAER_INVAL);
- }
- return XidImpl.convert(xid);
- }
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/XASessionImpl.java b/java/client/src/main/java/org/apache/qpid/client/XASessionImpl.java
deleted file mode 100644
index 354b67cd35..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/XASessionImpl.java
+++ /dev/null
@@ -1,159 +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.client;
-
-import org.apache.qpid.client.message.MessageFactoryRegistry;
-
-import javax.jms.*;
-import javax.transaction.xa.XAResource;
-
-/**
- * This is an implementation of the javax.njms.XASEssion interface.
- */
-public class XASessionImpl extends AMQSession_0_10 implements XASession, XATopicSession, XAQueueSession
-{
- /**
- * XAResource associated with this XASession
- */
- private final XAResourceImpl _xaResource;
-
- /**
- * This XASession Qpid DtxSession
- */
- private org.apache.qpid.transport.Session _qpidDtxSession;
-
- /**
- * The standard session
- */
- private Session _jmsSession;
-
-
- //-- Constructors
- /**
- * Create a JMS XASession
- */
- public XASessionImpl(org.apache.qpid.transport.Connection qpidConnection, AMQConnection con, int channelId,
- int defaultPrefetchHigh, int defaultPrefetchLow)
- {
- super(qpidConnection, con, channelId, false, // this is not a transacted session
- Session.AUTO_ACKNOWLEDGE, // the ack mode is transacted
- MessageFactoryRegistry.newDefaultRegistry(), defaultPrefetchHigh, defaultPrefetchLow);
- createSession();
- _xaResource = new XAResourceImpl(this);
- }
-
- //-- public methods
-
- /**
- * Create a qpid session.
- */
- public void createSession()
- {
- _qpidDtxSession = _qpidConnection.createSession(0);
- _qpidDtxSession.setSessionListener(this);
- _qpidDtxSession.dtxSelect();
- }
-
-
- //--- javax.njms.XASEssion API
-
- /**
- * Gets the session associated with this XASession.
- *
- * @return The session object.
- * @throws JMSException if an internal error occurs.
- */
- public Session getSession() throws JMSException
- {
- if (_jmsSession == null)
- {
- _jmsSession = getAMQConnection().createSession(true, getAcknowledgeMode());
- }
- return _jmsSession;
- }
-
- /**
- * Returns an XA resource.
- *
- * @return An XA resource.
- */
- public XAResource getXAResource()
- {
- return _xaResource;
- }
-
- //-- overwritten mehtods
- /**
- * Throws a {@link TransactionInProgressException}, since it should
- * not be called for an XASession object.
- *
- * @throws TransactionInProgressException always.
- */
- public void commit() throws JMSException
- {
- throw new TransactionInProgressException(
- "XASession: A direct invocation of the commit operation is probibited!");
- }
-
- /**
- * Throws a {@link TransactionInProgressException}, since it should
- * not be called for an XASession object.
- *
- * @throws TransactionInProgressException always.
- */
- public void rollback() throws JMSException
- {
- throw new TransactionInProgressException(
- "XASession: A direct invocation of the rollback operation is probibited!");
- }
-
- /**
- * Access to the underlying Qpid Session
- *
- * @return The associated Qpid Session.
- */
- protected org.apache.qpid.transport.Session getQpidSession()
- {
- return _qpidDtxSession;
- }
-
- //--- interface XAQueueSession
- /**
- * Gets the topic session associated with this <CODE>XATopicSession</CODE>.
- *
- * @return the topic session object
- * @throws JMSException If an internal error occurs.
- */
- public QueueSession getQueueSession() throws JMSException
- {
- return (QueueSession) getSession();
- }
-
- //--- interface XATopicSession
-
- /**
- * Gets the topic session associated with this <CODE>XATopicSession</CODE>.
- *
- * @return the topic session object
- * @throws JMSException If an internal error occurs.
- */
- public TopicSession getTopicSession() throws JMSException
- {
- return (TopicSession) getSession();
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/failover/FailoverException.java b/java/client/src/main/java/org/apache/qpid/client/failover/FailoverException.java
deleted file mode 100644
index 037b0dc2d1..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/failover/FailoverException.java
+++ /dev/null
@@ -1,49 +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.client.failover;
-
-/**
- * FailoverException is used to indicate that a synchronous request has failed to receive the reply that it is waiting
- * for because the fail-over process has been started whilst it was waiting for its reply. Synchronous methods generally
- * raise this exception to indicate that they must be re-tried once the fail-over process has completed.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Used to indicate failure of a synchronous request due to fail-over.
- * </table>
- *
- * @todo This exception is created and passed as an argument to a method, rather than thrown. The exception is being
- * used to represent an event, passed out to other threads. Use of exceptions as arguments rather than as
- * exceptions is extremly confusing. Ideally use a condition or set a flag and check it instead.
- * This exceptions-as-events pattern seems to be in a similar style to Mina code, which is not pretty, but
- * potentially acceptable for that reason. We have the option of extending the mina model to add more events
- * to it, that is, anything that is interested in handling failover as an event occurs below the main
- * amq event handler, which knows the specific interface of the qpid handlers, which can pass this down as
- * an explicit event, without it being an exception. Add failover method to BlockingMethodFrameListener,
- * have it set a flag or interrupt the waiting thread, which then creates and raises this exception.
- */
-public class FailoverException extends Exception
-{
- public FailoverException(String message)
- {
- super(message);
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/failover/FailoverHandler.java b/java/client/src/main/java/org/apache/qpid/client/failover/FailoverHandler.java
deleted file mode 100644
index f74dbba939..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/failover/FailoverHandler.java
+++ /dev/null
@@ -1,268 +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.client.failover;
-
-import org.apache.qpid.AMQDisconnectedException;
-import org.apache.qpid.client.protocol.AMQProtocolHandler;
-import org.apache.qpid.client.state.AMQStateManager;
-import org.apache.qpid.client.state.AMQState;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.concurrent.CountDownLatch;
-
-/**
- * FailoverHandler is a continuation that performs the failover procedure on a protocol session. As described in the
- * class level comment for {@link AMQProtocolHandler}, a protocol connection can span many physical transport
- * connections, failing over to a new connection if the transport connection fails. The procedure to establish a new
- * connection is expressed as a continuation, in order that it may be run in a seperate thread to the i/o thread that
- * detected the failure and is used to handle the communication to establish a new connection.
- *
- * </p>The reason this needs to be a separate thread is because this work cannot be done inside the i/o processor
- * thread. The significant task is the connection setup which involves a protocol exchange until a particular state
- * is achieved. This procedure waits until the state is achieved which would prevent the i/o thread doing the work
- * it needs to do to achieve the new state.
- *
- * <p/>The failover procedure does the following:
- *
- * <ol>
- * <li>Sets the failing over condition to true.</li>
- * <li>Creates a {@link FailoverException} and gets the protocol connection handler to propagate this event to all
- * interested parties.</li>
- * <li>Takes the failover mutex on the protocol connection handler.</li>
- * <li>Abandons the fail over if any of the interested parties vetoes it. The mutex is released and the condition
- * reset.</li>
- * <li>Creates a new {@link AMQStateManager} and re-established the connection through it.</li>
- * <li>Informs the AMQConnection if the connection cannot be re-established.</li>
- * <li>Recreates all sessions from the old connection to the new.</li>
- * <li>Resets the failing over condition and releases the mutex.</li>
- * </ol>
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Update fail-over state <td> {@link AMQProtocolHandler}
- * </table>
- *
- * @todo The failover latch and mutex are used like a lock and condition. If the retrotranlator supports lock/condition
- * then could change over to using them. 1.4 support still needed.
- *
- * @todo If the condition is set to null on a vetoes fail-over and there are already other threads waiting on the
- * condition, they will never be released. It might be an idea to reset the condition in a finally block.
- *
- * @todo Creates a {@link AMQDisconnectedException} and passes it to the AMQConnection. No need to use an
- * exception-as-argument here, could just as easily call a specific method for this purpose on AMQConnection.
- *
- * @todo Creates a {@link FailoverException} and propagates it to the MethodHandlers. No need to use an
- * exception-as-argument here, could just as easily call a specific method for this purpose on
- * {@link org.apache.qpid.protocol.AMQMethodListener}.
- */
-public class FailoverHandler implements Runnable
-{
- /** Used for debugging. */
- private static final Logger _logger = LoggerFactory.getLogger(FailoverHandler.class);
-
- /** Holds the protocol handler for the failed connection, upon which the new connection is to be set up. */
- private AMQProtocolHandler _amqProtocolHandler;
-
- /** Used to hold the host to fail over to. This is optional and if not set a reconnect to the previous host is tried. */
- private String _host;
-
- /** Used to hold the port to fail over to. */
- private int _port;
-
- /**
- * Creates a failover handler on a protocol session, for a particular MINA session (network connection).
- *
- * @param amqProtocolHandler The protocol handler that spans the failover.
- */
- public FailoverHandler(AMQProtocolHandler amqProtocolHandler)
- {
- _amqProtocolHandler = amqProtocolHandler;
- }
-
- /**
- * Performs the failover procedure. See the class level comment, {@link FailoverHandler}, for a description of the
- * failover procedure.
- */
- public void run()
- {
- if (Thread.currentThread().isDaemon())
- {
- throw new IllegalStateException("FailoverHandler must run on a non-daemon thread.");
- }
-
- // Create a latch, upon which tasks that must not run in parallel with a failover can wait for completion of
- // the fail over.
- _amqProtocolHandler.setFailoverLatch(new CountDownLatch(1));
-
- // We wake up listeners. If they can handle failover, they will extend the
- // FailoverRetrySupport class and will in turn block on the latch until failover
- // has completed before retrying the operation.
- _amqProtocolHandler.notifyFailoverStarting();
-
- // Since failover impacts several structures we protect them all with a single mutex. These structures
- // are also in child objects of the connection. This allows us to manipulate them without affecting
- // client code which runs in a separate thread.
- synchronized (_amqProtocolHandler.getConnection().getFailoverMutex())
- {
- //Clear the exception now that we have the failover mutex there can be no one else waiting for a frame so
- // we can clear the exception.
- _amqProtocolHandler.failoverInProgress();
-
- // We switch in a new state manager temporarily so that the interaction to get to the "connection open"
- // state works, without us having to terminate any existing "state waiters". We could theoretically
- // have a state waiter waiting until the connection is closed for some reason. Or in future we may have
- // a slightly more complex state model therefore I felt it was worthwhile doing this.
- AMQStateManager existingStateManager = _amqProtocolHandler.getStateManager();
-
-
- // Use a fresh new StateManager for the reconnection attempts
- _amqProtocolHandler.setStateManager(new AMQStateManager());
-
-
- if (!_amqProtocolHandler.getConnection().firePreFailover(_host != null))
- {
- _logger.info("Failover process veto-ed by client");
-
- //Restore Existing State Manager
- _amqProtocolHandler.setStateManager(existingStateManager);
-
- //todo: ritchiem these exceptions are useless... Would be better to attempt to propogate exception that
- // prompted the failover event.
- if (_host != null)
- {
- _amqProtocolHandler.getConnection().exceptionReceived(new AMQDisconnectedException("Redirect was vetoed by client", null));
- }
- else
- {
- _amqProtocolHandler.getConnection().exceptionReceived(new AMQDisconnectedException("Failover was vetoed by client", null));
- }
-
- _amqProtocolHandler.getFailoverLatch().countDown();
- _amqProtocolHandler.setFailoverLatch(null);
-
- return;
- }
-
- _logger.info("Starting failover process");
-
- boolean failoverSucceeded;
- // when host is non null we have a specified failover host otherwise we all the client to cycle through
- // all specified hosts
-
- // if _host has value then we are performing a redirect.
- if (_host != null)
- {
- failoverSucceeded = _amqProtocolHandler.getConnection().attemptReconnection(_host, _port);
- }
- else
- {
- failoverSucceeded = _amqProtocolHandler.getConnection().attemptReconnection();
- }
-
- if (!failoverSucceeded)
- {
- //Restore Existing State Manager
- _amqProtocolHandler.setStateManager(existingStateManager);
-
- _amqProtocolHandler.getConnection().exceptionReceived(
- new AMQDisconnectedException("Server closed connection and no failover " +
- "was successful", null));
- }
- else
- {
- // Set the new Protocol Session in the StateManager.
- existingStateManager.setProtocolSession(_amqProtocolHandler.getProtocolSession());
-
- // Now that the ProtocolHandler has been reconnected clean up
- // the state of the old state manager. As if we simply reinstate
- // it any old exception that had occured prior to failover may
- // prohibit reconnection.
- // e.g. During testing when the broker is shutdown gracefully.
- // The broker
- // Clear any exceptions we gathered
- if (existingStateManager.getCurrentState() != AMQState.CONNECTION_OPEN)
- {
- // Clear the state of the previous state manager as it may
- // have received an exception
- existingStateManager.clearLastException();
- existingStateManager.changeState(AMQState.CONNECTION_OPEN);
- }
-
-
- //Restore Existing State Manager
- _amqProtocolHandler.setStateManager(existingStateManager);
- try
- {
- if (_amqProtocolHandler.getConnection().firePreResubscribe())
- {
- _logger.info("Resubscribing on new connection");
- _amqProtocolHandler.getConnection().resubscribeSessions();
- }
- else
- {
- _logger.info("Client vetoed automatic resubscription");
- }
-
- _amqProtocolHandler.getConnection().fireFailoverComplete();
- _amqProtocolHandler.setFailoverState(FailoverState.NOT_STARTED);
- _logger.info("Connection failover completed successfully");
- }
- catch (Exception e)
- {
- _logger.info("Failover process failed - exception being propagated by protocol handler");
- _amqProtocolHandler.setFailoverState(FailoverState.FAILED);
- /*try
- {*/
- _amqProtocolHandler.exception(e);
- /*}
- catch (Exception ex)
- {
- _logger.error("Error notifying protocol session of error: " + ex, ex);
- }*/
- }
- }
- }
-
- _amqProtocolHandler.getFailoverLatch().countDown();
- }
-
- /**
- * Sets the host name to fail over to. This is optional and if not set a reconnect to the previous host is tried.
- *
- * @param host The host name to fail over to.
- */
- public void setHost(String host)
- {
- _host = host;
- }
-
- /**
- * Sets the port to fail over to.
- *
- * @param port The port to fail over to.
- */
- public void setPort(int port)
- {
- _port = port;
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/failover/FailoverNoopSupport.java b/java/client/src/main/java/org/apache/qpid/client/failover/FailoverNoopSupport.java
deleted file mode 100644
index 51cc94965a..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/failover/FailoverNoopSupport.java
+++ /dev/null
@@ -1,75 +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.client.failover;
-
-import org.apache.qpid.client.AMQConnection;
-
-/**
- * FailoverNoopSupport is a {@link FailoverSupport} implementation that does not really provide any failover support
- * at all. It wraps a {@link FailoverProtectedOperation} but should that operation throw {@link FailoverException} this
- * support class simply re-raises that exception as an IllegalStateException. This support wrapper should only be
- * used where the caller can be certain that the failover protected operation cannot acutally throw a failover exception,
- * for example, because the caller already holds a lock preventing that condition from arising.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Perform a fail-over protected operation raising providing no handling of fail-over conditions.
- * </table>
- */
-public class FailoverNoopSupport<T, E extends Exception> implements FailoverSupport<T, E>
-{
- /** The protected operation that is to be retried in the event of fail-over. */
- FailoverProtectedOperation<T, E> operation;
-
- /** The connection on which the fail-over protected operation is to be performed. */
- AMQConnection connection;
-
- /**
- * Creates an automatic retrying fail-over handler for the specified operation.
- *
- * @param operation The fail-over protected operation to wrap in this handler.
- */
- public FailoverNoopSupport(FailoverProtectedOperation<T, E> operation, AMQConnection con)
- {
- this.operation = operation;
- this.connection = con;
- }
-
- /**
- * Delegates to another continuation which is to be provided with fail-over handling.
- *
- * @return The return value from the delegated to continuation.
- * @throws E Any exception that the delegated to continuation may raise.
- */
- public T execute() throws E
- {
- try
- {
- return operation.execute();
- }
- catch (FailoverException e)
- {
- throw new IllegalStateException("Fail-over interupted no-op failover support. "
- + "No-op support should only be used where the caller is certain fail-over cannot occur.", e);
- }
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/failover/FailoverProtectedOperation.java b/java/client/src/main/java/org/apache/qpid/client/failover/FailoverProtectedOperation.java
deleted file mode 100644
index e9c5f24791..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/failover/FailoverProtectedOperation.java
+++ /dev/null
@@ -1,49 +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.client.failover;
-
-/**
- * FailoverProtectedOperation is a continuation for an operation that may throw a {@link FailoverException} because
- * it has been interrupted by the fail-over process. The {@link FailoverRetrySupport} class defines support wrappers
- * for failover protected operations, in order to provide different handling schemes when failovers occurr.
- *
- * <p/>The type of checked exception that the operation may perform has been generified, in order that fail over
- * protected operations can be defined that raise arbitrary exceptions. The actuall exception types used should not
- * be sub-classes of FailoverException, or else catching FailoverException in the {@link FailoverRetrySupport} classes
- * will mask the exception.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities
- * <tr><td> Perform an operation that may be interrupted by fail-over.
- * </table>
- */
-public interface FailoverProtectedOperation<T, E extends Exception>
-{
- /**
- * Performs the continuations work.
- *
- * @return Provdes scope for the continuation to return an arbitrary value.
- *
- * @throws FailoverException If the operation is interrupted by a fail-over notification.
- */
- public abstract T execute() throws E, FailoverException;
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/failover/FailoverRetrySupport.java b/java/client/src/main/java/org/apache/qpid/client/failover/FailoverRetrySupport.java
deleted file mode 100644
index e9e52cc97c..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/failover/FailoverRetrySupport.java
+++ /dev/null
@@ -1,104 +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.client.failover;
-
-import org.apache.qpid.client.AMQConnection;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * FailoverRetrySupport is a continuation that wraps another continuation, delaying its execution until it is notified
- * that a blocking condition has been met, and executing the continuation within a mutex. If the continuation fails, due
- * to the original condition being broken, whilst the continuation is waiting for a reponse to a synchronous request,
- * FailoverRetrySupport automatcally rechecks the condition and re-acquires the mutex and re-runs the continution. This
- * automatic retrying is continued until the continuation succeeds, or throws an exception (different to
- * FailoverException, which is used to signal the failure of the original condition).
- *
- * <p/>The blocking condition used is that the connection is not currently failing over, and the mutex used is the
- * connection failover mutex, which guards against the fail-over process being run during fail-over vulnerable methods.
- * These are used like a lock and condition variable.
- *
- * <p/>The wrapped operation may throw a FailoverException, this is an exception that can be raised by a
- * {@link org.apache.qpid.client.protocol.BlockingMethodFrameListener}, in response to it being notified that a
- * fail-over wants to start whilst it was waiting. Methods that are vulnerable to fail-over are those that are
- * synchronous, where a failure will prevent them from getting the reply they are waiting for and asynchronous
- * methods that should not be attempted when a fail-over is in progress.
- *
- * <p/>Wrapping a synchronous method in a FailoverRetrySupport will have the effect that the operation will not be
- * started during fail-over, but be delayed until any current fail-over has completed. Should a fail-over process want
- * to start whilst waiting for the synchrnous reply, the FailoverRetrySupport will detect this and rety the operation
- * until it succeeds. Synchronous methods are usually coordinated with a
- * {@link org.apache.qpid.client.protocol.BlockingMethodFrameListener} which is notified when a fail-over process wants
- * to start and throws a FailoverException in response to this.
- *
- * <p/>Wrapping an asynchronous method in a FailoverRetrySupport will have the effect that the operation will not be
- * started during fail-over, but be delayed until any current fail-over has completed.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Provide a continuation synchronized on a fail-over lock and condition.
- * <tr><td> Automatically retry the continuation accross fail-overs until it succeeds, or raises an exception.
- * </table>
- *
- * @todo Another continuation. Could use an interface Continuation (as described in other todos, for example, see
- * {@link org.apache.qpid.pool.Job}). Then have a wrapping continuation (this), which blocks on an arbitrary
- * Condition or Latch (specified in constructor call), that this blocks on before calling the wrapped Continuation.
- * Must work on Java 1.4, so check retrotranslator works on Lock/Condition or latch first. Argument and return type
- * to match wrapped condition as type parameters. Rename to AsyncConditionalContinuation or something like that.
- *
- * @todo InterruptedException not handled well.
- */
-public class FailoverRetrySupport<T, E extends Exception> implements FailoverSupport<T, E>
-{
- /** Used for debugging. */
- private static final Logger _log = LoggerFactory.getLogger(FailoverRetrySupport.class);
-
- /** The protected operation that is to be retried in the event of fail-over. */
- FailoverProtectedOperation<T, E> operation;
-
- /** The connection on which the fail-over protected operation is to be performed. */
- AMQConnection connection;
-
- /**
- * Creates an automatic retrying fail-over handler for the specified operation.
- *
- * @param operation The fail-over protected operation to wrap in this handler.
- */
- public FailoverRetrySupport(FailoverProtectedOperation<T, E> operation, AMQConnection con)
- {
- this.operation = operation;
- this.connection = con;
- }
-
- /**
- * Delays a continuation until the "not failing over" condition is met on the specified connection. Repeats
- * until the operation throws AMQException or succeeds without being interrupted by fail-over.
- *
- * @return The result of executing the continuation.
- *
- * @throws E Any underlying exception is allowed to fall through.
- */
- public T execute() throws E
- {
- return connection.executeRetrySupport(operation);
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/failover/FailoverState.java b/java/client/src/main/java/org/apache/qpid/client/failover/FailoverState.java
deleted file mode 100644
index 807a5f7d13..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/failover/FailoverState.java
+++ /dev/null
@@ -1,64 +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.client.failover;
-
-/**
- * Defines the possible states of the failover process; not started, in progress, failed.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Represent a one of the states of the fail-over process.
- * </table>
- */
-public final class FailoverState
-{
- /** The string description on this state. */
- private final String _state;
-
- /** Failover has not yet been attempted on this connection. */
- public static final FailoverState NOT_STARTED = new FailoverState("NOT STARTED");
-
- /** Failover has been requested on this connection but has not completed. */
- public static final FailoverState IN_PROGRESS = new FailoverState("IN PROGRESS");
-
- /** Failover has been attempted and failed. */
- public static final FailoverState FAILED = new FailoverState("FAILED");
-
- /**
- * Creates a type safe enumeration of a fail-over state.
- *
- * @param state The fail-over state description string.
- */
- private FailoverState(String state)
- {
- _state = state;
- }
-
- /**
- * Prints this state, mainly for debugging purposes.
- *
- * @return The string description of this state.
- */
- public String toString()
- {
- return "FailoverState: " + _state;
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/failover/FailoverSupport.java b/java/client/src/main/java/org/apache/qpid/client/failover/FailoverSupport.java
deleted file mode 100644
index ef2e7e1d65..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/failover/FailoverSupport.java
+++ /dev/null
@@ -1,47 +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.client.failover;
-
-/**
- * FailoverSupport defines an interface for different types of fail-over handlers, that provide different types of
- * behaviour for handling fail-overs during operations that can be interrupted by the fail-over process. For example,
- * the support could automatically retry once the fail-over process completes, could prevent an operation from being
- * started whilst fail-over is running, or could quietly abandon the operation or raise an exception, and so on.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities
- * <tr><td> Perform a fail-over protected operation with handling for fail-over conditions.
- * </table>
- *
- * @todo Continuation, extend some sort of re-usable Continuation interface, which might look very like this one.
- */
-public interface FailoverSupport<T, E extends Exception>
-{
- /**
- * Delegates to another continuation which is to be provided with fail-over handling.
- *
- * @return The return value from the delegated to continuation.
- *
- * @throws E Any exception that the delegated to continuation may raise.
- */
- public T execute() throws E;
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/handler/AccessRequestOkMethodHandler.java b/java/client/src/main/java/org/apache/qpid/client/handler/AccessRequestOkMethodHandler.java
deleted file mode 100644
index af47673a43..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/handler/AccessRequestOkMethodHandler.java
+++ /dev/null
@@ -1,50 +0,0 @@
-package org.apache.qpid.client.handler;
-/*
- *
- * 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.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import org.apache.qpid.framing.*;
-import org.apache.qpid.client.state.StateAwareMethodListener;
-import org.apache.qpid.client.protocol.AMQProtocolSession;
-import org.apache.qpid.AMQException;
-
-public class AccessRequestOkMethodHandler implements StateAwareMethodListener<AccessRequestOkBody>
-{
- private static final Logger _logger = LoggerFactory.getLogger(AccessRequestOkMethodHandler.class);
-
- private static AccessRequestOkMethodHandler _handler = new AccessRequestOkMethodHandler();
-
- public static AccessRequestOkMethodHandler getInstance()
- {
- return _handler;
- }
-
- public void methodReceived(AMQProtocolSession session, AccessRequestOkBody method, int channelId)
- throws AMQException
- {
- _logger.debug("AccessRequestOk method received");
- session.setTicket(method.getTicket(), channelId);
-
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/handler/BasicCancelOkMethodHandler.java b/java/client/src/main/java/org/apache/qpid/client/handler/BasicCancelOkMethodHandler.java
deleted file mode 100644
index 5cb9412d51..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/handler/BasicCancelOkMethodHandler.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.client.handler;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.protocol.AMQProtocolSession;
-import org.apache.qpid.client.state.StateAwareMethodListener;
-import org.apache.qpid.framing.BasicCancelOkBody;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class BasicCancelOkMethodHandler implements StateAwareMethodListener<BasicCancelOkBody>
-{
- private static final Logger _logger = LoggerFactory.getLogger(BasicCancelOkMethodHandler.class);
-
- private static final BasicCancelOkMethodHandler _instance = new BasicCancelOkMethodHandler();
-
- public static BasicCancelOkMethodHandler getInstance()
- {
- return _instance;
- }
-
- private BasicCancelOkMethodHandler()
- { }
-
- public void methodReceived(AMQProtocolSession session, BasicCancelOkBody body, int channelId)
- throws AMQException
- {
- if (_logger.isInfoEnabled())
- {
- _logger.info("New BasicCancelOk method received for consumer:" + body.getConsumerTag());
- }
-
- session.confirmConsumerCancelled(channelId, body.getConsumerTag());
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/handler/BasicDeliverMethodHandler.java b/java/client/src/main/java/org/apache/qpid/client/handler/BasicDeliverMethodHandler.java
deleted file mode 100644
index 6237234c4d..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/handler/BasicDeliverMethodHandler.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.client.handler;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.message.UnprocessedMessage_0_8;
-import org.apache.qpid.client.protocol.AMQProtocolSession;
-import org.apache.qpid.client.state.StateAwareMethodListener;
-import org.apache.qpid.framing.BasicDeliverBody;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class BasicDeliverMethodHandler implements StateAwareMethodListener<BasicDeliverBody>
-{
- private static final Logger _logger = LoggerFactory.getLogger(BasicDeliverMethodHandler.class);
-
- private static final BasicDeliverMethodHandler _instance = new BasicDeliverMethodHandler();
-
- public static BasicDeliverMethodHandler getInstance()
- {
- return _instance;
- }
-
- public void methodReceived(AMQProtocolSession session, BasicDeliverBody body, int channelId)
- throws AMQException
- {
- final UnprocessedMessage_0_8 msg = new UnprocessedMessage_0_8(
- body.getDeliveryTag(),
- body.getConsumerTag().toIntValue(),
- body.getExchange(),
- body.getRoutingKey(),
- body.getRedelivered());
- _logger.debug("New JmsDeliver method received:" + session);
- session.unprocessedMessageReceived(channelId, msg);
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/handler/BasicReturnMethodHandler.java b/java/client/src/main/java/org/apache/qpid/client/handler/BasicReturnMethodHandler.java
deleted file mode 100644
index 3bbc9209c5..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/handler/BasicReturnMethodHandler.java
+++ /dev/null
@@ -1,58 +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.client.handler;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.message.ReturnMessage;
-import org.apache.qpid.client.protocol.AMQProtocolSession;
-import org.apache.qpid.client.state.StateAwareMethodListener;
-import org.apache.qpid.framing.BasicReturnBody;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class BasicReturnMethodHandler implements StateAwareMethodListener<BasicReturnBody>
-{
- private static final Logger _logger = LoggerFactory.getLogger(BasicReturnMethodHandler.class);
-
- private static final BasicReturnMethodHandler _instance = new BasicReturnMethodHandler();
-
- public static BasicReturnMethodHandler getInstance()
- {
- return _instance;
- }
-
-
- public void methodReceived(AMQProtocolSession session, BasicReturnBody body, int channelId)
- throws AMQException
- {
- _logger.debug("New JmsBounce method received");
- final ReturnMessage msg = new ReturnMessage(
- body.getExchange(),
- body.getRoutingKey(),
- body.getReplyText(),
- body.getReplyCode()
- );
-
- session.unprocessedMessageReceived(channelId, msg);
- }
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/handler/ChannelCloseMethodHandler.java b/java/client/src/main/java/org/apache/qpid/client/handler/ChannelCloseMethodHandler.java
deleted file mode 100644
index 2cf19bf391..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/handler/ChannelCloseMethodHandler.java
+++ /dev/null
@@ -1,119 +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.client.handler;
-
-import org.apache.qpid.AMQChannelClosedException;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.AMQInvalidRoutingKeyException;
-import org.apache.qpid.client.AMQNoConsumersException;
-import org.apache.qpid.client.AMQNoRouteException;
-import org.apache.qpid.client.protocol.AMQProtocolSession;
-import org.apache.qpid.client.state.StateAwareMethodListener;
-import org.apache.qpid.framing.AMQFrame;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.ChannelCloseBody;
-import org.apache.qpid.framing.ChannelCloseOkBody;
-import org.apache.qpid.protocol.AMQConstant;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class ChannelCloseMethodHandler implements StateAwareMethodListener<ChannelCloseBody>
-{
- private static final Logger _logger = LoggerFactory.getLogger(ChannelCloseMethodHandler.class);
-
- private static ChannelCloseMethodHandler _handler = new ChannelCloseMethodHandler();
-
- public static ChannelCloseMethodHandler getInstance()
- {
- return _handler;
- }
-
- public void methodReceived(AMQProtocolSession session, ChannelCloseBody method, int channelId)
- throws AMQException
- {
- _logger.debug("ChannelClose method received");
-
- AMQConstant errorCode = AMQConstant.getConstant(method.getReplyCode());
- AMQShortString reason = method.getReplyText();
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Channel close reply code: " + errorCode + ", reason: " + reason);
- }
-
- ChannelCloseOkBody body = session.getMethodRegistry().createChannelCloseOkBody();
- AMQFrame frame = body.generateFrame(channelId);
- session.writeFrame(frame);
- try
- {
- if (errorCode != AMQConstant.REPLY_SUCCESS)
- {
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Channel close received with errorCode " + errorCode + ", and reason " + reason);
- }
-
- if (errorCode == AMQConstant.NO_CONSUMERS)
- {
- throw new AMQNoConsumersException("Error: " + reason, null, null);
- }
- else if (errorCode == AMQConstant.NO_ROUTE)
- {
- throw new AMQNoRouteException("Error: " + reason, null, null);
- }
- else if (errorCode == AMQConstant.INVALID_ARGUMENT)
- {
- _logger.debug("Broker responded with Invalid Argument.");
-
- throw new org.apache.qpid.AMQInvalidArgumentException(String.valueOf(reason), null);
- }
- else if (errorCode == AMQConstant.INVALID_ROUTING_KEY)
- {
- _logger.debug("Broker responded with Invalid Routing Key.");
-
- throw new AMQInvalidRoutingKeyException(String.valueOf(reason), null);
- }
- else
- {
-
- throw new AMQChannelClosedException(errorCode, "Error: " + reason, null);
- }
-
- }
- }
- finally
- {
- // fixme why is this only done when the close is expected...
- // should the above forced closes not also cause a close?
- // ----------
- // Closing the session only when it is expected allows the errors to be processed
- // Calling this here will prevent failover. So we should do this for all exceptions
- // that should never cause failover. Such as authentication errors.
- // ----
- // 2009-09-07 - ritchiem
- // calling channelClosed will only close this session and will not
- // prevent failover. If we don't close the session here then we will
- // have problems during the session close as it will attempt to
- // close the session that the broker has closed,
-
- session.channelClosed(channelId, errorCode, String.valueOf(reason));
- }
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/handler/ChannelCloseOkMethodHandler.java b/java/client/src/main/java/org/apache/qpid/client/handler/ChannelCloseOkMethodHandler.java
deleted file mode 100644
index 72936779c2..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/handler/ChannelCloseOkMethodHandler.java
+++ /dev/null
@@ -1,49 +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.client.handler;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.protocol.AMQProtocolSession;
-import org.apache.qpid.client.state.StateAwareMethodListener;
-import org.apache.qpid.framing.ChannelCloseOkBody;
-import org.apache.qpid.protocol.AMQConstant;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class ChannelCloseOkMethodHandler implements StateAwareMethodListener<ChannelCloseOkBody>
-{
- private static final Logger _logger = LoggerFactory.getLogger(ChannelCloseOkMethodHandler.class);
-
- private static final ChannelCloseOkMethodHandler _instance = new ChannelCloseOkMethodHandler();
-
- public static ChannelCloseOkMethodHandler getInstance()
- {
- return _instance;
- }
-
- public void methodReceived(AMQProtocolSession session, ChannelCloseOkBody method, int channelId)
- throws AMQException
- {
- _logger.info("Received channel-close-ok for channel-id " + channelId);
-
- session.channelClosed(channelId, AMQConstant.REPLY_SUCCESS, "Channel closed successfully");
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/handler/ChannelFlowMethodHandler.java b/java/client/src/main/java/org/apache/qpid/client/handler/ChannelFlowMethodHandler.java
deleted file mode 100644
index 2153b9cc8c..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/handler/ChannelFlowMethodHandler.java
+++ /dev/null
@@ -1,51 +0,0 @@
-package org.apache.qpid.client.handler;
-
-import org.apache.qpid.framing.ChannelFlowBody;
-import org.apache.qpid.client.state.StateAwareMethodListener;
-import org.apache.qpid.client.protocol.AMQProtocolSession;
-import org.apache.qpid.AMQException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/*
-*
-* 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 ChannelFlowMethodHandler implements StateAwareMethodListener<ChannelFlowBody>
-{
- private static final Logger _logger = LoggerFactory.getLogger(ChannelFlowMethodHandler.class);
- private static final ChannelFlowMethodHandler _instance = new ChannelFlowMethodHandler();
-
- public static ChannelFlowMethodHandler getInstance()
- {
- return _instance;
- }
-
- private ChannelFlowMethodHandler()
- { }
-
- public void methodReceived(AMQProtocolSession session, ChannelFlowBody body, int channelId)
- throws AMQException
- {
- session.setFlowControl(channelId, body.getActive());
- }
-
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/handler/ChannelFlowOkMethodHandler.java b/java/client/src/main/java/org/apache/qpid/client/handler/ChannelFlowOkMethodHandler.java
deleted file mode 100644
index 6f66a972d5..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/handler/ChannelFlowOkMethodHandler.java
+++ /dev/null
@@ -1,52 +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.client.handler;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.protocol.AMQProtocolSession;
-import org.apache.qpid.client.state.StateAwareMethodListener;
-import org.apache.qpid.framing.ChannelFlowOkBody;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class ChannelFlowOkMethodHandler implements StateAwareMethodListener<ChannelFlowOkBody>
-{
- private static final Logger _logger = LoggerFactory.getLogger(ChannelFlowOkMethodHandler.class);
- private static final ChannelFlowOkMethodHandler _instance = new ChannelFlowOkMethodHandler();
-
- public static ChannelFlowOkMethodHandler getInstance()
- {
- return _instance;
- }
-
- private ChannelFlowOkMethodHandler()
- { }
-
- public void methodReceived(AMQProtocolSession session, ChannelFlowOkBody body, int channelId)
- throws AMQException
- {
-
- _logger.debug("Received Channel.Flow-Ok message, active = " + body.getActive());
- }
-
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/handler/ClientMethodDispatcherImpl.java b/java/client/src/main/java/org/apache/qpid/client/handler/ClientMethodDispatcherImpl.java
deleted file mode 100644
index ec98783a8a..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/handler/ClientMethodDispatcherImpl.java
+++ /dev/null
@@ -1,543 +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.client.handler;
-
-import java.util.Map;
-import java.util.HashMap;
-
-import org.apache.qpid.framing.*;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.state.AMQStateManager;
-import org.apache.qpid.client.state.AMQMethodNotImplementedException;
-import org.apache.qpid.client.protocol.AMQProtocolSession;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class ClientMethodDispatcherImpl implements MethodDispatcher
-{
-
- private static final BasicCancelOkMethodHandler _basicCancelOkMethodHandler = BasicCancelOkMethodHandler.getInstance();
- private static final BasicDeliverMethodHandler _basicDeliverMethodHandler = BasicDeliverMethodHandler.getInstance();
- private static final BasicReturnMethodHandler _basicReturnMethodHandler = BasicReturnMethodHandler.getInstance();
- private static final ChannelCloseMethodHandler _channelCloseMethodHandler = ChannelCloseMethodHandler.getInstance();
- private static final ChannelCloseOkMethodHandler _channelCloseOkMethodHandler = ChannelCloseOkMethodHandler.getInstance();
- private static final ChannelFlowOkMethodHandler _channelFlowOkMethodHandler = ChannelFlowOkMethodHandler.getInstance();
- private static final ChannelFlowMethodHandler _channelFlowMethodHandler = ChannelFlowMethodHandler.getInstance();
- private static final ConnectionCloseMethodHandler _connectionCloseMethodHandler = ConnectionCloseMethodHandler.getInstance();
- private static final ConnectionOpenOkMethodHandler _connectionOpenOkMethodHandler = ConnectionOpenOkMethodHandler.getInstance();
- private static final ConnectionRedirectMethodHandler _connectionRedirectMethodHandler = ConnectionRedirectMethodHandler.getInstance();
- private static final ConnectionSecureMethodHandler _connectionSecureMethodHandler = ConnectionSecureMethodHandler.getInstance();
- private static final ConnectionStartMethodHandler _connectionStartMethodHandler = ConnectionStartMethodHandler.getInstance();
- private static final ConnectionTuneMethodHandler _connectionTuneMethodHandler = ConnectionTuneMethodHandler.getInstance();
- private static final ExchangeBoundOkMethodHandler _exchangeBoundOkMethodHandler = ExchangeBoundOkMethodHandler.getInstance();
- private static final QueueDeleteOkMethodHandler _queueDeleteOkMethodHandler = QueueDeleteOkMethodHandler.getInstance();
-
- private static final Logger _logger = LoggerFactory.getLogger(ClientMethodDispatcherImpl.class);
-
- private static interface DispatcherFactory
- {
- public ClientMethodDispatcherImpl createMethodDispatcher(AMQProtocolSession session);
- }
-
- private static final Map<ProtocolVersion, DispatcherFactory> _dispatcherFactories =
- new HashMap<ProtocolVersion, DispatcherFactory>();
-
- static
- {
- _dispatcherFactories.put(ProtocolVersion.v8_0,
- new DispatcherFactory()
- {
- public ClientMethodDispatcherImpl createMethodDispatcher(AMQProtocolSession session)
- {
- return new ClientMethodDispatcherImpl_8_0(session);
- }
- });
-
- _dispatcherFactories.put(ProtocolVersion.v0_9,
- new DispatcherFactory()
- {
- public ClientMethodDispatcherImpl createMethodDispatcher(AMQProtocolSession session)
- {
- return new ClientMethodDispatcherImpl_0_9(session);
- }
- });
-
-
- _dispatcherFactories.put(ProtocolVersion.v0_91,
- new DispatcherFactory()
- {
- public ClientMethodDispatcherImpl createMethodDispatcher(AMQProtocolSession session)
- {
- return new ClientMethodDispatcherImpl_0_91(session);
- }
- });
-
- }
-
- public static ClientMethodDispatcherImpl newMethodDispatcher(ProtocolVersion version, AMQProtocolSession session)
- {
- if (_logger.isInfoEnabled())
- {
- _logger.info("New Method Dispatcher:" + session);
- }
-
- DispatcherFactory factory = _dispatcherFactories.get(version);
- return factory.createMethodDispatcher(session);
- }
-
- AMQProtocolSession _session;
-
- public ClientMethodDispatcherImpl(AMQProtocolSession session)
- {
- _session = session;
- }
-
- public AMQStateManager getStateManager()
- {
- return _session.getStateManager();
- }
-
- public boolean dispatchAccessRequestOk(AccessRequestOkBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchBasicCancelOk(BasicCancelOkBody body, int channelId) throws AMQException
- {
- _basicCancelOkMethodHandler.methodReceived(_session, body, channelId);
- return true;
- }
-
- public boolean dispatchBasicConsumeOk(BasicConsumeOkBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchBasicDeliver(BasicDeliverBody body, int channelId) throws AMQException
- {
- _basicDeliverMethodHandler.methodReceived(_session, body, channelId);
- return true;
- }
-
- public boolean dispatchBasicGetEmpty(BasicGetEmptyBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchBasicGetOk(BasicGetOkBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchBasicQosOk(BasicQosOkBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchBasicReturn(BasicReturnBody body, int channelId) throws AMQException
- {
- _basicReturnMethodHandler.methodReceived(_session, body, channelId);
- return true;
- }
-
- public boolean dispatchChannelClose(ChannelCloseBody body, int channelId) throws AMQException
- {
- _channelCloseMethodHandler.methodReceived(_session, body, channelId);
- return true;
- }
-
- public boolean dispatchChannelCloseOk(ChannelCloseOkBody body, int channelId) throws AMQException
- {
- _channelCloseOkMethodHandler.methodReceived(_session, body, channelId);
- return true;
- }
-
- public boolean dispatchChannelFlow(ChannelFlowBody body, int channelId) throws AMQException
- {
- _channelFlowMethodHandler.methodReceived(_session, body, channelId);
- return true;
- }
-
- public boolean dispatchChannelFlowOk(ChannelFlowOkBody body, int channelId) throws AMQException
- {
- _channelFlowOkMethodHandler.methodReceived(_session, body, channelId);
- return true;
- }
-
- public boolean dispatchChannelOpenOk(ChannelOpenOkBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchConnectionClose(ConnectionCloseBody body, int channelId) throws AMQException
- {
- _connectionCloseMethodHandler.methodReceived(_session, body, channelId);
- return true;
- }
-
- public boolean dispatchConnectionCloseOk(ConnectionCloseOkBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchConnectionOpenOk(ConnectionOpenOkBody body, int channelId) throws AMQException
- {
- _connectionOpenOkMethodHandler.methodReceived(_session, body, channelId);
- return true;
- }
-
- public boolean dispatchConnectionRedirect(ConnectionRedirectBody body, int channelId) throws AMQException
- {
- _connectionRedirectMethodHandler.methodReceived(_session, body, channelId);
- return true;
- }
-
- public boolean dispatchConnectionSecure(ConnectionSecureBody body, int channelId) throws AMQException
- {
- _connectionSecureMethodHandler.methodReceived(_session, body, channelId);
- return true;
- }
-
- public boolean dispatchConnectionStart(ConnectionStartBody body, int channelId) throws AMQException
- {
- _connectionStartMethodHandler.methodReceived(_session, body, channelId);
- return true;
- }
-
- public boolean dispatchConnectionTune(ConnectionTuneBody body, int channelId) throws AMQException
- {
- _connectionTuneMethodHandler.methodReceived(_session, body, channelId);
- return true;
- }
-
- public boolean dispatchQueueDeleteOk(QueueDeleteOkBody body, int channelId) throws AMQException
- {
- _queueDeleteOkMethodHandler.methodReceived(_session, body, channelId);
- return true;
- }
-
- public boolean dispatchQueuePurgeOk(QueuePurgeOkBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchStreamCancelOk(StreamCancelOkBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchStreamConsumeOk(StreamConsumeOkBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchAccessRequest(AccessRequestBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchBasicAck(BasicAckBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchBasicCancel(BasicCancelBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchBasicConsume(BasicConsumeBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchBasicGet(BasicGetBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchBasicPublish(BasicPublishBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchBasicQos(BasicQosBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchBasicRecover(BasicRecoverBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchBasicReject(BasicRejectBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchChannelOpen(ChannelOpenBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchConnectionOpen(ConnectionOpenBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchConnectionSecureOk(ConnectionSecureOkBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchConnectionStartOk(ConnectionStartOkBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchConnectionTuneOk(ConnectionTuneOkBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchDtxSelect(DtxSelectBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchDtxStart(DtxStartBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchExchangeBound(ExchangeBoundBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchExchangeDeclare(ExchangeDeclareBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchExchangeDelete(ExchangeDeleteBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchFileAck(FileAckBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchFileCancel(FileCancelBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchFileConsume(FileConsumeBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchFilePublish(FilePublishBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchFileQos(FileQosBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchFileReject(FileRejectBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchQueueBind(QueueBindBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchQueueDeclare(QueueDeclareBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchQueueDelete(QueueDeleteBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchQueuePurge(QueuePurgeBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchStreamCancel(StreamCancelBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchStreamConsume(StreamConsumeBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchStreamPublish(StreamPublishBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchStreamQos(StreamQosBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchTunnelRequest(TunnelRequestBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchTxCommit(TxCommitBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchTxRollback(TxRollbackBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchTxSelect(TxSelectBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchDtxSelectOk(DtxSelectOkBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchDtxStartOk(DtxStartOkBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchExchangeBoundOk(ExchangeBoundOkBody body, int channelId) throws AMQException
- {
- _exchangeBoundOkMethodHandler.methodReceived(_session, body, channelId);
- return true;
- }
-
- public boolean dispatchExchangeDeclareOk(ExchangeDeclareOkBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchExchangeDeleteOk(ExchangeDeleteOkBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchFileCancelOk(FileCancelOkBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchFileConsumeOk(FileConsumeOkBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchFileDeliver(FileDeliverBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchFileOpen(FileOpenBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchFileOpenOk(FileOpenOkBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchFileQosOk(FileQosOkBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchFileReturn(FileReturnBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchFileStage(FileStageBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchQueueBindOk(QueueBindOkBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchQueueDeclareOk(QueueDeclareOkBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchStreamDeliver(StreamDeliverBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchStreamQosOk(StreamQosOkBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchStreamReturn(StreamReturnBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchTxCommitOk(TxCommitOkBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchTxRollbackOk(TxRollbackOkBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchTxSelectOk(TxSelectOkBody body, int channelId) throws AMQException
- {
- return false;
- }
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/handler/ClientMethodDispatcherImpl_0_9.java b/java/client/src/main/java/org/apache/qpid/client/handler/ClientMethodDispatcherImpl_0_9.java
deleted file mode 100644
index d3e9fba8ed..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/handler/ClientMethodDispatcherImpl_0_9.java
+++ /dev/null
@@ -1,153 +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.client.handler;
-
-import org.apache.qpid.framing.*;
-import org.apache.qpid.framing.amqp_0_9.MethodDispatcher_0_9;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.state.AMQStateManager;
-import org.apache.qpid.client.state.AMQMethodNotImplementedException;
-import org.apache.qpid.client.protocol.AMQProtocolSession;
-
-public class ClientMethodDispatcherImpl_0_9 extends ClientMethodDispatcherImpl implements MethodDispatcher_0_9
-{
- public ClientMethodDispatcherImpl_0_9(AMQProtocolSession session)
- {
- super(session);
- }
-
- public boolean dispatchBasicRecoverSyncOk(BasicRecoverSyncOkBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchBasicRecoverSync(BasicRecoverSyncBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchChannelOk(ChannelOkBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchChannelPing(ChannelPingBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchChannelPong(ChannelPongBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchChannelResume(ChannelResumeBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchMessageAppend(MessageAppendBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageCancel(MessageCancelBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchMessageCheckpoint(MessageCheckpointBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageClose(MessageCloseBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageConsume(MessageConsumeBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchMessageEmpty(MessageEmptyBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageGet(MessageGetBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchMessageOffset(MessageOffsetBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageOk(MessageOkBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageOpen(MessageOpenBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageQos(MessageQosBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchMessageRecover(MessageRecoverBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchMessageReject(MessageRejectBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageResume(MessageResumeBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageTransfer(MessageTransferBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchQueueUnbind(QueueUnbindBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchQueueUnbindOk(QueueUnbindOkBody body, int channelId) throws AMQException
- {
- return false;
- }
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/handler/ClientMethodDispatcherImpl_0_91.java b/java/client/src/main/java/org/apache/qpid/client/handler/ClientMethodDispatcherImpl_0_91.java
deleted file mode 100644
index f15340ae00..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/handler/ClientMethodDispatcherImpl_0_91.java
+++ /dev/null
@@ -1,158 +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.client.handler;
-
-import org.apache.qpid.framing.*;
-import org.apache.qpid.framing.amqp_0_91.MethodDispatcher_0_91;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.state.AMQStateManager;
-import org.apache.qpid.client.state.AMQMethodNotImplementedException;
-import org.apache.qpid.client.protocol.AMQProtocolSession;
-
-public class ClientMethodDispatcherImpl_0_91 extends ClientMethodDispatcherImpl implements MethodDispatcher_0_91
-{
- public ClientMethodDispatcherImpl_0_91(AMQProtocolSession session)
- {
- super(session);
- }
-
- public boolean dispatchBasicRecoverSyncOk(BasicRecoverSyncOkBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchBasicRecoverSync(BasicRecoverSyncBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchChannelOk(ChannelOkBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchChannelPing(ChannelPingBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchChannelPong(ChannelPongBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchChannelResume(ChannelResumeBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchMessageAppend(MessageAppendBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageCancel(MessageCancelBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchMessageCheckpoint(MessageCheckpointBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageClose(MessageCloseBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageConsume(MessageConsumeBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchMessageEmpty(MessageEmptyBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageGet(MessageGetBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchMessageOffset(MessageOffsetBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageOk(MessageOkBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageOpen(MessageOpenBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageQos(MessageQosBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchMessageRecover(MessageRecoverBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchMessageReject(MessageRejectBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageResume(MessageResumeBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchMessageTransfer(MessageTransferBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchQueueUnbind(QueueUnbindBody body, int channelId) throws AMQException
- {
- throw new AMQMethodNotImplementedException(body);
- }
-
- public boolean dispatchBasicRecoverOk(BasicRecoverOkBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchQueueUnbindOk(QueueUnbindOkBody body, int channelId) throws AMQException
- {
- return false;
- }
-
-} \ No newline at end of file
diff --git a/java/client/src/main/java/org/apache/qpid/client/handler/ClientMethodDispatcherImpl_8_0.java b/java/client/src/main/java/org/apache/qpid/client/handler/ClientMethodDispatcherImpl_8_0.java
deleted file mode 100644
index 19f758817d..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/handler/ClientMethodDispatcherImpl_8_0.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
- package org.apache.qpid.client.handler;
-
-import org.apache.qpid.framing.*;
-import org.apache.qpid.framing.amqp_8_0.MethodDispatcher_8_0;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.protocol.AMQProtocolSession;
-
-public class ClientMethodDispatcherImpl_8_0 extends ClientMethodDispatcherImpl implements MethodDispatcher_8_0
-{
- public ClientMethodDispatcherImpl_8_0(AMQProtocolSession session)
- {
- super(session);
- }
-
- public boolean dispatchBasicRecoverOk(BasicRecoverOkBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchChannelAlert(ChannelAlertBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchTestContent(TestContentBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchTestContentOk(TestContentOkBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchTestInteger(TestIntegerBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchTestIntegerOk(TestIntegerOkBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchTestString(TestStringBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchTestStringOk(TestStringOkBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchTestTable(TestTableBody body, int channelId) throws AMQException
- {
- return false;
- }
-
- public boolean dispatchTestTableOk(TestTableOkBody body, int channelId) throws AMQException
- {
- return false;
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionCloseMethodHandler.java b/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionCloseMethodHandler.java
deleted file mode 100644
index b392604822..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionCloseMethodHandler.java
+++ /dev/null
@@ -1,113 +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.client.handler;
-
-import org.apache.qpid.AMQConnectionClosedException;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.AMQSecurityException;
-import org.apache.qpid.client.AMQAuthenticationException;
-import org.apache.qpid.client.protocol.AMQProtocolSession;
-import org.apache.qpid.client.state.AMQState;
-import org.apache.qpid.client.state.StateAwareMethodListener;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.ConnectionCloseBody;
-import org.apache.qpid.framing.ConnectionCloseOkBody;
-import org.apache.qpid.protocol.AMQConstant;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class ConnectionCloseMethodHandler implements StateAwareMethodListener<ConnectionCloseBody>
-{
- private static final Logger _logger = LoggerFactory.getLogger(ConnectionCloseMethodHandler.class);
-
- private static ConnectionCloseMethodHandler _handler = new ConnectionCloseMethodHandler();
-
- public static ConnectionCloseMethodHandler getInstance()
- {
- return _handler;
- }
-
- private ConnectionCloseMethodHandler()
- {
- }
-
- public void methodReceived(AMQProtocolSession session, ConnectionCloseBody method, int channelId)
- throws AMQException
- {
- _logger.info("ConnectionClose frame received");
-
- // does it matter
- // stateManager.changeState(AMQState.CONNECTION_CLOSING);
-
- AMQConstant errorCode = AMQConstant.getConstant(method.getReplyCode());
- AMQShortString reason = method.getReplyText();
-
- AMQException error = null;
-
- try
- {
-
- ConnectionCloseOkBody closeOkBody = session.getMethodRegistry().createConnectionCloseOkBody();
- // TODO: check whether channel id of zero is appropriate
- // Be aware of possible changes to parameter order as versions change.
- session.writeFrame(closeOkBody.generateFrame(0));
-
- if (errorCode != AMQConstant.REPLY_SUCCESS)
- {
- if (errorCode == AMQConstant.NOT_ALLOWED)
- {
- _logger.info("Error :" + errorCode + ":" + Thread.currentThread().getName());
-
- error = new AMQAuthenticationException(errorCode, reason == null ? null : reason.toString(), null);
- }
- else if (errorCode == AMQConstant.ACCESS_REFUSED)
- {
- _logger.info("Error :" + errorCode + ":" + Thread.currentThread().getName());
-
- error = new AMQSecurityException(reason == null ? null : reason.toString(), null);
- }
- else
- {
- _logger.info("Connection close received with error code " + errorCode);
-
- error = new AMQConnectionClosedException(errorCode, "Error: " + reason, null);
- }
- }
- }
- finally
- {
-
- if (error != null)
- {
- session.notifyError(error);
- }
-
- // Close the protocol Session, including any open TCP connections
- session.closeProtocolSession();
-
- // Closing the session should not introduce a race condition as this thread will continue to propgate any
- // exception in to the exceptionCaught method of the SessionHandler.
- // Any sessionClosed event should occur after this.
- }
- }
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionOpenOkMethodHandler.java b/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionOpenOkMethodHandler.java
deleted file mode 100644
index e40cafd72f..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionOpenOkMethodHandler.java
+++ /dev/null
@@ -1,48 +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.client.handler;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.ConnectionOpenOkBody;
-import org.apache.qpid.client.protocol.AMQProtocolSession;
-import org.apache.qpid.client.state.AMQState;
-import org.apache.qpid.client.state.StateAwareMethodListener;
-
-public class ConnectionOpenOkMethodHandler implements StateAwareMethodListener<ConnectionOpenOkBody>
-{
- private static final ConnectionOpenOkMethodHandler _instance = new ConnectionOpenOkMethodHandler();
-
- public static ConnectionOpenOkMethodHandler getInstance()
- {
- return _instance;
- }
-
- private ConnectionOpenOkMethodHandler()
- {
- }
-
- public void methodReceived(AMQProtocolSession session, ConnectionOpenOkBody body, int channelId)
- {
- session.getStateManager().changeState(AMQState.CONNECTION_OPEN);
- }
-
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionRedirectMethodHandler.java b/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionRedirectMethodHandler.java
deleted file mode 100644
index 472c471fd6..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionRedirectMethodHandler.java
+++ /dev/null
@@ -1,71 +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.client.handler;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.protocol.AMQProtocolSession;
-import org.apache.qpid.client.state.StateAwareMethodListener;
-import org.apache.qpid.framing.ConnectionRedirectBody;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class ConnectionRedirectMethodHandler implements StateAwareMethodListener<ConnectionRedirectBody>
-{
- private static final Logger _logger = LoggerFactory.getLogger(ConnectionRedirectMethodHandler.class);
-
- private static final int DEFAULT_REDIRECT_PORT = 5672;
-
- private static ConnectionRedirectMethodHandler _handler = new ConnectionRedirectMethodHandler();
-
- public static ConnectionRedirectMethodHandler getInstance()
- {
- return _handler;
- }
-
- private ConnectionRedirectMethodHandler()
- { }
-
- public void methodReceived(AMQProtocolSession session, ConnectionRedirectBody method, int channelId)
- throws AMQException
- {
- _logger.info("ConnectionRedirect frame received");
-
- String host = method.getHost().toString();
- // the host is in the form hostname:port with the port being optional
- int portIndex = host.indexOf(':');
-
- int port;
- if (portIndex == -1)
- {
- port = DEFAULT_REDIRECT_PORT;
- }
- else
- {
- port = Integer.parseInt(host.substring(portIndex + 1));
- host = host.substring(0, portIndex);
-
- }
-
- session.failover(host, port);
- }
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionSecureMethodHandler.java b/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionSecureMethodHandler.java
deleted file mode 100644
index 9a9bee757b..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionSecureMethodHandler.java
+++ /dev/null
@@ -1,70 +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.client.handler;
-
-import javax.security.sasl.SaslClient;
-import javax.security.sasl.SaslException;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.protocol.AMQProtocolSession;
-import org.apache.qpid.client.state.StateAwareMethodListener;
-import org.apache.qpid.framing.ConnectionSecureBody;
-import org.apache.qpid.framing.ConnectionSecureOkBody;
-
-public class ConnectionSecureMethodHandler implements StateAwareMethodListener<ConnectionSecureBody>
-{
- private static final ConnectionSecureMethodHandler _instance = new ConnectionSecureMethodHandler();
-
- public static ConnectionSecureMethodHandler getInstance()
- {
- return _instance;
- }
-
- public void methodReceived(AMQProtocolSession session, ConnectionSecureBody body, int channelId)
- throws AMQException
- {
- SaslClient client = session.getSaslClient();
- if (client == null)
- {
- throw new AMQException(null, "No SASL client set up - cannot proceed with authentication", null);
- }
-
-
-
- try
- {
- // Evaluate server challenge
- byte[] response = client.evaluateChallenge(body.getChallenge());
-
- ConnectionSecureOkBody secureOkBody = session.getMethodRegistry().createConnectionSecureOkBody(response);
-
- session.writeFrame(secureOkBody.generateFrame(channelId));
- }
- catch (SaslException e)
- {
- throw new AMQException(null, "Error processing SASL challenge: " + e, e);
- }
-
-
- }
-
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionStartMethodHandler.java b/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionStartMethodHandler.java
deleted file mode 100644
index c81ad6422f..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionStartMethodHandler.java
+++ /dev/null
@@ -1,239 +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.client.handler;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.protocol.AMQProtocolSession;
-import org.apache.qpid.client.security.AMQCallbackHandler;
-import org.apache.qpid.client.security.CallbackHandlerRegistry;
-import org.apache.qpid.client.state.AMQState;
-import org.apache.qpid.client.state.StateAwareMethodListener;
-import org.apache.qpid.common.ClientProperties;
-import org.apache.qpid.common.QpidProperties;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.ConnectionStartBody;
-import org.apache.qpid.framing.ConnectionStartOkBody;
-import org.apache.qpid.framing.FieldTable;
-import org.apache.qpid.framing.FieldTableFactory;
-import org.apache.qpid.framing.ProtocolVersion;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.security.sasl.Sasl;
-import javax.security.sasl.SaslClient;
-import javax.security.sasl.SaslException;
-
-import java.io.UnsupportedEncodingException;
-import java.util.HashSet;
-import java.util.StringTokenizer;
-
-public class ConnectionStartMethodHandler implements StateAwareMethodListener<ConnectionStartBody>
-{
- private static final Logger _log = LoggerFactory.getLogger(ConnectionStartMethodHandler.class);
-
- private static final ConnectionStartMethodHandler _instance = new ConnectionStartMethodHandler();
-
- public static ConnectionStartMethodHandler getInstance()
- {
- return _instance;
- }
-
- private ConnectionStartMethodHandler()
- { }
-
- public void methodReceived(AMQProtocolSession session, ConnectionStartBody body, int channelId)
- throws AMQException
- {
- _log.debug("public void methodReceived(AMQStateManager stateManager, AMQProtocolSession protocolSession, "
- + "AMQMethodEvent evt): called");
-
- ProtocolVersion pv = new ProtocolVersion((byte) body.getVersionMajor(), (byte) body.getVersionMinor());
-
- // 0-9-1 is indistinguishable from 0-9 using only major and minor ... if we established the connection as 0-9-1
- // and now get back major = 0 , minor = 9 then we can assume it means 0-9-1
-
- if(pv.equals(ProtocolVersion.v0_9) && session.getProtocolVersion().equals(ProtocolVersion.v0_91))
- {
- pv = ProtocolVersion.v0_91;
- }
-
- // For the purposes of interop, we can make the client accept the broker's version string.
- // If it does, it then internally records the version as being the latest one that it understands.
- // It needs to do this since frame lookup is done by version.
- if (Boolean.getBoolean("qpid.accept.broker.version") && !pv.isSupported())
- {
-
- pv = ProtocolVersion.getLatestSupportedVersion();
- }
-
- if (pv.isSupported())
- {
- session.setProtocolVersion(pv);
-
- try
- {
- // Used to hold the SASL mechanism to authenticate with.
- String mechanism;
-
- if (body.getMechanisms()== null)
- {
- throw new AMQException(null, "mechanism not specified in ConnectionStart method frame", null);
- }
- else
- {
- mechanism = chooseMechanism(body.getMechanisms());
- _log.debug("mechanism = " + mechanism);
- }
-
- if (mechanism == null)
- {
- throw new AMQException(null, "No supported security mechanism found, passed: " + new String(body.getMechanisms()), null);
- }
-
- byte[] saslResponse;
- try
- {
- SaslClient sc =
- Sasl.createSaslClient(new String[] { mechanism }, null, "AMQP", "localhost", null,
- createCallbackHandler(mechanism, session));
- if (sc == null)
- {
- throw new AMQException(null, "Client SASL configuration error: no SaslClient could be created for mechanism " + mechanism
- + ". Please ensure all factories are registered. See DynamicSaslRegistrar for "
- + " details of how to register non-standard SASL client providers.", null);
- }
-
- session.setSaslClient(sc);
- saslResponse = (sc.hasInitialResponse() ? sc.evaluateChallenge(new byte[0]) : null);
- }
- catch (SaslException e)
- {
- session.setSaslClient(null);
- throw new AMQException(null, "Unable to create SASL client: " + e, e);
- }
-
- if (body.getLocales() == null)
- {
- throw new AMQException(null, "Locales is not defined in Connection Start method", null);
- }
-
- final String locales = new String(body.getLocales(), "utf8");
- final StringTokenizer tokenizer = new StringTokenizer(locales, " ");
- if (tokenizer.hasMoreTokens())
- {
- tokenizer.nextToken();
- }
- else
- {
- throw new AMQException(null, "No locales sent from server, passed: " + locales, null);
- }
-
- session.getStateManager().changeState(AMQState.CONNECTION_NOT_TUNED);
- FieldTable clientProperties = FieldTableFactory.newFieldTable();
-
- clientProperties.setString(new AMQShortString(ClientProperties.instance.toString()),
- session.getClientID());
- clientProperties.setString(new AMQShortString(ClientProperties.product.toString()),
- QpidProperties.getProductName());
- clientProperties.setString(new AMQShortString(ClientProperties.version.toString()),
- QpidProperties.getReleaseVersion());
- clientProperties.setString(new AMQShortString(ClientProperties.platform.toString()), getFullSystemInfo());
-
-
- ConnectionStartOkBody connectionStartOkBody = session.getMethodRegistry().createConnectionStartOkBody(clientProperties,new AMQShortString(mechanism),saslResponse,new AMQShortString(locales));
- // AMQP version change: Hardwire the version to 0-8 (major=8, minor=0)
- // TODO: Connect this to the session version obtained from ProtocolInitiation for this session.
- // Be aware of possible changes to parameter order as versions change.
- session.writeFrame(connectionStartOkBody.generateFrame(channelId));
-
- }
- catch (UnsupportedEncodingException e)
- {
- throw new AMQException(null, "Unable to decode data: " + e, e);
- }
- }
- else
- {
- _log.error("Broker requested Protocol [" + body.getVersionMajor() + "-" + body.getVersionMinor()
- + "] which is not supported by this version of the client library");
-
- session.closeProtocolSession();
- }
- }
-
- private String getFullSystemInfo()
- {
- StringBuffer fullSystemInfo = new StringBuffer();
- fullSystemInfo.append(System.getProperty("java.runtime.name"));
- fullSystemInfo.append(", " + System.getProperty("java.runtime.version"));
- fullSystemInfo.append(", " + System.getProperty("java.vendor"));
- fullSystemInfo.append(", " + System.getProperty("os.arch"));
- fullSystemInfo.append(", " + System.getProperty("os.name"));
- fullSystemInfo.append(", " + System.getProperty("os.version"));
- fullSystemInfo.append(", " + System.getProperty("sun.os.patch.level"));
-
- return fullSystemInfo.toString();
- }
-
- private String chooseMechanism(byte[] availableMechanisms) throws UnsupportedEncodingException
- {
- final String mechanisms = new String(availableMechanisms, "utf8");
- StringTokenizer tokenizer = new StringTokenizer(mechanisms, " ");
- HashSet mechanismSet = new HashSet();
- while (tokenizer.hasMoreTokens())
- {
- mechanismSet.add(tokenizer.nextToken());
- }
-
- String preferredMechanisms = CallbackHandlerRegistry.getInstance().getMechanisms();
- StringTokenizer prefTokenizer = new StringTokenizer(preferredMechanisms, " ");
- while (prefTokenizer.hasMoreTokens())
- {
- String mech = prefTokenizer.nextToken();
- if (mechanismSet.contains(mech))
- {
- return mech;
- }
- }
-
- return null;
- }
-
- private AMQCallbackHandler createCallbackHandler(String mechanism, AMQProtocolSession protocolSession)
- throws AMQException
- {
- Class mechanismClass = CallbackHandlerRegistry.getInstance().getCallbackHandlerClass(mechanism);
- try
- {
- Object instance = mechanismClass.newInstance();
- AMQCallbackHandler cbh = (AMQCallbackHandler) instance;
- cbh.initialise(protocolSession);
-
- return cbh;
- }
- catch (Exception e)
- {
- throw new AMQException(null, "Unable to create callback handler: " + e, e);
- }
- }
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionTuneMethodHandler.java b/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionTuneMethodHandler.java
deleted file mode 100644
index d1b2caf987..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionTuneMethodHandler.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.client.handler;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.ConnectionTuneParameters;
-import org.apache.qpid.client.protocol.AMQProtocolSession;
-import org.apache.qpid.client.state.AMQState;
-import org.apache.qpid.client.state.StateAwareMethodListener;
-import org.apache.qpid.framing.*;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class ConnectionTuneMethodHandler implements StateAwareMethodListener<ConnectionTuneBody>
-{
- private static final Logger _logger = LoggerFactory.getLogger(ConnectionTuneMethodHandler.class);
-
- private static final ConnectionTuneMethodHandler _instance = new ConnectionTuneMethodHandler();
-
- public static ConnectionTuneMethodHandler getInstance()
- {
- return _instance;
- }
-
- protected ConnectionTuneMethodHandler()
- { }
-
- public void methodReceived(AMQProtocolSession session, ConnectionTuneBody frame, int channelId)
- {
- _logger.debug("ConnectionTune frame received");
- final MethodRegistry methodRegistry = session.getMethodRegistry();
-
-
- ConnectionTuneParameters params = session.getConnectionTuneParameters();
- if (params == null)
- {
- params = new ConnectionTuneParameters();
- }
-
- int maxChannelNumber = frame.getChannelMax();
- //0 implies no limit, except that forced by protocol limitations (0xFFFF)
- params.setChannelMax(maxChannelNumber == 0 ? AMQProtocolSession.MAX_CHANNEL_MAX : maxChannelNumber);
-
- params.setFrameMax(frame.getFrameMax());
- params.setHeartbeat(Integer.getInteger("amqj.heartbeat.delay", frame.getHeartbeat()));
- session.setConnectionTuneParameters(params);
-
- session.getStateManager().changeState(AMQState.CONNECTION_NOT_OPENED);
-
- ConnectionTuneOkBody tuneOkBody = methodRegistry.createConnectionTuneOkBody(params.getChannelMax(),
- params.getFrameMax(),
- params.getHeartbeat());
- // Be aware of possible changes to parameter order as versions change.
- session.writeFrame(tuneOkBody.generateFrame(channelId));
-
- String host = session.getAMQConnection().getVirtualHost();
- AMQShortString virtualHost = new AMQShortString("/" + host);
-
- ConnectionOpenBody openBody = methodRegistry.createConnectionOpenBody(virtualHost,null,true);
-
- // Be aware of possible changes to parameter order as versions change.
- session.writeFrame(openBody.generateFrame(channelId));
- }
-
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/handler/ExchangeBoundOkMethodHandler.java b/java/client/src/main/java/org/apache/qpid/client/handler/ExchangeBoundOkMethodHandler.java
deleted file mode 100644
index 690d782b40..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/handler/ExchangeBoundOkMethodHandler.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.client.handler;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.protocol.AMQProtocolSession;
-import org.apache.qpid.client.state.StateAwareMethodListener;
-import org.apache.qpid.framing.ExchangeBoundOkBody;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * @author Apache Software Foundation
- */
-public class ExchangeBoundOkMethodHandler implements StateAwareMethodListener<ExchangeBoundOkBody>
-{
- private static final Logger _logger = LoggerFactory.getLogger(ExchangeBoundOkMethodHandler.class);
- private static final ExchangeBoundOkMethodHandler _instance = new ExchangeBoundOkMethodHandler();
-
- public static ExchangeBoundOkMethodHandler getInstance()
- {
- return _instance;
- }
-
- private ExchangeBoundOkMethodHandler()
- { }
-
- public void methodReceived(AMQProtocolSession session, ExchangeBoundOkBody body, int channelId)
- throws AMQException
- {
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Received Exchange.Bound-Ok message, response code: " + body.getReplyCode() + " text: "
- + body.getReplyText());
- }
- }
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/handler/QueueDeleteOkMethodHandler.java b/java/client/src/main/java/org/apache/qpid/client/handler/QueueDeleteOkMethodHandler.java
deleted file mode 100644
index 01d82c9b55..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/handler/QueueDeleteOkMethodHandler.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.client.handler;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.protocol.AMQProtocolSession;
-import org.apache.qpid.client.state.StateAwareMethodListener;
-import org.apache.qpid.framing.QueueDeleteOkBody;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * @author Apache Software Foundation
- */
-public class QueueDeleteOkMethodHandler implements StateAwareMethodListener<QueueDeleteOkBody>
-{
- private static final Logger _logger = LoggerFactory.getLogger(QueueDeleteOkMethodHandler.class);
- private static final QueueDeleteOkMethodHandler _instance = new QueueDeleteOkMethodHandler();
-
- public static QueueDeleteOkMethodHandler getInstance()
- {
- return _instance;
- }
-
- private QueueDeleteOkMethodHandler()
- { }
-
- public void methodReceived(AMQProtocolSession session, QueueDeleteOkBody body, int channelId)
- throws AMQException
- {
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Received Queue.Delete-Ok message, message count: " + body.getMessageCount());
- }
- }
-
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/AMQMessageDelegate.java b/java/client/src/main/java/org/apache/qpid/client/message/AMQMessageDelegate.java
deleted file mode 100644
index c2821591d8..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/message/AMQMessageDelegate.java
+++ /dev/null
@@ -1,140 +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.client.message;
-
-import org.apache.qpid.client.AMQSession;
-
-import javax.jms.Destination;
-import javax.jms.JMSException;
-
-import java.nio.ByteBuffer;
-import java.util.Enumeration;
-import java.util.Map;
-import java.util.UUID;
-
-public interface AMQMessageDelegate
-{
- void acknowledgeThis() throws JMSException;
-
- String getJMSMessageID() throws JMSException;
-
- void setJMSMessageID(String string) throws JMSException;
-
- long getJMSTimestamp() throws JMSException;
-
- void setJMSTimestamp(long l) throws JMSException;
-
- byte[] getJMSCorrelationIDAsBytes() throws JMSException;
-
- void setJMSCorrelationIDAsBytes(byte[] bytes) throws JMSException;
-
- void setJMSCorrelationID(String string) throws JMSException;
-
- String getJMSCorrelationID() throws JMSException;
-
- Destination getJMSReplyTo() throws JMSException;
-
- void setJMSReplyTo(Destination destination) throws JMSException;
-
- Destination getJMSDestination() throws JMSException;
-
- int getJMSDeliveryMode() throws JMSException;
-
- void setJMSDeliveryMode(int i) throws JMSException;
-
- String getJMSType() throws JMSException;
-
- void setJMSType(String string) throws JMSException;
-
- long getJMSExpiration() throws JMSException;
-
- void setJMSExpiration(long l) throws JMSException;
-
- int getJMSPriority() throws JMSException;
-
- void setJMSPriority(int i) throws JMSException;
-
- void clearProperties() throws JMSException;
-
- boolean propertyExists(String string) throws JMSException;
-
- boolean getBooleanProperty(String string) throws JMSException;
-
- byte getByteProperty(String string) throws JMSException;
-
- short getShortProperty(String string) throws JMSException;
-
- int getIntProperty(String string) throws JMSException;
-
- long getLongProperty(String string) throws JMSException;
-
- float getFloatProperty(String string) throws JMSException;
-
- double getDoubleProperty(String string) throws JMSException;
-
- String getStringProperty(String string) throws JMSException;
-
- Object getObjectProperty(String string) throws JMSException;
-
- Enumeration getPropertyNames() throws JMSException;
-
- void setBooleanProperty(String string, boolean b) throws JMSException;
-
- void setByteProperty(String string, byte b) throws JMSException;
-
- void setShortProperty(String string, short i) throws JMSException;
-
- void setIntProperty(String string, int i) throws JMSException;
-
- void setLongProperty(String string, long l) throws JMSException;
-
- void setFloatProperty(String string, float v) throws JMSException;
-
- void setDoubleProperty(String string, double v) throws JMSException;
-
- void setStringProperty(String string, String string1) throws JMSException;
-
- void setObjectProperty(String string, Object object) throws JMSException;
-
- void acknowledge() throws JMSException;
-
- public void setJMSDestination(Destination destination);
-
- public void setContentType(String contentType);
- public String getContentType();
-
- public void setEncoding(String encoding);
- public String getEncoding();
-
-
- String getReplyToString();
-
- void removeProperty(final String propertyName) throws JMSException;
-
- void setAMQSession(final AMQSession s);
-
- AMQSession getAMQSession();
-
- long getDeliveryTag();
-
- void setJMSMessageID(final UUID messageId) throws JMSException;
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/AMQMessageDelegateFactory.java b/java/client/src/main/java/org/apache/qpid/client/message/AMQMessageDelegateFactory.java
deleted file mode 100644
index 8c3f2fd08f..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/message/AMQMessageDelegateFactory.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.qpid.client.message;
-
-import org.apache.mina.common.ByteBuffer;
-import org.apache.qpid.framing.BasicContentHeaderProperties;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.AMQException;
-
-public interface AMQMessageDelegateFactory<D extends AMQMessageDelegate>
-{
- public static AMQMessageDelegateFactory DEFAULT_FACTORY = null;
-
- public static AMQMessageDelegateFactory<AMQMessageDelegate_0_8> FACTORY_0_8 =
- new AMQMessageDelegateFactory<AMQMessageDelegate_0_8>()
- {
- public AMQMessageDelegate_0_8 createDelegate()
- {
- return new AMQMessageDelegate_0_8();
- }
- };
-
- public static AMQMessageDelegateFactory<AMQMessageDelegate_0_10> FACTORY_0_10 =
- new AMQMessageDelegateFactory<AMQMessageDelegate_0_10>()
- {
- public AMQMessageDelegate_0_10 createDelegate()
- {
- return new AMQMessageDelegate_0_10();
- }
- };
-
-
- public D createDelegate();
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/AMQMessageDelegate_0_10.java b/java/client/src/main/java/org/apache/qpid/client/message/AMQMessageDelegate_0_10.java
deleted file mode 100644
index fb7b191656..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/message/AMQMessageDelegate_0_10.java
+++ /dev/null
@@ -1,980 +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.client.message;
-
-import java.lang.ref.SoftReference;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.UUID;
-
-import javax.jms.DeliveryMode;
-import javax.jms.Destination;
-import javax.jms.JMSException;
-import javax.jms.MessageFormatException;
-import javax.jms.MessageNotWriteableException;
-import javax.jms.Session;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.AMQPInvalidClassException;
-import org.apache.qpid.client.AMQDestination;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.client.AMQSession_0_10;
-import org.apache.qpid.client.CustomJMSXProperty;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.jms.Message;
-import org.apache.qpid.transport.DeliveryProperties;
-import org.apache.qpid.transport.ExchangeQueryResult;
-import org.apache.qpid.transport.Future;
-import org.apache.qpid.transport.Header;
-import org.apache.qpid.transport.MessageDeliveryMode;
-import org.apache.qpid.transport.MessageDeliveryPriority;
-import org.apache.qpid.transport.MessageProperties;
-import org.apache.qpid.transport.ReplyTo;
-
-/**
- * This extends AbstractAMQMessageDelegate which contains common code between
- * both the 0_8 and 0_10 Message types.
- *
- */
-public class AMQMessageDelegate_0_10 extends AbstractAMQMessageDelegate
-{
- private static final Map<ReplyTo, SoftReference<Destination>> _destinationCache = Collections.synchronizedMap(new HashMap<ReplyTo, SoftReference<Destination>>());
-
- public static final String JMS_TYPE = "x-jms-type";
-
-
- private boolean _readableProperties = false;
-
- private Destination _destination;
-
-
- private MessageProperties _messageProps;
- private DeliveryProperties _deliveryProps;
- /** If the acknowledge mode is CLIENT_ACKNOWLEDGE the session is required */
- private AMQSession _session;
- private final long _deliveryTag;
-
-
- protected AMQMessageDelegate_0_10()
- {
- this(new MessageProperties(), new DeliveryProperties(), -1);
- _readableProperties = false;
- }
-
- protected AMQMessageDelegate_0_10(MessageProperties messageProps, DeliveryProperties deliveryProps, long deliveryTag)
- {
- _messageProps = messageProps;
- _deliveryProps = deliveryProps;
- _deliveryTag = deliveryTag;
- _readableProperties = (_messageProps != null);
-
- AMQDestination dest;
-
- dest = generateDestination(new AMQShortString(_deliveryProps.getExchange()),
- new AMQShortString(_deliveryProps.getRoutingKey()));
- setJMSDestination(dest);
- }
-
- /**
- * Use the 0-10 ExchangeQuery call to validate the exchange type.
- *
- * This is used primarily to provide the correct JMSDestination value.
- *
- * The query is performed synchronously iff the map exchange is not already
- * present in the exchange Map.
- *
- * @param header The message headers, from which the exchange name can be extracted
- * @param session The 0-10 session to use to call ExchangeQuery
- */
- public static void updateExchangeTypeMapping(Header header, org.apache.qpid.transport.Session session)
- {
- DeliveryProperties deliveryProps = header.get(DeliveryProperties.class);
- if (deliveryProps != null)
- {
- String exchange = deliveryProps.getExchange();
- checkAndUpdateExchange(exchange,session);
-
- }
-
- MessageProperties msgProps = header.get(MessageProperties.class);
- if (msgProps != null && msgProps.getReplyTo() != null)
- {
- String exchange = msgProps.getReplyTo().getExchange();
- checkAndUpdateExchange(exchange,session);
-
- }
- }
-
- private static void checkAndUpdateExchange(String exchange, org.apache.qpid.transport.Session session)
- {
- if (exchange != null && !exchangeMapContains(exchange))
- {
- Future<ExchangeQueryResult> future =
- session.exchangeQuery(exchange.toString());
- ExchangeQueryResult res = future.get();
-
- updateExchangeType(exchange, res.getType());
- }
- }
-
-
- public String getJMSMessageID() throws JMSException
- {
- UUID id = _messageProps.getMessageId();
- return id == null ? null : "ID:" + id;
- }
-
- public void setJMSMessageID(String messageId) throws JMSException
- {
- if(messageId == null)
- {
- _messageProps.clearMessageId();
- }
- else
- {
- if(messageId.startsWith("ID:"))
- {
- try
- {
- _messageProps.setMessageId(UUID.fromString(messageId.substring(3)));
- }
- catch(IllegalArgumentException ex)
- {
- throw new JMSException("MessageId '"+messageId+"' is not of the correct format, it must be ID: followed by a UUID");
- }
- }
- else
- {
- throw new JMSException("MessageId '"+messageId+"' is not of the correct format, it must be ID: followed by a UUID");
- }
- }
- }
-
- public void setJMSMessageID(UUID messageId) throws JMSException
- {
- if(messageId == null)
- {
- _messageProps.clearMessageId();
- }
- else
- {
- _messageProps.setMessageId(messageId);
- }
- }
-
-
- public long getJMSTimestamp() throws JMSException
- {
- return _deliveryProps.getTimestamp();
- }
-
- public void setJMSTimestamp(long timestamp) throws JMSException
- {
- _deliveryProps.setTimestamp(timestamp);
- }
-
- public byte[] getJMSCorrelationIDAsBytes() throws JMSException
- {
- return _messageProps.getCorrelationId();
- }
-
- public void setJMSCorrelationIDAsBytes(byte[] bytes) throws JMSException
- {
- _messageProps.setCorrelationId(bytes);
- }
-
- public void setJMSCorrelationID(String correlationId) throws JMSException
- {
-
- setJMSCorrelationIDAsBytes(correlationId == null ? null : correlationId.getBytes());
- }
-
- public String getJMSCorrelationID() throws JMSException
- {
-
- byte[] correlationIDAsBytes = getJMSCorrelationIDAsBytes();
- return correlationIDAsBytes == null ? null : new String(correlationIDAsBytes);
- }
-
- public Destination getJMSReplyTo()
- {
- ReplyTo replyTo = _messageProps.getReplyTo();
-
- if (replyTo == null)
- {
- return null;
- }
- else
- {
- Destination dest = null;
- SoftReference<Destination> ref = _destinationCache.get(replyTo);
- if (ref != null)
- {
- dest = ref.get();
- }
- if (dest == null)
- {
- String exchange = replyTo.getExchange();
- String routingKey = replyTo.getRoutingKey();
-
- dest = generateDestination(new AMQShortString(exchange), new AMQShortString(routingKey));
- _destinationCache.put(replyTo, new SoftReference<Destination>(dest));
- }
-
- return dest;
- }
- }
-
- public void setJMSReplyTo(Destination destination) throws JMSException
- {
- if (destination == null)
- {
- _messageProps.setReplyTo(null);
- return;
- }
-
- if (!(destination instanceof AMQDestination))
- {
- throw new IllegalArgumentException(
- "ReplyTo destination may only be an AMQDestination - passed argument was type " + destination.getClass());
- }
-
- final AMQDestination amqd = (AMQDestination) destination;
-
- if (amqd.getDestSyntax() == AMQDestination.DestSyntax.ADDR)
- {
- try
- {
- int type = ((AMQSession_0_10)_session).resolveAddressType(amqd);
- if (type == AMQDestination.QUEUE_TYPE)
- {
- ((AMQSession_0_10)_session).setLegacyFiledsForQueueType(amqd);
- }
- else
- {
- ((AMQSession_0_10)_session).setLegacyFiledsForTopicType(amqd);
- }
- }
- catch(AMQException ex)
- {
- JMSException e = new JMSException("Error occured while figuring out the node type");
- e.initCause(ex);
- e.setLinkedException(ex);
- throw e;
- }
- }
-
- final ReplyTo replyTo = new ReplyTo(amqd.getExchangeName().toString(), amqd.getRoutingKey().toString());
- _destinationCache.put(replyTo, new SoftReference<Destination>(destination));
- _messageProps.setReplyTo(replyTo);
-
- }
-
- public Destination getJMSDestination() throws JMSException
- {
- return _destination;
- }
-
- public void setJMSDestination(Destination destination)
- {
- _destination = destination;
- }
-
- public void setContentType(String contentType)
- {
- _messageProps.setContentType(contentType);
- }
-
- public String getContentType()
- {
- return _messageProps.getContentType();
- }
-
- public void setEncoding(String encoding)
- {
- if(encoding == null || encoding.length() == 0)
- {
- _messageProps.clearContentEncoding();
- }
- else
- {
- _messageProps.setContentEncoding(encoding);
- }
- }
-
- public String getEncoding()
- {
- return _messageProps.getContentEncoding();
- }
-
- public String getReplyToString()
- {
- Destination replyTo = getJMSReplyTo();
- if(replyTo != null)
- {
- return ((AMQDestination)replyTo).toURL();
- }
- else
- {
- return null;
- }
-
- }
-
- public int getJMSDeliveryMode() throws JMSException
- {
-
- MessageDeliveryMode deliveryMode = _deliveryProps.getDeliveryMode();
- if(deliveryMode != null)
- {
- switch(deliveryMode)
- {
- case PERSISTENT :
- return DeliveryMode.PERSISTENT;
- case NON_PERSISTENT:
- return DeliveryMode.NON_PERSISTENT;
- default:
- throw new JMSException("Unknown Message Delivery Mode: " + _deliveryProps.getDeliveryMode());
- }
- }
- else
- {
- return Message.DEFAULT_DELIVERY_MODE;
- }
-
- }
-
- public void setJMSDeliveryMode(int deliveryMode) throws JMSException
- {
- switch(deliveryMode)
- {
- case DeliveryMode.PERSISTENT:
- _deliveryProps.setDeliveryMode(MessageDeliveryMode.PERSISTENT);
- break;
- case DeliveryMode.NON_PERSISTENT:
- _deliveryProps.setDeliveryMode(MessageDeliveryMode.NON_PERSISTENT);
- break;
- default:
- throw new JMSException("Unknown JMS Delivery Mode: " + deliveryMode);
- }
-
- }
-
-
- public String getJMSType() throws JMSException
- {
- if(getApplicationHeaders().containsKey(JMS_TYPE))
- {
- return getStringProperty(JMS_TYPE);
- }
- else
- {
- return null;
- }
- }
-
- private Map<String, Object> getApplicationHeaders()
- {
- Map<String, Object> map = _messageProps.getApplicationHeaders();
- return map == null ? Collections.EMPTY_MAP : map;
- }
-
- public void setJMSType(String type) throws JMSException
- {
- Map<String, Object> headers = _messageProps.getApplicationHeaders();
- if(type == null)
- {
- if(headers != null)
- {
- headers.remove(JMS_TYPE);
- }
- }
- else
- {
- if(headers == null)
- {
- headers = new HashMap<String,Object>();
- _messageProps.setApplicationHeaders(headers);
-
- }
- headers.put(JMS_TYPE, type);
- }
- }
-
- public long getJMSExpiration() throws JMSException
- {
- return _deliveryProps.getExpiration();
- }
-
- public void setJMSExpiration(long l) throws JMSException
- {
- _deliveryProps.setExpiration(l);
- }
-
-
-
- public boolean propertyExists(String propertyName) throws JMSException
- {
- return getApplicationHeaders().containsKey(propertyName);
- }
-
- public boolean getBooleanProperty(String propertyName) throws JMSException
- {
- checkPropertyName(propertyName);
-
- Object o = getApplicationHeaders().get(propertyName);
-
- if(o instanceof Boolean)
- {
- return ((Boolean)o).booleanValue();
- }
- else if(o instanceof String)
- {
- return Boolean.valueOf((String) o).booleanValue();
- }
- else if(getApplicationHeaders().containsKey(propertyName))
- {
- throw new MessageFormatException("getBooleanProperty(\""+propertyName+"\") failed as value is not boolean: " + o);
- }
- else
- {
- return Boolean.valueOf(null);
- }
- }
-
- public byte getByteProperty(String propertyName) throws JMSException
- {
- checkPropertyName(propertyName);
-
- Map<String, Object> propertyMap = getApplicationHeaders();
-
- Object o = propertyMap.get(propertyName);
-
- if(o instanceof Byte)
- {
- return ((Byte)o).byteValue();
- }
- else if(o instanceof String)
- {
- return Byte.valueOf((String) o).byteValue();
- }
- else if(getApplicationHeaders().containsKey(propertyName))
- {
- throw new MessageFormatException("getByteProperty(\""+propertyName+"\") failed as value is not a byte: " + o);
- }
- else
- {
- return Byte.valueOf(null);
- }
- }
-
- public short getShortProperty(String propertyName) throws JMSException
- {
- checkPropertyName(propertyName);
-
- Map<String, Object> propertyMap = getApplicationHeaders();
-
- Object o = propertyMap.get(propertyName);
-
- if(o instanceof Short)
- {
- return ((Short)o).shortValue();
- }
- else
- {
- try
- {
- return Short.valueOf(getByteProperty(propertyName));
- }
- catch(MessageFormatException e)
- {
- throw new MessageFormatException("getShortProperty(\""+propertyName+"\") failed as value is not a short: " + o);
- }
- }
-
-
- }
-
- public int getIntProperty(String propertyName) throws JMSException
- {
- checkPropertyName(propertyName);
-
- Map<String, Object> propertyMap = getApplicationHeaders();
-
- Object o = propertyMap.get(propertyName);
-
- if(o instanceof Integer)
- {
- return ((Integer)o).intValue();
- }
- else
- {
- try
- {
- return Integer.valueOf(getShortProperty(propertyName));
- }
- catch(MessageFormatException e)
- {
- throw new MessageFormatException("getIntProperty(\""+propertyName+"\") failed as value is not an int: " + o);
- }
-
- }
- }
-
- public long getLongProperty(String propertyName) throws JMSException
- {
- checkPropertyName(propertyName);
-
- Map<String, Object> propertyMap = getApplicationHeaders();
-
- Object o = propertyMap.get(propertyName);
-
- if(o instanceof Long)
- {
- return ((Long)o).longValue();
- }
- else
- {
- try
- {
- return Long.valueOf(getIntProperty(propertyName));
- }
- catch(MessageFormatException e)
- {
- throw new MessageFormatException("getLongProperty(\""+propertyName+"\") failed as value is not a long: " + o);
- }
-
- }
- }
-
- public float getFloatProperty(String propertyName) throws JMSException
- {
- checkPropertyName(propertyName);
- Map<String, Object> propertyMap = getApplicationHeaders();
-
- Object o = propertyMap.get(propertyName);
-
- if(o instanceof Float)
- {
- return ((Float)o).floatValue();
- }
- else if(o instanceof String)
- {
- return Float.valueOf((String) o).floatValue();
- }
- else if(getApplicationHeaders().containsKey(propertyName))
- {
- throw new MessageFormatException("getFloatProperty(\""+propertyName+"\") failed as value is not a float: " + o);
- }
- else
- {
- throw new NullPointerException("No such property: " + propertyName);
- }
-
- }
-
- public double getDoubleProperty(String propertyName) throws JMSException
- {
- checkPropertyName(propertyName);
-
- Map<String, Object> propertyMap = getApplicationHeaders();
-
- Object o = propertyMap.get(propertyName);
-
- if(o instanceof Double)
- {
- return ((Double)o).doubleValue();
- }
- else if (o instanceof String)
- {
- return Double.valueOf((String)o);
- }
- else
- {
- try
- {
- return Double.valueOf(getFloatProperty(propertyName));
- }
- catch(MessageFormatException e)
- {
- throw new MessageFormatException("getDoubleProperty(\""+propertyName+"\") failed as value is not a double: " + o);
- }
-
- }
- }
-
- public String getStringProperty(String propertyName) throws JMSException
- {
- if (propertyName.equals(CustomJMSXProperty.JMSXUserID.toString()))
- {
- return new String(_messageProps.getUserId());
- }
- else
- {
- checkPropertyName(propertyName);
- Map<String, Object> propertyMap = getApplicationHeaders();
-
- Object o = propertyMap.get(propertyName);
-
- if(o instanceof String)
- {
- return (String) o;
- }
- else if(o == null)
- {
- return null;
- }
- else if(o.getClass().isArray())
- {
- throw new MessageFormatException("getString(\""+propertyName+"\") failed as value of type " + o.getClass()+ " is an array.");
- }
- else
- {
- return String.valueOf(o);
- }
-
- }
- }
-
- public Object getObjectProperty(String propertyName) throws JMSException
- {
- checkPropertyName(propertyName);
- Map<String, Object> propertyMap = getApplicationHeaders();
-
- return propertyMap.get(propertyName);
-
- }
-
- public Enumeration getPropertyNames() throws JMSException
- {
- List<String> props = new ArrayList<String>();
- Map<String, Object> propertyMap = getApplicationHeaders();
- for (String prop: getApplicationHeaders().keySet())
- {
- Object value = propertyMap.get(prop);
- if (value instanceof Boolean || value instanceof Number
- || value instanceof String)
- {
- props.add(prop);
- }
- }
-
- return java.util.Collections.enumeration(props);
- }
-
- public void setBooleanProperty(String propertyName, boolean b) throws JMSException
- {
- checkPropertyName(propertyName);
- checkWritableProperties();
- setApplicationHeader(propertyName, b);
- }
-
- public void setByteProperty(String propertyName, byte b) throws JMSException
- {
- checkPropertyName(propertyName);
- checkWritableProperties();
- setApplicationHeader(propertyName, b);
- }
-
- public void setShortProperty(String propertyName, short i) throws JMSException
- {
- checkPropertyName(propertyName);
- checkWritableProperties();
- setApplicationHeader(propertyName, i);
- }
-
- public void setIntProperty(String propertyName, int i) throws JMSException
- {
- checkPropertyName(propertyName);
- checkWritableProperties();
- setApplicationHeader(propertyName, i);
- }
-
- public void setLongProperty(String propertyName, long l) throws JMSException
- {
- checkPropertyName(propertyName);
- checkWritableProperties();
- setApplicationHeader(propertyName, l);
- }
-
- public void setFloatProperty(String propertyName, float f) throws JMSException
- {
- checkPropertyName(propertyName);
- checkWritableProperties();
- setApplicationHeader(propertyName, f);
- }
-
- public void setDoubleProperty(String propertyName, double v) throws JMSException
- {
- checkPropertyName(propertyName);
- checkWritableProperties();
- setApplicationHeader(propertyName, v);
- }
-
- public void setStringProperty(String propertyName, String value) throws JMSException
- {
- checkPropertyName(propertyName);
- checkWritableProperties();
- setApplicationHeader(propertyName, value);
- }
-
- private static final Set<Class> ALLOWED = new HashSet();
- static
- {
- ALLOWED.add(Boolean.class);
- ALLOWED.add(Byte.class);
- ALLOWED.add(Short.class);
- ALLOWED.add(Integer.class);
- ALLOWED.add(Long.class);
- ALLOWED.add(Float.class);
- ALLOWED.add(Double.class);
- ALLOWED.add(Character.class);
- ALLOWED.add(String.class);
- ALLOWED.add(byte[].class);
- }
-
- public void setObjectProperty(String propertyName, Object object) throws JMSException
- {
- checkPropertyName(propertyName);
- checkWritableProperties();
- if (object == null)
- {
- throw new MessageFormatException(AMQPInvalidClassException.INVALID_OBJECT_MSG + "null");
- }
- else if (!ALLOWED.contains(object.getClass()))
- {
- throw new MessageFormatException(AMQPInvalidClassException.INVALID_OBJECT_MSG + object.getClass());
- }
- setApplicationHeader(propertyName, object);
- }
-
- private void setApplicationHeader(String propertyName, Object object)
- {
- Map<String, Object> headers = _messageProps.getApplicationHeaders();
- if(headers == null)
- {
- headers = new HashMap<String,Object>();
- _messageProps.setApplicationHeaders(headers);
- }
- headers.put(propertyName, object);
- }
-
- public void removeProperty(String propertyName) throws JMSException
- {
- Map<String, Object> headers = _messageProps.getApplicationHeaders();
- if(headers != null)
- {
- headers.remove(propertyName);
- }
- }
-
-
-
- protected void checkWritableProperties() throws MessageNotWriteableException
- {
- if (_readableProperties)
- {
- throw new MessageNotWriteableException("You need to call clearProperties() to make the message writable");
- }
- }
-
-
- public int getJMSPriority() throws JMSException
- {
- MessageDeliveryPriority messageDeliveryPriority = _deliveryProps.getPriority();
- return messageDeliveryPriority == null ? Message.DEFAULT_PRIORITY : messageDeliveryPriority.getValue();
- }
-
- public void setJMSPriority(int i) throws JMSException
- {
- _deliveryProps.setPriority(MessageDeliveryPriority.get((short)i));
- }
-
- public void clearProperties() throws JMSException
- {
- if(!getApplicationHeaders().isEmpty())
- {
- getApplicationHeaders().clear();
- }
-
- _readableProperties = false;
- }
-
-
- public void acknowledgeThis() throws JMSException
- {
- // the JMS 1.1 spec says in section 3.6 that calls to acknowledge are ignored when client acknowledge
- // is not specified. In our case, we only set the session field where client acknowledge mode is specified.
- if (_session != null && _session.getAcknowledgeMode() == Session.CLIENT_ACKNOWLEDGE)
- {
- if (_session.getAMQConnection().isClosed())
- {
- throw new javax.jms.IllegalStateException("Connection is already closed");
- }
-
- // we set multiple to true here since acknowledgment implies acknowledge of all previous messages
- // received on the session
- _session.acknowledgeMessage(_deliveryTag, true);
- }
- }
-
- public void acknowledge() throws JMSException
- {
- if (_session != null && _session.getAcknowledgeMode() == Session.CLIENT_ACKNOWLEDGE)
- {
- _session.acknowledge();
- }
- }
-
-
- /**
- * The session is set when CLIENT_ACKNOWLEDGE mode is used so that the CHANNEL ACK can be sent when the user calls
- * acknowledge()
- *
- * @param s the AMQ session that delivered this message
- */
- public void setAMQSession(AMQSession s)
- {
- _session = s;
- }
-
- public AMQSession getAMQSession()
- {
- return _session;
- }
-
- /**
- * Get the AMQ message number assigned to this message
- *
- * @return the message number
- */
- public long getDeliveryTag()
- {
- return _deliveryTag;
- }
-
-
-
-
-
-
- protected void checkPropertyName(CharSequence propertyName)
- {
- if (propertyName == null)
- {
- throw new IllegalArgumentException("Property name must not be null");
- }
- else if (propertyName.length() == 0)
- {
- throw new IllegalArgumentException("Property name must not be the empty string");
- }
-
- checkIdentiferFormat(propertyName);
- }
-
- protected void checkIdentiferFormat(CharSequence propertyName)
- {
-// JMS requirements 3.5.1 Property Names
-// Identifiers:
-// - An identifier is an unlimited-length character sequence that must begin
-// with a Java identifier start character; all following characters must be Java
-// identifier part characters. An identifier start character is any character for
-// which the method Character.isJavaIdentifierStart returns true. This includes
-// '_' and '$'. An identifier part character is any character for which the
-// method Character.isJavaIdentifierPart returns true.
-// - Identifiers cannot be the names NULL, TRUE, or FALSE.
-// Identifiers cannot be NOT, AND, OR, BETWEEN, LIKE, IN, IS, or
-// ESCAPE.
-// Identifiers are either header field references or property references. The
-// type of a property value in a message selector corresponds to the type
-// used to set the property. If a property that does not exist in a message is
-// referenced, its value is NULL. The semantics of evaluating NULL values
-// in a selector are described in Section 3.8.1.2, Null Values.
-// The conversions that apply to the get methods for properties do not
-// apply when a property is used in a message selector expression. For
-// example, suppose you set a property as a string value, as in the
-// following:
-// myMessage.setStringProperty("NumberOfOrders", "2");
-// The following expression in a message selector would evaluate to false,
-// because a string cannot be used in an arithmetic expression:
-// "NumberOfOrders > 1"
-// Identifiers are case sensitive.
-// Message header field references are restricted to JMSDeliveryMode,
-// JMSPriority, JMSMessageID, JMSTimestamp, JMSCorrelationID, and
-// JMSType. JMSMessageID, JMSCorrelationID, and JMSType values may be
-// null and if so are treated as a NULL value.
-
- if (Boolean.getBoolean("strict-jms"))
- {
- // JMS start character
- if (!(Character.isJavaIdentifierStart(propertyName.charAt(0))))
- {
- throw new IllegalArgumentException("Identifier '" + propertyName + "' does not start with a valid JMS identifier start character");
- }
-
- // JMS part character
- int length = propertyName.length();
- for (int c = 1; c < length; c++)
- {
- if (!(Character.isJavaIdentifierPart(propertyName.charAt(c))))
- {
- throw new IllegalArgumentException("Identifier '" + propertyName + "' contains an invalid JMS identifier character");
- }
- }
-
- // JMS invalid names
- if ((propertyName.equals("NULL")
- || propertyName.equals("TRUE")
- || propertyName.equals("FALSE")
- || propertyName.equals("NOT")
- || propertyName.equals("AND")
- || propertyName.equals("OR")
- || propertyName.equals("BETWEEN")
- || propertyName.equals("LIKE")
- || propertyName.equals("IN")
- || propertyName.equals("IS")
- || propertyName.equals("ESCAPE")))
- {
- throw new IllegalArgumentException("Identifier '" + propertyName + "' is not allowed in JMS");
- }
- }
-
- }
-
-
- public MessageProperties getMessageProperties()
- {
- return _messageProps;
- }
-
-
- public DeliveryProperties getDeliveryProperties()
- {
- return _deliveryProps;
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/AMQMessageDelegate_0_8.java b/java/client/src/main/java/org/apache/qpid/client/message/AMQMessageDelegate_0_8.java
deleted file mode 100644
index cec4268a7b..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/message/AMQMessageDelegate_0_8.java
+++ /dev/null
@@ -1,576 +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.client.message;
-
-import java.net.URISyntaxException;
-import java.util.Collections;
-import java.util.Enumeration;
-import java.util.Map;
-import java.util.UUID;
-
-import javax.jms.Destination;
-import javax.jms.JMSException;
-import javax.jms.MessageNotWriteableException;
-import javax.jms.Session;
-
-import org.apache.qpid.client.AMQDestination;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.client.AMQTopic;
-import org.apache.qpid.client.CustomJMSXProperty;
-import org.apache.qpid.client.JMSAMQException;
-import org.apache.qpid.collections.ReferenceMap;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.BasicContentHeaderProperties;
-import org.apache.qpid.framing.ContentHeaderProperties;
-import org.apache.qpid.url.AMQBindingURL;
-import org.apache.qpid.url.BindingURL;
-
-public class AMQMessageDelegate_0_8 extends AbstractAMQMessageDelegate
-{
- private static final Map _destinationCache = Collections.synchronizedMap(new ReferenceMap());
-
- public static final String JMS_TYPE = "x-jms-type";
-
-
- private boolean _readableProperties = false;
-
- private Destination _destination;
- private JMSHeaderAdapter _headerAdapter;
- private static final boolean STRICT_AMQP_COMPLIANCE =
- Boolean.parseBoolean(System.getProperties().getProperty(AMQSession.STRICT_AMQP, AMQSession.STRICT_AMQP_DEFAULT));
-
- private ContentHeaderProperties _contentHeaderProperties;
- /** If the acknowledge mode is CLIENT_ACKNOWLEDGE the session is required */
- private AMQSession _session;
- private final long _deliveryTag;
-
- // The base set of items that needs to be set.
- private AMQMessageDelegate_0_8(BasicContentHeaderProperties properties, long deliveryTag)
- {
- _contentHeaderProperties = properties;
- _deliveryTag = deliveryTag;
- _readableProperties = (_contentHeaderProperties != null);
- _headerAdapter = new JMSHeaderAdapter(_readableProperties ? ((BasicContentHeaderProperties) _contentHeaderProperties).getHeaders()
- : (new BasicContentHeaderProperties()).getHeaders() );
- }
-
- // Used for the creation of new messages
- protected AMQMessageDelegate_0_8()
- {
- this(new BasicContentHeaderProperties(), -1);
- _readableProperties = false;
- _headerAdapter = new JMSHeaderAdapter(((BasicContentHeaderProperties) _contentHeaderProperties).getHeaders());
-
- }
-
- // Used when generating a received message object
- protected AMQMessageDelegate_0_8(long deliveryTag, BasicContentHeaderProperties contentHeader, AMQShortString exchange,
- AMQShortString routingKey)
- {
- this(contentHeader, deliveryTag);
-
- Integer type = contentHeader.getHeaders().getInteger(CustomJMSXProperty.JMS_QPID_DESTTYPE.getShortStringName());
-
- AMQDestination dest = null;
-
- // If we have a type set the attempt to use that.
- if (type != null)
- {
- switch (type.intValue())
- {
- case AMQDestination.QUEUE_TYPE:
- dest = new AMQQueue(exchange, routingKey, routingKey);
- break;
- case AMQDestination.TOPIC_TYPE:
- dest = new AMQTopic(exchange, routingKey, null);
- break;
- default:
- // Use the generateDestination method
- dest = null;
- }
- }
-
- if (dest == null)
- {
- dest = generateDestination(exchange, routingKey);
- }
-
- setJMSDestination(dest);
- }
-
-
-
- public String getJMSMessageID() throws JMSException
- {
- return getContentHeaderProperties().getMessageIdAsString();
- }
-
- public void setJMSMessageID(String messageId) throws JMSException
- {
- if (messageId != null)
- {
- getContentHeaderProperties().setMessageId(messageId);
- }
- }
-
- public void setJMSMessageID(UUID messageId) throws JMSException
- {
- if (messageId != null)
- {
- getContentHeaderProperties().setMessageId("ID:" + messageId);
- }
- }
-
-
- public long getJMSTimestamp() throws JMSException
- {
- return getContentHeaderProperties().getTimestamp();
- }
-
- public void setJMSTimestamp(long timestamp) throws JMSException
- {
- getContentHeaderProperties().setTimestamp(timestamp);
- }
-
- public byte[] getJMSCorrelationIDAsBytes() throws JMSException
- {
- return getContentHeaderProperties().getCorrelationIdAsString().getBytes();
- }
-
- public void setJMSCorrelationIDAsBytes(byte[] bytes) throws JMSException
- {
- getContentHeaderProperties().setCorrelationId(new String(bytes));
- }
-
- public void setJMSCorrelationID(String correlationId) throws JMSException
- {
- getContentHeaderProperties().setCorrelationId(correlationId);
- }
-
- public String getJMSCorrelationID() throws JMSException
- {
- return getContentHeaderProperties().getCorrelationIdAsString();
- }
-
- public Destination getJMSReplyTo() throws JMSException
- {
- String replyToEncoding = getContentHeaderProperties().getReplyToAsString();
- if (replyToEncoding == null)
- {
- return null;
- }
- else
- {
- Destination dest = (Destination) _destinationCache.get(replyToEncoding);
- if (dest == null)
- {
- try
- {
- BindingURL binding = new AMQBindingURL(replyToEncoding);
- dest = AMQDestination.createDestination(binding);
- }
- catch (URISyntaxException e)
- {
- throw new JMSAMQException("Illegal value in JMS_ReplyTo property: " + replyToEncoding, e);
- }
-
- _destinationCache.put(replyToEncoding, dest);
- }
-
- return dest;
- }
- }
-
- public void setJMSReplyTo(Destination destination) throws JMSException
- {
- if (destination == null)
- {
- getContentHeaderProperties().setReplyTo((String) null);
- return; // We're done here
- }
-
- if (!(destination instanceof AMQDestination))
- {
- throw new IllegalArgumentException(
- "ReplyTo destination may only be an AMQDestination - passed argument was type " + destination.getClass());
- }
-
- final AMQDestination amqd = (AMQDestination) destination;
-
- final AMQShortString encodedDestination = amqd.getEncodedName();
- _destinationCache.put(encodedDestination, destination);
- getContentHeaderProperties().setReplyTo(encodedDestination);
- }
-
- public Destination getJMSDestination() throws JMSException
- {
- return _destination;
- }
-
- public void setJMSDestination(Destination destination)
- {
- _destination = destination;
- }
-
- public void setContentType(String contentType)
- {
- getContentHeaderProperties().setContentType(contentType);
- }
-
- public String getContentType()
- {
- return getContentHeaderProperties().getContentTypeAsString();
- }
-
- public void setEncoding(String encoding)
- {
- getContentHeaderProperties().setEncoding(encoding);
- }
-
- public String getEncoding()
- {
- return getContentHeaderProperties().getEncodingAsString();
- }
-
- public String getReplyToString()
- {
- return getContentHeaderProperties().getReplyToAsString();
- }
-
- public int getJMSDeliveryMode() throws JMSException
- {
- return getContentHeaderProperties().getDeliveryMode();
- }
-
- public void setJMSDeliveryMode(int i) throws JMSException
- {
- getContentHeaderProperties().setDeliveryMode((byte) i);
- }
-
- public BasicContentHeaderProperties getContentHeaderProperties()
- {
- return (BasicContentHeaderProperties) _contentHeaderProperties;
- }
-
-
- public String getJMSType() throws JMSException
- {
- return getContentHeaderProperties().getTypeAsString();
- }
-
- public void setJMSType(String string) throws JMSException
- {
- getContentHeaderProperties().setType(string);
- }
-
- public long getJMSExpiration() throws JMSException
- {
- return getContentHeaderProperties().getExpiration();
- }
-
- public void setJMSExpiration(long l) throws JMSException
- {
- getContentHeaderProperties().setExpiration(l);
- }
-
-
-
- public boolean propertyExists(String propertyName) throws JMSException
- {
- return getJmsHeaders().propertyExists(propertyName);
- }
-
- public boolean getBooleanProperty(String propertyName) throws JMSException
- {
- if (STRICT_AMQP_COMPLIANCE)
- {
- throw new UnsupportedOperationException("JMS Proprerties not supported in AMQP");
- }
-
- return getJmsHeaders().getBoolean(propertyName);
- }
-
- public byte getByteProperty(String propertyName) throws JMSException
- {
- if (STRICT_AMQP_COMPLIANCE)
- {
- throw new UnsupportedOperationException("JMS Proprerties not supported in AMQP");
- }
-
- return getJmsHeaders().getByte(propertyName);
- }
-
- public short getShortProperty(String propertyName) throws JMSException
- {
- if (STRICT_AMQP_COMPLIANCE)
- {
- throw new UnsupportedOperationException("JMS Proprerties not supported in AMQP");
- }
-
- return getJmsHeaders().getShort(propertyName);
- }
-
- public int getIntProperty(String propertyName) throws JMSException
- {
- if (STRICT_AMQP_COMPLIANCE)
- {
- throw new UnsupportedOperationException("JMS Proprerties not supported in AMQP");
- }
-
- return getJmsHeaders().getInteger(propertyName);
- }
-
- public long getLongProperty(String propertyName) throws JMSException
- {
- if (STRICT_AMQP_COMPLIANCE)
- {
- throw new UnsupportedOperationException("JMS Proprerties not supported in AMQP");
- }
-
- return getJmsHeaders().getLong(propertyName);
- }
-
- public float getFloatProperty(String propertyName) throws JMSException
- {
- if (STRICT_AMQP_COMPLIANCE)
- {
- throw new UnsupportedOperationException("JMS Proprerties not supported in AMQP");
- }
-
- return getJmsHeaders().getFloat(propertyName);
- }
-
- public double getDoubleProperty(String propertyName) throws JMSException
- {
- if (STRICT_AMQP_COMPLIANCE)
- {
- throw new UnsupportedOperationException("JMS Proprerties not supported in AMQP");
- }
-
- return getJmsHeaders().getDouble(propertyName);
- }
-
- public String getStringProperty(String propertyName) throws JMSException
- {
- //NOTE: if the JMSX Property is a non AMQP property then we must check _strictAMQP and throw as below.
- if (propertyName.equals(CustomJMSXProperty.JMSXUserID.toString()))
- {
- return ((BasicContentHeaderProperties) _contentHeaderProperties).getUserIdAsString();
- }
- else
- {
- if (STRICT_AMQP_COMPLIANCE)
- {
- throw new UnsupportedOperationException("JMS Proprerties not supported in AMQP");
- }
-
- return getJmsHeaders().getString(propertyName);
- }
- }
-
- public Object getObjectProperty(String propertyName) throws JMSException
- {
- return getJmsHeaders().getObject(propertyName);
- }
-
- public Enumeration getPropertyNames() throws JMSException
- {
- return getJmsHeaders().getPropertyNames();
- }
-
- public void setBooleanProperty(String propertyName, boolean b) throws JMSException
- {
- if (STRICT_AMQP_COMPLIANCE)
- {
- throw new UnsupportedOperationException("JMS Proprerties not supported in AMQP");
- }
-
- checkWritableProperties();
- getJmsHeaders().setBoolean(propertyName, b);
- }
-
- public void setByteProperty(String propertyName, byte b) throws JMSException
- {
- if (STRICT_AMQP_COMPLIANCE)
- {
- throw new UnsupportedOperationException("JMS Proprerties not supported in AMQP");
- }
-
- checkWritableProperties();
- getJmsHeaders().setByte(propertyName, new Byte(b));
- }
-
- public void setShortProperty(String propertyName, short i) throws JMSException
- {
- if (STRICT_AMQP_COMPLIANCE)
- {
- throw new UnsupportedOperationException("JMS Proprerties not supported in AMQP");
- }
-
- checkWritableProperties();
- getJmsHeaders().setShort(propertyName, new Short(i));
- }
-
- public void setIntProperty(String propertyName, int i) throws JMSException
- {
- checkWritableProperties();
- getJmsHeaders().setInteger(propertyName, new Integer(i));
- }
-
- public void setLongProperty(String propertyName, long l) throws JMSException
- {
- if (STRICT_AMQP_COMPLIANCE)
- {
- throw new UnsupportedOperationException("JMS Proprerties not supported in AMQP");
- }
-
- checkWritableProperties();
- getJmsHeaders().setLong(propertyName, new Long(l));
- }
-
- public void setFloatProperty(String propertyName, float f) throws JMSException
- {
- if (STRICT_AMQP_COMPLIANCE)
- {
- throw new UnsupportedOperationException("JMS Proprerties not supported in AMQP");
- }
-
- checkWritableProperties();
- getJmsHeaders().setFloat(propertyName, new Float(f));
- }
-
- public void setDoubleProperty(String propertyName, double v) throws JMSException
- {
- if (STRICT_AMQP_COMPLIANCE)
- {
- throw new UnsupportedOperationException("JMS Proprerties not supported in AMQP");
- }
-
- checkWritableProperties();
- getJmsHeaders().setDouble(propertyName, new Double(v));
- }
-
- public void setStringProperty(String propertyName, String value) throws JMSException
- {
- checkWritableProperties();
- getJmsHeaders().setString(propertyName, value);
- }
-
- public void setObjectProperty(String propertyName, Object object) throws JMSException
- {
- checkWritableProperties();
- getJmsHeaders().setObject(propertyName, object);
- }
-
- public void removeProperty(String propertyName) throws JMSException
- {
- getJmsHeaders().remove(propertyName);
- }
-
-
- private JMSHeaderAdapter getJmsHeaders()
- {
- return _headerAdapter;
- }
-
- protected void checkWritableProperties() throws MessageNotWriteableException
- {
- if (_readableProperties)
- {
- throw new MessageNotWriteableException("You need to call clearProperties() to make the message writable");
- }
- _contentHeaderProperties.updated();
- }
-
-
- public int getJMSPriority() throws JMSException
- {
- return getContentHeaderProperties().getPriority();
- }
-
- public void setJMSPriority(int i) throws JMSException
- {
- getContentHeaderProperties().setPriority((byte) i);
- }
-
- public void clearProperties() throws JMSException
- {
- getJmsHeaders().clear();
-
- _readableProperties = false;
- }
-
-
- public void acknowledgeThis() throws JMSException
- {
- // the JMS 1.1 spec says in section 3.6 that calls to acknowledge are ignored when client acknowledge
- // is not specified. In our case, we only set the session field where client acknowledge mode is specified.
- if (_session != null && _session.getAcknowledgeMode() == Session.CLIENT_ACKNOWLEDGE)
- {
- if (_session.getAMQConnection().isClosed())
- {
- throw new javax.jms.IllegalStateException("Connection is already closed");
- }
-
- // we set multiple to true here since acknowledgement implies acknowledge of all previous messages
- // received on the session
- _session.acknowledgeMessage(_deliveryTag, true);
- }
- }
-
- public void acknowledge() throws JMSException
- {
- if (_session != null && _session.getAcknowledgeMode() == Session.CLIENT_ACKNOWLEDGE)
- {
- _session.acknowledge();
- }
- }
-
-
- /**
- * The session is set when CLIENT_ACKNOWLEDGE mode is used so that the CHANNEL ACK can be sent when the user calls
- * acknowledge()
- *
- * @param s the AMQ session that delivered this message
- */
- public void setAMQSession(AMQSession s)
- {
- _session = s;
- }
-
- public AMQSession getAMQSession()
- {
- return _session;
- }
-
- /**
- * Get the AMQ message number assigned to this message
- *
- * @return the message number
- */
- public long getDeliveryTag()
- {
- return _deliveryTag;
- }
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/AMQPEncodedMapMessage.java b/java/client/src/main/java/org/apache/qpid/client/message/AMQPEncodedMapMessage.java
deleted file mode 100644
index 58f108f1a4..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/message/AMQPEncodedMapMessage.java
+++ /dev/null
@@ -1,122 +0,0 @@
-package org.apache.qpid.client.message;
-/*
- *
- * 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 java.util.List;
-import java.util.Map;
-import java.util.UUID;
-
-import javax.jms.JMSException;
-import javax.jms.MessageFormatException;
-
-import org.apache.mina.common.ByteBuffer;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.transport.codec.BBDecoder;
-import org.apache.qpid.transport.codec.BBEncoder;
-
-public class AMQPEncodedMapMessage extends JMSMapMessage
-{
- public static final String MIME_TYPE = "amqp/map";
-
- public AMQPEncodedMapMessage(AMQMessageDelegateFactory delegateFactory) throws JMSException
- {
- this(delegateFactory, null);
- }
-
- AMQPEncodedMapMessage(AMQMessageDelegateFactory delegateFactory, ByteBuffer data) throws JMSException
- {
- super(delegateFactory, data);
- }
-
- AMQPEncodedMapMessage(AMQMessageDelegate delegate, ByteBuffer data) throws AMQException
- {
- super(delegate, data);
- }
-
- @ Override
- protected String getMimeType()
- {
- return MIME_TYPE;
- }
-
- @ Override
- public void setObject(String propName, Object value) throws JMSException
- {
- checkWritable();
- checkPropertyName(propName);
- if ((value instanceof Boolean) || (value instanceof Byte) || (value instanceof Short) || (value instanceof Integer)
- || (value instanceof Long) || (value instanceof Character) || (value instanceof Float)
- || (value instanceof Double) || (value instanceof String) || (value instanceof byte[])
- || (value instanceof List) || (value instanceof Map) || (value instanceof UUID) || (value == null))
- {
- _map.put(propName, value);
- }
- else
- {
- throw new MessageFormatException("Cannot set property " + propName + " to value " + value + "of type "
- + value.getClass().getName() + ".");
- }
- }
-
- // The super clas methods resets the buffer
- @ Override
- public ByteBuffer getData()
- {
- writeMapToData();
- return _data;
- }
-
- @ Override
- protected void populateMapFromData() throws JMSException
- {
- if (_data != null)
- {
- _data.rewind();
- BBDecoder decoder = new BBDecoder();
- decoder.init(_data.buf());
- _map = decoder.readMap();
- }
- else
- {
- _map.clear();
- }
- }
-
- @ Override
- protected void writeMapToData()
- {
- BBEncoder encoder = new BBEncoder(1024);
- encoder.writeMap(_map);
- _data = ByteBuffer.wrap(encoder.segment());
- }
-
- // for testing
- Map<String,Object> getMap()
- {
- return _map;
- }
-
- void setMap(Map<String,Object> map)
- {
- _map = map;
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/AMQPEncodedMapMessageFactory.java b/java/client/src/main/java/org/apache/qpid/client/message/AMQPEncodedMapMessageFactory.java
deleted file mode 100644
index 4978d1ce85..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/message/AMQPEncodedMapMessageFactory.java
+++ /dev/null
@@ -1,46 +0,0 @@
-package org.apache.qpid.client.message;
-/*
- *
- * 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 javax.jms.JMSException;
-
-import org.apache.mina.common.ByteBuffer;
-import org.apache.qpid.AMQException;
-
-public class AMQPEncodedMapMessageFactory extends AbstractJMSMessageFactory
-{
-
- @Override
- protected AbstractJMSMessage createMessage(AMQMessageDelegate delegate,
- ByteBuffer data) throws AMQException
- {
- return new AMQPEncodedMapMessage(delegate,data);
- }
-
- @Override
- public AbstractJMSMessage createMessage(
- AMQMessageDelegateFactory delegateFactory) throws JMSException
- {
- return new AMQPEncodedMapMessage(delegateFactory);
- }
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/AbstractAMQMessageDelegate.java b/java/client/src/main/java/org/apache/qpid/client/message/AbstractAMQMessageDelegate.java
deleted file mode 100644
index 89fbc9722c..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/message/AbstractAMQMessageDelegate.java
+++ /dev/null
@@ -1,206 +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.client.message;
-
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-import org.apache.qpid.client.AMQAnyDestination;
-import org.apache.qpid.client.AMQDestination;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.client.AMQTopic;
-import org.apache.qpid.exchange.ExchangeDefaults;
-import org.apache.qpid.framing.AMQShortString;
-
-/**
- * This abstract class provides exchange lookup functionality that is shared
- * between all MessageDelegates. Update facilities are provided so that the 0-10
- * code base can update the mappings. The 0-8 code base does not have the
- * facility to update the exchange map so it can only use the default mappings.
- *
- * That said any updates that a 0-10 client performs will also benefit any 0-8
- * connections in this VM.
- *
- */
-public abstract class AbstractAMQMessageDelegate implements AMQMessageDelegate
-{
-
- private static Map<String, Integer> _exchangeTypeToDestinationType = new ConcurrentHashMap<String, Integer>();
- private static Map<String,ExchangeInfo> _exchangeMap = new ConcurrentHashMap<String, ExchangeInfo>();
-
- /**
- * Add default Mappings for the Direct, Default, Topic and Fanout exchanges.
- */
- static
- {
- _exchangeTypeToDestinationType.put("", AMQDestination.QUEUE_TYPE);
- _exchangeTypeToDestinationType.put(ExchangeDefaults.DIRECT_EXCHANGE_CLASS.toString(), AMQDestination.QUEUE_TYPE);
- _exchangeTypeToDestinationType.put(ExchangeDefaults.TOPIC_EXCHANGE_CLASS.toString(), AMQDestination.TOPIC_TYPE);
- _exchangeTypeToDestinationType.put(ExchangeDefaults.FANOUT_EXCHANGE_CLASS.toString(), AMQDestination.TOPIC_TYPE);
- _exchangeTypeToDestinationType.put(ExchangeDefaults.HEADERS_EXCHANGE_CLASS.toString(), AMQDestination.QUEUE_TYPE);
-
- _exchangeMap.put("", new ExchangeInfo("","",AMQDestination.QUEUE_TYPE));
-
- _exchangeMap.put(ExchangeDefaults.DIRECT_EXCHANGE_NAME.toString(),
- new ExchangeInfo(ExchangeDefaults.DIRECT_EXCHANGE_NAME.toString(),
- ExchangeDefaults.DIRECT_EXCHANGE_CLASS.toString(),
- AMQDestination.QUEUE_TYPE));
-
- _exchangeMap.put(ExchangeDefaults.TOPIC_EXCHANGE_NAME.toString(),
- new ExchangeInfo(ExchangeDefaults.TOPIC_EXCHANGE_NAME.toString(),
- ExchangeDefaults.TOPIC_EXCHANGE_CLASS.toString(),
- AMQDestination.TOPIC_TYPE));
-
- _exchangeMap.put(ExchangeDefaults.FANOUT_EXCHANGE_NAME.toString(),
- new ExchangeInfo(ExchangeDefaults.FANOUT_EXCHANGE_NAME.toString(),
- ExchangeDefaults.FANOUT_EXCHANGE_CLASS.toString(),
- AMQDestination.TOPIC_TYPE));
-
- _exchangeMap.put(ExchangeDefaults.HEADERS_EXCHANGE_NAME.toString(),
- new ExchangeInfo(ExchangeDefaults.HEADERS_EXCHANGE_NAME.toString(),
- ExchangeDefaults.HEADERS_EXCHANGE_CLASS.toString(),
- AMQDestination.QUEUE_TYPE));
-
- }
-
- /**
- * Called when a Destination is requried.
- *
- * This will create the AMQDestination that is the correct type and value
- * based on the incomming values.
- * @param exchange The exchange name
- * @param routingKey The routing key to be used for the Destination
- * @return AMQDestination of the correct subtype
- */
- protected AMQDestination generateDestination(AMQShortString exchange, AMQShortString routingKey)
- {
- AMQDestination dest;
- ExchangeInfo exchangeInfo = _exchangeMap.get(exchange.asString());
-
- if (exchangeInfo == null)
- {
- exchangeInfo = new ExchangeInfo(exchange.asString(),"",AMQDestination.UNKNOWN_TYPE);
- }
-
- if ("topic".equals(exchangeInfo.exchangeType))
- {
- dest = new AMQTopic(exchange, routingKey, null);
- }
- else if ("direct".equals(exchangeInfo.exchangeType))
- {
- dest = new AMQQueue(exchange, routingKey, routingKey);
- }
- else
- {
- dest = new AMQAnyDestination(exchange,
- new AMQShortString(exchangeInfo.exchangeType),
- routingKey,
- false,
- false,
- routingKey,
- false,
- new AMQShortString[] {routingKey});
- }
-
- return dest;
- }
-
- /**
- * Update the exchange name to type mapping.
- *
- * If the newType is not known then an UNKNOWN_TYPE is created. Only if the
- * exchange is of a known type: amq.direct, amq.topic, amq.fanout can we
- * create a suitable AMQDestination representation
- *
- * @param exchange the name of the exchange
- * @param newtype the AMQP exchange class name i.e. direct
- */
- protected static void updateExchangeType(String exchange, String newtype)
- {
- Integer type = _exchangeTypeToDestinationType.get(newtype);
- if (type == null)
- {
- type = AMQDestination.UNKNOWN_TYPE;
- }
-
- _exchangeMap.put(exchange, new ExchangeInfo(exchange,newtype,type));
- }
-
- /**
- * Accessor method to allow lookups of the given exchange name.
- *
- * This check allows the prevention of extra work required such as asking
- * the broker for the exchange class name.
- *
- * @param exchange the exchange name to lookup
- * @return true if there is a mapping for this exchange
- */
- protected static boolean exchangeMapContains(String exchange)
- {
- return _exchangeMap.containsKey(exchange);
- }
-}
-
-class ExchangeInfo
-{
- String exchangeName;
- String exchangeType;
- int destType = AMQDestination.QUEUE_TYPE;
-
- public ExchangeInfo(String exchangeName, String exchangeType,
- int destType)
- {
- super();
- this.exchangeName = exchangeName;
- this.exchangeType = exchangeType;
- this.destType = destType;
- }
-
- public String getExchangeName()
- {
- return exchangeName;
- }
-
- public void setExchangeName(String exchangeName)
- {
- this.exchangeName = exchangeName;
- }
-
- public String getExchangeType()
- {
- return exchangeType;
- }
-
- public void setExchangeType(String exchangeType)
- {
- this.exchangeType = exchangeType;
- }
-
- public int getDestType()
- {
- return destType;
- }
-
- public void setDestType(int destType)
- {
- this.destType = destType;
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/AbstractBytesMessage.java b/java/client/src/main/java/org/apache/qpid/client/message/AbstractBytesMessage.java
deleted file mode 100644
index 3846ee043d..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/message/AbstractBytesMessage.java
+++ /dev/null
@@ -1,124 +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.client.message;
-
-import java.io.IOException;
-import java.nio.charset.Charset;
-
-import javax.jms.JMSException;
-import javax.jms.MessageEOFException;
-
-import org.apache.mina.common.ByteBuffer;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.BasicContentHeaderProperties;
-import org.apache.qpid.transport.util.Functions;
-
-/**
- * @author Apache Software Foundation
- */
-public abstract class AbstractBytesMessage extends AbstractJMSMessage
-{
-
- /**
- * The default initial size of the buffer. The buffer expands automatically.
- */
- private static final int DEFAULT_BUFFER_INITIAL_SIZE = 1024;
-
- AbstractBytesMessage(AMQMessageDelegateFactory delegateFactory)
- {
- this(delegateFactory, null);
- }
-
- /**
- * Construct a bytes message with existing data.
- *
- * @param delegateFactory
- * @param data the data that comprises this message. If data is null, you get a 1024 byte buffer that is
- */
- AbstractBytesMessage(AMQMessageDelegateFactory delegateFactory, ByteBuffer data)
- {
- super(delegateFactory, data); // this instanties a content header
- setContentType(getMimeType());
-
- if (_data == null)
- {
- allocateInitialBuffer();
- }
- }
-
- protected void allocateInitialBuffer()
- {
- _data = ByteBuffer.allocate(DEFAULT_BUFFER_INITIAL_SIZE);
- _data.setAutoExpand(true);
- }
-
- AbstractBytesMessage(AMQMessageDelegate delegate, ByteBuffer data) throws AMQException
- {
- super(delegate, data);
- setContentType(getMimeType());
- }
-
-
- public void clearBodyImpl() throws JMSException
- {
- allocateInitialBuffer();
- }
-
- public String toBodyString() throws JMSException
- {
- try
- {
- if (_data != null)
- {
- return Functions.str(_data.buf(), 100,0);
- }
- else
- {
- return "";
- }
-
- }
- catch (Exception e)
- {
- JMSException jmse = new JMSException(e.toString());
- jmse.setLinkedException(e);
- jmse.initCause(e);
- throw jmse;
- }
-
- }
-
- /**
- * Check that there is at least a certain number of bytes available to read
- *
- * @param len the number of bytes
- * @throws javax.jms.MessageEOFException if there are less than len bytes available to read
- */
- protected void checkAvailable(int len) throws MessageEOFException
- {
- if (_data.remaining() < len)
- {
- throw new MessageEOFException("Unable to read " + len + " bytes");
- }
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/AbstractBytesTypedMessage.java b/java/client/src/main/java/org/apache/qpid/client/message/AbstractBytesTypedMessage.java
deleted file mode 100644
index 85818dcd2b..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/message/AbstractBytesTypedMessage.java
+++ /dev/null
@@ -1,804 +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.client.message;
-
-import java.nio.charset.CharacterCodingException;
-import java.nio.charset.Charset;
-
-import javax.jms.JMSException;
-import javax.jms.MessageEOFException;
-import javax.jms.MessageFormatException;
-import javax.jms.MessageNotReadableException;
-import javax.jms.MessageNotWriteableException;
-
-import org.apache.mina.common.ByteBuffer;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.BasicContentHeaderProperties;
-
-/**
- * @author Apache Software Foundation
- */
-public abstract class AbstractBytesTypedMessage extends AbstractBytesMessage
-{
-
- protected static final byte BOOLEAN_TYPE = (byte) 1;
-
- protected static final byte BYTE_TYPE = (byte) 2;
-
- protected static final byte BYTEARRAY_TYPE = (byte) 3;
-
- protected static final byte SHORT_TYPE = (byte) 4;
-
- protected static final byte CHAR_TYPE = (byte) 5;
-
- protected static final byte INT_TYPE = (byte) 6;
-
- protected static final byte LONG_TYPE = (byte) 7;
-
- protected static final byte FLOAT_TYPE = (byte) 8;
-
- protected static final byte DOUBLE_TYPE = (byte) 9;
-
- protected static final byte STRING_TYPE = (byte) 10;
-
- protected static final byte NULL_STRING_TYPE = (byte) 11;
-
- /**
- * This is set when reading a byte array. The readBytes(byte[]) method supports multiple calls to read
- * a byte array in multiple chunks, hence this is used to track how much is left to be read
- */
- private int _byteArrayRemaining = -1;
-
- AbstractBytesTypedMessage(AMQMessageDelegateFactory delegateFactory)
- {
-
- this(delegateFactory, null);
- }
-
- /**
- * Construct a stream message with existing data.
- *
- * @param delegateFactory
- * @param data the data that comprises this message. If data is null, you get a 1024 byte buffer that is
- */
- AbstractBytesTypedMessage(AMQMessageDelegateFactory delegateFactory, ByteBuffer data)
- {
-
- super(delegateFactory, data); // this instanties a content header
- }
-
- AbstractBytesTypedMessage(AMQMessageDelegate delegate, ByteBuffer data) throws AMQException
- {
-
- super(delegate, data);
- }
-
-
- protected byte readWireType() throws MessageFormatException, MessageEOFException,
- MessageNotReadableException
- {
- checkReadable();
- checkAvailable(1);
- return _data.get();
- }
-
- protected void writeTypeDiscriminator(byte type) throws MessageNotWriteableException
- {
- checkWritable();
- _data.put(type);
- _changedData = true;
- }
-
- protected boolean readBoolean() throws JMSException
- {
- int position = _data.position();
- byte wireType = readWireType();
- boolean result;
- try
- {
- switch (wireType)
- {
- case BOOLEAN_TYPE:
- checkAvailable(1);
- result = readBooleanImpl();
- break;
- case STRING_TYPE:
- checkAvailable(1);
- result = Boolean.parseBoolean(readStringImpl());
- break;
- default:
- _data.position(position);
- throw new MessageFormatException("Unable to convert " + wireType + " to a boolean");
- }
- return result;
- }
- catch (RuntimeException e)
- {
- _data.position(position);
- throw e;
- }
- }
-
- private boolean readBooleanImpl()
- {
- return _data.get() != 0;
- }
-
- protected byte readByte() throws JMSException
- {
- int position = _data.position();
- byte wireType = readWireType();
- byte result;
- try
- {
- switch (wireType)
- {
- case BYTE_TYPE:
- checkAvailable(1);
- result = readByteImpl();
- break;
- case STRING_TYPE:
- checkAvailable(1);
- result = Byte.parseByte(readStringImpl());
- break;
- default:
- _data.position(position);
- throw new MessageFormatException("Unable to convert " + wireType + " to a byte");
- }
- }
- catch (RuntimeException e)
- {
- _data.position(position);
- throw e;
- }
- return result;
- }
-
- private byte readByteImpl()
- {
- return _data.get();
- }
-
- protected short readShort() throws JMSException
- {
- int position = _data.position();
- byte wireType = readWireType();
- short result;
- try
- {
- switch (wireType)
- {
- case SHORT_TYPE:
- checkAvailable(2);
- result = readShortImpl();
- break;
- case STRING_TYPE:
- checkAvailable(1);
- result = Short.parseShort(readStringImpl());
- break;
- case BYTE_TYPE:
- checkAvailable(1);
- result = readByteImpl();
- break;
- default:
- _data.position(position);
- throw new MessageFormatException("Unable to convert " + wireType + " to a short");
- }
- }
- catch (RuntimeException e)
- {
- _data.position(position);
- throw e;
- }
- return result;
- }
-
- private short readShortImpl()
- {
- return _data.getShort();
- }
-
- /**
- * Note that this method reads a unicode character as two bytes from the stream
- *
- * @return the character read from the stream
- * @throws javax.jms.JMSException
- */
- protected char readChar() throws JMSException
- {
- int position = _data.position();
- byte wireType = readWireType();
- try
- {
- if(wireType == NULL_STRING_TYPE){
- throw new NullPointerException();
- }
-
- if (wireType != CHAR_TYPE)
- {
- _data.position(position);
- throw new MessageFormatException("Unable to convert " + wireType + " to a char");
- }
- else
- {
- checkAvailable(2);
- return readCharImpl();
- }
- }
- catch (RuntimeException e)
- {
- _data.position(position);
- throw e;
- }
- }
-
- private char readCharImpl()
- {
- return _data.getChar();
- }
-
- protected int readInt() throws JMSException
- {
- int position = _data.position();
- byte wireType = readWireType();
- int result;
- try
- {
- switch (wireType)
- {
- case INT_TYPE:
- checkAvailable(4);
- result = readIntImpl();
- break;
- case SHORT_TYPE:
- checkAvailable(2);
- result = readShortImpl();
- break;
- case STRING_TYPE:
- checkAvailable(1);
- result = Integer.parseInt(readStringImpl());
- break;
- case BYTE_TYPE:
- checkAvailable(1);
- result = readByteImpl();
- break;
- default:
- _data.position(position);
- throw new MessageFormatException("Unable to convert " + wireType + " to an int");
- }
- return result;
- }
- catch (RuntimeException e)
- {
- _data.position(position);
- throw e;
- }
- }
-
- protected int readIntImpl()
- {
- return _data.getInt();
- }
-
- protected long readLong() throws JMSException
- {
- int position = _data.position();
- byte wireType = readWireType();
- long result;
- try
- {
- switch (wireType)
- {
- case LONG_TYPE:
- checkAvailable(8);
- result = readLongImpl();
- break;
- case INT_TYPE:
- checkAvailable(4);
- result = readIntImpl();
- break;
- case SHORT_TYPE:
- checkAvailable(2);
- result = readShortImpl();
- break;
- case STRING_TYPE:
- checkAvailable(1);
- result = Long.parseLong(readStringImpl());
- break;
- case BYTE_TYPE:
- checkAvailable(1);
- result = readByteImpl();
- break;
- default:
- _data.position(position);
- throw new MessageFormatException("Unable to convert " + wireType + " to a long");
- }
- return result;
- }
- catch (RuntimeException e)
- {
- _data.position(position);
- throw e;
- }
- }
-
- private long readLongImpl()
- {
- return _data.getLong();
- }
-
- protected float readFloat() throws JMSException
- {
- int position = _data.position();
- byte wireType = readWireType();
- float result;
- try
- {
- switch (wireType)
- {
- case FLOAT_TYPE:
- checkAvailable(4);
- result = readFloatImpl();
- break;
- case STRING_TYPE:
- checkAvailable(1);
- result = Float.parseFloat(readStringImpl());
- break;
- default:
- _data.position(position);
- throw new MessageFormatException("Unable to convert " + wireType + " to a float");
- }
- return result;
- }
- catch (RuntimeException e)
- {
- _data.position(position);
- throw e;
- }
- }
-
- private float readFloatImpl()
- {
- return _data.getFloat();
- }
-
- protected double readDouble() throws JMSException
- {
- int position = _data.position();
- byte wireType = readWireType();
- double result;
- try
- {
- switch (wireType)
- {
- case DOUBLE_TYPE:
- checkAvailable(8);
- result = readDoubleImpl();
- break;
- case FLOAT_TYPE:
- checkAvailable(4);
- result = readFloatImpl();
- break;
- case STRING_TYPE:
- checkAvailable(1);
- result = Double.parseDouble(readStringImpl());
- break;
- default:
- _data.position(position);
- throw new MessageFormatException("Unable to convert " + wireType + " to a double");
- }
- return result;
- }
- catch (RuntimeException e)
- {
- _data.position(position);
- throw e;
- }
- }
-
- private double readDoubleImpl()
- {
- return _data.getDouble();
- }
-
- protected String readString() throws JMSException
- {
- int position = _data.position();
- byte wireType = readWireType();
- String result;
- try
- {
- switch (wireType)
- {
- case STRING_TYPE:
- checkAvailable(1);
- result = readStringImpl();
- break;
- case NULL_STRING_TYPE:
- result = null;
- throw new NullPointerException("data is null");
- case BOOLEAN_TYPE:
- checkAvailable(1);
- result = String.valueOf(readBooleanImpl());
- break;
- case LONG_TYPE:
- checkAvailable(8);
- result = String.valueOf(readLongImpl());
- break;
- case INT_TYPE:
- checkAvailable(4);
- result = String.valueOf(readIntImpl());
- break;
- case SHORT_TYPE:
- checkAvailable(2);
- result = String.valueOf(readShortImpl());
- break;
- case BYTE_TYPE:
- checkAvailable(1);
- result = String.valueOf(readByteImpl());
- break;
- case FLOAT_TYPE:
- checkAvailable(4);
- result = String.valueOf(readFloatImpl());
- break;
- case DOUBLE_TYPE:
- checkAvailable(8);
- result = String.valueOf(readDoubleImpl());
- break;
- case CHAR_TYPE:
- checkAvailable(2);
- result = String.valueOf(readCharImpl());
- break;
- default:
- _data.position(position);
- throw new MessageFormatException("Unable to convert " + wireType + " to a String");
- }
- return result;
- }
- catch (RuntimeException e)
- {
- _data.position(position);
- throw e;
- }
- }
-
- protected String readStringImpl() throws JMSException
- {
- try
- {
- return _data.getString(Charset.forName("UTF-8").newDecoder());
- }
- catch (CharacterCodingException e)
- {
- JMSException jmse = new JMSException("Error decoding byte stream as a UTF8 string: " + e);
- jmse.setLinkedException(e);
- jmse.initCause(e);
- throw jmse;
- }
- }
-
- protected int readBytes(byte[] bytes) throws JMSException
- {
- if (bytes == null)
- {
- throw new IllegalArgumentException("byte array must not be null");
- }
- checkReadable();
- // first call
- if (_byteArrayRemaining == -1)
- {
- // type discriminator checked separately so you get a MessageFormatException rather than
- // an EOF even in the case where both would be applicable
- checkAvailable(1);
- byte wireType = readWireType();
- if (wireType != BYTEARRAY_TYPE)
- {
- throw new MessageFormatException("Unable to convert " + wireType + " to a byte array");
- }
- checkAvailable(4);
- int size = _data.getInt();
- // length of -1 indicates null
- if (size == -1)
- {
- return -1;
- }
- else
- {
- if (size > _data.remaining())
- {
- throw new MessageEOFException("Byte array has stated length " + size + " but message only contains " +
- _data.remaining() + " bytes");
- }
- else
- {
- _byteArrayRemaining = size;
- }
- }
- }
- else if (_byteArrayRemaining == 0)
- {
- _byteArrayRemaining = -1;
- return -1;
- }
-
- int returnedSize = readBytesImpl(bytes);
- if (returnedSize < bytes.length)
- {
- _byteArrayRemaining = -1;
- }
- return returnedSize;
- }
-
- private int readBytesImpl(byte[] bytes)
- {
- int count = (_byteArrayRemaining >= bytes.length ? bytes.length : _byteArrayRemaining);
- _byteArrayRemaining -= count;
-
- if (count == 0)
- {
- return 0;
- }
- else
- {
- _data.get(bytes, 0, count);
- return count;
- }
- }
-
- protected Object readObject() throws JMSException
- {
- int position = _data.position();
- byte wireType = readWireType();
- Object result = null;
- try
- {
- switch (wireType)
- {
- case BOOLEAN_TYPE:
- checkAvailable(1);
- result = readBooleanImpl();
- break;
- case BYTE_TYPE:
- checkAvailable(1);
- result = readByteImpl();
- break;
- case BYTEARRAY_TYPE:
- checkAvailable(4);
- int size = _data.getInt();
- if (size == -1)
- {
- result = null;
- }
- else
- {
- _byteArrayRemaining = size;
- byte[] bytesResult = new byte[size];
- readBytesImpl(bytesResult);
- result = bytesResult;
- }
- break;
- case SHORT_TYPE:
- checkAvailable(2);
- result = readShortImpl();
- break;
- case CHAR_TYPE:
- checkAvailable(2);
- result = readCharImpl();
- break;
- case INT_TYPE:
- checkAvailable(4);
- result = readIntImpl();
- break;
- case LONG_TYPE:
- checkAvailable(8);
- result = readLongImpl();
- break;
- case FLOAT_TYPE:
- checkAvailable(4);
- result = readFloatImpl();
- break;
- case DOUBLE_TYPE:
- checkAvailable(8);
- result = readDoubleImpl();
- break;
- case NULL_STRING_TYPE:
- result = null;
- break;
- case STRING_TYPE:
- checkAvailable(1);
- result = readStringImpl();
- break;
- }
- return result;
- }
- catch (RuntimeException e)
- {
- _data.position(position);
- throw e;
- }
- }
-
- protected void writeBoolean(boolean b) throws JMSException
- {
- writeTypeDiscriminator(BOOLEAN_TYPE);
- _data.put(b ? (byte) 1 : (byte) 0);
- }
-
- protected void writeByte(byte b) throws JMSException
- {
- writeTypeDiscriminator(BYTE_TYPE);
- _data.put(b);
- }
-
- protected void writeShort(short i) throws JMSException
- {
- writeTypeDiscriminator(SHORT_TYPE);
- _data.putShort(i);
- }
-
- protected void writeChar(char c) throws JMSException
- {
- writeTypeDiscriminator(CHAR_TYPE);
- _data.putChar(c);
- }
-
- protected void writeInt(int i) throws JMSException
- {
- writeTypeDiscriminator(INT_TYPE);
- writeIntImpl(i);
- }
-
- protected void writeIntImpl(int i)
- {
- _data.putInt(i);
- }
-
- protected void writeLong(long l) throws JMSException
- {
- writeTypeDiscriminator(LONG_TYPE);
- _data.putLong(l);
- }
-
- protected void writeFloat(float v) throws JMSException
- {
- writeTypeDiscriminator(FLOAT_TYPE);
- _data.putFloat(v);
- }
-
- protected void writeDouble(double v) throws JMSException
- {
- writeTypeDiscriminator(DOUBLE_TYPE);
- _data.putDouble(v);
- }
-
- protected void writeString(String string) throws JMSException
- {
- if (string == null)
- {
- writeTypeDiscriminator(NULL_STRING_TYPE);
- }
- else
- {
- writeTypeDiscriminator(STRING_TYPE);
- try
- {
- writeStringImpl(string);
- }
- catch (CharacterCodingException e)
- {
- JMSException jmse = new JMSException("Unable to encode string: " + e);
- jmse.setLinkedException(e);
- jmse.initCause(e);
- throw jmse;
- }
- }
- }
-
- protected void writeStringImpl(String string)
- throws CharacterCodingException
- {
- _data.putString(string, Charset.forName("UTF-8").newEncoder());
- // we must write the null terminator ourselves
- _data.put((byte) 0);
- }
-
- protected void writeBytes(byte[] bytes) throws JMSException
- {
- writeBytes(bytes, 0, bytes == null ? 0 : bytes.length);
- }
-
- protected void writeBytes(byte[] bytes, int offset, int length) throws JMSException
- {
- writeTypeDiscriminator(BYTEARRAY_TYPE);
- if (bytes == null)
- {
- _data.putInt(-1);
- }
- else
- {
- _data.putInt(length);
- _data.put(bytes, offset, length);
- }
- }
-
- protected void writeObject(Object object) throws JMSException
- {
- checkWritable();
- Class clazz;
-
- if (object == null)
- {
- // string handles the output of null values
- clazz = String.class;
- }
- else
- {
- clazz = object.getClass();
- }
-
- if (clazz == Byte.class)
- {
- writeByte((Byte) object);
- }
- else if (clazz == Boolean.class)
- {
- writeBoolean((Boolean) object);
- }
- else if (clazz == byte[].class)
- {
- writeBytes((byte[]) object);
- }
- else if (clazz == Short.class)
- {
- writeShort((Short) object);
- }
- else if (clazz == Character.class)
- {
- writeChar((Character) object);
- }
- else if (clazz == Integer.class)
- {
- writeInt((Integer) object);
- }
- else if (clazz == Long.class)
- {
- writeLong((Long) object);
- }
- else if (clazz == Float.class)
- {
- writeFloat((Float) object);
- }
- else if (clazz == Double.class)
- {
- writeDouble((Double) object);
- }
- else if (clazz == String.class)
- {
- writeString((String) object);
- }
- else
- {
- throw new MessageFormatException("Only primitives plus byte arrays and String are valid types");
- }
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/AbstractJMSMessage.java b/java/client/src/main/java/org/apache/qpid/client/message/AbstractJMSMessage.java
deleted file mode 100644
index 6ba55b207a..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/message/AbstractJMSMessage.java
+++ /dev/null
@@ -1,536 +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.client.message;
-
-import java.io.IOException;
-import java.util.Enumeration;
-import java.util.UUID;
-
-import javax.jms.Destination;
-import javax.jms.JMSException;
-import javax.jms.MessageNotReadableException;
-import javax.jms.MessageNotWriteableException;
-
-import org.apache.mina.common.ByteBuffer;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.BasicContentHeaderProperties;
-
-public abstract class AbstractJMSMessage implements org.apache.qpid.jms.Message
-{
-
-
-
- protected ByteBuffer _data;
- protected boolean _readableMessage = false;
- protected boolean _changedData = true;
-
- /** If the acknowledge mode is CLIENT_ACKNOWLEDGE the session is required */
-
-
-
-
- protected AMQMessageDelegate _delegate;
- private boolean _redelivered;
-
- protected AbstractJMSMessage(AMQMessageDelegateFactory delegateFactory, ByteBuffer data)
- {
- _delegate = delegateFactory.createDelegate();
- _data = data;
- if (_data != null)
- {
- _data.acquire();
- }
-
-
- _readableMessage = (data != null);
- _changedData = (data == null);
-
- }
-
- protected AbstractJMSMessage(AMQMessageDelegate delegate, ByteBuffer data) throws AMQException
- {
-
- _delegate = delegate;
-
- _data = data;
- if (_data != null)
- {
- _data.acquire();
- }
-
- _readableMessage = data != null;
-
- }
-
- public String getJMSMessageID() throws JMSException
- {
- return _delegate.getJMSMessageID();
- }
-
- public void setJMSMessageID(String messageId) throws JMSException
- {
- _delegate.setJMSMessageID(messageId);
- }
-
- public void setJMSMessageID(UUID messageId) throws JMSException
- {
- _delegate.setJMSMessageID(messageId);
- }
-
-
- public long getJMSTimestamp() throws JMSException
- {
- return _delegate.getJMSTimestamp();
- }
-
- public void setJMSTimestamp(long timestamp) throws JMSException
- {
- _delegate.setJMSTimestamp(timestamp);
- }
-
- public byte[] getJMSCorrelationIDAsBytes() throws JMSException
- {
- return _delegate.getJMSCorrelationIDAsBytes();
- }
-
- public void setJMSCorrelationIDAsBytes(byte[] bytes) throws JMSException
- {
- _delegate.setJMSCorrelationIDAsBytes(bytes);
- }
-
- public void setJMSCorrelationID(String correlationId) throws JMSException
- {
- _delegate.setJMSCorrelationID(correlationId);
- }
-
- public String getJMSCorrelationID() throws JMSException
- {
- return _delegate.getJMSCorrelationID();
- }
-
- public Destination getJMSReplyTo() throws JMSException
- {
- return _delegate.getJMSReplyTo();
- }
-
- public void setJMSReplyTo(Destination destination) throws JMSException
- {
- _delegate.setJMSReplyTo(destination);
- }
-
- public Destination getJMSDestination() throws JMSException
- {
- return _delegate.getJMSDestination();
- }
-
- public void setJMSDestination(Destination destination)
- {
- _delegate.setJMSDestination(destination);
- }
-
- public int getJMSDeliveryMode() throws JMSException
- {
- return _delegate.getJMSDeliveryMode();
- }
-
- public void setJMSDeliveryMode(int i) throws JMSException
- {
- _delegate.setJMSDeliveryMode(i);
- }
-
-
- public boolean getJMSRedelivered() throws JMSException
- {
- return _redelivered;
- }
-
- public void setJMSRedelivered(boolean b) throws JMSException
- {
- _redelivered = b;
- }
-
-
- public String getJMSType() throws JMSException
- {
- return _delegate.getJMSType();
- }
-
- public void setJMSType(String string) throws JMSException
- {
- _delegate.setJMSType(string);
- }
-
- public long getJMSExpiration() throws JMSException
- {
- return _delegate.getJMSExpiration();
- }
-
- public void setJMSExpiration(long l) throws JMSException
- {
- _delegate.setJMSExpiration(l);
- }
-
- public int getJMSPriority() throws JMSException
- {
- return _delegate.getJMSPriority();
- }
-
- public void setJMSPriority(int i) throws JMSException
- {
- _delegate.setJMSPriority(i);
- }
-
-
- public boolean propertyExists(String propertyName) throws JMSException
- {
- return _delegate.propertyExists(propertyName);
- }
-
- public boolean getBooleanProperty(final String s)
- throws JMSException
- {
- return _delegate.getBooleanProperty(s);
- }
-
- public byte getByteProperty(final String s)
- throws JMSException
- {
- return _delegate.getByteProperty(s);
- }
-
- public short getShortProperty(final String s)
- throws JMSException
- {
- return _delegate.getShortProperty(s);
- }
-
- public int getIntProperty(final String s)
- throws JMSException
- {
- return _delegate.getIntProperty(s);
- }
-
- public long getLongProperty(final String s)
- throws JMSException
- {
- return _delegate.getLongProperty(s);
- }
-
- public float getFloatProperty(final String s)
- throws JMSException
- {
- return _delegate.getFloatProperty(s);
- }
-
- public double getDoubleProperty(final String s)
- throws JMSException
- {
- return _delegate.getDoubleProperty(s);
- }
-
- public String getStringProperty(final String s)
- throws JMSException
- {
- return _delegate.getStringProperty(s);
- }
-
- public Object getObjectProperty(final String s)
- throws JMSException
- {
- return _delegate.getObjectProperty(s);
- }
-
- public Enumeration getPropertyNames()
- throws JMSException
- {
- return _delegate.getPropertyNames();
- }
-
- public void setBooleanProperty(final String s, final boolean b)
- throws JMSException
- {
- _delegate.setBooleanProperty(s, b);
- }
-
- public void setByteProperty(final String s, final byte b)
- throws JMSException
- {
- _delegate.setByteProperty(s, b);
- }
-
- public void setShortProperty(final String s, final short i)
- throws JMSException
- {
- _delegate.setShortProperty(s, i);
- }
-
- public void setIntProperty(final String s, final int i)
- throws JMSException
- {
- _delegate.setIntProperty(s, i);
- }
-
- public void setLongProperty(final String s, final long l)
- throws JMSException
- {
- _delegate.setLongProperty(s, l);
- }
-
- public void setFloatProperty(final String s, final float v)
- throws JMSException
- {
- _delegate.setFloatProperty(s, v);
- }
-
- public void setDoubleProperty(final String s, final double v)
- throws JMSException
- {
- _delegate.setDoubleProperty(s, v);
- }
-
- public void setStringProperty(final String s, final String s1)
- throws JMSException
- {
- _delegate.setStringProperty(s, s1);
- }
-
- public void setObjectProperty(final String s, final Object o)
- throws JMSException
- {
- _delegate.setObjectProperty(s, o);
- }
-
-
-
- public void clearProperties() throws JMSException
- {
- _delegate.clearProperties();
- }
-
- public void clearBody() throws JMSException
- {
- clearBodyImpl();
- _readableMessage = false;
-
- }
-
-
- public void acknowledgeThis() throws JMSException
- {
- _delegate.acknowledgeThis();
- }
-
- public void acknowledge() throws JMSException
- {
- _delegate.acknowledge();
- }
-
- /**
- * This forces concrete classes to implement clearBody()
- *
- * @throws JMSException
- */
- public abstract void clearBodyImpl() throws JMSException;
-
- /**
- * Get a String representation of the body of the message. Used in the toString() method which outputs this before
- * message properties.
- */
- public abstract String toBodyString() throws JMSException;
-
- protected abstract String getMimeType();
-
-
-
- public String toString()
- {
- try
- {
- StringBuffer buf = new StringBuffer("Body:\n");
-
- buf.append(toBodyString());
- buf.append("\nJMS Correlation ID: ").append(getJMSCorrelationID());
- buf.append("\nJMS timestamp: ").append(getJMSTimestamp());
- buf.append("\nJMS expiration: ").append(getJMSExpiration());
- buf.append("\nJMS priority: ").append(getJMSPriority());
- buf.append("\nJMS delivery mode: ").append(getJMSDeliveryMode());
- buf.append("\nJMS reply to: ").append(getReplyToString());
- buf.append("\nJMS Redelivered: ").append(_redelivered);
- buf.append("\nJMS Destination: ").append(getJMSDestination());
- buf.append("\nJMS Type: ").append(getJMSType());
- buf.append("\nJMS MessageID: ").append(getJMSMessageID());
- buf.append("\nJMS Content-Type: ").append(getContentType());
- buf.append("\nAMQ message number: ").append(getDeliveryTag());
-
- buf.append("\nProperties:");
- final Enumeration propertyNames = getPropertyNames();
- if (!propertyNames.hasMoreElements())
- {
- buf.append("<NONE>");
- }
- else
- {
- buf.append('\n');
- while(propertyNames.hasMoreElements())
- {
- String propertyName = (String) propertyNames.nextElement();
- buf.append("\t").append(propertyName).append(" = ").append(getObjectProperty(propertyName)).append("\n");
- }
-
- }
-
- return buf.toString();
- }
- catch (JMSException e)
- {
- throw new RuntimeException(e);
- }
- }
-
-
- public AMQMessageDelegate getDelegate()
- {
- return _delegate;
- }
-
- public ByteBuffer getData()
- {
- // make sure we rewind the data just in case any method has moved the
- // position beyond the start
- if (_data != null)
- {
- reset();
- }
-
- return _data;
- }
-
- protected void checkReadable() throws MessageNotReadableException
- {
- if (!_readableMessage)
- {
- throw new MessageNotReadableException("You need to call reset() to make the message readable");
- }
- }
-
- protected void checkWritable() throws MessageNotWriteableException
- {
- if (_readableMessage)
- {
- throw new MessageNotWriteableException("You need to call clearBody() to make the message writable");
- }
- }
-
- public void reset()
- {
- if (!_changedData)
- {
- _data.rewind();
- }
- else
- {
- _data.flip();
- _changedData = false;
- }
- }
-
- public int getContentLength()
- {
- if(_data != null)
- {
- return _data.remaining();
- }
- else
- {
- return 0;
- }
- }
-
- public void receivedFromServer()
- {
- _changedData = false;
- }
-
- /**
- * The session is set when CLIENT_ACKNOWLEDGE mode is used so that the CHANNEL ACK can be sent when the user calls
- * acknowledge()
- *
- * @param s the AMQ session that delivered this message
- */
- public void setAMQSession(AMQSession s)
- {
- _delegate.setAMQSession(s);
- }
-
- public AMQSession getAMQSession()
- {
- return _delegate.getAMQSession();
- }
-
- /**
- * Get the AMQ message number assigned to this message
- *
- * @return the message number
- */
- public long getDeliveryTag()
- {
- return _delegate.getDeliveryTag();
- }
-
- /** Invoked prior to sending the message. Allows the message to be modified if necessary before sending. */
- public void prepareForSending() throws JMSException
- {
- }
-
-
- public void setContentType(String contentType)
- {
- _delegate.setContentType(contentType);
- }
-
- public String getContentType()
- {
- return _delegate.getContentType();
- }
-
- public void setEncoding(String encoding)
- {
- _delegate.setEncoding(encoding);
- }
-
- public String getEncoding()
- {
- return _delegate.getEncoding();
- }
-
- public String getReplyToString()
- {
- return _delegate.getReplyToString();
- }
-
- protected void removeProperty(final String propertyName) throws JMSException
- {
- _delegate.removeProperty(propertyName);
- }
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/AbstractJMSMessageFactory.java b/java/client/src/main/java/org/apache/qpid/client/message/AbstractJMSMessageFactory.java
deleted file mode 100644
index 40c1df0c5d..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/message/AbstractJMSMessageFactory.java
+++ /dev/null
@@ -1,173 +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.client.message;
-
-import org.apache.mina.common.ByteBuffer;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.ContentBody;
-import org.apache.qpid.framing.ContentHeaderBody;
-import org.apache.qpid.framing.BasicContentHeaderProperties;
-import org.apache.qpid.transport.MessageProperties;
-import org.apache.qpid.transport.DeliveryProperties;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.jms.JMSException;
-
-import java.util.Iterator;
-import java.util.List;
-
-public abstract class AbstractJMSMessageFactory implements MessageFactory
-{
- private static final Logger _logger = LoggerFactory.getLogger(AbstractJMSMessageFactory.class);
-
- protected AbstractJMSMessage create08MessageWithBody(long messageNbr, ContentHeaderBody contentHeader,
- AMQShortString exchange, AMQShortString routingKey,
- List bodies) throws AMQException
- {
- ByteBuffer data;
- final boolean debug = _logger.isDebugEnabled();
-
- // we optimise the non-fragmented case to avoid copying
- if ((bodies != null) && (bodies.size() == 1))
- {
- if (debug)
- {
- _logger.debug("Non-fragmented message body (bodySize=" + contentHeader.bodySize + ")");
- }
-
- data = ((ContentBody) bodies.get(0)).payload;
- }
- else if (bodies != null)
- {
- if (debug)
- {
- _logger.debug("Fragmented message body (" + bodies
- .size() + " frames, bodySize=" + contentHeader.bodySize + ")");
- }
-
- data = ByteBuffer.allocate((int) contentHeader.bodySize); // XXX: Is cast a problem?
- final Iterator it = bodies.iterator();
- while (it.hasNext())
- {
- ContentBody cb = (ContentBody) it.next();
- final ByteBuffer payload = cb.payload;
- if(payload.isDirect() || payload.isReadOnly())
- {
- data.put(payload);
- }
- else
- {
- data.put(payload.array(), payload.arrayOffset(), payload.limit());
- }
-
- payload.release();
- }
-
- data.flip();
- }
- else // bodies == null
- {
- data = ByteBuffer.allocate(0);
- }
-
- if (debug)
- {
- _logger.debug("Creating message from buffer with position=" + data.position() + " and remaining=" + data
- .remaining());
- }
-
- AMQMessageDelegate delegate = new AMQMessageDelegate_0_8(messageNbr,
- (BasicContentHeaderProperties) contentHeader.getProperties(),
- exchange, routingKey);
-
- return createMessage(delegate, data);
- }
-
- protected abstract AbstractJMSMessage createMessage(AMQMessageDelegate delegate, ByteBuffer data) throws AMQException;
-
-
- protected AbstractJMSMessage create010MessageWithBody(long messageNbr, MessageProperties msgProps,
- DeliveryProperties deliveryProps,
- java.nio.ByteBuffer body) throws AMQException
- {
- ByteBuffer data;
- final boolean debug = _logger.isDebugEnabled();
-
-
- if (body != null)
- {
- data = ByteBuffer.wrap(body);
- }
- else // body == null
- {
- data = ByteBuffer.allocate(0);
- }
-
- if (debug)
- {
- _logger.debug("Creating message from buffer with position=" + data.position() + " and remaining=" + data
- .remaining());
- }
- AMQMessageDelegate delegate = new AMQMessageDelegate_0_10(msgProps, deliveryProps, messageNbr);
-
- AbstractJMSMessage message = createMessage(delegate, data);
- return message;
- }
-
- private static final String asString(byte[] bytes)
- {
- if (bytes == null)
- {
- return null;
- }
- else
- {
- return new String(bytes);
- }
- }
-
-
- public AbstractJMSMessage createMessage(long messageNbr, boolean redelivered, ContentHeaderBody contentHeader,
- AMQShortString exchange, AMQShortString routingKey, List bodies)
- throws JMSException, AMQException
- {
- final AbstractJMSMessage msg = create08MessageWithBody(messageNbr, contentHeader, exchange, routingKey, bodies);
- msg.setJMSRedelivered(redelivered);
- msg.receivedFromServer();
- return msg;
- }
-
- public AbstractJMSMessage createMessage(long messageNbr, boolean redelivered, MessageProperties msgProps,
- DeliveryProperties deliveryProps, java.nio.ByteBuffer body)
- throws JMSException, AMQException
- {
- final AbstractJMSMessage msg =
- create010MessageWithBody(messageNbr,msgProps,deliveryProps, body);
- msg.setJMSRedelivered(redelivered);
- msg.receivedFromServer();
- return msg;
- }
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/CloseConsumerMessage.java b/java/client/src/main/java/org/apache/qpid/client/message/CloseConsumerMessage.java
deleted file mode 100644
index 4af04912e5..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/message/CloseConsumerMessage.java
+++ /dev/null
@@ -1,43 +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.client.message;
-
-import org.apache.qpid.client.BasicMessageConsumer;
-
-public final class CloseConsumerMessage extends UnprocessedMessage
-{
-
- public CloseConsumerMessage(BasicMessageConsumer consumer)
- {
- super(consumer.getConsumerTag());
- }
-
-
- public long getDeliveryTag()
- {
- return 0;
- }
-
- public boolean isRedelivered()
- {
- return false;
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/FieldTableSupport.java b/java/client/src/main/java/org/apache/qpid/client/message/FieldTableSupport.java
deleted file mode 100644
index 49ae8c14b2..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/message/FieldTableSupport.java
+++ /dev/null
@@ -1,54 +0,0 @@
-package org.apache.qpid.client.message;
-/*
- *
- * 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 java.util.HashMap;
-import java.util.Map;
-
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.FieldTable;
-
-public class FieldTableSupport
-{
- public static FieldTable convertToFieldTable(Map<String,?> props)
- {
- FieldTable ft = new FieldTable();
- if (props != null)
- {
- for (String key : props.keySet())
- {
- ft.setObject(key, props.get(key));
- }
- }
- return ft;
- }
-
- public static Map<String,Object> convertToMap(FieldTable ft)
- {
- Map<String,Object> map = new HashMap<String,Object>();
- for (AMQShortString key: ft.keySet() )
- {
- map.put(key.asString(), ft.getObject(key));
- }
-
- return map;
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/JMSBytesMessage.java b/java/client/src/main/java/org/apache/qpid/client/message/JMSBytesMessage.java
deleted file mode 100644
index b87275a9ce..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/message/JMSBytesMessage.java
+++ /dev/null
@@ -1,386 +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.client.message;
-
-import java.nio.CharBuffer;
-import java.nio.charset.CharacterCodingException;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CharsetEncoder;
-
-import javax.jms.BytesMessage;
-import javax.jms.JMSException;
-import javax.jms.MessageFormatException;
-
-import org.apache.mina.common.ByteBuffer;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.BasicContentHeaderProperties;
-
-public class JMSBytesMessage extends AbstractBytesMessage implements BytesMessage
-{
- public static final String MIME_TYPE = "application/octet-stream";
-
-
-
- public JMSBytesMessage(AMQMessageDelegateFactory delegateFactory)
- {
- this(delegateFactory,null);
-
- }
-
- /**
- * Construct a bytes message with existing data.
- *
- * @param delegateFactory
- * @param data the data that comprises this message. If data is null, you get a 1024 byte buffer that is
- */
- JMSBytesMessage(AMQMessageDelegateFactory delegateFactory, ByteBuffer data)
- {
-
- super(delegateFactory, data); // this instanties a content header
- }
-
- JMSBytesMessage(AMQMessageDelegate delegate, ByteBuffer data) throws AMQException
- {
- super(delegate, data);
- }
-
-
- public void reset()
- {
- super.reset();
- _readableMessage = true;
- }
-
- protected String getMimeType()
- {
- return MIME_TYPE;
- }
-
- public long getBodyLength() throws JMSException
- {
- checkReadable();
- return _data.limit();
- }
-
- public boolean readBoolean() throws JMSException
- {
- checkReadable();
- checkAvailable(1);
- return _data.get() != 0;
- }
-
- public byte readByte() throws JMSException
- {
- checkReadable();
- checkAvailable(1);
- return _data.get();
- }
-
- public int readUnsignedByte() throws JMSException
- {
- checkReadable();
- checkAvailable(1);
- return _data.getUnsigned();
- }
-
- public short readShort() throws JMSException
- {
- checkReadable();
- checkAvailable(2);
- return _data.getShort();
- }
-
- public int readUnsignedShort() throws JMSException
- {
- checkReadable();
- checkAvailable(2);
- return _data.getUnsignedShort();
- }
-
- /**
- * Note that this method reads a unicode character as two bytes from the stream
- *
- * @return the character read from the stream
- * @throws JMSException
- */
- public char readChar() throws JMSException
- {
- checkReadable();
- checkAvailable(2);
- return _data.getChar();
- }
-
- public int readInt() throws JMSException
- {
- checkReadable();
- checkAvailable(4);
- return _data.getInt();
- }
-
- public long readLong() throws JMSException
- {
- checkReadable();
- checkAvailable(8);
- return _data.getLong();
- }
-
- public float readFloat() throws JMSException
- {
- checkReadable();
- checkAvailable(4);
- return _data.getFloat();
- }
-
- public double readDouble() throws JMSException
- {
- checkReadable();
- checkAvailable(8);
- return _data.getDouble();
- }
-
- public String readUTF() throws JMSException
- {
- checkReadable();
- // we check only for one byte since theoretically the string could be only a
- // single byte when using UTF-8 encoding
-
- try
- {
- short length = readShort();
- if(length == 0)
- {
- return "";
- }
- else
- {
- CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();
- ByteBuffer encodedString = _data.slice();
- encodedString.limit(length);
- _data.position(_data.position()+length);
- CharBuffer string = decoder.decode(encodedString.buf());
-
- return string.toString();
- }
-
-
-
- }
- catch (CharacterCodingException e)
- {
- JMSException jmse = new JMSException("Error decoding byte stream as a UTF8 string: " + e);
- jmse.setLinkedException(e);
- jmse.initCause(e);
- throw jmse;
- }
- }
-
- public int readBytes(byte[] bytes) throws JMSException
- {
- if (bytes == null)
- {
- throw new IllegalArgumentException("byte array must not be null");
- }
- checkReadable();
- int count = (_data.remaining() >= bytes.length ? bytes.length : _data.remaining());
- if (count == 0)
- {
- return -1;
- }
- else
- {
- _data.get(bytes, 0, count);
- return count;
- }
- }
-
- public int readBytes(byte[] bytes, int maxLength) throws JMSException
- {
- if (bytes == null)
- {
- throw new IllegalArgumentException("byte array must not be null");
- }
- if (maxLength > bytes.length)
- {
- throw new IllegalArgumentException("maxLength must be <= bytes.length");
- }
- checkReadable();
- int count = (_data.remaining() >= maxLength ? maxLength : _data.remaining());
- if (count == 0)
- {
- return -1;
- }
- else
- {
- _data.get(bytes, 0, count);
- return count;
- }
- }
-
- public void writeBoolean(boolean b) throws JMSException
- {
- checkWritable();
- _changedData = true;
- _data.put(b ? (byte) 1 : (byte) 0);
- }
-
- public void writeByte(byte b) throws JMSException
- {
- checkWritable();
- _changedData = true;
- _data.put(b);
- }
-
- public void writeShort(short i) throws JMSException
- {
- checkWritable();
- _changedData = true;
- _data.putShort(i);
- }
-
- public void writeChar(char c) throws JMSException
- {
- checkWritable();
- _changedData = true;
- _data.putChar(c);
- }
-
- public void writeInt(int i) throws JMSException
- {
- checkWritable();
- _changedData = true;
- _data.putInt(i);
- }
-
- public void writeLong(long l) throws JMSException
- {
- checkWritable();
- _changedData = true;
- _data.putLong(l);
- }
-
- public void writeFloat(float v) throws JMSException
- {
- checkWritable();
- _changedData = true;
- _data.putFloat(v);
- }
-
- public void writeDouble(double v) throws JMSException
- {
- checkWritable();
- _changedData = true;
- _data.putDouble(v);
- }
-
- public void writeUTF(String string) throws JMSException
- {
- checkWritable();
- try
- {
- CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder();
- java.nio.ByteBuffer encodedString = encoder.encode(CharBuffer.wrap(string));
-
- _data.putShort((short)encodedString.limit());
- _data.put(encodedString);
- _changedData = true;
- //_data.putString(string, Charset.forName("UTF-8").newEncoder());
- // we must add the null terminator manually
- //_data.put((byte)0);
- }
- catch (CharacterCodingException e)
- {
- JMSException jmse = new JMSException("Unable to encode string: " + e);
- jmse.setLinkedException(e);
- jmse.initCause(e);
- throw jmse;
- }
- }
-
- public void writeBytes(byte[] bytes) throws JMSException
- {
- checkWritable();
- _data.put(bytes);
- _changedData = true;
- }
-
- public void writeBytes(byte[] bytes, int offset, int length) throws JMSException
- {
- checkWritable();
- _data.put(bytes, offset, length);
- _changedData = true;
- }
-
- public void writeObject(Object object) throws JMSException
- {
- checkWritable();
- if (object == null)
- {
- throw new NullPointerException("Argument must not be null");
- }
- Class clazz = object.getClass();
- if (clazz == Byte.class)
- {
- writeByte((Byte) object);
- }
- else if (clazz == Boolean.class)
- {
- writeBoolean((Boolean) object);
- }
- else if (clazz == byte[].class)
- {
- writeBytes((byte[]) object);
- }
- else if (clazz == Short.class)
- {
- writeShort((Short) object);
- }
- else if (clazz == Character.class)
- {
- writeChar((Character) object);
- }
- else if (clazz == Integer.class)
- {
- writeInt((Integer) object);
- }
- else if (clazz == Long.class)
- {
- writeLong((Long) object);
- }
- else if (clazz == Float.class)
- {
- writeFloat((Float) object);
- }
- else if (clazz == Double.class)
- {
- writeDouble((Double) object);
- }
- else if (clazz == String.class)
- {
- writeUTF((String) object);
- }
- else
- {
- throw new MessageFormatException("Only primitives plus byte arrays and String are valid types");
- }
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/JMSBytesMessageFactory.java b/java/client/src/main/java/org/apache/qpid/client/message/JMSBytesMessageFactory.java
deleted file mode 100644
index cb04ebee1b..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/message/JMSBytesMessageFactory.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.client.message;
-
-import javax.jms.JMSException;
-
-import org.apache.mina.common.ByteBuffer;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.BasicContentHeaderProperties;
-
-public class JMSBytesMessageFactory extends AbstractJMSMessageFactory
-{
- protected AbstractJMSMessage createMessage(AMQMessageDelegate delegate, ByteBuffer data) throws AMQException
- {
- return new JMSBytesMessage(delegate, data);
- }
-
- public AbstractJMSMessage createMessage(AMQMessageDelegateFactory delegateFactory) throws JMSException
- {
- return new JMSBytesMessage(delegateFactory);
- }
-
- // 0_10 specific
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/JMSHeaderAdapter.java b/java/client/src/main/java/org/apache/qpid/client/message/JMSHeaderAdapter.java
deleted file mode 100644
index e295d4a2a0..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/message/JMSHeaderAdapter.java
+++ /dev/null
@@ -1,553 +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.client.message;
-
-import java.util.Enumeration;
-
-import javax.jms.JMSException;
-import javax.jms.MessageFormatException;
-
-import org.apache.mina.common.ByteBuffer;
-import org.apache.qpid.AMQPInvalidClassException;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.FieldTable;
-
-
-public final class JMSHeaderAdapter
-{
- private final FieldTable _headers;
-
- public JMSHeaderAdapter(FieldTable headers)
- {
- _headers = headers;
- }
-
-
- public FieldTable getHeaders()
- {
- return _headers;
- }
-
- public boolean getBoolean(String string) throws JMSException
- {
- checkPropertyName(string);
- Boolean b = getHeaders().getBoolean(string);
-
- if (b == null)
- {
- if (getHeaders().containsKey(string))
- {
- Object str = getHeaders().getObject(string);
-
- if (str == null || !(str instanceof String))
- {
- throw new MessageFormatException("getBoolean can't use " + string + " item.");
- }
- else
- {
- return Boolean.valueOf((String) str);
- }
- }
- else
- {
- b = Boolean.valueOf(null);
- }
- }
-
- return b;
- }
-
- public boolean getBoolean(AMQShortString string) throws JMSException
- {
- checkPropertyName(string);
- Boolean b = getHeaders().getBoolean(string);
-
- if (b == null)
- {
- if (getHeaders().containsKey(string))
- {
- Object str = getHeaders().getObject(string);
-
- if (str == null || !(str instanceof String))
- {
- throw new MessageFormatException("getBoolean can't use " + string + " item.");
- }
- else
- {
- return Boolean.valueOf((String) str);
- }
- }
- else
- {
- b = Boolean.valueOf(null);
- }
- }
-
- return b;
- }
-
- public char getCharacter(String string) throws JMSException
- {
- checkPropertyName(string);
- Character c = getHeaders().getCharacter(string);
-
- if (c == null)
- {
- if (getHeaders().isNullStringValue(string))
- {
- throw new NullPointerException("Cannot convert null char");
- }
- else
- {
- throw new MessageFormatException("getChar can't use " + string + " item.");
- }
- }
- else
- {
- return (char) c;
- }
- }
-
- public byte[] getBytes(String string) throws JMSException
- {
- return getBytes(new AMQShortString(string));
- }
-
- public byte[] getBytes(AMQShortString string) throws JMSException
- {
- checkPropertyName(string);
-
- byte[] bs = getHeaders().getBytes(string);
-
- if (bs == null)
- {
- throw new MessageFormatException("getBytes can't use " + string + " item.");
- }
- else
- {
- return bs;
- }
- }
-
- public byte getByte(String string) throws JMSException
- {
- checkPropertyName(string);
- Byte b = getHeaders().getByte(string);
- if (b == null)
- {
- if (getHeaders().containsKey(string))
- {
- Object str = getHeaders().getObject(string);
-
- if (str == null || !(str instanceof String))
- {
- throw new MessageFormatException("getByte can't use " + string + " item.");
- }
- else
- {
- return Byte.valueOf((String) str);
- }
- }
- else
- {
- b = Byte.valueOf(null);
- }
- }
-
- return b;
- }
-
- public short getShort(String string) throws JMSException
- {
- checkPropertyName(string);
- Short s = getHeaders().getShort(string);
-
- if (s == null)
- {
- s = Short.valueOf(getByte(string));
- }
-
- return s;
- }
-
- public int getInteger(String string) throws JMSException
- {
- checkPropertyName(string);
- Integer i = getHeaders().getInteger(string);
-
- if (i == null)
- {
- i = Integer.valueOf(getShort(string));
- }
-
- return i;
- }
-
- public long getLong(String string) throws JMSException
- {
- checkPropertyName(string);
- Long l = getHeaders().getLong(string);
-
- if (l == null)
- {
- l = Long.valueOf(getInteger(string));
- }
-
- return l;
- }
-
- public float getFloat(String string) throws JMSException
- {
- checkPropertyName(string);
- Float f = getHeaders().getFloat(string);
-
- if (f == null)
- {
- if (getHeaders().containsKey(string))
- {
- Object str = getHeaders().getObject(string);
-
- if (str == null || !(str instanceof String))
- {
- throw new MessageFormatException("getFloat can't use " + string + " item.");
- }
- else
- {
- return Float.valueOf((String) str);
- }
- }
- else
- {
- throw new NullPointerException("No such property: " + string);
- }
-
- }
-
- return f;
- }
-
- public double getDouble(String string) throws JMSException
- {
- checkPropertyName(string);
- Double d = getHeaders().getDouble(string);
-
- if (d == null)
- {
- d = Double.valueOf(getFloat(string));
- }
-
- return d;
- }
-
- public String getString(String string) throws JMSException
- {
- checkPropertyName(string);
- String s = getHeaders().getString(string);
-
- if (s == null)
- {
- if (getHeaders().containsKey(string))
- {
- Object o = getHeaders().getObject(string);
- if (o instanceof byte[])
- {
- throw new MessageFormatException("getObject couldn't find " + string + " item.");
- }
- else
- {
- if (o == null)
- {
- return null;
- }
- else
- {
- s = String.valueOf(o);
- }
- }
- }//else return s // null;
- }
-
- return s;
- }
-
- public Object getObject(String string) throws JMSException
- {
- checkPropertyName(string);
- return getHeaders().getObject(string);
- }
-
- public void setBoolean(AMQShortString string, boolean b) throws JMSException
- {
- checkPropertyName(string);
- getHeaders().setBoolean(string, b);
- }
-
- public void setBoolean(String string, boolean b) throws JMSException
- {
- checkPropertyName(string);
- getHeaders().setBoolean(string, b);
- }
-
- public void setChar(String string, char c) throws JMSException
- {
- checkPropertyName(string);
- getHeaders().setChar(string, c);
- }
-
- public Object setBytes(AMQShortString string, byte[] bytes)
- {
- checkPropertyName(string);
- return getHeaders().setBytes(string, bytes);
- }
-
- public Object setBytes(String string, byte[] bytes)
- {
- checkPropertyName(string);
- return getHeaders().setBytes(string, bytes);
- }
-
- public Object setBytes(String string, byte[] bytes, int start, int length)
- {
- checkPropertyName(string);
- return getHeaders().setBytes(string, bytes, start, length);
- }
-
- public void setByte(String string, byte b) throws JMSException
- {
- checkPropertyName(string);
- getHeaders().setByte(string, b);
- }
-
- public void setByte(AMQShortString string, byte b) throws JMSException
- {
- checkPropertyName(string);
- getHeaders().setByte(string, b);
- }
-
-
- public void setShort(String string, short i) throws JMSException
- {
- checkPropertyName(string);
- getHeaders().setShort(string, i);
- }
-
- public void setInteger(String string, int i) throws JMSException
- {
- checkPropertyName(string);
- getHeaders().setInteger(string, i);
- }
-
- public void setInteger(AMQShortString string, int i) throws JMSException
- {
- checkPropertyName(string);
- getHeaders().setInteger(string, i);
- }
-
- public void setLong(String string, long l) throws JMSException
- {
- checkPropertyName(string);
- getHeaders().setLong(string, l);
- }
-
- public void setFloat(String string, float v) throws JMSException
- {
- checkPropertyName(string);
- getHeaders().setFloat(string, v);
- }
-
- public void setDouble(String string, double v) throws JMSException
- {
- checkPropertyName(string);
- getHeaders().setDouble(string, v);
- }
-
- public void setString(String string, String string1) throws JMSException
- {
- checkPropertyName(string);
- getHeaders().setString(string, string1);
- }
-
- public void setString(AMQShortString string, String string1) throws JMSException
- {
- checkPropertyName(string);
- getHeaders().setString(string, string1);
- }
-
- public void setObject(String string, Object object) throws JMSException
- {
- checkPropertyName(string);
- try
- {
- getHeaders().setObject(string, object);
- }
- catch (AMQPInvalidClassException aice)
- {
- MessageFormatException mfe = new MessageFormatException(AMQPInvalidClassException.INVALID_OBJECT_MSG + (object == null ? "null" : object.getClass()));
- mfe.setLinkedException(aice);
- mfe.initCause(aice);
- throw mfe;
- }
- }
-
- public boolean itemExists(String string) throws JMSException
- {
- checkPropertyName(string);
- return getHeaders().containsKey(string);
- }
-
- public Enumeration getPropertyNames()
- {
- return getHeaders().getPropertyNames();
- }
-
- public void clear()
- {
- getHeaders().clear();
- }
-
- public boolean propertyExists(AMQShortString propertyName)
- {
- checkPropertyName(propertyName);
- return getHeaders().propertyExists(propertyName);
- }
-
- public boolean propertyExists(String propertyName)
- {
- checkPropertyName(propertyName);
- return getHeaders().propertyExists(propertyName);
- }
-
- public Object put(Object key, Object value)
- {
- checkPropertyName(key.toString());
- return getHeaders().setObject(key.toString(), value);
- }
-
- public Object remove(AMQShortString propertyName)
- {
- checkPropertyName(propertyName);
- return getHeaders().remove(propertyName);
- }
-
- public Object remove(String propertyName)
- {
- checkPropertyName(propertyName);
- return getHeaders().remove(propertyName);
- }
-
- public boolean isEmpty()
- {
- return getHeaders().isEmpty();
- }
-
- public void writeToBuffer(ByteBuffer data)
- {
- getHeaders().writeToBuffer(data);
- }
-
- public Enumeration getMapNames()
- {
- return getPropertyNames();
- }
-
- protected void checkPropertyName(CharSequence propertyName)
- {
- if (propertyName == null)
- {
- throw new IllegalArgumentException("Property name must not be null");
- }
- else if (propertyName.length() == 0)
- {
- throw new IllegalArgumentException("Property name must not be the empty string");
- }
-
- checkIdentiferFormat(propertyName);
- }
-
- protected void checkIdentiferFormat(CharSequence propertyName)
- {
-// JMS requirements 3.5.1 Property Names
-// Identifiers:
-// - An identifier is an unlimited-length character sequence that must begin
-// with a Java identifier start character; all following characters must be Java
-// identifier part characters. An identifier start character is any character for
-// which the method Character.isJavaIdentifierStart returns true. This includes
-// '_' and '$'. An identifier part character is any character for which the
-// method Character.isJavaIdentifierPart returns true.
-// - Identifiers cannot be the names NULL, TRUE, or FALSE.
-// Identifiers cannot be NOT, AND, OR, BETWEEN, LIKE, IN, IS, or
-// ESCAPE.
-// Identifiers are either header field references or property references. The
-// type of a property value in a message selector corresponds to the type
-// used to set the property. If a property that does not exist in a message is
-// referenced, its value is NULL. The semantics of evaluating NULL values
-// in a selector are described in Section 3.8.1.2, Null Values.
-// The conversions that apply to the get methods for properties do not
-// apply when a property is used in a message selector expression. For
-// example, suppose you set a property as a string value, as in the
-// following:
-// myMessage.setStringProperty("NumberOfOrders", "2");
-// The following expression in a message selector would evaluate to false,
-// because a string cannot be used in an arithmetic expression:
-// "NumberOfOrders > 1"
-// Identifiers are case sensitive.
-// Message header field references are restricted to JMSDeliveryMode,
-// JMSPriority, JMSMessageID, JMSTimestamp, JMSCorrelationID, and
-// JMSType. JMSMessageID, JMSCorrelationID, and JMSType values may be
-// null and if so are treated as a NULL value.
-
- if (Boolean.getBoolean("strict-jms"))
- {
- // JMS start character
- if (!(Character.isJavaIdentifierStart(propertyName.charAt(0))))
- {
- throw new IllegalArgumentException("Identifier '" + propertyName + "' does not start with a valid JMS identifier start character");
- }
-
- // JMS part character
- int length = propertyName.length();
- for (int c = 1; c < length; c++)
- {
- if (!(Character.isJavaIdentifierPart(propertyName.charAt(c))))
- {
- throw new IllegalArgumentException("Identifier '" + propertyName + "' contains an invalid JMS identifier character");
- }
- }
-
- // JMS invalid names
- if ((propertyName.equals("NULL")
- || propertyName.equals("TRUE")
- || propertyName.equals("FALSE")
- || propertyName.equals("NOT")
- || propertyName.equals("AND")
- || propertyName.equals("OR")
- || propertyName.equals("BETWEEN")
- || propertyName.equals("LIKE")
- || propertyName.equals("IN")
- || propertyName.equals("IS")
- || propertyName.equals("ESCAPE")))
- {
- throw new IllegalArgumentException("Identifier '" + propertyName + "' is not allowed in JMS");
- }
- }
-
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/JMSMapMessage.java b/java/client/src/main/java/org/apache/qpid/client/message/JMSMapMessage.java
deleted file mode 100644
index 306ffeeadf..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/message/JMSMapMessage.java
+++ /dev/null
@@ -1,512 +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.client.message;
-
-import org.apache.mina.common.ByteBuffer;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.BasicContentHeaderProperties;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.jms.JMSException;
-import javax.jms.MessageFormatException;
-
-import java.nio.charset.CharacterCodingException;
-import java.util.Collections;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.Map;
-
-public class JMSMapMessage extends AbstractBytesTypedMessage implements javax.jms.MapMessage
-{
- private static final Logger _logger = LoggerFactory.getLogger(JMSMapMessage.class);
-
- public static final String MIME_TYPE = "jms/map-message";
-
- protected Map<String, Object> _map = new HashMap<String, Object>();
-
- public JMSMapMessage(AMQMessageDelegateFactory delegateFactory) throws JMSException
- {
- this(delegateFactory, null);
- }
-
- JMSMapMessage(AMQMessageDelegateFactory delegateFactory, ByteBuffer data) throws JMSException
- {
-
- super(delegateFactory, data); // this instantiates a content header
- if(data != null)
- {
- populateMapFromData();
- }
-
- }
-
- JMSMapMessage(AMQMessageDelegate delegate, ByteBuffer data) throws AMQException
- {
-
- super(delegate, data);
- try
- {
- populateMapFromData();
- }
- catch (JMSException je)
- {
- throw new AMQException(null, "Error populating MapMessage from ByteBuffer", je);
-
- }
-
- }
-
-
- public String toBodyString() throws JMSException
- {
- return _map == null ? "" : _map.toString();
- }
-
- protected String getMimeType()
- {
- return MIME_TYPE;
- }
-
- public ByteBuffer getData()
- {
- // What if _data is null?
- writeMapToData();
-
- return super.getData();
- }
-
- @Override
- public void clearBodyImpl() throws JMSException
- {
- super.clearBodyImpl();
- _map.clear();
- }
-
- public boolean getBoolean(String propName) throws JMSException
- {
- Object value = _map.get(propName);
-
- if (value instanceof Boolean)
- {
- return ((Boolean) value).booleanValue();
- }
- else if ((value instanceof String) || (value == null))
- {
- return Boolean.valueOf((String) value);
- }
- else
- {
- throw new MessageFormatException("Property " + propName + " of type " + value.getClass().getName()
- + " cannot be converted to boolean.");
- }
-
- }
-
- public byte getByte(String propName) throws JMSException
- {
- Object value = _map.get(propName);
-
- if (value instanceof Byte)
- {
- return ((Byte) value).byteValue();
- }
- else if ((value instanceof String) || (value == null))
- {
- return Byte.valueOf((String) value).byteValue();
- }
- else
- {
- throw new MessageFormatException("Property " + propName + " of type " + value.getClass().getName()
- + " cannot be converted to byte.");
- }
- }
-
- public short getShort(String propName) throws JMSException
- {
- Object value = _map.get(propName);
-
- if (value instanceof Short)
- {
- return ((Short) value).shortValue();
- }
- else if (value instanceof Byte)
- {
- return ((Byte) value).shortValue();
- }
- else if ((value instanceof String) || (value == null))
- {
- return Short.valueOf((String) value).shortValue();
- }
- else
- {
- throw new MessageFormatException("Property " + propName + " of type " + value.getClass().getName()
- + " cannot be converted to short.");
- }
-
- }
-
- public int getInt(String propName) throws JMSException
- {
- Object value = _map.get(propName);
-
- if (value instanceof Integer)
- {
- return ((Integer) value).intValue();
- }
- else if (value instanceof Short)
- {
- return ((Short) value).intValue();
- }
- else if (value instanceof Byte)
- {
- return ((Byte) value).intValue();
- }
- else if ((value instanceof String) || (value == null))
- {
- return Integer.valueOf((String) value).intValue();
- }
- else
- {
- throw new MessageFormatException("Property " + propName + " of type " + value.getClass().getName()
- + " cannot be converted to int.");
- }
-
- }
-
- public long getLong(String propName) throws JMSException
- {
- Object value = _map.get(propName);
-
- if (value instanceof Long)
- {
- return ((Long) value).longValue();
- }
- else if (value instanceof Integer)
- {
- return ((Integer) value).longValue();
- }
-
- if (value instanceof Short)
- {
- return ((Short) value).longValue();
- }
-
- if (value instanceof Byte)
- {
- return ((Byte) value).longValue();
- }
- else if ((value instanceof String) || (value == null))
- {
- return Long.valueOf((String) value).longValue();
- }
- else
- {
- throw new MessageFormatException("Property " + propName + " of type " + value.getClass().getName()
- + " cannot be converted to long.");
- }
-
- }
-
- public char getChar(String propName) throws JMSException
- {
- Object value = _map.get(propName);
-
- if (!_map.containsKey(propName))
- {
- throw new MessageFormatException("Property " + propName + " not present");
- }
- else if (value instanceof Character)
- {
- return ((Character) value).charValue();
- }
- else if (value == null)
- {
- throw new NullPointerException("Property " + propName + " has null value and therefore cannot "
- + "be converted to char.");
- }
- else
- {
- throw new MessageFormatException("Property " + propName + " of type " + value.getClass().getName()
- + " cannot be converted to boolan.");
- }
-
- }
-
- public float getFloat(String propName) throws JMSException
- {
- Object value = _map.get(propName);
-
- if (value instanceof Float)
- {
- return ((Float) value).floatValue();
- }
- else if ((value instanceof String) || (value == null))
- {
- return Float.valueOf((String) value).floatValue();
- }
- else
- {
- throw new MessageFormatException("Property " + propName + " of type " + value.getClass().getName()
- + " cannot be converted to float.");
- }
- }
-
- public double getDouble(String propName) throws JMSException
- {
- Object value = _map.get(propName);
-
- if (value instanceof Double)
- {
- return ((Double) value).doubleValue();
- }
- else if (value instanceof Float)
- {
- return ((Float) value).doubleValue();
- }
- else if ((value instanceof String) || (value == null))
- {
- return Double.valueOf((String) value).doubleValue();
- }
- else
- {
- throw new MessageFormatException("Property " + propName + " of type " + value.getClass().getName()
- + " cannot be converted to double.");
- }
- }
-
- public String getString(String propName) throws JMSException
- {
- Object value = _map.get(propName);
-
- if ((value instanceof String) || (value == null))
- {
- return (String) value;
- }
- else if (value instanceof byte[])
- {
- throw new MessageFormatException("Property " + propName + " of type byte[] " + "cannot be converted to String.");
- }
- else
- {
- return value.toString();
- }
-
- }
-
- public byte[] getBytes(String propName) throws JMSException
- {
- Object value = _map.get(propName);
-
- if (!_map.containsKey(propName))
- {
- throw new MessageFormatException("Property " + propName + " not present");
- }
- else if ((value instanceof byte[]) || (value == null))
- {
- return (byte[]) value;
- }
- else
- {
- throw new MessageFormatException("Property " + propName + " of type " + value.getClass().getName()
- + " cannot be converted to byte[].");
- }
- }
-
- public Object getObject(String propName) throws JMSException
- {
- return _map.get(propName);
- }
-
- public Enumeration getMapNames() throws JMSException
- {
- return Collections.enumeration(_map.keySet());
- }
-
- public void setBoolean(String propName, boolean b) throws JMSException
- {
- checkWritable();
- checkPropertyName(propName);
- _map.put(propName, b);
- }
-
- public void setByte(String propName, byte b) throws JMSException
- {
- checkWritable();
- checkPropertyName(propName);
- _map.put(propName, b);
- }
-
- public void setShort(String propName, short i) throws JMSException
- {
- checkWritable();
- checkPropertyName(propName);
- _map.put(propName, i);
- }
-
- public void setChar(String propName, char c) throws JMSException
- {
- checkWritable();
- checkPropertyName(propName);
- _map.put(propName, c);
- }
-
- public void setInt(String propName, int i) throws JMSException
- {
- checkWritable();
- checkPropertyName(propName);
- _map.put(propName, i);
- }
-
- public void setLong(String propName, long l) throws JMSException
- {
- checkWritable();
- checkPropertyName(propName);
- _map.put(propName, l);
- }
-
- public void setFloat(String propName, float v) throws JMSException
- {
- checkWritable();
- checkPropertyName(propName);
- _map.put(propName, v);
- }
-
- public void setDouble(String propName, double v) throws JMSException
- {
- checkWritable();
- checkPropertyName(propName);
- _map.put(propName, v);
- }
-
- public void setString(String propName, String string1) throws JMSException
- {
- checkWritable();
- checkPropertyName(propName);
- _map.put(propName, string1);
- }
-
- public void setBytes(String propName, byte[] bytes) throws JMSException
- {
- checkWritable();
- checkPropertyName(propName);
- _map.put(propName, bytes);
- }
-
- public void setBytes(String propName, byte[] bytes, int offset, int length) throws JMSException
- {
- if ((offset == 0) && (length == bytes.length))
- {
- setBytes(propName, bytes);
- }
- else
- {
- byte[] newBytes = new byte[length];
- System.arraycopy(bytes, offset, newBytes, 0, length);
- setBytes(propName, newBytes);
- }
- }
-
- public void setObject(String propName, Object value) throws JMSException
- {
- checkWritable();
- checkPropertyName(propName);
- if ((value instanceof Boolean) || (value instanceof Byte) || (value instanceof Short) || (value instanceof Integer)
- || (value instanceof Long) || (value instanceof Character) || (value instanceof Float)
- || (value instanceof Double) || (value instanceof String) || (value instanceof byte[]) || (value == null))
- {
- _map.put(propName, value);
- }
- else
- {
- throw new MessageFormatException("Cannot set property " + propName + " to value " + value + "of type "
- + value.getClass().getName() + ".");
- }
- }
-
- protected void checkPropertyName(String propName)
- {
- if ((propName == null) || propName.equals(""))
- {
- throw new IllegalArgumentException("Property name cannot be null, or the empty String.");
- }
- }
-
- public boolean itemExists(String propName) throws JMSException
- {
- return _map.containsKey(propName);
- }
-
- protected void populateMapFromData() throws JMSException
- {
- if (_data != null)
- {
- _data.rewind();
-
- final int entries = readIntImpl();
- for (int i = 0; i < entries; i++)
- {
- String propName = readStringImpl();
- Object value = readObject();
- _map.put(propName, value);
- }
- }
- else
- {
- _map.clear();
- }
- }
-
- protected void writeMapToData()
- {
- allocateInitialBuffer();
- final int size = _map.size();
- writeIntImpl(size);
- for (Map.Entry<String, Object> entry : _map.entrySet())
- {
- try
- {
- writeStringImpl(entry.getKey());
- }
- catch (CharacterCodingException e)
- {
- throw new IllegalArgumentException("Cannot encode property key name " + entry.getKey(), e);
-
- }
-
- try
- {
- writeObject(entry.getValue());
- }
- catch (JMSException e)
- {
- Object value = entry.getValue();
- throw new IllegalArgumentException("Cannot encode property key name " + entry.getKey() + " value : " + value
- + " (type: " + value.getClass().getName() + ").", e);
- }
- }
-
- }
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/JMSMapMessageFactory.java b/java/client/src/main/java/org/apache/qpid/client/message/JMSMapMessageFactory.java
deleted file mode 100644
index eccb90560b..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/message/JMSMapMessageFactory.java
+++ /dev/null
@@ -1,42 +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.client.message;
-
-import javax.jms.JMSException;
-
-import org.apache.mina.common.ByteBuffer;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.BasicContentHeaderProperties;
-
-public class JMSMapMessageFactory extends AbstractJMSMessageFactory
-{
- public AbstractJMSMessage createMessage(AMQMessageDelegateFactory delegateFactory) throws JMSException
- {
- return new JMSMapMessage(delegateFactory);
- }
-
- protected AbstractJMSMessage createMessage(AMQMessageDelegate delegate, ByteBuffer data) throws AMQException
- {
- return new JMSMapMessage(delegate, data);
-
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/JMSObjectMessage.java b/java/client/src/main/java/org/apache/qpid/client/message/JMSObjectMessage.java
deleted file mode 100644
index 637d9dd692..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/message/JMSObjectMessage.java
+++ /dev/null
@@ -1,176 +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.client.message;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.io.Serializable;
-
-import javax.jms.JMSException;
-import javax.jms.MessageFormatException;
-import javax.jms.ObjectMessage;
-
-import org.apache.mina.common.ByteBuffer;
-
-import org.apache.qpid.AMQException;
-
-public class JMSObjectMessage extends AbstractJMSMessage implements ObjectMessage
-{
- public static final String MIME_TYPE = "application/java-object-stream";
-
-
- private static final int DEFAULT_BUFFER_SIZE = 1024;
-
- /**
- * Creates empty, writable message for use by producers
- * @param delegateFactory
- */
- public JMSObjectMessage(AMQMessageDelegateFactory delegateFactory)
- {
- this(delegateFactory, null);
- }
-
- private JMSObjectMessage(AMQMessageDelegateFactory delegateFactory, ByteBuffer data)
- {
- super(delegateFactory, data);
- if (data == null)
- {
- _data = ByteBuffer.allocate(DEFAULT_BUFFER_SIZE);
- _data.setAutoExpand(true);
- }
-
- setContentType(getMimeType());
- }
-
- /**
- * Creates read only message for delivery to consumers
- */
-
- JMSObjectMessage(AMQMessageDelegate delegate, ByteBuffer data) throws AMQException
- {
- super(delegate, data);
- }
-
-
- public void clearBodyImpl() throws JMSException
- {
- if (_data != null)
- {
- _data.release();
- _data = null;
- }
-
-
-
- }
-
- public String toBodyString() throws JMSException
- {
- return String.valueOf(getObject());
- }
-
- public String getMimeType()
- {
- return MIME_TYPE;
- }
-
- public void setObject(Serializable serializable) throws JMSException
- {
- checkWritable();
-
- if (_data == null)
- {
- _data = ByteBuffer.allocate(DEFAULT_BUFFER_SIZE);
- _data.setAutoExpand(true);
- }
- else
- {
- _data.rewind();
- }
-
- try
- {
- ObjectOutputStream out = new ObjectOutputStream(_data.asOutputStream());
- out.writeObject(serializable);
- out.flush();
- out.close();
- }
- catch (IOException e)
- {
- MessageFormatException mfe = new MessageFormatException("Message not serializable: " + e);
- mfe.setLinkedException(e);
- mfe.initCause(e);
- throw mfe;
- }
-
- }
-
- public Serializable getObject() throws JMSException
- {
- ObjectInputStream in = null;
- if (_data == null)
- {
- return null;
- }
-
- try
- {
- _data.rewind();
- in = new ObjectInputStream(_data.asInputStream());
-
- return (Serializable) in.readObject();
- }
- catch (IOException e)
- {
- MessageFormatException mfe = new MessageFormatException("Could not deserialize message: " + e);
- mfe.setLinkedException(e);
- mfe.initCause(e);
- throw mfe;
- }
- catch (ClassNotFoundException e)
- {
- MessageFormatException mfe = new MessageFormatException("Could not deserialize message: " + e);
- mfe.setLinkedException(e);
- mfe.initCause(e);
- throw mfe;
- }
- finally
- {
- // _data.rewind();
- close(in);
- }
- }
-
- private static void close(InputStream in)
- {
- try
- {
- if (in != null)
- {
- in.close();
- }
- }
- catch (IOException ignore)
- { }
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/JMSObjectMessageFactory.java b/java/client/src/main/java/org/apache/qpid/client/message/JMSObjectMessageFactory.java
deleted file mode 100644
index 03851dfa01..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/message/JMSObjectMessageFactory.java
+++ /dev/null
@@ -1,41 +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.client.message;
-
-import javax.jms.JMSException;
-
-import org.apache.mina.common.ByteBuffer;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.BasicContentHeaderProperties;
-
-public class JMSObjectMessageFactory extends AbstractJMSMessageFactory
-{
- protected AbstractJMSMessage createMessage(AMQMessageDelegate delegate, ByteBuffer data) throws AMQException
- {
- return new JMSObjectMessage(delegate, data);
- }
-
- public AbstractJMSMessage createMessage(AMQMessageDelegateFactory delegateFactory) throws JMSException
- {
- return new JMSObjectMessage(delegateFactory);
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/JMSStreamMessage.java b/java/client/src/main/java/org/apache/qpid/client/message/JMSStreamMessage.java
deleted file mode 100644
index ad2620852b..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/message/JMSStreamMessage.java
+++ /dev/null
@@ -1,206 +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.client.message;
-
-import javax.jms.JMSException;
-import javax.jms.StreamMessage;
-
-import org.apache.mina.common.ByteBuffer;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.BasicContentHeaderProperties;
-
-/**
- * @author Apache Software Foundation
- */
-public class JMSStreamMessage extends AbstractBytesTypedMessage implements StreamMessage
-{
- public static final String MIME_TYPE="jms/stream-message";
-
-
-
- /**
- * This is set when reading a byte array. The readBytes(byte[]) method supports multiple calls to read
- * a byte array in multiple chunks, hence this is used to track how much is left to be read
- */
- private int _byteArrayRemaining = -1;
-
- public JMSStreamMessage(AMQMessageDelegateFactory delegateFactory)
- {
- this(delegateFactory,null);
-
- }
-
- /**
- * Construct a stream message with existing data.
- *
- * @param delegateFactory
- * @param data the data that comprises this message. If data is null, you get a 1024 byte buffer that is
- */
- JMSStreamMessage(AMQMessageDelegateFactory delegateFactory, ByteBuffer data)
- {
-
- super(delegateFactory, data); // this instanties a content header
- }
-
- JMSStreamMessage(AMQMessageDelegate delegate, ByteBuffer data) throws AMQException
- {
-
- super(delegate, data);
- }
-
-
- public void reset()
- {
- super.reset();
- _readableMessage = true;
- }
-
- protected String getMimeType()
- {
- return MIME_TYPE;
- }
-
-
-
- public boolean readBoolean() throws JMSException
- {
- return super.readBoolean();
- }
-
-
- public byte readByte() throws JMSException
- {
- return super.readByte();
- }
-
- public short readShort() throws JMSException
- {
- return super.readShort();
- }
-
- /**
- * Note that this method reads a unicode character as two bytes from the stream
- *
- * @return the character read from the stream
- * @throws JMSException
- */
- public char readChar() throws JMSException
- {
- return super.readChar();
- }
-
- public int readInt() throws JMSException
- {
- return super.readInt();
- }
-
- public long readLong() throws JMSException
- {
- return super.readLong();
- }
-
- public float readFloat() throws JMSException
- {
- return super.readFloat();
- }
-
- public double readDouble() throws JMSException
- {
- return super.readDouble();
- }
-
- public String readString() throws JMSException
- {
- return super.readString();
- }
-
- public int readBytes(byte[] bytes) throws JMSException
- {
- return super.readBytes(bytes);
- }
-
-
- public Object readObject() throws JMSException
- {
- return super.readObject();
- }
-
- public void writeBoolean(boolean b) throws JMSException
- {
- super.writeBoolean(b);
- }
-
- public void writeByte(byte b) throws JMSException
- {
- super.writeByte(b);
- }
-
- public void writeShort(short i) throws JMSException
- {
- super.writeShort(i);
- }
-
- public void writeChar(char c) throws JMSException
- {
- super.writeChar(c);
- }
-
- public void writeInt(int i) throws JMSException
- {
- super.writeInt(i);
- }
-
- public void writeLong(long l) throws JMSException
- {
- super.writeLong(l);
- }
-
- public void writeFloat(float v) throws JMSException
- {
- super.writeFloat(v);
- }
-
- public void writeDouble(double v) throws JMSException
- {
- super.writeDouble(v);
- }
-
- public void writeString(String string) throws JMSException
- {
- super.writeString(string);
- }
-
- public void writeBytes(byte[] bytes) throws JMSException
- {
- super.writeBytes(bytes);
- }
-
- public void writeBytes(byte[] bytes, int offset, int length) throws JMSException
- {
- super.writeBytes(bytes,offset,length);
- }
-
- public void writeObject(Object object) throws JMSException
- {
- super.writeObject(object);
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/JMSStreamMessageFactory.java b/java/client/src/main/java/org/apache/qpid/client/message/JMSStreamMessageFactory.java
deleted file mode 100644
index 5e25db9ae0..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/message/JMSStreamMessageFactory.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.client.message;
-
-import javax.jms.JMSException;
-
-import org.apache.mina.common.ByteBuffer;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.BasicContentHeaderProperties;
-
-public class JMSStreamMessageFactory extends AbstractJMSMessageFactory
-{
- protected AbstractJMSMessage createMessage(AMQMessageDelegate delegate, ByteBuffer data) throws AMQException
- {
- return new JMSStreamMessage(delegate, data);
- }
- public AbstractJMSMessage createMessage(AMQMessageDelegateFactory delegateFactory) throws JMSException
- {
- return new JMSStreamMessage(delegateFactory);
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/JMSTextMessage.java b/java/client/src/main/java/org/apache/qpid/client/message/JMSTextMessage.java
deleted file mode 100644
index fc2006a119..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/message/JMSTextMessage.java
+++ /dev/null
@@ -1,189 +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.client.message;
-
-import java.io.UnsupportedEncodingException;
-import java.nio.charset.CharacterCodingException;
-import java.nio.charset.Charset;
-
-import javax.jms.JMSException;
-
-import org.apache.mina.common.ByteBuffer;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.CustomJMSXProperty;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.BasicContentHeaderProperties;
-import org.apache.qpid.util.Strings;
-
-public class JMSTextMessage extends AbstractJMSMessage implements javax.jms.TextMessage
-{
- private static final String MIME_TYPE = "text/plain";
-
- private String _decodedValue;
-
- /**
- * This constant represents the name of a property that is set when the message payload is null.
- */
- private static final String PAYLOAD_NULL_PROPERTY = CustomJMSXProperty.JMS_AMQP_NULL.toString();
- private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
-
- public JMSTextMessage(AMQMessageDelegateFactory delegateFactory) throws JMSException
- {
- this(delegateFactory, null, null);
- }
-
- JMSTextMessage(AMQMessageDelegateFactory delegateFactory, ByteBuffer data, String encoding) throws JMSException
- {
- super(delegateFactory, data); // this instantiates a content header
- setContentType(getMimeType());
- setEncoding(encoding);
- }
-
- JMSTextMessage(AMQMessageDelegate delegate, ByteBuffer data)
- throws AMQException
- {
- super(delegate, data);
- setContentType(getMimeType());
- _data = data;
- }
-
-
- public void clearBodyImpl() throws JMSException
- {
- if (_data != null)
- {
- _data.release();
- _data = null;
- }
-
- _decodedValue = null;
- }
-
- public String toBodyString() throws JMSException
- {
- return getText();
- }
-
- protected String getMimeType()
- {
- return MIME_TYPE;
- }
-
- public void setText(String text) throws JMSException
- {
- checkWritable();
-
- clearBody();
- try
- {
- if (text != null)
- {
- final String encoding = getEncoding();
- if (encoding == null || encoding.equalsIgnoreCase("UTF-8"))
- {
- _data = ByteBuffer.wrap(Strings.toUTF8(text));
- setEncoding("UTF-8");
- }
- else
- {
- _data = ByteBuffer.wrap(text.getBytes(encoding));
- }
- _data.position(_data.limit());
- _changedData=true;
- }
- _decodedValue = text;
- }
- catch (UnsupportedEncodingException e)
- {
- // should never occur
- JMSException jmse = new JMSException("Unable to decode text data");
- jmse.setLinkedException(e);
- jmse.initCause(e);
- throw jmse;
- }
- }
-
- public String getText() throws JMSException
- {
- if (_data == null && _decodedValue == null)
- {
- return null;
- }
- else if (_decodedValue != null)
- {
- return _decodedValue;
- }
- else
- {
- _data.rewind();
-
- if (propertyExists(PAYLOAD_NULL_PROPERTY) && getBooleanProperty(PAYLOAD_NULL_PROPERTY))
- {
- return null;
- }
- if (getEncoding() != null)
- {
- try
- {
- _decodedValue = _data.getString(Charset.forName(getEncoding()).newDecoder());
- }
- catch (CharacterCodingException e)
- {
- JMSException jmse = new JMSException("Could not decode string data: " + e);
- jmse.setLinkedException(e);
- jmse.initCause(e);
- throw jmse;
- }
- }
- else
- {
- try
- {
- _decodedValue = _data.getString(DEFAULT_CHARSET.newDecoder());
- }
- catch (CharacterCodingException e)
- {
- JMSException jmse = new JMSException("Could not decode string data: " + e);
- jmse.setLinkedException(e);
- jmse.initCause(e);
- throw jmse;
- }
- }
- return _decodedValue;
- }
- }
-
- @Override
- public void prepareForSending() throws JMSException
- {
- super.prepareForSending();
- if (_data == null)
- {
- setBooleanProperty(PAYLOAD_NULL_PROPERTY, true);
- }
- else
- {
- removeProperty(PAYLOAD_NULL_PROPERTY);
- }
- }
-
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/JMSTextMessageFactory.java b/java/client/src/main/java/org/apache/qpid/client/message/JMSTextMessageFactory.java
deleted file mode 100644
index 1f4d64c78f..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/message/JMSTextMessageFactory.java
+++ /dev/null
@@ -1,42 +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.client.message;
-
-import javax.jms.JMSException;
-
-import org.apache.mina.common.ByteBuffer;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.BasicContentHeaderProperties;
-
-public class JMSTextMessageFactory extends AbstractJMSMessageFactory
-{
-
- public AbstractJMSMessage createMessage(AMQMessageDelegateFactory delegateFactory) throws JMSException
- {
- return new JMSTextMessage(delegateFactory);
- }
-
- protected AbstractJMSMessage createMessage(AMQMessageDelegate delegate, ByteBuffer data) throws AMQException
- {
- return new JMSTextMessage(delegate, data);
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/MessageConverter.java b/java/client/src/main/java/org/apache/qpid/client/message/MessageConverter.java
deleted file mode 100644
index e606ef11c9..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/message/MessageConverter.java
+++ /dev/null
@@ -1,195 +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.client.message;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.qpid.client.AMQSession;
-
-import javax.jms.*;
-
-import java.util.Enumeration;
-
-public class MessageConverter
-{
-
- /**
- * Log4J logger
- */
- protected final Logger _logger = LoggerFactory.getLogger(getClass());
-
- /**
- * AbstractJMSMessage which will hold the converted message
- */
- private AbstractJMSMessage _newMessage;
-
- public MessageConverter(AbstractJMSMessage message) throws JMSException
- {
- _newMessage = message;
- }
-
- public MessageConverter(AMQSession session, BytesMessage bytesMessage) throws JMSException
- {
- bytesMessage.reset();
-
- JMSBytesMessage nativeMsg = (JMSBytesMessage) session.createBytesMessage();
-
- byte[] buf = new byte[1024];
-
- int len;
-
- while ((len = bytesMessage.readBytes(buf)) != -1)
- {
- nativeMsg.writeBytes(buf, 0, len);
- }
-
- _newMessage = nativeMsg;
- setMessageProperties(bytesMessage);
- }
-
- public MessageConverter(AMQSession session, MapMessage message) throws JMSException
- {
- MapMessage nativeMessage = session.createMapMessage();
-
- Enumeration mapNames = message.getMapNames();
- while (mapNames.hasMoreElements())
- {
- String name = (String) mapNames.nextElement();
- nativeMessage.setObject(name, message.getObject(name));
- }
-
- _newMessage = (AbstractJMSMessage) nativeMessage;
- setMessageProperties(message);
- }
-
- public MessageConverter(AMQSession session, ObjectMessage origMessage) throws JMSException
- {
-
- ObjectMessage nativeMessage = session.createObjectMessage();
-
- nativeMessage.setObject(origMessage.getObject());
-
- _newMessage = (AbstractJMSMessage) nativeMessage;
- setMessageProperties(origMessage);
-
- }
-
- public MessageConverter(AMQSession session, TextMessage message) throws JMSException
- {
- TextMessage nativeMessage = session.createTextMessage();
-
- nativeMessage.setText(message.getText());
-
- _newMessage = (AbstractJMSMessage) nativeMessage;
- setMessageProperties(message);
- }
-
- public MessageConverter(AMQSession session, StreamMessage message) throws JMSException
- {
- StreamMessage nativeMessage = session.createStreamMessage();
-
- try
- {
- message.reset();
- while (true)
- {
- nativeMessage.writeObject(message.readObject());
- }
- }
- catch (MessageEOFException e)
- {
- // we're at the end so don't mind the exception
- }
-
- _newMessage = (AbstractJMSMessage) nativeMessage;
- setMessageProperties(message);
- }
-
- public MessageConverter(AMQSession session, Message message) throws JMSException
- {
- // Send a message with just properties.
- // Throwing away content
- Message nativeMessage = session.createMessage();
-
- _newMessage = (AbstractJMSMessage) nativeMessage;
- setMessageProperties(message);
- }
-
- public AbstractJMSMessage getConvertedMessage()
- {
- return _newMessage;
- }
-
- /**
- * Sets all message properties
- */
- protected void setMessageProperties(Message message) throws JMSException
- {
- setNonJMSProperties(message);
- setJMSProperties(message);
- }
-
- /**
- * Sets all non-JMS defined properties on converted message
- */
- protected void setNonJMSProperties(Message message) throws JMSException
- {
- Enumeration propertyNames = message.getPropertyNames();
- while (propertyNames.hasMoreElements())
- {
- String propertyName = String.valueOf(propertyNames.nextElement());
- // TODO: Shouldn't need to check for JMS properties here as don't think getPropertyNames() should return them
- if (!propertyName.startsWith("JMSX_"))
- {
- Object value = message.getObjectProperty(propertyName);
- _newMessage.setObjectProperty(propertyName, value);
- }
- }
- }
-
- /**
- * Exposed JMS defined properties on converted message:
- * JMSDestination - we don't set here
- * JMSDeliveryMode - set
- * JMSExpiration - we don't set here
- * JMSPriority - we don't set here
- * JMSMessageID - we don't set here
- * JMSTimestamp - we don't set here
- * JMSCorrelationID - set
- * JMSReplyTo - set
- * JMSType - set
- * JMSRedlivered - we don't set here
- */
- protected void setJMSProperties(Message message) throws JMSException
- {
- _newMessage.setJMSDeliveryMode(message.getJMSDeliveryMode());
-
- if (message.getJMSReplyTo() != null)
- {
- _newMessage.setJMSReplyTo(message.getJMSReplyTo());
- }
-
- _newMessage.setJMSType(message.getJMSType());
-
- _newMessage.setJMSCorrelationID(message.getJMSCorrelationID());
- }
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/MessageFactory.java b/java/client/src/main/java/org/apache/qpid/client/message/MessageFactory.java
deleted file mode 100644
index f3d96cd855..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/message/MessageFactory.java
+++ /dev/null
@@ -1,49 +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.client.message;
-
-import java.util.List;
-
-import javax.jms.JMSException;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.ContentHeaderBody;
-import org.apache.qpid.transport.DeliveryProperties;
-import org.apache.qpid.transport.MessageProperties;
-
-
-public interface MessageFactory
-{
- AbstractJMSMessage createMessage(long deliveryTag, boolean redelivered,
- ContentHeaderBody contentHeader,
- AMQShortString exchange, AMQShortString routingKey,
- List bodies)
- throws JMSException, AMQException;
-
- AbstractJMSMessage createMessage(long deliveryTag, boolean redelivered,
- MessageProperties msgProps,
- DeliveryProperties deliveryProps,
- java.nio.ByteBuffer body)
- throws JMSException, AMQException;
-
- AbstractJMSMessage createMessage(AMQMessageDelegateFactory delegateFactory) throws JMSException;
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/MessageFactoryRegistry.java b/java/client/src/main/java/org/apache/qpid/client/message/MessageFactoryRegistry.java
deleted file mode 100644
index cdb75fc9a9..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/message/MessageFactoryRegistry.java
+++ /dev/null
@@ -1,173 +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.client.message;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.nio.ByteBuffer;
-
-import javax.jms.JMSException;
-
-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.transport.Struct;
-import org.apache.qpid.transport.MessageProperties;
-import org.apache.qpid.transport.MessageTransfer;
-import org.apache.qpid.transport.DeliveryProperties;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class MessageFactoryRegistry
-{
- /**
- * This class logger
- */
- protected final Logger _logger = LoggerFactory.getLogger(getClass());
-
- private final Map<String, MessageFactory> _mimeStringToFactoryMap = new HashMap<String, MessageFactory>();
- private final Map<AMQShortString, MessageFactory> _mimeShortStringToFactoryMap =
- new HashMap<AMQShortString, MessageFactory>();
- private final MessageFactory _default = new JMSBytesMessageFactory();
-
- /**
- * Construct a new registry with the default message factories registered
- *
- * @return a message factory registry
- */
- public static MessageFactoryRegistry newDefaultRegistry()
- {
- MessageFactoryRegistry mf = new MessageFactoryRegistry();
- mf.registerFactory(JMSMapMessage.MIME_TYPE, new JMSMapMessageFactory());
- mf.registerFactory("text/plain", new JMSTextMessageFactory());
- mf.registerFactory("text/xml", new JMSTextMessageFactory());
- mf.registerFactory(JMSBytesMessage.MIME_TYPE, new JMSBytesMessageFactory());
- mf.registerFactory(JMSObjectMessage.MIME_TYPE, new JMSObjectMessageFactory());
- mf.registerFactory(JMSStreamMessage.MIME_TYPE, new JMSStreamMessageFactory());
- mf.registerFactory(AMQPEncodedMapMessage.MIME_TYPE, new AMQPEncodedMapMessageFactory());
- mf.registerFactory(null, mf._default);
-
- return mf;
- }
-
-
- public void registerFactory(String mimeType, MessageFactory mf)
- {
- if (mf == null)
- {
- throw new IllegalArgumentException("Message factory must not be null");
- }
-
- _mimeStringToFactoryMap.put(mimeType, mf);
- _mimeShortStringToFactoryMap.put(new AMQShortString(mimeType), mf);
- }
-
- public MessageFactory deregisterFactory(String mimeType)
- {
- _mimeShortStringToFactoryMap.remove(new AMQShortString(mimeType));
-
- return _mimeStringToFactoryMap.remove(mimeType);
- }
-
- /**
- * Create a message. This looks up the MIME type from the content header and instantiates the appropriate
- * concrete message type.
- *
- * @param deliveryTag the AMQ message id
- * @param redelivered true if redelivered
- * @param contentHeader the content header that was received
- * @param bodies a list of ContentBody instances @return the message.
- * @throws AMQException
- * @throws JMSException
- */
- public AbstractJMSMessage createMessage(long deliveryTag, boolean redelivered, AMQShortString exchange,
- AMQShortString routingKey, ContentHeaderBody contentHeader, List bodies)
- throws AMQException, JMSException
- {
- BasicContentHeaderProperties properties = (BasicContentHeaderProperties) contentHeader.getProperties();
-
- // Get the message content type. This may be null for pure AMQP messages, but will always be set for JMS over
- // AMQP. When the type is null, it can only be assumed that the message is a byte message.
- AMQShortString contentTypeShortString = properties.getContentType();
- contentTypeShortString = (contentTypeShortString == null) ? new AMQShortString(
- JMSBytesMessage.MIME_TYPE) : contentTypeShortString;
-
- MessageFactory mf = _mimeShortStringToFactoryMap.get(contentTypeShortString);
- if (mf == null)
- {
- mf = _default;
- }
-
- return mf.createMessage(deliveryTag, redelivered, contentHeader, exchange, routingKey, bodies);
- }
-
- public AbstractJMSMessage createMessage(MessageTransfer transfer) throws AMQException, JMSException
- {
-
- MessageProperties mprop = transfer.getHeader().get(MessageProperties.class);
- String messageType = "";
- if ( mprop == null || mprop.getContentType() == null)
- {
- _logger.debug("no message type specified, building a byte message");
- messageType = JMSBytesMessage.MIME_TYPE;
- }
- else
- {
- messageType = mprop.getContentType();
- }
- MessageFactory mf = _mimeStringToFactoryMap.get(messageType);
- if (mf == null)
- {
- mf = _default;
- }
-
- boolean redelivered = false;
- DeliveryProperties deliverProps;
- if((deliverProps = transfer.getHeader().get(DeliveryProperties.class)) != null)
- {
- redelivered = deliverProps.getRedelivered();
- }
- return mf.createMessage(transfer.getId(),
- redelivered,
- mprop == null? new MessageProperties():mprop,
- deliverProps == null? new DeliveryProperties():deliverProps,
- transfer.getBody());
- }
-
-
- public AbstractJMSMessage createMessage(AMQMessageDelegateFactory delegateFactory, String mimeType) throws AMQException, JMSException
- {
- if (mimeType == null)
- {
- throw new IllegalArgumentException("Mime type must not be null");
- }
-
- MessageFactory mf = _mimeStringToFactoryMap.get(mimeType);
- if (mf == null)
- {
- mf = _default;
- }
-
- return mf.createMessage(delegateFactory);
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/ReturnMessage.java b/java/client/src/main/java/org/apache/qpid/client/message/ReturnMessage.java
deleted file mode 100644
index 6e5f33a65c..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/message/ReturnMessage.java
+++ /dev/null
@@ -1,47 +0,0 @@
-package org.apache.qpid.client.message;
-/*
- *
- * 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.framing.AMQShortString;
-
-public class ReturnMessage extends UnprocessedMessage_0_8
-{
- final private AMQShortString _replyText;
- final private int _replyCode;
-
- public ReturnMessage(AMQShortString exchange, AMQShortString routingKey, AMQShortString replyText, int replyCode)
- {
- super(-1,0,exchange,routingKey,false);
- _replyText = replyText;
- _replyCode = replyCode;
- }
-
- public int getReplyCode()
- {
- return _replyCode;
- }
-
- public AMQShortString getReplyText()
- {
- return _replyText;
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/UnprocessedMessage.java b/java/client/src/main/java/org/apache/qpid/client/message/UnprocessedMessage.java
deleted file mode 100644
index e2cb36a030..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/message/UnprocessedMessage.java
+++ /dev/null
@@ -1,58 +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.client.message;
-
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.client.BasicMessageConsumer;
-
-
-/**
- * This class contains everything needed to process a JMS message. It assembles the deliver body, the content header and
- * the content body/ies.
- *
- * Note that the actual work of creating a JMS message for the client code's use is done outside of the MINA dispatcher
- * thread in order to minimise the amount of work done in the MINA dispatcher thread.
- */
-public abstract class UnprocessedMessage implements AMQSession.Dispatchable
-{
- private final int _consumerTag;
-
-
- public UnprocessedMessage(int consumerTag)
- {
- _consumerTag = consumerTag;
- }
-
-
- abstract public long getDeliveryTag();
-
-
- public int getConsumerTag()
- {
- return _consumerTag;
- }
-
- public void dispatch(AMQSession ssn)
- {
- ssn.dispatch(this);
- }
-
-} \ No newline at end of file
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/UnprocessedMessage_0_10.java b/java/client/src/main/java/org/apache/qpid/client/message/UnprocessedMessage_0_10.java
deleted file mode 100644
index f31bc88509..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/message/UnprocessedMessage_0_10.java
+++ /dev/null
@@ -1,53 +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.client.message;
-
-import org.apache.qpid.transport.MessageTransfer;
-
-/**
- * This class contains everything needed to process a JMS message. It assembles the deliver body, the content header and
- * the content body/ies.
- *
- * Note that the actual work of creating a JMS message for the client code's use is done outside of the MINA dispatcher
- * thread in order to minimise the amount of work done in the MINA dispatcher thread.
- */
-public class UnprocessedMessage_0_10 extends UnprocessedMessage
-{
- private MessageTransfer _transfer;
-
- public UnprocessedMessage_0_10(MessageTransfer xfr)
- {
- super(Integer.parseInt(xfr.getDestination()));
- _transfer = xfr;
- }
-
- // additional 0_10 method
-
- public long getDeliveryTag()
- {
- return _transfer.getId();
- }
-
- public MessageTransfer getMessageTransfer()
- {
- return _transfer;
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/UnprocessedMessage_0_8.java b/java/client/src/main/java/org/apache/qpid/client/message/UnprocessedMessage_0_8.java
deleted file mode 100644
index 685e646d85..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/message/UnprocessedMessage_0_8.java
+++ /dev/null
@@ -1,163 +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.client.message;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.BasicDeliverBody;
-import org.apache.qpid.framing.ContentBody;
-import org.apache.qpid.framing.ContentHeaderBody;
-
-/**
- * This class contains everything needed to process a JMS message. It assembles the deliver body, the content header and
- * the content body/ies.
- *
- * Note that the actual work of creating a JMS message for the client code's use is done outside of the MINA dispatcher
- * thread in order to minimise the amount of work done in the MINA dispatcher thread.
- */
-public class UnprocessedMessage_0_8 extends UnprocessedMessage
-{
- private long _bytesReceived = 0;
-
-
- private AMQShortString _exchange;
- private AMQShortString _routingKey;
- private final long _deliveryId;
- protected boolean _redelivered;
-
- private BasicDeliverBody _deliverBody;
- private ContentHeaderBody _contentHeader;
-
- /** List of ContentBody instances. Due to fragmentation you don't know how big this will be in general */
- private List<ContentBody> _bodies;
-
- public UnprocessedMessage_0_8(long deliveryId, int consumerTag, AMQShortString exchange, AMQShortString routingKey, boolean redelivered)
- {
- super(consumerTag);
- _exchange = exchange;
- _routingKey = routingKey;
-
- _redelivered = redelivered;
- _deliveryId = deliveryId;
- }
-
-
- public AMQShortString getExchange()
- {
- return _exchange;
- }
-
- public AMQShortString getRoutingKey()
- {
- return _routingKey;
- }
-
- public long getDeliveryTag()
- {
- return _deliveryId;
- }
-
- public boolean isRedelivered()
- {
- return _redelivered;
- }
-
-
- public void receiveBody(ContentBody body)
- {
-
- if (body.payload != null)
- {
- final long payloadSize = body.payload.remaining();
-
- if (_bodies == null)
- {
- if (payloadSize == getContentHeader().bodySize)
- {
- _bodies = Collections.singletonList(body);
- }
- else
- {
- _bodies = new ArrayList<ContentBody>();
- _bodies.add(body);
- }
-
- }
- else
- {
- _bodies.add(body);
- }
- _bytesReceived += payloadSize;
- }
- }
-
- public void setMethodBody(BasicDeliverBody deliverBody)
- {
- _deliverBody = deliverBody;
- }
-
- public void setContentHeader(ContentHeaderBody contentHeader)
- {
- this._contentHeader = contentHeader;
- }
-
- public boolean isAllBodyDataReceived()
- {
- return _bytesReceived == getContentHeader().bodySize;
- }
-
- public BasicDeliverBody getDeliverBody()
- {
- return _deliverBody;
- }
-
- public ContentHeaderBody getContentHeader()
- {
- return _contentHeader;
- }
-
- public List<ContentBody> getBodies()
- {
- return _bodies;
- }
-
- public String toString()
- {
- StringBuilder buf = new StringBuilder();
-
- if (_contentHeader != null)
- {
- buf.append("ContentHeader " + _contentHeader);
- }
- if(_deliverBody != null)
- {
- buf.append("Delivery tag " + _deliverBody.getDeliveryTag());
- buf.append("Consumer tag " + _deliverBody.getConsumerTag());
- buf.append("Deliver Body " + _deliverBody);
- }
-
- return buf.toString();
- }
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/messaging/address/AddressHelper.java b/java/client/src/main/java/org/apache/qpid/client/messaging/address/AddressHelper.java
deleted file mode 100644
index 368ec60525..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/messaging/address/AddressHelper.java
+++ /dev/null
@@ -1,332 +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.client.messaging.address;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.qpid.client.AMQDestination;
-import org.apache.qpid.client.AMQDestination.Binding;
-import org.apache.qpid.client.messaging.address.Link.Reliability;
-import org.apache.qpid.client.messaging.address.Link.Subscription;
-import org.apache.qpid.client.messaging.address.Node.ExchangeNode;
-import org.apache.qpid.client.messaging.address.Node.QueueNode;
-import org.apache.qpid.client.messaging.address.Node.UnknownNodeType;
-import org.apache.qpid.configuration.Accessor;
-import org.apache.qpid.configuration.Accessor.MapAccessor;
-import org.apache.qpid.messaging.Address;
-
-/**
- * Utility class for extracting information from the address class
- */
-public class AddressHelper
-{
- public static final String NODE = "node";
- public static final String LINK = "link";
- public static final String X_DECLARE = "x-declare";
- public static final String X_BINDINGS = "x-bindings";
- public static final String X_SUBSCRIBE = "x-subscribes";
- public static final String CREATE = "create";
- public static final String ASSERT = "assert";
- public static final String DELETE = "delete";
- public static final String FILTER = "filter";
- public static final String NO_LOCAL = "no-local";
- public static final String DURABLE = "durable";
- public static final String EXCLUSIVE = "exclusive";
- public static final String AUTO_DELETE = "auto-delete";
- public static final String TYPE = "type";
- public static final String ALT_EXCHANGE = "alternate-exchange";
- public static final String BINDINGS = "bindings";
- public static final String BROWSE = "browse";
- public static final String MODE = "mode";
- public static final String CAPACITY = "capacity";
- public static final String CAPACITY_SOURCE = "source";
- public static final String CAPACITY_TARGET = "target";
- public static final String NAME = "name";
- public static final String EXCHANGE = "exchange";
- public static final String QUEUE = "queue";
- public static final String KEY = "key";
- public static final String ARGUMENTS = "arguments";
- public static final String RELIABILITY = "reliability";
-
- private Address address;
- private Accessor addressProps;
- private Accessor nodeProps;
- private Accessor linkProps;
-
- public AddressHelper(Address address)
- {
- this.address = address;
- addressProps = new MapAccessor(address.getOptions());
- Map node_props = address.getOptions() == null
- || address.getOptions().get(NODE) == null ? null
- : (Map) address.getOptions().get(NODE);
-
- if (node_props != null)
- {
- nodeProps = new MapAccessor(node_props);
- }
-
- Map link_props = address.getOptions() == null
- || address.getOptions().get(LINK) == null ? null
- : (Map) address.getOptions().get(LINK);
-
- if (link_props != null)
- {
- linkProps = new MapAccessor(link_props);
- }
- }
-
- public String getCreate()
- {
- return addressProps.getString(CREATE);
- }
-
- public String getAssert()
- {
- return addressProps.getString(ASSERT);
- }
-
- public String getDelete()
- {
- return addressProps.getString(DELETE);
- }
-
- public boolean isNoLocal()
- {
- Boolean b = nodeProps.getBoolean(NO_LOCAL);
- return b == null ? false : b;
- }
-
- public boolean isBrowseOnly()
- {
- String mode = addressProps.getString(MODE);
- return mode != null && mode.equals(BROWSE) ? true : false;
- }
-
- @SuppressWarnings("unchecked")
- public List<Binding> getBindings(Map props)
- {
- List<Binding> bindings = new ArrayList<Binding>();
- List<Map> bindingList = (List<Map>) props.get(X_BINDINGS);
- if (bindingList != null)
- {
- for (Map bindingMap : bindingList)
- {
- Binding binding = new Binding(
- (String) bindingMap.get(EXCHANGE),
- (String) bindingMap.get(QUEUE),
- (String) bindingMap.get(KEY),
- bindingMap.get(ARGUMENTS) == null ? Collections.EMPTY_MAP
- : (Map<String, Object>) bindingMap
- .get(ARGUMENTS));
- bindings.add(binding);
- }
- }
- return bindings;
- }
-
- public Map getDeclareArgs(Map props)
- {
- if (props != null && props.get(X_DECLARE) != null)
- {
- return (Map) props.get(X_DECLARE);
-
- } else
- {
- return Collections.EMPTY_MAP;
- }
- }
-
- public int getTargetNodeType() throws Exception
- {
- if (nodeProps == null || nodeProps.getString(TYPE) == null)
- {
- // need to query and figure out
- return AMQDestination.UNKNOWN_TYPE;
- } else if (nodeProps.getString(TYPE).equals("queue"))
- {
- return AMQDestination.QUEUE_TYPE;
- } else if (nodeProps.getString(TYPE).equals("topic"))
- {
- return AMQDestination.TOPIC_TYPE;
- } else
- {
- throw new Exception("unkown exchange type");
- }
- }
-
- public Node getTargetNode(int addressType)
- {
- // target node here is the default exchange
- if (nodeProps == null || addressType == AMQDestination.QUEUE_TYPE)
- {
- return new ExchangeNode();
- } else if (addressType == AMQDestination.TOPIC_TYPE)
- {
- Map node = (Map) address.getOptions().get(NODE);
- return createExchangeNode(node);
- } else
- {
- // don't know yet
- return null;
- }
- }
-
- private Node createExchangeNode(Map parent)
- {
- Map declareArgs = getDeclareArgs(parent);
- MapAccessor argsMap = new MapAccessor(declareArgs);
- ExchangeNode node = new ExchangeNode();
- node.setExchangeType(argsMap.getString(TYPE) == null ? null : argsMap
- .getString(TYPE));
- fillInCommonNodeArgs(node, parent, argsMap);
- return node;
- }
-
- private Node createQueueNode(Map parent)
- {
- Map declareArgs = getDeclareArgs(parent);
- MapAccessor argsMap = new MapAccessor(declareArgs);
- QueueNode node = new QueueNode();
- node.setAlternateExchange(argsMap.getString(ALT_EXCHANGE));
- node.setExclusive(argsMap.getBoolean(EXCLUSIVE) == null ? false
- : argsMap.getBoolean(EXCLUSIVE));
- fillInCommonNodeArgs(node, parent, argsMap);
-
- return node;
- }
-
- private void fillInCommonNodeArgs(Node node, Map parent, MapAccessor argsMap)
- {
- node.setDurable(getDurability(parent));
- node.setAutoDelete(argsMap.getBoolean(AUTO_DELETE) == null ? false
- : argsMap.getBoolean(AUTO_DELETE));
- node.setAlternateExchange(argsMap.getString(ALT_EXCHANGE));
- node.setBindings(getBindings(parent));
- if (getDeclareArgs(parent).containsKey(ARGUMENTS))
- {
- node.setDeclareArgs((Map<String,Object>)getDeclareArgs(parent).get(ARGUMENTS));
- }
- }
-
- private boolean getDurability(Map map)
- {
- Accessor access = new MapAccessor(map);
- Boolean result = access.getBoolean(DURABLE);
- return (result == null) ? false : result.booleanValue();
- }
-
- /**
- * if the type == queue x-declare args from the node props is used. if the
- * type == exchange x-declare args from the link props is used else just
- * create a default temp queue.
- */
- public Node getSourceNode(int addressType)
- {
- if (addressType == AMQDestination.QUEUE_TYPE && nodeProps != null)
- {
- return createQueueNode((Map) address.getOptions().get(NODE));
- }
- if (addressType == AMQDestination.TOPIC_TYPE && linkProps != null)
- {
- return createQueueNode((Map) address.getOptions().get(LINK));
- } else
- {
- // need to query the info
- return new QueueNode();
- }
- }
-
- public Link getLink() throws Exception
- {
- Link link = new Link();
- link.setSubscription(new Subscription());
- if (linkProps != null)
- {
- link.setDurable(linkProps.getBoolean(DURABLE) == null ? false
- : linkProps.getBoolean(DURABLE));
- link.setName(linkProps.getString(NAME));
-
- String reliability = linkProps.getString(RELIABILITY);
- if ( reliability != null)
- {
- if (reliability.equalsIgnoreCase("unreliable"))
- {
- link.setReliability(Reliability.UNRELIABLE);
- }
- else if (reliability.equalsIgnoreCase("at-least-once"))
- {
- link.setReliability(Reliability.AT_LEAST_ONCE);
- }
- else
- {
- throw new Exception("The reliability mode '" +
- reliability + "' is not yet supported");
- }
-
- }
-
- if (((Map) address.getOptions().get(LINK)).get(CAPACITY) instanceof Map)
- {
- MapAccessor capacityProps = new MapAccessor(
- (Map) ((Map) address.getOptions().get(LINK))
- .get(CAPACITY));
- link
- .setConsumerCapacity(capacityProps
- .getInt(CAPACITY_SOURCE) == null ? 0
- : capacityProps.getInt(CAPACITY_SOURCE));
- link
- .setProducerCapacity(capacityProps
- .getInt(CAPACITY_TARGET) == null ? 0
- : capacityProps.getInt(CAPACITY_TARGET));
- }
- else
- {
- int cap = linkProps.getInt(CAPACITY) == null ? 0 : linkProps
- .getInt(CAPACITY);
- link.setConsumerCapacity(cap);
- link.setProducerCapacity(cap);
- }
- link.setFilter(linkProps.getString(FILTER));
- // so far filter type not used
-
- if (((Map) address.getOptions().get(LINK)).containsKey(X_SUBSCRIBE))
- {
- Map x_subscribe = (Map)((Map) address.getOptions().get(LINK)).get(X_SUBSCRIBE);
-
- if (x_subscribe.containsKey(ARGUMENTS))
- {
- link.getSubscription().setArgs((Map<String,Object>)x_subscribe.get(ARGUMENTS));
- }
-
- boolean exclusive = x_subscribe.containsKey(EXCLUSIVE) ?
- Boolean.parseBoolean((String)x_subscribe.get(EXCLUSIVE)): false;
-
- link.getSubscription().setExclusive(exclusive);
- }
- }
-
- return link;
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/messaging/address/Link.java b/java/client/src/main/java/org/apache/qpid/client/messaging/address/Link.java
deleted file mode 100644
index 5f97d625b4..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/messaging/address/Link.java
+++ /dev/null
@@ -1,172 +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.client.messaging.address;
-
-import static org.apache.qpid.client.messaging.address.Link.Reliability.UNSPECIFIED;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.apache.qpid.client.messaging.address.Node.QueueNode;
-
-public class Link
-{
- public enum FilterType { SQL92, XQUERY, SUBJECT }
-
- public enum Reliability { UNRELIABLE, AT_MOST_ONCE, AT_LEAST_ONCE, EXACTLY_ONCE, UNSPECIFIED }
-
- protected String name;
- protected String _filter;
- protected FilterType _filterType = FilterType.SUBJECT;
- protected boolean _isNoLocal;
- protected boolean _isDurable;
- protected int _consumerCapacity = 0;
- protected int _producerCapacity = 0;
- protected Node node;
- protected Subscription subscription;
- protected Reliability reliability = UNSPECIFIED;
-
- public Reliability getReliability()
- {
- return reliability;
- }
-
- public void setReliability(Reliability reliability)
- {
- this.reliability = reliability;
- }
-
- public Node getNode()
- {
- return node;
- }
-
- public void setNode(Node node)
- {
- this.node = node;
- }
-
- public boolean isDurable()
- {
- return _isDurable;
- }
-
- public void setDurable(boolean durable)
- {
- _isDurable = durable;
- }
-
- public String getFilter()
- {
- return _filter;
- }
-
- public void setFilter(String filter)
- {
- this._filter = filter;
- }
-
- public FilterType getFilterType()
- {
- return _filterType;
- }
-
- public void setFilterType(FilterType type)
- {
- _filterType = type;
- }
-
- public boolean isNoLocal()
- {
- return _isNoLocal;
- }
-
- public void setNoLocal(boolean noLocal)
- {
- _isNoLocal = noLocal;
- }
-
- public int getConsumerCapacity()
- {
- return _consumerCapacity;
- }
-
- public void setConsumerCapacity(int capacity)
- {
- _consumerCapacity = capacity;
- }
-
- public int getProducerCapacity()
- {
- return _producerCapacity;
- }
-
- public void setProducerCapacity(int capacity)
- {
- _producerCapacity = capacity;
- }
-
- public String getName()
- {
- return name;
- }
-
- public void setName(String name)
- {
- this.name = name;
- }
-
- public Subscription getSubscription()
- {
- return this.subscription;
- }
-
- public void setSubscription(Subscription subscription)
- {
- this.subscription = subscription;
- }
-
- public static class Subscription
- {
- private Map<String,Object> args = new HashMap<String,Object>();
- private boolean exclusive = false;
-
- public Map<String, Object> getArgs()
- {
- return args;
- }
-
- public void setArgs(Map<String, Object> args)
- {
- this.args = args;
- }
-
- public boolean isExclusive()
- {
- return exclusive;
- }
-
- public void setExclusive(boolean exclusive)
- {
- this.exclusive = exclusive;
- }
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/messaging/address/Node.java b/java/client/src/main/java/org/apache/qpid/client/messaging/address/Node.java
deleted file mode 100644
index c98b194334..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/messaging/address/Node.java
+++ /dev/null
@@ -1,148 +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.client.messaging.address;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-
-import javax.naming.OperationNotSupportedException;
-
-import org.apache.qpid.client.AMQDestination;
-import org.apache.qpid.client.AMQDestination.Binding;
-
-public abstract class Node
-{
- protected int _nodeType = AMQDestination.UNKNOWN_TYPE;
- protected boolean _isDurable;
- protected boolean _isAutoDelete;
- protected String _alternateExchange;
- protected List<Binding> _bindings = new ArrayList<Binding>();
- protected Map<String,Object> _declareArgs = Collections.emptyMap();
-
- public int getType()
- {
- return _nodeType;
- }
-
- public boolean isDurable()
- {
- return _isDurable;
- }
-
- public void setDurable(boolean durable)
- {
- _isDurable = durable;
- }
-
- public boolean isAutoDelete()
- {
- return _isAutoDelete;
- }
-
- public void setAutoDelete(boolean autoDelete)
- {
- _isAutoDelete = autoDelete;
- }
-
- public String getAlternateExchange()
- {
- return _alternateExchange;
- }
-
- public void setAlternateExchange(String altExchange)
- {
- _alternateExchange = altExchange;
- }
-
- public List<Binding> getBindings()
- {
- return _bindings;
- }
-
- public void setBindings(List<Binding> bindings)
- {
- _bindings = bindings;
- }
-
- public void addBinding(Binding binding) {
- this._bindings.add(binding);
- }
-
- public Map<String,Object> getDeclareArgs()
- {
- return _declareArgs;
- }
-
- public void setDeclareArgs(Map<String,Object> options)
- {
- _declareArgs = options;
- }
-
- public static class QueueNode extends Node
- {
- protected boolean _isExclusive;
- protected QpidQueueOptions _queueOptions = new QpidQueueOptions();
-
- public QueueNode()
- {
- _nodeType = AMQDestination.QUEUE_TYPE;
- }
-
- public boolean isExclusive()
- {
- return _isExclusive;
- }
-
- public void setExclusive(boolean exclusive)
- {
- _isExclusive = exclusive;
- }
- }
-
- public static class ExchangeNode extends Node
- {
- protected QpidExchangeOptions _exchangeOptions = new QpidExchangeOptions();
- protected String _exchangeType;
-
- public ExchangeNode()
- {
- _nodeType = AMQDestination.TOPIC_TYPE;
- }
-
- public String getExchangeType()
- {
- return _exchangeType;
- }
-
- public void setExchangeType(String exchangeType)
- {
- _exchangeType = exchangeType;
- }
-
- }
-
- public static class UnknownNodeType extends Node
- {
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/messaging/address/QpidExchangeOptions.java b/java/client/src/main/java/org/apache/qpid/client/messaging/address/QpidExchangeOptions.java
deleted file mode 100644
index 3ad9aff9ea..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/messaging/address/QpidExchangeOptions.java
+++ /dev/null
@@ -1,45 +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.client.messaging.address;
-
-import java.util.HashMap;
-
-public class QpidExchangeOptions extends HashMap<String,Object>
-{
- public static final String QPID_MSG_SEQUENCE = "qpid.msg_sequence";
- public static final String QPID_INITIAL_VALUE_EXCHANGE = "qpid.ive";
- public static final String QPID_EXCLUSIVE_BINDING = "qpid.exclusive-binding";
-
- public void setMessageSequencing()
- {
- this.put(QPID_MSG_SEQUENCE, 1);
- }
-
- public void setInitialValueExchange()
- {
- this.put(QPID_INITIAL_VALUE_EXCHANGE, 1);
- }
-
- public void setExclusiveBinding()
- {
- this.put(QPID_EXCLUSIVE_BINDING, 1);
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/messaging/address/QpidQueueOptions.java b/java/client/src/main/java/org/apache/qpid/client/messaging/address/QpidQueueOptions.java
deleted file mode 100644
index 04aa7d146f..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/messaging/address/QpidQueueOptions.java
+++ /dev/null
@@ -1,103 +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.client.messaging.address;
-
-import java.util.HashMap;
-
-public class QpidQueueOptions extends HashMap<String,Object>
-{
- public static final String QPID_MAX_COUNT = "qpid.max_count";
- public static final String QPID_MAX_SIZE = "qpid.max_size";
- public static final String QPID_POLICY_TYPE = "qpid.policy_type";
- public static final String QPID_PERSIST_LAST_NODE = "qpid.persist_last_node";
- public static final String QPID_LVQ_KEY = "qpid.LVQ_key";
- public static final String QPID_LAST_VALUE_QUEUE = "qpid.last_value_queue";
- public static final String QPID_LAST_VALUE_QUEUE_NO_BROWSE = "qpid.last_value_queue_no_browse";
- public static final String QPID_QUEUE_EVENT_GENERATION = "qpid.queue_event_generation";
-
- public void validatePolicyType(String type)
- {
- if (type == null ||
- !("reject".equals(type) || "flow_to_disk".equals(type) ||
- "ring".equals(type) || "ring_strict".equals(type)))
- {
- throw new IllegalArgumentException("Invalid Queue Policy Type" +
- " should be one of {reject|flow_to_disk|ring|ring_strict}");
- }
- }
-
- public void setPolicyType(String s)
- {
- validatePolicyType(s);
- this.put(QPID_POLICY_TYPE, s);
- }
-
- public void setMaxCount(Integer i)
- {
- this.put(QPID_MAX_COUNT, i);
- }
-
- public void setMaxSize(Integer i)
- {
- this.put(QPID_MAX_SIZE, i);
- }
-
- public void setPersistLastNode()
- {
- this.put(QPID_PERSIST_LAST_NODE, 1);
- }
-
- public void setOrderingPolicy(String s)
- {
- if (QpidQueueOptions.QPID_LAST_VALUE_QUEUE.equals(s))
- {
- this.put(QPID_LAST_VALUE_QUEUE, 1);
- }
- else if (QpidQueueOptions.QPID_LAST_VALUE_QUEUE_NO_BROWSE.equals(s))
- {
- this.put(QPID_LAST_VALUE_QUEUE_NO_BROWSE,1);
- }
- else
- {
- throw new IllegalArgumentException("Invalid Ordering Policy" +
- " should be one of {" + QpidQueueOptions.QPID_LAST_VALUE_QUEUE + "|" +
- QPID_LAST_VALUE_QUEUE_NO_BROWSE + "}");
- }
- }
-
- public void setLvqKey(String key)
- {
- this.put(QPID_LVQ_KEY, key);
- }
-
- public void setQueueEvents(String value)
- {
- if (value != null && (value.equals("1") || value.equals("2")))
- {
- this.put(QPID_QUEUE_EVENT_GENERATION, value);
- }
- else
- {
- throw new IllegalArgumentException("Invalid value for " +
- QPID_QUEUE_EVENT_GENERATION + " should be one of {1|2}");
- }
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/protocol/AMQProtocolHandler.java b/java/client/src/main/java/org/apache/qpid/client/protocol/AMQProtocolHandler.java
deleted file mode 100644
index eb5af119b2..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/protocol/AMQProtocolHandler.java
+++ /dev/null
@@ -1,881 +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.client.protocol;
-
-import java.io.IOException;
-import java.net.SocketAddress;
-import java.nio.ByteBuffer;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.Set;
-import java.util.concurrent.CopyOnWriteArraySet;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.ThreadFactory;
-import java.util.concurrent.TimeUnit;
-
-import org.apache.mina.filter.codec.ProtocolCodecException;
-import org.apache.qpid.AMQConnectionClosedException;
-import org.apache.qpid.AMQDisconnectedException;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.AMQTimeoutException;
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.client.failover.FailoverException;
-import org.apache.qpid.client.failover.FailoverHandler;
-import org.apache.qpid.client.failover.FailoverState;
-import org.apache.qpid.client.state.AMQState;
-import org.apache.qpid.client.state.AMQStateManager;
-import org.apache.qpid.client.state.StateWaiter;
-import org.apache.qpid.client.state.listener.SpecificMethodFrameListener;
-import org.apache.qpid.codec.AMQCodecFactory;
-import org.apache.qpid.framing.AMQBody;
-import org.apache.qpid.framing.AMQDataBlock;
-import org.apache.qpid.framing.AMQFrame;
-import org.apache.qpid.framing.AMQMethodBody;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.ConnectionCloseBody;
-import org.apache.qpid.framing.ConnectionCloseOkBody;
-import org.apache.qpid.framing.HeartbeatBody;
-import org.apache.qpid.framing.MethodRegistry;
-import org.apache.qpid.framing.ProtocolInitiation;
-import org.apache.qpid.framing.ProtocolVersion;
-import org.apache.qpid.jms.BrokerDetails;
-import org.apache.qpid.pool.Job;
-import org.apache.qpid.pool.ReferenceCountingExecutorService;
-import org.apache.qpid.protocol.AMQConstant;
-import org.apache.qpid.protocol.AMQMethodEvent;
-import org.apache.qpid.protocol.AMQMethodListener;
-import org.apache.qpid.protocol.ProtocolEngine;
-import org.apache.qpid.thread.Threading;
-import org.apache.qpid.transport.NetworkDriver;
-import org.apache.qpid.transport.network.io.IoTransport;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * AMQProtocolHandler is the client side protocol handler for AMQP, it handles all protocol events received from the
- * network by MINA. The primary purpose of AMQProtocolHandler is to translate the generic event model of MINA into the
- * specific event model of AMQP, by revealing the type of the received events (from decoded data), and passing the
- * event on to more specific handlers for the type. In this sense, it channels the richer event model of AMQP,
- * expressed in terms of methods and so on, through the cruder, general purpose event model of MINA, expressed in
- * terms of "message received" and so on.
- *
- * <p/>There is a 1:1 mapping between an AMQProtocolHandler and an {@link AMQConnection}. The connection class is
- * exposed to the end user of the AMQP client API, and also implements the JMS Connection API, so provides the public
- * API calls through which an individual connection can be manipulated. This protocol handler talks to the network
- * through MINA, in a behind the scenes role; it is not an exposed part of the client API.
- *
- * <p/>There is a 1:many mapping between an AMQProtocolHandler and a set of {@link AMQSession}s. At the MINA level,
- * there is one session per connection. At the AMQP level there can be many channels which are also called sessions in
- * JMS parlance. The {@link AMQSession}s are managed through an {@link AMQProtocolSession} instance. The protocol
- * session is similar to the MINA per-connection session, except that it can span the lifecycle of multiple MINA sessions
- * in the event of failover. See below for more information about this.
- *
- * <p/>Mina provides a session container that can be used to store/retrieve arbitrary objects as String named
- * attributes. A more convenient, type-safe, container for session data is provided in the form of
- * {@link AMQProtocolSession}.
- *
- * <p/>A common way to use MINA is to have a single instance of the event handler, and for MINA to pass in its session
- * object with every event, and for per-connection data to be held in the MINA session (perhaps using a type-safe wrapper
- * as described above). This event handler is different, because dealing with failover complicates things. To the
- * end client of an AMQConnection, a failed over connection is still handled through the same connection instance, but
- * behind the scenes a new transport connection, and MINA session will have been created. The MINA session object cannot
- * be used to track the state of the fail-over process, because it is destroyed and a new one is created, as the old
- * connection is shutdown and a new one created. For this reason, an AMQProtocolHandler is created per AMQConnection
- * and the protocol session data is held outside of the MINA IOSession.
- *
- * <p/>This handler is responsible for setting up the filter chain to filter all events for this handler through.
- * The filter chain is set up as a stack of event handers that perform the following functions (working upwards from
- * the network traffic at the bottom), handing off incoming events to an asynchronous thread pool to do the work,
- * optionally handling secure sockets encoding/decoding, encoding/decoding the AMQP format itself.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Maintain fail-over state.
- * <tr><td>
- * </table>
- *
- * @todo Use a single handler instance, by shifting everything to do with the 'protocol session' state, including
- * failover state, into AMQProtocolSession, and tracking that from AMQConnection? The lifecycles of
- * AMQProtocolSesssion and AMQConnection will be the same, so if there is high cohesion between them, they could
- * be merged, although there is sense in keeping the session model separate. Will clarify things by having data
- * held per protocol handler, per protocol session, per network connection, per channel, in separate classes, so
- * that lifecycles of the fields match lifecycles of their containing objects.
- */
-public class AMQProtocolHandler implements ProtocolEngine
-{
- /** Used for debugging. */
- private static final Logger _logger = LoggerFactory.getLogger(AMQProtocolHandler.class);
- private static final Logger _protocolLogger = LoggerFactory.getLogger("qpid.protocol");
- private static final boolean PROTOCOL_DEBUG = (System.getProperty("amqj.protocol.logging.level") != null);
-
- private static final long MAXIMUM_STATE_WAIT_TIME = Long.parseLong(System.getProperty("amqj.MaximumStateWait", "30000"));
-
- /**
- * The connection that this protocol handler is associated with. There is a 1-1 mapping between connection
- * instances and protocol handler instances.
- */
- private AMQConnection _connection;
-
- /** Our wrapper for a protocol session that provides access to session values in a typesafe manner. */
- private volatile AMQProtocolSession _protocolSession;
-
- /** Holds the state of the protocol session. */
- private AMQStateManager _stateManager;
-
- /** Holds the method listeners, */
- private final CopyOnWriteArraySet<AMQMethodListener> _frameListeners = new CopyOnWriteArraySet<AMQMethodListener>();
-
- /**
- * We create the failover handler when the session is created since it needs a reference to the IoSession in order
- * to be able to send errors during failover back to the client application. The session won't be available in the
- * case where we failing over due to a Connection.Redirect message from the broker.
- */
- private FailoverHandler _failoverHandler;
-
- /**
- * This flag is used to track whether failover is being attempted. It is used to prevent the application constantly
- * attempting failover where it is failing.
- */
- private FailoverState _failoverState = FailoverState.NOT_STARTED;
-
- /** Used to provide a condition to wait upon for operations that are required to wait for failover to complete. */
- private CountDownLatch _failoverLatch;
-
- /** The last failover exception that occurred */
- private FailoverException _lastFailoverException;
-
- /** Defines the default timeout to use for synchronous protocol commands. */
- private final long DEFAULT_SYNC_TIMEOUT = Long.getLong("amqj.default_syncwrite_timeout", 1000 * 30);
-
- /** Object to lock on when changing the latch */
- private Object _failoverLatchChange = new Object();
- private AMQCodecFactory _codecFactory;
- private Job _readJob;
- private Job _writeJob;
- private ReferenceCountingExecutorService _poolReference = ReferenceCountingExecutorService.getInstance();
- private NetworkDriver _networkDriver;
- private ProtocolVersion _suggestedProtocolVersion;
-
- private long _writtenBytes;
- private long _readBytes;
-
- /**
- * Creates a new protocol handler, associated with the specified client connection instance.
- *
- * @param con The client connection that this is the event handler for.
- */
- public AMQProtocolHandler(AMQConnection con)
- {
- _connection = con;
- _protocolSession = new AMQProtocolSession(this, _connection);
- _stateManager = new AMQStateManager(_protocolSession);
- _codecFactory = new AMQCodecFactory(false, _protocolSession);
- _poolReference.setThreadFactory(new ThreadFactory()
- {
-
- public Thread newThread(final Runnable runnable)
- {
- try
- {
- return Threading.getThreadFactory().createThread(runnable);
- }
- catch (Exception e)
- {
- throw new RuntimeException("Failed to create thread", e);
- }
- }
- });
- _readJob = new Job(_poolReference, Job.MAX_JOB_EVENTS, true);
- _writeJob = new Job(_poolReference, Job.MAX_JOB_EVENTS, false);
- _poolReference.acquireExecutorService();
- _failoverHandler = new FailoverHandler(this);
- }
-
- /**
- * Called when we want to create a new IoTransport session
- * @param brokerDetail
- */
- public void createIoTransportSession(BrokerDetails brokerDetail)
- {
- _protocolSession = new AMQProtocolSession(this, _connection);
- _stateManager.setProtocolSession(_protocolSession);
- IoTransport.connect_0_9(getProtocolSession(),
- brokerDetail.getHost(),
- brokerDetail.getPort(),
- brokerDetail.getBooleanProperty(BrokerDetails.OPTIONS_SSL));
- _protocolSession.init();
- }
-
- /**
- * Called when the network connection is closed. This can happen, either because the client explicitly requested
- * that the connection be closed, in which case nothing is done, or because the connection died. In the case
- * where the connection died, an attempt to failover automatically to a new connection may be started. The failover
- * process will be started, provided that it is the clients policy to allow failover, and provided that a failover
- * has not already been started or failed.
- *
- * @todo Clarify: presumably exceptionCaught is called when the client is sending during a connection failure and
- * not otherwise? The above comment doesn't make that clear.
- */
- public void closed()
- {
- if (_connection.isClosed())
- {
- _logger.debug("Session closed called by client");
- }
- else
- {
- _logger.debug("Session closed called with failover state currently " + _failoverState);
-
- // reconnetablility was introduced here so as not to disturb the client as they have made their intentions
- // known through the policy settings.
-
- if ((_failoverState != FailoverState.IN_PROGRESS) && _connection.failoverAllowed())
- {
- _logger.debug("FAILOVER STARTING");
- if (_failoverState == FailoverState.NOT_STARTED)
- {
- _failoverState = FailoverState.IN_PROGRESS;
- startFailoverThread();
- }
- else
- {
- _logger.debug("Not starting failover as state currently " + _failoverState);
- }
- }
- else
- {
- _logger.debug("Failover not allowed by policy."); // or already in progress?
-
- if (_logger.isDebugEnabled())
- {
- _logger.debug(_connection.getFailoverPolicy().toString());
- }
-
- if (_failoverState != FailoverState.IN_PROGRESS)
- {
- _logger.debug("sessionClose() not allowed to failover");
- _connection.exceptionReceived(new AMQDisconnectedException(
- "Server closed connection and reconnection " + "not permitted.",
- _stateManager.getLastException()));
- }
- else
- {
- _logger.debug("sessionClose() failover in progress");
- }
- }
- }
-
- _logger.debug("Protocol Session [" + this + "] closed");
- }
-
- /** See {@link FailoverHandler} to see rationale for separate thread. */
- private void startFailoverThread()
- {
- if(!_connection.isClosed())
- {
- final Thread failoverThread;
- try
- {
- failoverThread = Threading.getThreadFactory().createThread(_failoverHandler);
- }
- catch (Exception e)
- {
- throw new RuntimeException("Failed to create thread", e);
- }
- failoverThread.setName("Failover");
- // Do not inherit daemon-ness from current thread as this can be a daemon
- // thread such as a AnonymousIoService thread.
- failoverThread.setDaemon(false);
- failoverThread.start();
- }
- }
-
- public void readerIdle()
- {
- _logger.debug("Protocol Session [" + this + "] idle: reader");
- // failover:
- HeartbeatDiagnostics.timeout();
- _logger.warn("Timed out while waiting for heartbeat from peer.");
- _networkDriver.close();
- }
-
- public void writerIdle()
- {
- _logger.debug("Protocol Session [" + this + "] idle: reader");
- writeFrame(HeartbeatBody.FRAME);
- HeartbeatDiagnostics.sent();
- }
-
- /**
- * Invoked when any exception is thrown by the NetworkDriver
- */
- public void exception(Throwable cause)
- {
- if (_failoverState == FailoverState.NOT_STARTED)
- {
- // if (!(cause instanceof AMQUndeliveredException) && (!(cause instanceof AMQAuthenticationException)))
- if ((cause instanceof AMQConnectionClosedException) || cause instanceof IOException)
- {
- _logger.info("Exception caught therefore going to attempt failover: " + cause, cause);
- // this will attempt failover
- _networkDriver.close();
- closed();
- }
- else
- {
-
- if (cause instanceof ProtocolCodecException)
- {
- _logger.info("Protocol Exception caught NOT going to attempt failover as " +
- "cause isn't AMQConnectionClosedException: " + cause, cause);
-
- AMQException amqe = new AMQException("Protocol handler error: " + cause, cause);
- propagateExceptionToAllWaiters(amqe);
- }
- _connection.exceptionReceived(cause);
-
- }
-
- // FIXME Need to correctly handle other exceptions. Things like ...
- // if (cause instanceof AMQChannelClosedException)
- // which will cause the JMSSession to end due to a channel close and so that Session needs
- // to be removed from the map so we can correctly still call close without an exception when trying to close
- // the server closed session. See also CloseChannelMethodHandler as the sessionClose is never called on exception
- }
- // we reach this point if failover was attempted and failed therefore we need to let the calling app
- // know since we cannot recover the situation
- else if (_failoverState == FailoverState.FAILED)
- {
- _logger.error("Exception caught by protocol handler: " + cause, cause);
-
- // we notify the state manager of the error in case we have any clients waiting on a state
- // change. Those "waiters" will be interrupted and can handle the exception
- AMQException amqe = new AMQException("Protocol handler error: " + cause, cause);
- propagateExceptionToAllWaiters(amqe);
- _connection.exceptionReceived(cause);
- }
- }
-
- /**
- * There are two cases where we have other threads potentially blocking for events to be handled by this class.
- * These are for the state manager (waiting for a state change) or a frame listener (waiting for a particular type
- * of frame to arrive). When an error occurs we need to notify these waiters so that they can react appropriately.
- *
- * This should be called only when the exception is fatal for the connection.
- *
- * @param e the exception to propagate
- *
- * @see #propagateExceptionToFrameListeners
- */
- public void propagateExceptionToAllWaiters(Exception e)
- {
- getStateManager().error(e);
-
- propagateExceptionToFrameListeners(e);
- }
-
- /**
- * This caters for the case where we only need to propagate an exception to the the frame listeners to interupt any
- * protocol level waits.
- *
- * This will would normally be used to notify all Frame Listeners that Failover is about to occur and they should
- * stop waiting and relinquish the Failover lock {@see FailoverHandler}.
- *
- * Once the {@link FailoverHandler} has re-established the connection then the listeners will be able to re-attempt
- * their protocol request and so listen again for the correct frame.
- *
- * @param e the exception to propagate
- */
- public void propagateExceptionToFrameListeners(Exception e)
- {
- synchronized (_frameListeners)
- {
- if (!_frameListeners.isEmpty())
- {
- final Iterator it = _frameListeners.iterator();
- while (it.hasNext())
- {
- final AMQMethodListener ml = (AMQMethodListener) it.next();
- ml.error(e);
- }
- }
- }
- }
-
- public void notifyFailoverStarting()
- {
- // Set the last exception in the sync block to ensure the ordering with add.
- // either this gets done and the add does the ml.error
- // or the add completes first and the iterator below will do ml.error
- synchronized (_frameListeners)
- {
- _lastFailoverException = new FailoverException("Failing over about to start");
- }
-
- //Only notify the Frame listeners that failover is going to occur as the State listeners shouldn't be
- // interrupted unless failover cannot restore the state.
- propagateExceptionToFrameListeners(_lastFailoverException);
- }
-
- public void failoverInProgress()
- {
- _lastFailoverException = null;
- }
-
- private static int _messageReceivedCount;
-
-
- public void received(ByteBuffer msg)
- {
- try
- {
- _readBytes += msg.remaining();
- final ArrayList<AMQDataBlock> dataBlocks = _codecFactory.getDecoder().decodeBuffer(msg);
-
- Job.fireAsynchEvent(_poolReference.getPool(), _readJob, new Runnable()
- {
-
- public void run()
- {
- // Decode buffer
-
- for (AMQDataBlock message : dataBlocks)
- {
-
- try
- {
- if (PROTOCOL_DEBUG)
- {
- _protocolLogger.info(String.format("RECV: [%s] %s", this, message));
- }
-
- if(message instanceof AMQFrame)
- {
- final boolean debug = _logger.isDebugEnabled();
- final long msgNumber = ++_messageReceivedCount;
-
- if (debug && ((msgNumber % 1000) == 0))
- {
- _logger.debug("Received " + _messageReceivedCount + " protocol messages");
- }
-
- AMQFrame frame = (AMQFrame) message;
-
- final AMQBody bodyFrame = frame.getBodyFrame();
-
- HeartbeatDiagnostics.received(bodyFrame instanceof HeartbeatBody);
-
- bodyFrame.handle(frame.getChannel(), _protocolSession);
-
- _connection.bytesReceived(_readBytes);
- }
- else if (message instanceof ProtocolInitiation)
- {
- // We get here if the server sends a response to our initial protocol header
- // suggesting an alternate ProtocolVersion; the server will then close the
- // connection.
- ProtocolInitiation protocolInit = (ProtocolInitiation) message;
- _suggestedProtocolVersion = protocolInit.checkVersion();
- _logger.info("Broker suggested using protocol version:" + _suggestedProtocolVersion);
-
- // get round a bug in old versions of qpid whereby the connection is not closed
- _stateManager.changeState(AMQState.CONNECTION_CLOSED);
- }
- }
- catch (Exception e)
- {
- _logger.error("Exception processing frame", e);
- propagateExceptionToFrameListeners(e);
- exception(e);
- }
- }
- }
- });
- }
- catch (Exception e)
- {
- propagateExceptionToFrameListeners(e);
- exception(e);
- }
- }
-
- public void methodBodyReceived(final int channelId, final AMQBody bodyFrame)
- throws AMQException
- {
-
- if (_logger.isDebugEnabled())
- {
- _logger.debug("(" + System.identityHashCode(this) + ")Method frame received: " + bodyFrame);
- }
-
- final AMQMethodEvent<AMQMethodBody> evt =
- new AMQMethodEvent<AMQMethodBody>(channelId, (AMQMethodBody) bodyFrame);
-
- try
- {
-
- boolean wasAnyoneInterested = getStateManager().methodReceived(evt);
- synchronized (_frameListeners)
- {
- if (!_frameListeners.isEmpty())
- {
- //This iterator is safe from the error state as the frame listeners always add before they send so their
- // will be ready and waiting for this response.
- Iterator it = _frameListeners.iterator();
- while (it.hasNext())
- {
- final AMQMethodListener listener = (AMQMethodListener) it.next();
- wasAnyoneInterested = listener.methodReceived(evt) || wasAnyoneInterested;
- }
- }
- }
- if (!wasAnyoneInterested)
- {
- throw new AMQException(null, "AMQMethodEvent " + evt + " was not processed by any listener. Listeners:"
- + _frameListeners, null);
- }
- }
- catch (AMQException e)
- {
- propagateExceptionToFrameListeners(e);
-
- exception(e);
- }
-
- }
-
- private static int _messagesOut;
-
- public StateWaiter createWaiter(Set<AMQState> states) throws AMQException
- {
- return getStateManager().createWaiter(states);
- }
-
- /**
- * Convenience method that writes a frame to the protocol session. Equivalent to calling
- * getProtocolSession().write().
- *
- * @param frame the frame to write
- */
- public void writeFrame(AMQDataBlock frame)
- {
- writeFrame(frame, false);
- }
-
- public void writeFrame(AMQDataBlock frame, boolean wait)
- {
- final ByteBuffer buf = frame.toNioByteBuffer();
- _writtenBytes += buf.remaining();
- Job.fireAsynchEvent(_poolReference.getPool(), _writeJob, new Runnable()
- {
- public void run()
- {
- _networkDriver.send(buf);
- }
- });
- if (PROTOCOL_DEBUG)
- {
- _protocolLogger.debug(String.format("SEND: [%s] %s", this, frame));
- }
-
- final long sentMessages = _messagesOut++;
-
- final boolean debug = _logger.isDebugEnabled();
-
- if (debug && ((sentMessages % 1000) == 0))
- {
- _logger.debug("Sent " + _messagesOut + " protocol messages");
- }
-
- _connection.bytesSent(_writtenBytes);
-
- if (wait)
- {
- _networkDriver.flush();
- }
- }
-
- /**
- * Convenience method that writes a frame to the protocol session and waits for a particular response. Equivalent to
- * calling getProtocolSession().write() then waiting for the response.
- *
- * @param frame
- * @param listener the blocking listener. Note the calling thread will block.
- */
- public AMQMethodEvent writeCommandFrameAndWaitForReply(AMQFrame frame, BlockingMethodFrameListener listener)
- throws AMQException, FailoverException
- {
- return writeCommandFrameAndWaitForReply(frame, listener, DEFAULT_SYNC_TIMEOUT);
- }
-
- /**
- * Convenience method that writes a frame to the protocol session and waits for a particular response. Equivalent to
- * calling getProtocolSession().write() then waiting for the response.
- *
- * @param frame
- * @param listener the blocking listener. Note the calling thread will block.
- */
- public AMQMethodEvent writeCommandFrameAndWaitForReply(AMQFrame frame, BlockingMethodFrameListener listener,
- long timeout) throws AMQException, FailoverException
- {
- try
- {
- synchronized (_frameListeners)
- {
- if (_lastFailoverException != null)
- {
- throw _lastFailoverException;
- }
-
- if(_stateManager.getCurrentState() == AMQState.CONNECTION_CLOSED ||
- _stateManager.getCurrentState() == AMQState.CONNECTION_CLOSING)
- {
- Exception e = _stateManager.getLastException();
- if (e != null)
- {
- if (e instanceof AMQException)
- {
- AMQException amqe = (AMQException) e;
-
- throw amqe.cloneForCurrentThread();
- }
- else
- {
- throw new AMQException(AMQConstant.INTERNAL_ERROR, e.getMessage(), e);
- }
- }
- }
-
- _frameListeners.add(listener);
- //FIXME: At this point here we should check or before add we should check _stateManager is in an open
- // state so as we don't check we are likely just to time out here as I believe is being seen in QPID-1255
- }
- writeFrame(frame);
-
- return listener.blockForFrame(timeout);
- // When control resumes before this line, a reply will have been received
- // that matches the criteria defined in the blocking listener
- }
- finally
- {
- // If we don't removeKey the listener then no-one will
- _frameListeners.remove(listener);
- }
-
- }
-
- /** More convenient method to write a frame and wait for it's response. */
- public AMQMethodEvent syncWrite(AMQFrame frame, Class responseClass) throws AMQException, FailoverException
- {
- return syncWrite(frame, responseClass, DEFAULT_SYNC_TIMEOUT);
- }
-
- /** More convenient method to write a frame and wait for it's response. */
- public AMQMethodEvent syncWrite(AMQFrame frame, Class responseClass, long timeout) throws AMQException, FailoverException
- {
- return writeCommandFrameAndWaitForReply(frame, new SpecificMethodFrameListener(frame.getChannel(), responseClass),
- timeout);
- }
-
- public void closeSession(AMQSession session) throws AMQException
- {
- _protocolSession.closeSession(session);
- }
-
- /**
- * Closes the connection.
- *
- * <p/>If a failover exception occurs whilst closing the connection it is ignored, as the connection is closed
- * anyway.
- *
- * @param timeout The timeout to wait for an acknowledgement to the close request.
- *
- * @throws AMQException If the close fails for any reason.
- */
- public void closeConnection(long timeout) throws AMQException
- {
- ConnectionCloseBody body = _protocolSession.getMethodRegistry().createConnectionCloseBody(AMQConstant.REPLY_SUCCESS.getCode(), // replyCode
- new AMQShortString("JMS client is closing the connection."), 0, 0);
-
- final AMQFrame frame = body.generateFrame(0);
-
- //If the connection is already closed then don't do a syncWrite
- if (!getStateManager().getCurrentState().equals(AMQState.CONNECTION_CLOSED))
- {
- try
- {
- syncWrite(frame, ConnectionCloseOkBody.class, timeout);
- _networkDriver.close();
- closed();
- }
- catch (AMQTimeoutException e)
- {
- closed();
- }
- catch (FailoverException e)
- {
- _logger.debug("FailoverException interrupted connection close, ignoring as connection close anyway.");
- }
- }
- _poolReference.releaseExecutorService();
- }
-
- /** @return the number of bytes read from this protocol session */
- public long getReadBytes()
- {
- return _readBytes;
- }
-
- /** @return the number of bytes written to this protocol session */
- public long getWrittenBytes()
- {
- return _writtenBytes;
- }
-
- public void failover(String host, int port)
- {
- _failoverHandler.setHost(host);
- _failoverHandler.setPort(port);
- // see javadoc for FailoverHandler to see rationale for separate thread
- startFailoverThread();
- }
-
- public void blockUntilNotFailingOver() throws InterruptedException
- {
- synchronized(_failoverLatchChange)
- {
- if (_failoverLatch != null)
- {
- if(!_failoverLatch.await(MAXIMUM_STATE_WAIT_TIME, TimeUnit.MILLISECONDS))
- {
-
- }
- }
- }
- }
-
- public AMQShortString generateQueueName()
- {
- return _protocolSession.generateQueueName();
- }
-
- public CountDownLatch getFailoverLatch()
- {
- return _failoverLatch;
- }
-
- public void setFailoverLatch(CountDownLatch failoverLatch)
- {
- synchronized (_failoverLatchChange)
- {
- _failoverLatch = failoverLatch;
- }
- }
-
- public AMQConnection getConnection()
- {
- return _connection;
- }
-
- public AMQStateManager getStateManager()
- {
- return _stateManager;
- }
-
- public void setStateManager(AMQStateManager stateManager)
- {
- _stateManager = stateManager;
- _stateManager.setProtocolSession(_protocolSession);
- }
-
- public AMQProtocolSession getProtocolSession()
- {
- return _protocolSession;
- }
-
- FailoverState getFailoverState()
- {
- return _failoverState;
- }
-
- public void setFailoverState(FailoverState failoverState)
- {
- _failoverState = failoverState;
- }
-
- public byte getProtocolMajorVersion()
- {
- return _protocolSession.getProtocolMajorVersion();
- }
-
- public byte getProtocolMinorVersion()
- {
- return _protocolSession.getProtocolMinorVersion();
- }
-
- public MethodRegistry getMethodRegistry()
- {
- return _protocolSession.getMethodRegistry();
- }
-
- public ProtocolVersion getProtocolVersion()
- {
- return _protocolSession.getProtocolVersion();
- }
-
- public SocketAddress getRemoteAddress()
- {
- return _networkDriver.getRemoteAddress();
- }
-
- public SocketAddress getLocalAddress()
- {
- return _networkDriver.getLocalAddress();
- }
-
- public void setNetworkDriver(NetworkDriver driver)
- {
- _networkDriver = driver;
- }
-
- /** @param delay delay in seconds (not ms) */
- void initHeartbeats(int delay)
- {
- if (delay > 0)
- {
- getNetworkDriver().setMaxWriteIdle(delay);
- getNetworkDriver().setMaxReadIdle(HeartbeatConfig.CONFIG.getTimeout(delay));
- HeartbeatDiagnostics.init(delay, HeartbeatConfig.CONFIG.getTimeout(delay));
- }
- }
-
- public NetworkDriver getNetworkDriver()
- {
- return _networkDriver;
- }
-
- public ProtocolVersion getSuggestedProtocolVersion()
- {
- return _suggestedProtocolVersion;
- }
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/protocol/AMQProtocolSession.java b/java/client/src/main/java/org/apache/qpid/client/protocol/AMQProtocolSession.java
deleted file mode 100644
index 7976760696..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/protocol/AMQProtocolSession.java
+++ /dev/null
@@ -1,477 +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.client.protocol;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.jms.JMSException;
-import javax.security.sasl.SaslClient;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.client.ConnectionTuneParameters;
-import org.apache.qpid.client.message.UnprocessedMessage;
-import org.apache.qpid.client.message.UnprocessedMessage_0_8;
-import org.apache.qpid.client.state.AMQStateManager;
-import org.apache.qpid.client.state.AMQState;
-import org.apache.qpid.framing.*;
-import org.apache.qpid.protocol.AMQConstant;
-import org.apache.qpid.protocol.AMQVersionAwareProtocolSession;
-import org.apache.qpid.transport.Sender;
-import org.apache.qpid.client.handler.ClientMethodDispatcherImpl;
-
-/**
- * Wrapper for protocol session that provides type-safe access to session attributes. <p/> The underlying protocol
- * session is still available but clients should not use it to obtain session attributes.
- */
-public class AMQProtocolSession implements AMQVersionAwareProtocolSession
-{
- protected static final int LAST_WRITE_FUTURE_JOIN_TIMEOUT = 1000 * 60 * 2;
-
- protected static final Logger _logger = LoggerFactory.getLogger(AMQProtocolSession.class);
-
- public static final String PROTOCOL_INITIATION_RECEIVED = "ProtocolInitiatiionReceived";
-
- //Usable channels are numbered 1 to <ChannelMax>
- public static final int MAX_CHANNEL_MAX = 0xFFFF;
- public static final int MIN_USABLE_CHANNEL_NUM = 1;
-
- protected static final String CONNECTION_TUNE_PARAMETERS = "ConnectionTuneParameters";
-
- protected static final String AMQ_CONNECTION = "AMQConnection";
-
- protected static final String SASL_CLIENT = "SASLClient";
-
- /**
- * The handler from which this session was created and which is used to handle protocol events. We send failover
- * events to the handler.
- */
- protected final AMQProtocolHandler _protocolHandler;
-
- /** Maps from the channel id to the AMQSession that it represents. */
- protected ConcurrentMap<Integer, AMQSession> _channelId2SessionMap = new ConcurrentHashMap<Integer, AMQSession>();
-
- protected ConcurrentMap _closingChannels = new ConcurrentHashMap();
-
- /**
- * Maps from a channel id to an unprocessed message. This is used to tie together the JmsDeliverBody (which arrives
- * first) with the subsequent content header and content bodies.
- */
- private final ConcurrentMap<Integer, UnprocessedMessage> _channelId2UnprocessedMsgMap = new ConcurrentHashMap<Integer, UnprocessedMessage>();
- private final UnprocessedMessage[] _channelId2UnprocessedMsgArray = new UnprocessedMessage[16];
-
- /** Counter to ensure unique queue names */
- protected int _queueId = 1;
- protected final Object _queueIdLock = new Object();
-
- private ProtocolVersion _protocolVersion;
-// private VersionSpecificRegistry _registry =
-// MainRegistry.getVersionSpecificRegistry(ProtocolVersion.getLatestSupportedVersion());
-
- private MethodRegistry _methodRegistry =
- MethodRegistry.getMethodRegistry(ProtocolVersion.getLatestSupportedVersion());
-
- private MethodDispatcher _methodDispatcher;
-
- protected final AMQConnection _connection;
-
- private ConnectionTuneParameters _connectionTuneParameters;
-
- private SaslClient _saslClient;
-
- private static final int FAST_CHANNEL_ACCESS_MASK = 0xFFFFFFF0;
-
- public AMQProtocolSession(AMQProtocolHandler protocolHandler, AMQConnection connection)
- {
- _protocolHandler = protocolHandler;
- _protocolVersion = connection.getProtocolVersion();
- _logger.info("Using ProtocolVersion for Session:" + _protocolVersion);
- _methodDispatcher = ClientMethodDispatcherImpl.newMethodDispatcher(ProtocolVersion.getLatestSupportedVersion(),
- this);
- _connection = connection;
- }
-
- public void init()
- {
- // start the process of setting up the connection. This is the first place that
- // data is written to the server.
- _protocolHandler.writeFrame(new ProtocolInitiation(_connection.getProtocolVersion()));
- }
-
- public String getClientID()
- {
- try
- {
- return getAMQConnection().getClientID();
- }
- catch (JMSException e)
- {
- // we never throw a JMSException here
- return null;
- }
- }
-
- public void setClientID(String clientID) throws JMSException
- {
- getAMQConnection().setClientID(clientID);
- }
-
- public AMQStateManager getStateManager()
- {
- return _protocolHandler.getStateManager();
- }
-
- public String getVirtualHost()
- {
- return getAMQConnection().getVirtualHost();
- }
-
- public String getUsername()
- {
- return getAMQConnection().getUsername();
- }
-
- public String getPassword()
- {
- return getAMQConnection().getPassword();
- }
-
- public SaslClient getSaslClient()
- {
- return _saslClient;
- }
-
- /**
- * Store the SASL client currently being used for the authentication handshake
- *
- * @param client if non-null, stores this in the session. if null clears any existing client being stored
- */
- public void setSaslClient(SaslClient client)
- {
- _saslClient = client;
- }
-
- public ConnectionTuneParameters getConnectionTuneParameters()
- {
- return _connectionTuneParameters;
- }
-
- public void setConnectionTuneParameters(ConnectionTuneParameters params)
- {
- _connectionTuneParameters = params;
- AMQConnection con = getAMQConnection();
-
- con.setMaximumChannelCount(params.getChannelMax());
- con.setMaximumFrameSize(params.getFrameMax());
- _protocolHandler.initHeartbeats((int) params.getHeartbeat());
- }
-
- /**
- * Callback invoked from the BasicDeliverMethodHandler when a message has been received. This is invoked on the MINA
- * dispatcher thread.
- *
- * @param message
- *
- * @throws AMQException if this was not expected
- */
- public void unprocessedMessageReceived(final int channelId, UnprocessedMessage message) throws AMQException
- {
- if ((channelId & FAST_CHANNEL_ACCESS_MASK) == 0)
- {
- _channelId2UnprocessedMsgArray[channelId] = message;
- }
- else
- {
- _channelId2UnprocessedMsgMap.put(channelId, message);
- }
- }
-
- public void contentHeaderReceived(int channelId, ContentHeaderBody contentHeader) throws AMQException
- {
- final UnprocessedMessage_0_8 msg = (UnprocessedMessage_0_8) ((channelId & FAST_CHANNEL_ACCESS_MASK) == 0 ? _channelId2UnprocessedMsgArray[channelId]
- : _channelId2UnprocessedMsgMap.get(channelId));
-
- if (msg == null)
- {
- throw new AMQException(null, "Error: received content header without having received a BasicDeliver frame first on session:" + this, null);
- }
-
- if (msg.getContentHeader() != null)
- {
- throw new AMQException(null, "Error: received duplicate content header or did not receive correct number of content body frames on session:" + this, null);
- }
-
- msg.setContentHeader(contentHeader);
- if (contentHeader.bodySize == 0)
- {
- deliverMessageToAMQSession(channelId, msg);
- }
- }
-
- public void contentBodyReceived(final int channelId, ContentBody contentBody) throws AMQException
- {
- UnprocessedMessage_0_8 msg;
- final boolean fastAccess = (channelId & FAST_CHANNEL_ACCESS_MASK) == 0;
- if (fastAccess)
- {
- msg = (UnprocessedMessage_0_8) _channelId2UnprocessedMsgArray[channelId];
- }
- else
- {
- msg = (UnprocessedMessage_0_8) _channelId2UnprocessedMsgMap.get(channelId);
- }
-
- if (msg == null)
- {
- throw new AMQException(null, "Error: received content body without having received a JMSDeliver frame first", null);
- }
-
- if (msg.getContentHeader() == null)
- {
- if (fastAccess)
- {
- _channelId2UnprocessedMsgArray[channelId] = null;
- }
- else
- {
- _channelId2UnprocessedMsgMap.remove(channelId);
- }
- throw new AMQException(null, "Error: received content body without having received a ContentHeader frame first", null);
- }
-
- msg.receiveBody(contentBody);
-
- if (msg.isAllBodyDataReceived())
- {
- deliverMessageToAMQSession(channelId, msg);
- }
- }
-
- public void heartbeatBodyReceived(int channelId, HeartbeatBody body) throws AMQException
- {
-
- }
-
- /**
- * Deliver a message to the appropriate session, removing the unprocessed message from our map
- *
- * @param channelId the channel id the message should be delivered to
- * @param msg the message
- */
- private void deliverMessageToAMQSession(int channelId, UnprocessedMessage msg)
- {
- AMQSession session = getSession(channelId);
- session.messageReceived(msg);
- if ((channelId & FAST_CHANNEL_ACCESS_MASK) == 0)
- {
- _channelId2UnprocessedMsgArray[channelId] = null;
- }
- else
- {
- _channelId2UnprocessedMsgMap.remove(channelId);
- }
- }
-
- protected AMQSession getSession(int channelId)
- {
- return _connection.getSession(channelId);
- }
-
- /**
- * Convenience method that writes a frame to the protocol session. Equivalent to calling
- * getProtocolSession().write().
- *
- * @param frame the frame to write
- */
- public void writeFrame(AMQDataBlock frame)
- {
- _protocolHandler.writeFrame(frame);
- }
-
- public void writeFrame(AMQDataBlock frame, boolean wait)
- {
- _protocolHandler.writeFrame(frame, wait);
- }
-
- /**
- * Starts the process of closing a session
- *
- * @param session the AMQSession being closed
- */
- public void closeSession(AMQSession session)
- {
- _logger.debug("closeSession called on protocol session for session " + session.getChannelId());
- final int channelId = session.getChannelId();
- if (channelId <= 0)
- {
- throw new IllegalArgumentException("Attempt to close a channel with id < 0");
- }
- // we need to know when a channel is closing so that we can respond
- // with a channel.close frame when we receive any other type of frame
- // on that channel
- _closingChannels.putIfAbsent(channelId, session);
- }
-
- /**
- * Called from the ChannelClose handler when a channel close frame is received. This method decides whether this is
- * a response or an initiation. The latter case causes the AMQSession to be closed and an exception to be thrown if
- * appropriate.
- *
- * @param channelId the id of the channel (session)
- *
- * @return true if the client must respond to the server, i.e. if the server initiated the channel close, false if
- * the channel close is just the server responding to the client's earlier request to close the channel.
- */
- public boolean channelClosed(int channelId, AMQConstant code, String text) throws AMQException
- {
-
- // if this is not a response to an earlier request to close the channel
- if (_closingChannels.remove(channelId) == null)
- {
- final AMQSession session = getSession(channelId);
- try
- {
- session.closed(new AMQException(code, text, null));
- }
- catch (JMSException e)
- {
- throw new AMQException(null, "JMSException received while closing session", e);
- }
-
- return true;
- }
- else
- {
- return false;
- }
- }
-
- public AMQConnection getAMQConnection()
- {
- return _connection;
- }
-
- public void closeProtocolSession() throws AMQException
- {
- _protocolHandler.closeConnection(0);
- }
-
- public void failover(String host, int port)
- {
- _protocolHandler.failover(host, port);
- }
-
- protected AMQShortString generateQueueName()
- {
- int id;
- synchronized (_queueIdLock)
- {
- id = _queueId++;
- }
- // convert '.', '/', ':' and ';' to single '_', for spec compliance and readability
- String localAddress = _protocolHandler.getLocalAddress().toString().replaceAll("[./:;]", "_");
- String queueName = "tmp_" + localAddress + "_" + id;
- return new AMQShortString(queueName.replaceAll("_+", "_"));
- }
-
- public void confirmConsumerCancelled(int channelId, AMQShortString consumerTag)
- {
- final AMQSession session = getSession(channelId);
-
- session.confirmConsumerCancelled(consumerTag.toIntValue());
- }
-
- public void setProtocolVersion(final ProtocolVersion pv)
- {
- _logger.info("Setting ProtocolVersion to :" + pv);
- _protocolVersion = pv;
- _methodRegistry = MethodRegistry.getMethodRegistry(pv);
- _methodDispatcher = ClientMethodDispatcherImpl.newMethodDispatcher(pv, this);
- }
-
- public byte getProtocolMinorVersion()
- {
- return _protocolVersion.getMinorVersion();
- }
-
- public byte getProtocolMajorVersion()
- {
- return _protocolVersion.getMajorVersion();
- }
-
- public ProtocolVersion getProtocolVersion()
- {
- return _protocolVersion;
- }
-
- public MethodRegistry getMethodRegistry()
- {
- return _methodRegistry;
- }
-
- public MethodDispatcher getMethodDispatcher()
- {
- return _methodDispatcher;
- }
-
- public void setTicket(int ticket, int channelId)
- {
- final AMQSession session = getSession(channelId);
- session.setTicket(ticket);
- }
-
- public void setMethodDispatcher(MethodDispatcher methodDispatcher)
- {
- _methodDispatcher = methodDispatcher;
- }
-
- public void setFlowControl(final int channelId, final boolean active)
- {
- final AMQSession session = getSession(channelId);
- session.setFlowControl(active);
- }
-
- public void methodFrameReceived(final int channel, final AMQMethodBody amqMethodBody) throws AMQException
- {
- _protocolHandler.methodBodyReceived(channel, amqMethodBody);
- }
-
- public void notifyError(Exception error)
- {
- _protocolHandler.propagateExceptionToAllWaiters(error);
- }
-
- public void setSender(Sender<java.nio.ByteBuffer> sender)
- {
- // No-op, interface munging
- }
-
-
- @Override
- public String toString()
- {
- return "AMQProtocolSession[" + _connection + ']';
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/protocol/BlockingMethodFrameListener.java b/java/client/src/main/java/org/apache/qpid/client/protocol/BlockingMethodFrameListener.java
deleted file mode 100644
index 2bc609ebf2..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/protocol/BlockingMethodFrameListener.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.client.protocol;
-
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.locks.Condition;
-import java.util.concurrent.locks.ReentrantLock;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.AMQTimeoutException;
-import org.apache.qpid.client.failover.FailoverException;
-import org.apache.qpid.client.util.BlockingWaiter;
-import org.apache.qpid.framing.AMQMethodBody;
-import org.apache.qpid.protocol.AMQMethodEvent;
-import org.apache.qpid.protocol.AMQMethodListener;
-
-/**
- * BlockingMethodFrameListener is a 'rendezvous' which acts as a {@link AMQMethodListener} that delegates handling of
- * incoming methods to a method listener implemented as a sub-class of this and hands off the processed method or
- * error to a consumer. The producer of the event does not have to wait for the consumer to take the event, so this
- * differs from a 'rendezvous' in that sense.
- *
- * <p/>BlockingMethodFrameListeners are used to coordinate waiting for replies to method calls that expect a response.
- * They are always used in a 'one-shot' manner, that is, to recieve just one response. Usually the caller has to register
- * them as method listeners with an event dispatcher and remember to de-register them (in a finally block) once they
- * have been completed.
- *
- * <p/>The {@link #processMethod} must return <tt>true</tt> on any incoming method that it handles. This indicates to
- * this listeners that the method it is waiting for has arrived. Incoming methods are also filtered by channel prior to
- * being passed to the {@link #processMethod} method, so responses are only received for a particular channel. The
- * channel id must be passed to the constructor.
- *
- * <p/>Errors from the producer are rethrown to the consumer.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Accept notification of AMQP method events. <td> {@link AMQMethodEvent}
- * <tr><td> Delegate handling of the method to another method listener. <td> {@link AMQMethodBody}
- * <tr><td> Block until a method is handled by the delegated to handler.
- * <tr><td> Propagate the most recent exception to the consumer.
- * </table>
- *
- * @todo Might be neater if this method listener simply wrapped another that provided the method handling using a
- * methodRecevied method. The processMethod takes an additional channelId, however none of the implementations
- * seem to use it. So wrapping the listeners is possible.
- * @todo If the retrotranslator can handle it, could use a SynchronousQueue to implement this rendezvous. Need to
- * check that SynchronousQueue has a non-blocking put method available.
- */
-public abstract class BlockingMethodFrameListener extends BlockingWaiter<AMQMethodEvent> implements AMQMethodListener
-{
-
- /** Holds the channel id for the channel upon which this listener is waiting for a response. */
- protected int _channelId;
-
- /**
- * Creates a new method listener, that filters incoming method to just those that match the specified channel id.
- *
- * @param channelId The channel id to filter incoming methods with.
- */
- public BlockingMethodFrameListener(int channelId)
- {
- _channelId = channelId;
- }
-
- /**
- * Delegates any additional handling of the incoming methods to another handler.
- *
- * @param channelId The channel id of the incoming method.
- * @param frame The method body.
- *
- * @return <tt>true</tt> if the method was handled, <tt>false</tt> otherwise.
- */
- public abstract boolean processMethod(int channelId, AMQMethodBody frame);
-
- public boolean process(AMQMethodEvent evt)
- {
- AMQMethodBody method = evt.getMethod();
-
- return (evt.getChannelId() == _channelId) && processMethod(evt.getChannelId(), method);
- }
-
- /**
- * Informs this listener that an AMQP method has been received.
- *
- * @param evt The AMQP method.
- *
- * @return <tt>true</tt> if this listener has handled the method, <tt>false</tt> otherwise.
- */
- public boolean methodReceived(AMQMethodEvent evt)
- {
- return received(evt);
- }
-
- /**
- * Blocks until a method is received that is handled by the delegated to method listener, or the specified timeout
- * has passed.
- *
- * @param timeout The timeout in milliseconds.
- *
- * @return The AMQP method that was received.
- *
- * @throws AMQException
- * @throws FailoverException
- */
- public AMQMethodEvent blockForFrame(long timeout) throws AMQException, FailoverException
- {
- try
- {
- return (AMQMethodEvent) block(timeout);
- }
- finally
- {
- //Prevent any more errors being notified to this waiter.
- close();
- }
- }
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/protocol/HeartbeatConfig.java b/java/client/src/main/java/org/apache/qpid/client/protocol/HeartbeatConfig.java
deleted file mode 100644
index 35ea44a331..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/protocol/HeartbeatConfig.java
+++ /dev/null
@@ -1,61 +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.client.protocol;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-class HeartbeatConfig
-{
- private static final Logger _logger = LoggerFactory.getLogger(HeartbeatConfig.class);
- static final HeartbeatConfig CONFIG = new HeartbeatConfig();
-
- /**
- * The factor used to get the timeout from the delay between heartbeats.
- */
- private float timeoutFactor = 2;
-
- HeartbeatConfig()
- {
- String property = System.getProperty("amqj.heartbeat.timeoutFactor");
- if (property != null)
- {
- try
- {
- timeoutFactor = Float.parseFloat(property);
- }
- catch (NumberFormatException e)
- {
- _logger.warn("Invalid timeout factor (amqj.heartbeat.timeoutFactor): " + property);
- }
- }
- }
-
- float getTimeoutFactor()
- {
- return timeoutFactor;
- }
-
- int getTimeout(int writeDelay)
- {
- return (int) (timeoutFactor * writeDelay);
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/protocol/HeartbeatDiagnostics.java b/java/client/src/main/java/org/apache/qpid/client/protocol/HeartbeatDiagnostics.java
deleted file mode 100644
index d44faeab04..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/protocol/HeartbeatDiagnostics.java
+++ /dev/null
@@ -1,121 +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.client.protocol;
-
-class HeartbeatDiagnostics
-{
- private static final Diagnostics _impl = init();
-
- private static Diagnostics init()
- {
- return Boolean.getBoolean("amqj.heartbeat.diagnostics") ? new On() : new Off();
- }
-
- static void sent()
- {
- _impl.sent();
- }
-
- static void timeout()
- {
- _impl.timeout();
- }
-
- static void received(boolean heartbeat)
- {
- _impl.received(heartbeat);
- }
-
- static void init(int delay, int timeout)
- {
- _impl.init(delay, timeout);
- }
-
- private static interface Diagnostics
- {
- void sent();
- void timeout();
- void received(boolean heartbeat);
- void init(int delay, int timeout);
- }
-
- private static class On implements Diagnostics
- {
- private final String[] messages = new String[50];
- private int i;
-
- private void save(String msg)
- {
- messages[i++] = msg;
- if(i >= messages.length){
- i = 0;//i.e. a circular buffer
- }
- }
-
- public void sent()
- {
- save(System.currentTimeMillis() + ": sent heartbeat");
- }
-
- public void timeout()
- {
- for(int i = 0; i < messages.length; i++)
- {
- if(messages[i] != null)
- {
- System.out.println(messages[i]);
- }
- }
- System.out.println(System.currentTimeMillis() + ": timed out");
- }
-
- public void received(boolean heartbeat)
- {
- save(System.currentTimeMillis() + ": received " + (heartbeat ? "heartbeat" : "data"));
- }
-
- public void init(int delay, int timeout)
- {
- System.out.println(System.currentTimeMillis() + ": initialised delay=" + delay + ", timeout=" + timeout);
- }
- }
-
- private static class Off implements Diagnostics
- {
- public void sent()
- {
-
- }
- public void timeout()
- {
-
- }
- public void received(boolean heartbeat)
- {
-
- }
-
- public void init(int delay, int timeout)
- {
-
- }
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/protocol/ProtocolBufferMonitorFilter.java b/java/client/src/main/java/org/apache/qpid/client/protocol/ProtocolBufferMonitorFilter.java
deleted file mode 100644
index bbd0a7b144..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/protocol/ProtocolBufferMonitorFilter.java
+++ /dev/null
@@ -1,115 +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.client.protocol;
-
-import org.apache.mina.common.IoFilterAdapter;
-import org.apache.mina.common.IoSession;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * A MINA filter that monitors the numbers of messages pending to be sent by MINA. It outputs a message
- * when a threshold has been exceeded, and has a frequency configuration so that messages are not output
- * too often.
- *
- */
-public class ProtocolBufferMonitorFilter extends IoFilterAdapter
-{
- private static final Logger _logger = LoggerFactory.getLogger(ProtocolBufferMonitorFilter.class);
-
- public static final long DEFAULT_FREQUENCY = 5000;
-
- public static final int DEFAULT_THRESHOLD = 3000;
-
- private int _bufferedMessages = 0;
-
- private int _threshold;
-
- private long _lastMessageOutputTime;
-
- private long _outputFrequencyInMillis;
-
- public ProtocolBufferMonitorFilter()
- {
- _threshold = DEFAULT_THRESHOLD;
- _outputFrequencyInMillis = DEFAULT_FREQUENCY;
- }
-
- public ProtocolBufferMonitorFilter(int threshold, long frequency)
- {
- _threshold = threshold;
- _outputFrequencyInMillis = frequency;
- }
-
- public void messageReceived(NextFilter nextFilter, IoSession session, Object message) throws Exception
- {
- _bufferedMessages++;
- if (_bufferedMessages > _threshold)
- {
- long now = System.currentTimeMillis();
- if ((now - _lastMessageOutputTime) > _outputFrequencyInMillis)
- {
- _logger.warn("Protocol message buffer exceeded threshold of " + _threshold + ". Current backlog: "
- + _bufferedMessages);
- _lastMessageOutputTime = now;
- }
- }
-
- nextFilter.messageReceived(session, message);
- }
-
- public void messageSent(NextFilter nextFilter, IoSession session, Object message) throws Exception
- {
- _bufferedMessages--;
- nextFilter.messageSent(session, message);
- }
-
- public int getBufferedMessages()
- {
- return _bufferedMessages;
- }
-
- public int getThreshold()
- {
- return _threshold;
- }
-
- public void setThreshold(int threshold)
- {
- _threshold = threshold;
- }
-
- public long getOutputFrequencyInMillis()
- {
- return _outputFrequencyInMillis;
- }
-
- public void setOutputFrequencyInMillis(long outputFrequencyInMillis)
- {
- _outputFrequencyInMillis = outputFrequencyInMillis;
- }
-
- public long getLastMessageOutputTime()
- {
- return _lastMessageOutputTime;
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/security/AMQCallbackHandler.java b/java/client/src/main/java/org/apache/qpid/client/security/AMQCallbackHandler.java
deleted file mode 100644
index fbca444208..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/security/AMQCallbackHandler.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.
- *
- */
-package org.apache.qpid.client.security;
-
-import javax.security.auth.callback.CallbackHandler;
-
-import org.apache.qpid.client.protocol.AMQProtocolSession;
-
-public interface AMQCallbackHandler extends CallbackHandler
-{
- void initialise(AMQProtocolSession protocolSession);
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/security/CallbackHandlerRegistry.java b/java/client/src/main/java/org/apache/qpid/client/security/CallbackHandlerRegistry.java
deleted file mode 100644
index 140cbdeb75..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/security/CallbackHandlerRegistry.java
+++ /dev/null
@@ -1,231 +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.client.security;
-
-import org.apache.qpid.util.FileUtils;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Properties;
-
-/**
- * CallbackHandlerRegistry is a registry for call back handlers for user authentication and interaction during user
- * authentication. It is capable of reading its configuration from a properties file containing call back handler
- * implementing class names for different SASL mechanism names. Instantiating this registry also has the effect of
- * configuring and registering the SASL client factory implementations using {@link DynamicSaslRegistrar}.
- *
- * <p/>The callback configuration should be specified in a properties file, refered to by the System property
- * "amp.callbackhandler.properties". The format of the properties file is:
- *
- * <p/><pre>
- * CallbackHanlder.mechanism=fully.qualified.class.name
- * </pre>
- *
- * <p/>Where mechanism is an IANA-registered mechanism name and the fully qualified class name refers to a
- * class that implements org.apache.qpid.client.security.AMQCallbackHanlder and provides a call back handler for the
- * specified mechanism.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Parse callback properties.
- * <tr><td> Provide mapping from SASL mechanisms to callback implementations.
- * </table>
- */
-public class CallbackHandlerRegistry
-{
- private static final Logger _logger = LoggerFactory.getLogger(CallbackHandlerRegistry.class);
-
- /** The name of the system property that holds the name of the callback handler properties file. */
- private static final String FILE_PROPERTY = "amq.callbackhandler.properties";
-
- /** The default name of the callback handler properties resource. */
- public static final String DEFAULT_RESOURCE_NAME = "org/apache/qpid/client/security/CallbackHandlerRegistry.properties";
-
- /** A static reference to the singleton instance of this registry. */
- private static CallbackHandlerRegistry _instance = new CallbackHandlerRegistry();
-
- /** Holds a map from SASL mechanism names to call back handlers. */
- private Map<String, Class> _mechanismToHandlerClassMap = new HashMap<String, Class>();
-
- /** Holds a space delimited list of mechanisms that callback handlers exist for. */
- private String _mechanisms;
-
- /**
- * Gets the singleton instance of this registry.
- *
- * @return The singleton instance of this registry.
- */
- public static CallbackHandlerRegistry getInstance()
- {
- return _instance;
- }
-
- /**
- * Gets the callback handler class for a given SASL mechanism name.
- *
- * @param mechanism The SASL mechanism name.
- *
- * @return The callback handler class for the mechanism, or null if none is configured for that mechanism.
- */
- public Class getCallbackHandlerClass(String mechanism)
- {
- return (Class) _mechanismToHandlerClassMap.get(mechanism);
- }
-
- /**
- * Gets a space delimited list of supported SASL mechanisms.
- *
- * @return A space delimited list of supported SASL mechanisms.
- */
- public String getMechanisms()
- {
- return _mechanisms;
- }
-
- /**
- * Creates the call back handler registry from its configuration resource or file. This also has the side effect
- * of configuring and registering the SASL client factory implementations using {@link DynamicSaslRegistrar}.
- */
- private CallbackHandlerRegistry()
- {
- // Register any configured SASL client factories.
- DynamicSaslRegistrar.registerSaslProviders();
-
- String filename = System.getProperty(FILE_PROPERTY);
- InputStream is =
- FileUtils.openFileOrDefaultResource(filename, DEFAULT_RESOURCE_NAME,
- CallbackHandlerRegistry.class.getClassLoader());
-
- try
- {
- Properties props = new Properties();
- props.load(is);
- parseProperties(props);
- _logger.info("Callback handlers available for SASL mechanisms: " + _mechanisms);
- }
- catch (IOException e)
- {
- _logger.error("Error reading properties: " + e, e);
- }
- finally
- {
- if (is != null)
- {
- try
- {
- is.close();
-
- }
- catch (IOException e)
- {
- _logger.error("Unable to close properties stream: " + e, e);
- }
- }
- }
- }
-
- /*private InputStream openPropertiesInputStream(String filename)
- {
- boolean useDefault = true;
- InputStream is = null;
- if (filename != null)
- {
- try
- {
- is = new BufferedInputStream(new FileInputStream(new File(filename)));
- useDefault = false;
- }
- catch (FileNotFoundException e)
- {
- _logger.error("Unable to read from file " + filename + ": " + e, e);
- }
- }
-
- if (useDefault)
- {
- is = CallbackHandlerRegistry.class.getResourceAsStream(DEFAULT_RESOURCE_NAME);
- }
-
- return is;
- }*/
-
- /**
- * Scans the specified properties as a mapping from IANA registered SASL mechanism to call back handler
- * implementations, that provide the necessary call back handling for obtaining user log in credentials
- * during authentication for the specified mechanism, and builds a map from mechanism names to handler
- * classes.
- *
- * @param props
- */
- private void parseProperties(Properties props)
- {
- Enumeration e = props.propertyNames();
- while (e.hasMoreElements())
- {
- String propertyName = (String) e.nextElement();
- int period = propertyName.indexOf(".");
- if (period < 0)
- {
- _logger.warn("Unable to parse property " + propertyName + " when configuring SASL providers");
-
- continue;
- }
-
- String mechanism = propertyName.substring(period + 1);
- String className = props.getProperty(propertyName);
- Class clazz = null;
- try
- {
- clazz = Class.forName(className);
- if (!AMQCallbackHandler.class.isAssignableFrom(clazz))
- {
- _logger.warn("SASL provider " + clazz + " does not implement " + AMQCallbackHandler.class
- + ". Skipping");
-
- continue;
- }
-
- _mechanismToHandlerClassMap.put(mechanism, clazz);
- if (_mechanisms == null)
- {
- _mechanisms = mechanism;
- }
- else
- {
- // one time cost
- _mechanisms = _mechanisms + " " + mechanism;
- }
- }
- catch (ClassNotFoundException ex)
- {
- _logger.warn("Unable to load class " + className + ". Skipping that SASL provider");
-
- continue;
- }
- }
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/security/CallbackHandlerRegistry.properties b/java/client/src/main/java/org/apache/qpid/client/security/CallbackHandlerRegistry.properties
deleted file mode 100644
index 1fcfde3579..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/security/CallbackHandlerRegistry.properties
+++ /dev/null
@@ -1,22 +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.
-#
-CallbackHandler.CRAM-MD5-HASHED=org.apache.qpid.client.security.UsernameHashedPasswordCallbackHandler
-CallbackHandler.CRAM-MD5=org.apache.qpid.client.security.UsernamePasswordCallbackHandler
-CallbackHandler.AMQPLAIN=org.apache.qpid.client.security.UsernamePasswordCallbackHandler
-CallbackHandler.PLAIN=org.apache.qpid.client.security.UsernamePasswordCallbackHandler
diff --git a/java/client/src/main/java/org/apache/qpid/client/security/DynamicSaslRegistrar.java b/java/client/src/main/java/org/apache/qpid/client/security/DynamicSaslRegistrar.java
deleted file mode 100644
index 2b4261b4b7..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/security/DynamicSaslRegistrar.java
+++ /dev/null
@@ -1,210 +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.client.security;
-
-import org.apache.qpid.util.FileUtils;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.security.sasl.SaslClientFactory;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.security.Security;
-import java.util.Enumeration;
-import java.util.Map;
-import java.util.Properties;
-import java.util.TreeMap;
-
-/**
- * DynamicSaslRegistrar provides a collection of helper methods for reading a configuration file that contains a mapping
- * from SASL mechanism names to implementing client factory class names and registering a security provider with the
- * Java runtime system, that uses the configured client factory implementations.
- *
- * <p/>The sasl configuration should be specified in a properties file, refered to by the System property
- * "amp.dynamicsaslregistrar.properties". The format of the properties file is:
- *
- * <p/><pre>
- * mechanism=fully.qualified.class.name
- * </pre>
- *
- * <p/>Where mechanism is an IANA-registered mechanism name and the fully qualified class name refers to a class that
- * implements javax.security.sasl.SaslClientFactory and provides the specified mechanism.
- *
- * <p><table id="crc"><caption>CRC Card</caption> <tr><th> Responsibilities <th> Collaborations <tr><td> Parse SASL
- * mechanism properties. <tr><td> Create and register security provider for SASL mechanisms. </table>
- */
-public class DynamicSaslRegistrar
-{
- private static final Logger _logger = LoggerFactory.getLogger(DynamicSaslRegistrar.class);
-
- /** The name of the system property that holds the name of the SASL configuration properties. */
- private static final String FILE_PROPERTY = "amq.dynamicsaslregistrar.properties";
-
- /** The default name of the SASL properties file resource. */
- public static final String DEFAULT_RESOURCE_NAME = "org/apache/qpid/client/security/DynamicSaslRegistrar.properties";
-
- /** Reads the properties file, and creates a dynamic security provider to register the SASL implementations with. */
- public static void registerSaslProviders()
- {
- _logger.debug("public static void registerSaslProviders(): called");
-
- // Open the SASL properties file, using the default name is one is not specified.
- String filename = System.getProperty(FILE_PROPERTY);
- InputStream is =
- FileUtils.openFileOrDefaultResource(filename, DEFAULT_RESOURCE_NAME,
- DynamicSaslRegistrar.class.getClassLoader());
-
- try
- {
- Properties props = new Properties();
- props.load(is);
-
- _logger.debug("props = " + props);
-
- Map<String, Class<? extends SaslClientFactory>> factories = parseProperties(props);
-
- if (factories.size() > 0)
- {
- // Ensure we are used before the defaults
- if (Security.insertProviderAt(new JCAProvider(factories), 1) == -1)
- {
- _logger.error("Unable to load custom SASL providers.");
- }
- else
- {
- _logger.info("Additional SASL providers successfully registered.");
- }
- }
- else
- {
- _logger.warn("No additional SASL providers registered.");
- }
- }
- catch (IOException e)
- {
- _logger.error("Error reading properties: " + e, e);
- }
- finally
- {
- if (is != null)
- {
- try
- {
- is.close();
-
- }
- catch (IOException e)
- {
- _logger.error("Unable to close properties stream: " + e, e);
- }
- }
- }
- }
-
- /**
- * Either attempts to open the specified filename as an input stream, or uses the default SASL configuration
- * resource.
- *
- * @param filename The name of the file to get the SASL properties from, null to use the default.
- *
- * @return An input stream to read the dynamic SASL configuration from, or null if one could not be opened.
- */
- /*private static InputStream openPropertiesInputStream(String filename)
- {
- InputStream is = null;
-
- // Flag to indicate whether the default resource should be used. By default this is true, so that the default
- // is used when opening the file fails.
- boolean useDefault = true;
-
- // Try to open the file if one was specified.
- if (filename != null)
- {
- try
- {
- is = new BufferedInputStream(new FileInputStream(new File(filename)));
-
- // Clear the default flag because the file was succesfully opened.
- useDefault = false;
- }
- catch (FileNotFoundException e)
- {
- _logger.error("Unable to read from file " + filename + ": " + e, e);
- }
- }
-
- // Load the default resource if a file was not specified, or if opening the file failed.
- if (useDefault)
- {
- is = CallbackHandlerRegistry.class.getResourceAsStream(DEFAULT_RESOURCE_NAME);
- }
-
- return is;
- }*/
-
- /**
- * Parses the specified properties as a mapping from IANA registered SASL mechanism names to implementing client
- * factories. If the client factories cannot be instantiated or do not implement SaslClientFactory then the
- * properties refering to them are ignored.
- *
- * @param props The properties to scan for Sasl client factory implementations.
- *
- * @return A map from SASL mechanism names to implementing client factory classes.
- *
- * @todo Why tree map here? Do really want mechanisms in alphabetical order? Seems more likely that the declared
- * order of the mechanisms is intended to be preserved, so that they are registered in the declared order of
- * preference. Consider LinkedHashMap instead.
- */
- private static Map<String, Class<? extends SaslClientFactory>> parseProperties(Properties props)
- {
- Enumeration e = props.propertyNames();
-
- TreeMap<String, Class<? extends SaslClientFactory>> factoriesToRegister =
- new TreeMap<String, Class<? extends SaslClientFactory>>();
-
- while (e.hasMoreElements())
- {
- String mechanism = (String) e.nextElement();
- String className = props.getProperty(mechanism);
- try
- {
- Class<?> clazz = Class.forName(className);
- if (!(SaslClientFactory.class.isAssignableFrom(clazz)))
- {
- _logger.error("Class " + clazz + " does not implement " + SaslClientFactory.class + " - skipping");
-
- continue;
- }
-
- _logger.debug("Registering class "+ clazz.getName() +" for mechanism "+mechanism);
- factoriesToRegister.put(mechanism, (Class<? extends SaslClientFactory>) clazz);
- }
- catch (Exception ex)
- {
- _logger.error("Error instantiating SaslClientFactory calss " + className + " - skipping");
- }
- }
-
- return factoriesToRegister;
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/security/DynamicSaslRegistrar.properties b/java/client/src/main/java/org/apache/qpid/client/security/DynamicSaslRegistrar.properties
deleted file mode 100644
index b903208927..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/security/DynamicSaslRegistrar.properties
+++ /dev/null
@@ -1,21 +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.
-#
-AMQPLAIN=org.apache.qpid.client.security.amqplain.AmqPlainSaslClientFactory
-CRAM-MD5-HASHED=org.apache.qpid.client.security.crammd5hashed.CRAMMD5HashedSaslClientFactory
-ANONYMOUS=org.apache.qpid.client.security.anonymous.AnonymousSaslClientFactory
diff --git a/java/client/src/main/java/org/apache/qpid/client/security/JCAProvider.java b/java/client/src/main/java/org/apache/qpid/client/security/JCAProvider.java
deleted file mode 100644
index 828d26ed0d..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/security/JCAProvider.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.client.security;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.security.sasl.SaslClientFactory;
-
-import java.security.Provider;
-import java.security.Security;
-import java.util.Map;
-
-/**
- * JCAProvider is a security provider for SASL client factories that is configured from a map of SASL mechanism names
- * to client factories implementation class names. It is intended that the map of client factories can be read from a
- * configuration file or other application configuration mechanism.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Register SASL mechanism implementations.
- * </table>
- */
-public class JCAProvider extends Provider
-{
- private static final Logger log = LoggerFactory.getLogger(JCAProvider.class);
-
- /**
- * Creates the security provider with a map from SASL mechanisms to implementing factories.
- *
- * @param providerMap The map from SASL mechanims to implementing factory classes.
- */
- public JCAProvider(Map<String, Class<? extends SaslClientFactory>> providerMap)
- {
- super("AMQSASLProvider-Client", 1.0, "A JCA provider that registers all "
- + "AMQ SASL providers that want to be registered");
- register(providerMap);
-// Security.addProvider(this);
- }
-
- /**
- * Registers client factory classes for a map of mechanism names to client factory classes.
- *
- * @param providerMap The map from SASL mechanims to implementing factory classes.
- */
- private void register(Map<String, Class<? extends SaslClientFactory>> providerMap)
- {
- for (Map.Entry<String, Class<? extends SaslClientFactory>> me : providerMap.entrySet())
- {
- put( "SaslClientFactory."+me.getKey(), me.getValue().getName());
- log.debug("Registered SASL Client factory for " + me.getKey() + " as " + me.getValue().getName());
- }
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/security/UsernameHashedPasswordCallbackHandler.java b/java/client/src/main/java/org/apache/qpid/client/security/UsernameHashedPasswordCallbackHandler.java
deleted file mode 100644
index 66176dac3c..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/security/UsernameHashedPasswordCallbackHandler.java
+++ /dev/null
@@ -1,102 +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.client.security;
-
-import org.apache.qpid.client.protocol.AMQProtocolSession;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.security.auth.callback.Callback;
-import javax.security.auth.callback.NameCallback;
-import javax.security.auth.callback.PasswordCallback;
-import javax.security.auth.callback.UnsupportedCallbackException;
-
-import java.io.IOException;
-import java.io.UnsupportedEncodingException;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-
-public class UsernameHashedPasswordCallbackHandler implements AMQCallbackHandler
-{
- private static final Logger _logger = LoggerFactory.getLogger(UsernameHashedPasswordCallbackHandler.class);
-
- private AMQProtocolSession _protocolSession;
-
- public void initialise(AMQProtocolSession protocolSession)
- {
- _protocolSession = protocolSession;
- }
-
- public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException
- {
- for (int i = 0; i < callbacks.length; i++)
- {
- Callback cb = callbacks[i];
- if (cb instanceof NameCallback)
- {
- ((NameCallback) cb).setName(_protocolSession.getUsername());
- }
- else if (cb instanceof PasswordCallback)
- {
- try
- {
- ((PasswordCallback) cb).setPassword(getHash(_protocolSession.getPassword()));
- }
- catch (NoSuchAlgorithmException e)
- {
- UnsupportedCallbackException uce = new UnsupportedCallbackException(cb);
- uce.initCause(e);
- throw uce;
- }
- }
- else
- {
- throw new UnsupportedCallbackException(cb);
- }
- }
- }
-
- private char[] getHash(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException
- {
-
- byte[] data = text.getBytes("utf-8");
-
- MessageDigest md = MessageDigest.getInstance("MD5");
-
- for (byte b : data)
- {
- md.update(b);
- }
-
- byte[] digest = md.digest();
-
- char[] hash = new char[digest.length];
-
- int index = 0;
- for (byte b : digest)
- {
- hash[index++] = (char) b;
- }
-
- return hash;
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/security/UsernamePasswordCallbackHandler.java b/java/client/src/main/java/org/apache/qpid/client/security/UsernamePasswordCallbackHandler.java
deleted file mode 100644
index c50c62710f..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/security/UsernamePasswordCallbackHandler.java
+++ /dev/null
@@ -1,60 +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.client.security;
-
-import java.io.IOException;
-
-import javax.security.auth.callback.Callback;
-import javax.security.auth.callback.NameCallback;
-import javax.security.auth.callback.PasswordCallback;
-import javax.security.auth.callback.UnsupportedCallbackException;
-
-import org.apache.qpid.client.protocol.AMQProtocolSession;
-
-public class UsernamePasswordCallbackHandler implements AMQCallbackHandler
-{
- private AMQProtocolSession _protocolSession;
-
- public void initialise(AMQProtocolSession protocolSession)
- {
- _protocolSession = protocolSession;
- }
-
- public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException
- {
- for (int i = 0; i < callbacks.length; i++)
- {
- Callback cb = callbacks[i];
- if (cb instanceof NameCallback)
- {
- ((NameCallback)cb).setName(_protocolSession.getUsername());
- }
- else if (cb instanceof PasswordCallback)
- {
- ((PasswordCallback)cb).setPassword(_protocolSession.getPassword().toCharArray());
- }
- else
- {
- throw new UnsupportedCallbackException(cb);
- }
- }
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/security/amqplain/AmqPlainSaslClient.java b/java/client/src/main/java/org/apache/qpid/client/security/amqplain/AmqPlainSaslClient.java
deleted file mode 100644
index f8a25c630c..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/security/amqplain/AmqPlainSaslClient.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.client.security.amqplain;
-
-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.sasl.SaslClient;
-import javax.security.sasl.SaslException;
-
-import org.apache.qpid.framing.FieldTable;
-import org.apache.qpid.framing.FieldTableFactory;
-
-/**
- * Implements the "AMQPlain" authentication protocol that uses FieldTables to send username and pwd.
- *
- */
-public class AmqPlainSaslClient implements SaslClient
-{
- /**
- * The name of this mechanism
- */
- public static final String MECHANISM = "AMQPLAIN";
-
- private CallbackHandler _cbh;
-
- public AmqPlainSaslClient(CallbackHandler cbh)
- {
- _cbh = cbh;
- }
-
- public String getMechanismName()
- {
- return "AMQPLAIN";
- }
-
- public boolean hasInitialResponse()
- {
- return true;
- }
-
- public byte[] evaluateChallenge(byte[] challenge) throws SaslException
- {
- // we do not care about the prompt or the default name
- NameCallback nameCallback = new NameCallback("prompt", "defaultName");
- PasswordCallback pwdCallback = new PasswordCallback("prompt", false);
- Callback[] callbacks = new Callback[]{nameCallback, pwdCallback};
- try
- {
- _cbh.handle(callbacks);
- }
- catch (Exception e)
- {
- throw new SaslException("Error handling SASL callbacks: " + e, e);
- }
- FieldTable table = FieldTableFactory.newFieldTable();
- table.setString("LOGIN", nameCallback.getName());
- table.setString("PASSWORD", new String(pwdCallback.getPassword()));
- return table.getDataAsBytes();
- }
-
- public boolean isComplete()
- {
- return true;
- }
-
- public byte[] unwrap(byte[] incoming, int offset, int len) throws SaslException
- {
- throw new SaslException("Not supported");
- }
-
- public byte[] wrap(byte[] outgoing, int offset, int len) throws SaslException
- {
- throw new SaslException("Not supported");
- }
-
- public Object getNegotiatedProperty(String propName)
- {
- return null;
- }
-
- public void dispose() throws SaslException
- {
- _cbh = null;
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/security/amqplain/AmqPlainSaslClientFactory.java b/java/client/src/main/java/org/apache/qpid/client/security/amqplain/AmqPlainSaslClientFactory.java
deleted file mode 100644
index 30cc786890..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/security/amqplain/AmqPlainSaslClientFactory.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.client.security.amqplain;
-
-import java.util.Map;
-
-import javax.security.auth.callback.CallbackHandler;
-import javax.security.sasl.Sasl;
-import javax.security.sasl.SaslClient;
-import javax.security.sasl.SaslClientFactory;
-import javax.security.sasl.SaslException;
-
-public class AmqPlainSaslClientFactory implements SaslClientFactory
-{
- public SaslClient createSaslClient(String[] mechanisms, String authorizationId, String protocol, String serverName, Map props, CallbackHandler cbh) throws SaslException
- {
- for (int i = 0; i < mechanisms.length; i++)
- {
- if (mechanisms[i].equals(AmqPlainSaslClient.MECHANISM))
- {
- if (cbh == null)
- {
- throw new SaslException("CallbackHandler must not be null");
- }
- return new AmqPlainSaslClient(cbh);
- }
- }
- return null;
- }
-
- public String[] getMechanismNames(Map props)
- {
- if (props.containsKey(Sasl.POLICY_NOPLAINTEXT) ||
- props.containsKey(Sasl.POLICY_NODICTIONARY) ||
- props.containsKey(Sasl.POLICY_NOACTIVE))
- {
- // returned array must be non null according to interface documentation
- return new String[0];
- }
- else
- {
- return new String[]{AmqPlainSaslClient.MECHANISM};
- }
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/security/anonymous/AnonymousSaslClient.java b/java/client/src/main/java/org/apache/qpid/client/security/anonymous/AnonymousSaslClient.java
deleted file mode 100644
index 0f56b2ef6c..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/security/anonymous/AnonymousSaslClient.java
+++ /dev/null
@@ -1,52 +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.client.security.anonymous;
-
-import javax.security.sasl.SaslClient;
-import javax.security.sasl.SaslException;
-
-public class AnonymousSaslClient implements SaslClient
-{
- public String getMechanismName() {
- return "ANONYMOUS";
- }
- public boolean hasInitialResponse() {
- return true;
- }
- public byte[] evaluateChallenge(byte[] challenge) throws SaslException {
- return new byte[0];
- }
- public boolean isComplete() {
- return true;
- }
- public byte[] unwrap(byte[] incoming, int offset, int len) throws SaslException
- {
- throw new IllegalStateException("No security layer supported");
- }
- public byte[] wrap(byte[] outgoing, int offset, int len) throws SaslException
- {
- throw new IllegalStateException("No security layer supported");
- }
- public Object getNegotiatedProperty(String propName) {
- return null;
- }
- public void dispose() throws SaslException {}
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/security/anonymous/AnonymousSaslClientFactory.java b/java/client/src/main/java/org/apache/qpid/client/security/anonymous/AnonymousSaslClientFactory.java
deleted file mode 100644
index de698f87c6..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/security/anonymous/AnonymousSaslClientFactory.java
+++ /dev/null
@@ -1,52 +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.client.security.anonymous;
-
-import java.util.Arrays;
-import java.util.Map;
-
-import javax.security.sasl.Sasl;
-import javax.security.sasl.SaslClient;
-import javax.security.sasl.SaslClientFactory;
-import javax.security.sasl.SaslException;
-import javax.security.auth.callback.CallbackHandler;
-
-public class AnonymousSaslClientFactory implements SaslClientFactory
-{
- public SaslClient createSaslClient(String[] mechanisms, String authId,
- String protocol, String server,
- Map props, CallbackHandler cbh) throws SaslException
- {
- if (Arrays.asList(mechanisms).contains("ANONYMOUS")) {
- return new AnonymousSaslClient();
- } else {
- return null;
- }
- }
- public String[] getMechanismNames(Map props)
- {
- if (props == null || props.isEmpty()) {
- return new String[]{"ANONYMOUS"};
- } else {
- return new String[0];
- }
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/security/crammd5hashed/CRAMMD5HashedSaslClientFactory.java b/java/client/src/main/java/org/apache/qpid/client/security/crammd5hashed/CRAMMD5HashedSaslClientFactory.java
deleted file mode 100644
index 22bb1ac156..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/security/crammd5hashed/CRAMMD5HashedSaslClientFactory.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- *
- */
-package org.apache.qpid.client.security.crammd5hashed;
-
-import org.apache.qpid.client.security.amqplain.AmqPlainSaslClient;
-
-import javax.security.sasl.SaslClientFactory;
-import javax.security.sasl.SaslClient;
-import javax.security.sasl.SaslException;
-import javax.security.sasl.Sasl;
-import javax.security.auth.callback.CallbackHandler;
-import java.util.Map;
-import java.security.Security;
-
-public class CRAMMD5HashedSaslClientFactory implements SaslClientFactory
-{
- /** The name of this mechanism */
- public static final String MECHANISM = "CRAM-MD5-HASHED";
-
-
- public SaslClient createSaslClient(String[] mechanisms, String authorizationId, String protocol, String serverName, Map<String, ?> props, CallbackHandler cbh) throws SaslException
- {
- for (int i = 0; i < mechanisms.length; i++)
- {
- if (mechanisms[i].equals(MECHANISM))
- {
- if (cbh == null)
- {
- throw new SaslException("CallbackHandler must not be null");
- }
-
- String[] mechs = {"CRAM-MD5"};
- return Sasl.createSaslClient(mechs, authorizationId, protocol, serverName, props, cbh);
- }
- }
- return null;
- }
-
- public String[] getMechanismNames(Map props)
- {
- if (props != null)
- {
- if (props.containsKey(Sasl.POLICY_NOPLAINTEXT) ||
- props.containsKey(Sasl.POLICY_NODICTIONARY) ||
- props.containsKey(Sasl.POLICY_NOACTIVE))
- {
- // returned array must be non null according to interface documentation
- return new String[0];
- }
- }
-
- return new String[]{MECHANISM};
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/state/AMQMethodNotImplementedException.java b/java/client/src/main/java/org/apache/qpid/client/state/AMQMethodNotImplementedException.java
deleted file mode 100644
index 2c99b9a97b..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/state/AMQMethodNotImplementedException.java
+++ /dev/null
@@ -1,32 +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.client.state;
-
-import org.apache.qpid.framing.AMQMethodBody;
-import org.apache.qpid.AMQException;
-
-public class AMQMethodNotImplementedException extends AMQException
-{
- public AMQMethodNotImplementedException(AMQMethodBody body)
- {
- super(null, "Unexpected Method Received: " + body.getClass().getName(), null);
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/state/AMQState.java b/java/client/src/main/java/org/apache/qpid/client/state/AMQState.java
deleted file mode 100644
index d32d10542f..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/state/AMQState.java
+++ /dev/null
@@ -1,60 +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.client.state;
-
-/**
- * States used in the AMQ protocol. Used by the finite state machine to determine
- * valid responses.
- */
-public enum AMQState
-{
-
- CONNECTION_NOT_STARTED(1, "CONNECTION_NOT_STARTED"),
-
- CONNECTION_NOT_TUNED(2, "CONNECTION_NOT_TUNED"),
-
- CONNECTION_NOT_OPENED(3, "CONNECTION_NOT_OPENED"),
-
- CONNECTION_OPEN(4, "CONNECTION_OPEN"),
-
- CONNECTION_CLOSING(5, "CONNECTION_CLOSING"),
-
- CONNECTION_CLOSED(6, "CONNECTION_CLOSED");
-
-
- private final int _id;
-
- private final String _name;
-
- private AMQState(int id, String name)
- {
- _id = id;
- _name = name;
- }
-
- public String toString()
- {
- return "AMQState: id = " + _id + " name: " + _name;
- }
-
-
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/state/AMQStateChangedEvent.java b/java/client/src/main/java/org/apache/qpid/client/state/AMQStateChangedEvent.java
deleted file mode 100644
index edef54ccd6..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/state/AMQStateChangedEvent.java
+++ /dev/null
@@ -1,48 +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.client.state;
-
-/**
- * An event that is fired when the protocol state has changed.
- *
- */
-public class AMQStateChangedEvent
-{
- private final AMQState _oldState;
-
- private final AMQState _newState;
-
- public AMQStateChangedEvent(AMQState oldState, AMQState newState)
- {
- _oldState = oldState;
- _newState = newState;
- }
-
- public AMQState getOldState()
- {
- return _oldState;
- }
-
- public AMQState getNewState()
- {
- return _newState;
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/state/AMQStateListener.java b/java/client/src/main/java/org/apache/qpid/client/state/AMQStateListener.java
deleted file mode 100644
index 110471aad0..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/state/AMQStateListener.java
+++ /dev/null
@@ -1,26 +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.client.state;
-
-public interface AMQStateListener
-{
- void stateChanged(AMQStateChangedEvent evt);
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/state/AMQStateManager.java b/java/client/src/main/java/org/apache/qpid/client/state/AMQStateManager.java
deleted file mode 100644
index 9c7d62670c..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/state/AMQStateManager.java
+++ /dev/null
@@ -1,221 +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.client.state;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.protocol.AMQProtocolSession;
-import org.apache.qpid.framing.*;
-import org.apache.qpid.protocol.AMQMethodEvent;
-import org.apache.qpid.protocol.AMQMethodListener;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.Set;
-import java.util.List;
-import java.util.concurrent.CopyOnWriteArrayList;
-import java.io.IOException;
-
-/**
- * The state manager is responsible for managing the state of the protocol session. <p/>
- * For each {@link org.apache.qpid.client.protocol.AMQProtocolHandler} there is a separate state manager.
- *
- * The AMQStateManager is now attached to the {@link org.apache.qpid.client.protocol.AMQProtocolHandler} and that is the sole point of reference so that
- * As the {@link AMQProtocolSession} changes due to failover the AMQStateManager need not be copied around.
- *
- * The StateManager works by any component can wait for a state change to occur by using the following sequence.
- *
- * <li>StateWaiter waiter = stateManager.createWaiter(Set<AMQState> states);
- * <li> // Perform action that will cause state change
- * <li>waiter.await();
- *
- * The two step process is required as there is an inherit race condition between starting a process that will cause
- * the state to change and then attempting to wait for that change. The interest in the change must be first set up so
- * that any asynchrous errors that occur can be delivered to the correct waiters.
- */
-public class AMQStateManager implements AMQMethodListener
-{
- private static final Logger _logger = LoggerFactory.getLogger(AMQStateManager.class);
-
- private AMQProtocolSession _protocolSession;
-
- /** The current state */
- private AMQState _currentState;
-
- private final Object _stateLock = new Object();
-
- private static final long MAXIMUM_STATE_WAIT_TIME = Long.parseLong(System.getProperty("amqj.MaximumStateWait", "30000"));
-
- protected final List<StateWaiter> _waiters = new CopyOnWriteArrayList<StateWaiter>();
- private Exception _lastException;
-
- public AMQStateManager()
- {
- this(null);
- }
-
- public AMQStateManager(AMQProtocolSession protocolSession)
- {
- this(AMQState.CONNECTION_NOT_STARTED, protocolSession);
- }
-
- protected AMQStateManager(AMQState state, AMQProtocolSession protocolSession)
- {
- _protocolSession = protocolSession;
- _currentState = state;
- }
-
- public AMQState getCurrentState()
- {
- return _currentState;
- }
-
- public void changeState(AMQState newState)
- {
- _logger.debug("State changing to " + newState + " from old state " + _currentState);
-
- synchronized (_stateLock)
- {
- _currentState = newState;
-
- _logger.debug("Notififying State change to " + _waiters.size() + " : " + _waiters);
-
- for (StateWaiter waiter : _waiters)
- {
- waiter.received(newState);
- }
- }
- }
-
- public <B extends AMQMethodBody> boolean methodReceived(AMQMethodEvent<B> evt) throws AMQException
- {
- B method = evt.getMethod();
-
- // StateAwareMethodListener handler = findStateTransitionHandler(_currentState, evt.getMethod());
- method.execute(_protocolSession.getMethodDispatcher(), evt.getChannelId());
- return true;
- }
-
- /**
- * Setting of the ProtocolSession will be required when Failover has been successfuly compeleted.
- *
- * The new {@link AMQProtocolSession} that has been re-established needs to be provided as that is now the
- * connection to the network.
- *
- * @param session The new protocol session
- */
- public void setProtocolSession(AMQProtocolSession session)
- {
- if (_logger.isInfoEnabled())
- {
- _logger.info("Setting ProtocolSession:" + session);
- }
- _protocolSession = session;
- }
-
- /**
- * Propogate error to waiters
- *
- * @param error The error to propogate.
- */
- public void error(Exception error)
- {
- if (error instanceof AMQException)
- {
- // AMQException should be being notified before closing the
- // ProtocolSession. Which will change the State to CLOSED.
- // if we have a hard error.
- if (((AMQException)error).isHardError())
- {
- changeState(AMQState.CONNECTION_CLOSING);
- }
- }
- else
- {
- // Be on the safe side here and mark the connection closed
- changeState(AMQState.CONNECTION_CLOSED);
- }
-
- if (_waiters.size() == 0)
- {
- _logger.error("No Waiters for error saving as last error:" + error.getMessage());
- _lastException = error;
- }
- for (StateWaiter waiter : _waiters)
- {
- _logger.error("Notifying Waiters(" + _waiters + ") for error:" + error.getMessage());
- waiter.error(error);
- }
- }
-
- /**
- * This provides a single place that the maximum time for state change to occur can be accessed.
- * It is currently set via System property amqj.MaximumStateWait
- *
- * @return long Milliseconds value for a timeout
- */
- public long getWaitTimeout()
- {
- return MAXIMUM_STATE_WAIT_TIME;
- }
-
- /**
- * Create and add a new waiter to the notifcation list.
- *
- * @param states The waiter will attempt to wait for one of these desired set states to be achived.
- *
- * @return the created StateWaiter.
- */
- public StateWaiter createWaiter(Set<AMQState> states)
- {
- final StateWaiter waiter;
- synchronized (_stateLock)
- {
- waiter = new StateWaiter(this, _currentState, states);
-
- _waiters.add(waiter);
- }
-
- return waiter;
- }
-
- /**
- * Remove the waiter from the notification list.
- *
- * @param waiter The waiter to remove.
- */
- public void removeWaiter(StateWaiter waiter)
- {
- synchronized (_stateLock)
- {
- _waiters.remove(waiter);
- }
- }
-
- public Exception getLastException()
- {
- return _lastException;
- }
-
- public void clearLastException()
- {
- _lastException = null;
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/state/StateAwareMethodListener.java b/java/client/src/main/java/org/apache/qpid/client/state/StateAwareMethodListener.java
deleted file mode 100644
index 17d04f4fa3..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/state/StateAwareMethodListener.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.client.state;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.AMQMethodBody;
-import org.apache.qpid.client.protocol.AMQProtocolSession;
-import org.apache.qpid.protocol.AMQMethodEvent;
-
-/**
- * A frame listener that is informed of the protocl state when invoked and has
- * the opportunity to update state.
- *
- */
-public interface StateAwareMethodListener<B extends AMQMethodBody>
-{
-
- void methodReceived(AMQProtocolSession session, B body, int channelId) throws AMQException;
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/state/StateWaiter.java b/java/client/src/main/java/org/apache/qpid/client/state/StateWaiter.java
deleted file mode 100644
index 79f438d35d..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/state/StateWaiter.java
+++ /dev/null
@@ -1,128 +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.client.state;
-
-import org.apache.qpid.client.util.BlockingWaiter;
-import org.apache.qpid.client.failover.FailoverException;
-import org.apache.qpid.AMQException;
-import org.slf4j.LoggerFactory;
-import org.slf4j.Logger;
-
-import java.util.Set;
-
-/**
- * This is an implementation of the {@link BlockingWaiter} to provide error handing and a waiting mechanism for state
- * changes.
- *
- * On construction the current state and a set of States to await for is provided.
- *
- * When await() is called the state at constuction is compared against the awaitStates. If the state at construction is
- * a desired state then await() returns immediately.
- *
- * Otherwise it will block for the set timeout for a desired state to be achieved.
- *
- * The state changes are notified via the {@link #process} method.
- *
- * Any notified error is handled by the BlockingWaiter and thrown from the {@link #block} method.
- *
- */
-public class StateWaiter extends BlockingWaiter<AMQState>
-{
- private static final Logger _logger = LoggerFactory.getLogger(StateWaiter.class);
-
- Set<AMQState> _awaitStates;
- private AMQState _startState;
- private AMQStateManager _stateManager;
-
- /**
- *
- * @param stateManager The StateManager
- * @param currentState
- * @param awaitStates
- */
- public StateWaiter(AMQStateManager stateManager, AMQState currentState, Set<AMQState> awaitStates)
- {
- _logger.info("New StateWaiter :" + currentState + ":" + awaitStates);
- _stateManager = stateManager;
- _awaitStates = awaitStates;
- _startState = currentState;
- }
-
- /**
- * When the state is changed this StateWaiter is notified to process the change.
- *
- * @param state The new state that has been achieved.
- * @return
- */
- public boolean process(AMQState state)
- {
- return _awaitStates.contains(state);
- }
-
- /**
- * Await for the requried State to be achieved within the default timeout.
- * @return The achieved state that was requested.
- * @throws AMQException The exception that prevented the required state from being achived.
- */
- public AMQState await() throws AMQException
- {
- return await(_stateManager.getWaitTimeout());
- }
-
- /**
- * Await for the requried State to be achieved.
- *
- * <b>It is the responsibility of this class to remove the waiter from the StateManager
- *
- * @param timeout The time in milliseconds to wait for any of the states to be achived.
- * @return The achieved state that was requested.
- * @throws AMQException The exception that prevented the required state from being achived.
- */
- public AMQState await(long timeout) throws AMQException
- {
- try
- {
- if (process(_startState))
- {
- return _startState;
- }
-
- try
- {
- return (AMQState) block(timeout);
- }
- catch (FailoverException e)
- {
- _logger.error("Failover occured whilst waiting for states:" + _awaitStates);
-
- return null;
- }
- }
- finally
- {
- //Prevent any more errors being notified to this waiter.
- close();
-
- //Remove the waiter from the notifcation list in the statee manager
- _stateManager.removeWaiter(this);
- }
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/state/listener/SpecificMethodFrameListener.java b/java/client/src/main/java/org/apache/qpid/client/state/listener/SpecificMethodFrameListener.java
deleted file mode 100644
index f0d7feb059..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/state/listener/SpecificMethodFrameListener.java
+++ /dev/null
@@ -1,41 +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.client.state.listener;
-
-
-import org.apache.qpid.client.protocol.BlockingMethodFrameListener;
-import org.apache.qpid.framing.AMQMethodBody;
-
-public class SpecificMethodFrameListener extends BlockingMethodFrameListener
-{
- private final Class _expectedClass;
-
- public SpecificMethodFrameListener(int channelId, Class expectedClass)
- {
- super(channelId);
- _expectedClass = expectedClass;
- }
-
- public boolean processMethod(int channelId, AMQMethodBody frame)
- {
- return _expectedClass.isInstance(frame);
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/transport/AMQNoTransportForProtocolException.java b/java/client/src/main/java/org/apache/qpid/client/transport/AMQNoTransportForProtocolException.java
deleted file mode 100644
index 6e47e2ce28..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/transport/AMQNoTransportForProtocolException.java
+++ /dev/null
@@ -1,59 +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.client.transport;
-
-import org.apache.qpid.jms.BrokerDetails;
-
-/**
- * AMQNoTransportForProtocolException represents a connection failure where there is no transport medium to connect
- * to the broker available. This may be the case if their is a error in the connection url, or an unsupported transport
- * type is specified.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Represent absence of a transport medium.
- * </table>
- *
- * @todo Error code never used. This is not an AMQException.
- */
-public class AMQNoTransportForProtocolException extends AMQTransportConnectionException
-{
- BrokerDetails _details;
-
- public AMQNoTransportForProtocolException(BrokerDetails details, String message, Throwable cause)
- {
- super(null, message, cause);
-
- _details = details;
- }
-
- public String toString()
- {
- if (_details != null)
- {
- return super.toString() + _details.toString();
- }
- else
- {
- return super.toString();
- }
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/transport/AMQTransportConnectionException.java b/java/client/src/main/java/org/apache/qpid/client/transport/AMQTransportConnectionException.java
deleted file mode 100644
index 6bef6216bd..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/transport/AMQTransportConnectionException.java
+++ /dev/null
@@ -1,43 +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.client.transport;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.protocol.AMQConstant;
-
-/**
- * AMQTransportConnectionException indicates a failure to establish a connection through the transporting medium, to
- * an AMQP broker.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Represent failure to connect through the transport medium.
- * </table>
- *
- * @todo Error code never used. This is not an AMQException.
- */
-public class AMQTransportConnectionException extends AMQException
-{
- public AMQTransportConnectionException(AMQConstant errorCode, String message, Throwable cause)
- {
- super(errorCode, message, cause);
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/transport/ITransportConnection.java b/java/client/src/main/java/org/apache/qpid/client/transport/ITransportConnection.java
deleted file mode 100644
index 7a24d6e15a..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/transport/ITransportConnection.java
+++ /dev/null
@@ -1,32 +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.client.transport;
-
-import java.io.IOException;
-
-import org.apache.qpid.client.protocol.AMQProtocolHandler;
-import org.apache.qpid.jms.BrokerDetails;
-
-public interface ITransportConnection
-{
- void connect(AMQProtocolHandler protocolHandler, BrokerDetails brokerDetail)
- throws IOException;
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/transport/SocketTransportConnection.java b/java/client/src/main/java/org/apache/qpid/client/transport/SocketTransportConnection.java
deleted file mode 100644
index 1ac8f62e32..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/transport/SocketTransportConnection.java
+++ /dev/null
@@ -1,90 +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.client.transport;
-
-import java.io.IOException;
-import java.net.InetSocketAddress;
-
-import org.apache.mina.common.ByteBuffer;
-import org.apache.mina.common.IoConnector;
-import org.apache.mina.common.SimpleByteBufferAllocator;
-import org.apache.qpid.client.SSLConfiguration;
-import org.apache.qpid.client.protocol.AMQProtocolHandler;
-import org.apache.qpid.jms.BrokerDetails;
-import org.apache.qpid.ssl.SSLContextFactory;
-import org.apache.qpid.transport.network.mina.MINANetworkDriver;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class SocketTransportConnection implements ITransportConnection
-{
- private static final Logger _logger = LoggerFactory.getLogger(SocketTransportConnection.class);
- private static final int DEFAULT_BUFFER_SIZE = 32 * 1024;
-
- private SocketConnectorFactory _socketConnectorFactory;
-
- static interface SocketConnectorFactory
- {
- IoConnector newSocketConnector();
- }
-
- public SocketTransportConnection(SocketConnectorFactory socketConnectorFactory)
- {
- _socketConnectorFactory = socketConnectorFactory;
- }
-
- public void connect(AMQProtocolHandler protocolHandler, BrokerDetails brokerDetail) throws IOException
- {
- ByteBuffer.setUseDirectBuffers(Boolean.getBoolean("amqj.enableDirectBuffers"));
-
- // the MINA default is currently to use the pooled allocator although this may change in future
- // once more testing of the performance of the simple allocator has been done
- if (!Boolean.getBoolean("amqj.enablePooledAllocator"))
- {
- _logger.info("Using SimpleByteBufferAllocator");
- ByteBuffer.setAllocator(new SimpleByteBufferAllocator());
- }
-
- final IoConnector ioConnector = _socketConnectorFactory.newSocketConnector();
- final InetSocketAddress address;
-
- if (brokerDetail.getTransport().equals(BrokerDetails.SOCKET))
- {
- address = null;
- }
- else
- {
- address = new InetSocketAddress(brokerDetail.getHost(), brokerDetail.getPort());
- _logger.info("Attempting connection to " + address);
- }
-
- SSLConfiguration sslConfig = protocolHandler.getConnection().getSSLConfiguration();
- SSLContextFactory sslFactory = null;
- if (sslConfig != null)
- {
- sslFactory = new SSLContextFactory(sslConfig.getKeystorePath(), sslConfig.getKeystorePassword(), sslConfig.getCertType());
- }
-
- MINANetworkDriver driver = new MINANetworkDriver(ioConnector);
- driver.open(brokerDetail.getPort(), address.getAddress(), protocolHandler, null, sslFactory);
- protocolHandler.setNetworkDriver(driver);
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/transport/TransportConnection.java b/java/client/src/main/java/org/apache/qpid/client/transport/TransportConnection.java
deleted file mode 100644
index aef3a563af..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/transport/TransportConnection.java
+++ /dev/null
@@ -1,351 +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.client.transport;
-
-import java.io.IOException;
-import java.net.Socket;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-import org.apache.mina.common.IoConnector;
-import org.apache.mina.common.IoHandlerAdapter;
-import org.apache.mina.common.IoServiceConfig;
-import org.apache.mina.transport.socket.nio.ExistingSocketConnector;
-import org.apache.mina.transport.socket.nio.MultiThreadSocketConnector;
-import org.apache.mina.transport.socket.nio.SocketConnector;
-import org.apache.mina.transport.vmpipe.VmPipeAcceptor;
-import org.apache.mina.transport.vmpipe.VmPipeAddress;
-import org.apache.qpid.client.vmbroker.AMQVMBrokerCreationException;
-import org.apache.qpid.jms.BrokerDetails;
-import org.apache.qpid.protocol.ProtocolEngineFactory;
-import org.apache.qpid.thread.QpidThreadExecutor;
-import org.apache.qpid.transport.network.mina.MINANetworkDriver;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * The TransportConnection is a helper class responsible for connecting to an AMQ server. It sets up the underlying
- * connector, which currently always uses TCP/IP sockets. It creates the "protocol handler" which deals with MINA
- * protocol events. <p/> Could be extended in future to support different transport types by turning this into concrete
- * class/interface combo.
- */
-public class TransportConnection
-{
- private static ITransportConnection _instance;
-
- private static final Map _inVmPipeAddress = new HashMap();
- private static VmPipeAcceptor _acceptor;
- private static int _currentInstance = -1;
- private static int _currentVMPort = -1;
-
- private static final int TCP = 0;
- private static final int VM = 1;
- private static final int SOCKET = 2;
-
- private static Logger _logger = LoggerFactory.getLogger(TransportConnection.class);
-
- private static final String DEFAULT_QPID_SERVER = "org.apache.qpid.server.protocol.AMQProtocolEngineFactory";
-
- private static Map<String, Socket> _openSocketRegister = new ConcurrentHashMap<String, Socket>();
-
- public static void registerOpenSocket(String socketID, Socket openSocket)
- {
- _openSocketRegister.put(socketID, openSocket);
- }
-
- public static Socket removeOpenSocket(String socketID)
- {
- return _openSocketRegister.remove(socketID);
- }
-
- public static synchronized ITransportConnection getInstance(final BrokerDetails details) throws AMQTransportConnectionException
- {
- int transport = getTransport(details.getTransport());
-
- if (transport == -1)
- {
- throw new AMQNoTransportForProtocolException(details, null, null);
- }
-
- switch (transport)
- {
- case SOCKET:
- return new SocketTransportConnection(new SocketTransportConnection.SocketConnectorFactory()
- {
- public IoConnector newSocketConnector()
- {
- ExistingSocketConnector connector = new ExistingSocketConnector(1,new QpidThreadExecutor());
-
- Socket socket = TransportConnection.removeOpenSocket(details.getHost());
-
- if (socket != null)
- {
- _logger.info("Using existing Socket:" + socket);
-
- ((ExistingSocketConnector) connector).setOpenSocket(socket);
- }
- else
- {
- throw new IllegalArgumentException("Active Socket must be provided for broker " +
- "with 'socket://<SocketID>' transport:" + details);
- }
- return connector;
- }
- });
- case TCP:
- return new SocketTransportConnection(new SocketTransportConnection.SocketConnectorFactory()
- {
- public IoConnector newSocketConnector()
- {
- SocketConnector result;
- // FIXME - this needs to be sorted to use the new Mina MultiThread SA.
- if (Boolean.getBoolean("qpidnio"))
- {
- _logger.warn("Using Qpid MultiThreaded NIO - " + (System.getProperties().containsKey("qpidnio")
- ? "Qpid NIO is new default"
- : "Sysproperty 'qpidnio' is set"));
- result = new MultiThreadSocketConnector(1, new QpidThreadExecutor());
- }
- else
- {
- _logger.info("Using Mina NIO");
- result = new SocketConnector(1, new QpidThreadExecutor()); // non-blocking connector
- }
- // Don't have the connector's worker thread wait around for other connections (we only use
- // one SocketConnector per connection at the moment anyway). This allows short-running
- // clients (like unit tests) to complete quickly.
- result.setWorkerTimeout(0);
- return result;
- }
- });
- case VM:
- {
- return getVMTransport(details, Boolean.getBoolean("amqj.AutoCreateVMBroker"));
- }
- default:
- throw new AMQNoTransportForProtocolException(details, "Transport not recognised:" + transport, null);
- }
- }
-
- private static int getTransport(String transport)
- {
- if (transport.equals(BrokerDetails.SOCKET))
- {
- return SOCKET;
- }
-
- if (transport.equals(BrokerDetails.TCP))
- {
- return TCP;
- }
-
- if (transport.equals(BrokerDetails.VM))
- {
- return VM;
- }
-
- return -1;
- }
-
- private static ITransportConnection getVMTransport(BrokerDetails details, boolean AutoCreate)
- throws AMQVMBrokerCreationException
- {
- int port = details.getPort();
-
- synchronized (_inVmPipeAddress)
- {
- if (!_inVmPipeAddress.containsKey(port))
- {
- if (AutoCreate)
- {
- _logger.warn("Auto Creating InVM Broker on port:" + port);
- createVMBroker(port);
- }
- else
- {
- throw new AMQVMBrokerCreationException(null, port, "VM Broker on port " + port
- + " does not exist. Auto create disabled.", null);
- }
- }
- }
-
- return new VmPipeTransportConnection(port);
- }
-
- public static void createVMBroker(int port) throws AMQVMBrokerCreationException
- {
- synchronized(TransportConnection.class)
- {
- if (_acceptor == null)
- {
- _acceptor = new VmPipeAcceptor();
-
- IoServiceConfig config = _acceptor.getDefaultConfig();
- }
- }
- synchronized (_inVmPipeAddress)
- {
-
- if (!_inVmPipeAddress.containsKey(port))
- {
- _logger.info("Creating InVM Qpid.AMQP listening on port " + port);
- IoHandlerAdapter provider = null;
- try
- {
- VmPipeAddress pipe = new VmPipeAddress(port);
-
- provider = createBrokerInstance(port);
-
- _acceptor.bind(pipe, provider);
-
- _inVmPipeAddress.put(port, pipe);
- _logger.info("Created InVM Qpid.AMQP listening on port " + port);
- }
- catch (IOException e)
- {
- _logger.error("Got IOException.", e);
-
- // Try and unbind provider
- try
- {
- VmPipeAddress pipe = new VmPipeAddress(port);
-
- try
- {
- _acceptor.unbind(pipe);
- }
- catch (Exception ignore)
- {
- // ignore
- }
-
- if (provider == null)
- {
- provider = createBrokerInstance(port);
- }
-
- _acceptor.bind(pipe, provider);
- _inVmPipeAddress.put(port, pipe);
- _logger.info("Created InVM Qpid.AMQP listening on port " + port);
- }
- catch (IOException justUseFirstException)
- {
- String because;
- if (e.getCause() == null)
- {
- because = e.toString();
- }
- else
- {
- because = e.getCause().toString();
- }
-
- throw new AMQVMBrokerCreationException(null, port, because + " Stopped binding of InVM Qpid.AMQP", e);
- }
- }
-
- }
- else
- {
- _logger.info("InVM Qpid.AMQP on port " + port + " already exits.");
- }
- }
- }
-
- private static IoHandlerAdapter createBrokerInstance(int port) throws AMQVMBrokerCreationException
- {
- String protocolProviderClass = System.getProperty("amqj.protocolprovider.class", DEFAULT_QPID_SERVER);
- _logger.info("Creating Qpid protocol provider: " + protocolProviderClass);
-
- // can't use introspection to get Provider as it is a server class.
- // need to go straight to IoHandlerAdapter but that requries the queues and exchange from the ApplicationRegistry which we can't access.
-
- // get right constructor and pass in instancec ID - "port"
- IoHandlerAdapter provider;
- try
- {
- Class[] cnstr = {Integer.class};
- Object[] params = {port};
-
- provider = new MINANetworkDriver();
- ProtocolEngineFactory engineFactory = (ProtocolEngineFactory) Class.forName(protocolProviderClass).getConstructor(cnstr).newInstance(params);
- ((MINANetworkDriver) provider).setProtocolEngineFactory(engineFactory, true);
- // Give the broker a second to create
- _logger.info("Created VMBroker Instance:" + port);
- }
- catch (Exception e)
- {
- _logger.info("Unable to create InVM Qpid.AMQP on port " + port + ". Because: " + e.getCause());
- String because;
- if (e.getCause() == null)
- {
- because = e.toString();
- }
- else
- {
- because = e.getCause().toString();
- }
-
- AMQVMBrokerCreationException amqbce =
- new AMQVMBrokerCreationException(null, port, because + " Stopped InVM Qpid.AMQP creation", e);
- throw amqbce;
- }
-
- return provider;
- }
-
- public static void killAllVMBrokers()
- {
- _logger.info("Killing all VM Brokers");
- synchronized(TransportConnection.class)
- {
- if (_acceptor != null)
- {
- _acceptor.unbindAll();
- }
- synchronized (_inVmPipeAddress)
- {
- _inVmPipeAddress.clear();
- }
- _acceptor = null;
- }
- _currentInstance = -1;
- _currentVMPort = -1;
- }
-
- public static void killVMBroker(int port)
- {
- synchronized (_inVmPipeAddress)
- {
- VmPipeAddress pipe = (VmPipeAddress) _inVmPipeAddress.get(port);
- if (pipe != null)
- {
- _logger.info("Killing VM Broker:" + port);
- _inVmPipeAddress.remove(port);
- // This does need to be sychronized as otherwise mina can hang
- // if a new connection is made
- _acceptor.unbind(pipe);
- }
- }
- }
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/transport/VmPipeTransportConnection.java b/java/client/src/main/java/org/apache/qpid/client/transport/VmPipeTransportConnection.java
deleted file mode 100644
index 87cc2e7a5a..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/transport/VmPipeTransportConnection.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.client.transport;
-
-import java.io.IOException;
-
-import org.apache.mina.common.ConnectFuture;
-import org.apache.mina.transport.vmpipe.QpidVmPipeConnector;
-import org.apache.mina.transport.vmpipe.VmPipeAddress;
-import org.apache.mina.transport.vmpipe.VmPipeConnector;
-import org.apache.qpid.client.protocol.AMQProtocolHandler;
-import org.apache.qpid.jms.BrokerDetails;
-import org.apache.qpid.transport.network.mina.MINANetworkDriver;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class VmPipeTransportConnection implements ITransportConnection
-{
- private static final Logger _logger = LoggerFactory.getLogger(VmPipeTransportConnection.class);
-
- private int _port;
-
- private MINANetworkDriver _networkDriver;
-
- public VmPipeTransportConnection(int port)
- {
- _port = port;
- }
-
- public void connect(AMQProtocolHandler protocolHandler, BrokerDetails brokerDetail) throws IOException
- {
- final VmPipeConnector ioConnector = new QpidVmPipeConnector();
-
- final VmPipeAddress address = new VmPipeAddress(_port);
- _logger.info("Attempting connection to " + address);
- _networkDriver = new MINANetworkDriver(ioConnector, protocolHandler);
- protocolHandler.setNetworkDriver(_networkDriver);
- ConnectFuture future = ioConnector.connect(address, _networkDriver);
- // wait for connection to complete
- future.join();
- // we call getSession which throws an IOException if there has been an error connecting
- future.getSession();
- _networkDriver.setProtocolEngine(protocolHandler);
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/url/URLParser.java b/java/client/src/main/java/org/apache/qpid/client/url/URLParser.java
deleted file mode 100644
index f3f74dd332..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/url/URLParser.java
+++ /dev/null
@@ -1,253 +0,0 @@
-package org.apache.qpid.client.url;
-/*
- *
- * 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 java.net.URI;
-import java.net.URISyntaxException;
-import java.util.StringTokenizer;
-
-import org.apache.qpid.client.AMQBrokerDetails;
-import org.apache.qpid.client.AMQConnectionFactory;
-import org.apache.qpid.client.AMQConnectionURL;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.url.URLHelper;
-import org.apache.qpid.url.URLSyntaxException;
-
-public class URLParser
-{
- private AMQConnectionURL _url;
-
- public URLParser(AMQConnectionURL url)throws URLSyntaxException
- {
- _url = url;
- parseURL(_url.getURL());
- }
-
- private void parseURL(String fullURL) throws URLSyntaxException
- {
- // Connection URL format
- // amqp://[user:pass@][clientid]/virtualhost?brokerlist='tcp://host:port?option=\'value\',option=\'value\';vm://:3/virtualpath?option=\'value\'',failover='method?option=\'value\',option='value''"
- // Options are of course optional except for requiring a single broker in the broker list.
- try
- {
- URI connection = new URI(fullURL);
-
- if ((connection.getScheme() == null) || !(connection.getScheme().equalsIgnoreCase(AMQConnectionURL.AMQ_PROTOCOL)))
- {
- throw new URISyntaxException(fullURL, "Not an AMQP URL");
- }
-
- if ((connection.getHost() == null) || connection.getHost().equals(""))
- {
- String tmp = connection.getAuthority();
- // hack to read a clientid such as "my_clientID"
- if (tmp != null && tmp.indexOf('@') < tmp.length()-1)
- {
- _url.setClientName(tmp.substring(tmp.indexOf('@')+1,tmp.length()));
- }
- else
- {
- String uid = AMQConnectionFactory.getUniqueClientID();
- if (uid == null)
- {
- throw URLHelper.parseError(-1, "Client Name not specified", fullURL);
- }
- else
- {
- _url.setClientName(uid);
- }
- }
-
- }
- else
- {
- _url.setClientName(connection.getHost());
- }
-
- String userInfo = connection.getUserInfo();
-
- if (userInfo == null)
- {
- // Fix for Java 1.5 which doesn't parse UserInfo for non http URIs
- userInfo = connection.getAuthority();
-
- if (userInfo != null)
- {
- int atIndex = userInfo.indexOf('@');
-
- if (atIndex != -1)
- {
- userInfo = userInfo.substring(0, atIndex);
- }
- else
- {
- userInfo = null;
- }
- }
-
- }
-
- if (userInfo == null)
- {
- throw URLHelper.parseError(AMQConnectionURL.AMQ_PROTOCOL.length() + 3, "User information not found on url", fullURL);
- }
- else
- {
- parseUserInfo(userInfo);
- }
-
- String virtualHost = connection.getPath();
-
- if ((virtualHost != null) && (!virtualHost.equals("")))
- {
- _url.setVirtualHost(virtualHost);
- }
- else
- {
- int authLength = connection.getAuthority().length();
- int start = AMQConnectionURL.AMQ_PROTOCOL.length() + 3;
- int testIndex = start + authLength;
- if ((testIndex < fullURL.length()) && (fullURL.charAt(testIndex) == '?'))
- {
- throw URLHelper.parseError(start, testIndex - start, "Virtual host found", fullURL);
- }
- else
- {
- throw URLHelper.parseError(-1, "Virtual host not specified", fullURL);
- }
-
- }
-
- URLHelper.parseOptions(_url.getOptions(), connection.getQuery());
-
- processOptions();
- }
- catch (URISyntaxException uris)
- {
- if (uris instanceof URLSyntaxException)
- {
- throw (URLSyntaxException) uris;
- }
-
- int slash = fullURL.indexOf("\\");
-
- if (slash == -1)
- {
- throw URLHelper.parseError(uris.getIndex(), uris.getReason(), uris.getInput());
- }
- else
- {
- if ((slash != 0) && (fullURL.charAt(slash - 1) == ':'))
- {
- throw URLHelper.parseError(slash - 2, fullURL.indexOf('?') - slash + 2,
- "Virtual host looks like a windows path, forward slash not allowed in URL", fullURL);
- }
- else
- {
- throw URLHelper.parseError(slash, "Forward slash not allowed in URL", fullURL);
- }
- }
-
- }
- }
-
- private void parseUserInfo(String userinfo) throws URLSyntaxException
- {
- // user info = user:pass
-
- int colonIndex = userinfo.indexOf(':');
-
- if (colonIndex == -1)
- {
- throw URLHelper.parseError(AMQConnectionURL.AMQ_PROTOCOL.length() + 3, userinfo.length(),
- "Null password in user information not allowed.", _url.getURL());
- }
- else
- {
- _url.setUsername(userinfo.substring(0, colonIndex));
- _url.setPassword(userinfo.substring(colonIndex + 1));
- }
-
- }
-
- private void processOptions() throws URLSyntaxException
- {
- if (_url.getOptions().containsKey(AMQConnectionURL.OPTIONS_BROKERLIST))
- {
- String brokerlist = _url.getOptions().get(AMQConnectionURL.OPTIONS_BROKERLIST);
-
- // brokerlist tcp://host:port?option='value',option='value';vm://:3/virtualpath?option='value'
- StringTokenizer st = new StringTokenizer(brokerlist, "" + URLHelper.BROKER_SEPARATOR);
-
- while (st.hasMoreTokens())
- {
- String broker = st.nextToken();
-
- _url.addBrokerDetails(new AMQBrokerDetails(broker));
- }
-
- _url.getOptions().remove(AMQConnectionURL.OPTIONS_BROKERLIST);
- }
-
- if (_url.getOptions().containsKey(AMQConnectionURL.OPTIONS_FAILOVER))
- {
- String failover = _url.getOptions().get(AMQConnectionURL.OPTIONS_FAILOVER);
-
- // failover='method?option='value',option='value''
-
- int methodIndex = failover.indexOf('?');
-
- if (methodIndex > -1)
- {
- _url.setFailoverMethod(failover.substring(0, methodIndex));
- URLHelper.parseOptions(_url.getFailoverOptions(), failover.substring(methodIndex + 1));
- }
- else
- {
- _url.setFailoverMethod(failover);
- }
-
- _url.getOptions().remove(AMQConnectionURL.OPTIONS_FAILOVER);
- }
-
- if (_url.getOptions().containsKey(AMQConnectionURL.OPTIONS_DEFAULT_TOPIC_EXCHANGE))
- {
- _url.setDefaultTopicExchangeName(new AMQShortString(_url.getOptions().get(AMQConnectionURL.OPTIONS_DEFAULT_TOPIC_EXCHANGE)));
- }
-
- if (_url.getOptions().containsKey(AMQConnectionURL.OPTIONS_DEFAULT_QUEUE_EXCHANGE))
- {
- _url.setDefaultQueueExchangeName(new AMQShortString(_url.getOptions().get(AMQConnectionURL.OPTIONS_DEFAULT_QUEUE_EXCHANGE)));
- }
-
- if (_url.getOptions().containsKey(AMQConnectionURL.OPTIONS_TEMPORARY_QUEUE_EXCHANGE))
- {
- _url.setTemporaryQueueExchangeName(new AMQShortString(_url.getOptions().get(AMQConnectionURL.OPTIONS_TEMPORARY_QUEUE_EXCHANGE)));
- }
-
- if (_url.getOptions().containsKey(AMQConnectionURL.OPTIONS_TEMPORARY_TOPIC_EXCHANGE))
- {
- _url.setTemporaryTopicExchangeName(new AMQShortString(_url.getOptions().get(AMQConnectionURL.OPTIONS_TEMPORARY_TOPIC_EXCHANGE)));
- }
- }
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/url/URLParser_0_10.java b/java/client/src/main/java/org/apache/qpid/client/url/URLParser_0_10.java
deleted file mode 100644
index 605e9ee154..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/url/URLParser_0_10.java
+++ /dev/null
@@ -1,423 +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.client.url;
-
-import java.net.MalformedURLException;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.qpid.client.AMQBrokerDetails;
-import org.apache.qpid.jms.BrokerDetails;
-
-/**
- * The format Qpid URL is based on the AMQP one.
- * The grammar is as follows:
- * <p> qpid_url = "qpid:" [client_props "@"] port_addr_list ["/" future-parameters]
- * <p> port_addr_list = [port_addr ","]* port_addr
- * <p> port_addr = tcp_port_addr | tls_prot_addr | future_prot_addr
- * <p> tcp_port_addr = tcp_id tcp_addr
- * <p> tcp_id = "tcp:" | ""
- * <p> tcp_addr = host [":" port]
- * <p> host = <as per http://www.apps.ietf.org/>
- * <p> port = number
- * <p> tls_prot_addr = tls_id tls_addr
- * <p> tls_id = "tls:" | ""
- * <p> tls_addr = host [":" port]
- * <p> future_prot_addr = future_prot_id future_prot_addr
- * <p> future_prot_id = <placeholder, must end in ":". Example "sctp:">
- * <p> future_prot_addr = <placeholder, protocl-specific address>
- * <p> future_parameters = <placeholder, not used in failover addresses>
- * <p> client_props = [client_prop ";"]* client_prop
- * <p> client_prop = prop "=" val
- * <p> prop = chars as per <as per http://www.apps.ietf.org/>
- * <p> val = valid as per <as per http://www.apps.ietf.org/>
- * <p/>
- * Ex: qpid:virtualhost=tcp:host-foo,test,client_id=foo@tcp:myhost.com:5672,virtualhost=prod;
- * keystore=/opt/keystore@client_id2@tls:mysecurehost.com:5672
- */
-public class URLParser_0_10
-{
- private static final char[] URL_START_SEQ = new char[]{'q', 'p', 'i', 'd', ':'};
- private static final char PROPERTY_EQUALS_CHAR = '=';
- private static final char PROPERTY_SEPARATOR_CHAR = ';';
- private static final char ADDRESS_SEPERATOR_CHAR = ',';
-
- //private static final char CLIENT_ID_TRANSPORT_SEPARATOR_CHAR = ':';
- private static final char TRANSPORT_HOST_SEPARATOR_CHAR = ':';
- private static final char HOST_PORT_SEPARATOR_CHAR = ':';
- private static final char AT_CHAR = '@';
- private static final char END_OF_URL_MARKER = '^';
-
- enum URLParserState
- {
- QPID_URL_START,
- ADDRESS_START,
- PROPERTY_NAME,
- PROPERTY_EQUALS,
- PROPERTY_VALUE,
- PROPERTY_SEPARATOR,
- AT_CHAR,
- TRANSPORT,
- TRANSPORT_HOST_SEPARATOR,
- HOST,
- HOST_PORT_SEPARATOR,
- PORT,
- ADDRESS_END,
- ADDRESS_SEPERATOR,
- QPID_URL_END,
- ERROR
- }
-
- //-- Constructors
-
- private char[] _url;
- private List<BrokerDetails> _brokerDetailList = new ArrayList<BrokerDetails>();
- private String _error;
- private int _index = 0;
- private BrokerDetails _currentBroker;
- private String _currentPropName;
- private boolean _endOfURL = false;
- private URLParserState _currentParserState;
-
- public URLParser_0_10(String url) throws MalformedURLException
- {
- _url = (url + END_OF_URL_MARKER).toCharArray();
- _endOfURL = false;
- _currentParserState = URLParserState.QPID_URL_START;
- URLParserState prevState = _currentParserState; // for error handling
- try
- {
- while (_currentParserState != URLParserState.ERROR && _currentParserState != URLParserState.QPID_URL_END)
- {
- prevState = _currentParserState;
- _currentParserState = next();
- }
-
- if (_currentParserState == URLParserState.ERROR)
- {
- _error =
- "Invalid URL format [current_state = " + prevState + ", broker details parsed so far " + _currentBroker + " ] error at (" + _index + ") due to " + _error;
- MalformedURLException ex;
- ex = new MalformedURLException(_error);
- throw ex;
- }
- }
- catch (ArrayIndexOutOfBoundsException e)
- {
- _error = "Invalid URL format [current_state = " + prevState + ", broker details parsed so far " + _currentBroker + " ] error at (" + _index + ")";
- MalformedURLException ex = new MalformedURLException(_error);
- throw ex;
- }
- }
-
- //-- interface QpidURL
- public List<BrokerDetails> getAllBrokerDetails()
- {
- return _brokerDetailList;
- }
-
- public String getURL()
- {
- return new String(_url);
- }
-
- private URLParserState next()
- {
- switch (_currentParserState)
- {
- case QPID_URL_START:
- return checkSequence(URL_START_SEQ, URLParserState.ADDRESS_START);
- case ADDRESS_START:
- return startAddress();
- case PROPERTY_NAME:
- return extractPropertyName();
- case PROPERTY_EQUALS:
- _index++; // skip the equal sign
- return URLParserState.PROPERTY_VALUE;
- case PROPERTY_VALUE:
- return extractPropertyValue();
- case PROPERTY_SEPARATOR:
- _index++; // skip ","
- return URLParserState.PROPERTY_NAME;
- case AT_CHAR:
- _index++; // skip the @ sign
- return URLParserState.TRANSPORT;
- case TRANSPORT:
- return extractTransport();
- case TRANSPORT_HOST_SEPARATOR:
- _index++; // skip ":"
- return URLParserState.HOST;
- case HOST:
- return extractHost();
- case HOST_PORT_SEPARATOR:
- _index++; // skip ":"
- return URLParserState.PORT;
- case PORT:
- return extractPort();
- case ADDRESS_END:
- return endAddress();
- case ADDRESS_SEPERATOR:
- _index++; // skip ","
- return URLParserState.ADDRESS_START;
- default:
- return URLParserState.ERROR;
- }
- }
-
- private URLParserState checkSequence(char[] expected, URLParserState nextPart)
- {
- for (char expectedChar : expected)
- {
- if (expectedChar != _url[_index])
- {
- _error = "Excepted (" + expectedChar + ") at position " + _index + ", got (" + _url[_index] + ")";
- return URLParserState.ERROR;
- }
- _index++;
- }
- return nextPart;
- }
-
- private URLParserState startAddress()
- {
- _currentBroker = new AMQBrokerDetails();
-
- for (int j = _index; j < _url.length; j++)
- {
- if (_url[j] == PROPERTY_EQUALS_CHAR)
- {
- return URLParserState.PROPERTY_NAME;
- }
- else if (_url[j] == ADDRESS_SEPERATOR_CHAR)
- {
- return URLParserState.TRANSPORT;
- }
- }
- return URLParserState.TRANSPORT;
- }
-
- private URLParserState endAddress()
- {
- _brokerDetailList.add(_currentBroker);
- if (_endOfURL)
- {
- return URLParserState.QPID_URL_END;
- }
- else
- {
- return URLParserState.ADDRESS_SEPERATOR;
- }
- }
-
- private URLParserState extractPropertyName()
- {
- StringBuilder b = new StringBuilder();
- char next = _url[_index];
- while (next != PROPERTY_EQUALS_CHAR && next != AT_CHAR)
- {
- b.append(next);
- next = _url[++_index];
- }
- _currentPropName = b.toString();
- if (_currentPropName.trim().equals(""))
- {
- _error = "Property name cannot be empty";
- return URLParserState.ERROR;
- }
- else if (next == PROPERTY_EQUALS_CHAR)
- {
- return URLParserState.PROPERTY_EQUALS;
- }
- else
- {
- return URLParserState.AT_CHAR;
- }
- }
-
- private URLParserState extractPropertyValue()
- {
- StringBuilder b = new StringBuilder();
- char next = _url[_index];
- while (next != PROPERTY_SEPARATOR_CHAR && next != AT_CHAR)
- {
- b.append(next);
- next = _url[++_index];
- }
- String propValue = b.toString();
- if (propValue.trim().equals(""))
- {
- _error = "Property values cannot be empty";
- return URLParserState.ERROR;
- }
- else
- {
- _currentBroker.setProperty(_currentPropName, propValue);
- if (next == PROPERTY_SEPARATOR_CHAR)
- {
- return URLParserState.PROPERTY_SEPARATOR;
- }
- else
- {
- return URLParserState.AT_CHAR;
- }
- }
- }
-
- private URLParserState extractTransport()
- {
- String transport = buildUntil(TRANSPORT_HOST_SEPARATOR_CHAR);
- if (transport.trim().equals(""))
- {
- _error = "Transport cannot be empty";
- return URLParserState.ERROR;
- }
- else if (!(transport.trim().equals(BrokerDetails.PROTOCOL_TCP) || transport.trim()
- .equals(BrokerDetails.PROTOCOL_TLS)))
- {
- _error = "Transport cannot be " + transport + " value must be tcp or tls";
- return URLParserState.ERROR;
- }
- else
- {
- _currentBroker.setTransport(transport);
- return URLParserState.TRANSPORT_HOST_SEPARATOR;
- }
- }
-
- private URLParserState extractHost()
- {
- char nextSep = 'c';
- String host;
- URLParserState nextState;
-
- for (int i = _index; i < _url.length; i++)
- {
- if (_url[i] == HOST_PORT_SEPARATOR_CHAR)
- {
- nextSep = HOST_PORT_SEPARATOR_CHAR;
- break;
- }
- else if (_url[i] == ADDRESS_SEPERATOR_CHAR)
- {
- nextSep = ADDRESS_SEPERATOR_CHAR;
- break;
- }
- }
-
- if (nextSep == HOST_PORT_SEPARATOR_CHAR)
- {
- host = buildUntil(HOST_PORT_SEPARATOR_CHAR);
- nextState = URLParserState.HOST_PORT_SEPARATOR;
- }
- else if (nextSep == ADDRESS_SEPERATOR_CHAR)
- {
- host = buildUntil(ADDRESS_SEPERATOR_CHAR);
- nextState = URLParserState.ADDRESS_END;
- }
- else
- {
- host = buildUntil(END_OF_URL_MARKER);
- nextState = URLParserState.ADDRESS_END;
- _endOfURL = true;
- }
-
- if (host.trim().equals(""))
- {
- _error = "Host cannot be empty";
- return URLParserState.ERROR;
- }
- else
- {
- _currentBroker.setHost(host);
- return nextState;
- }
- }
-
-
- private URLParserState extractPort()
- {
-
- StringBuilder b = new StringBuilder();
- try
- {
- char next = _url[_index];
- while (next != ADDRESS_SEPERATOR_CHAR && next != END_OF_URL_MARKER )
- {
- b.append(next);
- next = _url[++_index];
- }
- }
- catch (ArrayIndexOutOfBoundsException e)
- {
- _endOfURL = true;
- }
- String portStr = b.toString();
- if (portStr.trim().equals(""))
- {
- _error = "Host cannot be empty";
- return URLParserState.ERROR;
- }
- else
- {
- try
- {
- int port = Integer.parseInt(portStr);
- _currentBroker.setPort(port);
- if( _url[_index] == END_OF_URL_MARKER )
- {
- _endOfURL = true;
- }
- return URLParserState.ADDRESS_END;
- }
- catch (NumberFormatException e)
- {
- _error = "Illegal number for port";
- return URLParserState.ERROR;
- }
- }
- }
-
- private String buildUntil(char c)
- {
- StringBuilder b = new StringBuilder();
- char next = _url[_index];
- while (next != c)
- {
- b.append(next);
- next = _url[++_index];
- }
- return b.toString();
- }
-
- public static void main(String[] args)
- {
- String testurl = "qpid:password=pass;username=name@tcp:test1";
- try
- {
- URLParser_0_10 impl = new URLParser_0_10(testurl);
- for (BrokerDetails d : impl.getAllBrokerDetails())
- {
- System.out.println(d);
- }
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/util/BlockingWaiter.java b/java/client/src/main/java/org/apache/qpid/client/util/BlockingWaiter.java
deleted file mode 100644
index 208658a5ff..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/util/BlockingWaiter.java
+++ /dev/null
@@ -1,348 +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.client.util;
-
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.locks.Condition;
-import java.util.concurrent.locks.ReentrantLock;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.AMQTimeoutException;
-import org.apache.qpid.client.failover.FailoverException;
-import org.apache.qpid.framing.AMQMethodBody;
-import org.apache.qpid.protocol.AMQMethodEvent;
-import org.apache.qpid.protocol.AMQMethodListener;
-
-/**
- * BlockingWaiter is a 'rendezvous' which delegates handling of
- * incoming Objects to a listener implemented as a sub-class of this and hands off the process or
- * error to a consumer. The producer of the event does not have to wait for the consumer to take the event, so this
- * differs from a 'rendezvous' in that sense.
- *
- * <p/>BlockingWaiters are used to coordinate when waiting for an an event that expect a response.
- * They are always used in a 'one-shot' manner, that is, to recieve just one response. Usually the caller has to register
- * them as method listeners with an event dispatcher and remember to de-register them (in a finally block) once they
- * have been completed.
- *
- * <p/>The {@link #process} must return <tt>true</tt> on any incoming method that it handles. This indicates to
- * this listeners that the object just processed ends the waiting process.
- *
- * <p/>Errors from the producer are rethrown to the consumer.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations </td>
- * <tr><td> Accept generic objects as events for processing via {@link #process}. <td>
- * <tr><td> Delegate handling and undserstanding of the object to a concrete implementation. <td>
- * <tr><td> Block until {@link #process} determines that waiting is no longer required <td>
- * <tr><td> Propagate the most recent exception to the consumer.<td>
- * </table>
- *
- * @todo Interuption is caught but not handled. This could be allowed to fall through. This might actually be usefull
- * for fail-over where a thread is blocking when failure happens, it could be interrupted to abandon or retry
- * when this happens. At the very least, restore the interrupted status flag.
- * @todo If the retrotranslator can handle it, could use a SynchronousQueue to implement this rendezvous. Need to
- * check that SynchronousQueue has a non-blocking put method available.
- */
-public abstract class BlockingWaiter<T>
-{
- /** This flag is used to indicate that the blocked for method has been received. */
- private volatile boolean _ready = false;
-
- /** This flag is used to indicate that the received error has been processed. */
- private volatile boolean _errorAck = false;
-
- /** Used to protect the shared event and ready flag between the producer and consumer. */
- private final ReentrantLock _lock = new ReentrantLock();
-
- /** Used to signal that a method has been received */
- private final Condition _receivedCondition = _lock.newCondition();
-
- /** Used to signal that a error has been processed */
- private final Condition _errorConditionAck = _lock.newCondition();
-
- /** Used to hold the most recent exception that is passed to the {@link #error(Exception)} method. */
- private volatile Exception _error;
-
- /** Holds the incomming Object. */
- protected Object _doneObject = null;
- private AtomicBoolean _waiting = new AtomicBoolean(false);
- private boolean _closed = false;
-
- /**
- * Delegates processing of the incomming object to the handler.
- *
- * @param object The object to process.
- *
- * @return <tt>true</tt> if the waiting is complete, <tt>false</tt> if waiting should continue.
- */
- public abstract boolean process(T object);
-
- /**
- * An Object has been received and should be processed to see if our wait condition has been reached.
- *
- * @param object The object received.
- *
- * @return <tt>true</tt> if the waiting is complete, <tt>false</tt> if waiting should continue.
- */
- public boolean received(T object)
- {
-
- boolean ready = process(object);
-
- if (ready)
- {
- // we only update the flag from inside the synchronized block
- // so that the blockForFrame method cannot "miss" an update - it
- // will only ever read the flag from within the synchronized block
- _lock.lock();
- try
- {
- _doneObject = object;
- _ready = ready;
- _receivedCondition.signal();
- }
- finally
- {
- _lock.unlock();
- }
- }
-
- return ready;
- }
-
- /**
- * Blocks until an object is received that is handled by process, or the specified timeout
- * has passed.
- *
- * Once closed any attempt to wait will throw an exception.
- *
- * @param timeout The timeout in milliseconds.
- *
- * @return The object that resolved the blocking.
- *
- * @throws AMQException
- * @throws FailoverException
- */
- public Object block(long timeout) throws AMQException, FailoverException
- {
- long nanoTimeout = TimeUnit.MILLISECONDS.toNanos(timeout);
-
- _lock.lock();
-
- try
- {
- if (_closed)
- {
- throw throwClosedException();
- }
-
- if (_error == null)
- {
- _waiting.set(true);
-
- while (!_ready)
- {
- try
- {
- if (timeout == -1)
- {
- _receivedCondition.await();
- }
- else
- {
- nanoTimeout = _receivedCondition.awaitNanos(nanoTimeout);
-
- if (nanoTimeout <= 0 && !_ready && _error == null)
- {
- _error = new AMQTimeoutException("Server did not respond in a timely fashion", null);
- _ready = true;
- }
- }
- }
- catch (InterruptedException e)
- {
- System.err.println(e.getMessage());
- // IGNORE -- //fixme this isn't ideal as being interrupted isn't equivellant to sucess
- // if (!_ready && timeout != -1)
- // {
- // _error = new AMQException("Server did not respond timely");
- // _ready = true;
- // }
- }
- }
- }
-
- if (_error != null)
- {
- if (_error instanceof AMQException)
- {
- throw (AMQException) _error;
- }
- else if (_error instanceof FailoverException)
- {
- // This should ensure that FailoverException is not wrapped and can be caught.
- throw (FailoverException) _error; // needed to expose FailoverException.
- }
- else
- {
- throw new AMQException("Woken up due to " + _error.getClass(), _error);
- }
- }
-
- }
- finally
- {
- _waiting.set(false);
-
- //Release Error handling thread
- if (_error != null)
- {
- _errorAck = true;
- _errorConditionAck.signal();
-
- _error = null;
- }
- _lock.unlock();
- }
-
- return _doneObject;
- }
-
- /**
- * This is a callback, called when an error has occured that should interupt any waiter.
- * It is also called from within this class to avoid code repetition but it should only be called by the MINA threads.
- *
- * Once closed any notification of an exception will be ignored.
- *
- * @param e The exception being propogated.
- */
- public void error(Exception e)
- {
- // set the error so that the thread that is blocking (against blockForFrame())
- // can pick up the exception and rethrow to the caller
-
- _lock.lock();
-
- try
- {
- if (_closed)
- {
- return;
- }
-
- if (_error == null)
- {
- _error = e;
- }
- else
- {
- System.err.println("WARNING: new error '" + e == null ? "null" : e.getMessage() + "' arrived while old one not yet processed:" + _error.getMessage());
- }
-
- if (_waiting.get())
- {
-
- _ready = true;
- _receivedCondition.signal();
-
- while (!_errorAck)
- {
- try
- {
- _errorConditionAck.await();
- }
- catch (InterruptedException e1)
- {
- System.err.println(e.getMessage());
- }
- }
- _errorAck = false;
- }
- }
- finally
- {
- _lock.unlock();
- }
- }
-
- /**
- * Close this Waiter so that no more errors are processed.
- * This is a preventative method to ensure that a second error thread does not get stuck in the error method after
- * the await has returned. This has not happend but in practise but if two errors occur on the Connection at
- * the same time then it is conceiveably possible for the second to get stuck if the first one is processed by a
- * waiter.
- *
- * Once closed any attempt to wait will throw an exception.
- * Any notification of an exception will be ignored.
- */
- public void close()
- {
- _lock.lock();
- try
- {
- //if we have already closed then our job is done.
- if (_closed)
- {
- return;
- }
-
- //Close Waiter so no more exceptions are processed
- _closed = true;
-
- //Wake up any await() threads
-
- //If we are waiting then use the error() to wake them up.
- if (_waiting.get())
- {
- error(throwClosedException());
- }
- //If they are not waiting then there is nothing to do.
-
- // Wake up any error handling threads
-
- if (!_errorAck)
- {
- _errorAck = true;
- _errorConditionAck.signal();
-
- _error = null;
- }
- }
- finally
- {
- _lock.unlock();
- }
- }
-
- /**
- * Helper method to generate the a closed Exception.
- *
- * todo: This should be converted to something more friendly.
- *
- * @return AMQException to throw to waiters when the Waiter is closed.
- */
- private AMQException throwClosedException()
- {
- return new AMQException(null, "Waiter was closed.", null);
- }
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/util/FlowControllingBlockingQueue.java b/java/client/src/main/java/org/apache/qpid/client/util/FlowControllingBlockingQueue.java
deleted file mode 100644
index ee7fc533a3..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/util/FlowControllingBlockingQueue.java
+++ /dev/null
@@ -1,135 +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.client.util;
-
-import java.util.Iterator;
-import java.util.Queue;
-import java.util.concurrent.ConcurrentLinkedQueue;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * A blocking queue that emits events above a user specified threshold allowing the caller to take action (e.g. flow
- * control) to try to prevent the queue growing (much) further. The underlying queue itself is not bounded therefore the
- * caller is not obliged to react to the events. <p/> This implementation is <b>only</b> safe where we have a single
- * thread adding items and a single (different) thread removing items.
- *
- * @todo Make this implement java.util.Queue and hide the implementation. Then different queue types can be substituted.
- */
-public class FlowControllingBlockingQueue
-{
- private static final Logger _logger = LoggerFactory.getLogger(FlowControllingBlockingQueue.class);
-
- /** This queue is bounded and is used to store messages before being dispatched to the consumer */
- private final Queue _queue = new ConcurrentLinkedQueue();
-
- private final int _flowControlHighThreshold;
- private final int _flowControlLowThreshold;
-
- private final ThresholdListener _listener;
-
- /** We require a separate count so we can track whether we have reached the threshold */
- private int _count;
-
- private boolean disableFlowControl;
-
- public boolean isEmpty()
- {
- return _queue.isEmpty();
- }
-
- public interface ThresholdListener
- {
- void aboveThreshold(int currentValue);
-
- void underThreshold(int currentValue);
- }
-
- public FlowControllingBlockingQueue(int threshold, ThresholdListener listener)
- {
- this(threshold, threshold, listener);
- }
-
- public FlowControllingBlockingQueue(int highThreshold, int lowThreshold, ThresholdListener listener)
- {
- _flowControlHighThreshold = highThreshold;
- _flowControlLowThreshold = lowThreshold;
- _listener = listener;
- if (highThreshold == 0)
- {
- disableFlowControl = true;
- }
- }
-
- public Object take() throws InterruptedException
- {
- Object o = _queue.poll();
- if(o == null)
- {
- synchronized(this)
- {
- while((o = _queue.poll())==null)
- {
- wait();
- }
- }
- }
- if (!disableFlowControl && _listener != null)
- {
- synchronized (_listener)
- {
- if (_count-- == _flowControlLowThreshold)
- {
- _listener.underThreshold(_count);
- }
- }
-
- }
-
- return o;
- }
-
- public void add(Object o)
- {
- synchronized(this)
- {
- _queue.add(o);
-
- notifyAll();
- }
- if (!disableFlowControl && _listener != null)
- {
- synchronized (_listener)
- {
- if (++_count == _flowControlHighThreshold)
- {
- _listener.aboveThreshold(_count);
- }
- }
- }
- }
-
- public Iterator iterator()
- {
- return _queue.iterator();
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/client/vmbroker/AMQVMBrokerCreationException.java b/java/client/src/main/java/org/apache/qpid/client/vmbroker/AMQVMBrokerCreationException.java
deleted file mode 100644
index dc0d9b8c78..0000000000
--- a/java/client/src/main/java/org/apache/qpid/client/vmbroker/AMQVMBrokerCreationException.java
+++ /dev/null
@@ -1,60 +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.client.vmbroker;
-
-import org.apache.qpid.client.transport.AMQTransportConnectionException;
-import org.apache.qpid.protocol.AMQConstant;
-
-/**
- * AMQVMBrokerCreationException represents failure to create an in VM broker on the vm transport medium.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Represent failure to create an in VM broker.
- * </table>
- *
- * @todo Error code never used. This is not an AMQException.
- */
-public class AMQVMBrokerCreationException extends AMQTransportConnectionException
-{
- private int _port;
-
- /**
- * @param port
- *
- * @deprecated
- */
- public AMQVMBrokerCreationException(int port)
- {
- this(null, port, "Unable to create vm broker", null);
- }
-
- public AMQVMBrokerCreationException(AMQConstant errorCode, int port, String message, Throwable cause)
- {
- super(errorCode, message, cause);
- _port = port;
- }
-
- public String toString()
- {
- return super.toString() + " on port " + _port;
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/collections/KeyValue.java b/java/client/src/main/java/org/apache/qpid/collections/KeyValue.java
deleted file mode 100644
index e890aba968..0000000000
--- a/java/client/src/main/java/org/apache/qpid/collections/KeyValue.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright 2003-2004 The Apache Software Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.qpid.collections;
-
-/**
- * Defines a simple key value pair.
- * <p>
- * A Map Entry has considerable additional semantics over and above a simple
- * key-value pair. This interface defines the minimum key value, with just the
- * two get methods.
- *
- * @since Commons Collections 3.0
- * @version $Revision$ $Date$
- *
- * @author Stephen Colebourne
- */
-public interface KeyValue {
-
- /**
- * Gets the key from the pair.
- *
- * @return the key
- */
- Object getKey();
-
- /**
- * Gets the value from the pair.
- *
- * @return the value
- */
- Object getValue();
-
-} \ No newline at end of file
diff --git a/java/client/src/main/java/org/apache/qpid/collections/ReferenceMap.java b/java/client/src/main/java/org/apache/qpid/collections/ReferenceMap.java
deleted file mode 100644
index 1516c56e42..0000000000
--- a/java/client/src/main/java/org/apache/qpid/collections/ReferenceMap.java
+++ /dev/null
@@ -1,957 +0,0 @@
-/*
- * Copyright 2001-2004 The Apache Software Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.qpid.collections;
-
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.lang.ref.Reference;
-import java.lang.ref.ReferenceQueue;
-import java.lang.ref.SoftReference;
-import java.lang.ref.WeakReference;
-import java.util.AbstractCollection;
-import java.util.AbstractMap;
-import java.util.AbstractSet;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.ConcurrentModificationException;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.NoSuchElementException;
-import java.util.Set;
-
-import org.apache.qpid.collections.keyvalue.DefaultMapEntry;
-
-/**
- * Hash-based {@link Map} implementation that allows
- * mappings to be removed by the garbage collector.<p>
- *
- * When you construct a <code>ReferenceMap</code>, you can
- * specify what kind of references are used to store the
- * map's keys and values. If non-hard references are
- * used, then the garbage collector can remove mappings
- * if a key or value becomes unreachable, or if the
- * JVM's memory is running low. For information on how
- * the different reference types behave, see
- * {@link Reference}.<p>
- *
- * Different types of references can be specified for keys
- * and values. The keys can be configured to be weak but
- * the values hard, in which case this class will behave
- * like a <a href="http://java.sun.com/j2se/1.4/docs/api/java/util/WeakHashMap.html">
- * <code>WeakHashMap</code></a>. However, you
- * can also specify hard keys and weak values, or any other
- * combination. The default constructor uses hard keys
- * and soft values, providing a memory-sensitive cache.<p>
- *
- * The algorithms used are basically the same as those
- * in {@link java.util.HashMap}. In particular, you
- * can specify a load factor and capacity to suit your
- * needs. All optional {@link Map} operations are
- * supported.<p>
- *
- * However, this {@link Map} implementation does <I>not</I>
- * allow null elements. Attempting to add a null key or
- * or a null value to the map will raise a
- * <code>NullPointerException</code>.<p>
- *
- * As usual, this implementation is not synchronized. You
- * can use {@link java.util.Collections#synchronizedMap} to
- * provide synchronized access to a <code>ReferenceMap</code>.
- *
- * @see java.lang.ref.Reference
- *
- * @deprecated Moved to map subpackage. Due to be removed in v4.0.
- * @since Commons Collections 2.1
- * @version $Revision$ $Date$
- *
- * @author Paul Jack
- */
-public class ReferenceMap extends AbstractMap {
-
- /**
- * For serialization.
- */
- private static final long serialVersionUID = -3370601314380922368L;
-
-
- /**
- * Constant indicating that hard references should be used.
- */
- final public static int HARD = 0;
-
-
- /**
- * Constant indicating that soft references should be used.
- */
- final public static int SOFT = 1;
-
-
- /**
- * Constant indicating that weak references should be used.
- */
- final public static int WEAK = 2;
-
-
- // --- serialized instance variables:
-
-
- /**
- * The reference type for keys. Must be HARD, SOFT, WEAK.
- * Note: I originally marked this field as final, but then this class
- * didn't compile under JDK1.2.2.
- * @serial
- */
- private int keyType;
-
-
- /**
- * The reference type for values. Must be HARD, SOFT, WEAK.
- * Note: I originally marked this field as final, but then this class
- * didn't compile under JDK1.2.2.
- * @serial
- */
- private int valueType;
-
-
- /**
- * The threshold variable is calculated by multiplying
- * table.length and loadFactor.
- * Note: I originally marked this field as final, but then this class
- * didn't compile under JDK1.2.2.
- * @serial
- */
- private float loadFactor;
-
- /**
- * Should the value be automatically purged when the associated key has been collected?
- */
- private boolean purgeValues = false;
-
-
- // -- Non-serialized instance variables
-
- /**
- * ReferenceQueue used to eliminate stale mappings.
- * See purge.
- */
- private transient ReferenceQueue queue = new ReferenceQueue();
-
-
- /**
- * The hash table. Its length is always a power of two.
- */
- private transient Entry[] table;
-
-
- /**
- * Number of mappings in this map.
- */
- private transient int size;
-
-
- /**
- * When size reaches threshold, the map is resized.
- * See resize().
- */
- private transient int threshold;
-
-
- /**
- * Number of times this map has been modified.
- */
- private transient volatile int modCount;
-
-
- /**
- * Cached key set. May be null if key set is never accessed.
- */
- private transient Set keySet;
-
-
- /**
- * Cached entry set. May be null if entry set is never accessed.
- */
- private transient Set entrySet;
-
-
- /**
- * Cached values. May be null if values() is never accessed.
- */
- private transient Collection values;
-
-
- /**
- * Constructs a new <code>ReferenceMap</code> that will
- * use hard references to keys and soft references to values.
- */
- public ReferenceMap() {
- this(HARD, SOFT);
- }
-
- /**
- * Constructs a new <code>ReferenceMap</code> that will
- * use the specified types of references.
- *
- * @param keyType the type of reference to use for keys;
- * must be {@link #HARD}, {@link #SOFT}, {@link #WEAK}
- * @param valueType the type of reference to use for values;
- * must be {@link #HARD}, {@link #SOFT}, {@link #WEAK}
- * @param purgeValues should the value be automatically purged when the
- * key is garbage collected
- */
- public ReferenceMap(int keyType, int valueType, boolean purgeValues) {
- this(keyType, valueType);
- this.purgeValues = purgeValues;
- }
-
- /**
- * Constructs a new <code>ReferenceMap</code> that will
- * use the specified types of references.
- *
- * @param keyType the type of reference to use for keys;
- * must be {@link #HARD}, {@link #SOFT}, {@link #WEAK}
- * @param valueType the type of reference to use for values;
- * must be {@link #HARD}, {@link #SOFT}, {@link #WEAK}
- */
- public ReferenceMap(int keyType, int valueType) {
- this(keyType, valueType, 16, 0.75f);
- }
-
- /**
- * Constructs a new <code>ReferenceMap</code> with the
- * specified reference types, load factor and initial
- * capacity.
- *
- * @param keyType the type of reference to use for keys;
- * must be {@link #HARD}, {@link #SOFT}, {@link #WEAK}
- * @param valueType the type of reference to use for values;
- * must be {@link #HARD}, {@link #SOFT}, {@link #WEAK}
- * @param capacity the initial capacity for the map
- * @param loadFactor the load factor for the map
- * @param purgeValues should the value be automatically purged when the
- * key is garbage collected
- */
- public ReferenceMap(
- int keyType,
- int valueType,
- int capacity,
- float loadFactor,
- boolean purgeValues) {
- this(keyType, valueType, capacity, loadFactor);
- this.purgeValues = purgeValues;
- }
-
- /**
- * Constructs a new <code>ReferenceMap</code> with the
- * specified reference types, load factor and initial
- * capacity.
- *
- * @param keyType the type of reference to use for keys;
- * must be {@link #HARD}, {@link #SOFT}, {@link #WEAK}
- * @param valueType the type of reference to use for values;
- * must be {@link #HARD}, {@link #SOFT}, {@link #WEAK}
- * @param capacity the initial capacity for the map
- * @param loadFactor the load factor for the map
- */
- public ReferenceMap(int keyType, int valueType, int capacity, float loadFactor) {
- super();
-
- verify("keyType", keyType);
- verify("valueType", valueType);
-
- if (capacity <= 0) {
- throw new IllegalArgumentException("capacity must be positive");
- }
- if ((loadFactor <= 0.0f) || (loadFactor >= 1.0f)) {
- throw new IllegalArgumentException("Load factor must be greater than 0 and less than 1.");
- }
-
- this.keyType = keyType;
- this.valueType = valueType;
-
- int v = 1;
- while (v < capacity) v *= 2;
-
- this.table = new Entry[v];
- this.loadFactor = loadFactor;
- this.threshold = (int)(v * loadFactor);
- }
-
-
- // used by constructor
- private static void verify(String name, int type) {
- if ((type < HARD) || (type > WEAK)) {
- throw new IllegalArgumentException(name +
- " must be HARD, SOFT, WEAK.");
- }
- }
-
-
- /**
- * Writes this object to the given output stream.
- *
- * @param out the output stream to write to
- * @throws IOException if the stream raises it
- */
- private void writeObject(ObjectOutputStream out) throws IOException {
- out.defaultWriteObject();
- out.writeInt(table.length);
-
- // Have to use null-terminated list because size might shrink
- // during iteration
-
- for (Iterator iter = entrySet().iterator(); iter.hasNext();) {
- Map.Entry entry = (Map.Entry)iter.next();
- out.writeObject(entry.getKey());
- out.writeObject(entry.getValue());
- }
- out.writeObject(null);
- }
-
-
- /**
- * Reads the contents of this object from the given input stream.
- *
- * @param inp the input stream to read from
- * @throws IOException if the stream raises it
- * @throws ClassNotFoundException if the stream raises it
- */
- private void readObject(ObjectInputStream inp) throws IOException, ClassNotFoundException {
- inp.defaultReadObject();
- table = new Entry[inp.readInt()];
- threshold = (int)(table.length * loadFactor);
- queue = new ReferenceQueue();
- Object key = inp.readObject();
- while (key != null) {
- Object value = inp.readObject();
- put(key, value);
- key = inp.readObject();
- }
- }
-
-
- /**
- * Constructs a reference of the given type to the given
- * referent. The reference is registered with the queue
- * for later purging.
- *
- * @param type HARD, SOFT or WEAK
- * @param referent the object to refer to
- * @param hash the hash code of the <I>key</I> of the mapping;
- * this number might be different from referent.hashCode() if
- * the referent represents a value and not a key
- */
- private Object toReference(int type, Object referent, int hash) {
- switch (type) {
- case HARD: return referent;
- case SOFT: return new SoftRef(hash, referent, queue);
- case WEAK: return new WeakRef(hash, referent, queue);
- default: throw new Error();
- }
- }
-
-
- /**
- * Returns the entry associated with the given key.
- *
- * @param key the key of the entry to look up
- * @return the entry associated with that key, or null
- * if the key is not in this map
- */
- private Entry getEntry(Object key) {
- if (key == null) return null;
- int hash = key.hashCode();
- int index = indexFor(hash);
- for (Entry entry = table[index]; entry != null; entry = entry.next) {
- if ((entry.hash == hash) && key.equals(entry.getKey())) {
- return entry;
- }
- }
- return null;
- }
-
-
- /**
- * Converts the given hash code into an index into the
- * hash table.
- */
- private int indexFor(int hash) {
- // mix the bits to avoid bucket collisions...
- hash += ~(hash << 15);
- hash ^= (hash >>> 10);
- hash += (hash << 3);
- hash ^= (hash >>> 6);
- hash += ~(hash << 11);
- hash ^= (hash >>> 16);
- return hash & (table.length - 1);
- }
-
-
-
- /**
- * Resizes this hash table by doubling its capacity.
- * This is an expensive operation, as entries must
- * be copied from the old smaller table to the new
- * bigger table.
- */
- private void resize() {
- Entry[] old = table;
- table = new Entry[old.length * 2];
-
- for (int i = 0; i < old.length; i++) {
- Entry next = old[i];
- while (next != null) {
- Entry entry = next;
- next = next.next;
- int index = indexFor(entry.hash);
- entry.next = table[index];
- table[index] = entry;
- }
- old[i] = null;
- }
- threshold = (int)(table.length * loadFactor);
- }
-
-
-
- /**
- * Purges stale mappings from this map.
- * <p>
- * Ordinarily, stale mappings are only removed during
- * a write operation, although this method is called for both
- * read and write operations to maintain a consistent state.
- * <p>
- * Note that this method is not synchronized! Special
- * care must be taken if, for instance, you want stale
- * mappings to be removed on a periodic basis by some
- * background thread.
- */
- private void purge() {
- Reference ref = queue.poll();
- while (ref != null) {
- purge(ref);
- ref = queue.poll();
- }
- }
-
-
- private void purge(Reference ref) {
- // The hashCode of the reference is the hashCode of the
- // mapping key, even if the reference refers to the
- // mapping value...
- int hash = ref.hashCode();
- int index = indexFor(hash);
- Entry previous = null;
- Entry entry = table[index];
- while (entry != null) {
- if (entry.purge(ref)) {
- if (previous == null) table[index] = entry.next;
- else previous.next = entry.next;
- this.size--;
- return;
- }
- previous = entry;
- entry = entry.next;
- }
-
- }
-
-
- /**
- * Returns the size of this map.
- *
- * @return the size of this map
- */
- public int size() {
- purge();
- return size;
- }
-
-
- /**
- * Returns <code>true</code> if this map is empty.
- *
- * @return <code>true</code> if this map is empty
- */
- public boolean isEmpty() {
- purge();
- return size == 0;
- }
-
-
- /**
- * Returns <code>true</code> if this map contains the given key.
- *
- * @return true if the given key is in this map
- */
- public boolean containsKey(Object key) {
- purge();
- Entry entry = getEntry(key);
- if (entry == null) return false;
- return entry.getValue() != null;
- }
-
-
- /**
- * Returns the value associated with the given key, if any.
- *
- * @return the value associated with the given key, or <code>null</code>
- * if the key maps to no value
- */
- public Object get(Object key) {
- purge();
- Entry entry = getEntry(key);
- if (entry == null) return null;
- return entry.getValue();
- }
-
-
- /**
- * Associates the given key with the given value.<p>
- * Neither the key nor the value may be null.
- *
- * @param key the key of the mapping
- * @param value the value of the mapping
- * @return the last value associated with that key, or
- * null if no value was associated with the key
- * @throws NullPointerException if either the key or value
- * is null
- */
- public Object put(Object key, Object value) {
- if (key == null) throw new NullPointerException("null keys not allowed");
- if (value == null) throw new NullPointerException("null values not allowed");
-
- purge();
- if (size + 1 > threshold) resize();
-
- int hash = key.hashCode();
- int index = indexFor(hash);
- Entry entry = table[index];
- while (entry != null) {
- if ((hash == entry.hash) && key.equals(entry.getKey())) {
- Object result = entry.getValue();
- entry.setValue(value);
- return result;
- }
- entry = entry.next;
- }
- this.size++;
- modCount++;
- key = toReference(keyType, key, hash);
- value = toReference(valueType, value, hash);
- table[index] = new Entry(key, hash, value, table[index]);
- return null;
- }
-
-
- /**
- * Removes the key and its associated value from this map.
- *
- * @param key the key to remove
- * @return the value associated with that key, or null if
- * the key was not in the map
- */
- public Object remove(Object key) {
- if (key == null) return null;
- purge();
- int hash = key.hashCode();
- int index = indexFor(hash);
- Entry previous = null;
- Entry entry = table[index];
- while (entry != null) {
- if ((hash == entry.hash) && key.equals(entry.getKey())) {
- if (previous == null) table[index] = entry.next;
- else previous.next = entry.next;
- this.size--;
- modCount++;
- return entry.getValue();
- }
- previous = entry;
- entry = entry.next;
- }
- return null;
- }
-
-
- /**
- * Clears this map.
- */
- public void clear() {
- Arrays.fill(table, null);
- size = 0;
- while (queue.poll() != null); // drain the queue
- }
-
-
- /**
- * Returns a set view of this map's entries.
- *
- * @return a set view of this map's entries
- */
- public Set entrySet() {
- if (entrySet != null) {
- return entrySet;
- }
- entrySet = new AbstractSet() {
- public int size() {
- return ReferenceMap.this.size();
- }
-
- public void clear() {
- ReferenceMap.this.clear();
- }
-
- public boolean contains(Object o) {
- if (o == null) return false;
- if (!(o instanceof Map.Entry)) return false;
- Map.Entry e = (Map.Entry)o;
- Entry e2 = getEntry(e.getKey());
- return (e2 != null) && e.equals(e2);
- }
-
- public boolean remove(Object o) {
- boolean r = contains(o);
- if (r) {
- Map.Entry e = (Map.Entry)o;
- ReferenceMap.this.remove(e.getKey());
- }
- return r;
- }
-
- public Iterator iterator() {
- return new EntryIterator();
- }
-
- public Object[] toArray() {
- return toArray(new Object[0]);
- }
-
- public Object[] toArray(Object[] arr) {
- ArrayList list = new ArrayList();
- Iterator iterator = iterator();
- while (iterator.hasNext()) {
- Entry e = (Entry)iterator.next();
- list.add(new DefaultMapEntry(e.getKey(), e.getValue()));
- }
- return list.toArray(arr);
- }
- };
- return entrySet;
- }
-
-
- /**
- * Returns a set view of this map's keys.
- *
- * @return a set view of this map's keys
- */
- public Set keySet() {
- if (keySet != null) return keySet;
- keySet = new AbstractSet() {
- public int size() {
- return ReferenceMap.this.size();
- }
-
- public Iterator iterator() {
- return new KeyIterator();
- }
-
- public boolean contains(Object o) {
- return containsKey(o);
- }
-
-
- public boolean remove(Object o) {
- Object r = ReferenceMap.this.remove(o);
- return r != null;
- }
-
- public void clear() {
- ReferenceMap.this.clear();
- }
-
- public Object[] toArray() {
- return toArray(new Object[0]);
- }
-
- public Object[] toArray(Object[] array) {
- Collection c = new ArrayList(size());
- for (Iterator it = iterator(); it.hasNext(); ) {
- c.add(it.next());
- }
- return c.toArray(array);
- }
- };
- return keySet;
- }
-
-
- /**
- * Returns a collection view of this map's values.
- *
- * @return a collection view of this map's values.
- */
- public Collection values() {
- if (values != null) return values;
- values = new AbstractCollection() {
- public int size() {
- return ReferenceMap.this.size();
- }
-
- public void clear() {
- ReferenceMap.this.clear();
- }
-
- public Iterator iterator() {
- return new ValueIterator();
- }
-
- public Object[] toArray() {
- return toArray(new Object[0]);
- }
-
- public Object[] toArray(Object[] array) {
- Collection c = new ArrayList(size());
- for (Iterator it = iterator(); it.hasNext(); ) {
- c.add(it.next());
- }
- return c.toArray(array);
- }
- };
- return values;
- }
-
-
- // If getKey() or getValue() returns null, it means
- // the mapping is stale and should be removed.
- private class Entry implements Map.Entry, KeyValue {
-
- Object key;
- Object value;
- int hash;
- Entry next;
-
-
- public Entry(Object key, int hash, Object value, Entry next) {
- this.key = key;
- this.hash = hash;
- this.value = value;
- this.next = next;
- }
-
-
- public Object getKey() {
- return (keyType > HARD) ? ((Reference)key).get() : key;
- }
-
-
- public Object getValue() {
- return (valueType > HARD) ? ((Reference)value).get() : value;
- }
-
-
- public Object setValue(Object object) {
- Object old = getValue();
- if (valueType > HARD) ((Reference)value).clear();
- value = toReference(valueType, object, hash);
- return old;
- }
-
-
- public boolean equals(Object o) {
- if (o == null) return false;
- if (o == this) return true;
- if (!(o instanceof Map.Entry)) return false;
-
- Map.Entry entry = (Map.Entry)o;
- Object key = entry.getKey();
- Object value = entry.getValue();
- if ((key == null) || (value == null)) return false;
- return key.equals(getKey()) && value.equals(getValue());
- }
-
-
- public int hashCode() {
- Object v = getValue();
- return hash ^ ((v == null) ? 0 : v.hashCode());
- }
-
-
- public String toString() {
- return getKey() + "=" + getValue();
- }
-
-
- boolean purge(Reference ref) {
- boolean r = (keyType > HARD) && (key == ref);
- r = r || ((valueType > HARD) && (value == ref));
- if (r) {
- if (keyType > HARD) ((Reference)key).clear();
- if (valueType > HARD) {
- ((Reference)value).clear();
- } else if (purgeValues) {
- value = null;
- }
- }
- return r;
- }
- }
-
-
- private class EntryIterator implements Iterator {
- // These fields keep track of where we are in the table.
- int index;
- Entry entry;
- Entry previous;
-
- // These Object fields provide hard references to the
- // current and next entry; this assures that if hasNext()
- // returns true, next() will actually return a valid element.
- Object nextKey, nextValue;
- Object currentKey, currentValue;
-
- int expectedModCount;
-
-
- public EntryIterator() {
- index = (size() != 0 ? table.length : 0);
- // have to do this here! size() invocation above
- // may have altered the modCount.
- expectedModCount = modCount;
- }
-
-
- public boolean hasNext() {
- checkMod();
- while (nextNull()) {
- Entry e = entry;
- int i = index;
- while ((e == null) && (i > 0)) {
- i--;
- e = table[i];
- }
- entry = e;
- index = i;
- if (e == null) {
- currentKey = null;
- currentValue = null;
- return false;
- }
- nextKey = e.getKey();
- nextValue = e.getValue();
- if (nextNull()) entry = entry.next;
- }
- return true;
- }
-
-
- private void checkMod() {
- if (modCount != expectedModCount) {
- throw new ConcurrentModificationException();
- }
- }
-
-
- private boolean nextNull() {
- return (nextKey == null) || (nextValue == null);
- }
-
- protected Entry nextEntry() {
- checkMod();
- if (nextNull() && !hasNext()) throw new NoSuchElementException();
- previous = entry;
- entry = entry.next;
- currentKey = nextKey;
- currentValue = nextValue;
- nextKey = null;
- nextValue = null;
- return previous;
- }
-
-
- public Object next() {
- return nextEntry();
- }
-
-
- public void remove() {
- checkMod();
- if (previous == null) throw new IllegalStateException();
- ReferenceMap.this.remove(currentKey);
- previous = null;
- currentKey = null;
- currentValue = null;
- expectedModCount = modCount;
- }
-
- }
-
-
- private class ValueIterator extends EntryIterator {
- public Object next() {
- return nextEntry().getValue();
- }
- }
-
-
- private class KeyIterator extends EntryIterator {
- public Object next() {
- return nextEntry().getKey();
- }
- }
-
-
-
- // These two classes store the hashCode of the key of
- // of the mapping, so that after they're dequeued a quick
- // lookup of the bucket in the table can occur.
-
-
- private static class SoftRef extends SoftReference {
- private int hash;
-
-
- public SoftRef(int hash, Object r, ReferenceQueue q) {
- super(r, q);
- this.hash = hash;
- }
-
-
- public int hashCode() {
- return hash;
- }
- }
-
-
- private static class WeakRef extends WeakReference {
- private int hash;
-
-
- public WeakRef(int hash, Object r, ReferenceQueue q) {
- super(r, q);
- this.hash = hash;
- }
-
-
- public int hashCode() {
- return hash;
- }
- }
-
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/collections/keyvalue/AbstractKeyValue.java b/java/client/src/main/java/org/apache/qpid/collections/keyvalue/AbstractKeyValue.java
deleted file mode 100644
index a7ca67ad15..0000000000
--- a/java/client/src/main/java/org/apache/qpid/collections/keyvalue/AbstractKeyValue.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright 2003-2006 The Apache Software Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.qpid.collections.keyvalue;
-
-import org.apache.qpid.collections.KeyValue;
-
-
-/**
- * Abstract pair class to assist with creating <code>KeyValue</code>
- * and {@link java.util.Map.Entry Map.Entry} implementations.
- *
- * @since Commons Collections 3.0
- * @version $Revision$ $Date$
- *
- * @author James Strachan
- * @author Michael A. Smith
- * @author Neil O'Toole
- * @author Stephen Colebourne
- */
-public abstract class AbstractKeyValue implements KeyValue {
-
- /** The key */
- protected Object key;
- /** The value */
- protected Object value;
-
- /**
- * Constructs a new pair with the specified key and given value.
- *
- * @param key the key for the entry, may be null
- * @param value the value for the entry, may be null
- */
- protected AbstractKeyValue(Object key, Object value) {
- super();
- this.key = key;
- this.value = value;
- }
-
- /**
- * Gets the key from the pair.
- *
- * @return the key
- */
- public Object getKey() {
- return key;
- }
-
- /**
- * Gets the value from the pair.
- *
- * @return the value
- */
- public Object getValue() {
- return value;
- }
-
- /**
- * Gets a debugging String view of the pair.
- *
- * @return a String view of the entry
- */
- public String toString() {
- return new StringBuffer()
- .append(getKey())
- .append('=')
- .append(getValue())
- .toString();
- }
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/collections/keyvalue/AbstractMapEntry.java b/java/client/src/main/java/org/apache/qpid/collections/keyvalue/AbstractMapEntry.java
deleted file mode 100644
index f4717a1c20..0000000000
--- a/java/client/src/main/java/org/apache/qpid/collections/keyvalue/AbstractMapEntry.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * Copyright 2003-2006 The Apache Software Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.qpid.collections.keyvalue;
-
-import java.util.Map;
-
-import org.apache.qpid.collections.keyvalue.AbstractKeyValue;
-
-/**
- * Abstract Pair class to assist with creating correct
- * {@link java.util.Map.Entry Map.Entry} implementations.
- *
- * @since Commons Collections 3.0
- * @version $Revision$ $Date$
- *
- * @author James Strachan
- * @author Michael A. Smith
- * @author Neil O'Toole
- * @author Stephen Colebourne
- */
-public abstract class AbstractMapEntry extends AbstractKeyValue implements Map.Entry {
-
- /**
- * Constructs a new entry with the given key and given value.
- *
- * @param key the key for the entry, may be null
- * @param value the value for the entry, may be null
- */
- protected AbstractMapEntry(Object key, Object value) {
- super(key, value);
- }
-
- // Map.Entry interface
- //-------------------------------------------------------------------------
- /**
- * Sets the value stored in this <code>Map.Entry</code>.
- * <p>
- * This <code>Map.Entry</code> is not connected to a Map, so only the
- * local data is changed.
- *
- * @param value the new value
- * @return the previous value
- */
- public Object setValue(Object value) {
- Object answer = this.value;
- this.value = value;
- return answer;
- }
-
- /**
- * Compares this <code>Map.Entry</code> with another <code>Map.Entry</code>.
- * <p>
- * Implemented per API documentation of {@link java.util.Map.Entry#equals(Object)}
- *
- * @param obj the object to compare to
- * @return true if equal key and value
- */
- public boolean equals(Object obj) {
- if (obj == this) {
- return true;
- }
- if (obj instanceof Map.Entry == false) {
- return false;
- }
- Map.Entry other = (Map.Entry) obj;
- return
- (getKey() == null ? other.getKey() == null : getKey().equals(other.getKey())) &&
- (getValue() == null ? other.getValue() == null : getValue().equals(other.getValue()));
- }
-
- /**
- * Gets a hashCode compatible with the equals method.
- * <p>
- * Implemented per API documentation of {@link java.util.Map.Entry#hashCode()}
- *
- * @return a suitable hash code
- */
- public int hashCode() {
- return (getKey() == null ? 0 : getKey().hashCode()) ^
- (getValue() == null ? 0 : getValue().hashCode());
- }
-
-} \ No newline at end of file
diff --git a/java/client/src/main/java/org/apache/qpid/collections/keyvalue/DefaultMapEntry.java b/java/client/src/main/java/org/apache/qpid/collections/keyvalue/DefaultMapEntry.java
deleted file mode 100644
index f0f04a366a..0000000000
--- a/java/client/src/main/java/org/apache/qpid/collections/keyvalue/DefaultMapEntry.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright 2001-2006 The Apache Software Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.qpid.collections.keyvalue;
-
-import java.util.Map;
-
-import org.apache.qpid.collections.KeyValue;
-import org.apache.qpid.collections.keyvalue.AbstractMapEntry;
-
-/**
- * A restricted implementation of {@link java.util.Map.Entry} that prevents
- * the <code>Map.Entry</code> contract from being broken.
- *
- * @since Commons Collections 3.0
- * @version $Revision$ $Date$
- *
- * @author James Strachan
- * @author Michael A. Smith
- * @author Neil O'Toole
- * @author Stephen Colebourne
- */
-public final class DefaultMapEntry extends AbstractMapEntry {
-
- /**
- * Constructs a new entry with the specified key and given value.
- *
- * @param key the key for the entry, may be null
- * @param value the value for the entry, may be null
- */
- public DefaultMapEntry(final Object key, final Object value) {
- super(key, value);
- }
-
- /**
- * Constructs a new entry from the specified <code>KeyValue</code>.
- *
- * @param pair the pair to copy, must not be null
- * @throws NullPointerException if the entry is null
- */
- public DefaultMapEntry(final KeyValue pair) {
- super(pair.getKey(), pair.getValue());
- }
-
- /**
- * Constructs a new entry from the specified <code>Map.Entry</code>.
- *
- * @param entry the entry to copy, must not be null
- * @throws NullPointerException if the entry is null
- */
- public DefaultMapEntry(final Map.Entry entry) {
- super(entry.getKey(), entry.getValue());
- }
-
-} \ No newline at end of file
diff --git a/java/client/src/main/java/org/apache/qpid/filter/ArithmeticExpression.java b/java/client/src/main/java/org/apache/qpid/filter/ArithmeticExpression.java
deleted file mode 100644
index a86613f10c..0000000000
--- a/java/client/src/main/java/org/apache/qpid/filter/ArithmeticExpression.java
+++ /dev/null
@@ -1,268 +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.filter;
-
-import org.apache.qpid.AMQInternalException;
-import org.apache.qpid.client.message.AbstractJMSMessage;
-
-
-/**
- * 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;
-
-
- 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;
- return text + rvalue;
- }
- 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 ArithmeticExpression.INTEGER:
- return new Integer(left.intValue() + right.intValue());
-
- case ArithmeticExpression.LONG:
- return new Long(left.longValue() + right.longValue());
-
- default:
- return new Double(left.doubleValue() + right.doubleValue());
- }
- }
-
- protected Number minus(Number left, Number right)
- {
- switch (numberType(left, right))
- {
-
- case ArithmeticExpression.INTEGER:
- return new Integer(left.intValue() - right.intValue());
-
- case ArithmeticExpression.LONG:
- return new Long(left.longValue() - right.longValue());
-
- default:
- return new Double(left.doubleValue() - right.doubleValue());
- }
- }
-
- protected Number multiply(Number left, Number right)
- {
- switch (numberType(left, right))
- {
-
- case ArithmeticExpression.INTEGER:
- return new Integer(left.intValue() * right.intValue());
-
- case ArithmeticExpression.LONG:
- return new Long(left.longValue() * right.longValue());
-
- default:
- return new Double(left.doubleValue() * right.doubleValue());
- }
- }
-
- protected Number divide(Number left, Number right)
- {
- return new Double(left.doubleValue() / right.doubleValue());
- }
-
- protected Number mod(Number left, Number right)
- {
- return new Double(left.doubleValue() % right.doubleValue());
- }
-
- private int numberType(Number left, Number right)
- {
- if (isDouble(left) || isDouble(right))
- {
- return ArithmeticExpression.DOUBLE;
- }
- else if ((left instanceof Long) || (right instanceof Long))
- {
- return ArithmeticExpression.LONG;
- }
- else
- {
- return ArithmeticExpression.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(AbstractJMSMessage message) throws AMQInternalException
- {
- 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/java/client/src/main/java/org/apache/qpid/filter/BinaryExpression.java b/java/client/src/main/java/org/apache/qpid/filter/BinaryExpression.java
deleted file mode 100644
index f97f858fad..0000000000
--- a/java/client/src/main/java/org/apache/qpid/filter/BinaryExpression.java
+++ /dev/null
@@ -1,103 +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.filter;
-
-/**
- * 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 Object#toString()
- */
- public String toString()
- {
- return "(" + left.toString() + " " + getExpressionSymbol() + " " + right.toString() + ")";
- }
-
- /**
- * TODO: more efficient hashCode()
- *
- * @see Object#hashCode()
- */
- public int hashCode()
- {
- return toString().hashCode();
- }
-
- /**
- * TODO: more efficient hashCode()
- *
- * @see Object#equals(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/java/client/src/main/java/org/apache/qpid/filter/BooleanExpression.java b/java/client/src/main/java/org/apache/qpid/filter/BooleanExpression.java
deleted file mode 100644
index 14a5c7ea87..0000000000
--- a/java/client/src/main/java/org/apache/qpid/filter/BooleanExpression.java
+++ /dev/null
@@ -1,33 +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.filter;
-
-import org.apache.qpid.AMQInternalException;
-import org.apache.qpid.client.message.AbstractJMSMessage;
-
-
-/**
- * A BooleanExpression is an expression that always
- * produces a Boolean result.
- */
-public interface BooleanExpression extends Expression
-{
-
- public boolean matches(AbstractJMSMessage message) throws AMQInternalException;
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/filter/ComparisonExpression.java b/java/client/src/main/java/org/apache/qpid/filter/ComparisonExpression.java
deleted file mode 100644
index 55fca853ef..0000000000
--- a/java/client/src/main/java/org/apache/qpid/filter/ComparisonExpression.java
+++ /dev/null
@@ -1,589 +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.filter;
-
-import java.util.HashSet;
-import java.util.List;
-import java.util.regex.Pattern;
-
-import org.apache.qpid.AMQInternalException;
-import org.apache.qpid.client.message.AbstractJMSMessage;
-
-/**
- * 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(ComparisonExpression.createGreaterThanEqual(value, left), ComparisonExpression.createLessThanEqual(value, right));
- }
-
- public static BooleanExpression createNotBetween(Expression value, Expression left, Expression right)
- {
- return LogicExpression.createOR(ComparisonExpression.createLessThan(value, left), ComparisonExpression.createGreaterThan(value, right));
- }
-
- private static final HashSet REGEXP_CONTROL_CHARS = new HashSet();
-
- static
- {
- ComparisonExpression.REGEXP_CONTROL_CHARS.add(new Character('.'));
- ComparisonExpression.REGEXP_CONTROL_CHARS.add(new Character('\\'));
- ComparisonExpression.REGEXP_CONTROL_CHARS.add(new Character('['));
- ComparisonExpression.REGEXP_CONTROL_CHARS.add(new Character(']'));
- ComparisonExpression.REGEXP_CONTROL_CHARS.add(new Character('^'));
- ComparisonExpression.REGEXP_CONTROL_CHARS.add(new Character('$'));
- ComparisonExpression.REGEXP_CONTROL_CHARS.add(new Character('?'));
- ComparisonExpression.REGEXP_CONTROL_CHARS.add(new Character('*'));
- ComparisonExpression.REGEXP_CONTROL_CHARS.add(new Character('+'));
- ComparisonExpression.REGEXP_CONTROL_CHARS.add(new Character('{'));
- ComparisonExpression.REGEXP_CONTROL_CHARS.add(new Character('}'));
- ComparisonExpression.REGEXP_CONTROL_CHARS.add(new Character('|'));
- ComparisonExpression.REGEXP_CONTROL_CHARS.add(new Character('('));
- ComparisonExpression.REGEXP_CONTROL_CHARS.add(new Character(')'));
- ComparisonExpression.REGEXP_CONTROL_CHARS.add(new Character(':'));
- ComparisonExpression.REGEXP_CONTROL_CHARS.add(new Character('&'));
- ComparisonExpression.REGEXP_CONTROL_CHARS.add(new Character('<'));
- ComparisonExpression.REGEXP_CONTROL_CHARS.add(new Character('>'));
- ComparisonExpression.REGEXP_CONTROL_CHARS.add(new Character('='));
- ComparisonExpression.REGEXP_CONTROL_CHARS.add(new Character('!'));
- }
-
- 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 (ComparisonExpression.REGEXP_CONTROL_CHARS.contains(new Character(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(AbstractJMSMessage message) throws AMQInternalException
- {
-
- 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(AbstractJMSMessage message) throws AMQInternalException
- {
- 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(ComparisonExpression.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 ComparisonExpression.doCreateEqual(left, ConstantExpression.NULL);
- }
-
- public static BooleanExpression createIsNotNull(Expression left)
- {
- return UnaryExpression.createNOT(ComparisonExpression.doCreateEqual(left, ConstantExpression.NULL));
- }
-
- public static BooleanExpression createNotEqual(Expression left, Expression right)
- {
- return UnaryExpression.createNOT(ComparisonExpression.createEqual(left, right));
- }
-
- public static BooleanExpression createEqual(Expression left, Expression right)
- {
- ComparisonExpression.checkEqualOperand(left);
- ComparisonExpression.checkEqualOperand(right);
- ComparisonExpression.checkEqualOperandCompatability(left, right);
-
- return ComparisonExpression.doCreateEqual(left, right);
- }
-
- private static BooleanExpression doCreateEqual(Expression left, Expression right)
- {
- return new ComparisonExpression(left, right)
- {
-
- public Object evaluate(AbstractJMSMessage message) throws AMQInternalException
- {
- 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 "=";
- }
- };
- }
-
- public static BooleanExpression createGreaterThan(final Expression left, final Expression right)
- {
- ComparisonExpression.checkLessThanOperand(left);
- ComparisonExpression.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)
- {
- ComparisonExpression.checkLessThanOperand(left);
- ComparisonExpression.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)
- {
- ComparisonExpression.checkLessThanOperand(left);
- ComparisonExpression.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)
- {
- ComparisonExpression.checkLessThanOperand(left);
- ComparisonExpression.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(AbstractJMSMessage message) throws AMQInternalException
- {
- 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 = new Short(((Number) lv).shortValue());
- }
- else if (rc == Integer.class)
- {
- lv = new Integer(((Number) lv).intValue());
- }
- else if (rc == Long.class)
- {
- lv = new Long(((Number) lv).longValue());
- }
- else if (rc == Float.class)
- {
- lv = new Float(((Number) lv).floatValue());
- }
- else if (rc == Double.class)
- {
- lv = new Double(((Number) lv).doubleValue());
- }
- else
- {
- return Boolean.FALSE;
- }
- }
- else if (lc == Short.class)
- {
- if (rc == Integer.class)
- {
- lv = new Integer(((Number) lv).intValue());
- }
- else if (rc == Long.class)
- {
- lv = new Long(((Number) lv).longValue());
- }
- else if (rc == Float.class)
- {
- lv = new Float(((Number) lv).floatValue());
- }
- else if (rc == Double.class)
- {
- lv = new Double(((Number) lv).doubleValue());
- }
- else
- {
- return Boolean.FALSE;
- }
- }
- else if (lc == Integer.class)
- {
- if (rc == Long.class)
- {
- lv = new Long(((Number) lv).longValue());
- }
- else if (rc == Float.class)
- {
- lv = new Float(((Number) lv).floatValue());
- }
- else if (rc == Double.class)
- {
- lv = new Double(((Number) lv).doubleValue());
- }
- else
- {
- return Boolean.FALSE;
- }
- }
- else if (lc == Long.class)
- {
- if (rc == Integer.class)
- {
- rv = new Long(((Number) rv).longValue());
- }
- else if (rc == Float.class)
- {
- lv = new Float(((Number) lv).floatValue());
- }
- else if (rc == Double.class)
- {
- lv = new Double(((Number) lv).doubleValue());
- }
- else
- {
- return Boolean.FALSE;
- }
- }
- else if (lc == Float.class)
- {
- if (rc == Integer.class)
- {
- rv = new Float(((Number) rv).floatValue());
- }
- else if (rc == Long.class)
- {
- rv = new Float(((Number) rv).floatValue());
- }
- else if (rc == Double.class)
- {
- lv = new Double(((Number) lv).doubleValue());
- }
- else
- {
- return Boolean.FALSE;
- }
- }
- else if (lc == Double.class)
- {
- if (rc == Integer.class)
- {
- rv = new Double(((Number) rv).doubleValue());
- }
- else if (rc == Long.class)
- {
- rv = new Double(((Number) rv).doubleValue());
- }
- else if (rc == Float.class)
- {
- rv = new Float(((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(AbstractJMSMessage message) throws AMQInternalException
- {
- Object object = evaluate(message);
-
- return (object != null) && (object == Boolean.TRUE);
- }
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/filter/ConstantExpression.java b/java/client/src/main/java/org/apache/qpid/filter/ConstantExpression.java
deleted file mode 100644
index 3874d13431..0000000000
--- a/java/client/src/main/java/org/apache/qpid/filter/ConstantExpression.java
+++ /dev/null
@@ -1,204 +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.filter;
-
-import java.math.BigDecimal;
-
-import org.apache.qpid.AMQInternalException;
-import org.apache.qpid.client.message.AbstractJMSMessage;
-
-/**
- * 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(AbstractJMSMessage message) throws AMQInternalException
- {
- 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 = new Integer(value.intValue());
- }
-
- return new ConstantExpression(value);
- }
-
- public static ConstantExpression createFromHex(String text)
- {
- Number value = new Long(Long.parseLong(text.substring(2), 16));
- long l = value.longValue();
- if ((Integer.MIN_VALUE <= l) && (l <= Integer.MAX_VALUE))
- {
- value = new Integer(value.intValue());
- }
-
- return new ConstantExpression(value);
- }
-
- public static ConstantExpression createFromOctal(String text)
- {
- Number value = new Long(Long.parseLong(text, 8));
- long l = value.longValue();
- if ((Integer.MIN_VALUE <= l) && (l <= Integer.MAX_VALUE))
- {
- value = new Integer(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(AbstractJMSMessage message) throws AMQInternalException
- {
- return value;
- }
-
- public Object getValue()
- {
- return value;
- }
-
- /**
- * @see Object#toString()
- */
- public String toString()
- {
- if (value == null)
- {
- return "NULL";
- }
-
- if (value instanceof Boolean)
- {
- return ((Boolean) value).booleanValue() ? "TRUE" : "FALSE";
- }
-
- if (value instanceof String)
- {
- return ConstantExpression.encodeString((String) value);
- }
-
- return value.toString();
- }
-
- /**
- * TODO: more efficient hashCode()
- *
- * @see Object#hashCode()
- */
- public int hashCode()
- {
- return toString().hashCode();
- }
-
- /**
- * TODO: more efficient hashCode()
- *
- * @see Object#equals(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/java/client/src/main/java/org/apache/qpid/filter/Expression.java b/java/client/src/main/java/org/apache/qpid/filter/Expression.java
deleted file mode 100644
index 8208f49688..0000000000
--- a/java/client/src/main/java/org/apache/qpid/filter/Expression.java
+++ /dev/null
@@ -1,35 +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.filter;
-
-import org.apache.qpid.AMQInternalException;
-import org.apache.qpid.client.message.AbstractJMSMessage;
-
-
-/**
- * Represents an expression
- */
-public interface Expression
-{
- /**
- * @param message The message to evaluate
- * @return the value of this expression
- * @throws AMQInternalException
- */
- public Object evaluate(AbstractJMSMessage message) throws AMQInternalException;
-}
diff --git a/java/client/src/main/java/org/apache/qpid/filter/JMSSelectorFilter.java b/java/client/src/main/java/org/apache/qpid/filter/JMSSelectorFilter.java
deleted file mode 100644
index 4159986090..0000000000
--- a/java/client/src/main/java/org/apache/qpid/filter/JMSSelectorFilter.java
+++ /dev/null
@@ -1,70 +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.filter;
-
-import org.apache.qpid.AMQInternalException;
-import org.apache.qpid.client.message.AbstractJMSMessage;
-import org.apache.qpid.filter.selector.SelectorParser;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-
-public class JMSSelectorFilter implements MessageFilter
-{
- /**
- * this JMSSelectorFilter's logger
- */
- private static final Logger _logger = LoggerFactory.getLogger(JMSSelectorFilter.class);
-
- private String _selector;
- private BooleanExpression _matcher;
-
- public JMSSelectorFilter(String selector) throws AMQInternalException
- {
- _selector = selector;
- if (JMSSelectorFilter._logger.isDebugEnabled())
- {
- JMSSelectorFilter._logger.debug("Created JMSSelectorFilter with selector:" + _selector);
- }
- _matcher = new SelectorParser().parse(selector);
- }
-
- public boolean matches(AbstractJMSMessage message)
- {
- try
- {
- boolean match = _matcher.matches(message);
- if (JMSSelectorFilter._logger.isDebugEnabled())
- {
- JMSSelectorFilter._logger.debug(message + " match(" + match + ") selector(" + System
- .identityHashCode(_selector) + "):" + _selector);
- }
- return match;
- }
- catch (AMQInternalException e)
- {
- JMSSelectorFilter._logger.warn("Caght exception when evaluating message selector for message " + message, e);
- }
- return false;
- }
-
- public String getSelector()
- {
- return _selector;
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/filter/LogicExpression.java b/java/client/src/main/java/org/apache/qpid/filter/LogicExpression.java
deleted file mode 100644
index 7ef85cbacb..0000000000
--- a/java/client/src/main/java/org/apache/qpid/filter/LogicExpression.java
+++ /dev/null
@@ -1,108 +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.filter;
-
-import org.apache.qpid.AMQInternalException;
-import org.apache.qpid.client.message.AbstractJMSMessage;
-
-
-/**
- * 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 LogicExpression(lvalue, rvalue)
- {
-
- public Object evaluate(AbstractJMSMessage message) throws AMQInternalException
- {
-
- 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";
- }
- };
- }
-
- public static BooleanExpression createAND(BooleanExpression lvalue, BooleanExpression rvalue)
- {
- return new LogicExpression(lvalue, rvalue)
- {
-
- public Object evaluate(AbstractJMSMessage message) throws AMQInternalException
- {
-
- 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";
- }
- };
- }
-
- /**
- * @param left
- * @param right
- */
- public LogicExpression(BooleanExpression left, BooleanExpression right)
- {
- super(left, right);
- }
-
- public abstract Object evaluate(AbstractJMSMessage message) throws AMQInternalException;
-
- public boolean matches(AbstractJMSMessage message) throws AMQInternalException
- {
- Object object = evaluate(message);
-
- return (object != null) && (object == Boolean.TRUE);
- }
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/filter/MessageFilter.java b/java/client/src/main/java/org/apache/qpid/filter/MessageFilter.java
deleted file mode 100644
index 62e4a28c1e..0000000000
--- a/java/client/src/main/java/org/apache/qpid/filter/MessageFilter.java
+++ /dev/null
@@ -1,27 +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.filter;
-
-import org.apache.qpid.AMQInternalException;
-import org.apache.qpid.client.message.AbstractJMSMessage;
-
-
-public interface MessageFilter
-{
- boolean matches(AbstractJMSMessage message) throws AMQInternalException;
-}
diff --git a/java/client/src/main/java/org/apache/qpid/filter/PropertyExpression.java b/java/client/src/main/java/org/apache/qpid/filter/PropertyExpression.java
deleted file mode 100644
index b7b6bd57bc..0000000000
--- a/java/client/src/main/java/org/apache/qpid/filter/PropertyExpression.java
+++ /dev/null
@@ -1,297 +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.filter;
-
-import java.util.HashMap;
-
-import javax.jms.JMSException;
-
-import org.apache.qpid.AMQInternalException;
-import org.apache.qpid.client.message.AbstractJMSMessage;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Represents a property expression
- */
-public class PropertyExpression implements Expression
-{
- // Constants - defined the same as JMS
- private static final int NON_PERSISTENT = 1;
- private static final int DEFAULT_PRIORITY = 4;
-
- private static final Logger _logger = LoggerFactory.getLogger(PropertyExpression.class);
-
- private static final HashMap<String, Expression> JMS_PROPERTY_EXPRESSIONS = new HashMap<String, Expression>();
-
- static
- {
- JMS_PROPERTY_EXPRESSIONS.put("JMSDestination", new Expression()
- {
- public Object evaluate(AbstractJMSMessage message)
- {
- //TODO
- return null;
- }
- });
- JMS_PROPERTY_EXPRESSIONS.put("JMSReplyTo", new Expression()
- {
- public Object evaluate(AbstractJMSMessage message)
- {
- return message.getReplyToString();
- }
- });
-
- JMS_PROPERTY_EXPRESSIONS.put("JMSType", new Expression()
- {
- public Object evaluate(AbstractJMSMessage message)
- {
- try
- {
- return message.getJMSType();
- }
- catch (JMSException e)
- {
- _logger.warn("Error evaluating property", e);
-
- return null;
- }
-
- }
- });
-
- JMS_PROPERTY_EXPRESSIONS.put("JMSDeliveryMode", new Expression()
- {
- public Object evaluate(AbstractJMSMessage message)
- {
- try
- {
- int mode = message.getJMSDeliveryMode();
- if (_logger.isDebugEnabled())
- {
- _logger.debug("JMSDeliveryMode is :" + mode);
- }
-
- return mode;
- }
- catch (JMSException e)
- {
- _logger.warn("Error evaluating property",e);
- }
-
- return NON_PERSISTENT;
- }
- });
-
- JMS_PROPERTY_EXPRESSIONS.put("JMSPriority", new Expression()
- {
- public Object evaluate(AbstractJMSMessage message)
- {
- try
- {
- return message.getJMSPriority();
- }
- catch (Exception e)
- {
- _logger.warn("Error evaluating property",e);
- }
-
- return DEFAULT_PRIORITY;
- }
- });
-
- JMS_PROPERTY_EXPRESSIONS.put("AMQMessageID", new Expression()
- {
- public Object evaluate(AbstractJMSMessage message)
- {
-
- try
- {
- return message.getJMSMessageID();
- }
- catch (JMSException e)
- {
- _logger.warn("Error evaluating property",e);
-
- return null;
- }
-
- }
- });
-
- JMS_PROPERTY_EXPRESSIONS.put("JMSTimestamp", new Expression()
- {
- public Object evaluate(AbstractJMSMessage message)
- {
- try
- {
- return message.getJMSTimestamp();
- }
- catch (Exception e)
- {
- _logger.warn("Error evaluating property",e);
-
- return null;
- }
-
- }
- });
-
- JMS_PROPERTY_EXPRESSIONS.put("JMSCorrelationID", new Expression()
- {
- public Object evaluate(AbstractJMSMessage message)
- {
-
- try
- {
- return message.getJMSCorrelationID();
- }
- catch (JMSException e)
- {
- _logger.warn("Error evaluating property",e);
-
- return null;
- }
-
- }
- });
-
- JMS_PROPERTY_EXPRESSIONS.put("JMSExpiration", new Expression()
- {
- public Object evaluate(AbstractJMSMessage message)
- {
-
- try
- {
- return message.getJMSExpiration();
- }
- catch (JMSException e)
- {
- _logger.warn("Error evaluating property",e);
- return null;
- }
-
- }
- });
-
- JMS_PROPERTY_EXPRESSIONS.put("JMSRedelivered", new Expression()
- {
- public Object evaluate(AbstractJMSMessage message)
- {
- try
- {
- return message.getJMSRedelivered();
- }
- catch (JMSException e)
- {
- _logger.warn("Error evaluating property",e);
- return null;
- }
- }
- });
-
- JMS_PROPERTY_EXPRESSIONS.put("JMSMessageID", new Expression()
- {
- public Object evaluate(AbstractJMSMessage message)
- {
- try
- {
- return message.getJMSMessageID();
- }
- catch (Exception e)
- {
- _logger.warn("Error evaluating property",e);
-
- return null;
- }
-
- }
- });
-
- }
-
- private final String name;
- private final Expression jmsPropertyExpression;
-
- public PropertyExpression(String name)
- {
- this.name = name;
- jmsPropertyExpression = JMS_PROPERTY_EXPRESSIONS.get(name);
- }
-
- public Object evaluate(AbstractJMSMessage message) throws AMQInternalException
- {
-
- if (jmsPropertyExpression != null)
- {
- return jmsPropertyExpression.evaluate(message);
- }
- else
- {
-
- try
- {
-
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Looking up property:" + name);
- _logger.debug("Properties are:" + message.getPropertyNames());
- }
- return message.getObjectProperty(name);
- }
- catch(JMSException e)
- {
- throw new AMQInternalException("Exception evaluating properties for filter", e);
- }
- }
- }
-
- 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);
- }
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/filter/UnaryExpression.java b/java/client/src/main/java/org/apache/qpid/filter/UnaryExpression.java
deleted file mode 100644
index 0fc3382b7e..0000000000
--- a/java/client/src/main/java/org/apache/qpid/filter/UnaryExpression.java
+++ /dev/null
@@ -1,321 +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.filter;
-
-import java.math.BigDecimal;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-
-import org.apache.qpid.AMQInternalException;
-import org.apache.qpid.client.message.AbstractJMSMessage;
-
-/**
- * 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 UnaryExpression(left)
- {
- public Object evaluate(AbstractJMSMessage message) throws AMQInternalException
- {
- Object rvalue = right.evaluate(message);
- if (rvalue == null)
- {
- return null;
- }
-
- if (rvalue instanceof Number)
- {
- return UnaryExpression.negate((Number) rvalue);
- }
-
- return null;
- }
-
- public String getExpressionSymbol()
- {
- return "-";
- }
- };
- }
-
- 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 BooleanUnaryExpression(right)
- {
- public Object evaluate(AbstractJMSMessage message) throws AMQInternalException
- {
-
- 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";
- }
- }
- };
- }
-
- abstract static class BooleanUnaryExpression extends UnaryExpression implements BooleanExpression
- {
- public BooleanUnaryExpression(Expression left)
- {
- super(left);
- }
-
- public boolean matches(AbstractJMSMessage message) throws AMQInternalException
- {
- Object object = evaluate(message);
-
- return (object != null) && (object == Boolean.TRUE);
- }
- }
-
- ;
-
- public static BooleanExpression createNOT(BooleanExpression left)
- {
- return new BooleanUnaryExpression(left)
- {
- public Object evaluate(AbstractJMSMessage message) throws AMQInternalException
- {
- Boolean lvalue = (Boolean) right.evaluate(message);
- if (lvalue == null)
- {
- return null;
- }
-
- return lvalue.booleanValue() ? Boolean.FALSE : Boolean.TRUE;
- }
-
- public String getExpressionSymbol()
- {
- return "NOT";
- }
- };
- }
- public static BooleanExpression createBooleanCast(Expression left)
- {
- return new BooleanUnaryExpression(left)
- {
- public Object evaluate(AbstractJMSMessage message) throws AMQInternalException
- {
- 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 "";
- }
- };
- }
-
- private static Number negate(Number left)
- {
- Class clazz = left.getClass();
- if (clazz == Integer.class)
- {
- return new Integer(-left.intValue());
- }
- else if (clazz == Long.class)
- {
- return new Long(-left.longValue());
- }
- else if (clazz == Float.class)
- {
- return new Float(-left.floatValue());
- }
- else if (clazz == Double.class)
- {
- return new Double(-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 (UnaryExpression.BD_LONG_MIN_VALUE.compareTo(bd) == 0)
- {
- return new Long(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 Object#toString()
- */
- public String toString()
- {
- return "(" + getExpressionSymbol() + " " + right.toString() + ")";
- }
-
- /**
- * TODO: more efficient hashCode()
- *
- * @see Object#hashCode()
- */
- public int hashCode()
- {
- return toString().hashCode();
- }
-
- /**
- * TODO: more efficient hashCode()
- *
- * @see Object#equals(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();
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/jms/BrokerDetails.java b/java/client/src/main/java/org/apache/qpid/jms/BrokerDetails.java
deleted file mode 100644
index 6d81f728c9..0000000000
--- a/java/client/src/main/java/org/apache/qpid/jms/BrokerDetails.java
+++ /dev/null
@@ -1,119 +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.jms;
-
-import java.util.Map;
-
-import org.apache.qpid.client.SSLConfiguration;
-
-public interface BrokerDetails
-{
-
- /*
- * Known URL Options
- * @see ConnectionURL
- */
- public static final String OPTIONS_RETRY = "retries";
- public static final String OPTIONS_CONNECT_TIMEOUT = "connecttimeout";
- public static final String OPTIONS_CONNECT_DELAY = "connectdelay";
- public static final String OPTIONS_IDLE_TIMEOUT = "idle_timeout"; // deprecated
- public static final String OPTIONS_HEARTBEAT = "heartbeat";
- public static final String OPTIONS_SASL_MECHS = "sasl_mechs";
- public static final String OPTIONS_SASL_ENCRYPTION = "sasl_encryption";
- public static final String OPTIONS_SSL = "ssl";
- public static final String OPTIONS_TCP_NO_DELAY = "tcp_nodelay";
- public static final String OPTIONS_SASL_PROTOCOL_NAME = "sasl_protocol";
- public static final String OPTIONS_SASL_SERVER_NAME = "sasl_server";
-
- public static final String OPTIONS_TRUST_STORE = "trust_store";
- public static final String OPTIONS_TRUST_STORE_PASSWORD = "trust_store_password";
- public static final String OPTIONS_KEY_STORE = "key_store";
- public static final String OPTIONS_KEY_STORE_PASSWORD = "key_store_password";
- public static final String OPTIONS_SSL_VERIFY_HOSTNAME = "ssl_verify_hostname";
- public static final String OPTIONS_SSL_CERT_ALIAS = "ssl_cert_alias";
-
- public static final int DEFAULT_PORT = 5672;
-
- public static final String SOCKET = "socket";
- public static final String TCP = "tcp";
- public static final String VM = "vm";
-
- public static final String DEFAULT_TRANSPORT = TCP;
-
- public static final String URL_FORMAT_EXAMPLE =
- "<transport>://<hostname>[:<port Default=\"" + DEFAULT_PORT + "\">][?<option>='<value>'[,<option>='<value>']]";
-
- public static final long DEFAULT_CONNECT_TIMEOUT = 30000L;
- public static final boolean USE_SSL_DEFAULT = false;
-
- // pulled these properties from the new BrokerDetails class in the qpid package
- public static final String PROTOCOL_TCP = "tcp";
- public static final String PROTOCOL_TLS = "tls";
-
- public static final String VIRTUAL_HOST = "virtualhost";
- public static final String CLIENT_ID = "client_id";
- public static final String USERNAME = "username";
- public static final String PASSWORD = "password";
-
- String getHost();
-
- void setHost(String host);
-
- int getPort();
-
- void setPort(int port);
-
- String getTransport();
-
- void setTransport(String transport);
-
- String getProperty(String key);
-
- void setProperty(String key, String value);
-
- /**
- * Ex: keystore path
- *
- * @return the Properties associated with this connection.
- */
- public Map<String,String> getProperties();
-
- /**
- * Sets the properties associated with this connection
- *
- * @param props the new p[roperties.
- */
- public void setProperties(Map<String,String> props);
-
- long getTimeout();
-
- void setTimeout(long timeout);
-
- SSLConfiguration getSSLConfiguration();
-
- void setSSLConfiguration(SSLConfiguration sslConfiguration);
-
- boolean getBooleanProperty(String propName);
-
- String toString();
-
- boolean equals(Object o);
-}
diff --git a/java/client/src/main/java/org/apache/qpid/jms/ChannelLimitReachedException.java b/java/client/src/main/java/org/apache/qpid/jms/ChannelLimitReachedException.java
deleted file mode 100644
index e8c2b9d682..0000000000
--- a/java/client/src/main/java/org/apache/qpid/jms/ChannelLimitReachedException.java
+++ /dev/null
@@ -1,46 +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.jms;
-
-import javax.jms.ResourceAllocationException;
-
-/**
- * Indicates that the maximum number of sessions per connection limit has been reached.
- */
-public class ChannelLimitReachedException extends ResourceAllocationException
-{
- private static final String ERROR_CODE = "1";
-
- private long _limit;
-
- public ChannelLimitReachedException(long limit)
- {
- super("Unable to create session, the maximum number of sessions per connection is " +
- limit + ". You must either close one or more sessions or increase the " +
- "maximum number of sessions available per connection.", ERROR_CODE);
- _limit = limit;
- }
-
- public long getLimit()
- {
- return _limit;
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/jms/Connection.java b/java/client/src/main/java/org/apache/qpid/jms/Connection.java
deleted file mode 100644
index 616c6dbbec..0000000000
--- a/java/client/src/main/java/org/apache/qpid/jms/Connection.java
+++ /dev/null
@@ -1,69 +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.jms;
-
-import javax.jms.JMSException;
-
-public interface Connection extends javax.jms.Connection
-{
- /**
- * @return the maximum number of sessions supported by this Connection
- */
- long getMaximumChannelCount() throws JMSException;
-
- void setConnectionListener(ConnectionListener listener);
-
- /**
- * Get the connection listener that has been registered with this connection, if any
- *
- * @return the listener or null if none has been set
- */
- ConnectionListener getConnectionListener();
-
- /**
- * Create a session specifying the prefetch limit of messages.
- *
- * @param transacted
- * @param acknowledgeMode
- * @param prefetch the maximum number of messages to buffer in the client. This
- * applies as a total across all consumers
- * @return
- * @throws JMSException
- */
- org.apache.qpid.jms.Session createSession(boolean transacted, int acknowledgeMode,
- int prefetch) throws JMSException;
-
-
- /**
- * Create a session specifying the prefetch limit of messages.
- *
- * @param transacted
- * @param acknowledgeMode
- * @param prefetchHigh the maximum number of messages to buffer in the client.
- * This applies as a total across all consumers
- * @param prefetchLow the number of messages that must be in the buffer in the client to renable message flow.
- * This applies as a total across all consumers
- * @return
- * @throws JMSException
- */
- org.apache.qpid.jms.Session createSession(boolean transacted, int acknowledgeMode,
- int prefetchHigh, int prefetchLow) throws JMSException;
-}
diff --git a/java/client/src/main/java/org/apache/qpid/jms/ConnectionListener.java b/java/client/src/main/java/org/apache/qpid/jms/ConnectionListener.java
deleted file mode 100644
index 11c235901c..0000000000
--- a/java/client/src/main/java/org/apache/qpid/jms/ConnectionListener.java
+++ /dev/null
@@ -1,58 +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.jms;
-
-public interface ConnectionListener
-{
- /**
- * Called when bytes have been transmitted to the server
- * @param count the number of bytes sent in total since the connection was opened
- */
- void bytesSent(long count);
-
- /**
- * Called when some bytes have been received on a connection
- * @param count the number of bytes received in total since the connection was opened
- */
- void bytesReceived(long count);
-
- /**
- * Called after the infrastructure has detected that failover is required but before attempting failover.
- * @param redirect true if the broker requested redirect. false if failover is occurring due to a connection error.
- * @return true to continue failing over, false to veto failover and raise a connection exception
- */
- boolean preFailover(boolean redirect);
-
- /**
- * Called after connection has been made to another broker after failover has been started but before
- * any resubscription has been done.
- * @return true to continue with resubscription, false to prevent automatic resubscription. This is useful in
- * cases where the application wants to handle resubscription. Note that in the latter case all sessions, producers
- * and consumers are invalidated.
- */
- boolean preResubscribe();
-
- /**
- * Called once failover has completed successfully. This is called irrespective of whether the client has
- * vetoed automatic resubscription.
- */
- void failoverComplete();
-}
diff --git a/java/client/src/main/java/org/apache/qpid/jms/ConnectionURL.java b/java/client/src/main/java/org/apache/qpid/jms/ConnectionURL.java
deleted file mode 100644
index 0e8ca60686..0000000000
--- a/java/client/src/main/java/org/apache/qpid/jms/ConnectionURL.java
+++ /dev/null
@@ -1,96 +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.jms;
-
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.ProtocolVersion;
-
-import java.util.List;
-
-/**
- Connection URL format
- amqp://[user:pass@][clientid]/virtualhost?brokerlist='tcp://host:port?option=\'value\'&option=\'value\';vm://:3/virtualpath?option=\'value\''&failover='method?option=\'value\'&option='value''"
- Options are of course optional except for requiring a single broker in the broker list.
- The option seperator is defined to be either '&' or ','
- */
-public interface ConnectionURL
-{
- public static final String AMQ_PROTOCOL = "amqp";
- public static final String OPTIONS_SYNC_PERSISTENCE = "sync_persistence";
- public static final String OPTIONS_MAXPREFETCH = "maxprefetch";
- public static final String OPTIONS_SYNC_ACK = "sync_ack";
- public static final String OPTIONS_SYNC_PUBLISH = "sync_publish";
- public static final String OPTIONS_USE_LEGACY_MAP_MESSAGE_FORMAT = "use_legacy_map_msg_format";
- public static final String OPTIONS_BROKERLIST = "brokerlist";
- public static final String OPTIONS_FAILOVER = "failover";
- public static final String OPTIONS_FAILOVER_CYCLE = "cyclecount";
- public static final String OPTIONS_DEFAULT_TOPIC_EXCHANGE = "defaultTopicExchange";
- public static final String OPTIONS_DEFAULT_QUEUE_EXCHANGE = "defaultQueueExchange";
- public static final String OPTIONS_TEMPORARY_TOPIC_EXCHANGE = "temporaryTopicExchange";
- public static final String OPTIONS_TEMPORARY_QUEUE_EXCHANGE = "temporaryQueueExchange";
- public static final byte URL_0_8 = 1;
- public static final byte URL_0_10 = 2;
-
- String getURL();
-
- String getFailoverMethod();
-
- String getFailoverOption(String key);
-
- int getBrokerCount();
-
- BrokerDetails getBrokerDetails(int index);
-
- void addBrokerDetails(BrokerDetails broker);
-
- void setBrokerDetails(List<BrokerDetails> brokers);
-
- List<BrokerDetails> getAllBrokerDetails();
-
- String getClientName();
-
- void setClientName(String clientName);
-
- String getUsername();
-
- void setUsername(String username);
-
- String getPassword();
-
- void setPassword(String password);
-
- String getVirtualHost();
-
- void setVirtualHost(String virtualHost);
-
- String getOption(String key);
-
- void setOption(String key, String value);
-
- AMQShortString getDefaultQueueExchangeName();
-
- AMQShortString getDefaultTopicExchangeName();
-
- AMQShortString getTemporaryQueueExchangeName();
-
- AMQShortString getTemporaryTopicExchangeName();
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/jms/FailoverPolicy.java b/java/client/src/main/java/org/apache/qpid/jms/FailoverPolicy.java
deleted file mode 100644
index 56abf03c81..0000000000
--- a/java/client/src/main/java/org/apache/qpid/jms/FailoverPolicy.java
+++ /dev/null
@@ -1,324 +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.jms;
-
-import org.apache.qpid.jms.failover.FailoverExchangeMethod;
-import org.apache.qpid.jms.failover.FailoverMethod;
-import org.apache.qpid.jms.failover.FailoverRoundRobinServers;
-import org.apache.qpid.jms.failover.FailoverSingleServer;
-import org.apache.qpid.jms.failover.NoFailover;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class FailoverPolicy
-{
- private static final Logger _logger = LoggerFactory.getLogger(FailoverPolicy.class);
-
- private static final long MINUTE = 60000L;
-
- private static final long DEFAULT_METHOD_TIMEOUT = 1 * MINUTE;
-
- private FailoverMethod[] _methods = new FailoverMethod[1];
-
- private int _currentMethod;
-
- private int _methodsRetries;
-
- private int _currentRetry;
-
- private boolean _timing;
-
- private long _lastMethodTime;
- private long _lastFailTime;
-
- public FailoverPolicy(ConnectionURL connectionDetails, Connection conn)
- {
- FailoverMethod method;
-
- // todo This should be integrated in to the connection url when it supports
- // multiple strategies.
-
- _methodsRetries = 0;
-
- if (connectionDetails.getFailoverMethod() == null)
- {
- if (connectionDetails.getBrokerCount() > 1)
- {
- method = new FailoverRoundRobinServers(connectionDetails);
- }
- else
- {
- method = new FailoverSingleServer(connectionDetails);
- }
- }
- else
- {
- String failoverMethod = connectionDetails.getFailoverMethod();
-
- /*
- if (failoverMethod.equals(FailoverMethod.RANDOM))
- {
- //todo write a random connection Failover
- }
- */
- if (failoverMethod.equals(FailoverMethod.SINGLE_BROKER))
- {
- method = new FailoverSingleServer(connectionDetails);
- }
- else
- {
- if (failoverMethod.equals(FailoverMethod.ROUND_ROBIN))
- {
- method = new FailoverRoundRobinServers(connectionDetails);
- }
- else if (failoverMethod.equals(FailoverMethod.FAILOVER_EXCHANGE))
- {
- method = new FailoverExchangeMethod(connectionDetails, conn);
- }
- else if (failoverMethod.equals(FailoverMethod.NO_FAILOVER))
- {
- method = new NoFailover(connectionDetails);
- }
- else
- {
- try
- {
- Class[] constructorSpec = { ConnectionURL.class };
- Object[] params = { connectionDetails };
-
- method =
- (FailoverMethod) ClassLoader.getSystemClassLoader().loadClass(failoverMethod)
- .getConstructor(constructorSpec).newInstance(params);
- }
- catch (Exception cnfe)
- {
- throw new IllegalArgumentException("Unknown failover method:" + failoverMethod, cnfe);
- }
- }
- }
- }
-
- if (method == null)
- {
- throw new IllegalArgumentException("Unknown failover method specified.");
- }
-
- reset();
-
- _methods[_currentMethod] = method;
- }
-
- public FailoverPolicy(FailoverMethod method)
- {
- this(method, 0);
- }
-
- public FailoverPolicy(FailoverMethod method, int retries)
- {
- _methodsRetries = retries;
-
- reset();
-
- _methods[_currentMethod] = method;
- }
-
- private void reset()
- {
- _currentMethod = 0;
- _currentRetry = 0;
- _timing = false;
-
- }
-
- public boolean failoverAllowed()
- {
- boolean failoverAllowed;
-
- if (_timing)
- {
- long now = System.currentTimeMillis();
-
- if ((now - _lastMethodTime) >= DEFAULT_METHOD_TIMEOUT)
- {
- _logger.info("Failover method timeout");
- _lastMethodTime = now;
-
- if (!nextMethod())
- {
- return false;
- }
-
- }
- else
- {
- _lastMethodTime = now;
- }
- }
- else
- {
- _timing = true;
- _lastMethodTime = System.currentTimeMillis();
- _lastFailTime = _lastMethodTime;
- }
-
- if (_methods[_currentMethod].failoverAllowed())
- {
- failoverAllowed = true;
- }
- else
- {
- if (_currentMethod < (_methods.length - 1))
- {
- nextMethod();
- _logger.info("Changing method to " + _methods[_currentMethod].methodName());
-
- return failoverAllowed();
- }
- else
- {
- return cycleMethods();
- }
- }
-
- return failoverAllowed;
- }
-
- private boolean nextMethod()
- {
- if (_currentMethod < (_methods.length - 1))
- {
- _currentMethod++;
- _methods[_currentMethod].reset();
-
- return true;
- }
- else
- {
- return cycleMethods();
- }
- }
-
- private boolean cycleMethods()
- {
- if (_currentRetry < _methodsRetries)
- {
- _currentRetry++;
-
- _currentMethod = 0;
-
- _logger.info("Retrying methods starting with " + _methods[_currentMethod].methodName());
- _methods[_currentMethod].reset();
-
- return failoverAllowed();
- }
- else
- {
- _logger.debug("All failover methods exhausted");
-
- return false;
- }
- }
-
- /**
- * Notification that connection was successful.
- */
- public void attainedConnection()
- {
- _currentRetry = 0;
-
- _methods[_currentMethod].attainedConnection();
-
- _timing = false;
- }
-
- public BrokerDetails getCurrentBrokerDetails()
- {
- return _methods[_currentMethod].getCurrentBrokerDetails();
- }
-
- public BrokerDetails getNextBrokerDetails()
- {
- return _methods[_currentMethod].getNextBrokerDetails();
- }
-
- public void setBroker(BrokerDetails broker)
- {
- _methods[_currentMethod].setBroker(broker);
- }
-
- public void addMethod(FailoverMethod method)
- {
- int len = _methods.length + 1;
- FailoverMethod[] newMethods = new FailoverMethod[len];
- System.arraycopy(_methods, 0, newMethods, 0, _methods.length);
- int index = len - 1;
- newMethods[index] = method;
- _methods = newMethods;
- }
-
- public void setMethodRetries(int retries)
- {
- _methodsRetries = retries;
- }
-
- public FailoverMethod getCurrentMethod()
- {
- if ((_currentMethod >= 0) && (_currentMethod < (_methods.length)))
- {
- return _methods[_currentMethod];
- }
- else
- {
- return null;
- }
- }
-
- public String toString()
- {
- StringBuffer sb = new StringBuffer();
-
- sb.append("Failover Policy:\n");
-
- if (failoverAllowed())
- {
- sb.append("Failover allowed\n");
- }
- else
- {
- sb.append("Failover not allowed\n");
- }
-
- sb.append("Failover policy methods\n");
- for (int i = 0; i < _methods.length; i++)
- {
-
- if (i == _currentMethod)
- {
- sb.append(">");
- }
-
- sb.append(_methods[i].toString());
- }
-
- return sb.toString();
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/jms/Message.java b/java/client/src/main/java/org/apache/qpid/jms/Message.java
deleted file mode 100644
index 53c615a1fd..0000000000
--- a/java/client/src/main/java/org/apache/qpid/jms/Message.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.
- *
- */
-package org.apache.qpid.jms;
-
-import javax.jms.JMSException;
-
-public interface Message extends javax.jms.Message
-{
- public static final String JMS_TYPE = "x-jms-type";
-
- public void acknowledgeThis() throws JMSException;
-}
diff --git a/java/client/src/main/java/org/apache/qpid/jms/MessageConsumer.java b/java/client/src/main/java/org/apache/qpid/jms/MessageConsumer.java
deleted file mode 100644
index caac2b5c1f..0000000000
--- a/java/client/src/main/java/org/apache/qpid/jms/MessageConsumer.java
+++ /dev/null
@@ -1,27 +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.jms;
-
-/**
- */
-public interface MessageConsumer extends javax.jms.MessageConsumer
-{
-}
diff --git a/java/client/src/main/java/org/apache/qpid/jms/MessageProducer.java b/java/client/src/main/java/org/apache/qpid/jms/MessageProducer.java
deleted file mode 100644
index b830c377b8..0000000000
--- a/java/client/src/main/java/org/apache/qpid/jms/MessageProducer.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.jms;
-
-import java.io.UnsupportedEncodingException;
-
-import javax.jms.Destination;
-import javax.jms.JMSException;
-import javax.jms.Message;
-
-/**
- */
-public interface MessageProducer extends javax.jms.MessageProducer
-{
- /**
- * Set the default MIME type for messages produced by this producer. This reduces the overhead of each message.
- * @param mimeType
- */
- void setMimeType(String mimeType) throws JMSException;
-
- /**
- * Set the default encoding for messages produced by this producer. This reduces the overhead of each message.
- * @param encoding the encoding as understood by XXXX how do I specify this?? RG
- * @throws UnsupportedEncodingException if the encoding is not understood
- */
- void setEncoding(String encoding) throws UnsupportedEncodingException, JMSException;
-
- void send(Destination destination, Message message, int deliveryMode,
- int priority, long timeToLive, boolean immediate)
- throws JMSException;
-
- void send(Destination destination, Message message, int deliveryMode,
- int priority, long timeToLive, boolean mandatory, boolean immediate)
- throws JMSException;
-
- void send(Destination destination, Message message, int deliveryMode, int priority, long timeToLive,
- boolean mandatory, boolean immediate, boolean waitUntilSent) throws JMSException;
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/jms/Session.java b/java/client/src/main/java/org/apache/qpid/jms/Session.java
deleted file mode 100644
index 5287381fae..0000000000
--- a/java/client/src/main/java/org/apache/qpid/jms/Session.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.jms;
-
-import org.apache.qpid.framing.AMQShortString;
-
-import javax.jms.Destination;
-import javax.jms.JMSException;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-
-
-public interface Session extends javax.jms.Session
-{
- /**
- * Indicates that no client acknowledgements are required. Broker assumes that once it has delivered
- * a message packet successfully it is acknowledged.
- */
- static final int NO_ACKNOWLEDGE = 257;
-
- /**
- * Pre acknowledge means that an ack is sent per message but sent before user code has processed
- * the message (i.e. before the onMessage() call or the receive() method has returned).
- */
- static final int PRE_ACKNOWLEDGE = 258;
-
- MessageConsumer createConsumer(Destination destination,
- int prefetch,
- boolean noLocal,
- boolean exclusive,
- String selector) throws JMSException;
-
- MessageConsumer createConsumer(Destination destination,
- int prefetchHigh,
- int prefetchLow,
- boolean noLocal,
- boolean exclusive,
- String selector) throws JMSException;
-
- /**
- * @return the prefetch value used by default for consumers created on this session.
- */
- int getDefaultPrefetch();
-
- /**
- * @return the High water prefetch value used by default for consumers created on this session.
- */
- int getDefaultPrefetchHigh();
-
- /**
- * @return the Low water prefetch value used by default for consumers created on this session.
- */
- int getDefaultPrefetchLow();
-
- /**
- * Create a producer
- * @param destination
- * @param mandatory the value of the mandatory flag used by default on the producer
- * @param immediate the value of the immediate flag used by default on the producer
- * @return
- * @throws JMSException
- */
- MessageProducer createProducer(Destination destination, boolean mandatory, boolean immediate)
- throws JMSException;
-
- /**
- * Create a producer
- * @param destination
- * @param immediate the value of the immediate flag used by default on the producer
- * @return
- * @throws JMSException
- */
- MessageProducer createProducer(Destination destination, boolean immediate)
- throws JMSException;
-
- AMQShortString getTemporaryTopicExchangeName();
-
- AMQShortString getDefaultQueueExchangeName();
-
- AMQShortString getDefaultTopicExchangeName();
-
- AMQShortString getTemporaryQueueExchangeName();
-}
diff --git a/java/client/src/main/java/org/apache/qpid/jms/TopicSubscriber.java b/java/client/src/main/java/org/apache/qpid/jms/TopicSubscriber.java
deleted file mode 100644
index 1dbe464230..0000000000
--- a/java/client/src/main/java/org/apache/qpid/jms/TopicSubscriber.java
+++ /dev/null
@@ -1,32 +0,0 @@
-package org.apache.qpid.jms;
-/*
- *
- * 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 javax.jms.Topic;
-
-public interface TopicSubscriber extends javax.jms.TopicSubscriber
-{
-
- void addBindingKey(Topic topic, String bindingKey) throws AMQException;
-}
diff --git a/java/client/src/main/java/org/apache/qpid/jms/failover/FailoverExchangeMethod.java b/java/client/src/main/java/org/apache/qpid/jms/failover/FailoverExchangeMethod.java
deleted file mode 100644
index ef30f2adbc..0000000000
--- a/java/client/src/main/java/org/apache/qpid/jms/failover/FailoverExchangeMethod.java
+++ /dev/null
@@ -1,320 +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.jms.failover;
-
-import java.net.InetAddress;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageListener;
-import javax.jms.Session;
-
-import org.apache.qpid.client.AMQAnyDestination;
-import org.apache.qpid.client.AMQBrokerDetails;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.jms.BrokerDetails;
-import org.apache.qpid.jms.Connection;
-import org.apache.qpid.jms.ConnectionURL;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * When using the Failover exchange a single broker is supplied in the URL.
- * The connection will then connect to the cluster using the above broker details.
- * Once connected, the membership details of the cluster will be obtained via
- * subscribing to a queue bound to the failover exchange.
- *
- * The failover exchange will provide a list of broker URLs in the format "transport:ip:port"
- * Out of this list we only select brokers that match the transport of the original
- * broker supplied in the connection URL.
- *
- * Also properties defined for the original broker will be applied to all the brokers selected
- * from the list.
- */
-
-public class FailoverExchangeMethod implements FailoverMethod, MessageListener
-{
- private static final Logger _logger = LoggerFactory.getLogger(FailoverExchangeMethod.class);
-
- /** This is not safe to use until attainConnection is called */
- private Connection _conn;
-
- /** Protects the broker list when modifications happens */
- private Object _brokerListLock = new Object();
-
- /** The session used to subscribe to failover exchange */
- private Session _ssn;
-
- private BrokerDetails _originalBrokerDetail;
-
- /** The index into the hostDetails array of the broker to which we are connected */
- private int _currentBrokerIndex = 0;
-
- /** The broker currently selected **/
- private BrokerDetails _currentBrokerDetail;
-
- /** Array of BrokerDetail used to make connections. */
- private ConnectionURL _connectionDetails;
-
- /** Denotes the number of failed attempts **/
- private int _failedAttemps = 0;
-
- public FailoverExchangeMethod(ConnectionURL connectionDetails, Connection conn)
- {
- _connectionDetails = connectionDetails;
- _originalBrokerDetail = _connectionDetails.getBrokerDetails(0);
-
- // This is not safe to use until attainConnection is called, as this ref will not initialized fully.
- // The reason being this constructor is called inside the AMWConnection constructor.
- // It would be best if we find a way to pass this ref after AMQConnection is fully initialized.
- _conn = conn;
- }
-
- private void subscribeForUpdates() throws JMSException
- {
- if (_ssn == null)
- {
- _ssn = _conn.createSession(false,Session.AUTO_ACKNOWLEDGE);
- MessageConsumer cons = _ssn.createConsumer(
- new AMQAnyDestination(new AMQShortString("amq.failover"),
- new AMQShortString("amq.failover"),
- new AMQShortString(""),
- true,true,null,false,
- new AMQShortString[0]));
- cons.setMessageListener(this);
- }
- }
-
- public void onMessage(Message m)
- {
- _logger.info("Failover exchange notified cluster membership change");
-
- String currentBrokerIP = "";
- try
- {
- currentBrokerIP = InetAddress.getByName(_currentBrokerDetail.getHost()).getHostAddress();
- }
- catch(Exception e)
- {
- _logger.warn("Unable to resolve current broker host name",e);
- }
-
- List<BrokerDetails> brokerList = new ArrayList<BrokerDetails>();
- try
- {
- List<String> list = (List<String>)m.getObjectProperty("amq.failover");
- for (String brokerEntry:list)
- {
- String[] urls = brokerEntry.substring(5) .split(",");
- // Iterate until you find the correct transport
- // Need to reconsider the logic when the C++ broker supports
- // SSL URLs.
- for (String url:urls)
- {
- String[] tokens = url.split(":");
- if (tokens[0].equalsIgnoreCase(_originalBrokerDetail.getTransport()))
- {
- BrokerDetails broker = new AMQBrokerDetails();
- broker.setTransport(tokens[0]);
- broker.setHost(tokens[1]);
- broker.setPort(Integer.parseInt(tokens[2]));
- broker.setProperties(_originalBrokerDetail.getProperties());
- broker.setSSLConfiguration(_originalBrokerDetail.getSSLConfiguration());
- brokerList.add(broker);
-
- if (currentBrokerIP.equals(broker.getHost()) &&
- _currentBrokerDetail.getPort() == broker.getPort())
- {
- _currentBrokerIndex = brokerList.indexOf(broker);
- }
-
- break;
- }
- }
- }
- }
- catch(JMSException e)
- {
- _logger.error("Error parsing the message sent by failover exchange",e);
- }
-
- synchronized (_brokerListLock)
- {
- _connectionDetails.setBrokerDetails(brokerList);
- }
-
- _logger.info("============================================================");
- _logger.info("Updated cluster membership details " + _connectionDetails);
- _logger.info("============================================================");
- }
-
- public void attainedConnection()
- {
- try
- {
- _failedAttemps = 0;
- _logger.info("============================================================");
- _logger.info("Attained connection ");
- _logger.info("============================================================");
- subscribeForUpdates();
- }
- catch (JMSException e)
- {
- throw new RuntimeException("Unable to subscribe for cluster membership updates",e);
- }
- }
-
- public BrokerDetails getCurrentBrokerDetails()
- {
- synchronized (_brokerListLock)
- {
- _currentBrokerDetail = _connectionDetails.getBrokerDetails(_currentBrokerIndex);
- return _currentBrokerDetail;
- }
- }
-
- public BrokerDetails getNextBrokerDetails()
- {
- BrokerDetails broker = null;
-
- synchronized(_brokerListLock)
- {
- if (_currentBrokerIndex == (_connectionDetails.getBrokerCount() - 1))
- {
- _currentBrokerIndex = 0;
- }
- else
- {
- _currentBrokerIndex++;
- }
-
- broker = _connectionDetails.getBrokerDetails(_currentBrokerIndex);
-
- // When the broker list is updated it will include the current broker as well
- // There is no point trying it again, so trying the next one.
- if (_currentBrokerDetail != null &&
- broker.getHost().equals(_currentBrokerDetail.getHost()) &&
- broker.getPort() == _currentBrokerDetail.getPort())
- {
- if (_connectionDetails.getBrokerCount() > 1)
- {
- return getNextBrokerDetails();
- }
- else
- {
- _failedAttemps ++;
- return null;
- }
- }
- }
-
- String delayStr = broker.getProperty(BrokerDetails.OPTIONS_CONNECT_DELAY);
- if (delayStr != null)
- {
- Long delay = Long.parseLong(delayStr);
- _logger.info("Delay between connect retries:" + delay);
- try
- {
- Thread.sleep(delay);
- }
- catch (InterruptedException ie)
- {
- return null;
- }
- }
- else
- {
- _logger.info("No delay between connect retries, use tcp://host:port?connectdelay='value' to enable.");
- }
-
- _failedAttemps ++;
- _currentBrokerDetail = broker;
-
- return broker;
- }
-
- public boolean failoverAllowed()
- {
- // We allow to Failover provided
- // our broker list is not empty and
- // we haven't gone through all of them
-
- boolean b = _connectionDetails.getBrokerCount() > 0 &&
- _failedAttemps <= _connectionDetails.getBrokerCount();
-
-
- _logger.info("============================================================");
- _logger.info(toString());
- _logger.info("FailoverAllowed " + b);
- _logger.info("============================================================");
-
- return b;
- }
-
- public void reset()
- {
- _failedAttemps = 0;
- }
-
- public void setBroker(BrokerDetails broker)
- {
- // not sure if this method is needed
- }
-
- public void setRetries(int maxRetries)
- {
- // no max retries we keep trying as long
- // as we get updates
- }
-
- public String methodName()
- {
- return "Failover Exchange";
- }
-
- public String toString()
- {
- StringBuffer sb = new StringBuffer();
- sb.append("FailoverExchange:\n");
- sb.append("\n Current Broker Index:");
- sb.append(_currentBrokerIndex);
- sb.append("\n Failed Attempts:");
- sb.append(_failedAttemps);
- sb.append("\n Orignal broker details:");
- sb.append(_originalBrokerDetail).append("\n");
- sb.append("\n -------- Broker List -----------\n");
- for (int i = 0; i < _connectionDetails.getBrokerCount(); i++)
- {
- if (i == _currentBrokerIndex)
- {
- sb.append(">");
- }
-
- sb.append(_connectionDetails.getBrokerDetails(i));
- sb.append("\n");
- }
- sb.append("--------------------------------\n");
- return sb.toString();
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/jms/failover/FailoverMethod.java b/java/client/src/main/java/org/apache/qpid/jms/failover/FailoverMethod.java
deleted file mode 100644
index 1cef067e5f..0000000000
--- a/java/client/src/main/java/org/apache/qpid/jms/failover/FailoverMethod.java
+++ /dev/null
@@ -1,79 +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.jms.failover;
-
-import org.apache.qpid.jms.BrokerDetails;
-
-public interface FailoverMethod
-{
- public static final String SINGLE_BROKER = "singlebroker";
- public static final String ROUND_ROBIN = "roundrobin";
- public static final String FAILOVER_EXCHANGE= "failover_exchange";
- public static final String RANDOM = "random";
- public static final String NO_FAILOVER = "nofailover";
-
- /**
- * Reset the Failover to initial conditions
- */
- void reset();
-
- /**
- * Check if failover is possible for this method
- *
- * @return true if failover is allowed
- */
- boolean failoverAllowed();
-
- /**
- * Notification to the Failover method that a connection has been attained.
- */
- void attainedConnection();
-
- /**
- * If there is no current BrokerDetails the null will be returned.
- * @return The current BrokerDetail value to use
- */
- BrokerDetails getCurrentBrokerDetails();
-
- /**
- * Move to the next BrokerDetails if one is available.
- * @return the next BrokerDetail or null if there is none.
- */
- BrokerDetails getNextBrokerDetails();
-
- /**
- * Set the currently active broker to be the new value.
- * @param broker The new BrokerDetail value
- */
- void setBroker(BrokerDetails broker);
-
- /**
- * Set the retries for this method
- * @param maxRetries the maximum number of time to retry this Method
- */
- void setRetries(int maxRetries);
-
- /**
- * @return The name of this method for display purposes.
- */
- String methodName();
-}
diff --git a/java/client/src/main/java/org/apache/qpid/jms/failover/FailoverRoundRobinServers.java b/java/client/src/main/java/org/apache/qpid/jms/failover/FailoverRoundRobinServers.java
deleted file mode 100644
index 41ba4974ec..0000000000
--- a/java/client/src/main/java/org/apache/qpid/jms/failover/FailoverRoundRobinServers.java
+++ /dev/null
@@ -1,253 +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.jms.failover;
-
-import org.apache.qpid.jms.BrokerDetails;
-import org.apache.qpid.jms.ConnectionURL;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class FailoverRoundRobinServers implements FailoverMethod
-{
- private static final Logger _logger = LoggerFactory.getLogger(FailoverRoundRobinServers.class);
-
- /** The default number of times to cycle through all servers */
- public static final int DEFAULT_CYCLE_RETRIES = 1;
- /** The default number of times to retry each server */
- public static final int DEFAULT_SERVER_RETRIES = 0;
-
- /** The index into the hostDetails array of the broker to which we are connected */
- private int _currentBrokerIndex = 0;
-
- /** The number of times to retry connecting for each server */
- private int _serverRetries;
-
- /** The current number of retry attempts made */
- private int _currentServerRetry = 0;
-
- /** The number of times to cycle through the servers */
- private int _cycleRetries;
-
- /** The current number of cycles performed. */
- private int _currentCycleRetries = 0;
-
- /** Array of BrokerDetail used to make connections. */
- protected ConnectionURL _connectionDetails;
-
- public FailoverRoundRobinServers(ConnectionURL connectionDetails)
- {
- if (!(connectionDetails.getBrokerCount() > 0))
- {
- throw new IllegalArgumentException("At least one broker details must be specified.");
- }
-
- _connectionDetails = connectionDetails;
-
- // There is no current broker at startup so set it to -1.
- _currentBrokerIndex = 0;
-
- String cycleRetries = _connectionDetails.getFailoverOption(ConnectionURL.OPTIONS_FAILOVER_CYCLE);
-
- _cycleRetries = DEFAULT_CYCLE_RETRIES;
-
- if (cycleRetries != null)
- {
- try
- {
- _cycleRetries = Integer.parseInt(cycleRetries);
- }
- catch (NumberFormatException nfe)
- {
- _logger.warn("Cannot set cycle Retries, " + cycleRetries + " is not a number. Using default: " + DEFAULT_CYCLE_RETRIES);
- }
- }
-
- _currentCycleRetries = 0;
-
- _serverRetries = 0;
- _currentServerRetry = 0;
- }
-
- public void reset()
- {
- _currentBrokerIndex = 0;
- _currentCycleRetries = 0;
- _currentServerRetry = 0;
- }
-
- public boolean failoverAllowed()
- {
- _logger.info("==== Checking failoverAllowed() ====");
- _logger.info(toString());
- _logger.info("====================================");
- return ((_currentCycleRetries < _cycleRetries) || (_currentServerRetry < _serverRetries));
- }
-
- public void attainedConnection()
- {
- _currentCycleRetries = 0;
- _currentServerRetry = 0;
- }
-
- public BrokerDetails getCurrentBrokerDetails()
- {
- return _connectionDetails.getBrokerDetails(_currentBrokerIndex);
- }
-
- public BrokerDetails getNextBrokerDetails()
- {
- boolean doDelay = false;
-
- if (_currentBrokerIndex == (_connectionDetails.getBrokerCount() - 1))
- {
- if (_currentServerRetry < _serverRetries)
- {
- _logger.info("Trying " + _connectionDetails.getBrokerDetails(_currentBrokerIndex));
- doDelay= _currentBrokerIndex != 0;
- _currentServerRetry++;
- }
- else
- {
- _currentCycleRetries++;
- // failed to connect to first broker
- _currentBrokerIndex = 0;
-
- setBroker(_connectionDetails.getBrokerDetails(_currentBrokerIndex));
-
- // This is zero rather than -1 as we are already retrieving the details.
- _currentServerRetry = 0;
- }
- // else - should force client to stop as max retries has been reached.
- }
- else
- {
- if (_currentServerRetry < _serverRetries)
- {
- _logger.info("Trying " + _connectionDetails.getBrokerDetails(_currentBrokerIndex));
- doDelay= _currentBrokerIndex != 0;
-
- _currentServerRetry++;
- }
- else
- {
- _currentBrokerIndex++;
-
- setBroker(_connectionDetails.getBrokerDetails(_currentBrokerIndex));
- // This is zero rather than -1 as we are already retrieving the details.
- _currentServerRetry = 0;
- }
- }
-
- BrokerDetails broker = _connectionDetails.getBrokerDetails(_currentBrokerIndex);
-
- String delayStr = broker.getProperty(BrokerDetails.OPTIONS_CONNECT_DELAY);
- if (delayStr != null && doDelay)
- {
- Long delay = Long.parseLong(delayStr);
- _logger.info("Delay between connect retries:" + delay);
- try
- {
- Thread.sleep(delay);
- }
- catch (InterruptedException ie)
- {
- return null;
- }
- }
- else
- {
- // Only display if option not set. Not if deDelay==false.
- if (delayStr == null)
- {
- _logger.info("No delay between connect retries, use tcp://host:port?connectdelay='value' to enable.");
- }
- }
-
- return broker;
- }
-
- public void setBroker(BrokerDetails broker)
- {
-
- _connectionDetails.addBrokerDetails(broker);
-
- int index = _connectionDetails.getAllBrokerDetails().indexOf(broker);
-
- String serverRetries = broker.getProperty(BrokerDetails.OPTIONS_RETRY);
-
- if (serverRetries != null)
- {
- try
- {
- _serverRetries = Integer.parseInt(serverRetries);
- }
- catch (NumberFormatException nfe)
- {
- _serverRetries = DEFAULT_SERVER_RETRIES;
- }
- }
-
- _currentServerRetry = 0;
- _currentBrokerIndex = index;
- }
-
- public void setRetries(int maxRetries)
- {
- _cycleRetries = maxRetries;
- }
-
- public String methodName()
- {
- return "Cycle Servers";
- }
-
- public String toString()
- {
- StringBuffer sb = new StringBuffer();
-
- sb.append("Cycle Servers:\n");
-
- sb.append("Cycle Retries:");
- sb.append(_cycleRetries);
- sb.append("\nCurrent Cycle:");
- sb.append(_currentCycleRetries);
- sb.append("\nServer Retries:");
- sb.append(_serverRetries);
- sb.append("\nCurrent Retry:");
- sb.append(_currentServerRetry);
- sb.append("\nCurrent Broker:");
- sb.append(_currentBrokerIndex);
- sb.append("\n");
-
- for (int i = 0; i < _connectionDetails.getBrokerCount(); i++)
- {
- if (i == _currentBrokerIndex)
- {
- sb.append(">");
- }
-
- sb.append(_connectionDetails.getBrokerDetails(i));
- sb.append("\n");
- }
-
- return sb.toString();
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/jms/failover/FailoverSingleServer.java b/java/client/src/main/java/org/apache/qpid/jms/failover/FailoverSingleServer.java
deleted file mode 100644
index d033a49f5c..0000000000
--- a/java/client/src/main/java/org/apache/qpid/jms/failover/FailoverSingleServer.java
+++ /dev/null
@@ -1,166 +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.jms.failover;
-
-import org.apache.qpid.jms.BrokerDetails;
-import org.apache.qpid.jms.ConnectionURL;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class FailoverSingleServer implements FailoverMethod
-{
- private static final Logger _logger = LoggerFactory.getLogger(FailoverSingleServer.class);
-
- /** The default number of times to rety a conection to this server */
- public static final int DEFAULT_SERVER_RETRIES = 0;
-
- /** The details of the Single Server */
- private BrokerDetails _brokerDetail;
-
- /** The number of times to retry connecting to the sever */
- protected int _retries;
-
- /** The current number of attempts made to the server */
- protected int _currentRetries = 0;
-
-
- public FailoverSingleServer(ConnectionURL connectionDetails)
- {
- if (connectionDetails.getBrokerCount() > 0)
- {
- setBroker(connectionDetails.getBrokerDetails(0));
- }
- else
- {
- throw new IllegalArgumentException("BrokerDetails details required for connection.");
- }
- }
-
- public FailoverSingleServer(BrokerDetails brokerDetail)
- {
- setBroker(brokerDetail);
- }
-
- public void reset()
- {
- _currentRetries = 0;
- }
-
- public boolean failoverAllowed()
- {
- return _currentRetries < _retries;
- }
-
- public void attainedConnection()
- {
- reset();
- }
-
- public BrokerDetails getCurrentBrokerDetails()
- {
- return _brokerDetail;
- }
-
- public BrokerDetails getNextBrokerDetails()
- {
- if (_currentRetries == _retries)
- {
- return null;
- }
- else
- {
- if (_currentRetries < _retries)
- {
- _currentRetries++;
- }
- }
-
-
- String delayStr = _brokerDetail.getProperty(BrokerDetails.OPTIONS_CONNECT_DELAY);
- if (delayStr != null && _currentRetries > 0)
- {
- Long delay = Long.parseLong(delayStr);
- _logger.info("Delay between connect retries:" + delay);
- try
- {
-
- Thread.sleep(delay);
- }
- catch (InterruptedException ie)
- {
- return null;
- }
- }
- else
- {
- _logger.info("No delay between connect retries, use tcp://host:port?connectdelay='value' to enable.");
- }
-
- return _brokerDetail;
- }
-
- public void setBroker(BrokerDetails broker)
- {
- if (broker == null)
- {
- throw new IllegalArgumentException("BrokerDetails details cannot be null");
- }
- _brokerDetail = broker;
-
- String retries = broker.getProperty(BrokerDetails.OPTIONS_RETRY);
- if (retries != null)
- {
- try
- {
- _retries = Integer.parseInt(retries);
- }
- catch (NumberFormatException nfe)
- {
- _retries = DEFAULT_SERVER_RETRIES;
- }
- }
- else
- {
- _retries = DEFAULT_SERVER_RETRIES;
- }
-
- reset();
- }
-
- public void setRetries(int retries)
- {
- _retries = retries;
- }
-
- public String methodName()
- {
- return "Single Server";
- }
-
- public String toString()
- {
- return methodName()+":\n" +
- "Max Retries:" + _retries +
- "\nCurrent Retry:" + _currentRetries +
- "\n" + _brokerDetail + "\n";
- }
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/jms/failover/NoFailover.java b/java/client/src/main/java/org/apache/qpid/jms/failover/NoFailover.java
deleted file mode 100644
index 1231324397..0000000000
--- a/java/client/src/main/java/org/apache/qpid/jms/failover/NoFailover.java
+++ /dev/null
@@ -1,62 +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.jms.failover;
-
-import org.apache.qpid.jms.BrokerDetails;
-import org.apache.qpid.jms.ConnectionURL;
-
-/**
- * Extend the Single Server Model to gain retry functionality but once connected do not attempt to failover.
- */
-public class NoFailover extends FailoverSingleServer
-{
- private boolean _connected = false;
-
- public NoFailover(BrokerDetails brokerDetail)
- {
- super(brokerDetail);
- }
-
- public NoFailover(ConnectionURL connectionDetails)
- {
- super(connectionDetails);
- }
-
- @Override
- public void attainedConnection()
- {
- _connected=true;
- _currentRetries = _retries;
- }
-
- @Override
- public String methodName()
- {
- return "NoFailover";
- }
-
- @Override
- public String toString()
- {
- return super.toString() + (_connected ? "Connection attained." : "Never connected.") + "\n";
- }
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/jndi/Example.properties b/java/client/src/main/java/org/apache/qpid/jndi/Example.properties
deleted file mode 100644
index def53d8494..0000000000
--- a/java/client/src/main/java/org/apache/qpid/jndi/Example.properties
+++ /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.
-#
-java.naming.factory.initial = org.apache.qpid.jndi.PropertiesFileInitialConextFactory
-
-# use the following property to configure the default connector
-#java.naming.provider.url - ignored.
-
-# register some connection factories
-# connectionfactory.[jndiname] = [ConnectionURL]
-connectionfactory.local = amqp://guest:guest@clientid/testpath?brokerlist='vm://:1'
-
-# register some queues in JNDI using the form
-# queue.[jndiName] = [physicalName]
-queue.MyQueue = example.MyQueue
-
-# register some topics in JNDI using the form
-# topic.[jndiName] = [physicalName]
-topic.ibmStocks = stocks.nyse.ibm
-
-# Register an AMQP destination in JNDI
-# NOTE: Qpid currently only supports direct,topics and headers
-# destination.[jniName] = [BindingURL]
-destination.direct = direct://amq.direct//directQueue
-destination.directQueue = direct://amq.direct//message_queue?routingkey="routing_key"
diff --git a/java/client/src/main/java/org/apache/qpid/jndi/NameParserImpl.java b/java/client/src/main/java/org/apache/qpid/jndi/NameParserImpl.java
deleted file mode 100644
index a3174aec7a..0000000000
--- a/java/client/src/main/java/org/apache/qpid/jndi/NameParserImpl.java
+++ /dev/null
@@ -1,37 +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.jndi;
-
-import javax.naming.CompositeName;
-import javax.naming.Name;
-import javax.naming.NameParser;
-import javax.naming.NamingException;
-
-/**
- * A default implementation of {@link NameParser}
- * <p/>
- * Based on class from ActiveMQ.
- */
-public class NameParserImpl implements NameParser
-{
- public Name parse(String name) throws NamingException
- {
- return new CompositeName(name);
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/jndi/PropertiesFileInitialContextFactory.java b/java/client/src/main/java/org/apache/qpid/jndi/PropertiesFileInitialContextFactory.java
deleted file mode 100644
index fec5af55c1..0000000000
--- a/java/client/src/main/java/org/apache/qpid/jndi/PropertiesFileInitialContextFactory.java
+++ /dev/null
@@ -1,369 +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.jndi;
-
-import java.io.BufferedInputStream;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.net.URISyntaxException;
-import java.util.Hashtable;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Properties;
-import java.util.concurrent.ConcurrentHashMap;
-
-import javax.jms.ConnectionFactory;
-import javax.jms.Destination;
-import javax.jms.Queue;
-import javax.jms.Topic;
-import javax.naming.Context;
-import javax.naming.NamingException;
-import javax.naming.spi.InitialContextFactory;
-
-import org.apache.qpid.client.AMQConnectionFactory;
-import org.apache.qpid.client.AMQDestination;
-import org.apache.qpid.client.AMQHeadersExchange;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.client.AMQTopic;
-import org.apache.qpid.exchange.ExchangeDefaults;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.url.AMQBindingURL;
-import org.apache.qpid.url.BindingURL;
-import org.apache.qpid.url.URLSyntaxException;
-import org.apache.qpid.util.Strings;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class PropertiesFileInitialContextFactory implements InitialContextFactory
-{
- protected final Logger _logger = LoggerFactory.getLogger(PropertiesFileInitialContextFactory.class);
-
- private String CONNECTION_FACTORY_PREFIX = "connectionfactory.";
- private String DESTINATION_PREFIX = "destination.";
- private String QUEUE_PREFIX = "queue.";
- private String TOPIC_PREFIX = "topic.";
-
- public Context getInitialContext(Hashtable environment) throws NamingException
- {
- Map data = new ConcurrentHashMap();
-
- try
- {
-
- String file = null;
- if (environment.containsKey(Context.PROVIDER_URL))
- {
- file = (String) environment.get(Context.PROVIDER_URL);
- }
- else
- {
- file = System.getProperty(Context.PROVIDER_URL);
- }
-
- if (file != null)
- {
- _logger.info("Loading Properties from:" + file);
-
- // Load the properties specified
- BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file));
- Properties p = new Properties();
- try
- {
- p.load(inputStream);
- }
- finally
- {
- inputStream.close();
- }
-
- Strings.Resolver resolver = new Strings.ChainedResolver
- (Strings.SYSTEM_RESOLVER, new Strings.PropertiesResolver(p));
-
- for (Map.Entry me : p.entrySet())
- {
- String key = (String) me.getKey();
- String value = (String) me.getValue();
- String expanded = Strings.expand(value, resolver);
- environment.put(key, expanded);
- if (System.getProperty(key) == null)
- {
- System.setProperty(key, expanded);
- }
- }
- _logger.info("Loaded Context Properties:" + environment.toString());
- }
- else
- {
- _logger.info("No Provider URL specified.");
- }
- }
- catch (IOException ioe)
- {
- _logger.warn("Unable to load property file specified in Provider_URL:" + environment.get(Context.PROVIDER_URL) +"\n" +
- "Due to:"+ioe.getMessage());
- }
-
- createConnectionFactories(data, environment);
-
- createDestinations(data, environment);
-
- createQueues(data, environment);
-
- createTopics(data, environment);
-
- return createContext(data, environment);
- }
-
- // Implementation methods
- // -------------------------------------------------------------------------
- protected ReadOnlyContext createContext(Map data, Hashtable environment)
- {
- return new ReadOnlyContext(environment, data);
- }
-
- protected void createConnectionFactories(Map data, Hashtable environment)
- {
- for (Iterator iter = environment.entrySet().iterator(); iter.hasNext();)
- {
- Map.Entry entry = (Map.Entry) iter.next();
- String key = entry.getKey().toString();
- if (key.startsWith(CONNECTION_FACTORY_PREFIX))
- {
- String jndiName = key.substring(CONNECTION_FACTORY_PREFIX.length());
- ConnectionFactory cf = createFactory(entry.getValue().toString().trim());
- if (cf != null)
- {
- data.put(jndiName, cf);
- }
- }
- }
- }
-
- protected void createDestinations(Map data, Hashtable environment)
- {
- for (Iterator iter = environment.entrySet().iterator(); iter.hasNext();)
- {
- Map.Entry entry = (Map.Entry) iter.next();
- String key = entry.getKey().toString();
- if (key.startsWith(DESTINATION_PREFIX))
- {
- String jndiName = key.substring(DESTINATION_PREFIX.length());
- Destination dest = createDestination(entry.getValue().toString().trim());
- if (dest != null)
- {
- data.put(jndiName, dest);
- }
- }
- }
- }
-
- protected void createQueues(Map data, Hashtable environment)
- {
- for (Iterator iter = environment.entrySet().iterator(); iter.hasNext();)
- {
- Map.Entry entry = (Map.Entry) iter.next();
- String key = entry.getKey().toString();
- if (key.startsWith(QUEUE_PREFIX))
- {
- String jndiName = key.substring(QUEUE_PREFIX.length());
- Queue q = createQueue(entry.getValue().toString().trim());
- if (q != null)
- {
- data.put(jndiName, q);
- }
- }
- }
- }
-
- protected void createTopics(Map data, Hashtable environment)
- {
- for (Iterator iter = environment.entrySet().iterator(); iter.hasNext();)
- {
- Map.Entry entry = (Map.Entry) iter.next();
- String key = entry.getKey().toString();
- if (key.startsWith(TOPIC_PREFIX))
- {
- String jndiName = key.substring(TOPIC_PREFIX.length());
- Topic t = createTopic(entry.getValue().toString().trim());
- if (t != null)
- {
- if (_logger.isDebugEnabled())
- {
- StringBuffer b = new StringBuffer();
- b.append("Creating the topic: " + jndiName + " with the following binding keys ");
- for (AMQShortString binding:((AMQTopic)t).getBindingKeys())
- {
- b.append(binding.toString()).append(",");
- }
-
- _logger.debug(b.toString());
- }
- data.put(jndiName, t);
- }
- }
- }
- }
-
- /**
- * Factory method to create new Connection Factory instances
- */
- protected ConnectionFactory createFactory(String url)
- {
- try
- {
- return new AMQConnectionFactory(url);
- }
- catch (URLSyntaxException urlse)
- {
- _logger.warn("Unable to createFactories:" + urlse);
- }
-
- return null;
- }
-
- /**
- * Factory method to create new Destination instances from an AMQP BindingURL
- */
- protected Destination createDestination(String str)
- {
- try
- {
- return AMQDestination.createDestination(str);
- }
- catch (Exception e)
- {
- _logger.warn("Unable to create destination:" + e, e);
-
- return null;
- }
- }
-
- /**
- * Factory method to create new Queue instances
- */
- protected Queue createQueue(Object value)
- {
- if (value instanceof AMQShortString)
- {
- return new AMQQueue(ExchangeDefaults.DIRECT_EXCHANGE_NAME, (AMQShortString) value);
- }
- else if (value instanceof String)
- {
- return new AMQQueue(ExchangeDefaults.DIRECT_EXCHANGE_NAME, new AMQShortString((String) value));
- }
- else if (value instanceof BindingURL)
- {
- return new AMQQueue((BindingURL) value);
- }
-
- return null;
- }
-
- /**
- * Factory method to create new Topic instances
- */
- protected Topic createTopic(Object value)
- {
- if (value instanceof AMQShortString)
- {
- return new AMQTopic(ExchangeDefaults.TOPIC_EXCHANGE_NAME, (AMQShortString) value);
- }
- else if (value instanceof String)
- {
- String[] keys = ((String)value).split(",");
- AMQShortString[] bindings = new AMQShortString[keys.length];
- int i = 0;
- for (String key:keys)
- {
- bindings[i] = new AMQShortString(key.trim());
- i++;
- }
- // The Destination has a dual nature. If this was used for a producer the key is used
- // for the routing key. If it was used for the consumer it becomes the bindingKey
- return new AMQTopic(ExchangeDefaults.TOPIC_EXCHANGE_NAME,bindings[0],null,bindings);
- }
- else if (value instanceof BindingURL)
- {
- return new AMQTopic((BindingURL) value);
- }
-
- return null;
- }
-
- /**
- * Factory method to create new HeaderExcahnge instances
- */
- protected Destination createHeaderExchange(Object value)
- {
- if (value instanceof String)
- {
- return new AMQHeadersExchange((String) value);
- }
- else if (value instanceof BindingURL)
- {
- return new AMQHeadersExchange((BindingURL) value);
- }
-
- return null;
- }
-
- // Properties
- // -------------------------------------------------------------------------
- public String getConnectionPrefix()
- {
- return CONNECTION_FACTORY_PREFIX;
- }
-
- public void setConnectionPrefix(String connectionPrefix)
- {
- this.CONNECTION_FACTORY_PREFIX = connectionPrefix;
- }
-
- public String getDestinationPrefix()
- {
- return DESTINATION_PREFIX;
- }
-
- public void setDestinationPrefix(String destinationPrefix)
- {
- this.DESTINATION_PREFIX = destinationPrefix;
- }
-
- public String getQueuePrefix()
- {
- return QUEUE_PREFIX;
- }
-
- public void setQueuePrefix(String queuePrefix)
- {
- this.QUEUE_PREFIX = queuePrefix;
- }
-
- public String getTopicPrefix()
- {
- return TOPIC_PREFIX;
- }
-
- public void setTopicPrefix(String topicPrefix)
- {
- this.TOPIC_PREFIX = topicPrefix;
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/jndi/ReadOnlyContext.java b/java/client/src/main/java/org/apache/qpid/jndi/ReadOnlyContext.java
deleted file mode 100644
index 1719ea1219..0000000000
--- a/java/client/src/main/java/org/apache/qpid/jndi/ReadOnlyContext.java
+++ /dev/null
@@ -1,527 +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.jndi;
-
-import java.io.Serializable;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Hashtable;
-import java.util.Iterator;
-import java.util.Map;
-
-import javax.naming.Binding;
-import javax.naming.CompositeName;
-import javax.naming.Context;
-import javax.naming.LinkRef;
-import javax.naming.Name;
-import javax.naming.NameClassPair;
-import javax.naming.NameNotFoundException;
-import javax.naming.NameParser;
-import javax.naming.NamingEnumeration;
-import javax.naming.NamingException;
-import javax.naming.NotContextException;
-import javax.naming.OperationNotSupportedException;
-import javax.naming.Reference;
-import javax.naming.spi.NamingManager;
-
-/**
- * Based on class from ActiveMQ.
- * A read-only Context
- * <p/>
- * This version assumes it and all its subcontext are read-only and any attempt
- * to modify (e.g. through bind) will result in an OperationNotSupportedException.
- * Each Context in the tree builds a cache of the entries in all sub-contexts
- * to optimise the performance of lookup.
- * </p>
- * <p>This implementation is intended to optimise the performance of lookup(String)
- * to about the level of a HashMap get. It has been observed that the scheme
- * resolution phase performed by the JVM takes considerably longer, so for
- * optimum performance lookups should be coded like:</p>
- * <code>
- * Context componentContext = (Context)new InitialContext().lookup("java:comp");
- * String envEntry = (String) componentContext.lookup("env/myEntry");
- * String envEntry2 = (String) componentContext.lookup("env/myEntry2");
- * </code>
- */
-public class ReadOnlyContext implements Context, Serializable
-{
- private static final long serialVersionUID = -5754338187296859149L;
- protected static final NameParser nameParser = new NameParserImpl();
-
- protected final Hashtable environment; // environment for this context
- protected final Map bindings; // bindings at my level
- protected final Map treeBindings; // all bindings under me
-
- private boolean frozen = false;
- private String nameInNamespace = "";
- public static final String SEPARATOR = "/";
-
- public ReadOnlyContext()
- {
- environment = new Hashtable();
- bindings = new HashMap();
- treeBindings = new HashMap();
- }
-
- public ReadOnlyContext(Hashtable env)
- {
- if (env == null)
- {
- this.environment = new Hashtable();
- }
- else
- {
- this.environment = new Hashtable(env);
- }
-
- this.bindings = Collections.EMPTY_MAP;
- this.treeBindings = Collections.EMPTY_MAP;
- }
-
- public ReadOnlyContext(Hashtable environment, Map bindings)
- {
- if (environment == null)
- {
- this.environment = new Hashtable();
- }
- else
- {
- this.environment = new Hashtable(environment);
- }
-
- this.bindings = bindings;
- treeBindings = new HashMap();
- frozen = true;
- }
-
- public ReadOnlyContext(Hashtable environment, Map bindings, String nameInNamespace)
- {
- this(environment, bindings);
- this.nameInNamespace = nameInNamespace;
- }
-
- protected ReadOnlyContext(ReadOnlyContext clone, Hashtable env)
- {
- this.bindings = clone.bindings;
- this.treeBindings = clone.treeBindings;
- this.environment = new Hashtable(env);
- }
-
- protected ReadOnlyContext(ReadOnlyContext clone, Hashtable env, String nameInNamespace)
- {
- this(clone, env);
- this.nameInNamespace = nameInNamespace;
- }
-
- public void freeze()
- {
- frozen = true;
- }
-
- boolean isFrozen()
- {
- return frozen;
- }
-
- /**
- * internalBind is intended for use only during setup or possibly by suitably synchronized superclasses.
- * It binds every possible lookup into a map in each context. To do this, each context
- * strips off one name segment and if necessary creates a new context for it. Then it asks that context
- * to bind the remaining name. It returns a map containing all the bindings from the next context, plus
- * the context it just created (if it in fact created it). (the names are suitably extended by the segment
- * originally lopped off).
- *
- * @param name
- * @param value
- * @return
- * @throws javax.naming.NamingException
- */
- protected Map internalBind(String name, Object value) throws NamingException
- {
- assert (name != null) && (name.length() > 0);
- assert !frozen;
-
- Map newBindings = new HashMap();
- int pos = name.indexOf('/');
- if (pos == -1)
- {
- if (treeBindings.put(name, value) != null)
- {
- throw new NamingException("Something already bound at " + name);
- }
-
- bindings.put(name, value);
- newBindings.put(name, value);
- }
- else
- {
- String segment = name.substring(0, pos);
- assert segment != null;
- assert !segment.equals("");
- Object o = treeBindings.get(segment);
- if (o == null)
- {
- o = newContext();
- treeBindings.put(segment, o);
- bindings.put(segment, o);
- newBindings.put(segment, o);
- }
- else if (!(o instanceof ReadOnlyContext))
- {
- throw new NamingException("Something already bound where a subcontext should go");
- }
-
- ReadOnlyContext readOnlyContext = (ReadOnlyContext) o;
- String remainder = name.substring(pos + 1);
- Map subBindings = readOnlyContext.internalBind(remainder, value);
- for (Iterator iterator = subBindings.entrySet().iterator(); iterator.hasNext();)
- {
- Map.Entry entry = (Map.Entry) iterator.next();
- String subName = segment + "/" + (String) entry.getKey();
- Object bound = entry.getValue();
- treeBindings.put(subName, bound);
- newBindings.put(subName, bound);
- }
- }
-
- return newBindings;
- }
-
- protected ReadOnlyContext newContext()
- {
- return new ReadOnlyContext();
- }
-
- public Object addToEnvironment(String propName, Object propVal) throws NamingException
- {
- return environment.put(propName, propVal);
- }
-
- public Hashtable getEnvironment() throws NamingException
- {
- return (Hashtable) environment.clone();
- }
-
- public Object removeFromEnvironment(String propName) throws NamingException
- {
- return environment.remove(propName);
- }
-
- public Object lookup(String name) throws NamingException
- {
- if (name.length() == 0)
- {
- return this;
- }
-
- Object result = treeBindings.get(name);
- if (result == null)
- {
- result = bindings.get(name);
- }
-
- if (result == null)
- {
- int pos = name.indexOf(':');
- if (pos > 0)
- {
- String scheme = name.substring(0, pos);
- Context ctx = NamingManager.getURLContext(scheme, environment);
- if (ctx == null)
- {
- throw new NamingException("scheme " + scheme + " not recognized");
- }
-
- return ctx.lookup(name);
- }
- else
- {
- // Split out the first name of the path
- // and look for it in the bindings map.
- CompositeName path = new CompositeName(name);
-
- if (path.size() == 0)
- {
- return this;
- }
- else
- {
- String first = path.get(0);
- Object obj = bindings.get(first);
- if (obj == null)
- {
- throw new NameNotFoundException(name);
- }
- else if ((obj instanceof Context) && (path.size() > 1))
- {
- Context subContext = (Context) obj;
- obj = subContext.lookup(path.getSuffix(1));
- }
-
- return obj;
- }
- }
- }
-
- if (result instanceof LinkRef)
- {
- LinkRef ref = (LinkRef) result;
- result = lookup(ref.getLinkName());
- }
-
- if (result instanceof Reference)
- {
- try
- {
- result = NamingManager.getObjectInstance(result, null, null, this.environment);
- }
- catch (NamingException e)
- {
- throw e;
- }
- catch (Exception e)
- {
- throw (NamingException) new NamingException("could not look up : " + name).initCause(e);
- }
- }
-
- if (result instanceof ReadOnlyContext)
- {
- String prefix = getNameInNamespace();
- if (prefix.length() > 0)
- {
- prefix = prefix + SEPARATOR;
- }
-
- result = new ReadOnlyContext((ReadOnlyContext) result, environment, prefix + name);
- }
-
- return result;
- }
-
- public Object lookup(Name name) throws NamingException
- {
- return lookup(name.toString());
- }
-
- public Object lookupLink(String name) throws NamingException
- {
- return lookup(name);
- }
-
- public Name composeName(Name name, Name prefix) throws NamingException
- {
- Name result = (Name) prefix.clone();
- result.addAll(name);
-
- return result;
- }
-
- public String composeName(String name, String prefix) throws NamingException
- {
- CompositeName result = new CompositeName(prefix);
- result.addAll(new CompositeName(name));
-
- return result.toString();
- }
-
- public NamingEnumeration list(String name) throws NamingException
- {
- Object o = lookup(name);
- if (o == this)
- {
- return new ListEnumeration();
- }
- else if (o instanceof Context)
- {
- return ((Context) o).list("");
- }
- else
- {
- throw new NotContextException();
- }
- }
-
- public NamingEnumeration listBindings(String name) throws NamingException
- {
- Object o = lookup(name);
- if (o == this)
- {
- return new ListBindingEnumeration();
- }
- else if (o instanceof Context)
- {
- return ((Context) o).listBindings("");
- }
- else
- {
- throw new NotContextException();
- }
- }
-
- public Object lookupLink(Name name) throws NamingException
- {
- return lookupLink(name.toString());
- }
-
- public NamingEnumeration list(Name name) throws NamingException
- {
- return list(name.toString());
- }
-
- public NamingEnumeration listBindings(Name name) throws NamingException
- {
- return listBindings(name.toString());
- }
-
- public void bind(Name name, Object obj) throws NamingException
- {
- throw new OperationNotSupportedException();
- }
-
- public void bind(String name, Object obj) throws NamingException
- {
- throw new OperationNotSupportedException();
- }
-
- public void close() throws NamingException
- {
- // ignore
- }
-
- public Context createSubcontext(Name name) throws NamingException
- {
- throw new OperationNotSupportedException();
- }
-
- public Context createSubcontext(String name) throws NamingException
- {
- throw new OperationNotSupportedException();
- }
-
- public void destroySubcontext(Name name) throws NamingException
- {
- throw new OperationNotSupportedException();
- }
-
- public void destroySubcontext(String name) throws NamingException
- {
- throw new OperationNotSupportedException();
- }
-
- public String getNameInNamespace() throws NamingException
- {
- return nameInNamespace;
- }
-
- public NameParser getNameParser(Name name) throws NamingException
- {
- return nameParser;
- }
-
- public NameParser getNameParser(String name) throws NamingException
- {
- return nameParser;
- }
-
- public void rebind(Name name, Object obj) throws NamingException
- {
- throw new OperationNotSupportedException();
- }
-
- public void rebind(String name, Object obj) throws NamingException
- {
- throw new OperationNotSupportedException();
- }
-
- public void rename(Name oldName, Name newName) throws NamingException
- {
- throw new OperationNotSupportedException();
- }
-
- public void rename(String oldName, String newName) throws NamingException
- {
- throw new OperationNotSupportedException();
- }
-
- public void unbind(Name name) throws NamingException
- {
- throw new OperationNotSupportedException();
- }
-
- public void unbind(String name) throws NamingException
- {
- throw new OperationNotSupportedException();
- }
-
- private abstract class LocalNamingEnumeration implements NamingEnumeration
- {
- private Iterator i = bindings.entrySet().iterator();
-
- public boolean hasMore() throws NamingException
- {
- return i.hasNext();
- }
-
- public boolean hasMoreElements()
- {
- return i.hasNext();
- }
-
- protected Map.Entry getNext()
- {
- return (Map.Entry) i.next();
- }
-
- public void close() throws NamingException
- { }
- }
-
- private class ListEnumeration extends LocalNamingEnumeration
- {
- public Object next() throws NamingException
- {
- return nextElement();
- }
-
- public Object nextElement()
- {
- Map.Entry entry = getNext();
-
- return new NameClassPair((String) entry.getKey(), entry.getValue().getClass().getName());
- }
- }
-
- private class ListBindingEnumeration extends LocalNamingEnumeration
- {
- public Object next() throws NamingException
- {
- return nextElement();
- }
-
- public Object nextElement()
- {
- Map.Entry entry = getNext();
-
- return new Binding((String) entry.getKey(), entry.getValue());
- }
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/naming/ReadOnlyContext.java b/java/client/src/main/java/org/apache/qpid/naming/ReadOnlyContext.java
deleted file mode 100644
index 59ec4cfba7..0000000000
--- a/java/client/src/main/java/org/apache/qpid/naming/ReadOnlyContext.java
+++ /dev/null
@@ -1,509 +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.naming;
-
-import org.apache.qpid.jndi.NameParserImpl;
-
-import javax.naming.*;
-import javax.naming.spi.NamingManager;
-import java.io.Serializable;
-import java.util.*;
-
-/**
- * Based on class from ActiveMQ.
- * A read-only Context
- * <p/>
- * This version assumes it and all its subcontext are read-only and any attempt
- * to modify (e.g. through bind) will result in an OperationNotSupportedException.
- * Each Context in the tree builds a cache of the entries in all sub-contexts
- * to optimise the performance of lookup.
- * </p>
- * <p>This implementation is intended to optimise the performance of lookup(String)
- * to about the level of a HashMap get. It has been observed that the scheme
- * resolution phase performed by the JVM takes considerably longer, so for
- * optimum performance lookups should be coded like:</p>
- * <code>
- * Context componentContext = (Context)new InitialContext().lookup("java:comp");
- * String envEntry = (String) componentContext.lookup("env/myEntry");
- * String envEntry2 = (String) componentContext.lookup("env/myEntry2");
- * </code>
- */
-public class ReadOnlyContext implements Context, Serializable
-{
- private static final long serialVersionUID = -5754338187296859149L;
- protected static final NameParser nameParser = new NameParserImpl();
-
- protected final Hashtable environment; // environment for this context
- protected final Map bindings; // bindings at my level
- protected final Map treeBindings; // all bindings under me
-
- private boolean frozen = false;
- private String nameInNamespace = "";
- public static final String SEPARATOR = "/";
-
- public ReadOnlyContext()
- {
- environment = new Hashtable();
- bindings = new HashMap();
- treeBindings = new HashMap();
- }
-
- public ReadOnlyContext(Hashtable env)
- {
- if (env == null)
- {
- this.environment = new Hashtable();
- }
- else
- {
- this.environment = new Hashtable(env);
- }
-
- this.bindings = Collections.EMPTY_MAP;
- this.treeBindings = Collections.EMPTY_MAP;
- }
-
- public ReadOnlyContext(Hashtable environment, Map bindings)
- {
- if (environment == null)
- {
- this.environment = new Hashtable();
- }
- else
- {
- this.environment = new Hashtable(environment);
- }
-
- this.bindings = bindings;
- treeBindings = new HashMap();
- frozen = true;
- }
-
- public ReadOnlyContext(Hashtable environment, Map bindings, String nameInNamespace)
- {
- this(environment, bindings);
- this.nameInNamespace = nameInNamespace;
- }
-
- protected ReadOnlyContext(ReadOnlyContext clone, Hashtable env)
- {
- this.bindings = clone.bindings;
- this.treeBindings = clone.treeBindings;
- this.environment = new Hashtable(env);
- }
-
- protected ReadOnlyContext(ReadOnlyContext clone, Hashtable env, String nameInNamespace)
- {
- this(clone, env);
- this.nameInNamespace = nameInNamespace;
- }
-
- public void freeze()
- {
- frozen = true;
- }
-
- boolean isFrozen()
- {
- return frozen;
- }
-
- /**
- * internalBind is intended for use only during setup or possibly by suitably synchronized superclasses.
- * It binds every possible lookup into a map in each context. To do this, each context
- * strips off one name segment and if necessary creates a new context for it. Then it asks that context
- * to bind the remaining name. It returns a map containing all the bindings from the next context, plus
- * the context it just created (if it in fact created it). (the names are suitably extended by the segment
- * originally lopped off).
- *
- * @param name
- * @param value
- * @return
- * @throws javax.naming.NamingException
- */
- protected Map internalBind(String name, Object value) throws NamingException
- {
- assert (name != null) && (name.length() > 0);
- assert !frozen;
-
- Map newBindings = new HashMap();
- int pos = name.indexOf('/');
- if (pos == -1)
- {
- if (treeBindings.put(name, value) != null)
- {
- throw new NamingException("Something already bound at " + name);
- }
-
- bindings.put(name, value);
- newBindings.put(name, value);
- }
- else
- {
- String segment = name.substring(0, pos);
- assert segment != null;
- assert !segment.equals("");
- Object o = treeBindings.get(segment);
- if (o == null)
- {
- o = newContext();
- treeBindings.put(segment, o);
- bindings.put(segment, o);
- newBindings.put(segment, o);
- }
- else if (!(o instanceof ReadOnlyContext))
- {
- throw new NamingException("Something already bound where a subcontext should go");
- }
-
- ReadOnlyContext readOnlyContext = (ReadOnlyContext) o;
- String remainder = name.substring(pos + 1);
- Map subBindings = readOnlyContext.internalBind(remainder, value);
- for (Iterator iterator = subBindings.entrySet().iterator(); iterator.hasNext();)
- {
- Map.Entry entry = (Map.Entry) iterator.next();
- String subName = segment + "/" + (String) entry.getKey();
- Object bound = entry.getValue();
- treeBindings.put(subName, bound);
- newBindings.put(subName, bound);
- }
- }
-
- return newBindings;
- }
-
- protected ReadOnlyContext newContext()
- {
- return new ReadOnlyContext();
- }
-
- public Object addToEnvironment(String propName, Object propVal) throws NamingException
- {
- return environment.put(propName, propVal);
- }
-
- public Hashtable getEnvironment() throws NamingException
- {
- return (Hashtable) environment.clone();
- }
-
- public Object removeFromEnvironment(String propName) throws NamingException
- {
- return environment.remove(propName);
- }
-
- public Object lookup(String name) throws NamingException
- {
- if (name.length() == 0)
- {
- return this;
- }
-
- Object result = treeBindings.get(name);
- if (result == null)
- {
- result = bindings.get(name);
- }
-
- if (result == null)
- {
- int pos = name.indexOf(':');
- if (pos > 0)
- {
- String scheme = name.substring(0, pos);
- Context ctx = NamingManager.getURLContext(scheme, environment);
- if (ctx == null)
- {
- throw new NamingException("scheme " + scheme + " not recognized");
- }
-
- return ctx.lookup(name);
- }
- else
- {
- // Split out the first name of the path
- // and look for it in the bindings map.
- CompositeName path = new CompositeName(name);
-
- if (path.size() == 0)
- {
- return this;
- }
- else
- {
- String first = path.get(0);
- Object obj = bindings.get(first);
- if (obj == null)
- {
- throw new NameNotFoundException(name);
- }
- else if ((obj instanceof Context) && (path.size() > 1))
- {
- Context subContext = (Context) obj;
- obj = subContext.lookup(path.getSuffix(1));
- }
-
- return obj;
- }
- }
- }
-
- if (result instanceof LinkRef)
- {
- LinkRef ref = (LinkRef) result;
- result = lookup(ref.getLinkName());
- }
-
- if (result instanceof Reference)
- {
- try
- {
- result = NamingManager.getObjectInstance(result, null, null, this.environment);
- }
- catch (NamingException e)
- {
- throw e;
- }
- catch (Exception e)
- {
- throw (NamingException) new NamingException("could not look up : " + name).initCause(e);
- }
- }
-
- if (result instanceof ReadOnlyContext)
- {
- String prefix = getNameInNamespace();
- if (prefix.length() > 0)
- {
- prefix = prefix + SEPARATOR;
- }
-
- result = new ReadOnlyContext((ReadOnlyContext) result, environment, prefix + name);
- }
-
- return result;
- }
-
- public Object lookup(Name name) throws NamingException
- {
- return lookup(name.toString());
- }
-
- public Object lookupLink(String name) throws NamingException
- {
- return lookup(name);
- }
-
- public Name composeName(Name name, Name prefix) throws NamingException
- {
- Name result = (Name) prefix.clone();
- result.addAll(name);
-
- return result;
- }
-
- public String composeName(String name, String prefix) throws NamingException
- {
- CompositeName result = new CompositeName(prefix);
- result.addAll(new CompositeName(name));
-
- return result.toString();
- }
-
- public NamingEnumeration list(String name) throws NamingException
- {
- Object o = lookup(name);
- if (o == this)
- {
- return new ReadOnlyContext.ListEnumeration();
- }
- else if (o instanceof Context)
- {
- return ((Context) o).list("");
- }
- else
- {
- throw new NotContextException();
- }
- }
-
- public NamingEnumeration listBindings(String name) throws NamingException
- {
- Object o = lookup(name);
- if (o == this)
- {
- return new ReadOnlyContext.ListBindingEnumeration();
- }
- else if (o instanceof Context)
- {
- return ((Context) o).listBindings("");
- }
- else
- {
- throw new NotContextException();
- }
- }
-
- public Object lookupLink(Name name) throws NamingException
- {
- return lookupLink(name.toString());
- }
-
- public NamingEnumeration list(Name name) throws NamingException
- {
- return list(name.toString());
- }
-
- public NamingEnumeration listBindings(Name name) throws NamingException
- {
- return listBindings(name.toString());
- }
-
- public void bind(Name name, Object obj) throws NamingException
- {
- throw new OperationNotSupportedException();
- }
-
- public void bind(String name, Object obj) throws NamingException
- {
- throw new OperationNotSupportedException();
- }
-
- public void close() throws NamingException
- {
- // ignore
- }
-
- public Context createSubcontext(Name name) throws NamingException
- {
- throw new OperationNotSupportedException();
- }
-
- public Context createSubcontext(String name) throws NamingException
- {
- throw new OperationNotSupportedException();
- }
-
- public void destroySubcontext(Name name) throws NamingException
- {
- throw new OperationNotSupportedException();
- }
-
- public void destroySubcontext(String name) throws NamingException
- {
- throw new OperationNotSupportedException();
- }
-
- public String getNameInNamespace() throws NamingException
- {
- return nameInNamespace;
- }
-
- public NameParser getNameParser(Name name) throws NamingException
- {
- return nameParser;
- }
-
- public NameParser getNameParser(String name) throws NamingException
- {
- return nameParser;
- }
-
- public void rebind(Name name, Object obj) throws NamingException
- {
- throw new OperationNotSupportedException();
- }
-
- public void rebind(String name, Object obj) throws NamingException
- {
- throw new OperationNotSupportedException();
- }
-
- public void rename(Name oldName, Name newName) throws NamingException
- {
- throw new OperationNotSupportedException();
- }
-
- public void rename(String oldName, String newName) throws NamingException
- {
- throw new OperationNotSupportedException();
- }
-
- public void unbind(Name name) throws NamingException
- {
- throw new OperationNotSupportedException();
- }
-
- public void unbind(String name) throws NamingException
- {
- throw new OperationNotSupportedException();
- }
-
- private abstract class LocalNamingEnumeration implements NamingEnumeration
- {
- private Iterator i = bindings.entrySet().iterator();
-
- public boolean hasMore() throws NamingException
- {
- return i.hasNext();
- }
-
- public boolean hasMoreElements()
- {
- return i.hasNext();
- }
-
- protected Map.Entry getNext()
- {
- return (Map.Entry) i.next();
- }
-
- public void close() throws NamingException
- { }
- }
-
- private class ListEnumeration extends ReadOnlyContext.LocalNamingEnumeration
- {
- public Object next() throws NamingException
- {
- return nextElement();
- }
-
- public Object nextElement()
- {
- Map.Entry entry = getNext();
-
- return new NameClassPair((String) entry.getKey(), entry.getValue().getClass().getName());
- }
- }
-
- private class ListBindingEnumeration extends ReadOnlyContext.LocalNamingEnumeration
- {
- public Object next() throws NamingException
- {
- return nextElement();
- }
-
- public Object nextElement()
- {
- Map.Entry entry = getNext();
-
- return new Binding((String) entry.getKey(), entry.getValue());
- }
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/naming/jndi.properties b/java/client/src/main/java/org/apache/qpid/naming/jndi.properties
deleted file mode 100644
index 830de5f619..0000000000
--- a/java/client/src/main/java/org/apache/qpid/naming/jndi.properties
+++ /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.
-#
-java.naming.factory.initial = org.apache.qpid.naming.PropertiesFileInitialConextFactory
-
-# use the following property to configure the default connector
-#java.naming.provider.url - ignored.
-
-# register some connection factories
-# connectionfactory.[jndiname] = [ConnectionURL]
-# qpid:username=foo;password=password;client_id=id;virtualhost=path@tpc:localhost:1556
-connectionfactory.local = qpid:tcp:localhost'
-
-# register some queues in JNDI using the form
-# queue.[jndiName] = [physicalName]
-queue.MyQueue = example.MyQueue
-
-# register some topics in JNDI using the form
-# topic.[jndiName] = [physicalName]
-topic.ibmStocks = stocks.nyse.ibm
-
-# Register an AMQP destination in JNDI
-# NOTE: Qpid currently only supports direct,topics and headers
-# destination.[jniName] = [BindingURL]
-destination.direct = direct://amq.direct//directQueue
diff --git a/java/client/src/main/java/org/apache/qpid/nclient/MessagePartListener.java b/java/client/src/main/java/org/apache/qpid/nclient/MessagePartListener.java
deleted file mode 100644
index 6f07dcb469..0000000000
--- a/java/client/src/main/java/org/apache/qpid/nclient/MessagePartListener.java
+++ /dev/null
@@ -1,46 +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.nclient;
-
-import java.nio.ByteBuffer;
-
-import org.apache.qpid.transport.Header;
-import org.apache.qpid.transport.MessageTransfer;
-
-/**
- * Assembles message parts.
- * <p> The sequence of event for transferring a message is as follows:
- * <ul>
- * <li> messageHeaders
- * <li> n calls to addData
- * <li> messageReceived
- * </ul>
- * It is up to the implementation to assemble the message once the different parts
- * are transferred.
- */
-public interface MessagePartListener
-{
-
- /**
- * Inform the listener of the message transfer
- *
- * @param xfr the message transfer object
- */
- public void messageTransfer(MessageTransfer xfr);
-
-}
diff --git a/java/client/src/main/java/org/apache/qpid/nclient/util/ByteBufferMessage.java b/java/client/src/main/java/org/apache/qpid/nclient/util/ByteBufferMessage.java
deleted file mode 100644
index 14bfb4f95e..0000000000
--- a/java/client/src/main/java/org/apache/qpid/nclient/util/ByteBufferMessage.java
+++ /dev/null
@@ -1,190 +0,0 @@
-package org.apache.qpid.nclient.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.
- *
- */
-
-
-import java.io.IOException;
-import java.nio.ByteBuffer;
-import java.util.*;
-
-import org.apache.qpid.transport.DeliveryProperties;
-import org.apache.qpid.transport.MessageProperties;
-import org.apache.qpid.transport.Header;
-import org.apache.qpid.api.Message;
-
-/**
- * <p>A Simple implementation of the message interface
- * for small messages. When the readData methods are called
- * we assume the message is complete. i.e there want be any
- * appendData operations after that.</p>
- *
- * <p>If you need large message support please see
- * <code>FileMessage</code> and <code>StreamingMessage</code>
- * </p>
- */
-public class ByteBufferMessage implements Message
-{
- private List<ByteBuffer> _data;// = new ArrayList<ByteBuffer>();
- private ByteBuffer _readBuffer;
- private int _dataSize;
- private DeliveryProperties _currentDeliveryProps;
- private MessageProperties _currentMessageProps;
- private int _transferId;
- private Header _header;
-
- public ByteBufferMessage(MessageProperties messageProperties, DeliveryProperties deliveryProperties)
- {
- _currentMessageProps = messageProperties;
- _currentDeliveryProps = deliveryProperties;
- }
-
- public void setHeader(Header header) {
- _header = header;
- }
-
- public Header getHeader() {
- return _header;
- }
-
- public ByteBufferMessage()
- {
- _currentDeliveryProps = new DeliveryProperties();
- _currentMessageProps = new MessageProperties();
- }
-
- public ByteBufferMessage(int transferId)
- {
- _transferId = transferId;
- }
-
- public int getMessageTransferId()
- {
- return _transferId;
- }
-
- public void clearData()
- {
- _data = new LinkedList<ByteBuffer>();
- _readBuffer = null;
- }
-
- public void appendData(byte[] src) throws IOException
- {
- appendData(ByteBuffer.wrap(src));
- }
-
- /**
- * write the data from the current position up to the buffer limit
- */
- public void appendData(ByteBuffer src) throws IOException
- {
- if(_data == null)
- {
- _data = Collections.singletonList(src);
- }
- else
- {
- if(_data.size() == 1)
- {
- _data = new ArrayList<ByteBuffer>(_data);
- }
- _data.add(src);
- }
- _dataSize += src.remaining();
- }
-
- public DeliveryProperties getDeliveryProperties()
- {
- return _currentDeliveryProps;
- }
-
- public MessageProperties getMessageProperties()
- {
- return _currentMessageProps;
- }
-
- public void setDeliveryProperties(DeliveryProperties props)
- {
- _currentDeliveryProps = props;
- }
-
- public void setMessageProperties(MessageProperties props)
- {
- _currentMessageProps = props;
- }
-
- public void readData(byte[] target)
- {
- getReadBuffer().get(target);
- }
-
- public ByteBuffer readData()
- {
- return getReadBuffer();
- }
-
- private void buildReadBuffer()
- {
- //optimize for the simple cases
- if(_data.size() == 1)
- {
- _readBuffer = _data.get(0).duplicate();
- }
- else
- {
- _readBuffer = ByteBuffer.allocate(_dataSize);
- for(ByteBuffer buf:_data)
- {
- _readBuffer.put(buf);
- }
- _readBuffer.flip();
- }
- }
-
- private ByteBuffer getReadBuffer()
- {
- if (_readBuffer != null )
- {
- return _readBuffer.slice();
- }
- else
- {
- if (_data.size() >0)
- {
- buildReadBuffer();
- return _readBuffer.slice();
- }
- else
- {
- return ByteBuffer.allocate(0);
- }
- }
- }
-
- //hack for testing
- @Override public String toString()
- {
- ByteBuffer temp = getReadBuffer();
- byte[] b = new byte[temp.remaining()];
- temp.get(b);
- return new String(b);
- }
-}
diff --git a/java/client/src/main/java/org/apache/qpid/nclient/util/MessageListener.java b/java/client/src/main/java/org/apache/qpid/nclient/util/MessageListener.java
deleted file mode 100644
index c5edd62143..0000000000
--- a/java/client/src/main/java/org/apache/qpid/nclient/util/MessageListener.java
+++ /dev/null
@@ -1,34 +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.nclient.util;
-
-import org.apache.qpid.api.Message;
-
-/**
- *A message listener
- */
-public interface MessageListener
-{
- /**
- * Process an incoming message.
- *
- * @param message The incoming message.
- */
- public void onMessage(Message message);
-}
diff --git a/java/client/src/main/java/org/apache/qpid/nclient/util/MessagePartListenerAdapter.java b/java/client/src/main/java/org/apache/qpid/nclient/util/MessagePartListenerAdapter.java
deleted file mode 100644
index 10fd8d2a80..0000000000
--- a/java/client/src/main/java/org/apache/qpid/nclient/util/MessagePartListenerAdapter.java
+++ /dev/null
@@ -1,88 +0,0 @@
-package org.apache.qpid.nclient.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.
- *
- */
-
-
-import java.io.IOException;
-import java.nio.ByteBuffer;
-
-import org.apache.qpid.transport.*;
-import org.apache.qpid.nclient.MessagePartListener;
-
-/**
- * This is a simple message assembler.
- * Will call onMessage method of the adaptee
- * when all message data is read.
- *
- * This is a good convinience utility for handling
- * small messages
- */
-public class MessagePartListenerAdapter implements MessagePartListener
-{
- MessageListener _adaptee;
- ByteBufferMessage _currentMsg;
-
- public MessagePartListenerAdapter(MessageListener listener)
- {
- _adaptee = listener;
- }
-
- public void messageTransfer(MessageTransfer xfr)
- {
- _currentMsg = new ByteBufferMessage(xfr.getId());
-
- for (Struct st : xfr.getHeader().getStructs())
- {
- if(st instanceof DeliveryProperties)
- {
- _currentMsg.setDeliveryProperties((DeliveryProperties)st);
-
- }
- else if(st instanceof MessageProperties)
- {
- _currentMsg.setMessageProperties((MessageProperties)st);
- }
-
- }
-
-
- ByteBuffer body = xfr.getBody();
- if (body == null)
- {
- body = ByteBuffer.allocate(0);
- }
-
-
- try
- {
- _currentMsg.appendData(body);
- }
- catch(IOException e)
- {
- // A chance for IO exception
- // doesn't occur as we are using
- // a ByteBuffer
- }
-
- _adaptee.onMessage(_currentMsg);
- }
-
-}
diff --git a/java/client/src/old_test/java/org/apache/qpid/IBMPerfTest/JNDIBindConnectionFactory.java b/java/client/src/old_test/java/org/apache/qpid/IBMPerfTest/JNDIBindConnectionFactory.java
deleted file mode 100644
index 2c08f1e34a..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/IBMPerfTest/JNDIBindConnectionFactory.java
+++ /dev/null
@@ -1,185 +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.IBMPerfTest;
-
-import org.apache.log4j.Level;
-import org.apache.log4j.Logger;
-import org.apache.qpid.client.AMQConnectionFactory;
-import org.apache.qpid.url.URLSyntaxException;
-
-import javax.jms.ConnectionFactory;
-import javax.naming.Context;
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-import java.io.File;
-import java.util.Hashtable;
-
-public class JNDIBindConnectionFactory
-{
-
- public static final String CONNECTION_FACTORY_BINDING = "amq.ConnectionFactory";
- public static final String DEFAULT_PROVIDER_FILE_PATH = System.getProperty("java.io.tmpdir") + File.separator + "IBMPerfTestsJNDI";
- public static final String PROVIDER_URL = "file://" + DEFAULT_PROVIDER_FILE_PATH;
- public static final String FSCONTEXT_FACTORY = "com.sun.jndi.fscontext.RefFSContextFactory";
- public static final String DEFAULT_CONNECTION_URL = "amqp://guest:guest@clientid/testpath?brokerlist='tcp://localhost:5672'";
-
- private static void printUsage()
- {
- System.out.println("Using default values: Usage:java JNDIBindConnectionFactory <connection url> [<Connection Factory Binding>] [<Provider URL>] [<JNDI Context Factory>]");
-
- }
-
- public static void main(String[] args)
- {
- Logger.getRootLogger().setLevel(Level.OFF);
-
- String connectionFactoryBinding = CONNECTION_FACTORY_BINDING;
- String provider = PROVIDER_URL;
- String contextFactory = FSCONTEXT_FACTORY;
- if (args.length == 0)
- {
- printUsage();
- System.exit(1);
- }
-
- String connectionURL = args[0];
-
- System.out.println("Using Connection:" + connectionURL + "\n");
-
-
- if (args.length > 1)
- {
- connectionFactoryBinding = args[1];
-
- if (args.length > 2)
- {
- provider = args[2];
-
- if (args.length > 3)
- {
- contextFactory = args[3];
- }
- }
- else
- {
- System.out.println("Using default File System Context Factory");
- System.out.println("Using default Connection Factory Binding:" + connectionFactoryBinding);
- }
- }
- else
- {
- printUsage();
- }
-
-
- System.out.println("File System Context Factory\n" +
- "Connection:" + connectionURL + "\n" +
- "Connection Factory Binding:" + connectionFactoryBinding + "\n" +
- "JNDI Provider URL:" + provider);
-
- if (provider.startsWith("file"))
- {
- File file = new File(provider.substring(provider.indexOf("://") + 3));
-
- if (file.exists() && !file.isDirectory())
- {
- System.out.println("Couldn't make directory file already exists");
- System.exit(1);
- }
- else
- {
- if (!file.exists())
- {
- if (!file.mkdirs())
- {
- System.out.println("Couldn't make directory");
- System.exit(1);
- }
- }
- }
- }
-
- new JNDIBindConnectionFactory(provider, connectionFactoryBinding, contextFactory, connectionURL);
-
- }
-
- public JNDIBindConnectionFactory(String provider, String binding, String contextFactory, String CONNECTION_URL)
- {
- // Set up the environment for creating the initial context
- Hashtable env = new Hashtable(11);
- env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactory);
-
- env.put(Context.PROVIDER_URL, provider);
-
- try
- {
- // Create the initial context
- Context ctx = new InitialContext(env);
-
- // Create the object to be bound
- ConnectionFactory factory = null;
-
- try
- {
- factory = new AMQConnectionFactory(CONNECTION_URL);
-
-
- try
- {
- Object obj = ctx.lookup(binding);
-
- if (obj != null)
- {
- System.out.println("Un-binding previous Connection Factory");
- ctx.unbind(binding);
- }
- }
- catch (NamingException e)
- {
- System.out.println("Operation failed: " + e);
- }
-
- // Perform the bind
- ctx.bind(binding, factory);
- System.out.println("Bound Connection Factory:" + binding);
-
- // Check that it is bound
- Object obj = ctx.lookup(binding);
- System.out.println("Connection URL:" + ((AMQConnectionFactory) obj).getConnectionURL());
-
- System.out.println("JNDI FS Context:" + provider);
- }
- catch (NamingException amqe)
- {
- System.out.println("Operation failed: " + amqe);
- }
- catch (URLSyntaxException e)
- {
- System.out.println("Operation failed: " + e);
- }
-
- }
- catch (NamingException e)
- {
- System.out.println("Operation failed: " + e);
- }
- }
-}
diff --git a/java/client/src/old_test/java/org/apache/qpid/IBMPerfTest/JNDIBindQueue.java b/java/client/src/old_test/java/org/apache/qpid/IBMPerfTest/JNDIBindQueue.java
deleted file mode 100644
index 10e8b94311..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/IBMPerfTest/JNDIBindQueue.java
+++ /dev/null
@@ -1,213 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.IBMPerfTest;
-
-import org.apache.log4j.Level;
-import org.apache.log4j.Logger;
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.client.AMQSession;
-
-import javax.jms.Connection;
-import javax.jms.JMSException;
-import javax.jms.Queue;
-import javax.jms.Session;
-import javax.naming.Context;
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-import java.io.File;
-import java.util.Hashtable;
-
-public class JNDIBindQueue
-{
- public static final String DEFAULT_PROVIDER_FILE_PATH = System.getProperty("java.io.tmpdir") + File.separator + "IBMPerfTestsJNDI";
- public static final String PROVIDER_URL = "file://" + DEFAULT_PROVIDER_FILE_PATH;
- public static final String FSCONTEXT_FACTORY = "com.sun.jndi.fscontext.RefFSContextFactory";
-
- Connection _connection = null;
- Context _ctx = null;
-
-
- public JNDIBindQueue(String queueBinding, String queueName, String provider, String contextFactory)
- {
- // Set up the environment for creating the initial context
- Hashtable env = new Hashtable(11);
- env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactory);
-
- env.put(Context.PROVIDER_URL, provider);
-
- try
- {
- // Create the initial context
- _ctx = new InitialContext(env);
-
- // Create the object to be bound
-
- try
- {
- _connection = new AMQConnection("amqp://guest:guest@clientid/test?brokerlist='tcp://localhost:5672'");
- System.out.println("Connected");
- }
- catch (Exception amqe)
- {
- System.out.println("Unable to create AMQConnectionFactory:" + amqe);
- }
-
- if (_connection != null)
- {
- bindQueue(queueName, queueBinding);
- }
-
- // Check that it is bound
- Object obj = _ctx.lookup(queueBinding);
-
- System.out.println("Bound Queue:" + ((AMQQueue) obj).toURL());
-
- System.out.println("JNDI FS Context:" + provider);
-
- }
- catch (NamingException e)
- {
- System.out.println("Operation failed: " + e);
- }
- finally
- {
- try
- {
- if (_connection != null)
- {
- _connection.close();
- }
- }
- catch (JMSException closeE)
- {
- System.out.println("Connection closing failed: " + closeE);
- }
- }
-
-
- }
-
-
- private void bindQueue(String queueName, String queueBinding) throws NamingException
- {
-
- try
- {
- Object obj = _ctx.lookup(queueBinding);
-
- if (obj != null)
- {
- System.out.println("Un-binding exisiting object");
- _ctx.unbind(queueBinding);
- }
- }
- catch (NamingException e)
- {
-
- }
-
- Queue queue = null;
- try
- {
-
- Session session = _connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- if (session != null)
- {
- queue = ((AMQSession) session).createQueue(queueName);
- }
- }
- catch (JMSException jmse)
- {
- System.out.println("Unable to create Queue:" + jmse);
- }
-
- // Perform the bind
- _ctx.bind(queueBinding, queue);
- }
-
-
- public static void main(String[] args)
- {
- Logger.getRootLogger().setLevel(Level.OFF);
-
- String provider = JNDIBindQueue.PROVIDER_URL;
- String contextFactory = JNDIBindQueue.FSCONTEXT_FACTORY;
-
- if (args.length > 1)
- {
- String binding = args[0];
- String queueName = args[1];
-
- if (args.length > 2)
- {
- provider = args[2];
-
- if (args.length > 3)
- {
- contextFactory = args[3];
- }
- }
- else
- {
- System.out.println("Using default File System Context Factory");
- }
-
- System.out.println("File System Context Factory\n" +
- "Binding Queue:'" + queueName + "' to '" + binding + "'\n" +
- "JNDI Provider URL:" + provider);
-
- if (provider.startsWith("file"))
- {
- File file = new File(provider.substring(provider.indexOf("://") + 3));
-
- if (file.exists() && !file.isDirectory())
- {
- System.out.println("Couldn't make directory file already exists");
- System.exit(1);
- }
- else
- {
- if (!file.exists())
- {
- if (!file.mkdirs())
- {
- System.out.println("Couldn't make directory");
- System.exit(1);
- }
- }
- }
- }
-
-
- new JNDIBindQueue(binding, queueName, provider, contextFactory);
-
- }
- else
- {
- System.out.println("Using Defaults: Usage:java JNDIBindQueue <Binding> <queue name> [<Provider URL> [<JNDI Context Factory>]]");
- }
-
- }
-
-
-}
diff --git a/java/client/src/old_test/java/org/apache/qpid/IBMPerfTest/JNDIBindTopic.java b/java/client/src/old_test/java/org/apache/qpid/IBMPerfTest/JNDIBindTopic.java
deleted file mode 100644
index ca071c1187..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/IBMPerfTest/JNDIBindTopic.java
+++ /dev/null
@@ -1,212 +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.IBMPerfTest;
-
-import org.apache.log4j.Level;
-import org.apache.log4j.Logger;
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.client.AMQTopic;
-
-import javax.jms.Connection;
-import javax.jms.JMSException;
-import javax.jms.Session;
-import javax.jms.Topic;
-import javax.naming.Context;
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-import java.io.File;
-import java.util.Hashtable;
-
-public class JNDIBindTopic
-{
- public static final String DEFAULT_PROVIDER_FILE_PATH = System.getProperty("java.io.tmpdir") + File.separator + "IBMPerfTestsJNDI";
- public static final String PROVIDER_URL = "file://" + DEFAULT_PROVIDER_FILE_PATH;
-
- public static final String FSCONTEXT_FACTORY = "com.sun.jndi.fscontext.RefFSContextFactory";
-
- Connection _connection = null;
- Context _ctx = null;
-
-
- public JNDIBindTopic(String topicBinding, String topicName, String provider, String contextFactory)
- {
- // Set up the environment for creating the initial context
- Hashtable env = new Hashtable(11);
- env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactory);
-
- env.put(Context.PROVIDER_URL, provider);
-
- try
- {
- // Create the initial context
- _ctx = new InitialContext(env);
-
- // Create the object to be bound
-
- try
- {
- _connection = new AMQConnection("amqp://guest:guest@clientid/test?brokerlist='tcp://localhost:5672'");
- System.out.println("Connected");
- }
- catch (Exception amqe)
- {
- System.out.println("Unable to create AMQConnectionFactory:" + amqe);
- }
-
- if (_connection != null)
- {
- bindTopic(topicName, topicBinding);
- }
-
- // Check that it is bound
- Object obj = _ctx.lookup(topicBinding);
-
- System.out.println("Bound Queue:" + ((AMQTopic) obj).toURL());
-
- System.out.println("JNDI FS Context:" + provider);
-
- }
- catch (NamingException e)
- {
- System.out.println("Operation failed: " + e);
- }
- finally
- {
- try
- {
- if (_connection != null)
- {
- _connection.close();
- }
- }
- catch (JMSException closeE)
- {
- System.out.println("Operation failed: " + closeE);
- }
- }
- }
-
-
- private void bindTopic(String topicName, String topicBinding) throws NamingException
- {
-
- try
- {
- Object obj = _ctx.lookup(topicBinding);
-
- if (obj != null)
- {
- System.out.println("Un-binding exisiting object");
- _ctx.unbind(topicBinding);
- }
- }
- catch (NamingException e)
- {
-
- }
-
- Topic topic = null;
- try
- {
-
- Session session = _connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- if (session != null)
- {
- topic = ((AMQSession) session).createTopic(topicName);
- }
- }
- catch (JMSException jmse)
- {
- System.out.println("Unable to create Topic:" + jmse);
- }
-
- // Perform the bind
- _ctx.bind(topicBinding, topic);
- }
-
-
- public static void main(String[] args)
- {
- Logger.getRootLogger().setLevel(Level.OFF);
-
- String provider = JNDIBindTopic.PROVIDER_URL;
- String contextFactory = JNDIBindTopic.FSCONTEXT_FACTORY;
-
- if (args.length > 1)
- {
- String binding = args[0];
- String queueName = args[1];
-
- if (args.length > 2)
- {
- provider = args[2];
-
- if (args.length > 3)
- {
- contextFactory = args[3];
- }
- }
- else
- {
- System.out.println("Using default File System Context Factory");
- }
-
- System.out.println("File System Context Factory\n" +
- "Binding Topic:'" + queueName + "' to '" + binding + "'\n" +
- "JNDI Provider URL:" + provider);
-
-
- if (provider.startsWith("file"))
- {
- File file = new File(provider.substring(provider.indexOf("://") + 3));
-
- if (file.exists() && !file.isDirectory())
- {
- System.out.println("Couldn't make directory file already exists");
- System.exit(1);
- }
- else
- {
- if (!file.exists())
- {
- if (!file.mkdirs())
- {
- System.out.println("Couldn't make directory");
- System.exit(1);
- }
- }
- }
- }
-
- new JNDIBindTopic(binding, queueName, provider, contextFactory);
-
- }
- else
- {
- System.out.println("Usage:java JNDIBindTopic <Binding> <topic name> [<Provider URL> [<JNDI Context Factory>]]");
- }
-
- }
-
-
-}
diff --git a/java/client/src/old_test/java/org/apache/qpid/IBMPerfTest/README.txt b/java/client/src/old_test/java/org/apache/qpid/IBMPerfTest/README.txt
deleted file mode 100644
index 95ee9f9c77..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/IBMPerfTest/README.txt
+++ /dev/null
@@ -1,11 +0,0 @@
-These JNDI setup tools are mainly for use in conjunction with the IBM JMS Performance Harness available here:
-The jar should be placed in the client/test/lib/ directory.
-
-http://www.alphaworks.ibm.com/tech/perfharness
-
-
-These JNDI classes use the the SUN FileSystem context.
-There are two jar files that should be placed in your client/test/lib directory.
-
-http://javashoplm.sun.com/ECom/docs/Welcome.jsp?StoreId=22&PartDetailId=7110-jndi-1.2.1-oth-JPR&SiteId=JSC&TransactionId=noreg
-
diff --git a/java/client/src/old_test/java/org/apache/qpid/cluster/Client.java b/java/client/src/old_test/java/org/apache/qpid/cluster/Client.java
deleted file mode 100644
index cf8059a143..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/cluster/Client.java
+++ /dev/null
@@ -1,129 +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.cluster;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.client.AMQTopic;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.exchange.ExchangeDefaults;
-import org.apache.qpid.url.URLSyntaxException;
-
-import javax.jms.MessageListener;
-import javax.jms.Message;
-import javax.jms.Session;
-import javax.jms.JMSException;
-import javax.jms.MessageProducer;
-import javax.jms.TextMessage;
-import java.util.Random;
-
-public class Client
-{
- private final Random random = new Random();
- private final String name;
- private final Session session;
- private final MessageProducer topicProducer;
- private final MessageProducer queueProducer;
-
- Client(AMQConnection connection, String name) throws JMSException, InterruptedException
- {
- this.name = name;
- session = connection.createSession(false, AMQSession.NO_ACKNOWLEDGE);
-
- AMQTopic topic = new AMQTopic(((AMQSession)session).getDefaultTopicExchangeName(), new AMQShortString("cluster_test_topic"));
- AMQQueue queue = new AMQQueue(((AMQSession)session).getDefaultQueueExchangeName(), new AMQShortString("cluster_test_queue"));
-
- topicProducer = session.createProducer(topic);
- queueProducer = session.createProducer(queue);
-
- //subscribe to a known topic
- session.createConsumer(topic).setMessageListener(new TopicHandler());
- //subscribe to a known queue
- session.createConsumer(queue).setMessageListener(new QueueHandler());
-
- connection.start();
-
- while(true)
- {
- Thread.sleep(random.nextInt(60000));
- sendToQueue(name + ":" + randomString(5));
- }
- }
-
- private synchronized void sendToTopic(String message) throws JMSException
- {
- topicProducer.send(session.createTextMessage(message));
- }
-
- private synchronized void sendToQueue(String message) throws JMSException
- {
- queueProducer.send(session.createTextMessage(message));
- }
-
- private String randomString(int length){
- char[] c = new char[length];
- for(int i = 0; i < length; i++)
- {
- c[i] = (char) ('A' + random.nextInt(26));
- }
- return new String(c);
- }
-
- private class QueueHandler implements MessageListener
- {
- public void onMessage(Message message)
- {
- try
- {
- sendToTopic(((TextMessage) message).getText());
- }
- catch (JMSException e)
- {
- e.printStackTrace();
- }
- }
- }
-
- private class TopicHandler implements MessageListener
- {
- public void onMessage(Message message)
- {
- try
- {
- System.out.println(((TextMessage) message).getText());
- }
- catch (JMSException e)
- {
- e.printStackTrace();
- }
- }
- }
-
- public static void main(String[] argv) throws AMQException, JMSException, InterruptedException, URLSyntaxException
- {
- //assume args describe the set of brokers to try
-
- String clientName = argv.length > 1 ? argv[1] : "testClient";
- new Client(new AMQConnection(argv.length > 0 ? argv[0] : "vm://:1", "guest", "guest", clientName, "/test"), clientName);
- }
-}
diff --git a/java/client/src/old_test/java/org/apache/qpid/codec/BasicDeliverTest.java b/java/client/src/old_test/java/org/apache/qpid/codec/BasicDeliverTest.java
deleted file mode 100644
index 1db7e200bd..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/codec/BasicDeliverTest.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.codec;
-
-import org.apache.qpid.framing.*;
-import org.apache.mina.common.*;
-import org.apache.mina.common.support.BaseIoSession;
-import org.apache.mina.filter.codec.ProtocolDecoderOutput;
-import org.apache.mina.filter.codec.ProtocolEncoderOutput;
-
-import java.net.SocketAddress;
-
-/**
- */
-public class BasicDeliverTest
-{
- public static void main(String[] argv) throws Exception
- {
- BasicDeliverTest test = new BasicDeliverTest();
-
- //warm up:
- test.encode(512, 100000);
-
- //real tests:
- test.encode(16, 10000, 15);
- test.encode(32, 10000, 15);
- test.encode(64, 10000, 15);
- test.encode(128, 10000, 15);
- test.encode(256, 10000, 15);
- test.encode(512, 10000, 15);
- test.encode(1024, 10000, 15);
- test.encode(2048, 10000, 15);
-
- test.decode(16, 10000, 15);
- test.decode(32, 10000, 15);
- test.decode(64, 10000, 15);
- test.decode(128, 10000, 15);
- test.decode(256, 10000, 15);
- test.decode(512, 10000, 15);
- test.decode(1024, 10000, 15);
- test.decode(2048, 10000, 15);
- }
-
- void decode(int size, int count, int iterations) throws Exception
- {
- long min = Long.MAX_VALUE;
- long max = 0;
- long total = 0;
- for (int i = 0; i < iterations; i++)
- {
- long time = decode(size, count);
- total += time;
- if (time < min)
- {
- min = time;
- }
- if (time > max)
- {
- max = time;
- }
- }
- System.out.println("Decoded " + count + " messages of " + size +
- " bytes: avg=" + (total / iterations) + ", min=" + min + ", max=" + max);
- }
-
-
- long decode(int size, int count) throws Exception
- {
- AMQDataBlock block = getDataBlock(size);
- ByteBuffer data = ByteBuffer.allocate((int) block.getSize()); // XXX: Is cast a problem?
- block.writePayload(data);
- data.flip();
- AMQDecoder decoder = new AMQDecoder(false);
- long start = System.currentTimeMillis();
- for (int i = 0; i < count; i++)
- {
- decoder.decode(session, data, decoderOutput);
- data.rewind();
- }
- return System.currentTimeMillis() - start;
- }
-
- void encode(int size, int count, int iterations) throws Exception
- {
- long min = Long.MAX_VALUE;
- long max = 0;
- long total = 0;
- for (int i = 0; i < iterations; i++)
- {
- long time = encode(size, count);
- total += time;
- if (time < min)
- {
- min = time;
- }
- if (time > max)
- {
- max = time;
- }
- }
- System.out.println("Encoded " + count + " messages of " + size +
- " bytes: avg=" + (total / iterations) + ", min=" + min + ", max=" + max);
- }
-
- long encode(int size, int count) throws Exception
- {
- IoSession session = null;
- AMQDataBlock block = getDataBlock(size);
- AMQEncoder encoder = new AMQEncoder();
- long start = System.currentTimeMillis();
- for (int i = 0; i < count; i++)
- {
- encoder.encode(session, block, encoderOutput);
- }
- return System.currentTimeMillis() - start;
- }
-
- private final ProtocolEncoderOutput encoderOutput = new ProtocolEncoderOutput()
- {
-
- public void write(ByteBuffer byteBuffer)
- {
- }
-
- public void mergeAll()
- {
- }
-
- public WriteFuture flush()
- {
- return null;
- }
- };
-
- private final ProtocolDecoderOutput decoderOutput = new ProtocolDecoderOutput()
- {
- public void write(Object object)
- {
- }
-
- public void flush()
- {
- }
- };
-
- private final IoSession session = new BaseIoSession()
- {
-
- protected void updateTrafficMask()
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public IoService getService()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public IoServiceConfig getServiceConfig()
- {
- return null;
- }
-
- public IoHandler getHandler()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public IoSessionConfig getConfig()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public IoFilterChain getFilterChain()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public TransportType getTransportType()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public SocketAddress getRemoteAddress()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public SocketAddress getLocalAddress()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public SocketAddress getServiceAddress()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public int getScheduledWriteRequests()
- {
- return 0; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public int getScheduledWriteBytes()
- {
- return 0; //To change body of implemented methods use File | Settings | File Templates.
- }
- };
-
- private static final char[] DATA = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
-
- static CompositeAMQDataBlock getDataBlock(int size)
- {
- //create a frame representing message delivery
- AMQFrame[] frames = new AMQFrame[3];
- frames[0] = wrapBody(createBasicDeliverBody());
- frames[1] = wrapBody(createContentHeaderBody());
- frames[2] = wrapBody(createContentBody(size));
-
- return new CompositeAMQDataBlock(frames);
- }
-
- static AMQFrame wrapBody(AMQBody body)
- {
- AMQFrame frame = new AMQFrame(1, body);
- return frame;
- }
-
- static ContentBody createContentBody(int size)
- {
- ContentBody body = new ContentBody();
- body.payload = ByteBuffer.allocate(size);
- for (int i = 0; i < size; i++)
- {
- body.payload.put((byte) DATA[i % DATA.length]);
- }
- return body;
- }
-
- static ContentHeaderBody createContentHeaderBody()
- {
- ContentHeaderBody body = new ContentHeaderBody();
- body.properties = new BasicContentHeaderProperties();
- body.weight = 1;
- body.classId = 6;
- return body;
- }
-
- static BasicDeliverBody createBasicDeliverBody()
- {
- BasicDeliverBody body = new BasicDeliverBody((byte) 8, (byte) 0,
- BasicDeliverBody.getClazz((byte) 8, (byte) 0),
- BasicDeliverBody.getMethod((byte) 8, (byte) 0),
- new AMQShortString("myConsumerTag"), 1,
- new AMQShortString("myExchange"), false,
- new AMQShortString("myRoutingKey"));
- return body;
- }
-}
diff --git a/java/client/src/old_test/java/org/apache/qpid/codec/Client.java b/java/client/src/old_test/java/org/apache/qpid/codec/Client.java
deleted file mode 100644
index 3886021277..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/codec/Client.java
+++ /dev/null
@@ -1,133 +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.codec;
-
-import org.apache.mina.transport.socket.nio.SocketConnector;
-import org.apache.mina.common.ConnectFuture;
-import org.apache.mina.common.IoHandlerAdapter;
-import org.apache.mina.common.IoSession;
-import org.apache.mina.filter.codec.ProtocolCodecFilter;
-import org.apache.qpid.framing.AMQDataBlock;
-import org.apache.qpid.framing.AMQFrame;
-import org.apache.qpid.framing.BasicDeliverBody;
-import org.apache.qpid.framing.ContentBody;
-
-import java.net.InetSocketAddress;
-
-public class Client extends IoHandlerAdapter
-{
- //private static final int[] DEFAULT_SIZES = new int[]{1024, 512, 256, 128, 56};
- //private static final int[] DEFAULT_SIZES = new int[]{256, 256, 256, 256, 256, 512, 512, 512, 512, 512};
- private static final int[] DEFAULT_SIZES = new int[]{256, 512, 256, 512, 256, 512, 256, 512, 256, 512};
- //private static final int[] DEFAULT_SIZES = new int[]{1024, 1024, 1024, 1024, 1024};
-
- private final IoSession _session;
- private final long _start;
- private final int _size;
- private final int _count;
- private int _received;
- private boolean _closed;
-
- Client(String host, int port, int size, int count) throws Exception
- {
- _count = count;
- _size = size;
- AMQDataBlock block = BasicDeliverTest.getDataBlock(size);
-
- InetSocketAddress address = new InetSocketAddress(host, port);
- ConnectFuture future = new SocketConnector().connect(address, this);
- future.join();
- _session = future.getSession();
-
- _start = System.currentTimeMillis();
- for(int i = 0; i < count; i++)
- {
- _session.write(block);
- }
- }
-
- void close()
- {
- long time = System.currentTimeMillis() - _start;
- System.out.println("Received " + _received + " messages of " + _size
- + " bytes in " + time + "ms.");
- _session.close();
- synchronized(this)
- {
- _closed = true;
- notify();
- }
- }
-
- void waitForClose() throws InterruptedException
- {
- synchronized(this)
- {
- while(!_closed)
- {
- wait();
- }
- }
- }
-
- public void sessionCreated(IoSession session) throws Exception
- {
- session.getFilterChain().addLast("protocolFilter", new ProtocolCodecFilter(new AMQCodecFactory(false)));
- }
-
- public void messageReceived(IoSession session, Object object) throws Exception
- {
- if(isContent(object) && ++_received == _count) close();
- }
-
- public void exceptionCaught(IoSession session, Throwable throwable) throws Exception
- {
- throwable.printStackTrace();
- close();
- }
-
- private static boolean isDeliver(Object o)
- {
- return o instanceof AMQFrame && ((AMQFrame) o).getBodyFrame() instanceof BasicDeliverBody;
- }
-
- private static boolean isContent(Object o)
- {
- return o instanceof AMQFrame && ((AMQFrame) o).getBodyFrame() instanceof ContentBody;
- }
-
- public static void main(String[] argv) throws Exception
- {
- String host = argv.length > 0 ? argv[0] : "localhost";
- int port = argv.length > 1 ? Integer.parseInt(argv[1]) : 8888;
- int count = argv.length > 2 ? Integer.parseInt(argv[2]) : 10000;
- int[] sizes = argv.length > 3 ? new int[]{Integer.parseInt(argv[3])} : DEFAULT_SIZES;
-
- System.out.println("Connecting to " + host + ":" + port);
-
- for(int i = 0; i < sizes.length; i++)
- {
- new Client(host, port, sizes[i], count).waitForClose();
- Thread.sleep(1000);
- }
- }
-
-}
diff --git a/java/client/src/old_test/java/org/apache/qpid/codec/Server.java b/java/client/src/old_test/java/org/apache/qpid/codec/Server.java
deleted file mode 100644
index fa4295e0b2..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/codec/Server.java
+++ /dev/null
@@ -1,103 +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.codec;
-
-import org.apache.mina.common.IoHandlerAdapter;
-import org.apache.mina.common.IoSession;
-import org.apache.mina.transport.socket.nio.SocketAcceptor;
-import org.apache.mina.util.SessionUtil;
-import org.apache.mina.filter.codec.ProtocolCodecFilter;
-import org.apache.qpid.framing.AMQFrame;
-import org.apache.qpid.framing.CompositeAMQDataBlock;
-
-import java.net.InetSocketAddress;
-
-public class Server extends IoHandlerAdapter
-{
- Server(int port) throws Exception
- {
- new SocketAcceptor().bind(new InetSocketAddress(port), this);
- System.out.println("Listening on " + port);
- }
-
- public void sessionCreated(IoSession session) throws Exception
- {
- SessionUtil.initialize(session);
- session.getFilterChain().addLast("protocolFilter", new ProtocolCodecFilter(new AMQCodecFactory(false)));
- }
-
- public void messageReceived(IoSession session, Object object) throws Exception
- {
- getAccumulator(session).received(session, (AMQFrame) object);
- }
-
- public void sessionOpened(IoSession session) throws Exception
- {
- System.out.println("sessionOpened()");
- }
-
- public void sessionClosed(IoSession session) throws Exception
- {
- System.out.println("sessionClosed()");
- }
-
- public void exceptionCaught(IoSession session, Throwable t) throws Exception
- {
- System.out.println("exceptionCaught()");
- t.printStackTrace();
- session.close();
- }
-
- private Accumulator getAccumulator(IoSession session)
- {
- Accumulator a = (Accumulator) session.getAttribute(ACCUMULATOR);
- if(a == null)
- {
- a = new Accumulator();
- session.setAttribute(ACCUMULATOR, a);
- }
- return a;
- }
-
- private static final String ACCUMULATOR = Accumulator.class.getName();
-
- private static class Accumulator
- {
- private final AMQFrame[] frames = new AMQFrame[3];
- private int i;
-
- void received(IoSession session, AMQFrame frame)
- {
- frames[i++] = frame;
- if(i >= frames.length)
- {
- i = 0;
- session.write(new CompositeAMQDataBlock(frames));
- }
- }
- }
-
- public static void main(String[] argv) throws Exception
- {
- int port = argv.length > 0 ? Integer.parseInt(argv[0]) : 8888;
- new Server(port);
- }
-}
diff --git a/java/client/src/old_test/java/org/apache/qpid/config/AMQConnectionFactoryInitialiser.java b/java/client/src/old_test/java/org/apache/qpid/config/AMQConnectionFactoryInitialiser.java
deleted file mode 100644
index cac0064785..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/config/AMQConnectionFactoryInitialiser.java
+++ /dev/null
@@ -1,35 +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.config;
-
-import org.apache.qpid.client.AMQConnectionFactory;
-import org.apache.qpid.config.ConnectionFactoryInitialiser;
-import org.apache.qpid.config.ConnectorConfig;
-
-import javax.jms.ConnectionFactory;
-
-class AMQConnectionFactoryInitialiser implements ConnectionFactoryInitialiser
-{
- public ConnectionFactory getFactory(ConnectorConfig config)
- {
- return new AMQConnectionFactory(config.getHost(), config.getPort(), "/test_path");
- }
-}
diff --git a/java/client/src/old_test/java/org/apache/qpid/config/AbstractConfig.java b/java/client/src/old_test/java/org/apache/qpid/config/AbstractConfig.java
deleted file mode 100644
index 04381d66a0..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/config/AbstractConfig.java
+++ /dev/null
@@ -1,69 +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.config;
-
-public abstract class AbstractConfig
-{
- public boolean setOptions(String[] argv)
- {
- try
- {
- for(int i = 0; i < argv.length - 1; i += 2)
- {
- String key = argv[i];
- String value = argv[i+1];
- setOption(key, value);
- }
- return true;
- }
- catch(Exception e)
- {
- System.out.println(e.getMessage());
- }
- return false;
- }
-
- protected int parseInt(String msg, String i)
- {
- try
- {
- return Integer.parseInt(i);
- }
- catch(NumberFormatException e)
- {
- throw new RuntimeException(msg + ": " + i);
- }
- }
-
- protected long parseLong(String msg, String i)
- {
- try
- {
- return Long.parseLong(i);
- }
- catch(NumberFormatException e)
- {
- throw new RuntimeException(msg + ": " + i);
- }
- }
-
- public abstract void setOption(String key, String value);
-}
diff --git a/java/client/src/old_test/java/org/apache/qpid/config/ConnectionFactoryInitialiser.java b/java/client/src/old_test/java/org/apache/qpid/config/ConnectionFactoryInitialiser.java
deleted file mode 100644
index a9984eb09a..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/config/ConnectionFactoryInitialiser.java
+++ /dev/null
@@ -1,29 +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.config;
-
-import javax.jms.ConnectionFactory;
-import javax.jms.JMSException;
-
-public interface ConnectionFactoryInitialiser
-{
- public ConnectionFactory getFactory(ConnectorConfig config) throws JMSException;
-}
diff --git a/java/client/src/old_test/java/org/apache/qpid/config/Connector.java b/java/client/src/old_test/java/org/apache/qpid/config/Connector.java
deleted file mode 100644
index ff2377f087..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/config/Connector.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.config;
-
-import javax.jms.Connection;
-import javax.jms.ConnectionFactory;
-
-public class Connector
-{
- public Connection createConnection(ConnectorConfig config) throws Exception
- {
- return getConnectionFactory(config).createConnection();
- }
-
- ConnectionFactory getConnectionFactory(ConnectorConfig config) throws Exception
- {
- String factory = config.getFactory();
- if(factory == null) factory = AMQConnectionFactoryInitialiser.class.getName();
- System.out.println("Using " + factory);
- return ((ConnectionFactoryInitialiser) Class.forName(factory).newInstance()).getFactory(config);
- }
-}
diff --git a/java/client/src/old_test/java/org/apache/qpid/config/ConnectorConfig.java b/java/client/src/old_test/java/org/apache/qpid/config/ConnectorConfig.java
deleted file mode 100644
index b120ed3f12..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/config/ConnectorConfig.java
+++ /dev/null
@@ -1,28 +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.config;
-
-public interface ConnectorConfig
-{
- public String getHost();
- public int getPort();
- public String getFactory();
-}
diff --git a/java/client/src/old_test/java/org/apache/qpid/config/JBossConnectionFactoryInitialiser.java b/java/client/src/old_test/java/org/apache/qpid/config/JBossConnectionFactoryInitialiser.java
deleted file mode 100644
index 1c86aea56c..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/config/JBossConnectionFactoryInitialiser.java
+++ /dev/null
@@ -1,117 +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.config;
-
-import org.apache.qpid.config.ConnectionFactoryInitialiser;
-import org.apache.qpid.config.ConnectorConfig;
-
-import javax.jms.ConnectionFactory;
-import javax.jms.JMSException;
-import javax.management.MBeanServerConnection;
-import javax.management.ObjectName;
-import javax.management.MBeanException;
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-import javax.naming.NameNotFoundException;
-import java.util.Hashtable;
-
-public class JBossConnectionFactoryInitialiser implements ConnectionFactoryInitialiser
-{
- public ConnectionFactory getFactory(ConnectorConfig config) throws JMSException
- {
- ConnectionFactory cf = null;
- InitialContext ic = null;
- Hashtable ht = new Hashtable();
- ht.put(InitialContext.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
- String jbossHost = System.getProperty("jboss.host", "eqd-lxamq01");
- String jbossPort = System.getProperty("jboss.port", "1099");
- ht.put(InitialContext.PROVIDER_URL, "jnp://" + jbossHost + ":" + jbossPort);
- ht.put(InitialContext.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");
-
- try
- {
- ic = new InitialContext(ht);
- if (!doesDestinationExist("topictest.messages", ic))
- {
- deployTopic("topictest.messages", ic);
- }
- if (!doesDestinationExist("topictest.control", ic))
- {
- deployTopic("topictest.control", ic);
- }
-
- cf = (ConnectionFactory) ic.lookup("/ConnectionFactory");
- return cf;
- }
- catch (NamingException e)
- {
- JMSException jmse = new JMSException("Unable to lookup object: " + e);
- jmse.setLinkedException(e);
- jmse.initCause(e);
- throw jmse;
- }
- catch (Exception e)
- {
- JMSException jmse = new JMSException("Error creating topic: " + e);
- jmse.setLinkedException(e);
- jmse.initCause(e);
- throw jmse;
- }
- }
-
- private boolean doesDestinationExist(String name, InitialContext ic) throws Exception
- {
- try
- {
- ic.lookup("/" + name);
- }
- catch (NameNotFoundException e)
- {
- return false;
- }
- return true;
- }
-
- private void deployTopic(String name, InitialContext ic) throws Exception
- {
- MBeanServerConnection mBeanServer = lookupMBeanServerProxy(ic);
-
- ObjectName serverObjectName = new ObjectName("jboss.messaging:service=ServerPeer");
-
- String jndiName = "/" + name;
- try
- {
- mBeanServer.invoke(serverObjectName, "createTopic",
- new Object[]{name, jndiName},
- new String[]{"java.lang.String", "java.lang.String"});
- }
- catch (MBeanException e)
- {
- System.err.println("Error: " + e);
- System.err.println("Cause: " + e.getCause());
- }
- }
-
- private MBeanServerConnection lookupMBeanServerProxy(InitialContext ic) throws NamingException
- {
- return (MBeanServerConnection) ic.lookup("jmx/invoker/RMIAdaptor");
- }
-}
diff --git a/java/client/src/old_test/java/org/apache/qpid/flow/ChannelFlowTest.java b/java/client/src/old_test/java/org/apache/qpid/flow/ChannelFlowTest.java
deleted file mode 100644
index cb8adae18c..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/flow/ChannelFlowTest.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.flow;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQDestination;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.exchange.ExchangeDefaults;
-import org.apache.qpid.framing.AMQShortString;
-
-import javax.jms.Message;
-import javax.jms.MessageListener;
-import javax.jms.MessageProducer;
-
-public class ChannelFlowTest implements MessageListener
-{
- private int sent;
- private int received;
-
- ChannelFlowTest(String broker) throws Exception
- {
- this(new AMQConnection(broker, "guest", "guest", randomize("Client"), "/test"));
- }
-
- ChannelFlowTest(AMQConnection connection) throws Exception
- {
- this(connection, new AMQQueue(connection.getDefaultQueueExchangeName(), new AMQShortString(randomize("ChannelFlowTest")), true));
- }
-
- ChannelFlowTest(AMQConnection connection, AMQDestination destination) throws Exception
- {
- AMQSession session = (AMQSession) connection.createSession(false, AMQSession.NO_ACKNOWLEDGE, 50,25);
-
- //set up a slow consumer
- session.createConsumer(destination).setMessageListener(this);
- connection.start();
-
- //create a publisher
- MessageProducer producer = session.createProducer(destination);
- Message msg = session.createTextMessage("Message");
-
- //publish in bursts that are fast enough to cause channel flow control
- for(int i = 0; i < 10; i++)
- {
- for(int j = 0; j < 100; j++)
- {
- producer.send(msg);
- sent++;
- }
- waitUntilReceived(sent - 40);
- }
-
- waitUntilReceived(sent);
-
- session.close();
- connection.close();
- }
-
-
- private synchronized void waitUntilReceived(int count) throws InterruptedException
- {
- while(received <count)
- {
- wait();
- }
- }
-
- public synchronized void onMessage(Message message)
- {
- try
- {
- Thread.sleep(50);
-
- received++;
- notify();
- }
- catch (InterruptedException e)
- {
- e.printStackTrace();
- }
- }
-
- private static String randomize(String in)
- {
- return in + System.currentTimeMillis();
- }
-
- public static void main(String[] argv) throws Exception
- {
- new ChannelFlowTest(argv.length == 0 ? "localhost:5672" : argv[0]);
- }
-
-}
diff --git a/java/client/src/old_test/java/org/apache/qpid/fragmentation/TestLargePublisher.java b/java/client/src/old_test/java/org/apache/qpid/fragmentation/TestLargePublisher.java
deleted file mode 100644
index 2fe01fc126..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/fragmentation/TestLargePublisher.java
+++ /dev/null
@@ -1,196 +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.fragmentation;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.exchange.ExchangeDefaults;
-import org.apache.qpid.url.URLSyntaxException;
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQTopic;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.jms.MessageProducer;
-import org.apache.qpid.jms.Session;
-import org.apache.log4j.Logger;
-
-import javax.jms.BytesMessage;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageListener;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-
-/**
- * A client that behaves as follows:
- * <ul><li>Connects to a queue, whose name is specified as a cmd-line argument</li>
- * <li>Creates a temporary queue</li>
- * <li>Creates messages containing a property that is the name of the temporary queue</li>
- * <li>Fires off a message on the original queue and waits for a response on the temporary queue</li>
- * </ul>
- */
-public class TestLargePublisher
-{
- private static final Logger _log = Logger.getLogger(TestLargePublisher.class);
-
- private AMQConnection _connection;
-
- private AMQSession _session;
-
- private class CallbackHandler implements MessageListener
- {
- private int _expectedMessageCount;
-
- private int _actualMessageCount;
-
- private long _startTime;
-
- public CallbackHandler(int expectedMessageCount, long startTime)
- {
- _expectedMessageCount = expectedMessageCount;
- _startTime = startTime;
- }
-
- public void onMessage(Message m)
- {
- if (_log.isDebugEnabled())
- {
- _log.debug("Message received: " + m);
- }
- _actualMessageCount++;
- if (_actualMessageCount%1000 == 0)
- {
- _log.info("Received message count: " + _actualMessageCount);
- }
- /*if (!"henson".equals(m.toString()))
- {
- _log.error("AbstractJMSMessage response not correct: expected 'henson' but got " + m.toString());
- }
- else
- {
- if (_log.isDebugEnabled())
- {
- _log.debug("AbstractJMSMessage " + m + " received");
- }
- else
- {
- _log.info("AbstractJMSMessage received");
- }
- } */
-
- if (_actualMessageCount == _expectedMessageCount)
- {
- long timeTaken = System.currentTimeMillis() - _startTime;
- System.out.println("Total time taken to receive " + _expectedMessageCount+ " messages was " +
- timeTaken + "ms, equivalent to " +
- (_expectedMessageCount/(timeTaken/1000.0)) + " messages per second");
- }
- }
- }
-
- public TestLargePublisher(String host, int port, String clientID,
- final int messageCount) throws AMQException,URLSyntaxException
- {
- try
- {
- createConnection(host, port, clientID);
-
- _session = (AMQSession) _connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- AMQTopic destination = new AMQTopic(_session.getDefaultTopicExchangeName(), new AMQShortString("large"));
- MessageProducer producer = (MessageProducer) _session.createProducer(destination);
-
- _connection.start();
- //TextMessage msg = _session.createTextMessage(tempDestination.getQueueName() + "/Presented to in conjunction with Mahnah Mahnah and the Snowths");
- final long startTime = System.currentTimeMillis();
-
- for (int i = 0; i < messageCount; i++)
- {
- BytesMessage msg = _session.createBytesMessage();
- populateMessage(msg);
- producer.send(msg);
- }
- _log.info("Finished sending " + messageCount + " messages");
- }
- catch (JMSException e)
- {
- e.printStackTrace();
- }
- }
-
- private void createConnection(String host, int port, String clientID) throws AMQException , URLSyntaxException
- {
- _connection = new AMQConnection(host, port, "guest", "guest",
- clientID, "/test");
- }
-
- private void populateMessage(BytesMessage msg) throws JMSException
- {
- int size = 1024 * 187; // 187k
- byte[] data = new byte[size];
- for (int i = 0; i < data.length; i++)
- {
- data[i] = (byte)(i%25);
- }
- msg.writeBytes(data);
- }
-
- /**
- *
- * @param args argument 1 if present specifies the name of the temporary queue to create. Leaving it blank
- * means the server will allocate a name.
- */
- public static void main(String[] args) throws URLSyntaxException
- {
- final String host;
- final int port;
- final int numMessages;
- if (args.length == 0)
- {
- host = "localhost";
- port = 5672;
- numMessages = 100;
-// System.err.println("Usage: TestLargePublisher <host> <port> <number of messages>");
- }
- else
- {
- host = args[0];
- port = Integer.parseInt(args[1]);
- numMessages = Integer.parseInt(args[2]);
- }
-
- try
- {
- InetAddress address = InetAddress.getLocalHost();
- String clientID = address.getHostName() + System.currentTimeMillis();
- TestLargePublisher client = new TestLargePublisher(host, port, clientID, numMessages);
- }
- catch (UnknownHostException e)
- {
- e.printStackTrace();
- }
- catch (AMQException e)
- {
- System.err.println("Error in client: " + e);
- e.printStackTrace();
- }
-
- //System.exit(0);
- }
-}
diff --git a/java/client/src/old_test/java/org/apache/qpid/fragmentation/TestLargeSubscriber.java b/java/client/src/old_test/java/org/apache/qpid/fragmentation/TestLargeSubscriber.java
deleted file mode 100644
index b0cde22349..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/fragmentation/TestLargeSubscriber.java
+++ /dev/null
@@ -1,167 +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.fragmentation;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQTopic;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.jms.Session;
-import org.apache.qpid.exchange.ExchangeDefaults;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.log4j.Logger;
-
-import javax.jms.*;
-import java.net.InetAddress;
-
-public class TestLargeSubscriber
-{
- private static final Logger _logger = Logger.getLogger(TestLargeSubscriber.class);
-
- private static MessageProducer _destinationProducer;
-
- private static String _destinationName;
-
- public static void main(String[] args)
- {
- _logger.info("Starting...");
-
- final String host;
- final int port;
- final String username;
- final String password;
- final String virtualPath;
- final int numExpectedMessages;
- if (args.length == 0)
- {
- host = "localhost";
- port = 5672;
- username = "guest";
- password = "guest";
- virtualPath = "/test";
- numExpectedMessages = 100;
- }
- else if (args.length == 6)
- {
- host = args[0];
- port = Integer.parseInt(args[1]);
- username = args[2];
- password = args[3];
- virtualPath = args[4];
- numExpectedMessages = Integer.parseInt(args[5]);
- }
- else
- {
- System.out.println("Usage: host port username password virtual-path expectedMessageCount");
- System.exit(1);
- throw new RuntimeException("cannot be reached");
- }
-
- try
- {
- InetAddress address = InetAddress.getLocalHost();
- AMQConnection con = new AMQConnection(host, port, username, password,
- address.getHostName(), virtualPath);
- final AMQSession session = (AMQSession) con.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- final int expectedMessageCount = numExpectedMessages;
-
- MessageConsumer consumer = session.createConsumer(new AMQTopic(session.getDefaultTopicExchangeName(),
- new AMQShortString("large")),
- 100, true, false, null);
-
- consumer.setMessageListener(new MessageListener()
- {
- private int _messageCount;
-
- private long _startTime = 0;
-
- public void onMessage(Message message)
- {
- validateMessage(message);
- if (_messageCount++ == 0)
- {
- _startTime = System.currentTimeMillis();
- }
- if (_logger.isInfoEnabled())
- {
- _logger.info("Got message '" + message + "'");
- }
- if (_messageCount == expectedMessageCount)
- {
- long totalTime = System.currentTimeMillis() - _startTime;
- _logger.error("Total time to receive " + _messageCount + " messages was " +
- totalTime + "ms. Rate is " + (_messageCount/(totalTime/1000.0)));
- }
- }
-
- private void validateMessage(Message message)
- {
- if (!(message instanceof BytesMessage))
- {
- _logger.error("Message is not of correct type - should be BytesMessage and is " +
- message.getClass());
- }
- BytesMessage bm = (BytesMessage) message;
- final int expectedSize = 1024 * 187; // 187k
- try
- {
- if (bm.getBodyLength() != expectedSize)
- {
- _logger.error("Message is not correct length - should be " + expectedSize + " and is " +
- bm.getBodyLength());
- }
- }
- catch (JMSException e)
- {
- _logger.error("Failed to validate message: " + e, e);
- }
- try
- {
- byte[] data = new byte[(int)bm.getBodyLength()];
- bm.readBytes(data);
- for (int i = 0; i < data.length; i++)
- {
- if (data[i] != (byte)(i%25))
- {
- _logger.error("byte " + i + " of message is wrong - should be " + i%25 + " but is " +
- data[i]);
- }
- }
- _logger.info("***** Validated message successfully");
- }
- catch (JMSException e)
- {
- _logger.error("Failed to validate message: " + e, e);
- }
- }
- });
- con.start();
- }
- catch (Throwable t)
- {
- System.err.println("Fatal error: " + t);
- t.printStackTrace();
- }
-
- System.out.println("Waiting...");
- }
-}
-
diff --git a/java/client/src/old_test/java/org/apache/qpid/headers/Listener.java b/java/client/src/old_test/java/org/apache/qpid/headers/Listener.java
deleted file mode 100644
index cb5caefc1e..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/headers/Listener.java
+++ /dev/null
@@ -1,117 +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.headers;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.jms.Session;
-//import org.apache.qpid.testutil.Config;
-
-import javax.jms.MessageListener;
-import javax.jms.Message;
-import javax.jms.Destination;
-import javax.jms.MessageProducer;
-import javax.jms.JMSException;
-
-public class Listener //implements MessageListener
-{
-/* private final AMQConnection _connection;
- private final MessageProducer _controller;
- private final AMQSession _session;
- private final MessageFactory _factory;
- private int count;
- private long start;
-
- Listener(AMQConnection connection, Destination exchange) throws Exception
- {
- _connection = connection;
- _session = (AMQSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- _factory = new MessageFactory(_session, 0, 19);
-
- //register for events
- _factory.createConsumer(exchange).setMessageListener(this);
- _connection.start();
-
- _controller = _session.createProducer(exchange);
- }
-
- private void shutdown()
- {
- try
- {
- _session.close();
- _connection.stop();
- _connection.close();
- }
- catch(Exception e)
- {
- e.printStackTrace(System.out);
- }
- }
-
- private void report()
- {
- try
- {
- String msg = getReport();
- _controller.send(_factory.createReportResponseMessage(msg));
- System.out.println("Sent report: " + msg);
- }
- catch(Exception e)
- {
- e.printStackTrace(System.out);
- }
- }
-
- private String getReport() throws JMSException
- {
- long time = (System.currentTimeMillis() - start);
- return "Received " + count + " in " + time + "ms";
- }
-
- public void onMessage(Message message)
- {
- if(count == 0) start = System.currentTimeMillis();
-
- if(_factory.isShutdown(message))
- {
- shutdown();
- }
- else if(_factory.isReport(message))
- {
- //send a report:
- report();
- }
- else if (++count % 100 == 0)
- {
- System.out.println("Received " + count + " messages.");
- }
- }
-
- public static void main(String[] argv) throws Exception
- {
- Config config = new Config();
- config.setType(Config.HEADERS);
- config.setName("test_headers_exchange");
- config.setOptions(argv);
- new Listener((AMQConnection) config.getConnection(), config.getDestination());
- }*/
-}
diff --git a/java/client/src/old_test/java/org/apache/qpid/headers/MessageFactory.java b/java/client/src/old_test/java/org/apache/qpid/headers/MessageFactory.java
deleted file mode 100644
index a2d575fdd4..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/headers/MessageFactory.java
+++ /dev/null
@@ -1,175 +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.headers;
-
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.framing.FieldTable;
-import org.apache.qpid.framing.FieldTableFactory;
-
-import javax.jms.BytesMessage;
-import javax.jms.Destination;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.TextMessage;
-
-/**
- */
-class MessageFactory
-{
- private static final char[] DATA = "abcdefghijklmnopqrstuvwxyz".toCharArray();
-
- private final AMQSession _session;
- private final byte[] _payload;
-
- private String[] _headerNames;
-
- MessageFactory(AMQSession session)
- {
- this(session, Integer.getInteger("amqj.test.message_size", 256).intValue(), 5);
- }
-
- MessageFactory(AMQSession session, int payloadSize, int headerCount)
- {
- if (headerCount < 1)
- {
- throw new IllegalArgumentException("Header count must be positive");
- }
- _session = session;
- _payload = new byte[payloadSize];
- for (int i = 0; i < _payload.length; i++)
- {
- _payload[i] = (byte) DATA[i % DATA.length];
- }
- _headerNames = new String[headerCount];
- // note that with the standard encoding the headers get prefixed with an S to indicate their type
- for (int i = 0; i < _headerNames.length; i++)
- {
- if (i < 10)
- {
- _headerNames[i] = "F000" + i;
- }
- else if (i >= 10 && i < 100)
- {
- _headerNames[i] = "F00" + i;
- }
- else
- {
- _headerNames[i] = "F0" + i;
- }
- }
- }
-
- Message createEventMessage() throws JMSException
- {
- BytesMessage msg = _session.createBytesMessage();
- if (_payload.length != 0)
- {
- msg.writeBytes(_payload);
- }
- return setHeaders(msg, _headerNames);
- }
-
- Message createShutdownMessage() throws JMSException
- {
- return setHeaders(_session.createMessage(), new String[]{"F0000", "SHUTDOWN"});
- }
-
- Message createReportRequestMessage() throws JMSException
- {
- return setHeaders(_session.createMessage(), new String[]{"F0000", "REPORT"});
- }
-
- Message createReportResponseMessage(String msg) throws JMSException
- {
- return setHeaders(_session.createTextMessage(msg), new String[]{"CONTROL", "REPORT"});
- }
-
- boolean isShutdown(Message m)
- {
- return checkPresent(m, "SHUTDOWN");
- }
-
- boolean isReport(Message m)
- {
- return checkPresent(m, "REPORT");
- }
-
- Object getReport(Message m)
- {
- try
- {
- return ((TextMessage) m).getText();
- }
- catch (JMSException e)
- {
- e.printStackTrace(System.out);
- return e.toString();
- }
- }
-
- FieldTable getConsumerBinding()
- {
- FieldTable binding = FieldTableFactory.newFieldTable();
- binding.setString("SF0000", "value");
- return binding;
- }
-
- FieldTable getControllerBinding()
- {
- FieldTable binding = FieldTableFactory.newFieldTable();
- binding.setString("SCONTROL", "value");
- return binding;
- }
-
- MessageConsumer createConsumer(Destination source) throws Exception
- {
- return _session.createConsumer(source, 0, false, true, null, getConsumerBinding());
- }
-
- MessageConsumer createController(Destination source) throws Exception
- {
- return _session.createConsumer(source, 0, false, true, null, getControllerBinding());
- }
-
- private static boolean checkPresent(Message m, String s)
- {
- try
- {
- return m.getStringProperty(s) != null;
- }
- catch (JMSException e)
- {
- e.printStackTrace(System.out);
- return false;
- }
- }
-
- private static Message setHeaders(Message m, String[] headers) throws JMSException
- {
- for (int i = 0; i < headers.length; i++)
- {
- // the value in GRM is 5 bytes
- m.setStringProperty(headers[i], "value");
- }
- return m;
- }
-}
diff --git a/java/client/src/old_test/java/org/apache/qpid/headers/Publisher.java b/java/client/src/old_test/java/org/apache/qpid/headers/Publisher.java
deleted file mode 100644
index d9ef702c48..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/headers/Publisher.java
+++ /dev/null
@@ -1,133 +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.headers;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQSession;
-//import org.apache.qpid.testutil.Config;
-
-import javax.jms.*;
-
-public class Publisher // implements MessageListener
-{
-/* private final Object _lock = new Object();
- private final AMQConnection _connection;
- private final AMQSession _session;
- private final Destination _exchange;
- private final MessageFactory _factory;
- private final MessageProducer _publisher;
- private int _count;
-
- Publisher(AMQConnection connection, Destination exchange) throws Exception
- {
- _connection = connection;
- _exchange = exchange;
- _session = (AMQSession) _connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- _factory = new MessageFactory(_session, 0, 19);
- _publisher = _session.createProducer(_exchange);
- }
-
- Publisher(Config config) throws Exception
- {
- this((AMQConnection) config.getConnection(), config.getDestination());
- }
-
- private void test(int msgCount, int consumerCount) throws Exception
- {
- _count = consumerCount;
- _factory.createController(_exchange).setMessageListener(this);
- _connection.start();
- long start = System.currentTimeMillis();
- publish(msgCount);
- waitForCompletion(consumerCount);
- long end = System.currentTimeMillis();
-
- System.out.println("Completed in " + (end - start) + " ms.");
-
- //request shutdown
- _publisher.send(_factory.createShutdownMessage());
-
- _connection.stop();
- _connection.close();
- }
-
- private void publish(int count) throws Exception
- {
-
- //send events
- for (int i = 0; i < count; i++)
- {
- _publisher.send(_factory.createEventMessage());
- if ((i + 1) % 100 == 0)
- {
- System.out.println("Sent " + (i + 1) + " messages");
- }
- }
-
- //request report
- _publisher.send(_factory.createReportRequestMessage());
- }
-
- private void waitForCompletion(int consumers) throws Exception
- {
- System.out.println("Waiting for completion...");
- synchronized (_lock)
- {
- while (_count > 0)
- {
- _lock.wait();
- }
- }
- }
-
-
- public void onMessage(Message message)
- {
- System.out.println("Received report " + _factory.getReport(message) + " " + --_count + " remaining");
- if (_count == 0)
- {
- synchronized (_lock)
- {
- _lock.notify();
- }
- }
- }
-
-
- public static void main(String[] argv) throws Exception
- {
- if (argv.length >= 2)
- {
- int msgCount = Integer.parseInt(argv[argv.length - 2]);
- int consumerCount = Integer.parseInt(argv[argv.length - 1]);
-
- Config config = new Config();
- config.setType(Config.HEADERS);
- config.setName("test_headers_exchange");
- String[] options = new String[argv.length - 2];
- System.arraycopy(argv, 0, options, 0, options.length);
- config.setOptions(options);
-
- new Publisher(config).test(msgCount, consumerCount);
- }
-
- }*/
-}
diff --git a/java/client/src/old_test/java/org/apache/qpid/jndi/referenceable/Bind.java b/java/client/src/old_test/java/org/apache/qpid/jndi/referenceable/Bind.java
deleted file mode 100644
index ee6a12c233..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/jndi/referenceable/Bind.java
+++ /dev/null
@@ -1,273 +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.jndi.referenceable;
-
-import org.apache.qpid.client.*;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.url.URLSyntaxException;
-
-import javax.jms.*;
-import javax.naming.*;
-
-import java.util.Properties;
-import java.io.InputStream;
-import java.io.FileInputStream;
-import java.io.IOException;
-
-/**
- * Binds a reference from a JNDI source.
- * Given a properties file with the JNDI information and a binding string.
- */
-public class Bind
-{
- private static final String USAGE="USAGE: java bind <JNDI Properties file> -cf <url> <binding> | -c <url> <binding> [-t <topic Name> <binding>] [-q <queue Name> <binding>]";
- public Bind(String propertiesFile, String bindingURL, Referenceable reference) throws NameAlreadyBoundException, NoInitialContextException
- {
- // Set up the environment for creating the initial context
- String qpid_home = System.getProperty("QPID_HOME");
-
- if (qpid_home == null || qpid_home.equals(""))
- {
- System.out.println("QPID_HOME is not set");
- System.exit(1);
- }
-
- if (qpid_home.charAt(qpid_home.length() - 1) != '/')
- {
- qpid_home += "/";
- }
-
- try
- {
- InputStream inputStream = new FileInputStream(qpid_home + propertiesFile);
- Properties properties = new Properties();
- properties.load(inputStream);
-
- // Create the initial context
- Context ctx = new InitialContext(properties);
-
- // Perform the binds
- ctx.bind(bindingURL, reference);
-
- // Close the context when we're done
- ctx.close();
- }
- catch (IOException ioe)
- {
- System.out.println("Unable to access properties file:" + propertiesFile + " Due to:" + ioe);
- }
- catch (NamingException e)
- {
- System.out.println("Operation failed: " + e);
- if (e instanceof NameAlreadyBoundException)
- {
- throw (NameAlreadyBoundException) e;
- }
-
- if (e instanceof NoInitialContextException)
- {
- throw (NoInitialContextException) e;
- }
- }
-
- }
-
- private static String parse(String[] args, int index, String what, String type)
- {
- try
- {
- return args[index];
- }
- catch (IndexOutOfBoundsException ioobe)
- {
- System.out.println("ERROR: No " + what + " specified for " + type + ".");
- System.out.println(USAGE);
- System.exit(1);
- }
-
- // The path is either return normally or exception.. which calls system exit so keep the compiler happy
- return "Never going to happen";
- }
-
-
- public static void main(String[] args) throws NameAlreadyBoundException, NoInitialContextException, URLSyntaxException, AMQException, JMSException
- {
-
-
- org.apache.log4j.Logger.getRootLogger().setLevel(org.apache.log4j.Level.OFF);
-
-// org.apache.log4j.Logger _logger = org.apache.log4j.Logger.getLogger(AMQConnection.class);
-// _logger.setLevel(org.apache.log4j.Level.OFF);
-
- boolean exit = false;
-
- String qpid_home = System.getProperty("QPID_HOME");
-
- if (qpid_home == null || qpid_home.equals(""))
- {
- System.out.println("QPID_HOME is not set");
- exit = true;
- }
-
- if (args.length <= 2)
- {
- System.out.println("At least a connection or connection factory must be requested to be bound.");
- exit = true;
- }
- else
- {
- if ((args.length - 1) % 3 != 0)
- {
- System.out.println("Not all values have full details");
- exit = true;
- }
- }
- if (exit)
- {
- System.out.println(USAGE);
- System.exit(1);
- }
-
- if (qpid_home.charAt(qpid_home.length() - 1) != '/')
-
- {
- qpid_home += "/";
- }
-
- AMQConnectionFactory cf = null;
- AMQConnection c = null;
- AMQSession session = null;
- Referenceable reference = null;
-
- for (int index = 1; index < args.length; index ++)
- {
- String obj = args[index];
-
- String what = "Invalid";
- String binding;
-
- if (obj.startsWith("-c"))
- {
- boolean isFactory = obj.contains("f");
-
-
- if (isFactory)
- {
- what = "ConnectionFactory";
- }
- else
- {
- what = "Factory";
- }
-
- String url = parse(args, ++index, "url", what);
-
- if (isFactory)
- {
-
- cf = new AMQConnectionFactory(url);
- reference = cf;
- }
- else
- {
- c = new AMQConnection(url);
- reference = c;
- }
-
- }
-
- if (obj.equals("-t") || obj.equals("-q"))
- {
- if (c == null)
- {
- c = (AMQConnection) cf.createConnection();
- }
-
- if (session == null)
- {
- session = (AMQSession) c.createSession(false, Session.AUTO_ACKNOWLEDGE);
- }
-
- }
-
- if (obj.equals("-t"))
- {
-
- String topicName = parse(args, ++index, "Topic Name", "Topic");
- reference = (AMQTopic) session.createTopic(topicName);
- what = "Topic";
- }
- else
- {
- if (obj.equals("-q"))
- {
- String topicName = parse(args, ++index, "Queue Name", "Queue");
- reference = (AMQQueue) session.createQueue(topicName);
- what = "Queue";
- }
- }
-
- binding = parse(args, ++index, "binding", what);
- if (binding == null)
- {
- System.out.println(obj + " is not a known Object to bind.");
- System.exit(1);
- }
- else
- {
- System.out.print("Binding:" + reference + " to " + binding);
- try
- {
- new Bind(args[0], binding, reference);
- System.out.println(" ..Successful");
-
- }
- catch (NameAlreadyBoundException nabe)
- {
- System.out.println("");
- if (!obj.startsWith("-c") || index == args.length - 1)
- {
- throw nabe;
- }
- else
- {
- System.out.println("Continuing with other bindings using the same connection details");
- }
- }
- finally
- {
- if (!obj.startsWith("-c") || index == args.length - 1)
- {
- if (c != null)
- {
- c.close();
- }
- }
- }
- }
- }
-
- if (c != null)
- {
- c.close();
- }
- }
-}
diff --git a/java/client/src/old_test/java/org/apache/qpid/jndi/referenceable/Lookup.java b/java/client/src/old_test/java/org/apache/qpid/jndi/referenceable/Lookup.java
deleted file mode 100644
index 1c9d8b0fd5..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/jndi/referenceable/Lookup.java
+++ /dev/null
@@ -1,196 +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.jndi.referenceable;
-
-import javax.jms.Connection;
-import javax.jms.JMSException;
-import javax.naming.Context;
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Properties;
-
-/**
- * Looksup a reference from a JNDI source.
- * Given a properties file with the JNDI information and a binding string.
- */
-public class Lookup
-{
- private static final String USAGE = "USAGE: java lookup <JNDI Properties file> -b <binding>";
- private Properties _properties;
- private Object _object;
-
- public Lookup(String propertiesFile, String bindingValue) throws NamingException
- {
- // Set up the environment for creating the initial context
- String qpid_home = System.getProperty("QPID_HOME");
-
- if (qpid_home == null || qpid_home.equals(""))
- {
- System.out.println("QPID_HOME is not set");
- System.exit(1);
- }
-
- if (qpid_home.charAt(qpid_home.length() - 1) != '/')
- {
- qpid_home += "/";
- }
-
- try
- {
- InputStream inputStream = new FileInputStream(qpid_home + propertiesFile);
- Properties properties = new Properties();
- properties.load(inputStream);
-
- _properties = properties;
- lookup(bindingValue);
- }
- catch (IOException ioe)
- {
- System.out.println("Unable to access properties file:" + propertiesFile + " Due to:" + ioe);
- }
- }
-
- public Object lookup(String bindingValue) throws NamingException
- {
-
- // Create the initial context
- Context ctx = new InitialContext(_properties);
-
- // Perform the binds
- _object = ctx.lookup(bindingValue);
-
- // Close the context when we're done
- ctx.close();
-
- return getObject();
- }
-
- public Object getObject()
- {
- return _object;
- }
-
- private static String parse(String[] args, int index, String what)
- {
- try
- {
- return args[index];
- }
- catch (IndexOutOfBoundsException ioobe)
- {
- System.out.println("ERROR: No " + what + " specified.");
- System.out.println(USAGE);
- System.exit(1);
- }
-
- // The path is either return normally or exception.. which calls system exit so keep the compiler happy
- return "Never going to happen";
- }
-
-
- public static void main(String[] args) throws NamingException
- {
- boolean exit = false;
-
- String qpid_home = System.getProperty("QPID_HOME");
-
- if (qpid_home == null || qpid_home.equals(""))
- {
- System.out.println("QPID_HOME is not set");
- exit = true;
- }
-
- if (args.length <= 2)
- {
- System.out.println("At least a connection or connection factory must be requested to be bound.");
- exit = true;
- }
- else
- {
- if ((args.length - 1) % 2 != 0)
- {
- System.out.println("Not all values have full details");
- exit = true;
- }
- }
- if (exit)
- {
- System.out.println(USAGE);
- System.exit(1);
- }
-
- if (qpid_home.charAt(qpid_home.length() - 1) != '/')
-
- {
- qpid_home += "/";
- }
-
- for (int index = 1; index < args.length; index ++)
- {
- String obj = args[index];
-
-
- if (obj.equals("-b"))
- {
- String binding = parse(args, ++index, "binding");
-
- if (binding == null)
- {
- System.out.println("Binding not specified.");
- System.exit(1);
- }
- else
- {
- System.out.print("Looking up:" + binding);
- try
- {
- Lookup l = new Lookup(args[0], binding);
-
- Object object = l.getObject();
-
- if (object instanceof Connection)
- {
- try
- {
- ((Connection) object).close();
- }
- catch (JMSException jmse)
- {
- ;
- }
- }
- }
- catch (NamingException nabe)
- {
- System.out.println("Problem unbinding " + binding + " continuing with other values.");
- }
- }
- }// if -b
- else
- {
- System.out.println("Continuing with other bindings option not known:" + obj);
- }
- }//for
- }//main
-}//class
diff --git a/java/client/src/old_test/java/org/apache/qpid/jndi/referenceable/Unbind.java b/java/client/src/old_test/java/org/apache/qpid/jndi/referenceable/Unbind.java
deleted file mode 100644
index 1acead674c..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/jndi/referenceable/Unbind.java
+++ /dev/null
@@ -1,166 +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.jndi.referenceable;
-
-import javax.naming.*;
-
-import java.util.Properties;
-import java.io.InputStream;
-import java.io.FileInputStream;
-import java.io.IOException;
-
-/**
- * Unbinds a reference from a JNDI source.
- * Given a properties file with the JNDI information and a binding string.
- */
-public class Unbind
-{
- private static final String USAGE = "USAGE: java unbind <JNDI Properties file> -b <binding>";
-
- public Unbind(String propertiesFile, String bindingValue) throws NamingException
- {
- // Set up the environment for creating the initial context
- String qpid_home = System.getProperty("QPID_HOME");
-
- if (qpid_home == null || qpid_home.equals(""))
- {
- System.out.println("QPID_HOME is not set");
- System.exit(1);
- }
-
- if (qpid_home.charAt(qpid_home.length() - 1) != '/')
- {
- qpid_home += "/";
- }
-
- try
- {
- InputStream inputStream = new FileInputStream(qpid_home + propertiesFile);
- Properties properties = new Properties();
- properties.load(inputStream);
-
- // Create the initial context
- Context ctx = new InitialContext(properties);
-
- // Perform the binds
- ctx.unbind(bindingValue);
-
- // Close the context when we're done
- ctx.close();
- }
- catch (IOException ioe)
- {
- System.out.println("Unable to access properties file:" + propertiesFile + " Due to:" + ioe);
- }
- }
-
- private static String parse(String[] args, int index, String what)
- {
- try
- {
- return args[index];
- }
- catch (IndexOutOfBoundsException ioobe)
- {
- System.out.println("ERROR: No " + what + " specified.");
- System.out.println(USAGE);
- System.exit(1);
- }
-
- // The path is either return normally or exception.. which calls system exit so keep the compiler happy
- return "Never going to happen";
- }
-
-
- public static void main(String[] args) throws NamingException
- {
- boolean exit = false;
-
- String qpid_home = System.getProperty("QPID_HOME");
-
- if (qpid_home == null || qpid_home.equals(""))
- {
- System.out.println("QPID_HOME is not set");
- exit = true;
- }
-
- if (args.length <= 2)
- {
- System.out.println("At least a connection or connection factory must be requested to be bound.");
- exit = true;
- }
- else
- {
- if ((args.length - 1) % 2 != 0)
- {
- System.out.println("Not all values have full details");
- exit = true;
- }
- }
- if (exit)
- {
- System.out.println(USAGE);
- System.exit(1);
- }
-
- if (qpid_home.charAt(qpid_home.length() - 1) != '/')
-
- {
- qpid_home += "/";
- }
-
- for (int index = 1; index < args.length; index ++)
- {
- String obj = args[index];
-
-
- if (obj.equals("-b"))
- {
- String binding = parse(args, ++index, "binding");
-
- if (binding == null)
- {
- System.out.println("Binding not specified.");
- System.exit(1);
- }
- else
- {
- System.out.print("UnBinding:" + binding);
- try
- {
- new Unbind(args[0], binding);
- System.out.println(" ..Successful");
- }
- catch (NamingException nabe)
- {
- System.out.println("");
-
- System.out.println("Problem unbinding " + binding + " continuing with other values.");
- }
- }
- }// if -b
- else
- {
- System.out.println("Continuing with other bindings option not known:" + obj);
- }
- }//for
- }//main
-}//class
diff --git a/java/client/src/old_test/java/org/apache/qpid/latency/LatencyTest.java b/java/client/src/old_test/java/org/apache/qpid/latency/LatencyTest.java
deleted file mode 100644
index 4865a68dc4..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/latency/LatencyTest.java
+++ /dev/null
@@ -1,153 +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.latency;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.client.AMQDestination;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.exchange.ExchangeDefaults;
-import org.apache.qpid.framing.AMQShortString;
-
-import javax.jms.MessageProducer;
-import javax.jms.Message;
-import javax.jms.MessageListener;
-import javax.jms.JMSException;
-import javax.jms.TextMessage;
-import javax.jms.BytesMessage;
-
-public class LatencyTest implements MessageListener
-{
- private volatile boolean waiting;
- private int sent;
- private int received;
-
- private final byte[] data;
-
- private long min = Long.MAX_VALUE;
- private long max = 0;
- private long total = 0;
-
- LatencyTest(String broker, int count, int delay, int length) throws Exception
- {
- this(new AMQConnection(broker, "guest", "guest", randomize("Client"), "/test"), count, delay, length);
- }
-
- LatencyTest(AMQConnection connection, int count, int delay, int length) throws Exception
- {
- this(connection, new AMQQueue(connection.getDefaultQueueExchangeName(), new AMQShortString(randomize("LatencyTest")), true), count, delay, length);
- }
-
- LatencyTest(AMQConnection connection, AMQDestination destination, int count, int delay, int length) throws Exception
- {
- AMQSession session = (AMQSession) connection.createSession(false, AMQSession.NO_ACKNOWLEDGE);
-
- data = new byte[length];
- for(int i = 0; i < data.length; i++)
- {
- data[i] = (byte) (i % 100);
- }
-
- //set up a consumer
- session.createConsumer(destination).setMessageListener(this);
- connection.start();
-
- //create a publisher
- MessageProducer producer = session.createProducer(destination, false, false, true);
-
- //publish at a low volume
- for(int i = 0; i < count; i++)
- {
- BytesMessage msg = session.createBytesMessage();
- msg.writeBytes(data);
- msg.setStringProperty("sent-at", Long.toString(System.nanoTime()));
- producer.send(msg);
- Thread.sleep(delay);
- if(++sent % 100 == 0)
- {
- System.out.println("Sent " + sent + " of " + count);
- }
- }
-
- waitUntilReceived(sent);
-
- session.close();
- connection.close();
-
- System.out.println("Latency (in nanoseconds): avg=" + (total/sent) + ", min=" + min + ", max=" + max
- + ", avg(discarding min and max)=" + ((total - min - max) / (sent - 2)));
- }
-
-
- private synchronized void waitUntilReceived(int count) throws InterruptedException
- {
- waiting = true;
- while(received < count)
- {
- wait();
- }
- waiting = false;
- }
-
- public void onMessage(Message message)
- {
- received++;
- try
- {
- long sent = Long.parseLong(message.getStringProperty("sent-at"));
- long time = System.nanoTime() - sent;
- total += time;
- min = Math.min(min, time);
- max = Math.max(max, time);
- }
- catch (JMSException e)
- {
- e.printStackTrace();
- }
-
- if(waiting){
- synchronized(this)
- {
- notify();
- }
- }
- }
-
- private static String randomize(String in)
- {
- return in + System.currentTimeMillis();
- }
-
- public static void main(String[] argv) throws Exception
- {
- String host = argv.length > 0 ? argv[0] : "localhost:5672";
- if("-help".equals(host))
- {
- System.out.println("Usage: <broker> <message count> <delay between messages> <message size>");
- }
- int count = argv.length > 1 ? Integer.parseInt(argv[1]) : 1000;
- int delay = argv.length > 2 ? Integer.parseInt(argv[2]) : 1000;
- int size = argv.length > 3 ? Integer.parseInt(argv[3]) : 512;
- new LatencyTest(host, count, delay, size);
- }
-
-
-}
diff --git a/java/client/src/old_test/java/org/apache/qpid/mina/AcceptorTest.java b/java/client/src/old_test/java/org/apache/qpid/mina/AcceptorTest.java
deleted file mode 100644
index f0ac0e6902..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/mina/AcceptorTest.java
+++ /dev/null
@@ -1,102 +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.mina;
-
-import org.apache.log4j.Logger;
-import org.apache.mina.common.ByteBuffer;
-import org.apache.mina.common.IoAcceptor;
-import org.apache.mina.common.IoHandlerAdapter;
-import org.apache.mina.common.IoSession;
-import org.apache.mina.transport.socket.nio.SocketAcceptor;
-import org.apache.mina.transport.socket.nio.SocketAcceptorConfig;
-import org.apache.mina.transport.socket.nio.SocketSessionConfig;
-import org.apache.qpid.pool.ReadWriteThreadModel;
-
-import java.io.IOException;
-import java.net.InetSocketAddress;
-
-import junit.framework.TestCase;
-
-/**
- * Tests MINA socket performance. This acceptor simply reads data from the network and writes it back again.
- *
- */
-public class AcceptorTest extends TestCase
-{
- private static final Logger _logger = Logger.getLogger(AcceptorTest.class);
-
- public static int PORT = 9999;
-
- private static class TestHandler extends IoHandlerAdapter
- {
- private int _sentCount;
-
- private int _bytesSent;
-
- public void messageReceived(IoSession session, Object message) throws Exception
- {
- ((ByteBuffer) message).acquire();
- session.write(message);
- _logger.debug("Sent response " + ++_sentCount);
- _bytesSent += ((ByteBuffer)message).remaining();
- _logger.debug("Bytes sent: " + _bytesSent);
- }
-
- public void messageSent(IoSession session, Object message) throws Exception
- {
- //((ByteBuffer) message).release();
- }
-
- public void exceptionCaught(IoSession session, Throwable cause) throws Exception
- {
- _logger.error("Error: " + cause, cause);
- }
- }
-
- public void testStartAcceptor() throws IOException
- {
- IoAcceptor acceptor = null;
- acceptor = new SocketAcceptor();
-
- SocketAcceptorConfig config = (SocketAcceptorConfig) acceptor.getDefaultConfig();
- SocketSessionConfig sc = (SocketSessionConfig) config.getSessionConfig();
- sc.setTcpNoDelay(true);
- sc.setSendBufferSize(32768);
- sc.setReceiveBufferSize(32768);
-
- config.setThreadModel(ReadWriteThreadModel.getInstance());
-
- acceptor.bind(new InetSocketAddress(PORT),
- new TestHandler());
- _logger.info("Bound on port " + PORT);
- }
-
- public static void main(String[] args) throws IOException
- {
- AcceptorTest a = new AcceptorTest();
- a.testStartAcceptor();
- }
-
- public static junit.framework.Test suite()
- {
- return new junit.framework.TestSuite(AcceptorTest.class);
- }
-}
diff --git a/java/client/src/old_test/java/org/apache/qpid/mina/BlockingAcceptorTest.java b/java/client/src/old_test/java/org/apache/qpid/mina/BlockingAcceptorTest.java
deleted file mode 100644
index bfe29c47e6..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/mina/BlockingAcceptorTest.java
+++ /dev/null
@@ -1,93 +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.mina;
-
-import org.apache.log4j.Logger;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.net.ServerSocket;
-import java.net.Socket;
-
-import junit.framework.TestCase;
-
-public class BlockingAcceptorTest extends TestCase
-{
- private static final Logger _logger = Logger.getLogger(BlockingAcceptorTest.class);
-
- public static int PORT = 9999;
-
- public void testStartAcceptor() throws IOException
- {
-
- ServerSocket sock = new ServerSocket(PORT);
-
- sock.setReuseAddress(true);
- sock.setReceiveBufferSize(32768);
- _logger.info("Bound on port " + PORT);
-
- while (true)
- {
- final Socket s = sock.accept();
- _logger.info("Received connection from " + s.getRemoteSocketAddress());
- s.setReceiveBufferSize(32768);
- s.setSendBufferSize(32768);
- s.setTcpNoDelay(true);
- new Thread(new Runnable()
- {
- public void run()
- {
- byte[] chunk = new byte[32768];
- try
- {
- InputStream is = s.getInputStream();
- OutputStream os = s.getOutputStream();
-
- while (true)
- {
- int count = is.read(chunk, 0, chunk.length);
- if (count > 0)
- {
- os.write(chunk, 0, count);
- }
- }
- }
- catch (IOException e)
- {
- _logger.error("Error - closing connection: " + e, e);
- }
- }
- }, "SocketReaderWriter").start();
- }
- }
-
- public static void main(String[] args) throws IOException
- {
- BlockingAcceptorTest a = new BlockingAcceptorTest();
- a.testStartAcceptor();
- }
-
- public static junit.framework.Test suite()
- {
- return new junit.framework.TestSuite(AcceptorTest.class);
- }
-}
diff --git a/java/client/src/old_test/java/org/apache/qpid/mina/WriterTest.java b/java/client/src/old_test/java/org/apache/qpid/mina/WriterTest.java
deleted file mode 100644
index 910345624f..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/mina/WriterTest.java
+++ /dev/null
@@ -1,271 +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.mina;
-
-import org.apache.log4j.Logger;
-import org.apache.mina.common.*;
-import org.apache.mina.transport.socket.nio.SocketConnector;
-import org.apache.mina.transport.socket.nio.SocketConnectorConfig;
-import org.apache.mina.transport.socket.nio.SocketSessionConfig;
-
-import java.io.IOException;
-import java.net.InetSocketAddress;
-import java.util.concurrent.CountDownLatch;
-
-import junit.framework.TestCase;
-
-public class WriterTest extends TestCase
-{
- private static final Logger _logger = Logger.getLogger(WriterTest.class);
-
- private static class RunnableWriterTest implements Runnable
- {
- private Logger _logger;
-
- private IoSession _session;
-
- private long _startTime;
-
- private long[] _chunkTimes;
-
- private int _chunkCount = 500000;
-
- private int _chunkSize = 1024;
-
- private CountDownLatch _notifier;
-
- public RunnableWriterTest(Logger logger)
- {
- _logger = logger;
- }
-
- public void run()
- {
- _startTime = System.currentTimeMillis();
- _notifier = new CountDownLatch(1);
- for (int i = 0; i < _chunkCount; i++)
- {
- ByteBuffer buf = ByteBuffer.allocate(_chunkSize, false);
- byte check = (byte) (i % 128);
- buf.put(check);
- buf.fill((byte)88, buf.remaining());
- buf.flip();
- _session.write(buf);
- }
-
- try
- {
- _logger.info("All buffers sent; waiting for receipt from server");
- _notifier.await();
- }
- catch (InterruptedException e)
- {
- }
- _logger.info("Completed");
- long totalTime = System.currentTimeMillis() - _startTime;
- _logger.info("Total time: " + totalTime);
- _logger.info("MB per second: " + (_chunkSize * _chunkCount)/totalTime);
- long lastChunkTime = _startTime;
- double average = 0;
- for (int i = 0; i < _chunkTimes.length; i++)
- {
- if (i == 0)
- {
- average = _chunkTimes[i] - _startTime;
- }
- else
- {
- long delta = _chunkTimes[i] - lastChunkTime;
- if (delta != 0)
- {
- average = (average + delta)/2;
- }
- }
- lastChunkTime = _chunkTimes[i];
- }
- _logger.info("Average chunk time: " + average + "ms");
- CloseFuture cf = _session.close();
- cf.join();
- }
-
- private class WriterHandler extends IoHandlerAdapter
- {
- private int _chunksReceived = 0;
-
- private int _partialBytesRead = 0;
-
- private byte _partialCheckNumber;
-
- private int _totalBytesReceived = 0;
-
- public void messageReceived(IoSession session, Object message) throws Exception
- {
- ByteBuffer result = (ByteBuffer) message;
- _totalBytesReceived += result.remaining();
- int size = result.remaining();
- long now = System.currentTimeMillis();
- if (_partialBytesRead > 0)
- {
- int offset = _chunkSize - _partialBytesRead;
- if (size >= offset)
- {
- _chunkTimes[_chunksReceived++] = now;
- result.position(offset);
- }
- else
- {
- // have not read even one chunk, including the previous partial bytes
- _partialBytesRead += size;
- return;
- }
- }
-
- int chunkCount = result.remaining()/_chunkSize;
-
- for (int i = 0; i < chunkCount; i++)
- {
- _chunkTimes[_chunksReceived++] = now;
- byte check = result.get();
- _logger.debug("Check number " + check + " read");
- if (check != (byte)((_chunksReceived - 1)%128))
- {
- _logger.error("Check number " + check + " read when expected " + (_chunksReceived%128));
- }
- _logger.debug("Chunk times recorded");
-
- try
- {
- result.skip(_chunkSize - 1);
- }
- catch (IllegalArgumentException e)
- {
- _logger.error("Position was: " + result.position());
- _logger.error("Tried to skip to: " + (_chunkSize * i));
- _logger.error("limit was; " + result.limit());
- }
- }
- _logger.debug("Chunks received now " + _chunksReceived);
- _logger.debug("Bytes received: " + _totalBytesReceived);
- _partialBytesRead = result.remaining();
-
- if (_partialBytesRead > 0)
- {
- _partialCheckNumber = result.get();
- }
-
- if (_chunksReceived >= _chunkCount)
- {
- _notifier.countDown();
- }
-
- }
-
- public void exceptionCaught(IoSession session, Throwable cause) throws Exception
- {
- _logger.error("Error: " + cause, cause);
- }
- }
-
- public void startWriter(int chunkSize) throws IOException, InterruptedException
- {
- _chunkSize = chunkSize;
-
- IoConnector ioConnector = null;
-
- ioConnector = new SocketConnector();
-
- SocketConnectorConfig cfg = (SocketConnectorConfig) ioConnector.getDefaultConfig();
- cfg.setThreadModel(ThreadModel.MANUAL);
- SocketSessionConfig scfg = (SocketSessionConfig) cfg.getSessionConfig();
- scfg.setTcpNoDelay(true);
- scfg.setSendBufferSize(32768);
- scfg.setReceiveBufferSize(32768);
-
- final InetSocketAddress address = new InetSocketAddress("localhost", AcceptorTest.PORT);
- _logger.info("Attempting connection to " + address);
- ConnectFuture future = ioConnector.connect(address, new WriterHandler());
- // wait for connection to complete
- future.join();
- _logger.info("Connection completed");
- // we call getSession which throws an IOException if there has been an error connecting
- _session = future.getSession();
- _chunkTimes = new long[_chunkCount];
- Thread t = new Thread(this);
- t.start();
- t.join();
- _logger.info("Test completed");
- }
- }
-
- private RunnableWriterTest _runnableWriterTest = new RunnableWriterTest(_logger);
-
- public void test1k() throws IOException, InterruptedException
- {
- _logger.info("Starting 1k test");
- _runnableWriterTest.startWriter(1024);
- }
-
- public void test2k() throws IOException, InterruptedException
- {
- _logger.info("Starting 2k test");
- _runnableWriterTest.startWriter(2048);
- }
-
- public void test4k() throws IOException, InterruptedException
- {
- _logger.info("Starting 4k test");
- _runnableWriterTest.startWriter(4096);
- }
-
- public void test8k() throws IOException, InterruptedException
- {
- _logger.info("Starting 8k test");
- _runnableWriterTest.startWriter(8192);
- }
-
- public void test16k() throws IOException, InterruptedException
- {
- _logger.info("Starting 16k test");
- _runnableWriterTest.startWriter(16384);
- }
-
- public void test32k() throws IOException, InterruptedException
- {
- _logger.info("Starting 32k test");
- _runnableWriterTest.startWriter(32768);
- }
-
- public static void main(String[] args) throws IOException, InterruptedException
- {
- WriterTest w = new WriterTest();
- //w.test1k();
- //w.test2k();
- //w.test4k();
- w.test8k();
- //w.test16k();
- //w.test32k();
- }
-
- public static junit.framework.Test suite()
- {
- return new junit.framework.TestSuite(WriterTest.class);
- }
-}
diff --git a/java/client/src/old_test/java/org/apache/qpid/multiconsumer/AMQTest.java b/java/client/src/old_test/java/org/apache/qpid/multiconsumer/AMQTest.java
deleted file mode 100644
index db02b9954a..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/multiconsumer/AMQTest.java
+++ /dev/null
@@ -1,269 +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.multiconsumer;
-
-import java.io.ByteArrayOutputStream;
-import java.util.zip.Deflater;
-import java.util.zip.Inflater;
-
-import javax.jms.Connection;
-import javax.jms.ExceptionListener;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageListener;
-import javax.jms.MessageProducer;
-import javax.jms.TextMessage;
-import javax.jms.Topic;
-
-import junit.framework.TestCase;
-
-import org.apache.commons.codec.binary.Base64;
-import org.apache.qpid.client.AMQConnectionFactory;
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQTopic;
-import org.apache.qpid.exchange.ExchangeDefaults;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.jms.Session;
-
-/**
- * Test AMQ.
- */
-public class AMQTest extends TestCase implements ExceptionListener
-{
-
- private final static String COMPRESSION_PROPNAME = "_MSGAPI_COMP";
- private final static String UTF8 = "UTF-8";
- private static final String SUBJECT = "test.amq";
- private static final String DUMMYCONTENT = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
- private static final String HUGECONTENT;
-
- private AMQConnection connect = null;
- private Session pubSession = null;
- private Session subSession = null;
- private Topic topic = null;
-
- static
- {
- StringBuilder sb = new StringBuilder(DUMMYCONTENT.length() * 115);
- for (int i = 0; i < 100; i++)
- {
- sb.append(DUMMYCONTENT);
- }
- HUGECONTENT = sb.toString();
- }
-
- private void setup() throws Exception
- {
- connect = new AMQConnection("localhost", 5672, "guest", "guest", "client1", "/");
- connect.setExceptionListener(this);
- pubSession = connect.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
- subSession = connect.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
- topic = new AMQTopic(pubSession.getDefaultTopicExchangeName(), new AMQShortString(SUBJECT));
-
- connect.start();
- }
-
- public void testMultipleListeners() throws Exception
- {
- setup();
- try
- {
- // Create 5 listeners
- MsgHandler[] listeners = new MsgHandler[5];
- for (int i = 0; i < listeners.length; i++)
- {
- listeners[i] = new MsgHandler();
- MessageConsumer subscriber = subSession.createConsumer(topic);
- subscriber.setMessageListener(listeners[i]);
- }
- MessageProducer publisher = pubSession.createProducer(topic);
- // Send a single message
- TextMessage msg = pubSession.createTextMessage();
- msg.setText(DUMMYCONTENT);
- publisher.send(msg);
- Thread.sleep(5000);
- // Check listeners to ensure they all got it
- for (int i = 0; i < listeners.length; i++)
- {
- if (listeners[i].isGotIt())
- {
- System.out.println("Got callback for listener " + i);
- }
- else
- {
- TestCase.fail("Listener " + i + " did not get callback");
- }
- }
- }
- catch (Throwable e)
- {
- System.err.println("Error: " + e);
- e.printStackTrace(System.err);
- }
- finally
- {
- close();
- }
- }
-
- public void testCompression() throws Exception
- {
- setup();
- String comp = this.compressString(HUGECONTENT);
- try
- {
- MsgHandler listener = new MsgHandler();
- MessageConsumer subscriber = subSession.createConsumer(topic);
- subscriber.setMessageListener(listener);
- MessageProducer publisher = pubSession.createProducer(topic);
-
- // Send a single message
- TextMessage msg = pubSession.createTextMessage();
- // Set the compressed text
- msg.setText(comp);
- msg.setBooleanProperty(COMPRESSION_PROPNAME, true);
- publisher.send(msg);
- Thread.sleep(1000);
- // Check listeners to ensure we got it
- if (listener.isGotIt())
- {
- System.out.println("Got callback for listener");
- }
- else
- {
- TestCase.fail("Listener did not get callback");
- }
- }
- finally
- {
- close();
- }
- }
-
- private void close() throws Exception
- {
- if (connect != null)
- {
- connect.close();
- }
- }
-
- private class MsgHandler implements MessageListener
- {
- private boolean gotIt = false;
-
- public void onMessage(Message msg)
- {
- try
- {
- TextMessage textMessage = (TextMessage) msg;
- String string = textMessage.getText();
- if (string != null && string.length() > 0)
- {
- gotIt = true;
- }
- if (textMessage.getBooleanProperty(COMPRESSION_PROPNAME))
- {
- string = inflateString(string);
- }
- System.out.println("Got callback of size " + (string==null?0:string.length()));
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
- }
-
- public boolean isGotIt()
- {
- return this.gotIt;
- }
- }
-
- private String compressString(String string) throws Exception
- {
- long start = System.currentTimeMillis();
- byte[] input = string.getBytes();
- Deflater compressor = new Deflater(Deflater.BEST_COMPRESSION);
- compressor.setInput(input);
- compressor.finish();
-
- // Get byte array from output of compressor
- ByteArrayOutputStream baos = new ByteArrayOutputStream(input.length);
- byte[] buf = new byte[1024];
- while (!compressor.finished())
- {
- int cnt = compressor.deflate(buf);
- baos.write(buf, 0, cnt);
- }
- baos.close();
- byte[] output = baos.toByteArray();
-
- // Convert byte array into String
- byte[] base64 = Base64.encodeBase64(output);
- String sComp = new String(base64, UTF8);
-
- long diff = System.currentTimeMillis() - start;
- System.out.println("Compressed text from " + input.length + " to "
- + sComp.getBytes().length + " in " + diff + " ms");
- System.out.println("Compressed text = '" + sComp + "'");
-
- return sComp;
- }
-
- private String inflateString(String string) throws Exception
- {
- byte[] input = string.getBytes();
-
- // First convert Base64 string back to binary array
- byte[] bytes = Base64.decodeBase64(input);
-
- // Set string as input data for decompressor
- Inflater decompressor = new Inflater();
- decompressor.setInput(bytes);
-
- // Decompress the data
- ByteArrayOutputStream bos = new ByteArrayOutputStream(input.length);
- byte[] buf = new byte[1024];
- while (!decompressor.finished())
- {
- int count = decompressor.inflate(buf);
- bos.write(buf, 0, count);
- }
- bos.close();
- byte[] output = bos.toByteArray();
-
- // Get the decompressed data
- return new String(output, UTF8);
- }
-
- /**
- * @see javax.jms.ExceptionListener#onException(javax.jms.JMSException)
- */
- public void onException(JMSException e)
- {
- System.err.println(e.getMessage());
- e.printStackTrace(System.err);
- }
-
-
-}
diff --git a/java/client/src/old_test/java/org/apache/qpid/pubsub1/TestPublisher.java b/java/client/src/old_test/java/org/apache/qpid/pubsub1/TestPublisher.java
deleted file mode 100644
index 37b4ff1498..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/pubsub1/TestPublisher.java
+++ /dev/null
@@ -1,176 +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.pubsub1;
-
-import org.apache.log4j.Logger;
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.exchange.ExchangeDefaults;
-import org.apache.qpid.url.URLSyntaxException;
-import org.apache.qpid.client.AMQTopic;
-import org.apache.qpid.jms.MessageProducer;
-import org.apache.qpid.jms.Session;
-
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageListener;
-import javax.jms.TextMessage;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-
-/**
- * A client that behaves as follows:
- * <ul><li>Connects to a queue, whose name is specified as a cmd-line argument</li>
- * <li>Creates a temporary queue</li>
- * <li>Creates messages containing a property that is the name of the temporary queue</li>
- * <li>Fires off a message on the original queue and waits for a response on the temporary queue</li>
- * </ul>
- *
- */
-public class TestPublisher
-{
- private static final Logger _log = Logger.getLogger(TestPublisher.class);
-
- private AMQConnection _connection;
-
- private Session _session;
-
- private class CallbackHandler implements MessageListener
- {
- private int _expectedMessageCount;
-
- private int _actualMessageCount;
-
- private long _startTime;
-
- public CallbackHandler(int expectedMessageCount, long startTime)
- {
- _expectedMessageCount = expectedMessageCount;
- _startTime = startTime;
- }
-
- public void onMessage(Message m)
- {
- if (_log.isDebugEnabled())
- {
- _log.debug("Message received: " + m);
- }
- _actualMessageCount++;
- if (_actualMessageCount%1000 == 0)
- {
- _log.info("Received message count: " + _actualMessageCount);
- }
- /*if (!"henson".equals(m.toString()))
- {
- _log.error("AbstractJMSMessage response not correct: expected 'henson' but got " + m.toString());
- }
- else
- {
- if (_log.isDebugEnabled())
- {
- _log.debug("AbstractJMSMessage " + m + " received");
- }
- else
- {
- _log.info("AbstractJMSMessage received");
- }
- } */
-
- if (_actualMessageCount == _expectedMessageCount)
- {
- long timeTaken = System.currentTimeMillis() - _startTime;
- System.out.println("Total time taken to receive " + _expectedMessageCount+ " messages was " +
- timeTaken + "ms, equivalent to " +
- (_expectedMessageCount/(timeTaken/1000.0)) + " messages per second");
- }
- }
- }
-
- public TestPublisher(String host, int port, String clientID, String commandQueueName,
- final int messageCount) throws AMQException, URLSyntaxException
- {
- try
- {
- createConnection(host, port, clientID);
-
- _session = _connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- AMQTopic destination = new AMQTopic(_session.getDefaultTopicExchangeName(), new AMQShortString(commandQueueName));
- MessageProducer producer = (MessageProducer) _session.createProducer(destination);
-
- _connection.start();
- //TextMessage msg = _session.createTextMessage(tempDestination.getQueueName() + "/Presented to in conjunction with Mahnah Mahnah and the Snowths");
- final long startTime = System.currentTimeMillis();
-
- for (int i = 0; i < messageCount; i++)
- {
- TextMessage msg = _session.createTextMessage(destination.getTopicName() + "/Presented to in conjunction with Mahnah Mahnah and the Snowths: " + i);
-
- //msg.setIntProperty("a",i % 2);
- //msg.setIntProperty("b",i % 4);
-
- producer.send(msg);
- }
- _log.info("Finished sending " + messageCount + " messages");
- }
- catch (JMSException e)
- {
- e.printStackTrace();
- }
- }
-
- private void createConnection(String host, int port, String clientID) throws AMQException, URLSyntaxException
- {
- _connection = new AMQConnection(host, port, "guest", "guest",
- clientID, "/test");
- }
-
- /**
- *
- * @param args argument 1 if present specifies the name of the temporary queue to create. Leaving it blank
- * means the server will allocate a name.
- */
- public static void main(String[] args) throws URLSyntaxException
- {
- if (args.length == 0)
- {
- System.err.println("Usage: TestPublisher <host> <port> <command queue name> <number of messages>");
- }
- try
- {
- int port = Integer.parseInt(args[1]);
- InetAddress address = InetAddress.getLocalHost();
- String clientID = address.getHostName() + System.currentTimeMillis();
- TestPublisher client = new TestPublisher(args[0], port, clientID, args[2], Integer.parseInt(args[3]));
- }
- catch (UnknownHostException e)
- {
- e.printStackTrace();
- }
- catch (AMQException e)
- {
- System.err.println("Error in client: " + e);
- e.printStackTrace();
- }
-
- //System.exit(0);
- }
-}
diff --git a/java/client/src/old_test/java/org/apache/qpid/pubsub1/TestSubscriber.java b/java/client/src/old_test/java/org/apache/qpid/pubsub1/TestSubscriber.java
deleted file mode 100644
index 450d9b3914..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/pubsub1/TestSubscriber.java
+++ /dev/null
@@ -1,122 +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.pubsub1;
-
-import org.apache.log4j.Logger;
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQTopic;
-import org.apache.qpid.jms.Session;
-import org.apache.qpid.exchange.ExchangeDefaults;
-import org.apache.qpid.framing.AMQShortString;
-
-import javax.jms.MessageConsumer;
-import javax.jms.MessageListener;
-import javax.jms.Topic;
-import java.net.InetAddress;
-
-public class TestSubscriber
-{
- private static final Logger _logger = Logger.getLogger(TestSubscriber.class);
-
- private static class TestMessageListener implements MessageListener
- {
- private String _name;
-
- private int _expectedMessageCount;
-
- private int _messageCount;
-
- private long _startTime = 0;
-
- public TestMessageListener(String name, int expectedMessageCount)
- {
- _name = name;
- _expectedMessageCount = expectedMessageCount;
- }
-
- public void onMessage(javax.jms.Message message)
- {
- if (_messageCount++ == 0)
- {
- _startTime = System.currentTimeMillis();
- }
- if (_logger.isInfoEnabled())
- {
- _logger.info(_name + " got message '" + message + "'");
- }
- if (_messageCount == _expectedMessageCount)
- {
- long totalTime = System.currentTimeMillis() - _startTime;
- _logger.error(_name + ": Total time to receive " + _messageCount + " messages was " +
- totalTime + "ms. Rate is " + (_messageCount/(totalTime/1000.0)));
- }
- if (_messageCount > _expectedMessageCount)
- {
- _logger.error("Oops! More messages received than expected (" + _messageCount + ")");
- }
- }
- }
-
- public static void main(String[] args)
- {
- _logger.info("Starting...");
-
- if (args.length != 7)
- {
- System.out.println("Usage: host port username password virtual-path expectedMessageCount selector");
- System.exit(1);
- }
- try
- {
- InetAddress address = InetAddress.getLocalHost();
- AMQConnection con1 = new AMQConnection(args[0], Integer.parseInt(args[1]), args[2], args[3],
- address.getHostName(), args[4]);
- final Session session1 = con1.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- AMQConnection con2 = new AMQConnection(args[0], Integer.parseInt(args[1]), args[2], args[3],
- address.getHostName(), args[4]);
- final Session session2 = con2.createSession(false, Session.AUTO_ACKNOWLEDGE);
- String selector = args[6];
-
- final int expectedMessageCount = Integer.parseInt(args[5]);
- _logger.info("Message selector is <" + selector + ">...");
-
- Topic t = new AMQTopic(session1.getDefaultTopicExchangeName(), new AMQShortString("cbr"));
- MessageConsumer consumer1 = session1.createConsumer(t,
- 100, false, false, selector);
- MessageConsumer consumer2 = session2.createConsumer(t,
- 100, false, false, selector);
-
- consumer1.setMessageListener(new TestMessageListener("ML 1", expectedMessageCount));
- consumer2.setMessageListener(new TestMessageListener("ML 2", expectedMessageCount));
- con1.start();
- con2.start();
- }
- catch (Throwable t)
- {
- System.err.println("Fatal error: " + t);
- t.printStackTrace();
- }
-
- System.out.println("Waiting...");
- }
-}
-
diff --git a/java/client/src/old_test/java/org/apache/qpid/test/unit/client/connection/TestManyConnections.java b/java/client/src/old_test/java/org/apache/qpid/test/unit/client/connection/TestManyConnections.java
deleted file mode 100644
index f59b36166a..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/test/unit/client/connection/TestManyConnections.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.client.connection;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.url.URLSyntaxException;
-import org.apache.qpid.client.AMQConnection;
-import org.apache.log4j.Logger;
-
-import junit.framework.TestCase;
-
-public class TestManyConnections extends TestCase
-{
- private static final Logger _log = Logger.getLogger(TestManyConnections.class);
-
- private AMQConnection[] _connections;
-
- private void createConnection(int index, String brokerHosts, String clientID, String username, String password,
- String vpath) throws AMQException, URLSyntaxException
- {
- _connections[index] = new AMQConnection(brokerHosts, username, password,
- clientID, vpath);
- }
-
- private void createConnections(int count) throws AMQException, URLSyntaxException
- {
- _connections = new AMQConnection[count];
- long startTime = System.currentTimeMillis();
- for (int i = 0; i < count; i++)
- {
- createConnection(i, "vm://:1", "myClient" + i, "guest", "guest", "test");
- }
- long endTime = System.currentTimeMillis();
- _log.info("Time to create " + count + " connections: " + (endTime - startTime) +
- "ms");
- }
-
- public void testCreate10Connections() throws AMQException, URLSyntaxException
- {
- createConnections(10);
- }
-
- public void testCreate50Connections() throws AMQException, URLSyntaxException
- {
- createConnections(50);
- }
-
- public void testCreate100Connections() throws AMQException, URLSyntaxException
- {
- createConnections(100);
- }
-
- public void testCreate250Connections() throws AMQException, URLSyntaxException
- {
- createConnections(250);
- }
-
- public void testCreate500Connections() throws AMQException, URLSyntaxException
- {
- createConnections(500);
- }
-
- public void testCreate1000Connections() throws AMQException, URLSyntaxException
- {
- createConnections(1000);
- }
-
- public void testCreate5000Connections() throws AMQException, URLSyntaxException
- {
- createConnections(5000);
- }
-
- public static junit.framework.Test suite()
- {
- return new junit.framework.TestSuite(TestManyConnections.class);
- }
-}
diff --git a/java/client/src/old_test/java/org/apache/qpid/test/unit/jndi/PropertiesFileInitialContextFactoryTest.java b/java/client/src/old_test/java/org/apache/qpid/test/unit/jndi/PropertiesFileInitialContextFactoryTest.java
deleted file mode 100644
index 5ab5722146..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/test/unit/jndi/PropertiesFileInitialContextFactoryTest.java
+++ /dev/null
@@ -1,153 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.jndi;
-
-import org.apache.qpid.client.AMQConnectionFactory;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.client.AMQTopic;
-
-import javax.naming.Context;
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-import javax.naming.spi.InitialContextFactory;
-import java.util.Properties;
-import java.io.InputStream;
-
-
-import junit.framework.TestCase;
-
-public class PropertiesFileInitialContextFactoryTest extends TestCase
-{
- InitialContextFactory contextFactory;
- Properties _properties;
- Properties _fileProperties;
-
- protected void setUp() throws Exception
- {
- super.setUp();
-
- //create simple set of hardcoded props
- _properties = new Properties();
- _properties.put("java.naming.factory.initial", "org.apache.qpid.jndi.PropertiesFileInitialContextFactory");
- _properties.put("connectionfactory.local", "amqp://guest:guest@clientid/testpath?brokerlist='vm://:1'");
- _properties.put("queue.MyQueue", "example.MyQueue");
- _properties.put("topic.ibmStocks", "stocks.nyse.ibm");
- _properties.put("destination.direct", "direct://amq.direct//directQueue");
-
- //create properties from file as a more realistic test
- _fileProperties = new Properties();
- ClassLoader cl = this.getClass().getClassLoader();
- InputStream is = cl.getResourceAsStream("org/apache/qpid/test/unit/jndi/example.properties");
- _fileProperties.load(is);
- }
-
- /**
- * Test using hardcoded properties
- */
- public void testWithoutFile()
- {
- Context ctx = null;
-
- try
- {
- ctx = new InitialContext(_properties);
- }
- catch (NamingException ne)
- {
- fail("Error loading context:" + ne);
- }
-
- checkPropertiesMatch(ctx, "Using hardcoded properties: ");
- }
-
- /**
- * Test using properties from example file
- */
- public void testWithFile()
- {
- Context ctx = null;
-
- try
- {
- ctx = new InitialContext(_fileProperties);
- }
- catch (Exception e)
- {
- fail("Error loading context:" + e);
- }
-
- checkPropertiesMatch(ctx, "Using properties from file: ");
- }
-
- public void tearDown()
- {
- _properties = null;
- _fileProperties = null;
- }
-
- public static junit.framework.Test suite()
- {
- return new junit.framework.TestSuite(PropertiesFileInitialContextFactoryTest.class);
- }
-
- private void checkPropertiesMatch(Context ctx, String errorInfo)
- {
- try
- {
- AMQConnectionFactory cf = (AMQConnectionFactory) ctx.lookup("local");
- assertEquals("amqp://guest:guest@clientid/testpath?brokerlist='vm://:1'", cf.getConnectionURL().toString());
- }
- catch (NamingException ne)
- {
- fail(errorInfo + "Unable to create Connection Factory:" + ne);
- }
-
- try
- {
- AMQQueue queue = (AMQQueue) ctx.lookup("MyQueue");
- assertEquals("example.MyQueue", queue.getRoutingKey().toString());
- }
- catch (NamingException ne)
- {
- fail(errorInfo + "Unable to create queue:" + ne);
- }
-
- try
- {
- AMQTopic topic = (AMQTopic) ctx.lookup("ibmStocks");
- assertEquals("stocks.nyse.ibm", topic.getTopicName().toString());
- }
- catch (Exception ne)
- {
- fail(errorInfo + "Unable to create topic:" + ne);
- }
-
- try
- {
- AMQQueue direct = (AMQQueue) ctx.lookup("direct");
- assertEquals("directQueue", direct.getRoutingKey().toString());
- }
- catch (NamingException ne)
- {
- fail(errorInfo + "Unable to create direct destination:" + ne);
- }
- }
-}
diff --git a/java/client/src/old_test/java/org/apache/qpid/test/unit/jndi/example.properties b/java/client/src/old_test/java/org/apache/qpid/test/unit/jndi/example.properties
deleted file mode 100644
index ea9dc5ae0e..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/test/unit/jndi/example.properties
+++ /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.
-
-java.naming.factory.initial = org.apache.qpid.jndi.PropertiesFileInitialContextFactory
-
-# use the following property to configure the default connector
-#java.naming.provider.url - ignored.
-
-# register some connection factories
-# connectionfactory.[jndiname] = [ConnectionURL]
-connectionfactory.local = amqp://guest:guest@clientid/testpath?brokerlist='vm://:1'
-
-# register some queues in JNDI using the form
-# queue.[jndiName] = [physicalName]
-queue.MyQueue = example.MyQueue
-
-# register some topics in JNDI using the form
-# topic.[jndiName] = [physicalName]
-topic.ibmStocks = stocks.nyse.ibm
-
-# Register an AMQP destination in JNDI
-# NOTE: Qpid currently only supports direct,topics and headers
-# destination.[jniName] = [BindingURL]
-destination.direct = direct://amq.direct//directQueue
diff --git a/java/client/src/old_test/java/org/apache/qpid/topic/Config.java b/java/client/src/old_test/java/org/apache/qpid/topic/Config.java
deleted file mode 100644
index bb740f9094..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/topic/Config.java
+++ /dev/null
@@ -1,243 +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.topic;
-
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.config.ConnectorConfig;
-import org.apache.qpid.config.ConnectionFactoryInitialiser;
-import org.apache.qpid.config.Connector;
-import org.apache.qpid.config.AbstractConfig;
-
-import javax.jms.Connection;
-import javax.jms.ConnectionFactory;
-
-class Config extends AbstractConfig implements ConnectorConfig
-{
-
- private String host = "localhost";
- private int port = 5672;
- private String factory = null;
-
- private int payload = 256;
- private int messages = 1000;
- private int clients = 1;
- private int batch = 1;
- private long delay = 1;
- private int warmup;
- private int ackMode= AMQSession.NO_ACKNOWLEDGE;
- private String clientId;
- private String subscriptionId;
- private boolean persistent;
-
- public Config()
- {
- }
-
- int getAckMode()
- {
- return ackMode;
- }
-
- void setPayload(int payload)
- {
- this.payload = payload;
- }
-
- int getPayload()
- {
- return payload;
- }
-
- void setClients(int clients)
- {
- this.clients = clients;
- }
-
- int getClients()
- {
- return clients;
- }
-
- void setMessages(int messages)
- {
- this.messages = messages;
- }
-
- int getMessages()
- {
- return messages;
- }
-
- public String getHost()
- {
- return host;
- }
-
- public void setHost(String host)
- {
- this.host = host;
- }
-
- public int getPort()
- {
- return port;
- }
-
- public String getFactory()
- {
- return factory;
- }
-
- public void setPort(int port)
- {
- this.port = port;
- }
-
- int getBatch()
- {
- return batch;
- }
-
- void setBatch(int batch)
- {
- this.batch = batch;
- }
-
- int getWarmup()
- {
- return warmup;
- }
-
- void setWarmup(int warmup)
- {
- this.warmup = warmup;
- }
-
- public long getDelay()
- {
- return delay;
- }
-
- public void setDelay(long delay)
- {
- this.delay = delay;
- }
-
- String getClientId()
- {
- return clientId;
- }
-
- String getSubscriptionId()
- {
- return subscriptionId;
- }
-
- boolean usePersistentMessages()
- {
- return persistent;
- }
-
- public void setOption(String key, String value)
- {
- if("-host".equalsIgnoreCase(key))
- {
- setHost(value);
- }
- else if("-port".equalsIgnoreCase(key))
- {
- try
- {
- setPort(Integer.parseInt(value));
- }
- catch(NumberFormatException e)
- {
- throw new RuntimeException("Bad port number: " + value);
- }
- }
- else if("-payload".equalsIgnoreCase(key))
- {
- setPayload(parseInt("Bad payload size", value));
- }
- else if("-messages".equalsIgnoreCase(key))
- {
- setMessages(parseInt("Bad message count", value));
- }
- else if("-clients".equalsIgnoreCase(key))
- {
- setClients(parseInt("Bad client count", value));
- }
- else if("-batch".equalsIgnoreCase(key))
- {
- setBatch(parseInt("Bad batch count", value));
- }
- else if("-delay".equalsIgnoreCase(key))
- {
- setDelay(parseLong("Bad batch delay", value));
- }
- else if("-warmup".equalsIgnoreCase(key))
- {
- setWarmup(parseInt("Bad warmup count", value));
- }
- else if("-ack".equalsIgnoreCase(key))
- {
- ackMode = parseInt("Bad ack mode", value);
- }
- else if("-factory".equalsIgnoreCase(key))
- {
- factory = value;
- }
- else if("-clientId".equalsIgnoreCase(key))
- {
- clientId = value;
- }
- else if("-subscriptionId".equalsIgnoreCase(key))
- {
- subscriptionId = value;
- }
- else if("-persistent".equalsIgnoreCase(key))
- {
- persistent = "true".equalsIgnoreCase(value);
- }
- else
- {
- System.out.println("Ignoring unrecognised option: " + key);
- }
- }
-
- static String getAckModeDescription(int ackMode)
- {
- switch(ackMode)
- {
- case AMQSession.NO_ACKNOWLEDGE: return "NO_ACKNOWLEDGE";
- case AMQSession.AUTO_ACKNOWLEDGE: return "AUTO_ACKNOWLEDGE";
- case AMQSession.CLIENT_ACKNOWLEDGE: return "CLIENT_ACKNOWLEDGE";
- case AMQSession.DUPS_OK_ACKNOWLEDGE: return "DUPS_OK_ACKNOWELDGE";
- case AMQSession.PRE_ACKNOWLEDGE: return "PRE_ACKNOWLEDGE";
- }
- return "AckMode=" + ackMode;
- }
-
- public Connection createConnection() throws Exception
- {
- return new Connector().createConnection(this);
- }
-}
diff --git a/java/client/src/old_test/java/org/apache/qpid/topic/Listener.java b/java/client/src/old_test/java/org/apache/qpid/topic/Listener.java
deleted file mode 100644
index 47c608cfe4..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/topic/Listener.java
+++ /dev/null
@@ -1,141 +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.topic;
-
-import javax.jms.Connection;
-import javax.jms.Message;
-import javax.jms.MessageListener;
-import javax.jms.MessageProducer;
-import javax.jms.Session;
-
-public class Listener implements MessageListener
-{
- private final Connection _connection;
- private final MessageProducer _controller;
- private final javax.jms.Session _session;
- private final MessageFactory _factory;
- private boolean init;
- private int count;
- private long start;
-
- Listener(Connection connection, int ackMode) throws Exception
- {
- this(connection, ackMode, null);
- }
-
- Listener(Connection connection, int ackMode, String name) throws Exception
- {
- _connection = connection;
- _session = connection.createSession(false, ackMode);
- _factory = new MessageFactory(_session);
-
- //register for events
- if(name == null)
- {
- _factory.createTopicConsumer().setMessageListener(this);
- }
- else
- {
- _factory.createDurableTopicConsumer(name).setMessageListener(this);
- }
-
- _connection.start();
-
- _controller = _factory.createControlPublisher();
- System.out.println("Waiting for messages " +
- Config.getAckModeDescription(ackMode)
- + (name == null ? "" : " (subscribed with name " + name + " and client id " + connection.getClientID() + ")")
- + "...");
-
- }
-
- private void shutdown()
- {
- try
- {
- _session.close();
- _connection.stop();
- _connection.close();
- }
- catch(Exception e)
- {
- e.printStackTrace(System.out);
- }
- }
-
- private void report()
- {
- try
- {
- String msg = getReport();
- _controller.send(_factory.createReportResponseMessage(msg));
- System.out.println("Sent report: " + msg);
- }
- catch(Exception e)
- {
- e.printStackTrace(System.out);
- }
- }
-
- private String getReport()
- {
- long time = (System.currentTimeMillis() - start);
- return "Received " + count + " in " + time + "ms";
- }
-
- public void onMessage(Message message)
- {
- if(!init)
- {
- start = System.currentTimeMillis();
- count = 0;
- init = true;
- }
-
- if(_factory.isShutdown(message))
- {
- shutdown();
- }
- else if(_factory.isReport(message))
- {
- //send a report:
- report();
- init = false;
- }
- else if (++count % 100 == 0)
- {
- System.out.println("Received " + count + " messages.");
- }
- }
-
- public static void main(String[] argv) throws Exception
- {
- Config config = new Config();
- config.setOptions(argv);
-
- Connection con = config.createConnection();
- if(config.getClientId() != null)
- {
- con.setClientID(config.getClientId());
- }
- new Listener(con, config.getAckMode(), config.getSubscriptionId());
- }
-}
diff --git a/java/client/src/old_test/java/org/apache/qpid/topic/MessageFactory.java b/java/client/src/old_test/java/org/apache/qpid/topic/MessageFactory.java
deleted file mode 100644
index 39d64069d1..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/topic/MessageFactory.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.
- *
- */
-package org.apache.qpid.topic;
-
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.client.AMQTopic;
-import org.apache.qpid.exchange.ExchangeDefaults;
-import org.apache.qpid.framing.AMQShortString;
-
-import javax.jms.*;
-
-/**
- */
-class MessageFactory
-{
- private static final char[] DATA = "abcdefghijklmnopqrstuvwxyz".toCharArray();
-
- private final Session _session;
- private final Topic _topic;
- private final Topic _control;
- private final byte[] _payload;
-
-
- MessageFactory(Session session) throws JMSException
- {
- this(session, 256);
- }
-
- MessageFactory(Session session, int size) throws JMSException
- {
- _session = session;
- if(session instanceof AMQSession)
- {
- _topic = new AMQTopic(((AMQSession)session).getDefaultTopicExchangeName(),new AMQShortString("topictest.messages"));
- _control = new AMQTopic(((AMQSession)session).getDefaultTopicExchangeName(),new AMQShortString("topictest.control"));
- }
- else
- {
- _topic = session.createTopic("topictest.messages");
- _control = session.createTopic("topictest.control");
- }
- _payload = new byte[size];
-
- for(int i = 0; i < size; i++)
- {
- _payload[i] = (byte) DATA[i % DATA.length];
- }
- }
-
- Topic getTopic()
- {
- return _topic;
- }
-
- Message createEventMessage() throws JMSException
- {
- BytesMessage msg = _session.createBytesMessage();
- msg.writeBytes(_payload);
- return msg;
- }
-
- Message createShutdownMessage() throws JMSException
- {
- return _session.createTextMessage("SHUTDOWN");
- }
-
- Message createReportRequestMessage() throws JMSException
- {
- return _session.createTextMessage("REPORT");
- }
-
- Message createReportResponseMessage(String msg) throws JMSException
- {
- return _session.createTextMessage(msg);
- }
-
- boolean isShutdown(Message m)
- {
- return checkText(m, "SHUTDOWN");
- }
-
- boolean isReport(Message m)
- {
- return checkText(m, "REPORT");
- }
-
- Object getReport(Message m)
- {
- try
- {
- return ((TextMessage) m).getText();
- }
- catch (JMSException e)
- {
- e.printStackTrace(System.out);
- return e.toString();
- }
- }
-
- MessageConsumer createTopicConsumer() throws Exception
- {
- return _session.createConsumer(_topic);
- }
-
- MessageConsumer createDurableTopicConsumer(String name) throws Exception
- {
- return _session.createDurableSubscriber(_topic, name);
- }
-
- MessageConsumer createControlConsumer() throws Exception
- {
- return _session.createConsumer(_control);
- }
-
- MessageProducer createTopicPublisher() throws Exception
- {
- return _session.createProducer(_topic);
- }
-
- MessageProducer createControlPublisher() throws Exception
- {
- return _session.createProducer(_control);
- }
-
- private static boolean checkText(Message m, String s)
- {
- try
- {
- return m instanceof TextMessage && ((TextMessage) m).getText().equals(s);
- }
- catch (JMSException e)
- {
- e.printStackTrace(System.out);
- return false;
- }
- }
-}
diff --git a/java/client/src/old_test/java/org/apache/qpid/topic/Publisher.java b/java/client/src/old_test/java/org/apache/qpid/topic/Publisher.java
deleted file mode 100644
index d788029ee9..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/topic/Publisher.java
+++ /dev/null
@@ -1,175 +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.topic;
-
-import javax.jms.*;
-
-public class Publisher implements MessageListener
-{
- private final Object _lock = new Object();
- private final Connection _connection;
- private final Session _session;
- private final MessageFactory _factory;
- private final MessageProducer _publisher;
- private int _count;
-
- Publisher(Connection connection, int size, int ackMode, boolean persistent) throws Exception
- {
- _connection = connection;
- _session = _connection.createSession(false, ackMode);
- _factory = new MessageFactory(_session, size);
- _publisher = _factory.createTopicPublisher();
- _publisher.setDeliveryMode(persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT);
- System.out.println("Publishing " + (persistent ? "persistent" : "non-persistent") + " messages of " + size + " bytes, " + Config.getAckModeDescription(ackMode) + ".");
- }
-
- private void test(Config config) throws Exception
- {
- test(config.getBatch(), config.getDelay(), config.getMessages(), config.getClients(), config.getWarmup());
- }
-
- private void test(int batches, long delay, int msgCount, int consumerCount, int warmup) throws Exception
- {
- _factory.createControlConsumer().setMessageListener(this);
- _connection.start();
-
- if(warmup > 0)
- {
- System.out.println("Runing warmup (" + warmup + " msgs)");
- long time = batch(warmup, consumerCount);
- System.out.println("Warmup completed in " + time + "ms");
- }
-
- long[] times = new long[batches];
- for(int i = 0; i < batches; i++)
- {
- if(i > 0) Thread.sleep(delay*1000);
- times[i] = batch(msgCount, consumerCount);
- System.out.println("Batch " + (i+1) + " of " + batches + " completed in " + times[i] + " ms.");
- }
-
- long min = min(times);
- long max = max(times);
- System.out.println("min: " + min + ", max: " + max + " avg: " + avg(times, min, max));
-
- //request shutdown
- _publisher.send(_factory.createShutdownMessage());
-
- _connection.stop();
- _connection.close();
- }
-
- private long batch(int msgCount, int consumerCount) throws Exception
- {
- _count = consumerCount;
- long start = System.currentTimeMillis();
- publish(msgCount);
- waitForCompletion(consumerCount);
- return System.currentTimeMillis() - start;
- }
-
- private void publish(int count) throws Exception
- {
-
- //send events
- for (int i = 0; i < count; i++)
- {
- _publisher.send(_factory.createEventMessage());
- if ((i + 1) % 100 == 0)
- {
- System.out.println("Sent " + (i + 1) + " messages");
- }
- }
-
- //request report
- _publisher.send(_factory.createReportRequestMessage());
- }
-
- private void waitForCompletion(int consumers) throws Exception
- {
- System.out.println("Waiting for completion...");
- synchronized (_lock)
- {
- while (_count > 0)
- {
- _lock.wait();
- }
- }
- }
-
-
- public void onMessage(Message message)
- {
- System.out.println("Received report " + _factory.getReport(message) + " " + --_count + " remaining");
- if (_count == 0)
- {
- synchronized (_lock)
- {
- _lock.notify();
- }
- }
- }
-
- static long min(long[] times)
- {
- long min = times.length > 0 ? times[0] : 0;
- for(int i = 0; i < times.length; i++)
- {
- min = Math.min(min, times[i]);
- }
- return min;
- }
-
- static long max(long[] times)
- {
- long max = times.length > 0 ? times[0] : 0;
- for(int i = 0; i < times.length; i++)
- {
- max = Math.max(max, times[i]);
- }
- return max;
- }
-
- static long avg(long[] times, long min, long max)
- {
- long sum = 0;
- for(int i = 0; i < times.length; i++)
- {
- sum += times[i];
- }
- sum -= min;
- sum -= max;
-
- return (sum / (times.length - 2));
- }
-
- public static void main(String[] argv) throws Exception
- {
- Config config = new Config();
- config.setOptions(argv);
-
- Connection con = config.createConnection();
- int size = config.getPayload();
- int ackMode = config.getAckMode();
- boolean persistent = config.usePersistentMessages();
- new Publisher(con, size, ackMode, persistent).test(config);
- }
-}
diff --git a/java/client/src/old_test/java/org/apache/qpid/transacted/Config.java b/java/client/src/old_test/java/org/apache/qpid/transacted/Config.java
deleted file mode 100644
index bd104e5407..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/transacted/Config.java
+++ /dev/null
@@ -1,110 +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.transacted;
-
-import org.apache.qpid.config.ConnectorConfig;
-import org.apache.qpid.config.AbstractConfig;
-import org.apache.qpid.config.Connector;
-
-import javax.jms.Connection;
-
-class Config extends AbstractConfig implements ConnectorConfig
-{
- private String host = "localhost";
- private int port = 5672;
- private String factory;
- private boolean echo;
- private int batch = 100;
- private boolean persistent = true;
-
- Config(String[] argv)
- {
- setOptions(argv);
- }
-
- Connection createConnection() throws Exception
- {
- return new Connector().createConnection(this);
- }
-
- public boolean isEchoOn()
- {
- return echo;
- }
-
- public boolean usePersistentMessages()
- {
- return persistent;
- }
-
- public int getBatchSize()
- {
- return batch;
- }
-
- public String getHost()
- {
- return host;
- }
-
- public int getPort()
- {
- return port;
- }
-
- public String getFactory()
- {
- return factory;
- }
-
- public void setOption(String key, String value)
- {
- if("-host".equalsIgnoreCase(key))
- {
- host = value;
- }
- else if("-port".equalsIgnoreCase(key))
- {
- port = parseInt("Bad port number", value);
- }
- else if("-factory".equalsIgnoreCase(key))
- {
- factory = value;
- }
- else if("-echo".equalsIgnoreCase(key))
- {
- echo = "true".equalsIgnoreCase(value);
- }
- else if("-persistent".equalsIgnoreCase(key))
- {
- persistent = "true".equalsIgnoreCase(value);
- }
- else if("-batch".equalsIgnoreCase(key))
- {
- batch = parseInt("Bad batch size", value);
- }
- else
- {
- System.out.println("Ignoring nrecognised option " + key);
- }
- }
-
-}
diff --git a/java/client/src/old_test/java/org/apache/qpid/transacted/Ping.java b/java/client/src/old_test/java/org/apache/qpid/transacted/Ping.java
deleted file mode 100644
index 8f15bf089e..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/transacted/Ping.java
+++ /dev/null
@@ -1,45 +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.transacted;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.exchange.ExchangeDefaults;
-import org.apache.qpid.client.AMQQueue;
-
-import javax.jms.Connection;
-import javax.jms.JMSException;
-import java.util.Arrays;
-
-public class Ping
-{
- public static void main(String[] argv) throws Exception
- {
- Config config = new Config(argv);
- Connection con = config.createConnection();
- con.setClientID("ping");
- new Relay(new AMQQueue(ExchangeDefaults.DIRECT_EXCHANGE_NAME, new AMQShortString("ping")), new AMQQueue(ExchangeDefaults.DIRECT_EXCHANGE_NAME, new AMQShortString("pong")), con,
- config.isEchoOn(),
- config.getBatchSize(),
- config.usePersistentMessages()).start();
- }
-}
diff --git a/java/client/src/old_test/java/org/apache/qpid/transacted/Pong.java b/java/client/src/old_test/java/org/apache/qpid/transacted/Pong.java
deleted file mode 100644
index f4f4b20d7c..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/transacted/Pong.java
+++ /dev/null
@@ -1,45 +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.transacted;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.exchange.ExchangeDefaults;
-import org.apache.qpid.client.AMQQueue;
-
-import javax.jms.Connection;
-import javax.jms.JMSException;
-
-public class Pong
-{
- public static void main(String[] argv) throws Exception
- {
- Config config = new Config(argv);
- Connection con = config.createConnection();
- con.setClientID("pong");
- new Relay(new AMQQueue(ExchangeDefaults.DIRECT_EXCHANGE_NAME, new AMQShortString("pong")), new AMQQueue(ExchangeDefaults.DIRECT_EXCHANGE_NAME, new AMQShortString("ping")), con,
- config.isEchoOn(),
- config.getBatchSize(),
- config.usePersistentMessages()).start();
-
- }
-}
diff --git a/java/client/src/old_test/java/org/apache/qpid/transacted/Relay.java b/java/client/src/old_test/java/org/apache/qpid/transacted/Relay.java
deleted file mode 100644
index cede95e5f0..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/transacted/Relay.java
+++ /dev/null
@@ -1,127 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.transacted;
-
-import org.apache.qpid.client.AMQSession;
-
-import javax.jms.MessageProducer;
-import javax.jms.MessageConsumer;
-import javax.jms.Session;
-import javax.jms.Destination;
-import javax.jms.Connection;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.TextMessage;
-import javax.jms.DeliveryMode;
-
-class Relay implements Runnable
-{
- private final Connection _con;
- private final Session _session;
- private final MessageConsumer _src;
- private final MessageProducer _dest;
- private final int _batch;
- private final boolean _echo;
- private int _counter;
- private long start;
- private boolean _running;
-
- Relay(Destination src, Destination dest, Connection con) throws JMSException
- {
- this(src, dest, con, false, 100, true);
- }
-
- Relay(Destination src, Destination dest, Connection con, boolean echo, int batch, boolean persistent) throws JMSException
- {
- _echo = echo;
- _batch = batch;
- _con = con;
- _session = con.createSession(true, AMQSession.NO_ACKNOWLEDGE);
- _src = _session.createConsumer(src);
- _dest = _session.createProducer(dest);
- _dest.setDeliveryMode(persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT);
-
- }
-
- public void run()
- {
- start = System.currentTimeMillis();
- try{
- while(true) relay();
- }
- catch(JMSException e)
- {
- e.printStackTrace();
- }
- try
- {
- _session.close();
- }
- catch (JMSException e)
- {
- e.printStackTrace();
- }
- }
-
- void relay() throws JMSException
- {
- _dest.send(relay(_src.receive()));
- _session.commit();
- }
-
- Message relay(Message in) throws JMSException
- {
- if(!_running)
- {
- System.out.println(_con.getClientID() + " started.");
- _running = true;
- }
- if(++_counter % _batch == 0)
- {
- long time = System.currentTimeMillis() - start;
- System.out.println(_batch + " iterations performed in " + time + " ms");
- try
- {
- Thread.sleep(100);
- }
- catch (InterruptedException e)
- {
- e.printStackTrace();
- }
- start = System.currentTimeMillis();
- }
- if(_echo)
- {
- System.out.println("Received: " + ((TextMessage) in).getText());
- }
- return _session.createTextMessage(_con.getClientID() + _counter);
- }
-
- void start() throws InterruptedException, JMSException
- {
- Thread runner = new Thread(this);
- runner.start();
- _con.start();
- System.out.println(_con.getClientID() + " waiting...");
- runner.join();
- _con.close();
- }
-}
diff --git a/java/client/src/old_test/java/org/apache/qpid/transacted/Start.java b/java/client/src/old_test/java/org/apache/qpid/transacted/Start.java
deleted file mode 100644
index de718d828a..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/transacted/Start.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.transacted;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.exchange.ExchangeDefaults;
-import org.apache.qpid.client.AMQQueue;
-
-import javax.jms.Connection;
-import javax.jms.JMSException;
-import javax.jms.Session;
-
-public class Start
-{
- public static void main(String[] argv) throws Exception
- {
- Connection con = new Config(argv).createConnection();
- AMQQueue ping = new AMQQueue(ExchangeDefaults.DIRECT_EXCHANGE_NAME, new AMQShortString("ping"));
- Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
- session.createProducer(ping).send(session.createTextMessage("start"));
- session.close();
- con.close();
- }
-}
diff --git a/java/client/src/old_test/java/org/apache/qpid/weblogic/ServiceProvider.java b/java/client/src/old_test/java/org/apache/qpid/weblogic/ServiceProvider.java
deleted file mode 100644
index 71d806b338..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/weblogic/ServiceProvider.java
+++ /dev/null
@@ -1,151 +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.weblogic;
-
-import org.apache.log4j.Logger;
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQDestination;
-
-import javax.jms.*;
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-import javax.naming.Context;
-import java.net.InetAddress;
-import java.util.Hashtable;
-
-public class ServiceProvider
-{
- private static final String JNDI_FACTORY = "weblogic.jndi.WLInitialContextFactory";
- private static final String JMS_FACTORY = "transientJMSConnectionFactory";
-
- private static final Logger _logger = Logger.getLogger(ServiceProvider.class);
-
- private static MessageProducer _destinationProducer;
-
- private static Queue _destinationQ;
-
- public static void main(String[] args)
- {
- _logger.info("Starting...");
-
- if (args.length != 2)
- {
- System.out.println("Usage: <WLS URI> <service queue>");
- System.exit(1);
- }
- try
- {
- String url = args[0];
- String receiveQueue = args[1];
-
- final InitialContext ctx = getInitialContext(url);
-
- QueueConnectionFactory qconFactory = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY);
- QueueConnection qcon = qconFactory.createQueueConnection();
- final QueueSession qsession = qcon.createQueueSession(false, Session.CLIENT_ACKNOWLEDGE);
- Queue receiveQ = (Queue) ctx.lookup(receiveQueue);
-
- _logger.info("Service (queue) name is '" + receiveQ + "'...");
-
- String selector = (args.length > 2 && args[2] != null && args[2].length() > 1) ? args[2] : null;
-
- _logger.info("Message selector is <" + selector + ">...");
-
- MessageConsumer consumer = qsession.createConsumer(receiveQ, selector);
-
- consumer.setMessageListener(new MessageListener()
- {
- private int _messageCount;
-
- public void onMessage(javax.jms.Message message)
- {
- //_logger.info("Got message '" + message + "'");
-
- TextMessage tm = (TextMessage) message;
-
- try
- {
- Queue responseQueue = (Queue)tm.getJMSReplyTo();
- if (!responseQueue.equals(_destinationQ))
- {
- _destinationQ = responseQueue;
- _logger.info("Creating destination for " + responseQueue);
-
- try
- {
- _destinationProducer = qsession.createProducer(_destinationQ);
- _destinationProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
- }
- catch (JMSException e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- _messageCount++;
- if (_messageCount % 1000 == 0)
- {
- _logger.info("Received message total: " + _messageCount);
- _logger.info("Sending response to '" + responseQueue + "'");
- }
-
- String payload = "This is a response: sing together: 'Mahnah mahnah...'" + tm.getText();
- TextMessage msg = qsession.createTextMessage(payload);
- if (tm.propertyExists("timeSent"))
- {
- _logger.info("timeSent property set on message");
- final long timeSent = tm.getLongProperty("timeSent");
- msg.setLongProperty("timeSent", timeSent);
- _logger.info("time taken to go from service request to provider is: " + (System.currentTimeMillis() - timeSent));
- }
- _destinationProducer.send(msg);
- if (_messageCount % 1000 == 0)
- {
- tm.acknowledge();
- _logger.info("Sent response to '" + responseQueue + "'");
- }
- }
- catch (JMSException e)
- {
- _logger.error("Error sending message: " + e, e);
- }
- }
- });
- qcon.start();
- }
- catch (Throwable t)
- {
- System.err.println("Fatal error: " + t);
- t.printStackTrace();
- }
-
-
- System.out.println("Waiting...");
- }
-
- private static InitialContext getInitialContext(String url) throws NamingException
- {
- Hashtable env = new Hashtable();
- env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
- env.put(Context.PROVIDER_URL, url);
- return new InitialContext(env);
- }
-}
diff --git a/java/client/src/old_test/java/org/apache/qpid/weblogic/ServiceRequestingClient.java b/java/client/src/old_test/java/org/apache/qpid/weblogic/ServiceRequestingClient.java
deleted file mode 100644
index 2f64a1dde5..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/weblogic/ServiceRequestingClient.java
+++ /dev/null
@@ -1,185 +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.weblogic;
-
-import org.apache.log4j.Logger;
-
-import javax.jms.*;
-import javax.naming.Context;
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-import java.util.Hashtable;
-
-/**
- * Created by IntelliJ IDEA.
- * User: U806869
- * Date: 28-May-2005
- * Time: 21:54:51
- * To change this template use File | Settings | File Templates.
- */
-public class ServiceRequestingClient
-{
- private static final Logger _log = Logger.getLogger(ServiceRequestingClient.class);
- private static final String JNDI_FACTORY = "weblogic.jndi.WLInitialContextFactory";
- private static final String JMS_FACTORY = "transientJMSConnectionFactory";
-
- private static class CallbackHandler implements MessageListener
- {
- private int _expectedMessageCount;
-
- private int _actualMessageCount;
-
- private long _startTime;
-
- private long _averageLatency;
-
- public CallbackHandler(int expectedMessageCount, long startTime)
- {
- _expectedMessageCount = expectedMessageCount;
- _startTime = startTime;
- }
-
- public void onMessage(Message m)
- {
- if (_log.isDebugEnabled())
- {
- _log.debug("Message received: " + m);
- }
- try
- {
- if (m.propertyExists("timeSent"))
- {
- long timeSent = m.getLongProperty("timeSent");
- long now = System.currentTimeMillis();
- if (_averageLatency == 0)
- {
- _averageLatency = now - timeSent;
- _log.info("Latency " + _averageLatency);
- }
- else
- {
- _log.info("Individual latency: " + (now-timeSent));
- _averageLatency = (_averageLatency + (now - timeSent))/2;
- _log.info("Average latency now: " + _averageLatency);
- }
- }
- }
- catch (JMSException e)
- {
- _log.error("Could not calculate latency");
- }
-
- _actualMessageCount++;
- if (_actualMessageCount%1000 == 0)
- {
- try
- {
- m.acknowledge();
- }
- catch (JMSException e)
- {
- _log.error("Error acknowledging message");
- }
- _log.info("Received message count: " + _actualMessageCount);
- }
- /*if (!"henson".equals(m.toString()))
- {
- _log.error("Message response not correct: expected 'henson' but got " + m.toString());
- }
- else
- {
- if (_log.isDebugEnabled())
- {
- _log.debug("Message " + m + " received");
- }
- else
- {
- _log.info("Message received");
- }
- } */
-
- if (_actualMessageCount == _expectedMessageCount)
- {
- long timeTaken = System.currentTimeMillis() - _startTime;
- System.out.println("Total time taken to receive " + _expectedMessageCount+ " messages was " +
- timeTaken + "ms, equivalent to " +
- (_expectedMessageCount/(timeTaken/1000.0)) + " messages per second");
- System.out.println("Average latency is: " + _averageLatency);
- }
- }
- }
-
- public static void main(String[] args) throws Exception
- {
- if (args.length != 3)
- {
- System.out.println("Usage: IXPublisher <WLS URL> <sendQueue> <count> will publish count messages to ");
- System.out.println("queue sendQueue and waits for a response on a temp queue");
- System.exit(1);
- }
-
- String url = args[0];
- String sendQueue = args[1];
- int messageCount = Integer.parseInt(args[2]);
-
- InitialContext ctx = getInitialContext(url);
-
- QueueConnectionFactory qconFactory = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY);
- QueueConnection qcon = qconFactory.createQueueConnection();
- QueueSession qsession = qcon.createQueueSession(false, Session.CLIENT_ACKNOWLEDGE);
- Queue sendQ = (Queue) ctx.lookup(sendQueue);
- Queue receiveQ = qsession.createTemporaryQueue();
- QueueSender qsender = qsession.createSender(sendQ);
- qsender.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
- _log.debug("Queue sender created for service queue " + sendQ);
-
- javax.jms.MessageConsumer messageConsumer = (javax.jms.MessageConsumer) qsession.createConsumer(receiveQ);
-
- //TextMessage msg = _session.createTextMessage(tempDestination.getQueueName() + "/Presented to in conjunction with Mahnah Mahnah and the Snowths");
- final long startTime = System.currentTimeMillis();
-
- messageConsumer.setMessageListener(new CallbackHandler(messageCount, startTime));
- qcon.start();
- for (int i = 0; i < messageCount; i++)
- {
- TextMessage msg = qsession.createTextMessage("/Presented to in conjunction with Mahnah Mahnah and the Snowths:" + i);
- msg.setJMSReplyTo(receiveQ);
- if (i%1000 == 0)
- {
- long timeNow = System.currentTimeMillis();
- msg.setLongProperty("timeSent", timeNow);
- }
- qsender.send(msg);
- }
-
- new Thread("foo").start();
- //qsession.close();
- //qcon.close();
- }
-
- private static InitialContext getInitialContext(String url) throws NamingException
- {
- Hashtable env = new Hashtable();
- env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
- env.put(Context.PROVIDER_URL, url);
- return new InitialContext(env);
- }
-}
diff --git a/java/client/src/test/java/org/apache/mina/transport/vmpipe/support/VmPipeIdleStatusChecker.java b/java/client/src/test/java/org/apache/mina/transport/vmpipe/support/VmPipeIdleStatusChecker.java
deleted file mode 100644
index 5323ad28bf..0000000000
--- a/java/client/src/test/java/org/apache/mina/transport/vmpipe/support/VmPipeIdleStatusChecker.java
+++ /dev/null
@@ -1,125 +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.mina.transport.vmpipe.support;
-
-import org.apache.mina.common.IdleStatus;
-
-import java.util.HashMap;
-import java.util.IdentityHashMap;
-import java.util.Iterator;
-import java.util.Map;
-
-/**
- * This file is a patch to override MINA, because of the IdentityHashMap bug. Workaround to be supplied in MINA 1.0.7.
- * This patched file will be removed once upgraded onto a newer MINA.
- *
- * Dectects idle sessions and fires <tt>sessionIdle</tt> events to them.
- *
- * @author The Apache Directory Project (mina-dev@directory.apache.org)
- */
-public class VmPipeIdleStatusChecker
-{
- private static final VmPipeIdleStatusChecker INSTANCE = new VmPipeIdleStatusChecker();
-
- public static VmPipeIdleStatusChecker getInstance()
- {
- return INSTANCE;
- }
-
- private final Map sessions = new HashMap(); // will use as a set
-
- private final Worker worker = new Worker();
-
- private VmPipeIdleStatusChecker()
- {
- worker.start();
- }
-
- public void addSession(VmPipeSessionImpl session)
- {
- synchronized (sessions)
- {
- sessions.put(session, session);
- }
- }
-
- private class Worker extends Thread
- {
- private Worker()
- {
- super("VmPipeIdleStatusChecker");
- setDaemon(true);
- }
-
- public void run()
- {
- for (;;)
- {
- try
- {
- Thread.sleep(1000);
- }
- catch (InterruptedException e)
- { }
-
- long currentTime = System.currentTimeMillis();
-
- synchronized (sessions)
- {
- Iterator it = sessions.keySet().iterator();
- while (it.hasNext())
- {
- VmPipeSessionImpl session = (VmPipeSessionImpl) it.next();
- if (!session.isConnected())
- {
- it.remove();
- }
- else
- {
- notifyIdleSession(session, currentTime);
- }
- }
- }
- }
- }
- }
-
- private void notifyIdleSession(VmPipeSessionImpl session, long currentTime)
- {
- notifyIdleSession0(session, currentTime, session.getIdleTimeInMillis(IdleStatus.BOTH_IDLE), IdleStatus.BOTH_IDLE,
- Math.max(session.getLastIoTime(), session.getLastIdleTime(IdleStatus.BOTH_IDLE)));
- notifyIdleSession0(session, currentTime, session.getIdleTimeInMillis(IdleStatus.READER_IDLE), IdleStatus.READER_IDLE,
- Math.max(session.getLastReadTime(), session.getLastIdleTime(IdleStatus.READER_IDLE)));
- notifyIdleSession0(session, currentTime, session.getIdleTimeInMillis(IdleStatus.WRITER_IDLE), IdleStatus.WRITER_IDLE,
- Math.max(session.getLastWriteTime(), session.getLastIdleTime(IdleStatus.WRITER_IDLE)));
- }
-
- private void notifyIdleSession0(VmPipeSessionImpl session, long currentTime, long idleTime, IdleStatus status,
- long lastIoTime)
- {
- if ((idleTime > 0) && (lastIoTime != 0) && ((currentTime - lastIoTime) >= idleTime))
- {
- session.increaseIdleCount(status);
- session.getFilterChain().fireSessionIdle(session, status);
- }
- }
-
-}
diff --git a/java/client/src/test/java/org/apache/qpid/client/AMQQueueTest.java b/java/client/src/test/java/org/apache/qpid/client/AMQQueueTest.java
deleted file mode 100644
index 7789f87ace..0000000000
--- a/java/client/src/test/java/org/apache/qpid/client/AMQQueueTest.java
+++ /dev/null
@@ -1,42 +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.client;
-
-import org.apache.qpid.framing.AMQShortString;
-
-import junit.framework.TestCase;
-
-public class AMQQueueTest extends TestCase
-{
- AMQShortString exchange = new AMQShortString("test.exchange");
- AMQShortString routingkey = new AMQShortString("test-route");
- AMQShortString qname = new AMQShortString("test-queue");
- AMQShortString[] oneBinding = new AMQShortString[]{new AMQShortString("bindingA")};
- AMQShortString[] bindings = new AMQShortString[]{new AMQShortString("bindingB"),
- new AMQShortString("bindingC")};
-
- public void testToURLNoBindings()
- {
- AMQQueue dest = new AMQQueue(exchange, routingkey, qname);
- String url = dest.toURL();
- assertEquals("direct://test.exchange/test-route/test-queue?routingkey='test-route'", url);
- }
-}
diff --git a/java/client/src/test/java/org/apache/qpid/client/MockAMQConnection.java b/java/client/src/test/java/org/apache/qpid/client/MockAMQConnection.java
deleted file mode 100644
index da44822ec3..0000000000
--- a/java/client/src/test/java/org/apache/qpid/client/MockAMQConnection.java
+++ /dev/null
@@ -1,94 +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.client;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.state.AMQState;
-import org.apache.qpid.framing.ProtocolVersion;
-import org.apache.qpid.jms.ConnectionURL;
-import org.apache.qpid.jms.BrokerDetails;
-import org.apache.qpid.url.URLSyntaxException;
-
-import java.io.IOException;
-
-public class MockAMQConnection extends AMQConnection
-{
- public MockAMQConnection(String broker, String username, String password, String clientName, String virtualHost)
- throws AMQException, URLSyntaxException
- {
- super(broker, username, password, clientName, virtualHost);
- }
-
- public MockAMQConnection(String broker, String username, String password, String clientName, String virtualHost, SSLConfiguration sslConfig)
- throws AMQException, URLSyntaxException
- {
- super(broker, username, password, clientName, virtualHost, sslConfig);
- }
-
- public MockAMQConnection(String host, int port, String username, String password, String clientName, String virtualHost)
- throws AMQException, URLSyntaxException
- {
- super(host, port, username, password, clientName, virtualHost);
- }
-
- public MockAMQConnection(String host, int port, String username, String password, String clientName, String virtualHost, SSLConfiguration sslConfig)
- throws AMQException, URLSyntaxException
- {
- super(host, port, username, password, clientName, virtualHost, sslConfig);
- }
-
- public MockAMQConnection(String host, int port, boolean useSSL, String username, String password, String clientName, String virtualHost, SSLConfiguration sslConfig)
- throws AMQException, URLSyntaxException
- {
- super(host, port, useSSL, username, password, clientName, virtualHost, sslConfig);
- }
-
- public MockAMQConnection(String connection)
- throws AMQException, URLSyntaxException
- {
- super(connection);
- }
-
- public MockAMQConnection(String connection, SSLConfiguration sslConfig)
- throws AMQException, URLSyntaxException
- {
- super(connection, sslConfig);
- }
-
- public MockAMQConnection(ConnectionURL connectionURL, SSLConfiguration sslConfig)
- throws AMQException
- {
- super(connectionURL, sslConfig);
- }
-
- protected MockAMQConnection(String username, String password, String clientName, String virtualHost)
- {
- super(username, password, clientName, virtualHost);
- }
-
- @Override
- public ProtocolVersion makeBrokerConnection(BrokerDetails brokerDetail) throws IOException
- {
- _connected = true;
- _protocolHandler.getStateManager().changeState(AMQState.CONNECTION_OPEN);
- return null;
- }
-}
diff --git a/java/client/src/test/java/org/apache/qpid/client/message/AbstractJMSMessageTest.java b/java/client/src/test/java/org/apache/qpid/client/message/AbstractJMSMessageTest.java
deleted file mode 100644
index f81f482c6a..0000000000
--- a/java/client/src/test/java/org/apache/qpid/client/message/AbstractJMSMessageTest.java
+++ /dev/null
@@ -1,57 +0,0 @@
-package org.apache.qpid.client.message;
-/*
- *
- * 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 javax.jms.JMSException;
-
-import junit.framework.TestCase;
-
-public class AbstractJMSMessageTest extends TestCase
-{
-
- public void testSetNullJMSReplyTo08() throws JMSException
- {
- JMSTextMessage message = new JMSTextMessage(AMQMessageDelegateFactory.FACTORY_0_8);
- try
- {
- message.setJMSReplyTo(null);
- }
- catch (IllegalArgumentException e)
- {
- fail("Null destination should be allowed");
- }
- }
-
- public void testSetNullJMSReplyTo10() throws JMSException
- {
- JMSTextMessage message = new JMSTextMessage(AMQMessageDelegateFactory.FACTORY_0_10);
- try
- {
- message.setJMSReplyTo(null);
- }
- catch (IllegalArgumentException e)
- {
- fail("Null destination should be allowed");
- }
- }
-
-}
diff --git a/java/client/src/test/java/org/apache/qpid/client/message/TestMessageHelper.java b/java/client/src/test/java/org/apache/qpid/client/message/TestMessageHelper.java
deleted file mode 100644
index 7ee991b63c..0000000000
--- a/java/client/src/test/java/org/apache/qpid/client/message/TestMessageHelper.java
+++ /dev/null
@@ -1,46 +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.client.message;
-
-import javax.jms.JMSException;
-
-public class TestMessageHelper
-{
- public static JMSTextMessage newJMSTextMessage() throws JMSException
- {
- return new JMSTextMessage(AMQMessageDelegateFactory.FACTORY_0_8);
- }
-
- public static JMSBytesMessage newJMSBytesMessage() throws JMSException
- {
- return new JMSBytesMessage(AMQMessageDelegateFactory.FACTORY_0_8);
- }
-
- public static JMSMapMessage newJMSMapMessage() throws JMSException
- {
- return new JMSMapMessage(AMQMessageDelegateFactory.FACTORY_0_8);
- }
-
- public static JMSStreamMessage newJMSStreamMessage()
- {
- return new JMSStreamMessage(AMQMessageDelegateFactory.FACTORY_0_8);
- }
-}
diff --git a/java/client/src/test/java/org/apache/qpid/client/protocol/AMQProtocolHandlerTest.java b/java/client/src/test/java/org/apache/qpid/client/protocol/AMQProtocolHandlerTest.java
deleted file mode 100644
index f520a21ba0..0000000000
--- a/java/client/src/test/java/org/apache/qpid/client/protocol/AMQProtocolHandlerTest.java
+++ /dev/null
@@ -1,289 +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.client.protocol;
-
-import junit.framework.TestCase;
-import org.apache.qpid.framing.AMQFrame;
-import org.apache.qpid.framing.AMQBody;
-import org.apache.qpid.framing.AMQMethodBody;
-import org.apache.qpid.framing.amqp_8_0.BasicRecoverOkBodyImpl;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.protocol.AMQConstant;
-import org.apache.qpid.transport.TestNetworkDriver;
-import org.apache.qpid.client.MockAMQConnection;
-import org.apache.qpid.client.AMQAuthenticationException;
-import org.apache.qpid.client.state.AMQState;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-/**
- * This is a test address QPID-1431 where frame listeners would fail to be notified of an incomming exception.
- *
- * Currently we do checks at the Session level to ensure that the connection/session are open. However, it is possible
- * for the connection to close AFTER this check has been performed.
- *
- * Performing a similar check at the frameListener level in AMQProtocolHandler makes most sence as this will prevent
- * listening when there can be no returning frames.
- *
- * With the correction in place it also means that the new listener will either make it on to the list for notification
- * or it will be notified of any existing exception due to the connection being closed.
- *
- * There may still be an issue in this space if the client utilises a second thread to close the session as there will
- * be no exception set to throw and so the wait will occur. That said when the session is closed the framelisteners
- * should be notified. Not sure this is tested.
- */
-public class AMQProtocolHandlerTest extends TestCase
-{
- private static final Logger _logger = LoggerFactory.getLogger(AMQProtocolHandlerTest.class);
-
- // The handler to test
- AMQProtocolHandler _handler;
-
- // A frame to block upon whilst waiting the exception
- AMQFrame _blockFrame;
-
- // Latch to know when the listener receives an exception
- private CountDownLatch _handleCountDown;
- // The listener that will receive an exception
- BlockToAccessFrameListener _listener;
-
- @Override
- public void setUp() throws Exception
- {
- //Create a new ProtocolHandler with a fake connection.
- _handler = new AMQProtocolHandler(new MockAMQConnection("amqp://guest:guest@client/test?brokerlist='vm://:1'"));
- _handler.setNetworkDriver(new TestNetworkDriver());
- AMQBody body = BasicRecoverOkBodyImpl.getFactory().newInstance(null, 1);
- _blockFrame = new AMQFrame(0, body);
-
- _handleCountDown = new CountDownLatch(1);
-
- _logger.info("Creating _Listener that should also receive the thrown exception.");
- _listener = new BlockToAccessFrameListener(1);
- }
-
- /**
- * There are two paths based on the type of exception thrown.
- *
- * This tests that when an AMQException is thrown we get the same type of AMQException back with the real exception
- * wrapped as the cause.
- *
- * @throws InterruptedException - if we are unable to wait for the test signals
- */
- public void testFrameListenerUpdateWithAMQException() throws InterruptedException
- {
- AMQException trigger = new AMQAuthenticationException(AMQConstant.ACCESS_REFUSED,
- "AMQPHTest", new RuntimeException());
-
- performWithException(trigger);
-
-
- AMQException receivedException = (AMQException) _listener.getReceivedException();
-
- assertEquals("Return exception was not the expected type",
- AMQAuthenticationException.class, receivedException.getClass());
-
- assertEquals("The _Listener did not receive the correct error code",
- trigger.getErrorCode(), receivedException.getErrorCode());
- }
-
- /**
- * There are two paths based on the type of exception thrown.
- *
- * This tests that when a generic Exception is thrown we get the exception back wrapped in a AMQException
- * as the cause.
- * @throws InterruptedException - if we are unable to wait for the test signals
- */
- public void testFrameListenerUpdateWithException() throws InterruptedException
- {
-
- Exception trigger = new Exception(new RuntimeException());
-
- performWithException(trigger);
-
- assertEquals("The _Listener did not receive the correct error code",
- AMQConstant.INTERNAL_ERROR, ((AMQException)_listener.getReceivedException()).getErrorCode());
- }
-
- /**
- * This is the main test method for both test cases.
- *
- * What occurs is that we create a new thread that will block (<30s[DEFAULT]) for a frame or exception to occur .
- *
- * We use a CountDownLatch to ensure that the new thread is running before we then yield and sleep to help ensure
- * the new thread has entered the synchronized block in the writeCommandFrameAndWaitForReply.
- *
- * We can then ack like an the incomming exception handler in (ConnectionCloseMethodHandler).
- *
- * We fire the error to the stateManager, which in this case will recored the error as there are no state listeners.
- *
- * We then set the connection to be closed, as we would normally close the socket at this point.
- *
- * Then fire the exception in to any frameListeners.
- *
- * The blocked listener (created above) when receiving the error simulates the user by creating a new request to
- * block for a frame.
- *
- * This request should fail. Prior to the fix this will fail with a NPE as we are attempting to use a null listener
- * in the writeCommand.... call L:268.
- *
- * This highlights that the listener would be added dispite there being a pending error state that the listener will
- * miss as it is not currently part of the _frameListeners set that is being notified by the iterator.
- *
- * The method waits to ensure that an exception is received before returning.
- *
- * The calling methods validate that exception that was received based on the one they sent in.
- *
- * @param trigger The exception to throw through the handler
- */
- private void performWithException(Exception trigger) throws InterruptedException
- {
-
- final CountDownLatch callingWriteCommand = new CountDownLatch(1);
-
- //Set an initial listener that will allow us to create a new blocking method
- new Thread(new Runnable()
- {
- public void run()
- {
-
- try
- {
-
- _logger.info("At initial block, signalling to fire new exception");
- callingWriteCommand.countDown();
-
- _handler.writeCommandFrameAndWaitForReply(_blockFrame, _listener);
- }
- catch (Exception e)
- {
- e.printStackTrace();
- fail(e.getMessage());
- }
- }
- }).start();
-
- _logger.info("Waiting for 'initial block' to start ");
- if (!callingWriteCommand.await(1000, TimeUnit.MILLISECONDS))
- {
- fail("Failed to start new thread to block for frame");
- }
-
- // Do what we can to ensure that this thread does not continue before the above thread has hit the synchronized
- // block in the writeCommandFrameAndWaitForReply
- Thread.yield();
- Thread.sleep(1000);
-
- _logger.info("Firing Erorr through state manager. There should be not state waiters here.");
- _handler.getStateManager().error(trigger);
-
- _logger.info("Setting state to be CONNECTION_CLOSED.");
-
- _handler.getStateManager().changeState(AMQState.CONNECTION_CLOSED);
-
- _logger.info("Firing exception");
- _handler.propagateExceptionToFrameListeners(trigger);
-
- _logger.info("Awaiting notifcation from handler that exception arrived.");
-
- if (!_handleCountDown.await(2000, TimeUnit.MILLISECONDS))
- {
- fail("Failed to handle exception and timeout has not occured");
- }
-
-
- assertNotNull("The _Listener did not receive the exception", _listener.getReceivedException());
-
- assertTrue("Received exception not an AMQException",
- _listener.getReceivedException() instanceof AMQException);
-
- AMQException receivedException = (AMQException) _listener.getReceivedException();
-
- assertTrue("The _Listener did not receive the correct message",
- receivedException.getMessage().startsWith(trigger.getMessage()));
-
-
- assertEquals("The _Listener did not receive the correct cause",
- trigger, receivedException.getCause());
-
- assertEquals("The _Listener did not receive the correct sub cause",
- trigger.getCause(), receivedException.getCause().getCause());
-
- }
-
- class BlockToAccessFrameListener extends BlockingMethodFrameListener
- {
- private Exception _receivedException = null;
-
- /**
- * Creates a new method listener, that filters incoming method to just those that match the specified channel id.
- *
- * @param channelId The channel id to filter incoming methods with.
- */
- public BlockToAccessFrameListener(int channelId)
- {
- super(channelId);
- _logger.info("Creating a listener:" + this);
- }
-
- public boolean processMethod(int channelId, AMQMethodBody frame)
- {
- return true;
- }
-
- @Override
- public void error(Exception e)
- {
- _logger.info("Exception(" + e + ") Received by:" + this);
- // Create a new Thread to start the blocking registration.
- new Thread(new Runnable()
- {
-
- public void run()
- {
- //Set an initial listener that will allow us to create a new blocking method
- try
- {
- _handler.writeCommandFrameAndWaitForReply(_blockFrame, null, 2000L);
- _logger.info("listener(" + this + ") Wait completed");
- }
- catch (Exception e)
- {
- _logger.info("listener(" + this + ") threw exception:" + e.getMessage());
- _receivedException = e;
- }
-
- _logger.info("listener(" + this + ") completed");
- _handleCountDown.countDown();
- }
- }).start();
- }
-
- public Exception getReceivedException()
- {
- return _receivedException;
- }
- }
-
-}
diff --git a/java/client/src/test/java/org/apache/qpid/client/protocol/MockIoSession.java b/java/client/src/test/java/org/apache/qpid/client/protocol/MockIoSession.java
deleted file mode 100644
index f0938a4bc0..0000000000
--- a/java/client/src/test/java/org/apache/qpid/client/protocol/MockIoSession.java
+++ /dev/null
@@ -1,312 +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.client.protocol;
-
-import org.apache.mina.common.*;
-import org.apache.mina.common.support.DefaultCloseFuture;
-import org.apache.mina.common.support.DefaultWriteFuture;
-import org.apache.mina.common.support.AbstractIoFilterChain;
-import org.apache.qpid.client.protocol.AMQProtocolSession;
-
-import java.net.SocketAddress;
-import java.net.InetSocketAddress;
-import java.util.Set;
-
-public class MockIoSession implements IoSession
-{
- private AMQProtocolSession _protocolSession;
-
- /**
- * Stores the last response written
- */
- private Object _lastWrittenObject;
-
- private boolean _closing;
- private IoFilterChain _filterChain;
-
- public MockIoSession()
- {
- _filterChain = new AbstractIoFilterChain(this)
- {
- protected void doWrite(IoSession ioSession, IoFilter.WriteRequest writeRequest) throws Exception
- {
-
- }
-
- protected void doClose(IoSession ioSession) throws Exception
- {
-
- }
- };
- }
-
- public Object getLastWrittenObject()
- {
- return _lastWrittenObject;
- }
-
- public IoService getService()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public IoServiceConfig getServiceConfig()
- {
- return null;
- }
-
- public IoHandler getHandler()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public IoSessionConfig getConfig()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public IoFilterChain getFilterChain()
- {
- return _filterChain;
- }
-
- public WriteFuture write(Object message)
- {
- WriteFuture wf = new DefaultWriteFuture(null);
- _lastWrittenObject = message;
- return wf;
- }
-
- public CloseFuture close()
- {
- _closing = true;
- CloseFuture cf = new DefaultCloseFuture(null);
- cf.setClosed();
- return cf;
- }
-
- public Object getAttachment()
- {
- return _protocolSession;
- }
-
- public Object setAttachment(Object attachment)
- {
- Object current = _protocolSession;
- _protocolSession = (AMQProtocolSession) attachment;
- return current;
- }
-
- public Object getAttribute(String key)
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public Object setAttribute(String key, Object value)
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public Object setAttribute(String key)
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public Object removeAttribute(String key)
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean containsAttribute(String key)
- {
- return false; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public Set getAttributeKeys()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public TransportType getTransportType()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean isConnected()
- {
- return false; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean isClosing()
- {
- return _closing;
- }
-
- public CloseFuture getCloseFuture()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public SocketAddress getRemoteAddress()
- {
- return new InetSocketAddress("127.0.0.1", 1234); //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public SocketAddress getLocalAddress()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public SocketAddress getServiceAddress()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public int getIdleTime(IdleStatus status)
- {
- return 0; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public long getIdleTimeInMillis(IdleStatus status)
- {
- return 0; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void setIdleTime(IdleStatus status, int idleTime)
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public int getWriteTimeout()
- {
- return 0; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public long getWriteTimeoutInMillis()
- {
- return 0; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void setWriteTimeout(int writeTimeout)
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public TrafficMask getTrafficMask()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void setTrafficMask(TrafficMask trafficMask)
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void suspendRead()
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void suspendWrite()
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void resumeRead()
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void resumeWrite()
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public long getReadBytes()
- {
- return 0; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public long getWrittenBytes()
- {
- return 0; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public long getReadMessages()
- {
- return 0L;
- }
-
- public long getWrittenMessages()
- {
- return 0L;
- }
-
- public long getWrittenWriteRequests()
- {
- return 0; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public int getScheduledWriteRequests()
- {
- return 0; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public int getScheduledWriteBytes()
- {
- return 0; //TODO
- }
-
- public long getCreationTime()
- {
- return 0; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public long getLastIoTime()
- {
- return 0; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public long getLastReadTime()
- {
- return 0; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public long getLastWriteTime()
- {
- return 0; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean isIdle(IdleStatus status)
- {
- return false; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public int getIdleCount(IdleStatus status)
- {
- return 0; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public long getLastIdleTime(IdleStatus status)
- {
- return 0; //To change body of implemented methods use File | Settings | File Templates.
- }
-}
diff --git a/java/client/src/test/java/org/apache/qpid/jms/FailoverPolicyTest.java b/java/client/src/test/java/org/apache/qpid/jms/FailoverPolicyTest.java
deleted file mode 100644
index 438995aedc..0000000000
--- a/java/client/src/test/java/org/apache/qpid/jms/FailoverPolicyTest.java
+++ /dev/null
@@ -1,338 +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.jms;
-
-import javax.jms.ConnectionConsumer;
-import javax.jms.ConnectionMetaData;
-import javax.jms.Destination;
-import javax.jms.ExceptionListener;
-import javax.jms.JMSException;
-import javax.jms.ServerSessionPool;
-import javax.jms.Topic;
-
-import org.apache.qpid.client.AMQConnectionURL;
-import org.apache.qpid.jms.failover.FailoverExchangeMethod;
-import org.apache.qpid.jms.failover.FailoverMethod;
-import org.apache.qpid.jms.failover.FailoverRoundRobinServers;
-import org.apache.qpid.jms.failover.FailoverSingleServer;
-import org.apache.qpid.jms.failover.NoFailover;
-
-import junit.framework.TestCase;
-
-/**
- * Tests the ability of FailoverPolicy to instantiate the correct FailoverMethod.
- *
- * This test presently does <i>not</i> test {@link FailoverPolicy#FailoverPolicy(FailoverMethod) or
- * {@link FailoverPolicy#addMethod(FailoverMethod)} as it appears that this functionality
- * is no longer in use.
- *
- */
-public class FailoverPolicyTest extends TestCase
-{
- private FailoverPolicy _failoverPolicy = null; // class under test
- private String _url;
- private Connection _connection = null;
- private ConnectionURL _connectionUrl = null;
-
- /**
- * Tests single server method is selected for a brokerlist with one broker when
- * the failover option is not specified.
- */
- public void testBrokerListWithOneBrokerDefaultsToSingleServerPolicy() throws Exception
- {
- _url = "amqp://user:pass@clientid/test?brokerlist='tcp://localhost:5672'";
- _connectionUrl = new AMQConnectionURL(_url);
- _connection = createStubConnection();
-
- _failoverPolicy = new FailoverPolicy(_connectionUrl, _connection);
-
- assertTrue("Unexpected failover method", _failoverPolicy.getCurrentMethod() instanceof FailoverSingleServer);
- }
-
- /**
- * Tests round robin method is selected for a brokerlist with two brokers when
- * the failover option is not specified.
- */
- public void testBrokerListWithTwoBrokersDefaultsToRoundRobinPolicy() throws Exception
- {
- _url = "amqp://user:pass@clientid/test?brokerlist='tcp://localhost:5672;tcp://localhost:5673'";
- _connectionUrl = new AMQConnectionURL(_url);
- _connection = createStubConnection();
-
- _failoverPolicy = new FailoverPolicy(_connectionUrl, _connection);
-
- assertTrue("Unexpected failover method", _failoverPolicy.getCurrentMethod() instanceof FailoverRoundRobinServers);
- }
-
- /**
- * Tests single server method is selected for a brokerlist with one broker when
- * the failover option passed as 'singlebroker'.
- */
- public void testExplictFailoverOptionSingleBroker() throws Exception
- {
- _url = "amqp://user:pass@clientid/test?brokerlist='tcp://localhost:5672'&failover='singlebroker'";
- _connectionUrl = new AMQConnectionURL(_url);
- _connection = createStubConnection();
-
- _failoverPolicy = new FailoverPolicy(_connectionUrl, _connection);
-
- assertTrue("Unexpected failover method", _failoverPolicy.getCurrentMethod() instanceof FailoverSingleServer);
- }
-
- /**
- * Tests round robin method is selected for a brokerlist with two brokers when
- * the failover option passed as 'roundrobin'.
- */
- public void testExplictFailoverOptionRoundrobin() throws Exception
- {
- _url = "amqp://user:pass@clientid/test?brokerlist='tcp://localhost:5672;tcp://localhost:5673'&failover='roundrobin'";
- _connectionUrl = new AMQConnectionURL(_url);
- _connection = createStubConnection();
-
- _failoverPolicy = new FailoverPolicy(_connectionUrl, _connection);
-
- assertTrue("Unexpected failover method", _failoverPolicy.getCurrentMethod() instanceof FailoverRoundRobinServers);
- }
-
- /**
- * Tests no failover method is selected for a brokerlist with one broker when
- * the failover option passed as 'nofailover'.
- */
- public void testExplictFailoverOptionNofailover() throws Exception
- {
- _url = "amqp://user:pass@clientid/test?brokerlist='tcp://localhost:5672'&failover='nofailover'";
- _connectionUrl = new AMQConnectionURL(_url);
- _connection = createStubConnection();
-
- _failoverPolicy = new FailoverPolicy(_connectionUrl, _connection);
-
- assertTrue("Unexpected failover method", _failoverPolicy.getCurrentMethod() instanceof NoFailover);
- }
-
- /**
- * Tests failover exchange method is selected for a brokerlist with one broker when
- * the failover option passed as 'failover_exchange'.
- */
- public void testExplictFailoverOptionFailoverExchange() throws Exception
- {
- _url = "amqp://user:pass@clientid/test?brokerlist='tcp://localhost:5672'&failover='failover_exchange'";
- _connectionUrl = new AMQConnectionURL(_url);
- _connection = createStubConnection();
-
- _failoverPolicy = new FailoverPolicy(_connectionUrl, _connection);
-
- assertTrue("Unexpected failover method", _failoverPolicy.getCurrentMethod() instanceof FailoverExchangeMethod);
- }
-
- /**
- * Tests that a custom method can be selected for a brokerlist with one brokers when
- * the failover option passed as a qualified class-name.
- */
- public void testExplictFailoverOptionDynamicallyLoadedFailoverMethod() throws Exception
- {
- _url = "amqp://user:pass@clientid/test?brokerlist='tcp://localhost:5672'&failover='org.apache.qpid.jms.FailoverPolicyTest$MyFailoverMethod'";
- _connectionUrl = new AMQConnectionURL(_url);
- _connection = createStubConnection();
-
- _failoverPolicy = new FailoverPolicy(_connectionUrl, _connection);
-
- assertTrue("Unexpected failover method", _failoverPolicy.getCurrentMethod() instanceof MyFailoverMethod);
- }
-
- /**
- * Tests that an unknown method caused an exception.
- */
- public void testUnknownFailoverMethod() throws Exception
- {
- _url = "amqp://user:pass@clientid/test?brokerlist='tcp://localhost:5672'&failover='unknown'";
- _connectionUrl = new AMQConnectionURL(_url);
- _connection = createStubConnection();
-
- try
- {
- new FailoverPolicy(_connectionUrl, _connection);
- fail("Exception not thrown");
- }
- catch(IllegalArgumentException iae)
- {
- // PASS
- }
- }
-
- private Connection createStubConnection()
- {
- return new Connection()
- {
-
- @Override
- public Session createSession(boolean transacted,
- int acknowledgeMode, int prefetch) throws JMSException
- {
- return null;
- }
-
- @Override
- public Session createSession(boolean transacted,
- int acknowledgeMode, int prefetchHigh, int prefetchLow)
- throws JMSException
- {
- return null;
- }
-
- @Override
- public ConnectionListener getConnectionListener()
- {
- return null;
- }
-
- @Override
- public long getMaximumChannelCount() throws JMSException
- {
- return 0;
- }
-
- @Override
- public void setConnectionListener(ConnectionListener listener)
- {
- }
-
- @Override
- public void close() throws JMSException
- {
- }
-
- @Override
- public ConnectionConsumer createConnectionConsumer(
- Destination arg0, String arg1, ServerSessionPool arg2,
- int arg3) throws JMSException
- {
- return null;
- }
-
- @Override
- public ConnectionConsumer createDurableConnectionConsumer(
- Topic arg0, String arg1, String arg2,
- ServerSessionPool arg3, int arg4) throws JMSException
- {
- return null;
- }
-
- @Override
- public javax.jms.Session createSession(boolean arg0, int arg1)
- throws JMSException
- {
- return null;
- }
-
- @Override
- public String getClientID() throws JMSException
- {
- return null;
- }
-
- @Override
- public ExceptionListener getExceptionListener() throws JMSException
- {
- return null;
- }
-
- @Override
- public ConnectionMetaData getMetaData() throws JMSException
- {
- return null;
- }
-
- @Override
- public void setClientID(String arg0) throws JMSException
- {
- }
-
- @Override
- public void setExceptionListener(ExceptionListener arg0)
- throws JMSException
- {
- }
-
- @Override
- public void start() throws JMSException
- {
- }
-
- @Override
- public void stop() throws JMSException
- {
- }
- };
- }
-
- // Class used to test the ability of FailoverPolicy to load an implementation.
- static class MyFailoverMethod implements FailoverMethod
- {
- public MyFailoverMethod(ConnectionURL connectionDetails)
- {
- }
-
- @Override
- public void attainedConnection()
- {
- }
-
- @Override
- public boolean failoverAllowed()
- {
- return false;
- }
-
- @Override
- public BrokerDetails getCurrentBrokerDetails()
- {
- return null;
- }
-
- @Override
- public BrokerDetails getNextBrokerDetails()
- {
- return null;
- }
-
- @Override
- public String methodName()
- {
- return null;
- }
-
- @Override
- public void reset()
- {
- }
-
- @Override
- public void setBroker(BrokerDetails broker)
- {
- }
-
- @Override
- public void setRetries(int maxRetries)
- {
- }
- }
-
-}
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/basic/FieldTableKeyEnumeratorTest.java b/java/client/src/test/java/org/apache/qpid/test/unit/basic/FieldTableKeyEnumeratorTest.java
deleted file mode 100644
index ddbc69826d..0000000000
--- a/java/client/src/test/java/org/apache/qpid/test/unit/basic/FieldTableKeyEnumeratorTest.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.basic;
-
-import java.util.Enumeration;
-import java.util.Iterator;
-import java.util.NoSuchElementException;
-
-import javax.jms.JMSException;
-
-import junit.framework.TestCase;
-
-import org.apache.qpid.client.message.JMSTextMessage;
-import org.apache.qpid.client.message.TestMessageHelper;
-import org.apache.qpid.framing.FieldTable;
-import org.apache.qpid.framing.FieldTableFactory;
-
-public class FieldTableKeyEnumeratorTest extends TestCase
-{
- public void testTrue()
- {
-
- }
- public void testKeyEnumeration()
- {
- FieldTable result = FieldTableFactory.newFieldTable();
- result.setObject("one", 1L);
- result.setObject("two", 2L);
- result.setObject("three", 3L);
- result.setObject("four", 4L);
- result.setObject("five", 5L);
-
- Iterator iterator = result.keys().iterator();
-
- try
- {
- assertTrue("one".equals(iterator.next()));
- assertTrue("two".equals(iterator.next()));
- assertTrue("three".equals(iterator.next()));
- assertTrue("four".equals(iterator.next()));
- assertTrue("five".equals(iterator.next()));
- }
- catch (NoSuchElementException e)
- {
- fail("All elements should be found.");
- }
-
- }
-
- public void testPropertEnu()
- {
- try
- {
- JMSTextMessage text = TestMessageHelper.newJMSTextMessage();
-
- text.setBooleanProperty("Boolean1", true);
- text.setBooleanProperty("Boolean2", true);
- text.setIntProperty("Int", 2);
- text.setLongProperty("Long", 2);
-
- Enumeration e = text.getPropertyNames();
-
- assertTrue("Boolean1".equals(e.nextElement()));
- assertTrue("Boolean2".equals(e.nextElement()));
- assertTrue("Int".equals(e.nextElement()));
- assertTrue("Long".equals(e.nextElement()));
- }
- catch (JMSException e)
- {
-
- }
- }
-
- public static junit.framework.Test suite()
- {
- return new junit.framework.TestSuite(FieldTableKeyEnumeratorTest.class);
- }
-}
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/basic/FieldTablePropertyTest.java b/java/client/src/test/java/org/apache/qpid/test/unit/basic/FieldTablePropertyTest.java
deleted file mode 100644
index 60ed688897..0000000000
--- a/java/client/src/test/java/org/apache/qpid/test/unit/basic/FieldTablePropertyTest.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.basic;
-
-import java.util.Enumeration;
-
-import javax.jms.JMSException;
-
-import junit.framework.TestCase;
-
-import org.apache.qpid.client.message.JMSTextMessage;
-import org.apache.qpid.client.message.TestMessageHelper;
-
-public class FieldTablePropertyTest extends TestCase
-{
- public void testPropertyNames()
- {
- try
- {
- JMSTextMessage text = TestMessageHelper.newJMSTextMessage();
-
- text.setBooleanProperty("Boolean1", true);
- text.setBooleanProperty("Boolean2", true);
- text.setIntProperty("Int", 2);
- text.setLongProperty("Long", 2);
-
- Enumeration e = text.getPropertyNames();
-
- assertEquals("Boolean1", e.nextElement());
- assertTrue("Boolean2".equals(e.nextElement()));
- assertTrue("Int".equals(e.nextElement()));
- assertTrue("Long".equals(e.nextElement()));
- }
- catch (JMSException e)
- {
-
- }
- }
-
- public static junit.framework.Test suite()
- {
- return new junit.framework.TestSuite(FieldTablePropertyTest.class);
- }
-}
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/client/BrokerDetails/BrokerDetailsTest.java b/java/client/src/test/java/org/apache/qpid/test/unit/client/BrokerDetails/BrokerDetailsTest.java
deleted file mode 100644
index 1b27ff6300..0000000000
--- a/java/client/src/test/java/org/apache/qpid/test/unit/client/BrokerDetails/BrokerDetailsTest.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.test.unit.client.BrokerDetails;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import junit.framework.TestCase;
-
-import org.apache.qpid.client.AMQBrokerDetails;
-import org.apache.qpid.client.AMQConnectionURL;
-import org.apache.qpid.jms.ConnectionURL;
-import org.apache.qpid.jms.BrokerDetails;
-import org.apache.qpid.url.URLSyntaxException;
-
-public class BrokerDetailsTest extends TestCase
-{
- public void testMultiParameters() throws URLSyntaxException
- {
- String url = "tcp://localhost:5672?timeout='200',immediatedelivery='true'";
-
- AMQBrokerDetails broker = new AMQBrokerDetails(url);
-
- assertTrue(broker.getProperty("timeout").equals("200"));
- assertTrue(broker.getProperty("immediatedelivery").equals("true"));
- }
-
- public void testVMBroker() throws URLSyntaxException
- {
- String url = "vm://:2";
-
- AMQBrokerDetails broker = new AMQBrokerDetails(url);
- assertTrue(broker.getTransport().equals("vm"));
- assertEquals(broker.getPort(), 2);
- }
-
- public void testTransportsDefaultToTCP() throws URLSyntaxException
- {
- String url = "localhost:5672";
-
- AMQBrokerDetails broker = new AMQBrokerDetails(url);
- assertTrue(broker.getTransport().equals("tcp"));
- }
-
- public void testCheckDefaultPort() throws URLSyntaxException
- {
- String url = "tcp://localhost";
-
- AMQBrokerDetails broker = new AMQBrokerDetails(url);
- assertTrue(broker.getPort() == AMQBrokerDetails.DEFAULT_PORT);
- }
-
- public void testBothDefaults() throws URLSyntaxException
- {
- String url = "localhost";
-
- AMQBrokerDetails broker = new AMQBrokerDetails(url);
-
- assertTrue(broker.getTransport().equals("tcp"));
- assertTrue(broker.getPort() == AMQBrokerDetails.DEFAULT_PORT);
- }
-
- public void testWrongOptionSeparatorInBroker()
- {
- String url = "tcp://localhost:5672+option='value'";
- try
- {
- new AMQBrokerDetails(url);
- }
- catch (URLSyntaxException urise)
- {
- assertTrue(urise.getReason().equals("Illegal character in port number"));
- }
-
- }
-
- public static junit.framework.Test suite()
- {
- return new junit.framework.TestSuite(BrokerDetailsTest.class);
- }
-}
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/client/channelclose/ChannelCloseMethodHandlerNoCloseOk.java b/java/client/src/test/java/org/apache/qpid/test/unit/client/channelclose/ChannelCloseMethodHandlerNoCloseOk.java
deleted file mode 100644
index 66f220643c..0000000000
--- a/java/client/src/test/java/org/apache/qpid/test/unit/client/channelclose/ChannelCloseMethodHandlerNoCloseOk.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- *
- */
-package org.apache.qpid.test.unit.client.channelclose;
-
-import org.apache.qpid.AMQChannelClosedException;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.AMQInvalidArgumentException;
-import org.apache.qpid.AMQInvalidRoutingKeyException;
-import org.apache.qpid.client.AMQNoConsumersException;
-import org.apache.qpid.client.AMQNoRouteException;
-import org.apache.qpid.client.protocol.AMQProtocolSession;
-import org.apache.qpid.client.state.StateAwareMethodListener;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.ChannelCloseBody;
-import org.apache.qpid.protocol.AMQConstant;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class ChannelCloseMethodHandlerNoCloseOk implements StateAwareMethodListener<ChannelCloseBody>
-{
- private static final Logger _logger = LoggerFactory.getLogger(ChannelCloseMethodHandlerNoCloseOk.class);
-
- private static ChannelCloseMethodHandlerNoCloseOk _handler = new ChannelCloseMethodHandlerNoCloseOk();
-
- public static ChannelCloseMethodHandlerNoCloseOk getInstance()
- {
- return _handler;
- }
-
- public void methodReceived(AMQProtocolSession session, ChannelCloseBody method, int channelId)
- throws AMQException
- {
- _logger.debug("ChannelClose method received");
-
- AMQConstant errorCode = AMQConstant.getConstant(method.getReplyCode());
- AMQShortString reason = method.getReplyText();
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Channel close reply code: " + errorCode + ", reason: " + reason);
- }
-
- // For this test Method Handler .. don't send Close-OK
- // // TODO: Be aware of possible changes to parameter order as versions change.
- // AMQFrame frame = ChannelCloseOkBody.createAMQFrame(evt.getChannelId(), method.getMajor(), method.getMinor());
- // protocolSession.writeFrame(frame);
- if (errorCode != AMQConstant.REPLY_SUCCESS)
- {
- _logger.error("Channel close received with errorCode " + errorCode + ", and reason " + reason);
- if (errorCode == AMQConstant.NO_CONSUMERS)
- {
- throw new AMQNoConsumersException("Error: " + reason, null, null);
- }
- else if (errorCode == AMQConstant.NO_ROUTE)
- {
- throw new AMQNoRouteException("Error: " + reason, null, null);
- }
- else if (errorCode == AMQConstant.INVALID_ARGUMENT)
- {
- _logger.debug("Broker responded with Invalid Argument.");
-
- throw new AMQInvalidArgumentException(String.valueOf(reason), null);
- }
- else if (errorCode == AMQConstant.INVALID_ROUTING_KEY)
- {
- _logger.debug("Broker responded with Invalid Routing Key.");
-
- throw new AMQInvalidRoutingKeyException(String.valueOf(reason), null);
- }
- else
- {
- throw new AMQChannelClosedException(errorCode, "Error: " + reason, null);
- }
-
- }
-
- session.channelClosed(channelId, errorCode, String.valueOf(reason));
- }
-}
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/client/channelclose/NoCloseOKStateManager.java b/java/client/src/test/java/org/apache/qpid/test/unit/client/channelclose/NoCloseOKStateManager.java
deleted file mode 100644
index c7eb745566..0000000000
--- a/java/client/src/test/java/org/apache/qpid/test/unit/client/channelclose/NoCloseOKStateManager.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- *
- */
-package org.apache.qpid.test.unit.client.channelclose;
-
-import org.apache.qpid.client.state.AMQStateManager;
-import org.apache.qpid.client.state.AMQState;
-import org.apache.qpid.client.handler.ConnectionStartMethodHandler;
-import org.apache.qpid.client.handler.ConnectionCloseMethodHandler;
-import org.apache.qpid.client.handler.ConnectionTuneMethodHandler;
-import org.apache.qpid.client.handler.ConnectionSecureMethodHandler;
-import org.apache.qpid.client.handler.ConnectionOpenOkMethodHandler;
-import org.apache.qpid.client.handler.ChannelCloseOkMethodHandler;
-import org.apache.qpid.client.handler.BasicDeliverMethodHandler;
-import org.apache.qpid.client.handler.BasicReturnMethodHandler;
-import org.apache.qpid.client.handler.BasicCancelOkMethodHandler;
-import org.apache.qpid.client.handler.ChannelFlowOkMethodHandler;
-import org.apache.qpid.client.handler.QueueDeleteOkMethodHandler;
-import org.apache.qpid.client.handler.ExchangeBoundOkMethodHandler;
-import org.apache.qpid.client.protocol.AMQProtocolSession;
-import org.apache.qpid.framing.ConnectionStartBody;
-import org.apache.qpid.framing.ConnectionCloseBody;
-import org.apache.qpid.framing.ConnectionTuneBody;
-import org.apache.qpid.framing.ConnectionSecureBody;
-import org.apache.qpid.framing.ConnectionOpenOkBody;
-import org.apache.qpid.framing.ChannelCloseBody;
-import org.apache.qpid.framing.ChannelCloseOkBody;
-import org.apache.qpid.framing.BasicDeliverBody;
-import org.apache.qpid.framing.BasicReturnBody;
-import org.apache.qpid.framing.BasicCancelOkBody;
-import org.apache.qpid.framing.ChannelFlowOkBody;
-import org.apache.qpid.framing.QueueDeleteOkBody;
-import org.apache.qpid.framing.ExchangeBoundOkBody;
-
-import java.util.Map;
-import java.util.HashMap;
-
-public class NoCloseOKStateManager extends AMQStateManager
-{
- public NoCloseOKStateManager(AMQProtocolSession protocolSession)
- {
- super(protocolSession);
- }
-
-
-
-
-}
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/client/connectionurl/ConnectionURLTest.java b/java/client/src/test/java/org/apache/qpid/test/unit/client/connectionurl/ConnectionURLTest.java
deleted file mode 100644
index 2c5fa0112e..0000000000
--- a/java/client/src/test/java/org/apache/qpid/test/unit/client/connectionurl/ConnectionURLTest.java
+++ /dev/null
@@ -1,588 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.client.connectionurl;
-
-import junit.framework.TestCase;
-
-import org.apache.qpid.client.AMQBrokerDetails;
-import org.apache.qpid.client.AMQConnectionURL;
-import org.apache.qpid.jms.BrokerDetails;
-import org.apache.qpid.jms.ConnectionURL;
-import org.apache.qpid.url.URLSyntaxException;
-
-public class ConnectionURLTest extends TestCase
-{
-
- public void testFailoverURL() throws URLSyntaxException
- {
- String url = "amqp://ritchiem:bob@/test?brokerlist='tcp://localhost:5672;tcp://fancyserver:3000/',failover='roundrobin?cyclecount='100''";
-
- ConnectionURL connectionurl = new AMQConnectionURL(url);
-
- assertTrue(connectionurl.getFailoverMethod().equals("roundrobin"));
- assertEquals("100", connectionurl.getFailoverOption(ConnectionURL.OPTIONS_FAILOVER_CYCLE));
- assertTrue(connectionurl.getUsername().equals("ritchiem"));
- assertTrue(connectionurl.getPassword().equals("bob"));
- assertTrue(connectionurl.getVirtualHost().equals("/test"));
-
- assertTrue(connectionurl.getBrokerCount() == 2);
-
- BrokerDetails service = connectionurl.getBrokerDetails(0);
-
- assertTrue(service.getTransport().equals("tcp"));
- assertTrue(service.getHost().equals("localhost"));
- assertTrue(service.getPort() == 5672);
-
- service = connectionurl.getBrokerDetails(1);
-
- assertTrue(service.getTransport().equals("tcp"));
- assertTrue(service.getHost().equals("fancyserver"));
- assertTrue(service.getPort() == 3000);
-
- }
-
- public void testSingleTransportUsernamePasswordURL() throws URLSyntaxException
- {
- String url = "amqp://ritchiem:bob@/test?brokerlist='tcp://localhost:5672'";
-
- ConnectionURL connectionurl = new AMQConnectionURL(url);
-
- assertTrue(connectionurl.getFailoverMethod() == null);
- assertTrue(connectionurl.getUsername().equals("ritchiem"));
- assertTrue(connectionurl.getPassword().equals("bob"));
- assertTrue(connectionurl.getVirtualHost().equals("/test"));
-
- assertTrue(connectionurl.getBrokerCount() == 1);
-
- BrokerDetails service = connectionurl.getBrokerDetails(0);
-
- assertTrue(service.getTransport().equals("tcp"));
- assertTrue(service.getHost().equals("localhost"));
- assertTrue(service.getPort() == 5672);
- }
-
- public void testSingleTransportUsernameBlankPasswordURL() throws URLSyntaxException
- {
- String url = "amqp://ritchiem:@/test?brokerlist='tcp://localhost:5672'";
-
- ConnectionURL connectionurl = new AMQConnectionURL(url);
-
- assertTrue(connectionurl.getFailoverMethod() == null);
- assertTrue(connectionurl.getUsername().equals("ritchiem"));
- assertTrue(connectionurl.getPassword().equals(""));
- assertTrue(connectionurl.getVirtualHost().equals("/test"));
-
- assertTrue(connectionurl.getBrokerCount() == 1);
-
- BrokerDetails service = connectionurl.getBrokerDetails(0);
-
- assertTrue(service.getTransport().equals("tcp"));
- assertTrue(service.getHost().equals("localhost"));
- assertTrue(service.getPort() == 5672);
- }
-
- public void testFailedURLNullPassword()
- {
- String url = "amqp://ritchiem@/test?brokerlist='tcp://localhost:5672'";
-
- try
- {
- new AMQConnectionURL(url);
- fail("URL has null password");
- }
- catch (URLSyntaxException e)
- {
- assertTrue(e.getReason().equals("Null password in user information not allowed."));
- assertTrue(e.getIndex() == 7);
- }
- }
-
-
- public void testSingleTransportURL() throws URLSyntaxException
- {
- String url = "amqp://guest:guest@/test?brokerlist='tcp://localhost:5672'";
-
- ConnectionURL connectionurl = new AMQConnectionURL(url);
-
-
- assertTrue(connectionurl.getFailoverMethod() == null);
- assertTrue(connectionurl.getUsername().equals("guest"));
- assertTrue(connectionurl.getPassword().equals("guest"));
- assertTrue(connectionurl.getVirtualHost().equals("/test"));
-
-
- assertTrue(connectionurl.getBrokerCount() == 1);
-
-
- BrokerDetails service = connectionurl.getBrokerDetails(0);
-
- assertTrue(service.getTransport().equals("tcp"));
- assertTrue(service.getHost().equals("localhost"));
- assertTrue(service.getPort() == 5672);
- }
-
- public void testSingleTransportWithClientURLURL() throws URLSyntaxException
- {
- String url = "amqp://guest:guest@clientname/test?brokerlist='tcp://localhost:5672'";
-
- ConnectionURL connectionurl = new AMQConnectionURL(url);
-
-
- assertTrue(connectionurl.getFailoverMethod() == null);
- assertTrue(connectionurl.getUsername().equals("guest"));
- assertTrue(connectionurl.getPassword().equals("guest"));
- assertTrue(connectionurl.getVirtualHost().equals("/test"));
- assertTrue(connectionurl.getClientName().equals("clientname"));
-
-
- assertTrue(connectionurl.getBrokerCount() == 1);
-
-
- BrokerDetails service = connectionurl.getBrokerDetails(0);
-
- assertTrue(service.getTransport().equals("tcp"));
- assertTrue(service.getHost().equals("localhost"));
- assertTrue(service.getPort() == 5672);
- }
-
- public void testSingleTransport1OptionURL() throws URLSyntaxException
- {
- String url = "amqp://guest:guest@/test?brokerlist='tcp://localhost:5672',routingkey='jim'";
-
- ConnectionURL connectionurl = new AMQConnectionURL(url);
-
- assertTrue(connectionurl.getFailoverMethod() == null);
- assertTrue(connectionurl.getUsername().equals("guest"));
- assertTrue(connectionurl.getPassword().equals("guest"));
- assertTrue(connectionurl.getVirtualHost().equals("/test"));
-
-
- assertTrue(connectionurl.getBrokerCount() == 1);
-
- BrokerDetails service = connectionurl.getBrokerDetails(0);
-
- assertTrue(service.getTransport().equals("tcp"));
-
- assertTrue(service.getHost().equals("localhost"));
- assertTrue(service.getPort() == 5672);
- assertTrue(connectionurl.getOption("routingkey").equals("jim"));
- }
-
- public void testSingleTransportDefaultedBroker() throws URLSyntaxException
- {
- String url = "amqp://guest:guest@/test?brokerlist='localhost'";
-
- ConnectionURL connectionurl = new AMQConnectionURL(url);
-
- assertTrue(connectionurl.getFailoverMethod() == null);
- assertTrue(connectionurl.getUsername().equals("guest"));
- assertTrue(connectionurl.getPassword().equals("guest"));
- assertTrue(connectionurl.getVirtualHost().equals("/test"));
-
-
- assertTrue(connectionurl.getBrokerCount() == 1);
-
- BrokerDetails service = connectionurl.getBrokerDetails(0);
-
- assertTrue(service.getTransport().equals("tcp"));
-
- assertTrue(service.getHost().equals("localhost"));
- assertTrue(service.getPort() == 5672);
- }
-
- public void testSingleTransportDefaultedBrokerWithPort() throws URLSyntaxException
- {
- String url = "amqp://guest:guest@/test?brokerlist='localhost:1234'";
-
- ConnectionURL connectionurl = new AMQConnectionURL(url);
-
- assertTrue(connectionurl.getFailoverMethod() == null);
- assertTrue(connectionurl.getUsername().equals("guest"));
- assertTrue(connectionurl.getPassword().equals("guest"));
- assertTrue(connectionurl.getVirtualHost().equals("/test"));
-
-
- assertTrue(connectionurl.getBrokerCount() == 1);
-
- BrokerDetails service = connectionurl.getBrokerDetails(0);
-
- assertTrue(service.getTransport().equals("tcp"));
-
- assertTrue(service.getHost().equals("localhost"));
- assertTrue(service.getPort() == 1234);
- }
-
- public void testSingleTransportDefaultedBrokerWithIP() throws URLSyntaxException
- {
- String url = "amqp://guest:guest@/test?brokerlist='127.0.0.1'";
-
- ConnectionURL connectionurl = new AMQConnectionURL(url);
-
- assertTrue(connectionurl.getFailoverMethod() == null);
- assertTrue(connectionurl.getUsername().equals("guest"));
- assertTrue(connectionurl.getPassword().equals("guest"));
- assertTrue(connectionurl.getVirtualHost().equals("/test"));
-
-
- assertTrue(connectionurl.getBrokerCount() == 1);
-
- BrokerDetails service = connectionurl.getBrokerDetails(0);
-
- assertTrue(service.getTransport().equals("tcp"));
-
- assertTrue(service.getHost().equals("127.0.0.1"));
- assertTrue(service.getPort() == 5672);
- }
-
- public void testSingleTransportDefaultedBrokerWithIPandPort() throws URLSyntaxException
- {
- String url = "amqp://guest:guest@/test?brokerlist='127.0.0.1:1234'";
-
-// ConnectionURL connectionurl = new AMQConnectionURL(url);
-//
-// assertTrue(connectionurl.getFailoverMethod() == null);
-// assertTrue(connectionurl.getUsername().equals("guest"));
-// assertTrue(connectionurl.getPassword().equals("guest"));
-// assertTrue(connectionurl.getVirtualHost().equals("/temp"));
-//
-//
-// assertTrue(connectionurl.getBrokerCount() == 1);
-//
-// BrokerDetails service = connectionurl.getBrokerDetails(0);
-//
-// assertTrue(service.getTransport().equals("tcp"));
-//
-// assertTrue(service.getHost().equals("127.0.0.1"));
-// assertTrue(service.getPort() == 1234);
- }
-
-
- public void testSingleTransportMultiOptionURL() throws URLSyntaxException
- {
- String url = "amqp://guest:guest@/test?brokerlist='tcp://localhost:5672?foo='jim'&bar='bob'&fred='jimmy'',routingkey='jim',timeout='200',immediatedelivery='true'";
-
- ConnectionURL connectionurl = new AMQConnectionURL(url);
-
- assertTrue(connectionurl.getFailoverMethod() == null);
- assertTrue(connectionurl.getUsername().equals("guest"));
- assertTrue(connectionurl.getPassword().equals("guest"));
- assertTrue(connectionurl.getVirtualHost().equals("/test"));
-
- assertTrue(connectionurl.getBrokerCount() == 1);
-
- BrokerDetails service = connectionurl.getBrokerDetails(0);
-
- assertTrue(service.getTransport().equals("tcp"));
-
- assertTrue(service.getHost().equals("localhost"));
- assertTrue(service.getPort() == 5672);
-
- assertTrue(connectionurl.getOption("routingkey").equals("jim"));
- assertTrue(connectionurl.getOption("timeout").equals("200"));
- assertTrue(connectionurl.getOption("immediatedelivery").equals("true"));
- }
-
- public void testSinglevmURL() throws URLSyntaxException
- {
- String url = "amqp://guest:guest@/test?brokerlist='vm://:2'";
-
- ConnectionURL connectionurl = new AMQConnectionURL(url);
-
- assertTrue(connectionurl.getFailoverMethod() == null);
- assertTrue(connectionurl.getUsername().equals("guest"));
- assertTrue(connectionurl.getPassword().equals("guest"));
- assertTrue(connectionurl.getVirtualHost().equals("/test"));
-
- assertTrue(connectionurl.getBrokerCount() == 1);
-
- BrokerDetails service = connectionurl.getBrokerDetails(0);
-
- assertTrue(service.getTransport().equals("vm"));
- assertTrue(service.getHost().equals(""));
- assertTrue(service.getPort() == 2);
-
- }
-
- public void testFailoverVMURL() throws URLSyntaxException
- {
- String url = "amqp://ritchiem:bob@/test?brokerlist='vm://:2;vm://:3',failover='roundrobin'";
-
- ConnectionURL connectionurl = new AMQConnectionURL(url);
-
- assertTrue(connectionurl.getFailoverMethod().equals("roundrobin"));
- assertTrue(connectionurl.getUsername().equals("ritchiem"));
- assertTrue(connectionurl.getPassword().equals("bob"));
- assertTrue(connectionurl.getVirtualHost().equals("/test"));
-
- assertTrue(connectionurl.getBrokerCount() == 2);
-
- BrokerDetails service = connectionurl.getBrokerDetails(0);
-
- assertTrue(service.getTransport().equals("vm"));
- assertTrue(service.getHost().equals(""));
- assertTrue(service.getPort() == 2);
-
- service = connectionurl.getBrokerDetails(1);
- assertTrue(service.getTransport().equals("vm"));
- assertTrue(service.getHost().equals(""));
- assertTrue(service.getPort() == 3);
- }
-
-
- public void testNoVirtualHostURL()
- {
- String url = "amqp://user@?brokerlist='tcp://localhost:5672'";
-
- try
- {
- new AMQConnectionURL(url);
- fail("URL has no virtual host should not parse");
- }
- catch (URLSyntaxException e)
- {
- // This should occur.
- }
- }
-
- public void testNoClientID() throws URLSyntaxException
- {
- String url = "amqp://user:@/test?brokerlist='tcp://localhost:5672'";
-
- ConnectionURL connectionurl = new AMQConnectionURL(url);
-
- assertTrue(connectionurl.getUsername().equals("user"));
- assertTrue(connectionurl.getPassword().equals(""));
- assertTrue(connectionurl.getVirtualHost().equals("/test"));
-
- assertTrue(connectionurl.getBrokerCount() == 1);
- }
-
- public void testClientIDWithUnderscore() throws URLSyntaxException
- {
- String url = "amqp://user:pass@client_id/test?brokerlist='tcp://localhost:5672'";
-
- ConnectionURL connectionurl = new AMQConnectionURL(url);
-
- assertTrue(connectionurl.getUsername().equals("user"));
- assertTrue(connectionurl.getPassword().equals("pass"));
- assertTrue(connectionurl.getVirtualHost().equals("/test"));
- assertTrue(connectionurl.getClientName().equals("client_id"));
-
- assertTrue(connectionurl.getBrokerCount() == 1);
- }
-
- public void testWrongOptionSeparatorInOptions()
- {
- String url = "amqp://guest:guest@/test?brokerlist='tcp://localhost:5672;tcp://localhost:5673'+failover='roundrobin'";
- try
- {
- new AMQConnectionURL(url);
- fail("URL Should not parse");
- }
- catch (URLSyntaxException urise)
- {
- assertTrue(urise.getReason().equals("Unterminated option. Possible illegal option separator:'+'"));
- }
-
- }
-
-
- public void testNoUserDetailsProvidedWithClientID()
-
- {
- String url = "amqp://clientID/test?brokerlist='tcp://localhost:5672;tcp://localhost:5673'";
- try
- {
- new AMQConnectionURL(url);
- fail("URL Should not parse");
- }
- catch (URLSyntaxException urise)
- {
- assertTrue(urise.getMessage().startsWith("User information not found on url"));
- }
-
- }
-
- public void testNoUserDetailsProvidedNOClientID()
-
- {
- String url = "amqp:///test?brokerlist='tcp://localhost:5672;tcp://localhost:5673'";
- try
- {
- new AMQConnectionURL(url);
- fail("URL Should not parse");
- }
- catch (URLSyntaxException urise)
- {
- assertTrue(urise.getMessage().startsWith("User information not found on url"));
- }
-
- }
-
- public void testCheckVirtualhostFormat() throws URLSyntaxException
- {
- String url = "amqp://guest:guest@/t.-_+!=:?brokerlist='tcp://localhost:5672'";
-
- AMQConnectionURL connection = new AMQConnectionURL(url);
- assertTrue(connection.getVirtualHost().equals("/t.-_+!=:"));
- }
-
- public void testCheckDefaultPort() throws URLSyntaxException
- {
- String url = "amqp://guest:guest@/test=:?brokerlist='tcp://localhost'";
-
- AMQConnectionURL connection = new AMQConnectionURL(url);
-
- BrokerDetails broker = connection.getBrokerDetails(0);
- assertTrue(broker.getPort() == AMQBrokerDetails.DEFAULT_PORT);
-
- }
-
- public void testCheckMissingFinalQuote() throws URLSyntaxException
- {
- String url = "amqp://guest:guest@id/test" + "?brokerlist='tcp://localhost:5672";
-
- try
- {
- new AMQConnectionURL(url);
- }
- catch (URLSyntaxException e)
- {
- assertEquals(e.getMessage(), "Unterminated option at index 32: brokerlist='tcp://localhost:5672");
- }
- }
-
-
- public void testDefaultExchanges() throws URLSyntaxException
- {
- String url = "amqp://guest:guest@id/test" + "?defaultQueueExchange='test.direct'&defaultTopicExchange='test.topic'&temporaryQueueExchange='tmp.direct'&temporaryTopicExchange='tmp.topic'";
-
- AMQConnectionURL conn = new AMQConnectionURL(url);
-
- assertEquals(conn.getDefaultQueueExchangeName(),"test.direct");
-
- assertEquals(conn.getDefaultTopicExchangeName(),"test.topic");
-
- assertEquals(conn.getTemporaryQueueExchangeName(),"tmp.direct");
-
- assertEquals(conn.getTemporaryTopicExchangeName(),"tmp.topic");
-
- }
-
- public void testSocketProtocol() throws URLSyntaxException
- {
- String url = "amqp://guest:guest@id/test" + "?brokerlist='socket://VM-Unique-socketID'";
-
- try
- {
- AMQConnectionURL curl = new AMQConnectionURL(url);
- assertNotNull(curl);
- assertEquals(1, curl.getBrokerCount());
- assertNotNull(curl.getBrokerDetails(0));
- assertEquals(BrokerDetails.SOCKET, curl.getBrokerDetails(0).getTransport());
- assertEquals("VM-Unique-socketID", curl.getBrokerDetails(0).getHost());
- assertEquals("URL does not toString as expected",
- url.replace(":guest", ":********"), curl.toString());
- }
- catch (URLSyntaxException e)
- {
- fail(e.getMessage());
- }
- }
-
- public void testSingleTransportMultiOptionOnBrokerURL() throws URLSyntaxException
- {
- String url = "amqp://guest:guest@/test?brokerlist='tcp://localhost:5672?foo='jim'&bar='bob'&fred='jimmy'',routingkey='jim',timeout='200',immediatedelivery='true'";
-
- ConnectionURL connectionurl = new AMQConnectionURL(url);
-
- assertTrue(connectionurl.getFailoverMethod() == null);
- assertTrue(connectionurl.getUsername().equals("guest"));
- assertTrue(connectionurl.getPassword().equals("guest"));
- assertTrue(connectionurl.getVirtualHost().equals("/test"));
-
- assertTrue(connectionurl.getBrokerCount() == 1);
-
- BrokerDetails service = connectionurl.getBrokerDetails(0);
-
- assertTrue(service.getTransport().equals("tcp"));
-
-
- assertTrue(service.getHost().equals("localhost"));
- assertTrue(service.getPort() == 5672);
- assertEquals("jim",service.getProperty("foo"));
- assertEquals("bob",service.getProperty("bar"));
- assertEquals("jimmy",service.getProperty("fred"));
-
- assertTrue(connectionurl.getOption("routingkey").equals("jim"));
- assertTrue(connectionurl.getOption("timeout").equals("200"));
- assertTrue(connectionurl.getOption("immediatedelivery").equals("true"));
- }
-
- /**
- * Test that options other than failover and brokerlist are returned in the string representation.
- * <p>
- * QPID-2697
- */
- public void testOptionToString() throws Exception
- {
- ConnectionURL url = new AMQConnectionURL("amqp://user:pass@temp/test?maxprefetch='12345'&brokerlist='tcp://localhost:5672'");
-
- assertTrue("String representation should contain options and values", url.toString().contains("maxprefetch='12345'"));
- }
-
- public void testHostNamesWithUnderScore() throws URLSyntaxException
- {
- String url = "amqp://guest:guest@clientid/test?brokerlist='tcp://under_score:6672'";
-
- ConnectionURL connectionurl = new AMQConnectionURL(url);
-
- assertTrue(connectionurl.getUsername().equals("guest"));
- assertTrue(connectionurl.getPassword().equals("guest"));
- assertTrue(connectionurl.getVirtualHost().equals("/test"));
-
- assertTrue(connectionurl.getBrokerCount() == 1);
- BrokerDetails service = connectionurl.getBrokerDetails(0);
- assertTrue(service.getTransport().equals("tcp"));
- assertTrue(service.getHost().equals("under_score"));
- assertTrue(service.getPort() == 6672);
-
- url = "amqp://guest:guest@clientid/test?brokerlist='tcp://under_score'";
-
- connectionurl = new AMQConnectionURL(url);
-
- assertTrue(connectionurl.getUsername().equals("guest"));
- assertTrue(connectionurl.getPassword().equals("guest"));
- assertTrue(connectionurl.getVirtualHost().equals("/test"));
-
- assertTrue(connectionurl.getBrokerCount() == 1);
- service = connectionurl.getBrokerDetails(0);
- assertTrue(service.getTransport().equals("tcp"));
- assertTrue(service.getHost().equals("under_score"));
- assertTrue(service.getPort() == 5672);
- }
-
- public static junit.framework.Test suite()
- {
- return new junit.framework.TestSuite(ConnectionURLTest.class);
- }
-}
-
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/client/destinationurl/DestinationURLTest.java b/java/client/src/test/java/org/apache/qpid/test/unit/client/destinationurl/DestinationURLTest.java
deleted file mode 100644
index 7de09cff45..0000000000
--- a/java/client/src/test/java/org/apache/qpid/test/unit/client/destinationurl/DestinationURLTest.java
+++ /dev/null
@@ -1,197 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.client.destinationurl;
-
-import junit.framework.TestCase;
-
-import org.apache.qpid.exchange.ExchangeDefaults;
-import org.apache.qpid.url.AMQBindingURL;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.net.URISyntaxException;
-
-public class DestinationURLTest extends TestCase
-{
- private static final Logger _logger = LoggerFactory.getLogger(DestinationURLTest.class);
-
- public void testFullURL() throws URISyntaxException
- {
-
- String url = "exchange.Class://exchangeName/Destination/Queue";
-
- AMQBindingURL dest = new AMQBindingURL(url);
-
- assertTrue(url.equals(dest.toString()));
-
- assertTrue(dest.getExchangeClass().equals("exchange.Class"));
- assertTrue(dest.getExchangeName().equals("exchangeName"));
- assertTrue(dest.getDestinationName().equals("Destination"));
- assertTrue(dest.getQueueName().equals("Queue"));
- }
-
- public void testQueue() throws URISyntaxException
- {
-
- String url = "exchangeClass://exchangeName//Queue";
-
- AMQBindingURL dest = new AMQBindingURL(url);
-
- assertTrue(url.equals(dest.toString()));
-
- assertTrue(dest.getExchangeClass().equals("exchangeClass"));
- assertTrue(dest.getExchangeName().equals("exchangeName"));
- assertTrue(dest.getDestinationName().equals(""));
- assertTrue(dest.getQueueName().equals("Queue"));
- }
-
- public void testQueueWithOption() throws URISyntaxException
- {
-
- String url = "exchangeClass://exchangeName//Queue?option='value'";
-
- AMQBindingURL dest = new AMQBindingURL(url);
-
- assertTrue(url.equals(dest.toString()));
-
- assertTrue(dest.getExchangeClass().equals("exchangeClass"));
- assertTrue(dest.getExchangeName().equals("exchangeName"));
- assertTrue(dest.getDestinationName().equals(""));
- assertTrue(dest.getQueueName().equals("Queue"));
- assertTrue(dest.getOption("option").equals("value"));
- }
-
-
- public void testDestination() throws URISyntaxException
- {
-
- String url = "exchangeClass://exchangeName/Destination/";
-
- AMQBindingURL dest = new AMQBindingURL(url);
-
- assertTrue(url.equals(dest.toString()));
-
- assertTrue(dest.getExchangeClass().equals("exchangeClass"));
- assertTrue(dest.getExchangeName().equals("exchangeName"));
- assertTrue(dest.getDestinationName().equals("Destination"));
- assertTrue(dest.getQueueName().equals(""));
- }
-
- public void testDestinationWithOption() throws URISyntaxException
- {
-
- String url = "exchangeClass://exchangeName/Destination/?option='value'";
-
- AMQBindingURL dest = new AMQBindingURL(url);
-
- assertTrue(url.equals(dest.toString()));
-
- assertTrue(dest.getExchangeClass().equals("exchangeClass"));
- assertTrue(dest.getExchangeName().equals("exchangeName"));
- assertTrue(dest.getDestinationName().equals("Destination"));
- assertTrue(dest.getQueueName().equals(""));
-
- assertTrue(dest.getOption("option").equals("value"));
- }
-
- public void testDestinationWithMultiOption() throws URISyntaxException
- {
-
- String url = "exchangeClass://exchangeName/Destination/?option='value',option2='value2'";
-
- AMQBindingURL dest = new AMQBindingURL(url);
-
- assertTrue(dest.getExchangeClass().equals("exchangeClass"));
- assertTrue(dest.getExchangeName().equals("exchangeName"));
- assertTrue(dest.getDestinationName().equals("Destination"));
- assertTrue(dest.getQueueName().equals(""));
-
- assertTrue(dest.getOption("option").equals("value"));
- assertTrue(dest.getOption("option2").equals("value2"));
- }
-
- public void testDestinationWithNoExchangeDefaultsToDirect() throws URISyntaxException
- {
-
- String url = "IBMPerfQueue1?durable='true'";
-
- AMQBindingURL dest = new AMQBindingURL(url);
-
- assertTrue(dest.getExchangeClass().equals(ExchangeDefaults.DIRECT_EXCHANGE_CLASS));
- assertTrue(dest.getExchangeName().equals(""));
- assertTrue(dest.getDestinationName().equals(""));
- assertTrue(dest.getQueueName().equals("IBMPerfQueue1"));
-
- assertTrue(dest.getOption("durable").equals("true"));
- }
-
- public void testDestinationWithMultiBindingKeys() throws URISyntaxException
- {
-
- String url = "exchangeClass://exchangeName/Destination/?bindingkey='key1',bindingkey='key2'";
-
- AMQBindingURL dest = new AMQBindingURL(url);
-
- assertTrue(dest.getExchangeClass().equals("exchangeClass"));
- assertTrue(dest.getExchangeName().equals("exchangeName"));
- assertTrue(dest.getDestinationName().equals("Destination"));
- assertTrue(dest.getQueueName().equals(""));
-
- assertTrue(dest.getBindingKeys().length == 2);
- }
-
- // You can only specify only a routing key or binding key, but not both.
- public void testDestinationIfOnlyRoutingKeyOrBindingKeyIsSpecified() throws URISyntaxException
- {
-
- String url = "exchangeClass://exchangeName/Destination/?bindingkey='key1',routingkey='key2'";
- boolean exceptionThrown = false;
- try
- {
-
- new AMQBindingURL(url);
- }
- catch(URISyntaxException e)
- {
- exceptionThrown = true;
- _logger.info("Exception thrown",e);
- }
-
- assertTrue("Failed to throw an URISyntaxException when both the bindingkey and routingkey is specified",exceptionThrown);
- }
-
- public void testDestinationWithDurableTopic() throws URISyntaxException
- {
-
- String url = "topic://amq.topic//testTopicD?durable='true'&autodelete='true'&clientid='test'&subscription='testQueueD'";
-
- AMQBindingURL dest = new AMQBindingURL(url);
-
- assertTrue(dest.getExchangeClass().equals("topic"));
- assertTrue(dest.getExchangeName().equals("amq.topic"));
- assertTrue(dest.getQueueName().equals("test:testQueueD"));
- }
-
- public static junit.framework.Test suite()
- {
- return new junit.framework.TestSuite(DestinationURLTest.class);
- }
-}
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/client/message/BytesMessageTest.java b/java/client/src/test/java/org/apache/qpid/test/unit/client/message/BytesMessageTest.java
deleted file mode 100644
index 65013e7e6d..0000000000
--- a/java/client/src/test/java/org/apache/qpid/test/unit/client/message/BytesMessageTest.java
+++ /dev/null
@@ -1,569 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.client.message;
-
-import java.util.HashMap;
-
-import javax.jms.MessageEOFException;
-import javax.jms.MessageFormatException;
-import javax.jms.MessageNotReadableException;
-import javax.jms.MessageNotWriteableException;
-
-import junit.framework.TestCase;
-
-import org.apache.qpid.client.message.JMSBytesMessage;
-import org.apache.qpid.client.message.TestMessageHelper;
-
-public class BytesMessageTest extends TestCase
-{
- /**
- * Tests that on creation a call to getBodyLength() throws an exception
- * if null was passed in during creation
- */
- public void testNotReadableOnCreationWithNull() throws Exception
- {
- try
- {
- JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage();
- bm.getBodyLength();
- fail("expected exception did not occur");
- }
- catch (MessageNotReadableException m)
- {
- // ok
- }
- catch (Exception e)
- {
- fail("expected MessageNotReadableException, got " + e);
- }
- }
-
- public void testResetMakesReadble() throws Exception
- {
- try
- {
- JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage();
- bm.writeInt(10);
- bm.reset();
- bm.writeInt(12);
- fail("expected exception did not occur");
- }
- catch (MessageNotWriteableException m)
- {
- // ok
- }
- catch (Exception e)
- {
- fail("expected MessageNotWriteableException, got " + e);
- }
- }
-
- public void testClearBodyMakesWritable() throws Exception
- {
- JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage();
- bm.writeInt(10);
- bm.reset();
- bm.clearBody();
- bm.writeInt(10);
- }
-
- public void testWriteBoolean() throws Exception
- {
- JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage();
- bm.writeBoolean(true);
- bm.writeBoolean(false);
- bm.reset();
- boolean val = bm.readBoolean();
- assertEquals(true, val);
- val = bm.readBoolean();
- assertEquals(false, val);
- }
-
- public void testWriteInt() throws Exception
- {
- JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage();
- bm.writeInt(10);
- bm.reset();
- long len = bm.getBodyLength();
- assertTrue(len == 4);
- int val = bm.readInt();
- assertTrue(val == 10);
- }
-
- public void testWriteString() throws Exception
- {
- JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage();
- bm.writeUTF("Bananas");
- bm.reset();
- String res = bm.readUTF();
- assertEquals("Bananas", res);
- }
-
- public void testWriteBytes() throws Exception
- {
- JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage();
- byte[] bytes = {1,2,3,4};
- bm.writeBytes(bytes, 1, 2);
- bm.reset();
- bytes = new byte[2];
- bm.readBytes(bytes);
- assertEquals(2, bytes[0]);
- assertEquals(3, bytes[1]);
- }
-
- public void testWriteObject() throws Exception
- {
- JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage();
- bm.writeObject(new Boolean(true));
- bm.writeObject(new Boolean(false));
- bm.writeObject(new Byte((byte)2));
- bm.writeObject(new byte[]{1,2,3,4});
- bm.writeObject(new Character('g'));
- bm.writeObject(new Short((short) 29));
- bm.writeObject(new Integer(101));
- bm.writeObject(new Long(50003222L));
- bm.writeObject("Foobar");
- bm.writeObject(new Float(1.7f));
- bm.writeObject(new Double(8.7d));
- bm.reset();
- assertTrue(bm.readBoolean());
- assertTrue(!bm.readBoolean());
- assertEquals((byte)2, bm.readByte());
- byte[] bytes = new byte[4];
- bm.readBytes(bytes);
- assertEquals('g', bm.readChar());
- assertEquals((short) 29, bm.readShort());
- assertEquals(101, bm.readInt());
- assertEquals(50003222L, bm.readLong());
- assertEquals("Foobar", bm.readUTF());
- assertEquals(1.7f, bm.readFloat());
- assertEquals(8.7d, bm.readDouble());
- }
-
- public void testWriteObjectRejectsNonPrimitives() throws Exception
- {
- try
- {
- JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage();
- bm.writeObject(new HashMap());
- fail("expected MessageFormatException was not thrown");
- }
- catch (MessageFormatException e)
- {
- // pass
- }
- }
-
- public void testWriteObjectThrowsNPE() throws Exception
- {
- try
- {
- JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage();
- bm.writeObject(null);
- fail("expected exception did not occur");
- }
- catch (NullPointerException n)
- {
- // ok
- }
- catch (Exception e)
- {
- fail("expected NullPointerException, got " + e);
- }
- }
-
- public void testReadBoolean() throws Exception
- {
- JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage();
- bm.writeBoolean(true);
- bm.reset();
- boolean result = bm.readBoolean();
- assertTrue(result);
- }
-
- public void testReadUnsignedByte() throws Exception
- {
- JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage();
- bm.writeByte((byte) 9);
- bm.reset();
- int result = bm.readUnsignedByte();
- assertEquals(9, result);
- }
-
- public void testReadUnsignedShort() throws Exception
- {
- JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage();
- bm.writeShort((byte) 9);
- bm.reset();
- int result = bm.readUnsignedShort();
- assertEquals(9, result);
- }
-
- public void testReadBytesChecksNull() throws Exception
- {
- try
- {
- JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage();
- bm.readBytes(null);
- }
- catch (IllegalArgumentException e)
- {
- // pass
- }
-
- try
- {
- JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage();
- bm.readBytes(null, 1);
- }
- catch (IllegalArgumentException e)
- {
- // pass
- }
- }
-
- public void testReadBytesChecksMaxSize() throws Exception
- {
- try
- {
- JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage();
- byte[] bytes = new byte[100];
- bm.readBytes(bytes, 120);
- }
- catch (IllegalArgumentException e)
- {
- // pass
- }
- }
-
- public void testReadBytesReturnsCorrectLengths() throws Exception
- {
- JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage();
- byte[] bytes = {2, 3};
- bm.writeBytes(bytes);
- bm.reset();
- int len = bm.readBytes(bytes);
- assertEquals(2, len);
- len = bm.readBytes(bytes);
- assertEquals(-1, len);
- len = bm.readBytes(bytes, 2);
- assertEquals(-1, len);
- bm.reset();
- len = bm.readBytes(bytes, 2);
- assertEquals(2, len);
- bm.reset();
- len = bm.readBytes(bytes, 1);
- assertEquals(1, len);
-
- }
-
- public void testEOFByte() throws Exception
- {
- try
- {
- JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage();
- bm.writeByte((byte)1);
- bm.reset();
- bm.readByte();
- // should throw
- bm.readByte();
- fail("expected exception did not occur");
- }
- catch (MessageEOFException m)
- {
- // ok
- }
- catch (Exception e)
- {
- fail("expected MessageEOFException, got " + e);
- }
- }
-
- public void testEOFUnsignedByte() throws Exception
- {
- try
- {
- JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage();
- bm.writeByte((byte)1);
- bm.reset();
- bm.readByte();
- // should throw
- bm.readUnsignedByte();
- fail("expected exception did not occur");
- }
- catch (MessageEOFException m)
- {
- // ok
- }
- catch (Exception e)
- {
- fail("expected MessageEOFException, got " + e);
- }
- }
-
- public void testEOFBoolean() throws Exception
- {
- try
- {
- JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage();
- bm.writeBoolean(true);
- bm.reset();
- bm.readBoolean();
- // should throw
- bm.readBoolean();
- fail("expected exception did not occur");
- }
- catch (MessageEOFException m)
- {
- // ok
- }
- catch (Exception e)
- {
- fail("expected MessageEOFException, got " + e);
- }
- }
-
- public void testEOFChar() throws Exception
- {
- try
- {
- JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage();
- bm.writeChar('A');
- bm.reset();
- bm.readChar();
- // should throw
- bm.readChar();
- fail("expected exception did not occur");
- }
- catch (MessageEOFException m)
- {
- // ok
- }
- catch (Exception e)
- {
- fail("expected MessageEOFException, got " + e);
- }
- }
-
- public void testEOFDouble() throws Exception
- {
- try
- {
- JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage();
- bm.writeDouble(1.3d);
- bm.reset();
- bm.readDouble();
- // should throw
- bm.readDouble();
- fail("expected exception did not occur");
- }
- catch (MessageEOFException m)
- {
- // ok
- }
- catch (Exception e)
- {
- fail("expected MessageEOFException, got " + e);
- }
- }
-
- public void testEOFFloat() throws Exception
- {
- try
- {
- JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage();
- bm.writeFloat(1.3f);
- bm.reset();
- bm.readFloat();
- // should throw
- bm.readFloat();
- fail("expected exception did not occur");
- }
- catch (MessageEOFException m)
- {
- // ok
- }
- catch (Exception e)
- {
- fail("expected MessageEOFException, got " + e);
- }
- }
-
- public void testEOFInt() throws Exception
- {
- try
- {
- JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage();
- bm.writeInt(99);
- bm.reset();
- bm.readInt();
- // should throw
- bm.readInt();
- fail("expected exception did not occur");
- }
- catch (MessageEOFException m)
- {
- // ok
- }
- catch (Exception e)
- {
- fail("expected MessageEOFException, got " + e);
- }
- }
-
- public void testEOFLong() throws Exception
- {
- try
- {
- JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage();
- bm.writeLong(4L);
- bm.reset();
- bm.readLong();
- // should throw
- bm.readLong();
- fail("expected exception did not occur");
- }
- catch (MessageEOFException m)
- {
- // ok
- }
- catch (Exception e)
- {
- fail("expected MessageEOFException, got " + e);
- }
- }
-
- public void testEOFShort() throws Exception
- {
- try
- {
- JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage();
- bm.writeShort((short)4);
- bm.reset();
- bm.readShort();
- // should throw
- bm.readShort();
- fail("expected exception did not occur");
- }
- catch (MessageEOFException m)
- {
- // ok
- }
- catch (Exception e)
- {
- fail("expected MessageEOFException, got " + e);
- }
- }
-
- public void testEOFUnsignedShort() throws Exception
- {
- try
- {
- JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage();
- bm.writeShort((short)4);
- bm.reset();
- bm.readUnsignedShort();
- // should throw
- bm.readUnsignedShort();
- fail("expected exception did not occur");
- }
- catch (MessageEOFException m)
- {
- // ok
- }
- catch (Exception e)
- {
- fail("expected MessageEOFException, got " + e);
- }
- }
-
- /**
- * Tests that the readBytes() method populates the passed in array
- * correctly
- * @throws Exception
- */
- public void testReadBytes() throws Exception
- {
- JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage();
- bm.writeByte((byte)3);
- bm.writeByte((byte)4);
- bm.reset();
- byte[] result = new byte[2];
- int count = bm.readBytes(result);
- assertEquals((byte)3, result[0]);
- assertEquals((byte)4, result[1]);
- assertEquals(2, count);
- }
-
- public void testReadBytesEOF() throws Exception
- {
- JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage();
- bm.writeByte((byte)3);
- bm.writeByte((byte)4);
- bm.reset();
- byte[] result = new byte[2];
- bm.readBytes(result);
- int count = bm.readBytes(result);
- assertEquals(-1, count);
- }
-
- public void testReadBytesWithLargerArray() throws Exception
- {
- JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage();
- bm.writeByte((byte)3);
- bm.writeByte((byte)4);
- bm.reset();
- byte[] result = new byte[3];
- int count = bm.readBytes(result);
- assertEquals(2, count);
- assertEquals((byte)3, result[0]);
- assertEquals((byte)4, result[1]);
- assertEquals((byte)0, result[2]);
- }
-
- public void testReadBytesWithCount() throws Exception
- {
- JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage();
- bm.writeByte((byte)3);
- bm.writeByte((byte)4);
- bm.writeByte((byte)5);
- bm.reset();
- byte[] result = new byte[3];
- int count = bm.readBytes(result, 2);
- assertEquals(2, count);
- assertEquals((byte)3, result[0]);
- assertEquals((byte)4, result[1]);
- assertEquals((byte)0, result[2]);
- }
-
- public void testToBodyStringWithNull() throws Exception
- {
- JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage();
- bm.reset();
- String result = bm.toBodyString();
- assertEquals("\"\"", result);
- }
-
- public static junit.framework.Test suite()
- {
- return new junit.framework.TestSuite(BytesMessageTest.class);
- }
-}
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/client/message/MapMessageTest.java b/java/client/src/test/java/org/apache/qpid/test/unit/client/message/MapMessageTest.java
deleted file mode 100644
index 3e04c36b38..0000000000
--- a/java/client/src/test/java/org/apache/qpid/test/unit/client/message/MapMessageTest.java
+++ /dev/null
@@ -1,383 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- *
- */
-package org.apache.qpid.test.unit.client.message;
-
-import javax.jms.JMSException;
-import javax.jms.MessageFormatException;
-
-import junit.framework.Assert;
-import junit.framework.TestCase;
-
-import org.apache.qpid.client.message.JMSMapMessage;
-import org.apache.qpid.client.message.TestMessageHelper;
-
-
-public class MapMessageTest extends TestCase
-{
-
- //Test Lookups
-
- public void testBooleanLookup()
- {
- try
- {
- JMSMapMessage mm = TestMessageHelper.newJMSMapMessage();
-
- mm.setBoolean("value", true);
- Assert.assertEquals(true, mm.getBoolean("value"));
- Assert.assertEquals("true", mm.getString("value"));
- }
- catch (JMSException e)
- {
- Assert.fail("JMSException received." + e);
- }
- }
-
- public void testByteLookup()
- {
- try
- {
- JMSMapMessage mm = TestMessageHelper.newJMSMapMessage();
- mm.setByte("value", Byte.MAX_VALUE);
-
- Assert.assertEquals(Byte.MAX_VALUE, mm.getByte("value"));
- Assert.assertEquals((short) Byte.MAX_VALUE, mm.getShort("value"));
- Assert.assertEquals(Byte.MAX_VALUE, mm.getInt("value"));
- Assert.assertEquals((long) Byte.MAX_VALUE, mm.getLong("value"));
- Assert.assertEquals("" + Byte.MAX_VALUE, mm.getString("value"));
-
- }
- catch (JMSException e)
- {
- Assert.fail("JMSException received." + e);
- }
- }
-
- public void testShortLookup()
- {
- try
- {
- JMSMapMessage mm = TestMessageHelper.newJMSMapMessage();
- mm.setShort("value", Short.MAX_VALUE);
- Assert.assertEquals(Short.MAX_VALUE, mm.getShort("value"));
- Assert.assertEquals((int) Short.MAX_VALUE, mm.getInt("value"));
- Assert.assertEquals((long) Short.MAX_VALUE, mm.getLong("value"));
- Assert.assertEquals("" + Short.MAX_VALUE, mm.getString("value"));
- }
- catch (JMSException e)
- {
- Assert.fail("JMSException received." + e);
- }
- }
-
-
- public void testCharLookup()
- {
- try
- {
- JMSMapMessage mm = TestMessageHelper.newJMSMapMessage();
-
- mm.setChar("value", 'c');
- Assert.assertEquals('c', mm.getChar("value"));
- Assert.assertEquals("c", mm.getString("value"));
- }
- catch (JMSException e)
- {
- Assert.fail("JMSException received." + e);
- }
-
- try
- {
- JMSMapMessage mm = TestMessageHelper.newJMSMapMessage();
-
- mm.setString("value", null);
- mm.getChar("value");
- fail("Expected NullPointerException");
-
- }
- catch (NullPointerException e)
- {
- ; // pass
- }
- catch (JMSException e)
- {
- Assert.fail("JMSException received." + e);
- }
-
-
-
- }
-
- public void testDoubleLookup()
- {
- try
- {
- JMSMapMessage mm = TestMessageHelper.newJMSMapMessage();
- mm.setDouble("value", Double.MAX_VALUE);
- Assert.assertEquals(Double.MAX_VALUE, mm.getDouble("value"));
- Assert.assertEquals("" + Double.MAX_VALUE, mm.getString("value"));
- }
- catch (JMSException e)
- {
- Assert.fail("JMSException received." + e);
- }
- }
-
- public void testFloatLookup()
- {
- try
- {
- JMSMapMessage mm = TestMessageHelper.newJMSMapMessage();
- mm.setFloat("value", Float.MAX_VALUE);
- Assert.assertEquals(Float.MAX_VALUE, mm.getFloat("value"));
- Assert.assertEquals((double) Float.MAX_VALUE, mm.getDouble("value"));
- Assert.assertEquals("" + Float.MAX_VALUE, mm.getString("value"));
- }
- catch (JMSException e)
- {
- Assert.fail("JMSException received." + e);
- }
- }
-
- public void testIntLookup()
- {
- try
- {
- JMSMapMessage mm = TestMessageHelper.newJMSMapMessage();
- mm.setInt("value", Integer.MAX_VALUE);
- Assert.assertEquals(Integer.MAX_VALUE, mm.getInt("value"));
- Assert.assertEquals((long) Integer.MAX_VALUE, mm.getLong("value"));
- Assert.assertEquals("" + Integer.MAX_VALUE, mm.getString("value"));
- }
- catch (JMSException e)
- {
- Assert.fail("JMSException received." + e);
- }
- }
-
- public void testLongLookup()
- {
- try
- {
- JMSMapMessage mm = TestMessageHelper.newJMSMapMessage();
- mm.setLong("value", Long.MAX_VALUE);
- Assert.assertEquals(Long.MAX_VALUE, mm.getLong("value"));
- Assert.assertEquals("" + Long.MAX_VALUE, mm.getString("value"));
- }
- catch (JMSException e)
- {
- Assert.fail("JMSException received." + e);
- }
- }
-
- public void testBytesLookup()
- {
- try
- {
- JMSMapMessage mm = TestMessageHelper.newJMSMapMessage();
- byte[] bytes = {99, 98, 97, 96, 95};
- mm.setBytes("bytes", bytes);
- assertBytesEqual(bytes, mm.getBytes("bytes"));
- }
- catch (JMSException e)
- {
- Assert.fail("JMSException received." + e);
- }
- }
-
- // Failed Lookups
-
- public void testFailedBooleanLookup()
- {
- try
- {
- JMSMapMessage mm = TestMessageHelper.newJMSMapMessage();
- Assert.assertEquals(false, mm.getBoolean("int"));
- }
- catch (JMSException e)
- {
- Assert.fail("JMSException received." + e);
- }
- }
-
- public void testFailedByteLookup()
- {
- try
- {
- JMSMapMessage mm = TestMessageHelper.newJMSMapMessage();
- mm.getByte("random");
- Assert.fail("NumberFormatException expected");
- }
- catch (NumberFormatException e)
- {
- //normal execution
- }
- catch (JMSException e)
- {
- Assert.fail("JMSException received:" + e);
- }
-
- }
-
- public void testFailedBytesLookup()
- {
- try
- {
- JMSMapMessage mm = TestMessageHelper.newJMSMapMessage();
- mm.getBytes("random");
- Assert.fail("MessageFormatException expected");
- }
- catch (MessageFormatException mfe)
- {
- //normal path
- }
- catch (JMSException e)
- {
- Assert.fail("JMSException received:" + e);
- }
- }
-
- public void testFailedCharLookup()
- {
- try
- {
- JMSMapMessage mm = TestMessageHelper.newJMSMapMessage();
- mm.getChar("random");
- Assert.fail("MessageFormatException expected");
- }
- catch (MessageFormatException e)
- {
- //normal execution
- }
- catch (JMSException e)
- {
- Assert.fail("JMSException received:" + e);
- }
- }
-
- public void testFailedDoubleLookup()
- {
- try
- {
- JMSMapMessage mm = TestMessageHelper.newJMSMapMessage();
- mm.getDouble("random");
- Assert.fail("NullPointerException should be received.");
- }
- catch (NullPointerException e)
- {
- //normal execution
- }
- catch (JMSException e)
- {
- Assert.fail("JMSException received:" + e);
- }
- }
-
- public void testFailedFloatLookup()
- {
- try
- {
- JMSMapMessage mm = TestMessageHelper.newJMSMapMessage();
- mm.getFloat("random");
- Assert.fail("NullPointerException should be received.");
- }
- catch (NullPointerException e)
- {
- //normal execution
- }
- catch (JMSException e)
- {
- Assert.fail("JMSException received:" + e);
- }
- }
-
- public void testFailedIntLookup()
- {
- try
- {
- JMSMapMessage mm = TestMessageHelper.newJMSMapMessage();
- mm.getInt("random");
- Assert.fail("NumberFormatException should be received.");
- }
- catch (NumberFormatException e)
- {
- //normal execution
- }
- catch (JMSException e)
- {
- Assert.fail("JMSException received:" + e);
- }
- }
-
- public void testFailedLongLookup()
- {
- try
- {
- JMSMapMessage mm = TestMessageHelper.newJMSMapMessage();
- mm.getLong("random");
- Assert.fail("NumberFormatException should be received.");
- }
- catch (NumberFormatException e)
- {
- //normal execution
- }
- catch (JMSException e)
- {
- Assert.fail("JMSException received:" + e);
- }
- }
-
- public void testFailedShortLookup()
- {
- try
- {
- JMSMapMessage mm = TestMessageHelper.newJMSMapMessage();
- mm.getShort("random");
- Assert.fail("NumberFormatException should be received.");
- }
- catch (NumberFormatException e)
- {
- //normal execution
- }
- catch (JMSException e)
- {
- Assert.fail("JMSException received:" + e);
- }
- }
-
-
- private void assertBytesEqual(byte[] expected, byte[] actual)
- {
- Assert.assertEquals(expected.length, actual.length);
-
- for (int index = 0; index < expected.length; index++)
- {
- Assert.assertEquals(expected[index], actual[index]);
- }
- }
-
- public static junit.framework.Test suite()
- {
- return new junit.framework.TestSuite(MapMessageTest.class);
- }
-
-
-}
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/client/message/StreamMessageTest.java b/java/client/src/test/java/org/apache/qpid/test/unit/client/message/StreamMessageTest.java
deleted file mode 100644
index 085dd81079..0000000000
--- a/java/client/src/test/java/org/apache/qpid/test/unit/client/message/StreamMessageTest.java
+++ /dev/null
@@ -1,623 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.client.message;
-
-import java.util.HashMap;
-
-import javax.jms.JMSException;
-import javax.jms.MessageEOFException;
-import javax.jms.MessageFormatException;
-import javax.jms.MessageNotReadableException;
-import javax.jms.MessageNotWriteableException;
-import javax.jms.StreamMessage;
-
-import junit.framework.TestCase;
-
-import org.apache.qpid.client.message.JMSStreamMessage;
-import org.apache.qpid.client.message.TestMessageHelper;
-
-/**
- * @author Apache Software Foundation
- */
-public class StreamMessageTest extends TestCase
-{
- /**
- * Tests that on creation a call to getBodyLength() throws an exception
- * if null was passed in during creation
- */
- public void testNotReadableOnCreationWithNull() throws Exception
- {
- try
- {
- JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage();
- bm.readByte();
- fail("expected exception did not occur");
- }
- catch (MessageNotReadableException m)
- {
- // ok
- }
- catch (Exception e)
- {
- fail("expected MessageNotReadableException, got " + e);
- }
- }
-
- public void testResetMakesReadble() throws Exception
- {
- try
- {
- JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage();
- bm.writeInt(10);
- bm.reset();
- bm.writeInt(12);
- fail("expected exception did not occur");
- }
- catch (MessageNotWriteableException m)
- {
- // ok
- }
- catch (Exception e)
- {
- fail("expected MessageNotWriteableException, got " + e);
- }
- }
-
- public void testClearBodyMakesWritable() throws Exception
- {
- JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage();
- bm.writeInt(10);
- bm.reset();
- bm.clearBody();
- bm.writeInt(10);
- }
-
- public void testWriteBoolean() throws Exception
- {
- JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage();
- bm.writeBoolean(true);
- bm.writeBoolean(false);
- bm.reset();
- boolean val = bm.readBoolean();
- assertEquals(true, val);
- val = bm.readBoolean();
- assertEquals(false, val);
- }
-
- public void testWriteInt() throws Exception
- {
- JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage();
- bm.writeInt(10);
- bm.reset();
- int val = bm.readInt();
- assertTrue(val == 10);
- }
-
- public void testWriteString() throws Exception
- {
- JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage();
- bm.writeString("Bananas");
- bm.reset();
- String res = bm.readString();
- assertEquals("Bananas", res);
- }
-
- public void testWriteBytes() throws Exception
- {
- JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage();
- byte[] bytes = {1,2,3,4};
- bm.writeBytes(bytes, 1, 2);
- bm.reset();
- bytes = new byte[2];
- bm.readBytes(bytes);
- assertEquals(2, bytes[0]);
- assertEquals(3, bytes[1]);
- }
-
- public void testWriteObject() throws Exception
- {
- JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage();
- bm.writeObject(new Boolean(true));
- bm.writeObject(new Boolean(false));
- bm.writeObject(new Byte((byte)2));
- bm.writeObject(new byte[]{1,2,3,4});
- bm.writeObject(new Character('g'));
- bm.writeObject(new Short((short) 29));
- bm.writeObject(new Integer(101));
- bm.writeObject(new Long(50003222L));
- bm.writeObject("Foobar");
- bm.writeObject(new Float(1.7f));
- bm.writeObject(new Double(8.7d));
- bm.reset();
- assertTrue(bm.readBoolean());
- assertTrue(!bm.readBoolean());
- assertEquals((byte)2, bm.readByte());
- byte[] bytes = new byte[4];
- bm.readBytes(bytes);
- assertEquals('g', bm.readChar());
- assertEquals((short) 29, bm.readShort());
- assertEquals(101, bm.readInt());
- assertEquals(50003222L, bm.readLong());
- assertEquals("Foobar", bm.readString());
- assertEquals(1.7f, bm.readFloat());
- assertEquals(8.7d, bm.readDouble());
- }
-
- public void testWriteObjectRejectsNonPrimitives() throws Exception
- {
- try
- {
- JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage();
- bm.writeObject(new HashMap());
- fail("expected MessageFormatException was not thrown");
- }
- catch (MessageFormatException e)
- {
- // pass
- }
- }
-
- public void testReadBoolean() throws Exception
- {
- JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage();
- bm.writeBoolean(true);
- bm.reset();
- boolean result = bm.readBoolean();
- assertTrue(result);
- }
-
- public void testReadBytesChecksNull() throws Exception
- {
- try
- {
- JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage();
- bm.readBytes(null);
- }
- catch (IllegalArgumentException e)
- {
- // pass
- }
- }
-
- public void testReadBytesReturnsCorrectLengths() throws Exception
- {
- JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage();
- byte[] bytes = {2, 3};
- bm.writeBytes(bytes);
- bm.writeBytes(null);
- bm.writeBytes(new byte[]{});
- bm.reset();
- int len = bm.readBytes(bytes);
- assertEquals(2, len);
- len = bm.readBytes(bytes);
- assertEquals(-1, len);
- len = bm.readBytes(bytes);
- assertEquals(-1, len);
- len = bm.readBytes(bytes);
- assertEquals(0, len);
- }
-
- public void testReadBytesFollowedByPrimitive() throws Exception
- {
- JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage();
- bm.writeBytes(new byte[]{2, 3, 4, 5, 6, 7, 8});
- bm.writeBytes(new byte[]{2, 3, 4, 5, 6, 7});
- bm.writeString("Foo");
- bm.reset();
- int len;
- do
- {
- len = bm.readBytes(new byte[2]);
- }
- while (len == 2);
-
- do
- {
- len = bm.readBytes(new byte[2]);
- }
- while (len == 2);
-
- assertEquals("Foo", bm.readString());
- }
-
- public void testReadMultipleByteArrays() throws Exception
- {
- JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage();
- byte[] bytes = {2, 3, 4};
- bm.writeBytes(bytes);
- bm.writeBytes(bytes);
- bm.reset();
- byte[] result = new byte[2];
- int len = bm.readBytes(result);
- assertEquals(2, len);
- len = bm.readBytes(result);
- assertEquals(1, len);
- len = bm.readBytes(result);
- assertEquals(2, len);
- }
-
- public void testEOFByte() throws Exception
- {
- try
- {
- JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage();
- bm.writeByte((byte)1);
- bm.reset();
- bm.readByte();
- // should throw
- bm.readByte();
- fail("expected exception did not occur");
- }
- catch (MessageEOFException m)
- {
- // ok
- }
- catch (Exception e)
- {
- fail("expected MessageEOFException, got " + e);
- }
- }
-
- public void testEOFBoolean() throws Exception
- {
- try
- {
- JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage();
- bm.writeBoolean(true);
- bm.reset();
- bm.readBoolean();
- // should throw
- bm.readBoolean();
- fail("expected exception did not occur");
- }
- catch (MessageEOFException m)
- {
- // ok
- }
- catch (Exception e)
- {
- fail("expected MessageEOFException, got " + e);
- }
- }
-
- public void testEOFChar() throws Exception
- {
- try
- {
- JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage();
- bm.writeChar('A');
- bm.reset();
- bm.readChar();
- // should throw
- bm.readChar();
- fail("expected exception did not occur");
- }
- catch (MessageEOFException m)
- {
- // ok
- }
- catch (Exception e)
- {
- fail("expected MessageEOFException, got " + e);
- }
- }
-
- public void testEOFDouble() throws Exception
- {
- try
- {
- JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage();
- bm.writeDouble(1.3d);
- bm.reset();
- bm.readDouble();
- // should throw
- bm.readDouble();
- fail("expected exception did not occur");
- }
- catch (MessageEOFException m)
- {
- // ok
- }
- catch (Exception e)
- {
- fail("expected MessageEOFException, got " + e);
- }
- }
-
- public void testEOFFloat() throws Exception
- {
- try
- {
- JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage();
- bm.writeFloat(1.3f);
- bm.reset();
- bm.readFloat();
- // should throw
- bm.readFloat();
- fail("expected exception did not occur");
- }
- catch (MessageEOFException m)
- {
- // ok
- }
- catch (Exception e)
- {
- fail("expected MessageEOFException, got " + e);
- }
- }
-
- public void testEOFInt() throws Exception
- {
- try
- {
- JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage();
- bm.writeInt(99);
- bm.reset();
- bm.readInt();
- // should throw
- bm.readInt();
- fail("expected exception did not occur");
- }
- catch (MessageEOFException m)
- {
- // ok
- }
- catch (Exception e)
- {
- fail("expected MessageEOFException, got " + e);
- }
- }
-
- public void testEOFLong() throws Exception
- {
- try
- {
- JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage();
- bm.writeLong(4L);
- bm.reset();
- bm.readLong();
- // should throw
- bm.readLong();
- fail("expected exception did not occur");
- }
- catch (MessageEOFException m)
- {
- // ok
- }
- catch (Exception e)
- {
- fail("expected MessageEOFException, got " + e);
- }
- }
-
- public void testEOFShort() throws Exception
- {
- try
- {
- JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage();
- bm.writeShort((short)4);
- bm.reset();
- bm.readShort();
- // should throw
- bm.readShort();
- fail("expected exception did not occur");
- }
- catch (MessageEOFException m)
- {
- // ok
- }
- catch (Exception e)
- {
- fail("expected MessageEOFException, got " + e);
- }
- }
-
- public void testToBodyStringWithNull() throws Exception
- {
- JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage();
- bm.reset();
- String result = bm.toBodyString();
- assertEquals("\"\"", result);
- }
-
- private void checkConversionsFail(StreamMessage sm, int[] conversions) throws JMSException
- {
- for (int conversion : conversions)
- {
- try
- {
- switch (conversion)
- {
- case 0:
- sm.readBoolean();
- break;
- case 1:
- sm.readByte();
- break;
- case 2:
- sm.readShort();
- break;
- case 3:
- sm.readChar();
- break;
- case 4:
- sm.readInt();
- break;
- case 5:
- sm.readLong();
- break;
- case 6:
- sm.readFloat();
- break;
- case 7:
- sm.readDouble();
- break;
- case 8:
- sm.readString();
- break;
- case 9:
- sm.readBytes(new byte[3]);
- break;
- }
- fail("MessageFormatException was not thrown");
- }
- catch (MessageFormatException e)
- {
- // PASS
- }
- sm.reset();
- }
- }
- public void testBooleanConversions() throws Exception
- {
- JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage();
- bm.writeBoolean(true);
- bm.reset();
- String result = bm.readString();
- assertEquals("true", result);
- bm.reset();
- checkConversionsFail(bm, new int[]{1,2,3,4,5,6,7,9});
- }
-
- public void testByteConversions() throws Exception
- {
- JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage();
- bm.writeByte((byte) 43);
- bm.reset();
- assertEquals(43, bm.readShort());
- bm.reset();
- assertEquals(43, bm.readInt());
- bm.reset();
- assertEquals(43, bm.readLong());
- bm.reset();
- String result = bm.readString();
- assertEquals("43", result);
- bm.reset();
- checkConversionsFail(bm, new int[]{0, 3, 6, 7, 9});
- }
-
- public void testShortConversions() throws Exception
- {
- JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage();
- bm.writeShort((short) 87);
- bm.reset();
- assertEquals(87, bm.readInt());
- bm.reset();
- assertEquals(87, bm.readLong());
- bm.reset();
- assertEquals("87", bm.readString());
- bm.reset();
- checkConversionsFail(bm, new int[]{0, 1, 3, 6, 7, });
- }
-
- public void testCharConversions() throws Exception
- {
- JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage();
- bm.writeChar('d');
- bm.reset();
- assertEquals("d", bm.readString());
- bm.reset();
- checkConversionsFail(bm, new int[]{0, 1, 2, 4, 5, 6, 7, 9});
- }
-
- public void testIntConversions() throws Exception
- {
- JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage();
- bm.writeInt(167);
- bm.reset();
- assertEquals(167, bm.readLong());
- bm.reset();
- assertEquals("167", bm.readString());
- bm.reset();
- checkConversionsFail(bm, new int[]{0, 1, 2, 3, 6, 7, 9});
- }
-
- public void testLongConversions() throws Exception
- {
- JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage();
- bm.writeLong(1678);
- bm.reset();
- assertEquals("1678", bm.readString());
- bm.reset();
- checkConversionsFail(bm, new int[]{0, 1, 2, 3, 4, 6, 7, 9});
- }
-
- public void testFloatConversions() throws Exception
- {
- JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage();
- bm.writeFloat(6.2f);
- bm.reset();
- assertEquals(6.2d, bm.readDouble(), 0.01);
- bm.reset();
- assertEquals("6.2", bm.readString());
- bm.reset();
- checkConversionsFail(bm, new int[]{0, 1, 2, 3, 4, 5, 9});
- }
-
- public void testDoubleConversions() throws Exception
- {
- JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage();
- bm.writeDouble(88.35d);
- bm.reset();
- assertEquals("88.35", bm.readString());
- bm.reset();
- checkConversionsFail(bm, new int[]{0, 1, 2, 3, 4, 5, 6, 9});
- }
-
- public void testStringConversions() throws Exception
- {
- JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage();
- bm.writeString("true");
- bm.reset();
- assertEquals(true, bm.readBoolean());
- bm = TestMessageHelper.newJMSStreamMessage();
- bm.writeString("2");
- bm.reset();
- assertEquals((byte)2, bm.readByte());
- bm.reset();
- assertEquals((short)2, bm.readShort());
- bm.reset();
- assertEquals(2, bm.readInt());
- bm.reset();
- assertEquals((long)2, bm.readLong());
- bm = TestMessageHelper.newJMSStreamMessage();
- bm.writeString("5.7");
- bm.reset();
- assertEquals(5.7f, bm.readFloat());
- bm.reset();
- assertEquals(5.7d, bm.readDouble());
- }
-
- public void testNulls() throws Exception
- {
- JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage();
- bm.writeString(null);
- bm.writeObject(null);
- bm.reset();
- assertNull(bm.readObject());
- assertNull(bm.readObject());
- }
-
- public static junit.framework.Test suite()
- {
- return new junit.framework.TestSuite(StreamMessageTest.class);
- }
-}
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/client/message/TextMessageTest.java b/java/client/src/test/java/org/apache/qpid/test/unit/client/message/TextMessageTest.java
deleted file mode 100644
index 30f3b0b4eb..0000000000
--- a/java/client/src/test/java/org/apache/qpid/test/unit/client/message/TextMessageTest.java
+++ /dev/null
@@ -1,300 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.client.message;
-
-import javax.jms.JMSException;
-
-import junit.framework.Assert;
-import junit.framework.TestCase;
-
-import org.apache.qpid.client.message.JMSMapMessage;
-import org.apache.qpid.client.message.JMSTextMessage;
-import org.apache.qpid.client.message.TestMessageHelper;
-
-public class TextMessageTest extends TestCase
-{
- public void testTextOnConstruction() throws Exception
- {
- JMSTextMessage tm = TestMessageHelper.newJMSTextMessage();
- tm.setText("pies");
- String val = tm.getText();
- assertEquals(val, "pies");
- }
-
- public void testClearBody() throws Exception
- {
- JMSTextMessage tm = TestMessageHelper.newJMSTextMessage();
- tm.setText("pies");
- tm.clearBody();
- String val = tm.getText();
- assertNull(val);
- tm.setText("Banana");
- val = tm.getText();
- assertEquals(val, "Banana");
- }
-
-
- public void testBooleanPropertyLookup()
- {
- try
- {
- JMSTextMessage tm = TestMessageHelper.newJMSTextMessage();
-
- tm.setBooleanProperty("value", true);
- Assert.assertEquals(true, tm.getBooleanProperty("value"));
- Assert.assertEquals("true", tm.getStringProperty("value"));
- }
- catch (JMSException e)
- {
- Assert.fail("JMSException received." + e);
- }
- }
-
- public void testBytePropertyLookup()
- {
- try
- {
- JMSMapMessage mm = TestMessageHelper.newJMSMapMessage();
- mm.setByteProperty("value", Byte.MAX_VALUE);
-
- Assert.assertEquals(Byte.MAX_VALUE, mm.getByteProperty("value"));
- Assert.assertEquals((short) Byte.MAX_VALUE, mm.getShortProperty("value"));
- Assert.assertEquals(Byte.MAX_VALUE, mm.getIntProperty("value"));
- Assert.assertEquals((long) Byte.MAX_VALUE, mm.getLongProperty("value"));
- Assert.assertEquals("" + Byte.MAX_VALUE, mm.getStringProperty("value"));
-
- }
- catch (JMSException e)
- {
- Assert.fail("JMSException received." + e);
- }
- }
-
- public void testShortPropertyLookup()
- {
- try
- {
- JMSMapMessage mm = TestMessageHelper.newJMSMapMessage();
- mm.setShortProperty("value", Short.MAX_VALUE);
- Assert.assertEquals(Short.MAX_VALUE, mm.getShortProperty("value"));
- Assert.assertEquals((int) Short.MAX_VALUE, mm.getIntProperty("value"));
- Assert.assertEquals((long) Short.MAX_VALUE, mm.getLongProperty("value"));
- Assert.assertEquals("" + Short.MAX_VALUE, mm.getStringProperty("value"));
- }
- catch (JMSException e)
- {
- Assert.fail("JMSException received." + e);
- }
- }
-
- public void testDoublePropertyLookup()
- {
- try
- {
- JMSMapMessage mm = TestMessageHelper.newJMSMapMessage();
- mm.setDoubleProperty("value", Double.MAX_VALUE);
- Assert.assertEquals(Double.MAX_VALUE, mm.getDoubleProperty("value"));
- Assert.assertEquals("" + Double.MAX_VALUE, mm.getStringProperty("value"));
- }
- catch (JMSException e)
- {
- Assert.fail("JMSException received." + e);
- }
- }
-
- public void testFloatPropertyLookup()
- {
- try
- {
- JMSMapMessage mm = TestMessageHelper.newJMSMapMessage();
- mm.setFloatProperty("value", Float.MAX_VALUE);
- Assert.assertEquals(Float.MAX_VALUE, mm.getFloatProperty("value"));
- Assert.assertEquals((double) Float.MAX_VALUE, mm.getDoubleProperty("value"));
- Assert.assertEquals("" + Float.MAX_VALUE, mm.getStringProperty("value"));
- }
- catch (JMSException e)
- {
- Assert.fail("JMSException received." + e);
- }
- }
-
- public void testIntPropertyLookup()
- {
- try
- {
- JMSMapMessage mm = TestMessageHelper.newJMSMapMessage();
- mm.setIntProperty("value", Integer.MAX_VALUE);
- Assert.assertEquals(Integer.MAX_VALUE, mm.getIntProperty("value"));
- Assert.assertEquals((long) Integer.MAX_VALUE, mm.getLongProperty("value"));
- Assert.assertEquals("" + Integer.MAX_VALUE, mm.getStringProperty("value"));
- }
- catch (JMSException e)
- {
- Assert.fail("JMSException received." + e);
- }
- }
-
- public void testLongPropertyLookup()
- {
- try
- {
- JMSMapMessage mm = TestMessageHelper.newJMSMapMessage();
- mm.setLongProperty("value", Long.MAX_VALUE);
- Assert.assertEquals(Long.MAX_VALUE, mm.getLongProperty("value"));
- Assert.assertEquals("" + Long.MAX_VALUE, mm.getStringProperty("value"));
- }
- catch (JMSException e)
- {
- Assert.fail("JMSException received." + e);
- }
- }
-
-
- // Failed Lookups
-
- public void testFailedBooleanPropertyLookup()
- {
- try
- {
- JMSMapMessage mm = TestMessageHelper.newJMSMapMessage();
- Assert.assertEquals(false, mm.getBooleanProperty("int"));
- }
- catch (JMSException e)
- {
- Assert.fail("JMSException received." + e);
- }
- }
-
- public void testFailedBytePropertyLookup()
- {
- try
- {
- JMSMapMessage mm = TestMessageHelper.newJMSMapMessage();
- mm.getByteProperty("random");
- Assert.fail("NumberFormatException expected");
- }
- catch (NumberFormatException e)
- {
- //normal execution
- }
- catch (JMSException e)
- {
- Assert.fail("JMSException received:" + e);
- }
-
- }
-
- public void testFailedDoublePropertyLookup()
- {
- try
- {
- JMSMapMessage mm = TestMessageHelper.newJMSMapMessage();
- mm.getDoubleProperty("random");
- Assert.fail("NullPointerException should be received.");
- }
- catch (NullPointerException e)
- {
- //normal execution
- }
- catch (JMSException e)
- {
- Assert.fail("JMSException received:" + e);
- }
- }
-
- public void testFailedFloatPropertyLookup()
- {
- try
- {
- JMSMapMessage mm = TestMessageHelper.newJMSMapMessage();
- mm.getFloatProperty("random");
- Assert.fail("NullPointerException should be received.");
- }
- catch (NullPointerException e)
- {
- //normal execution
- }
- catch (JMSException e)
- {
- Assert.fail("JMSException received:" + e);
- }
- }
-
- public void testFailedIntPropertyLookup()
- {
- try
- {
- JMSMapMessage mm = TestMessageHelper.newJMSMapMessage();
- mm.getIntProperty("random");
- Assert.fail("NumberFormatException should be received.");
- }
- catch (NumberFormatException e)
- {
- //normal execution
- }
- catch (JMSException e)
- {
- Assert.fail("JMSException received:" + e);
- }
- }
-
- public void testFailedLongPropertyLookup()
- {
- try
- {
- JMSMapMessage mm = TestMessageHelper.newJMSMapMessage();
- mm.getLongProperty("random");
- Assert.fail("NumberFormatException should be received.");
- }
- catch (NumberFormatException e)
- {
- //normal execution
- }
- catch (JMSException e)
- {
- Assert.fail("JMSException received:" + e);
- }
- }
-
- public void testFailedShortPropertyLookup()
- {
- try
- {
- JMSMapMessage mm = TestMessageHelper.newJMSMapMessage();
- mm.getShortProperty("random");
- Assert.fail("NumberFormatException should be received.");
- }
- catch (NumberFormatException e)
- {
- //normal execution
- }
- catch (JMSException e)
- {
- Assert.fail("JMSException received:" + e);
- }
- }
-
-
- public static junit.framework.Test suite()
- {
- return new junit.framework.TestSuite(TextMessageTest.class);
- }
-}
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/jndi/ConnectionFactoryTest.java b/java/client/src/test/java/org/apache/qpid/test/unit/jndi/ConnectionFactoryTest.java
deleted file mode 100644
index 9e76b0d468..0000000000
--- a/java/client/src/test/java/org/apache/qpid/test/unit/jndi/ConnectionFactoryTest.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.jndi;
-
-import junit.framework.TestCase;
-import org.apache.qpid.client.AMQConnectionFactory;
-import org.apache.qpid.jms.BrokerDetails;
-import org.apache.qpid.jms.ConnectionURL;
-import org.apache.qpid.url.URLSyntaxException;
-
-public class ConnectionFactoryTest extends TestCase
-{
-
- //URL will be returned with the password field swapped for '********'
- // so ensure that these two strings are kept in sync.
- public static final String URL = "amqp://guest:guest@clientID/test?brokerlist='tcp://localhost:5672'";
- public static final String URL_STAR_PWD = "amqp://guest:********@clientID/test?brokerlist='tcp://localhost:5672'";
-
- public void testConnectionURLString()
- {
- AMQConnectionFactory factory = new AMQConnectionFactory();
-
- assertNull("ConnectionURL should have no value at start",
- factory.getConnectionURL());
-
- try
- {
- factory.setConnectionURLString(URL);
- }
- catch (URLSyntaxException e)
- {
- fail(e.getMessage());
- }
-
- //URL will be returned with the password field swapped for '********'
- assertEquals("Connection URL not correctly set", URL_STAR_PWD, factory.getConnectionURLString());
-
- // Further test that the processed ConnectionURL is as expected after
- // the set call
- ConnectionURL connectionurl = factory.getConnectionURL();
-
- assertNull("Failover is set.", connectionurl.getFailoverMethod());
- assertEquals("guest", connectionurl.getUsername());
- assertEquals("guest", connectionurl.getPassword());
- assertEquals("clientID", connectionurl.getClientName());
- assertEquals("/test", connectionurl.getVirtualHost());
-
- assertEquals(1, connectionurl.getBrokerCount());
-
- BrokerDetails service = connectionurl.getBrokerDetails(0);
-
- assertEquals("tcp", service.getTransport());
- assertEquals("localhost", service.getHost());
- assertEquals(5672, service.getPort());
-
- }
-}
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/jndi/JNDIPropertyFileTest.java b/java/client/src/test/java/org/apache/qpid/test/unit/jndi/JNDIPropertyFileTest.java
deleted file mode 100644
index a1b14d5723..0000000000
--- a/java/client/src/test/java/org/apache/qpid/test/unit/jndi/JNDIPropertyFileTest.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- *
- */
-package org.apache.qpid.test.unit.jndi;
-
-import java.util.Properties;
-
-import javax.jms.Queue;
-import javax.jms.Topic;
-import javax.naming.Context;
-import javax.naming.InitialContext;
-
-import org.apache.qpid.client.AMQDestination;
-import org.apache.qpid.framing.AMQShortString;
-
-import junit.framework.TestCase;
-
-public class JNDIPropertyFileTest extends TestCase
-{
- Context ctx;
-
- public JNDIPropertyFileTest() throws Exception
- {
- Properties properties = new Properties();
- properties.load(this.getClass().getResourceAsStream("JNDITest.properties"));
-
- //Create the initial context
- ctx = new InitialContext(properties);
- }
-
- public void testQueueNamesWithTrailingSpaces() throws Exception
- {
- Queue queue = (Queue)ctx.lookup("QueueNameWithSpace");
- assertEquals("QueueNameWithSpace",queue.getQueueName());
- }
-
- public void testTopicNamesWithTrailingSpaces() throws Exception
- {
- Topic topic = (Topic)ctx.lookup("TopicNameWithSpace");
- assertEquals("TopicNameWithSpace",topic.getTopicName());
- }
-
- public void testMultipleTopicNamesWithTrailingSpaces() throws Exception
- {
- Topic topic = (Topic)ctx.lookup("MultipleTopicNamesWithSpace");
- int i = 0;
- for (AMQShortString bindingKey: ((AMQDestination)topic).getBindingKeys())
- {
- i++;
- assertEquals("Topic" + i + "WithSpace",bindingKey.asString());
- }
- }
-}
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/jndi/JNDITest.properties b/java/client/src/test/java/org/apache/qpid/test/unit/jndi/JNDITest.properties
deleted file mode 100644
index 07017a05a6..0000000000
--- a/java/client/src/test/java/org/apache/qpid/test/unit/jndi/JNDITest.properties
+++ /dev/null
@@ -1,28 +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.
-#
-java.naming.factory.initial = org.apache.qpid.jndi.PropertiesFileInitialContextFactory
-
-# Queue name with spaces
-queue.QueueNameWithSpace = QueueNameWithSpace
-
-# Topic name with spaces
-topic.TopicNameWithSpace = TopicNameWithSpace
-
-# Multiple topic names with spaces
-topic.MultipleTopicNamesWithSpace = Topic1WithSpace , Topic2WithSpace , Topic3WithSpace
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/message/MessageConverterTest.java b/java/client/src/test/java/org/apache/qpid/test/unit/message/MessageConverterTest.java
deleted file mode 100644
index b5e7ae82b5..0000000000
--- a/java/client/src/test/java/org/apache/qpid/test/unit/message/MessageConverterTest.java
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.message;
-
-import javax.jms.*;
-
-import junit.framework.TestCase;
-
-import org.apache.qpid.client.*;
-import org.apache.qpid.client.protocol.AMQProtocolHandler;
-import org.apache.qpid.client.failover.FailoverException;
-import org.apache.qpid.client.message.*;
-import org.apache.qpid.exchange.ExchangeDefaults;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.FieldTable;
-import org.apache.qpid.AMQException;
-
-import java.util.Map;
-
-
-public class MessageConverterTest extends TestCase
-{
-
- public static final String JMS_CORR_ID = "QPIDID_01";
- public static final int JMS_DELIV_MODE = 1;
- public static final String JMS_TYPE = "test.jms.type";
- public static final Destination JMS_REPLY_TO = new AMQQueue(ExchangeDefaults.DIRECT_EXCHANGE_NAME,"my.replyto");
-
- protected JMSTextMessage testTextMessage;
-
- protected JMSMapMessage testMapMessage;
- private AMQSession _session = new TestAMQSession();
-
-
- protected void setUp() throws Exception
- {
- super.setUp();
- testTextMessage = new JMSTextMessage(AMQMessageDelegateFactory.FACTORY_0_8);
-
- //Set Message Text
- testTextMessage.setText("testTextMessage text");
- setMessageProperties(testTextMessage);
-
- testMapMessage = new JMSMapMessage(AMQMessageDelegateFactory.FACTORY_0_8);
- testMapMessage.setString("testMapString", "testMapStringValue");
- testMapMessage.setDouble("testMapDouble", Double.MAX_VALUE);
- }
-
- public void testSetProperties() throws Exception
- {
- AbstractJMSMessage newMessage = new MessageConverter(_session, (TextMessage) testTextMessage).getConvertedMessage();
- mesagePropertiesTest(testTextMessage, newMessage);
- }
-
- public void testJMSTextMessageConversion() throws Exception
- {
- AbstractJMSMessage newMessage = new MessageConverter(_session, (TextMessage) testTextMessage).getConvertedMessage();
- assertEquals("Converted message text mismatch", ((JMSTextMessage) newMessage).getText(), testTextMessage.getText());
- }
-
- public void testJMSMapMessageConversion() throws Exception
- {
- AbstractJMSMessage newMessage = new MessageConverter(_session, (MapMessage) testMapMessage).getConvertedMessage();
- assertEquals("Converted map message String mismatch", ((JMSMapMessage) newMessage).getString("testMapString"),
- testMapMessage.getString("testMapString"));
- assertEquals("Converted map message Double mismatch", ((JMSMapMessage) newMessage).getDouble("testMapDouble"),
- testMapMessage.getDouble("testMapDouble"));
-
- }
-
- public void testMessageConversion() throws Exception
- {
- Message newMessage = new NonQpidMessage();
- setMessageProperties(newMessage);
- mesagePropertiesTest(testTextMessage, newMessage);
- }
-
- private void setMessageProperties(Message message) throws JMSException
- {
- message.setJMSCorrelationID(JMS_CORR_ID);
- message.setJMSDeliveryMode(JMS_DELIV_MODE);
- message.setJMSType(JMS_TYPE);
- message.setJMSReplyTo(JMS_REPLY_TO);
-
- //Add non-JMS properties
- message.setStringProperty("testProp1", "testValue1");
- message.setDoubleProperty("testProp2", Double.MIN_VALUE);
- }
-
-
- private void mesagePropertiesTest(Message expectedMessage, Message actualMessage)
- {
- try
- {
- //check JMS prop values on newMessage match
- assertEquals("JMS Correlation ID mismatch", expectedMessage.getJMSCorrelationID(), actualMessage.getJMSCorrelationID());
- assertEquals("JMS Delivery mode mismatch", expectedMessage.getJMSDeliveryMode(), actualMessage.getJMSDeliveryMode());
- assertEquals("JMS Type mismatch", expectedMessage.getJMSType(), actualMessage.getJMSType());
- assertEquals("JMS Reply To mismatch", expectedMessage.getJMSReplyTo(), actualMessage.getJMSReplyTo());
-
- //check non-JMS standard props ok too
- assertEquals("Test String prop value mismatch", expectedMessage.getStringProperty("testProp1"),
- actualMessage.getStringProperty("testProp1"));
-
- assertEquals("Test Double prop value mismatch", expectedMessage.getDoubleProperty("testProp2"),
- actualMessage.getDoubleProperty("testProp2"));
- }
- catch (JMSException e)
- {
- fail("An error occured testing the property values" + e.getCause());
- e.printStackTrace();
- }
- }
-
- protected void tearDown() throws Exception
- {
- super.tearDown();
- testTextMessage = null;
- }
-
-
-}
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/message/NonQpidMessage.java b/java/client/src/test/java/org/apache/qpid/test/unit/message/NonQpidMessage.java
deleted file mode 100644
index b1cf23bb9e..0000000000
--- a/java/client/src/test/java/org/apache/qpid/test/unit/message/NonQpidMessage.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.
- *
- *
- */
-package org.apache.qpid.test.unit.message;
-
-import java.util.Enumeration;
-import java.util.Hashtable;
-
-import javax.jms.Destination;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageFormatException;
-
-public class NonQpidMessage implements Message
-{
- private String _JMSMessageID;
- private long _JMSTimestamp;
- private byte[] _JMSCorrelationIDAsBytes;
- private String _JMSCorrelationID;
- private Destination _JMSReplyTo;
- private Destination _JMSDestination;
- private int _JMSDeliveryMode;
- private boolean _JMSRedelivered;
- private String _JMSType;
- private long _JMSExpiration;
- private int _JMSPriority;
- private Hashtable _properties;
-
- public NonQpidMessage()
- {
- _properties = new Hashtable();
- _JMSPriority = javax.jms.Message.DEFAULT_PRIORITY;
- _JMSDeliveryMode = javax.jms.Message.DEFAULT_DELIVERY_MODE;
- }
-
- public String getJMSMessageID() throws JMSException
- {
- return _JMSMessageID;
- }
-
- public void setJMSMessageID(String string) throws JMSException
- {
- _JMSMessageID = string;
- }
-
- public long getJMSTimestamp() throws JMSException
- {
- return _JMSTimestamp;
- }
-
- public void setJMSTimestamp(long l) throws JMSException
- {
- _JMSTimestamp = l;
- }
-
- public byte[] getJMSCorrelationIDAsBytes() throws JMSException
- {
- return _JMSCorrelationIDAsBytes;
- }
-
- public void setJMSCorrelationIDAsBytes(byte[] bytes) throws JMSException
- {
- _JMSCorrelationIDAsBytes = bytes;
- }
-
- public void setJMSCorrelationID(String string) throws JMSException
- {
- _JMSCorrelationID = string;
- }
-
- public String getJMSCorrelationID() throws JMSException
- {
- return _JMSCorrelationID;
- }
-
- public Destination getJMSReplyTo() throws JMSException
- {
- return _JMSReplyTo;
- }
-
- public void setJMSReplyTo(Destination destination) throws JMSException
- {
- _JMSReplyTo = destination;
- }
-
- public Destination getJMSDestination() throws JMSException
- {
- return _JMSDestination;
- }
-
- public void setJMSDestination(Destination destination) throws JMSException
- {
- _JMSDestination = destination;
- }
-
- public int getJMSDeliveryMode() throws JMSException
- {
- return _JMSDeliveryMode;
- }
-
- public void setJMSDeliveryMode(int i) throws JMSException
- {
- _JMSDeliveryMode = i;
- }
-
- public boolean getJMSRedelivered() throws JMSException
- {
- return _JMSRedelivered;
- }
-
- public void setJMSRedelivered(boolean b) throws JMSException
- {
- _JMSRedelivered = b;
- }
-
- public String getJMSType() throws JMSException
- {
- return _JMSType;
- }
-
- public void setJMSType(String string) throws JMSException
- {
- _JMSType = string;
- }
-
- public long getJMSExpiration() throws JMSException
- {
- return _JMSExpiration;
- }
-
- public void setJMSExpiration(long l) throws JMSException
- {
- _JMSExpiration = l;
- }
-
- public int getJMSPriority() throws JMSException
- {
- return _JMSPriority;
- }
-
- public void setJMSPriority(int i) throws JMSException
- {
- _JMSPriority = i;
- }
-
- public void clearProperties() throws JMSException
- {
- _properties.clear();
- }
-
- public boolean propertyExists(String string) throws JMSException
- {
- return _properties.containsKey(string);
- }
-
- public boolean getBooleanProperty(String string) throws JMSException
- {
- if (propertyExists(string))
- {
- Object o = _properties.get(string);
- if (o instanceof Boolean)
- {
- return (Boolean) o;
- }
- else
- {
- return Boolean.valueOf(null);
- }
- }
- else
- {
- throw new JMSException("property does not exist: " + string);
- }
- }
-
- public byte getByteProperty(String string) throws JMSException
- {
- if (propertyExists(string))
- {
- Object o = _properties.get(string);
- if (o instanceof Byte)
- {
- return (Byte) o;
- }
- else
- {
- return Byte.valueOf(null);
- }
- }
- else
- {
- throw new JMSException("property does not exist: " + string);
- }
- }
-
- public short getShortProperty(String string) throws JMSException
- {
- if (propertyExists(string))
- {
- Object o = _properties.get(string);
- if (o instanceof Short)
- {
- return (Short) o;
- }
- else
- {
- return Short.valueOf(null);
- }
- }
- else
- {
- throw new JMSException("property does not exist: " + string);
- }
- }
-
- public int getIntProperty(String string) throws JMSException
- {
- if (propertyExists(string))
- {
- Object o = _properties.get(string);
- if (o instanceof Integer)
- {
- return (Integer) o;
- }
- else
- {
- return Integer.valueOf(null);
- }
- }
- else
- {
- throw new JMSException("property does not exist: " + string);
- }
- }
-
- public long getLongProperty(String string) throws JMSException
- {
- if (propertyExists(string))
- {
- Object o = _properties.get(string);
- if (o instanceof Long)
- {
- return (Long) o;
- }
- else
- {
- return Long.valueOf(null);
- }
- }
- else
- {
- throw new JMSException("property does not exist: " + string);
- }
- }
-
- public float getFloatProperty(String string) throws JMSException
- {
- if (propertyExists(string))
- {
- Object o = _properties.get(string);
- if (o instanceof Float)
- {
- return (Float) o;
- }
- else if(o instanceof String)
- {
- return Float.valueOf((String)o);
- }
- else if(o == null)
- {
- throw new NullPointerException("No such property: " + string);
- }
- else
- {
- throw new MessageFormatException("getFloatProperty(\""+string+"\") failed as value is not a float: " + o);
- }
- }
- else
- {
- throw new JMSException("property does not exist: " + string);
- }
- }
-
- public double getDoubleProperty(String string) throws JMSException
- {
- if (propertyExists(string))
- {
- Object o = _properties.get(string);
- if (o instanceof Double)
- {
- return (Double) o;
- }
- else
- {
- return getFloatProperty(string);
- }
- }
- else
- {
- throw new JMSException("property does not exist: " + string);
- }
- }
-
- public String getStringProperty(String string) throws JMSException
- {
- if (propertyExists(string))
- {
- Object o = _properties.get(string);
- if (o instanceof String)
- {
- return (String) o;
- }
- else
- {
- return null;
- }
- }
- else
- {
- throw new JMSException("property does not exist: " + string);
- }
- }
-
- public Object getObjectProperty(String string) throws JMSException
- {
- if (propertyExists(string))
- {
- Object o = _properties.get(string);
- if (o instanceof Boolean)
- {
- return (Boolean) o;
- }
- else
- {
- return Boolean.valueOf(null);
- }
- }
- else
- {
- throw new JMSException("property does not exist: " + string);
- }
- }
-
- public Enumeration getPropertyNames() throws JMSException
- {
- return _properties.keys();
- }
-
- public void setBooleanProperty(String string, boolean b) throws JMSException
- {
- _properties.put(string, b);
- }
-
- public void setByteProperty(String string, byte b) throws JMSException
- {
- _properties.put(string, b);
- }
-
- public void setShortProperty(String string, short i) throws JMSException
- {
- _properties.put(string, i);
- }
-
- public void setIntProperty(String string, int i) throws JMSException
- {
- _properties.put(string, i);
- }
-
- public void setLongProperty(String string, long l) throws JMSException
- {
- _properties.put(string, l);
- }
-
- public void setFloatProperty(String string, float v) throws JMSException
- {
- _properties.put(string, v);
- }
-
- public void setDoubleProperty(String string, double v) throws JMSException
- {
- _properties.put(string, v);
- }
-
- public void setStringProperty(String string, String string1) throws JMSException
- {
- _properties.put(string, string1);
- }
-
- public void setObjectProperty(String string, Object object) throws JMSException
- {
- _properties.put(string, object);
- }
-
- public void acknowledge() throws JMSException
- {
-
- }
-
- public void clearBody() throws JMSException
- {
-
- }
-}
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/message/TestAMQSession.java b/java/client/src/test/java/org/apache/qpid/test/unit/message/TestAMQSession.java
deleted file mode 100644
index 4637c6e505..0000000000
--- a/java/client/src/test/java/org/apache/qpid/test/unit/message/TestAMQSession.java
+++ /dev/null
@@ -1,204 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.message;
-
-import org.apache.qpid.client.*;
-import org.apache.qpid.client.message.AMQMessageDelegateFactory;
-import org.apache.qpid.client.protocol.AMQProtocolHandler;
-import org.apache.qpid.client.failover.FailoverException;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.FieldTable;
-import org.apache.qpid.AMQException;
-
-import javax.jms.*;
-
-import java.util.Map;
-
-public class TestAMQSession extends AMQSession<BasicMessageConsumer_0_8, BasicMessageProducer_0_8>
-{
-
- public TestAMQSession()
- {
- super(null, 0, false, AUTO_ACKNOWLEDGE, null, 0, 0);
- }
-
- public void acknowledgeMessage(long deliveryTag, boolean multiple)
- {
-
- }
-
- public void sendQueueBind(AMQShortString queueName, AMQShortString routingKey, FieldTable arguments,
- AMQShortString exchangeName, AMQDestination destination,
- boolean nowait) throws AMQException, FailoverException
- {
-
- }
-
- public void sendClose(long timeout) throws AMQException, FailoverException
- {
-
- }
-
- public void sendCommit() throws AMQException, FailoverException
- {
-
- }
-
- public TopicSubscriber createDurableSubscriber(Topic topic, String name) throws JMSException
- {
- return null;
- }
-
- public void sendCreateQueue(AMQShortString name, boolean autoDelete, boolean durable, boolean exclusive, Map<String, Object> arguments) throws AMQException, FailoverException
- {
-
- }
-
- public TemporaryQueue createTemporaryQueue() throws JMSException
- {
- return null;
- }
-
- protected void sendRecover() throws AMQException, FailoverException
- {
-
- }
-
- public void rejectMessage(long deliveryTag, boolean requeue)
- {
-
- }
-
- public void releaseForRollback()
- {
-
- }
-
- public void sendRollback() throws AMQException, FailoverException
- {
-
- }
-
- public BasicMessageConsumer_0_8 createMessageConsumer(AMQDestination destination, int prefetchHigh, int prefetchLow, boolean noLocal, boolean exclusive, String selector, FieldTable arguments, boolean noConsume, boolean autoClose) throws JMSException
- {
- return null;
- }
-
- public boolean isQueueBound(AMQShortString exchangeName, AMQShortString queueName, AMQShortString routingKey) throws JMSException
- {
- return false;
- }
-
- public boolean isQueueBound(AMQDestination destination) throws JMSException
- {
- return false;
- }
-
- public void sendConsume(BasicMessageConsumer_0_8 consumer, AMQShortString queueName, AMQProtocolHandler protocolHandler, boolean nowait, String messageSelector, int tag) throws AMQException, FailoverException
- {
-
- }
-
- public BasicMessageProducer_0_8 createMessageProducer(Destination destination, boolean mandatory, boolean immediate, boolean waitUntilSent, long producerId)
- {
- return null;
- }
-
- protected Long requestQueueDepth(AMQDestination amqd) throws AMQException, FailoverException
- {
- return null;
- }
-
- public void sendExchangeDeclare(AMQShortString name, AMQShortString type, AMQProtocolHandler protocolHandler, boolean nowait) throws AMQException, FailoverException
- {
-
- }
-
- public void sendQueueDeclare(AMQDestination amqd, AMQProtocolHandler protocolHandler,
- boolean nowait) throws AMQException, FailoverException
- {
-
- }
-
- public void sendQueueDelete(AMQShortString queueName) throws AMQException, FailoverException
- {
-
- }
-
- public void sendSuspendChannel(boolean suspend) throws AMQException, FailoverException
- {
-
- }
-
- protected boolean tagLE(long tag1, long tag2)
- {
- return false;
- }
-
- protected boolean updateRollbackMark(long current, long deliveryTag)
- {
- return false;
- }
-
- public AMQMessageDelegateFactory getMessageDelegateFactory()
- {
- return AMQMessageDelegateFactory.FACTORY_0_8;
- }
-
- protected Object getFailoverMutex()
- {
- return this;
- }
-
- public void checkNotClosed()
- {
-
- }
-
- public void sync()
- {
- }
-
- public void handleAddressBasedDestination(AMQDestination dest,
- boolean isConsumer,
- boolean noWait) throws AMQException
- {
- throw new UnsupportedOperationException("The new addressing based sytanx is "
- + "not supported for AMQP 0-8/0-9 versions");
- }
-
- @Override
- protected void flushAcknowledgments()
- {
- }
-
- public boolean isQueueBound(String exchangeName, String queueName,
- String bindingKey, Map<String, Object> args) throws JMSException
- {
- return false;
- }
-
- @Override
- public AMQException getLastException()
- {
- return null;
- }
-}
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/tests.properties b/java/client/src/test/java/org/apache/qpid/test/unit/tests.properties
deleted file mode 100644
index 2fd961a078..0000000000
--- a/java/client/src/test/java/org/apache/qpid/test/unit/tests.properties
+++ /dev/null
@@ -1,45 +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.
-
-
-java.naming.factory.initial = org.apache.qpid.jndi.PropertiesFileInitialContextFactory
-
-# use the following property to configure the default connector
-#java.naming.provider.url - ignored.
-
-# register some connection factories
-# connectionfactory.[jndiname] = [ConnectionURL]
-connectionfactory.local = amqp://username:password@clientid/test?brokerlist='tcp://localhost:5672'
-#qpid:password=guest;username=guest;client_id=clientid;virtualhost=test@tcp:127.0.0.1:5672
-
-
-# register some queues in JNDI using the form
-# queue.[jndiName] = [physicalName]
-queue.MyQueue = example.MyQueue
-queue.queue = example.queue
-queue.xaQueue = xaQueue
-
-# register some topics in JNDI using the form
-# topic.[jndiName] = [physicalName]
-#topic.ibmStocks = stocks.nyse.ibm
-topic.xaTopic = xaTopic
-topic.durableSubscriberTopic = durableSubscriberTopic
-
-# Register an AMQP destination in JNDI
-# NOTE: Qpid currently only supports direct,topics and headers
-# destination.[jniName] = [BindingURL]
-#destination.direct = direct://amq.direct//directQueue
diff --git a/java/client/test/bin/IBM-JNDI-Setup.bat b/java/client/test/bin/IBM-JNDI-Setup.bat
deleted file mode 100644
index eb6a87fa9e..0000000000
--- a/java/client/test/bin/IBM-JNDI-Setup.bat
+++ /dev/null
@@ -1,69 +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
-
-@echo off
-REM Script to run the Qpid Java Broker
-
-set CMD="IBM-JNDI-Setup.bat"
-set JAVACLASS=
-
-rem Guess QPID_HOME if not defined
-set CURRENT_DIR=%cd%
-if not "%QPID_HOME%" == "" goto gotHome
-set QPID_HOME=%CURRENT_DIR%
-echo %QPID_HOME%
-if exist "%QPID_HOME%\bin\%CMD%" goto okHome
-cd ..
-set QPID_HOME=%cd%
-cd %CURRENT_DIR%
-:gotHome
-if exist "%QPID_HOME%\bin\%CMD%" goto okHome
-echo The QPID_HOME environment variable is not defined correctly
-echo This environment variable is needed to run this program
-goto end
-:okHome
-
-if not "%JAVA_HOME%" == "" goto gotJavaHome
-echo The JAVA_HOME environment variable is not defined
-echo This environment variable is needed to run this program
-goto exit
-:gotJavaHome
-if not exist "%JAVA_HOME%\bin\java.exe" goto noJavaHome
-goto okJavaHome
-:noJavaHome
-echo The JAVA_HOME environment variable is not defined correctly
-echo This environment variable is needed to run this program.
-goto exit
-:okJavaHome
-
-set CLIENT_TEST_CLASSES=%QPID_HOME%\lib\client-test-launch.jar
-
-echo on
-"%JAVA_HOME%\bin\java" -server -Xmx1024m -DQPID_HOME="%QPID_HOME%" -cp "%CLIENT_TEST_CLASSES%" org.apache.qpid.IBMPerfTest.JNDIBindConnectionFactory amqp://guest:guest@clientid/testpath?brokerlist='localhost' amq.ConnectionFactory
-"%JAVA_HOME%\bin\java" -server -Xmx1024m -DQPID_HOME="%QPID_HOME%" -cp "%CLIENT_TEST_CLASSES%" org.apache.qpid.IBMPerfTest.JNDIBindConnectionFactory amqp://guest:guest@clientid/testpath?brokerlist='vm://:1' amq.VMConnectionFactory
-"%JAVA_HOME%\bin\java" -server -Xmx1024m -DQPID_HOME="%QPID_HOME%" -cp "%CLIENT_TEST_CLASSES%" org.apache.qpid.IBMPerfTest.JNDIBindQueue amq.Queue direct://amq.direct//IBMPerfQueue1
-"%JAVA_HOME%\bin\java" -server -Xmx1024m -DQPID_HOME="%QPID_HOME%" -cp "%CLIENT_TEST_CLASSES%" org.apache.qpid.IBMPerfTest.JNDIBindTopic amq.Topic1 topic://amq.topic/IBMPerfTopic1/
-"%JAVA_HOME%\bin\java" -server -Xmx1024m -DQPID_HOME="%QPID_HOME%" -cp "%CLIENT_TEST_CLASSES%" org.apache.qpid.IBMPerfTest.JNDIBindTopic amq.Topic2 topic://amq.topic/IBMPerfTopic2/
-"%JAVA_HOME%\bin\java" -server -Xmx1024m -DQPID_HOME="%QPID_HOME%" -cp "%CLIENT_TEST_CLASSES%" org.apache.qpid.IBMPerfTest.JNDIBindTopic amq.Topic3 topic://amq.topic/IBMPerfTopic3/
-
-
-
-:end
-
-pause \ No newline at end of file
diff --git a/java/client/test/bin/IBM-JNDI-Setup.sh b/java/client/test/bin/IBM-JNDI-Setup.sh
deleted file mode 100755
index e3112f812d..0000000000
--- a/java/client/test/bin/IBM-JNDI-Setup.sh
+++ /dev/null
@@ -1,27 +0,0 @@
-#!/bin/bash
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-#
-
-qpid-run org.apache.qpid.IBMPerfTest.JNDIBindConnectionFactory amqp://guest:guest@clientid/testpath?brokerlist=\'tcp://localhost\' amq.ConnectionFactory
-qpid-run org.apache.qpid.IBMPerfTest.JNDIBindConnectionFactory amqp://guest:guest@clientid/testpath?brokerlist=\'vm://:1\' amq.VMConnectionFactory
-qpid-run org.apache.qpid.IBMPerfTest.JNDIBindQueue amq.Queue direct://amq.direct//IBMPerfQueue1
-qpid-run org.apache.qpid.IBMPerfTest.JNDIBindTopic amq.Topic1 topic://amq.topic/IBMPerfTopic1/
-qpid-run org.apache.qpid.IBMPerfTest.JNDIBindTopic amq.Topic2 topic://amq.topic/IBMPerfTopic2/
-qpid-run org.apache.qpid.IBMPerfTest.JNDIBindTopic amq.Topic3 topic://amq.topic/IBMPerfTopic3/
-qpid-run org.apache.qpid.IBMPerfTest.JNDIBindTopic amq.Topic4 topic://amq.topic/IBMPerfTopic4/ \ No newline at end of file
diff --git a/java/client/test/bin/IBM-Publisher.bat b/java/client/test/bin/IBM-Publisher.bat
deleted file mode 100644
index 5bb4343c4c..0000000000
--- a/java/client/test/bin/IBM-Publisher.bat
+++ /dev/null
@@ -1,62 +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
-
-@echo off
-REM Script to run the Qpid Java Broker
-
-set CMD="IBM-Publisher.bat"
-set JAVACLASS=JMSPerfHarness -pc JNDI -ii com.sun.jndi.fscontext.RefFSContextFactory -iu file:/C:/temp/IBMPerfTestsJNDI/ -cf amq.ConnectionFactory -d amq.Topic -db 1 -dx 4 -tc jms.r11.Publisher -nt 4 %*
-
-rem Guess QPID_HOME if not defined
-set CURRENT_DIR=%cd%
-if not "%QPID_HOME%" == "" goto gotHome
-set QPID_HOME=%CURRENT_DIR%
-echo %QPID_HOME%
-if exist "%QPID_HOME%\bin\%CMD%" goto okHome
-cd ..
-set QPID_HOME=%cd%
-cd %CURRENT_DIR%
-:gotHome
-if exist "%QPID_HOME%\bin\%CMD%" goto okHome
-echo The QPID_HOME environment variable is not defined correctly
-echo This environment variable is needed to run this program
-goto end
-:okHome
-
-if not "%JAVA_HOME%" == "" goto gotJavaHome
-echo The JAVA_HOME environment variable is not defined
-echo This environment variable is needed to run this program
-goto exit
-:gotJavaHome
-if not exist "%JAVA_HOME%\bin\java.exe" goto noJavaHome
-goto okJavaHome
-:noJavaHome
-echo The JAVA_HOME environment variable is not defined correctly
-echo This environment variable is needed to run this program.
-goto exit
-:okJavaHome
-
-set CLIENT_TEST_CLASSES=%QPID_HOME%\lib\client-test-launch.jar
-
-echo on
-"%JAVA_HOME%\bin\java" -server -Xmx1024m -DQPID_HOME="%QPID_HOME%" -cp "%CLIENT_TEST_CLASSES%" %JAVACLASS%
-
-:end
-
-pause \ No newline at end of file
diff --git a/java/client/test/bin/IBM-Publisher.sh b/java/client/test/bin/IBM-Publisher.sh
deleted file mode 100755
index adecf040bc..0000000000
--- a/java/client/test/bin/IBM-Publisher.sh
+++ /dev/null
@@ -1,22 +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.
-#
-
-export MSGSIZE=100
-qpid-run JMSPerfHarness -pc JNDI -ii com.sun.jndi.fscontext.RefFSContextFactory -iu file:///tmp/IBMPerfTestsJNDI/ -cf amq.ConnectionFactory -d amq.Topic -db 1 -dx 4 -tc jms.r11.Publisher -nt 4 $* \ No newline at end of file
diff --git a/java/client/test/bin/IBM-PutGet.bat b/java/client/test/bin/IBM-PutGet.bat
deleted file mode 100644
index c4316f1256..0000000000
--- a/java/client/test/bin/IBM-PutGet.bat
+++ /dev/null
@@ -1,62 +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
-
-@echo off
-REM Script to run the Qpid Java Broker
-
-set CMD="IBM-PutGet.bat"
-set JAVACLASS=JMSPerfHarness -pc JNDI -ii com.sun.jndi.fscontext.RefFSContextFactory -iu file:/C:/temp/IBMPerfTestsJNDI/ -cf amq.ConnectionFactory -d amq.Queue -tc jms.r11.PutGet -nt 6 %*
-
-rem Guess QPID_HOME if not defined
-set CURRENT_DIR=%cd%
-if not "%QPID_HOME%" == "" goto gotHome
-set QPID_HOME=%CURRENT_DIR%
-echo %QPID_HOME%
-if exist "%QPID_HOME%\bin\%CMD%" goto okHome
-cd ..
-set QPID_HOME=%cd%
-cd %CURRENT_DIR%
-:gotHome
-if exist "%QPID_HOME%\bin\%CMD%" goto okHome
-echo The QPID_HOME environment variable is not defined correctly
-echo This environment variable is needed to run this program
-goto end
-:okHome
-
-if not "%JAVA_HOME%" == "" goto gotJavaHome
-echo The JAVA_HOME environment variable is not defined
-echo This environment variable is needed to run this program
-goto exit
-:gotJavaHome
-if not exist "%JAVA_HOME%\bin\java.exe" goto noJavaHome
-goto okJavaHome
-:noJavaHome
-echo The JAVA_HOME environment variable is not defined correctly
-echo This environment variable is needed to run this program.
-goto exit
-:okJavaHome
-
-set CLIENT_TEST_CLASSES=%QPID_HOME%\lib\client-test-launch.jar
-
-echo on
-"%JAVA_HOME%\bin\java" -server -Xmx1024m -DQPID_HOME="%QPID_HOME%" -cp "%CLIENT_TEST_CLASSES%" %JAVACLASS%
-
-:end
-
-pause \ No newline at end of file
diff --git a/java/client/test/bin/IBM-PutGet.sh b/java/client/test/bin/IBM-PutGet.sh
deleted file mode 100755
index c75667c9f6..0000000000
--- a/java/client/test/bin/IBM-PutGet.sh
+++ /dev/null
@@ -1,21 +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.
-#
-
-qpid-run JMSPerfHarness -pc JNDI -ii com.sun.jndi.fscontext.RefFSContextFactory -iu file:///tmp/IBMPerfTestsJNDI/ -cf amq.ConnectionFactory -d amq.Queue -tc jms.r11.PutGet -nt 6 $* \ No newline at end of file
diff --git a/java/client/test/bin/IBM-README.txt b/java/client/test/bin/IBM-README.txt
deleted file mode 100644
index b076f3b3ca..0000000000
--- a/java/client/test/bin/IBM-README.txt
+++ /dev/null
@@ -1,19 +0,0 @@
-The IBM JMS Performance Harness scripts have take the following additional parameters
-
--tx : Enable transactions
--pp : Enable persistent messaging
-
--ms 1000 : Set message size (default 1000 bytes)
--cc 1 : Number of messages to per commit (default 1) Only applies to Sender/Subscriber
-
-The IBM JMS Performance Harness will need to be downloaded and the library added to client/test/lib.
-
-The Library can be found here:
-
-http://www.alphaworks.ibm.com/tech/perfharness
-
-Before running the required test the IBM JNDI Setup script should be run.
-
-This will create a filesystem based JNDI Context located at:
-
-System.properties{java.io.tmpdir}/IBMPerfTestsJNDI/ \ No newline at end of file
diff --git a/java/client/test/bin/IBM-Receiver.bat b/java/client/test/bin/IBM-Receiver.bat
deleted file mode 100644
index dff44d472a..0000000000
--- a/java/client/test/bin/IBM-Receiver.bat
+++ /dev/null
@@ -1,62 +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
-
-@echo off
-REM Script to run the Qpid Java Broker
-
-set CMD="IBM-Receiver.bat"
-set JAVACLASS=JMSPerfHarness -pc JNDI -ii com.sun.jndi.fscontext.RefFSContextFactory -iu file:/C:/temp/IBMPerfTestsJNDI/ -cf amq.ConnectionFactory -d amq.Queue -tc jms.r11.Receiver %*
-
-rem Guess QPID_HOME if not defined
-set CURRENT_DIR=%cd%
-if not "%QPID_HOME%" == "" goto gotHome
-set QPID_HOME=%CURRENT_DIR%
-echo %QPID_HOME%
-if exist "%QPID_HOME%\bin\%CMD%" goto okHome
-cd ..
-set QPID_HOME=%cd%
-cd %CURRENT_DIR%
-:gotHome
-if exist "%QPID_HOME%\bin\%CMD%" goto okHome
-echo The QPID_HOME environment variable is not defined correctly
-echo This environment variable is needed to run this program
-goto end
-:okHome
-
-if not "%JAVA_HOME%" == "" goto gotJavaHome
-echo The JAVA_HOME environment variable is not defined
-echo This environment variable is needed to run this program
-goto exit
-:gotJavaHome
-if not exist "%JAVA_HOME%\bin\java.exe" goto noJavaHome
-goto okJavaHome
-:noJavaHome
-echo The JAVA_HOME environment variable is not defined correctly
-echo This environment variable is needed to run this program.
-goto exit
-:okJavaHome
-
-set CLIENT_TEST_CLASSES=%QPID_HOME%\lib\client-test-launch.jar
-
-echo on
-"%JAVA_HOME%\bin\java" -server -Xmx1024m -DQPID_HOME="%QPID_HOME%" -cp "%CLIENT_TEST_CLASSES%" %JAVACLASS%
-
-:end
-
-pause \ No newline at end of file
diff --git a/java/client/test/bin/IBM-Receiver.sh b/java/client/test/bin/IBM-Receiver.sh
deleted file mode 100755
index f50f0f744e..0000000000
--- a/java/client/test/bin/IBM-Receiver.sh
+++ /dev/null
@@ -1,22 +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.
-#
-
-export MSGSIZE=100
-qpid-run JMSPerfHarness -pc JNDI -ii com.sun.jndi.fscontext.RefFSContextFactory -iu file:///tmp/IBMPerfTestsJNDI/ -cf amq.ConnectionFactory -d amq.Queue -tc jms.r11.Receiver $* \ No newline at end of file
diff --git a/java/client/test/bin/IBM-Sender.bat b/java/client/test/bin/IBM-Sender.bat
deleted file mode 100644
index b8826322e5..0000000000
--- a/java/client/test/bin/IBM-Sender.bat
+++ /dev/null
@@ -1,62 +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
-
-@echo off
-REM Script to run the Qpid Java Broker
-
-set CMD="IBM-Sender.bat"
-set JAVACLASS=JMSPerfHarness -pc JNDI -ii com.sun.jndi.fscontext.RefFSContextFactory -iu file:/C:/temp/IBMPerfTestsJNDI/ -cf amq.ConnectionFactory -d amq.Queue -tc jms.r11.Sender -ms $MSGSIZE -mg 1000000 %*
-
-rem Guess QPID_HOME if not defined
-set CURRENT_DIR=%cd%
-if not "%QPID_HOME%" == "" goto gotHome
-set QPID_HOME=%CURRENT_DIR%
-echo %QPID_HOME%
-if exist "%QPID_HOME%\bin\%CMD%" goto okHome
-cd ..
-set QPID_HOME=%cd%
-cd %CURRENT_DIR%
-:gotHome
-if exist "%QPID_HOME%\bin\%CMD%" goto okHome
-echo The QPID_HOME environment variable is not defined correctly
-echo This environment variable is needed to run this program
-goto end
-:okHome
-
-if not "%JAVA_HOME%" == "" goto gotJavaHome
-echo The JAVA_HOME environment variable is not defined
-echo This environment variable is needed to run this program
-goto exit
-:gotJavaHome
-if not exist "%JAVA_HOME%\bin\java.exe" goto noJavaHome
-goto okJavaHome
-:noJavaHome
-echo The JAVA_HOME environment variable is not defined correctly
-echo This environment variable is needed to run this program.
-goto exit
-:okJavaHome
-
-set CLIENT_TEST_CLASSES=%QPID_HOME%\lib\client-test-launch.jar
-
-echo on
-"%JAVA_HOME%\bin\java" -server -Xmx1024m -DQPID_HOME="%QPID_HOME%" -cp "%CLIENT_TEST_CLASSES%" %JAVACLASS%
-
-:end
-
-pause \ No newline at end of file
diff --git a/java/client/test/bin/IBM-Sender.sh b/java/client/test/bin/IBM-Sender.sh
deleted file mode 100755
index b99429fd54..0000000000
--- a/java/client/test/bin/IBM-Sender.sh
+++ /dev/null
@@ -1,22 +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.
-#
-
-export MSGSIZE=100
-qpid-run JMSPerfHarness -pc JNDI -ii com.sun.jndi.fscontext.RefFSContextFactory -iu file:///tmp/IBMPerfTestsJNDI/ -cf amq.ConnectionFactory -d amq.Queue -tc jms.r11.Sender -ms $MSGSIZE -mg 1000000 $* \ No newline at end of file
diff --git a/java/client/test/bin/IBM-Subscriber.bat b/java/client/test/bin/IBM-Subscriber.bat
deleted file mode 100644
index 5245639eba..0000000000
--- a/java/client/test/bin/IBM-Subscriber.bat
+++ /dev/null
@@ -1,62 +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
-
-@echo off
-REM Script to run the Qpid Java Broker
-
-set CMD="IBM-Subscriber.bat"
-set JAVACLASS=JMSPerfHarness -pc JNDI -ii com.sun.jndi.fscontext.RefFSContextFactory -iu file:/C:/temp/IBMPerfTestsJNDI/ -cf amq.ConnectionFactory -d amq.Topic -db 1 -dx 4 -tc jms.r11.Subscriber -nt 4 %*
-
-rem Guess QPID_HOME if not defined
-set CURRENT_DIR=%cd%
-if not "%QPID_HOME%" == "" goto gotHome
-set QPID_HOME=%CURRENT_DIR%
-echo %QPID_HOME%
-if exist "%QPID_HOME%\bin\%CMD%" goto okHome
-cd ..
-set QPID_HOME=%cd%
-cd %CURRENT_DIR%
-:gotHome
-if exist "%QPID_HOME%\bin\%CMD%" goto okHome
-echo The QPID_HOME environment variable is not defined correctly
-echo This environment variable is needed to run this program
-goto end
-:okHome
-
-if not "%JAVA_HOME%" == "" goto gotJavaHome
-echo The JAVA_HOME environment variable is not defined
-echo This environment variable is needed to run this program
-goto exit
-:gotJavaHome
-if not exist "%JAVA_HOME%\bin\java.exe" goto noJavaHome
-goto okJavaHome
-:noJavaHome
-echo The JAVA_HOME environment variable is not defined correctly
-echo This environment variable is needed to run this program.
-goto exit
-:okJavaHome
-
-set CLIENT_TEST_CLASSES=%QPID_HOME%\lib\client-test-launch.jar
-
-echo on
-"%JAVA_HOME%\bin\java" -server -Xmx1024m -DQPID_HOME="%QPID_HOME%" -cp "%CLIENT_TEST_CLASSES%" %JAVACLASS%
-
-:end
-
-pause \ No newline at end of file
diff --git a/java/client/test/bin/IBM-Subscriber.sh b/java/client/test/bin/IBM-Subscriber.sh
deleted file mode 100755
index 43550100be..0000000000
--- a/java/client/test/bin/IBM-Subscriber.sh
+++ /dev/null
@@ -1,22 +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.
-#
-
-export MSGSIZE=100
-qpid-run JMSPerfHarness -pc JNDI -ii com.sun.jndi.fscontext.RefFSContextFactory -iu file:///tmp/IBMPerfTestsJNDI/ -cf amq.ConnectionFactory -d amq.Topic -db 1 -dx 4 -tc jms.r11.Subscriber -nt 4 $* \ No newline at end of file
diff --git a/java/client/test/bin/headersListener.sh b/java/client/test/bin/headersListener.sh
deleted file mode 100755
index 81930b7043..0000000000
--- a/java/client/test/bin/headersListener.sh
+++ /dev/null
@@ -1,22 +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.
-#
-
-
-. qpid-run -Damqj.logging.level="INFO" org.apache.qpid.headers.Listener $*
diff --git a/java/client/test/bin/headersListenerGroup.sh b/java/client/test/bin/headersListenerGroup.sh
deleted file mode 100755
index e1cc05cfd2..0000000000
--- a/java/client/test/bin/headersListenerGroup.sh
+++ /dev/null
@@ -1,25 +0,0 @@
-#!/bin/sh
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-#
-
-
-for i; do
- ./headersListener.sh -host 10.0.0.1 -port 5672 >$i.out 2>$i.err &
- echo $! > $i.pid
-done;
diff --git a/java/client/test/bin/headersPublisher.sh b/java/client/test/bin/headersPublisher.sh
deleted file mode 100755
index fd9fd26416..0000000000
--- a/java/client/test/bin/headersPublisher.sh
+++ /dev/null
@@ -1,22 +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.
-#
-
-
-. qpid-run -Damqj.logging.level="INFO" org.apache.qpid.headers.Publisher $*
diff --git a/java/client/test/bin/run_many.sh b/java/client/test/bin/run_many.sh
deleted file mode 100755
index cca2ffec21..0000000000
--- a/java/client/test/bin/run_many.sh
+++ /dev/null
@@ -1,30 +0,0 @@
-#!/bin/sh
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-#
-
-
-# args:
-# <number of processes to start>
-# <name of run>
-# <command ro run>
-
-for i in `seq 1 $1`; do
- $3 >$2.$i.out 2>>$2.err &
- echo $! > $2.$i.pid
-done;
diff --git a/java/client/test/bin/serviceProvidingClient.sh b/java/client/test/bin/serviceProvidingClient.sh
deleted file mode 100755
index cbcf5a0f4b..0000000000
--- a/java/client/test/bin/serviceProvidingClient.sh
+++ /dev/null
@@ -1,24 +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.
-#
-
-PROFILE=$1
-shift
-# XXX -Xms1024m -XX:NewSize=300m
-. qpid-run org.apache.qpid.requestreply1.ServiceProvidingClient $1 guest guest /test serviceQ
diff --git a/java/client/test/bin/serviceRequestingClient.sh b/java/client/test/bin/serviceRequestingClient.sh
deleted file mode 100755
index 213f44c00b..0000000000
--- a/java/client/test/bin/serviceRequestingClient.sh
+++ /dev/null
@@ -1,27 +0,0 @@
-#!/bin/bash
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-#
-
-PROFILE=$1
-shift
-thehosts=$1
-shift
-echo $thehosts
-# XXX -Xms1024m -XX:NewSize=300m
-. qpid-run -Damqj.logging.level="INFO" org.apache.qpid.requestreply1.ServiceRequestingClient $thehosts guest guest /test serviceQ "$@"
diff --git a/java/client/test/bin/testService.sh b/java/client/test/bin/testService.sh
deleted file mode 100755
index 20161c3abf..0000000000
--- a/java/client/test/bin/testService.sh
+++ /dev/null
@@ -1,22 +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.
-#
-
-
-. qpid-run org.apache.qpid.requestreply1.TestService 192.168.55.63 5672 foo x x
diff --git a/java/client/test/bin/topicListener.sh b/java/client/test/bin/topicListener.sh
deleted file mode 100755
index ac0cb63c91..0000000000
--- a/java/client/test/bin/topicListener.sh
+++ /dev/null
@@ -1,23 +0,0 @@
-#!/bin/bash
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-#
-
-
-# XXX -Xmx512m -Xms512m -XX:NewSize=150m
-. qpid-run -Damqj.logging.level="INFO" org.apache.qpid.topic.Listener $*
diff --git a/java/client/test/bin/topicPublisher.sh b/java/client/test/bin/topicPublisher.sh
deleted file mode 100755
index e35c131fe8..0000000000
--- a/java/client/test/bin/topicPublisher.sh
+++ /dev/null
@@ -1,22 +0,0 @@
-#!/bin/bash
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-#
-
-# XXX -Xmx512m -Xms512m -XX:NewSize=150m
-. qpid-run -Damqj.logging.level="INFO" org.apache.qpid.topic.Publisher $*
diff --git a/java/client/test/etc/ApacheDS.properties b/java/client/test/etc/ApacheDS.properties
deleted file mode 100644
index 6c5cb4cec4..0000000000
--- a/java/client/test/etc/ApacheDS.properties
+++ /dev/null
@@ -1,24 +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.
-#
-# Standard JNDI properties
-java.naming.factory.initial=com.sun.jndi.ldap.LdapCtxFactory
-java.naming.provider.url=ldap://localhost:389/ou=system
-java.naming.security.authentication=simple
-java.naming.security.principal=uid=admin,ou=system
-java.naming.security.credentials=secret
diff --git a/java/client/test/example_build.xml b/java/client/test/example_build.xml
deleted file mode 100644
index 329c12982c..0000000000
--- a/java/client/test/example_build.xml
+++ /dev/null
@@ -1,104 +0,0 @@
-<?xml version="1.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.
- -
- -->
-
-<!-- example Blaze Component Java build file -->
-
-<project name="example-client" default="jar" basedir=".">
- <property name="lib" value="${basedir}/lib"/>
- <property name="common.lib" value="${basedir}/../common/lib"/>
- <property name="example.dir" value="${basedir}"/>
- <property name="example.src" value="${example.dir}/src"/>
- <property name="example.lib" value="${example.dir}/lib"/>
- <property name="example.tests" value="${example.dir}/test"/>
- <property name="example.classes" value="${example.dir}/classes"/>
- <property name="dist" value="${basedir}/dist"/>
- <property name="dam.dist" value="${basedir}/damPackage"/>
-
- <!-- Setup details -->
- <target name="init">
- <tstamp>
- <format property="release" pattern="-dMMMyy" locale="en" timezone="GMT"/>
- </tstamp>
- <mkdir dir="${example.classes}"/>
- </target>
-
- <path id="example.classpath">
- <fileset dir="${common}/lib">
- <include name="**/*.jar"/>
- </fileset>
- <pathelement path="${example.classes}"/>
- </path>
-
- <!-- Remove all built files -->
- <target name="clean" depends="init">
- <delete dir="${example.classes}"/>
- </target>
-
- <path id="example_amq.classpath">
- <fileset dir="${basedir}/lib">
- <include name="**/*.jar"/>
- </fileset>
- <fileset dir="${example.lib}">
- <include name="**/*.jar"/>
- </fileset>
- <pathelement path="${example.classes}"/>
-
- </path>
-
- <!-- Compile Java -->
- <target name="compile" depends="init">
- <javac destdir="${example.classes}" debug="on" includeantruntime="false">
- <classpath refid="example_amq.classpath"/>
- <src path="${example.src}"/>
- <exclude name="**/Test*.java"/>
- </javac>
-
- <copy todir="${example.classes}">
- <!-- copy any non java src files into the build tree, e.g. log4j.properties -->
- <fileset dir="${example.src}">
- <exclude name="**/*.java"/>
- <exclude name="**/package.html"/>
- </fileset>
- </copy>
- </target>
-
- <!-- Compile and build jar archive -->
- <target name="dist" depends="compile">
- <mkdir dir="${dist}"/>
- <jar basedir="${example.classes}" jarfile="${dist}/example_amq.jar"/>
- </target>
-
- <!-- Create release zip and tar -->
- <target name="release" depends="dist" description="Create a release package">
-
- <zip destfile="${dist}/example_client.zip">
- <zipfileset prefix="lib" file="${dist}/example_amq.jar" />
- </zip>
-
- <tar destfile="${dist}/example_client.tar.gz" compression="gzip">
- <tarfileset prefix="lib" file="${dist}/example_amq.jar" />
- </tar>
- </target>
-
-
-
-</project>
diff --git a/java/common.xml b/java/common.xml
deleted file mode 100644
index 1125a3230c..0000000000
--- a/java/common.xml
+++ /dev/null
@@ -1,350 +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.
- -
- -->
-<project name="common">
-
- <dirname property="project.root" file="${ant.file.common}"/>
-
- <property name="project.name" value="qpid"/>
- <property name="project.version" value="0.11"/>
- <property name="project.url" value="http://qpid.apache.org"/>
- <property name="project.groupid" value="org.apache.qpid"/>
- <property name="project.namever" value="${project.name}-${project.version}"/>
-
- <property name="resources" location="${project.root}/resources"/>
- <property name="test.profiles" location="${project.root}/test-profiles"/>
- <property name="build" location="${project.root}/build"/>
- <property name="build.scratch" location="${build}/scratch"/>
- <property name="build.bin" location="${build}/bin"/>
- <property name="build.etc" location="${build}/etc"/>
- <property name="build.lib" location="${build}/lib"/>
- <property name="build.api" location="${build}/api"/>
- <property name="build.test.api" location="${build}/test-api"/>
- <property name="build.results" location="${build}/results"/>
- <property name="build.failed" location="${build.results}/FAILED"/>
- <property name="build.report" location="${build}/report"/>
- <property name="build.release" location="${build}/release"/>
- <property name="build.release.prepare" location="${build.release}/prepare"/>
- <property name="build.data" location="${build.scratch}/data"/>
- <property name="build.plugins" location="${build}/lib/plugins"/>
- <property name="build.coveragereport" location="${build}/coverage"/>
- <property name="build.findbugs" location="${build}/findbugs"/>
-
- <property name="java.target" value="1.5"/>
- <property name="java.source" value="1.5"/>
-
- <property name="release" location="${project.root}/release"/>
-
- <property name="tasks" location="${project.root}/tasks"/>
- <property name="tasks.classes" location="${tasks}/classes"/>
- <property name="tasks.src" location="${tasks}/src"/>
-
- <property name="qpid.home" location="${project.root}/build"/>
- <property name="qpid.work" location="${qpid.home}/work"/>
-
- <property name="javac.compiler.args" value=""/>
-
- <property name="cobertura.dir" value="${project.root}/lib/cobertura" />
- <property name="mllib.dir" value="${project.root}/../python" />
- <property name="findbugs.dir" value="${project.root}/lib/findbugs" />
-
- <!-- properties used to control Ant Eclipse for Eclipse classpath/project files etc -->
- <property name="eclipse.updatealways" value="false"/>
- <property name="eclipse.compilercompliance" value="5.0"/>
- <property name="eclipse.container" value="JVM 1.5"/>
-
- <path id="cobertura.classpath">
- <fileset dir="${cobertura.dir}">
- <include name="cobertura.jar" />
- <include name="lib/**/*.jar" />
- </fileset>
- </path>
-
- <property name="maven.local.repo" value="${build.scratch}/maven-local-repo"/>
- <property name="maven.settings.xml" value="${project.root}/maven-settings.xml"/>
- <property name="maven.unique.version" value="false"/>
- <property name="maven.snapshot" value="true"/>
- <condition property="maven.version.suffix" value="" else="-SNAPSHOT">
- <isfalse value="${maven.snapshot}"/>
- </condition>
-
- <macrodef name="indirect">
- <attribute name="name"/>
- <attribute name="variable"/>
- <sequential>
- <property name="@{name}" value="${@{variable}}"/>
- </sequential>
- </macrodef>
-
- <macrodef name="echo-path">
- <attribute name="refid"/>
- <sequential>
- <property name="@{refid}" refid="@{refid}"/>
- <echo message="@{refid} = ${@{refid}}"/>
- <pathconvert property="@{refid}.pretty"
- refid="@{refid}"
- pathsep="${line.separator} |-- "/>
- <echo message="@{refid}.pretty =${line.separator} |-- ${@{refid}.pretty}"/>
- </sequential>
- </macrodef>
-
- <macrodef name="echo-prop">
- <attribute name="name"/>
- <sequential>
- <echo message="@{name} = ${@{name}}"/>
- </sequential>
- </macrodef>
-
- <macrodef name="findSubProjects">
- <attribute name="dir"/>
- <attribute name="name"/>
- <attribute name="excludes" default=""/>
-
- <sequential>
- <dirset id="@{dir}.refid" dir="@{dir}" excludes="@{excludes}">
- <present targetdir="@{dir}">
- <mapper type="glob" from="*" to="*/build.xml" />
- </present>
- </dirset>
-
- <pathconvert property="@{name}"
- refid="@{dir}.refid"
- pathsep=" ">
- <map from="${project.root}/" to=""/>
- </pathconvert>
- </sequential>
- </macrodef>
-
-
-
- <macrodef name="jython">
- <attribute name="path"/>
- <element name="args"/>
- <sequential>
- <java jar="${project.root}/lib/jython-2.5.0.jar" fork="true" failonerror="true">
- <arg value="-Dpython.path=@{path}"/>
- <args/>
- </java>
- </sequential>
- </macrodef>
-
- <mkdir dir="${tasks.classes}"/>
- <javac source="${java.source}" target="${java.target}" srcdir="${tasks.src}" destdir="${tasks.classes}" classpath="${java.class.path}" includeantruntime="false">
- <compilerarg line="${javac.compiler.args}"/>
- </javac>
-
-
- <typedef name="propertymapper" classname="org.apache.qpid.tasks.PropertyMapper"
- classpath="${tasks.classes}"/>
-
- <taskdef name="map" classname="org.apache.qpid.tasks.Map"
- classpath="${tasks.classes}"/>
- <taskdef name="foreach" classname="org.apache.qpid.tasks.Foreach"
- classpath="${tasks.classes}"/>
-
- <macrodef name="copylist">
- <attribute name="todir"/>
- <attribute name="dir"/>
- <attribute name="files"/>
- <sequential>
- <foreach property="file" list="@{files}">
- <copy todir="@{todir}" flatten="true">
- <fileset dir="@{dir}" includes="${file}"/>
- </copy>
- </foreach>
- </sequential>
- </macrodef>
-
- <target name="clean-tasks">
- <delete dir="${tasks.classes}"/>
- </target>
-
- <target name="clean-results">
- <delete dir="${build.results}"/>
- </target>
-
- <target name="report" description="generate test report">
- <delete dir="${build.report}"/>
- <mkdir dir="${build.report}"/>
- <junitreport todir="${build.report}">
- <fileset dir="${build.results}">
- <include name="**/TEST-*.xml"/>
- </fileset>
- <report todir="${build.report}"/>
- </junitreport>
- </target>
-
- <target name="cobertura-init">
- <taskdef classpathref="cobertura.classpath" resource="tasks.properties" />
- </target>
-
- <target name="findbugs-init">
- <available file="${findbugs.dir}/findbugs-ant.jar" property="findbugs-ant.jar.present"/>
- <fail unless="findbugs-ant.jar.present" message="Please follow the instructions at ${findbugs.dir}/README.txt to configure FindBugs"/>
-
- <taskdef name="findbugs" classname="edu.umd.cs.findbugs.anttask.FindBugsTask" classpath="${findbugs.dir}/findbugs-ant.jar"/>
- </target>
-
- <target name="help" description="display detailed build documentation">
- <echo>
- ant build
-
- This target compiles all sources, creates java archives, and
- copies scripts and configurations into the build directory:
-
- ${build}
-
- The build directory is treated as a live distro which this target
- will incrementally update. Developers can put the build/bin
- directory into their path in order to run any scripts or code
- directly out of the live build:
-
- ${build.bin}
-
- ant test [ -Dtest=&lt;pattern&gt; ] [-Dprofile=&lt;profile&gt;] [ report ]
-
- Execute unit tests and place the output in the build results
- directory:
-
- ${build.results}
-
- All test output will be redirected to a file of the form:
-
- TEST-&lt;class&gt;.txt
-
- The same output is available using an xml file format:
-
- TEST-&lt;class&gt;.xml
-
- The test system property may be used to restrict the number of
- tests run by a given invocation of the ant test target. The
- following command will run just the MongooseTest test case:
-
- ant test -Dtest=MongooseTest
-
- In addition, patterns may be used to specify more than one test.
- The following command will run both the MongooseTest and GooseTest
- test cases:
-
- ant test -Dtest=*ooseTest
-
- If no test property is specified, the "ant test" target will
- default to running all available tests for the project or module
- depending on the current working directory.
-
- Test Reports
-
- It can be useful to append the report target in order to
- generate an html summary of the tests that were just run. The
- following command will run both the MongooseTest and GooseTest
- test cases and generate an html summary of the results:
-
- ant test -Dtest=*ooseTest report
-
- See the documentation for the "ant report" target for more details
- on the generated report.
-
- Test Profiles
-
- There are a number of profiles defined for running the test suite.
- These test profiles define how the test should be run. If the test
- profile is not specified then 'default.testprofile' is utilised.
- This runs the system tests against the Java InVM broker. Additional
- test profiles exists as follows:
-
- cpp : Runs against the built cpp tree broker.
-
- ant report
-
- The report target will generate an html summary of the current
- test results into the report directory:
-
- ${build.report}
-
- The report target will operate on all results currently in the
- build results directory. Results are not cleared unless the clean
- target is used. This means that several consecutive test runs can
- be summarized into a single report. The following commands will
- produce a report summarizing both the MongooseTest and GooseTest
- test cases:
-
- ant test -Dtest=MongooseTest
- ...
- ant test -Dtest=GooseTest
- ...
- ant report
-
- ant release
-
- The release target generates binary distribution archives and
- places them into the release directory:
-
- ${release}
-
- ant release-bin
-
- The release-bin target generates binary distribution archives for
- modules that have a specific binary package configured.
- To enable for other modules create a target "release-bin" that
- depends on target "release-bin-tasks". The output is placed in:
-
- ${module.release}
-
- ant clean
-
- The clean target removes build artifacts. When invoked from the
- project root this target will remove the entire project build and
- release directories:
-
- ${build}
- and
- ${release}
- and
- ${module.release}
-
- When invoked from a specific module, the clean target will delete
- that modules build root from underneath the project build root:
-
- ${build}/&lt;module&gt;
-
- ant clean-results
-
- The clean-results target removes all test output from the test
- results directory:
-
- ${build.results}
-
- ant eclipse
-
- Generates project and classpath files for the Eclispe IDE. Requires that
- the Ant Eclipse task (http://ant-eclipse.sourceforge.net/) has been installed
- in $ANT_HOME/lib.
-
- The following system properties will be passed to the task. These can be usefully
- overridden from the command line.
-
- eclipse.updatealways - forces Eclipse files to be regenerated even if they are newer then the build.xml (default ${eclipse.updatealways}).
- eclipse.container - controls the Eclipse container (default ${eclipse.container}).
- eclipse.compilercompliance" - controls the Eclipse compiler compliance (default ${eclipse.compilercompliance}).
-
- </echo>
- </target>
-
-</project>
diff --git a/java/common/Composite.tpl b/java/common/Composite.tpl
deleted file mode 100644
index 350dd893c8..0000000000
--- a/java/common/Composite.tpl
+++ /dev/null
@@ -1,350 +0,0 @@
-package org.apache.qpid.transport;
-/*
- *
- * 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 java.nio.ByteBuffer;
-import java.util.ArrayList;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.UUID;
-
-import org.apache.qpid.transport.codec.Decoder;
-import org.apache.qpid.transport.codec.Encodable;
-import org.apache.qpid.transport.codec.Encoder;
-
-import org.apache.qpid.transport.network.Frame;
-
-import org.apache.qpid.util.Strings;
-
-
-${
-from genutil import *
-
-cls = klass(type)["@name"]
-
-segments = type["segments"]
-
-connectioncontrol="false"
-
-if type.name in ("control", "command"):
- base = "Method"
- size = 0
- pack = 2
- if segments:
- payload = "true"
- else:
- payload = "false"
- if type.name == "control" and cls == "connection":
- track = "Frame.L1"
- connectioncontrol="true"
- elif cls == "session" and type["@name"] in ("attach", "attached", "detach", "detached"):
- track = "Frame.L2"
- elif type.name == "command":
- track = "Frame.L4"
- else:
- track = "Frame.L3"
-else:
- base = "Struct"
- size = type["@size"]
- pack = num(type["@pack"])
- payload = "false"
- track = "-1"
-
-PACK_TYPES = {
- 1: "byte",
- 2: "short",
- 4: "int"
-}
-
-typecode = code(type)
-}
-
-public final class $name extends $base {
-
- public static final int TYPE = $typecode;
-
- public final int getStructType() {
- return TYPE;
- }
-
- public final int getSizeWidth() {
- return $size;
- }
-
- public final int getPackWidth() {
- return $pack;
- }
-
- public final boolean hasPayload() {
- return $payload;
- }
-
- public final byte getEncodedTrack() {
- return $track;
- }
-
- public final boolean isConnectionControl()
- {
- return $connectioncontrol;
- }
-
-${
-
-if pack > 0:
- out(" private $(PACK_TYPES[pack]) packing_flags = 0;\n");
-
-fields = get_fields(type)
-params = get_parameters(type, fields)
-options = get_options(fields)
-
-for f in fields:
- if not f.empty:
- out(" private $(f.type) $(f.name);\n")
-
-if segments:
- out(" private Header header;\n")
- out(" private ByteBuffer body;\n")
-}
-
-${
-if fields:
- out(" public $name() {}\n")
-}
-
- public $name($(", ".join(params))) {
-${
-for f in fields:
- if f.option: continue
- if f.ref_type != f.type:
- out(" $(f.set)($(f.name));\n")
- else:
- out(" if($(f.name) != null) {\n")
- out(" $(f.set)($(f.name));\n")
- out(" }\n")
-
-if segments:
- out(" setHeader(header);\n")
- out(" setBody(body);\n")
-
-if options or base == "Method":
- out("""
- for (int i=0; i < _options.length; i++) {
- switch (_options[i]) {
-""")
-
- for f in options:
- out(" case $(f.option): packing_flags |= $(f.flag_mask(pack)); break;\n")
-
- if base == "Method":
- out(""" case SYNC: this.setSync(true); break;
- case BATCH: this.setBatch(true); break;
- case UNRELIABLE: this.setUnreliable(true); break;
-""")
- out(""" case NONE: break;
- default: throw new IllegalArgumentException("invalid option: " + _options[i]);
- }
- }
-""")
-}
- }
-
-${
-
-if base == "Method":
- out(""" public <C> void dispatch(C context, MethodDelegate<C> delegate) {
- delegate.$(dromedary(name))(context, this);
- }""")
-}
-
-${
-for f in fields:
- if pack > 0:
- out("""
- public final boolean $(f.has)() {
- return (packing_flags & $(f.flag_mask(pack))) != 0;
- }
-
- public final $name $(f.clear)() {
- packing_flags &= ~$(f.flag_mask(pack));
-${
-if not f.empty:
- out(" this.$(f.name) = $(f.default);")
-}
- this.dirty = true;
- return this;
- }
-""")
-
- out("""
- public final $(f.type) $(f.get)() {
-${
-if f.empty:
- out(" return $(f.has)();")
-else:
- out(" return $(f.name);")
-}
- }
-
- public final $name $(f.set)($(f.type) value) {
-${
-if not f.empty:
- out(" this.$(f.name) = value;")
-}
-${
-if pack > 0:
- if f.empty:
- out(" if (value)\\n")
- out(" packing_flags |= $(f.flag_mask(pack));\\n")
- out(" else\\n")
- out(" packing_flags &= ~$(f.flag_mask(pack));")
- else:
- out(" packing_flags |= $(f.flag_mask(pack));")
-}
- this.dirty = true;
- return this;
- }
-
- public final $name $(f.name)($(f.type) value) {
- return $(f.set)(value);
- }
-""")
-}
-
-${
-if segments:
- out(""" public final Header getHeader() {
- return this.header;
- }
-
- public final void setHeader(Header header) {
- this.header = header;
- }
-
- public final $name header(Header header) {
- setHeader(header);
- return this;
- }
-
- public final ByteBuffer getBody() {
- if (this.body == null)
- {
- return null;
- }
- else
- {
- return this.body.slice();
- }
- }
-
- public final void setBody(ByteBuffer body) {
- this.body = body;
- }
-
- public final $name body(ByteBuffer body)
- {
- setBody(body);
- return this;
- }
-
- public final byte[] getBodyBytes() {
- ByteBuffer buf = getBody();
- byte[] bytes = new byte[buf.remaining()];
- buf.get(bytes);
- return bytes;
- }
-
- public final void setBody(byte[] body)
- {
- setBody(ByteBuffer.wrap(body));
- }
-
- public final String getBodyString() {
- return Strings.fromUTF8(getBodyBytes());
- }
-
- public final void setBody(String body) {
- setBody(Strings.toUTF8(body));
- }
-""")
-}
-
- public void write(Encoder enc)
- {
-${
-if pack > 0:
- out(" enc.writeUint%s(packing_flags);\n" % (pack*8));
-
-for f in fields:
- if f.empty:
- continue
- if pack > 0:
- out(" if ((packing_flags & $(f.flag_mask(pack))) != 0)\n ")
- pre = ""
- post = ""
- if f.type_node.name == "struct":
- pre = "%s.TYPE, " % cname(f.type_node)
- elif f.type_node.name == "domain":
- post = ".getValue()"
- out(" enc.write$(f.coder)($(pre)this.$(f.name)$(post));\n")
-}
- }
-
- public void read(Decoder dec)
- {
-${
-if pack > 0:
- out(" packing_flags = ($(PACK_TYPES[pack])) dec.readUint%s();\n" % (pack*8));
-
-for f in fields:
- if f.empty:
- continue
- if pack > 0:
- out(" if ((packing_flags & $(f.flag_mask(pack))) != 0)\n ")
- pre = ""
- post = ""
- arg = ""
- if f.type_node.name == "struct":
- pre = "(%s)" % cname(f.type_node)
- arg = "%s.TYPE" % cname(f.type_node)
- elif f.type_node.name == "domain":
- pre = "%s.get(" % cname(f.type_node)
- post = ")"
- out(" this.$(f.name) = $(pre)dec.read$(f.coder)($(arg))$(post);\n")
-}
- }
-
- public Map<String,Object> getFields()
- {
- Map<String,Object> result = new LinkedHashMap<String,Object>();
-
-${
-for f in fields:
- if pack > 0:
- out(" if ((packing_flags & $(f.flag_mask(pack))) != 0)\n ")
- out(' result.put("$(f.name)", $(f.get)());\n')
-}
-
- return result;
- }
-
-}
diff --git a/java/common/Constant.tpl b/java/common/Constant.tpl
deleted file mode 100644
index da4233c847..0000000000
--- a/java/common/Constant.tpl
+++ /dev/null
@@ -1,35 +0,0 @@
-package org.apache.qpid.transport;
-/*
- *
- * 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.
- *
- */
-
-
-${from genutil import *}
-
-public interface Constant
-{
-${
-constants = spec.query["amqp/constant"]
-
-for c in constants:
- name = scream(c["@name"])
- value = c["@value"]
- out(" public static final int $name = $value;\n")
-}}
diff --git a/java/common/Enum.tpl b/java/common/Enum.tpl
deleted file mode 100644
index 0835d34a20..0000000000
--- a/java/common/Enum.tpl
+++ /dev/null
@@ -1,57 +0,0 @@
-package org.apache.qpid.transport;
-/*
- *
- * 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 enum $name {
-${
-from genutil import *
-
-vtype = jtype(resolve_type(type))
-
-choices = [(scream(ch["@name"]), "(%s) %s" % (vtype, ch["@value"]))
- for ch in type.query["enum/choice"]]
-}
- $(",\n ".join(["%s(%s)" % ch for ch in choices]));
-
- private final $vtype value;
-
- $name($vtype value)
- {
- this.value = value;
- }
-
- public $vtype getValue()
- {
- return value;
- }
-
- public static $name get($vtype value)
- {
- switch (value)
- {
-${
-for ch, value in choices:
- out(' case $value: return $ch;\n')
-} default: throw new IllegalArgumentException("no such value: " + value);
- }
- }
-}
diff --git a/java/common/Invoker.tpl b/java/common/Invoker.tpl
deleted file mode 100644
index 2eed43ad28..0000000000
--- a/java/common/Invoker.tpl
+++ /dev/null
@@ -1,73 +0,0 @@
-package org.apache.qpid.transport;
-/*
- *
- * 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 java.nio.ByteBuffer;
-import java.util.List;
-import java.util.Map;
-import java.util.UUID;
-
-public abstract class $(invoker) {
-${
-from genutil import *
-
-results = False
-
-for c in composites:
- name = cname(c)
- fields = get_fields(c)
- params = get_parameters(c, fields)
- args = get_arguments(c, fields)
- result = c["result"]
- if result:
- results = True
- if not result["@type"]:
- rname = cname(result["struct"])
- else:
- rname = cname(result, "@type")
- jresult = "Future<%s>" % rname
- jreturn = "return "
- jclass = ", %s.class" % rname
- else:
- jresult = "void"
- jreturn = ""
- jclass = ""
-
- if c.name == "command":
- access = "public "
- else:
- access = ""
-
- out("""
- $(access)final $jresult $(dromedary(name))($(", ".join(params))) {
- $(jreturn)invoke(new $name($(", ".join(args)))$jclass);
- }
-""")
-}
- protected abstract void invoke(Method method);
-${
-if results:
- out("""
- protected abstract <T> Future<T> invoke(Method method, Class<T> resultClass);
-""")
-}
-}
diff --git a/java/common/MethodDelegate.tpl b/java/common/MethodDelegate.tpl
deleted file mode 100644
index 27e20a7ef2..0000000000
--- a/java/common/MethodDelegate.tpl
+++ /dev/null
@@ -1,37 +0,0 @@
-package org.apache.qpid.transport;
-/*
- *
- * 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 abstract class MethodDelegate<C> {
-
- public abstract void handle(C context, Method method);
-${
-from genutil import *
-
-for c in composites:
- name = cname(c)
- out("""
- public void $(dromedary(name))(C context, $name method) {
- handle(context, method);
- }""")
-}
-}
diff --git a/java/common/Option.tpl b/java/common/Option.tpl
deleted file mode 100644
index c22b35b999..0000000000
--- a/java/common/Option.tpl
+++ /dev/null
@@ -1,42 +0,0 @@
-package org.apache.qpid.transport;
-/*
- *
- * 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 enum Option {
-
-${
-from genutil import *
-
-options = {}
-
-for c in composites:
- for f in c.query["field"]:
- t = resolve_type(f)
- if t["@name"] == "bit":
- option = scream(f["@name"])
- if not options.has_key(option):
- options[option] = None
- out(" $option,\n")}
- BATCH,
- UNRELIABLE,
- NONE
-}
diff --git a/java/common/StructFactory.tpl b/java/common/StructFactory.tpl
deleted file mode 100644
index 09c669f74e..0000000000
--- a/java/common/StructFactory.tpl
+++ /dev/null
@@ -1,60 +0,0 @@
-package org.apache.qpid.transport;
-/*
- *
- * 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.
- *
- */
-
-
-class StructFactory {
-
- public static Struct create(int type)
- {
- switch (type)
- {
-${
-from genutil import *
-
-fragment = """ case $name.TYPE:
- return new $name();
-"""
-
-for c in composites:
- name = cname(c)
- if c.name == "struct":
- out(fragment)
-} default:
- throw new IllegalArgumentException("type: " + type);
- }
- }
-
- public static Struct createInstruction(int type)
- {
- switch (type)
- {
-${
-for c in composites:
- name = cname(c)
- if c.name in ("command", "control"):
- out(fragment)
-} default:
- throw new IllegalArgumentException("type: " + type);
- }
- }
-
-}
diff --git a/java/common/Type.tpl b/java/common/Type.tpl
deleted file mode 100644
index 7f9cfee268..0000000000
--- a/java/common/Type.tpl
+++ /dev/null
@@ -1,84 +0,0 @@
-package org.apache.qpid.transport;
-/*
- *
- * 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.
- *
- */
-
-
-${from genutil import *}
-
-public enum Type
-{
-
-${
-types = spec.query["amqp/type"] + spec.query["amqp/class/type"]
-codes = {}
-first = True
-for t in types:
- code = t["@code"]
- fix_width = t["@fixed-width"]
- var_width = t["@variable-width"]
-
- if code is None:
- continue
-
- if fix_width is None:
- width = var_width
- fixed = "false"
- else:
- width = fix_width
- fixed = "true"
-
- name = scream(t["@name"])
- codes[code] = name
-
- if first:
- first = False
- else:
- out(",\n")
-
- out(" $name((byte) $code, $width, $fixed)")
-};
-
- public byte code;
- public int width;
- public boolean fixed;
-
- Type(byte code, int width, boolean fixed)
- {
- this.code = code;
- this.width = width;
- this.fixed = fixed;
- }
-
- public static Type get(byte code)
- {
- switch (code)
- {
-${
-keys = list(codes.keys())
-keys.sort()
-
-for code in keys:
- out(" case (byte) $code: return $(codes[code]);\n")
-}
- default: return null;
- }
- }
-}
diff --git a/java/common/bin/qpid-jaddr b/java/common/bin/qpid-jaddr
deleted file mode 100755
index d456171bf1..0000000000
--- a/java/common/bin/qpid-jaddr
+++ /dev/null
@@ -1,33 +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.
-#
-
-if [ -z "$QPID_HOME" ]; then
- export QPID_HOME=$(dirname $(dirname $(readlink -f $0)))
- export PATH=${PATH}:${QPID_HOME}/bin
-fi
-
-# Set classpath to include Qpid jar with all required jars in manifest
-QPID_LIBS=$QPID_HOME/lib/qpid-all.jar
-
-# Set other variables used by the qpid-run script before calling
-export JAVA=java \
- QPID_CLASSPATH=$QPID_LIBS
-
-. qpid-run org.apache.qpid.messaging.util.JAddr "$@"
diff --git a/java/common/bin/qpid-run b/java/common/bin/qpid-run
deleted file mode 100755
index 15d88992df..0000000000
--- a/java/common/bin/qpid-run
+++ /dev/null
@@ -1,259 +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.
-#
-
-# Test if we're running on cygwin.
-cygwin=false
-if [[ "$(uname -a | fgrep Cygwin)" != "" ]]; then
- cygwin=true
-fi
-
-die() {
- if [[ $1 = -usage ]]; then
- shift
- usage=true
- else
- usage=false
- fi
- echo "$@"
- $usage && echo
- $usage && usage
- exit 1
-}
-
-OFF=0
-WARN=1
-INFO=2
-
-if [ -z "$QPID_RUN_LOG" ]; then
- QPID_RUN_LOG=$OFF
-fi
-
-log() {
- if [ "$1" -le "$QPID_RUN_LOG" ]; then
- shift
- echo "$@"
- fi
-}
-
-if [ -z $AMQJ_LOGGING_LEVEL ]; then
- export AMQJ_LOGGING_LEVEL=info
-fi
-
-if [ -z "$QPID_HOME" ]; then
- export QPID_HOME=$(dirname $(dirname $(readlink -f $0)))
- export PATH=${PATH}:${QPID_HOME}/bin
-fi
-
-if [ -z "$QPID_WORK" ]; then
- log $INFO Setting QPID_WORK to $HOME as default
- QPID_WORK=$HOME
-fi
-
-if [ -z "$JAVA" ]; then
- JAVA=java
-fi
-
-if $cygwin; then
- QPID_HOME=$(cygpath -w $QPID_HOME)
- QPID_WORK=$(cygpath -w $QPID_WORK)
-fi
-
-#Set the default system properties that we'll use now that they have
-#all been initialised
-SYSTEM_PROPS="-Damqj.logging.level=$AMQJ_LOGGING_LEVEL -DQPID_HOME=$QPID_HOME -DQPID_WORK=$QPID_WORK"
-
-#If logprefix or logsuffix set to use PID make that happen
-#Otherwise just pass the value through for these props
-#Using X character to avoid probs with empty strings
-if [ -n "$QPID_LOG_PREFIX" ]; then
- if [ "X$QPID_LOG_PREFIX" = "XPID" ]; then
- log $INFO Using pid in qpid log name prefix
- LOG_PREFIX=" -Dlogprefix=$$"
- else
- log $INFO Using qpid logprefix property
- LOG_PREFIX=" -Dlogprefix=$QPID_LOG_PREFIX"
- fi
- SYSTEM_PROPS="${SYSTEM_PROPS} ${LOG_PREFIX}"
-fi
-
-if [ -n "$QPID_LOG_SUFFIX" ]; then
- if [ "X$QPID_LOG_SUFFIX" = "XPID" ]; then
- log $INFO Using pid in qpid log name suffix
- LOG_SUFFIX=" -Dlogsuffix=$$"
- else
- log $INFO Using qpig logsuffix property
- LOG_SUFFIX=" -Dlogsuffix=$QPID_LOG_SUFFIX"
- fi
- SYSTEM_PROPS="${SYSTEM_PROPS} ${LOG_SUFFIX}"
-fi
-
-log $INFO System Properties set to $SYSTEM_PROPS
-log $INFO QPID_OPTS set to $QPID_OPTS
-
-program=$(basename $0)
-sourced=${BASH_SOURCE[0]}
-if [[ -z ${sourced:-''} ]]; then
- sourced=$(which qpid-run) || ${QPID_HOME}/bin/qpid-run
-fi
-
-usage() {
- echo Usage: $program ... "[-run:<option>]" ...
- echo
- echo Options:
- egrep -B 1 "^\s*#USAGE: " ${sourced} |\
- sed "s/#USAGE:/ /" |\
- sed "s/-run:\(.*\))/-run:\1/" |\
- sed "s/-run:\(.*\)=\*/-run:\1=<value>/" |\
- sed "s/^--$//"
-}
-
-export EXTERNAL_CLASSPATH=$CLASSPATH
-unset CLASSPATH
-
-#Use QPID_CLASSPATH if set
-if [ -n "$QPID_CLASSPATH" ]; then
- export CLASSPATH=$QPID_CLASSPATH
- log $INFO "Using QPID_CLASSPATH" $QPID_CLASSPATH
-else
- log $WARN "Warning: Qpid classpath not set. CLASSPATH must include qpid jars."
-fi
-
-#Use QPID_JAVA_GC if set
-if [ -n "$QPID_JAVA_GC" ]; then
- export JAVA_GC=$QPID_JAVA_GC
- log $INFO "Using QPID_JAVA_GC setting" $QPID_JAVA_GC
-else
- log $INFO "Info: QPID_JAVA_GC not set. Defaulting to JAVA_GC" $JAVA_GC
-fi
-
-
-#Use QPID_JAVA_MEM if set
-if [ -n "$QPID_JAVA_MEM" ]; then
- export JAVA_MEM=$QPID_JAVA_MEM
- log $INFO "Using QPID_JAVA_MEM setting" $QPID_JAVA_MEM
-else
- log $INFO "Info: QPID_JAVA_MEM not set. Defaulting to JAVA_MEM" $JAVA_MEM
-fi
-
-declare -a RUN_ARGS JAVA_ARGS
-for arg in "$@"; do
- if [[ $arg == -run:* ]]; then
- RUN_ARGS[${#RUN_ARGS[@]}]="$arg"
- else
- JAVA_ARGS[${#JAVA_ARGS[@]}]="$arg"
- fi
-done
-
-# this defines the default behavior, it may be modified during option
-# processing below
-DISPATCH() {
- if $debug; then
- echo "CLASSPATH=${CLASSPATH}"
- echo "${COMMAND[@]}"
- fi
-
- exec "${COMMAND[@]}"
-}
-
-exclusive() {
- if [ -z "$PREVIOUS_ARGS" ]; then
- PREVIOUS_ARGS=$1
- else
- PREVIOUS_ARGS="${PREVIOUS_ARGS}, $1"
- DISPATCH() {
- die -usage "you must choose one of: $PREVIOUS_ARGS"
- }
- fi
-}
-
-debug=false
-
-for arg in "${RUN_ARGS[@]}"; do
- case $arg in
- -run:debug)
-#USAGE: print the classpath and command before running it
- debug=true
- ;;
- -run:jpda)
-#USAGE: adds debugging options to the java command, use
-#USAGE: JPDA_TRANSPORT and JPDA_ADDRESS to customize the debugging
-#USAGE: behavior and use JPDA_OPTS to override it entirely
- if [ -z "$JPDA_OPTS" ]; then
- JPDA_OPTS="-Xdebug -Xrunjdwp:transport=${JPDA_TRANSPORT:-dt_socket},address=${JPDA_ADDRESS:-8000},server=y,suspend=n"
- fi
- QPID_OPTS="${QPID_OPTS} ${JPDA_OPTS}"
- ;;
- -run:external-classpath=*)
-#USAGE: controls how the CLASSPATH environment variable is used by
-#USAGE: this script, value can be one of ignore (the default), first,
-#USAGE: last, and only
- case $arg in
- *=ignore)
- # do nothing
- ;;
- *=first)
- CLASSPATH=$EXTERNAL_CLASSPATH:$CLASSPATH
- ;;
- *=last)
- CLASSPATH=$CLASSPATH:$EXTERNAL_CLASSPATH
- ;;
- *=only)
- CLASSPATH=$EXTERNAL_CLASSPATH
- ;;
- *)
- die -usage $(echo $arg | sed "s/=/: invalid value '/")\'
- ;;
- esac
- ;;
- -run:print-classpath)
-#USAGE: print the classpath
- DISPATCH() {
- echo $CLASSPATH
- }
- exclusive $arg
- ;;
- -run:print-command)
-#USAGE: print the command
- DISPATCH() {
- echo "${COMMAND[@]}"
- }
- exclusive $arg
- ;;
- -run:help)
-#USAGE: print this message
- DISPATCH() {
- usage
- }
- exclusive $arg
- ;;
- *)
- die -usage "unrecognized -run option '$arg'"
- ;;
- esac
-done
-
-if $cygwin; then
- CLASSPATH=$(cygpath -w -p $CLASSPATH)
- JAVA=$(cygpath -u $JAVA)
-fi
-
-COMMAND=($JAVA $JAVA_VM $QPID_PNAME $JAVA_GC $JAVA_MEM $SYSTEM_PROPS $JAVA_OPTS $QPID_OPTS "${JAVA_ARGS[@]}")
-
-DISPATCH
diff --git a/java/common/build.xml b/java/common/build.xml
deleted file mode 100644
index f2f85fc634..0000000000
--- a/java/common/build.xml
+++ /dev/null
@@ -1,102 +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.
- -
- -->
-<project name="AMQ Common" default="build">
-
- <property name="module.genpom" value="true"/>
-
- <import file="../module.xml"/>
-
- <property name="generated.package" value="org/apache/qpid/framing" />
- <property name="framing.generated.dir" location="${module.precompiled}/${generated.package}" />
- <property name="qpidbuildversion.java" location="${module.precompiled}/org/apache/qpid/QpidBuildVersion.java" />
- <property name="xml.spec.dir" location="${project.root}/../specs" />
- <property name="xml.spec.deps" value="amqp.0-8.xml amqp.0-9.xml amqp0-9-1.stripped.xml" />
- <property name="xml.spec.list" value='"${xml.spec.dir}/amqp.0-8.xml" "${xml.spec.dir}/amqp.0-9.xml" "${xml.spec.dir}/amqp0-9-1.stripped.xml"' />
- <property name="gentools.timestamp" location="${framing.generated.dir}/gentools.timestamp" />
- <property name="jython.timestamp" location="${framing.generated.dir}/jython.timestamp" />
-
- <target name="check_jython_deps">
- <uptodate property="jython.notRequired" targetfile="${jython.timestamp}">
- <srcfiles dir="${xml.spec.dir}" includes="amqp.0-10-qpid-errata.xml" />
- </uptodate>
- </target>
-
- <target name="jython" depends="check_jython_deps" unless="jython.notRequired">
- <jython path="${mllib.dir}">
- <args>
- <arg value="${basedir}/codegen"/>
- <arg value="${module.precompiled}"/>
- <arg value="${xml.spec.dir}/amqp.0-10-qpid-errata.xml"/>
- <arg value="${basedir}"/>
- </args>
- </jython>
- <touch file="${jython.timestamp}" />
- </target>
-
- <target name="compile_gentools">
- <ant dir="${gentools.home}" />
- </target>
-
- <target name="check_gentool_deps">
- <uptodate property="gentools.notRequired" targetfile="${gentools.timestamp}">
- <srcfiles dir="${xml.spec.dir}" includes="${xml.spec.deps}" />
- </uptodate>
- </target>
-
- <target name="gentools" depends="compile_gentools,check_gentool_deps" unless="gentools.notRequired">
- <mkdir dir="${framing.generated.dir}"/>
- <java classname="org.apache.qpid.gentools.Main" fork="true" dir="${gentools.home}/src" failonerror="true">
- <arg line='-j -o "${framing.generated.dir}" -t "${project.root}/common/templates" ${xml.spec.list}'/>
- <classpath>
- <pathelement path="${gentools.home}/src" />
- <fileset dir="${gentools.home}/lib">
- <include name="**/*.jar"/>
- </fileset>
- <pathelement path="${gentools.home}/lib/velocity-1.4.jar" />
- <pathelement path="${gentools.home}/lib/velocity-dep-1.4.jar" />
- </classpath>
- </java>
- <touch file="${gentools.timestamp}" />
- </target>
-
- <target name="build-version" depends="create-version" if="version-stale">
- <tstamp>
- <format property="build.time" pattern="yyyy-MM-dd HH:mm:ss z" timezone="UTC"/>
- </tstamp>
-
- <echo file="${qpidbuildversion.java}" append="false">package org.apache.qpid;
-
-public class QpidBuildVersion
-{
- public static final String VERSION = "${project.version}";
- public static final String SVN_VERSION = "${svnversion.output}";
- public static final String BUILD_PROJECT = "${project.name}";
- public static final String BUILD_TIME = "${build.time}";
-
-}
-</echo>
-
- </target>
-
- <target name="precompile" depends="gentools,jython,create-version,build-version"/>
-
- <target name="bundle" depends="bundle-tasks"/>
-</project>
diff --git a/java/common/codegen b/java/common/codegen
deleted file mode 100755
index 6a1effc07b..0000000000
--- a/java/common/codegen
+++ /dev/null
@@ -1,89 +0,0 @@
-#!/usr/bin/env python
-
-#
-# 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 os, sys, mllib
-from templating import Parser
-from genutil import *
-
-out_dir = sys.argv[1]
-spec_file = sys.argv[2]
-tpl_dir = sys.argv[3]
-pkg_dir = os.path.join(out_dir, "org/apache/qpid/transport")
-
-if not os.path.exists(pkg_dir):
- os.makedirs(pkg_dir)
-
-spec = mllib.xml_parse(spec_file)
-
-def excludes(nd):
- if (nd.parent is not None and
- nd.parent.name == "class" and
- nd.parent["@name"] in ("file", "stream")):
- return False
- else:
- return True
-
-def execute(output, template, **kwargs):
- f = open(os.path.join(tpl_dir, template))
- input = f.read()
- f.close()
- p = Parser(**kwargs)
- p.parse(input)
- fname = os.path.join(pkg_dir, output)
- f = open(fname, "w")
- f.write(p.output)
- f.close()
-
-execute("Type.java", "Type.tpl", spec = spec)
-execute("Constant.java", "Constant.tpl", spec = spec)
-
-structs = spec.query["amqp/struct"] + \
- spec.query["amqp/class/struct", excludes] + \
- spec.query["amqp/class/command/result/struct", excludes]
-controls = spec.query["amqp/class/control", excludes]
-commands = spec.query["amqp/class/command", excludes]
-
-composites = structs + controls + commands
-actions = controls + commands
-connection = [c for c in actions if c.parent["@name"] == "connection"]
-session = [c for c in actions if c.parent["@name"] != "connection"]
-
-for c in composites:
- name = cname(c)
- execute("%s.java" % name, "Composite.tpl", type = c, name = name)
-
-execute("MethodDelegate.java", "MethodDelegate.tpl", composites = actions)
-execute("Option.java", "Option.tpl", composites = composites)
-execute("ConnectionInvoker.java", "Invoker.tpl", invoker = "ConnectionInvoker",
- composites = connection)
-execute("SessionInvoker.java", "Invoker.tpl", invoker = "SessionInvoker",
- composites = session)
-execute("StructFactory.java", "StructFactory.tpl", composites = composites)
-
-def is_enum(nd):
- return nd["enum"] is not None
-
-enums = spec.query["amqp/domain", is_enum] + \
- spec.query["amqp/class/domain", is_enum]
-
-for e in enums:
- name = cname(e)
- execute("%s.java" % name, "Enum.tpl", name = name, type = e)
diff --git a/java/common/etc/qpid-run.conf b/java/common/etc/qpid-run.conf
deleted file mode 100644
index b9765fe3ce..0000000000
--- a/java/common/etc/qpid-run.conf
+++ /dev/null
@@ -1,25 +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.
-#
-
-QPID_LIBS=$(find ${QPID_HOME}/lib -name "*.jar" -print | sed -e :a -e '$!N;s/\n/:/;ta' -e 'P;D')
-
-export JAVA=java \
- JAVA_VM=-server \
- JAVA_MEM=-Xmx1024m \
- CLASSPATH=$QPID_LIBS
diff --git a/java/common/etc/qpid-run.conf.dev b/java/common/etc/qpid-run.conf.dev
deleted file mode 100644
index a5419eb4e8..0000000000
--- a/java/common/etc/qpid-run.conf.dev
+++ /dev/null
@@ -1,26 +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.
-#
-
-QPID_LIBS=$(find ${QPID_HOME} -type d -name "classes" -print | sed -e :a -e '$!N;s/\n/:/;ta' -e 'P;D')
-QPID_LIBS=${QPID_LIBS}:$(find $(dirname ${QPID_HOME}) -name "*.jar" -print | sed -e :a -e '$!N;s/\n/:/;ta' -e 'P;D')
-
-export JAVA=java \
- JAVA_VM=-server \
- JAVA_MEM=-Xmx1024m \
- CLASSPATH=$QPID_LIBS
diff --git a/java/common/genutil.py b/java/common/genutil.py
deleted file mode 100644
index 57a461ed40..0000000000
--- a/java/common/genutil.py
+++ /dev/null
@@ -1,256 +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.
-#
-
-def camel(offset, *args):
- parts = []
- for a in args:
- parts.extend(a.split("-"))
- return "".join(parts[:offset] + [p[0].upper() + p[1:] for p in parts[offset:]])
-
-def dromedary(s):
- return s[0].lower() + s[1:]
-
-def scream(*args):
- return "_".join([a.replace("-", "_").upper() for a in args])
-
-def num(x, default=None):
- if x is not None and x != "":
- return int(x, 0)
- else:
- return default
-
-def klass(nd):
- parent = nd.parent
- while parent is not None:
- if hasattr(parent, "name") and parent.name == "class":
- return parent
- parent = parent.parent
-
-untyped = -1
-
-def code(nd):
- global untyped
- cd = num(nd["@code"])
- if cd is None:
- cd = untyped
- untyped -= 1
- return cd
-
- cls = klass(nd)
- if cls:
- cd |= (num(cls["@code"]) << 8)
- return cd
-
-def root(nd):
- if nd.parent is None:
- return nd
- else:
- return root(nd.parent)
-
-def qname(nd):
- name = nd["@name"]
- cls = klass(nd)
- if cls != None:
- return "%s.%s" % (cls["@name"], name)
- else:
- return name
-
-RESOLVED = {}
-
-def resolve(node, name):
- key = (node, name)
- if RESOLVED.has_key(key):
- return RESOLVED[key]
- else:
- spec = root(node)
- cls = klass(node)
- if cls:
- for nd in cls.query["#tag"]:
- if nd["@name"] == name:
- RESOLVED[key] = nd
- return nd
- for nd in spec.query["amqp/#tag"] + spec.query["amqp/class/#tag"]:
- if name == qname(nd):
- RESOLVED[key] = nd
- return nd
- raise Exception("unresolved name: %s" % name)
-
-def resolve_type(nd):
- if hasattr(nd, "_resolved_type"):
- return nd._resolved_type
- else:
- name = nd["@type"]
- type = resolve(nd, name)
- if type.name == "domain" and not type["enum"]:
- type = resolve_type(type)
- nd._resolved_type = type
- return type
-
-TYPES = {
- "bit": "boolean",
- "uint8": "short",
- "uint16": "int",
- "uint32": "long",
- "uint64": "long",
- "datetime": "long",
- "uuid": "UUID",
- "sequence-no": "int",
- "sequence-set": "RangeSet", # XXX
- "byte-ranges": "RangeSet", # XXX
- "str8": "String",
- "str16": "String",
- "vbin8": "byte[]",
- "vbin16": "byte[]",
- "vbin32": "byte[]",
- "struct32": "Struct",
- "map": "Map<String,Object>",
- "array": "List<Object>"
- }
-
-def cname(nd, field="@name"):
- cls = klass(nd)
- if cls:
- if (nd.name in ("struct", "result") and
- cls["@name"] != "session" and
- nd[field] != "header"):
- return camel(0, nd[field])
- else:
- return camel(0, cls["@name"], nd[field])
- else:
- return camel(0, nd[field])
-
-def jtype(nd):
- if nd.name == "struct" or nd["enum"]:
- return cname(nd)
- else:
- return TYPES[nd["@name"]]
-
-REFS = {
- "boolean": "Boolean",
- "byte": "Byte",
- "short": "Short",
- "int": "Integer",
- "long": "Long",
- "float": "Float",
- "double": "Double",
- "char": "Character"
-}
-
-def jref(jt):
- return REFS.get(jt, jt)
-
-def jclass(jt):
- idx = jt.find('<')
- if idx > 0:
- return jt[:idx]
- else:
- return jt
-
-DEFAULTS = {
- "long": 0,
- "int": 0,
- "short": 0,
- "byte": 0,
- "char": 0,
- "boolean": "false"
- }
-
-class Field:
-
- def __init__(self, index, nd):
- self.index = index
- self.name = camel(1, nd["@name"])
- self.type_node = resolve_type(nd)
- if self.type_node.name == "domain":
- self.prim_type = resolve_type(self.type_node)
- else:
- self.prim_type = self.type_node
- self.variable_width = num(self.prim_type["@variable-width"], 0)
- self.fixed_width = num(self.prim_type["@fixed-width"], 0)
- self.empty = self.variable_width == 0 and self.fixed_width == 0 and self.prim_type.name != "struct"
- tname = cname(self.type_node)
- if self.type_node.name == "struct":
- self.read = "(%s) dec.readStruct(%s.TYPE)" % (tname, tname)
- self.write = "enc.writeStruct(%s.TYPE, check(struct).%s)" % (tname, self.name)
- self.coder = "Struct"
- elif self.type_node.name == "domain":
- self.coder = camel(0, self.prim_type["@name"])
- self.read = "%s.get(dec.read%s())" % (tname, self.coder)
- self.write = "enc.write%s(check(struct).%s.getValue())" % (self.coder, self.name)
- else:
- self.coder = camel(0, self.type_node["@name"])
- self.read = "dec.read%s()" % self.coder
- self.write = "enc.write%s(check(struct).%s)" % (self.coder, self.name)
- self.type = jtype(self.type_node)
- self.ref_type = jref(self.type)
- self.default = DEFAULTS.get(self.type, "null")
- self.has = camel(1, "has", self.name)
- self.get = camel(1, "get", self.name)
- self.set = camel(1, "set", self.name)
- self.clear = camel(1, "clear", self.name)
- if self.type == "boolean":
- self.option = scream(nd["@name"])
- else:
- self.option = None
-
- def flag_mask(self, pack):
- flag = pack * 8 - 8 - (self.index/8)*8 + (self.index % 8)
- return 1 << flag
-
-
-def get_fields(nd):
- fields = []
- index = 0
- for f in nd.query["field"]:
- fields.append(Field(index, f))
- index += 1
- return fields
-
-def get_parameters(type, fields):
- params = []
- options = False
- for f in fields:
- if f.option:
- options = True
- else:
- params.append("%s %s" % (f.type, f.name))
- if type["segments"]:
- params.append("Header header")
- params.append("ByteBuffer body")
- if options or type.name in ("control", "command"):
- params.append("Option ... _options")
- return params
-
-def get_arguments(type, fields):
- args = []
- options = False
- for f in fields:
- if f.option:
- options = True
- else:
- args.append(f.name)
- if type["segments"]:
- args.append("header")
- args.append("body")
- if options or type.name in ("control", "command"):
- args.append("_options")
- return args
-
-def get_options(fields):
- return [f for f in fields if f.option]
diff --git a/java/common/protocol-version.xml b/java/common/protocol-version.xml
deleted file mode 100644
index 5435a0a582..0000000000
--- a/java/common/protocol-version.xml
+++ /dev/null
@@ -1,70 +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.
- -
- -->
-<project name="Qpid Common Protocol Versions" default="generate">
- <property name="topDirectoryLocation" location=".." />
- <property name="project.build.directory" location="target" />
- <property name="gentools.home" location="${topDirectoryLocation}/../gentools" />
- <property name="generated.path" location="${project.build.directory}/generated-sources/gentools" />
- <property name="generated.package" value="org/apache/qpid/framing" />
- <property name="generated.dir" location="${generated.path}/${generated.package}" />
- <property name="generated.timestamp" location="${generated.dir}/timestamp" />
- <property name="xml.spec.dir" location="${topDirectoryLocation}/../specs" />
- <property name="xml.spec.deps" value="amqp.0-8.xml amqp.0-9.xml amqp0-9-1.stripped.xml" />
- <property name="xml.spec.list" value="${xml.spec.dir}/amqp.0-8.xml ${xml.spec.dir}/amqp.0-9.xml ${xml.spec.dir}/amqp0-9-1.stripped.xml" />
- <property name="template.dir" value="${topDirectoryLocation}/common/templates" />
-
-
- <!--<target name="generate" depends="compile_generator,check_generate_deps" unless="generation.notRequired">-->
- <target name="generate" depends="compile_generator" unless="generation.notRequired">
- <mkdir dir="${generated.dir}"/>
- <java classname="org.apache.qpid.gentools.Main" fork="true" dir="${gentools.home}/src" failonerror="true">
- <arg line="-j -o ${generated.dir} -t ${template.dir} ${xml.spec.list}" />
- <classpath>
- <pathelement path="${gentools.home}/src" />
- <fileset dir="${gentools.home}/lib">
- <include name="**/*.jar"/>
- </fileset>
- <pathelement path="${gentools.home}/lib/velocity-1.4.jar" />
- <pathelement path="${gentools.home}/lib/velocity-dep-1.4.jar" />
- </classpath>
- </java>
- <touch file="${generated.timestamp}" />
- </target>
-
- <target name="check_generate_deps">
- <uptodate property="generation.notRequired" targetfile="${generated.timestamp}">
- <srcfiles dir="${xml.spec.dir}" includes="${xml.spec.deps}" />
- <srcfiles dir="${template.dir}" includes="**/*.vm **/*.tmpl" />
- </uptodate>
- </target>
-
- <target name="compile_generator">
- <ant dir="${gentools.home}" />
- </target>
-
- <target name="precompile" depends="generate"/>
-
- <target name="clean">
- <delete dir="${generated.path}" />
- </target>
-
-</project>
-
diff --git a/java/common/readme.txt b/java/common/readme.txt
deleted file mode 100644
index 12841fa08d..0000000000
--- a/java/common/readme.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-AMQP Common Java API
-
-Common generated functionality for AMQP Java client and broker. See the
-readme in the client and broker directories.
diff --git a/java/common/src/main/java/common.bnd b/java/common/src/main/java/common.bnd
deleted file mode 100755
index 89c397f400..0000000000
--- a/java/common/src/main/java/common.bnd
+++ /dev/null
@@ -1,25 +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.
-#
-
-ver: 0.11.0
-
-Bundle-SymbolicName: qpid-common
-Bundle-Version: ${ver}
-Export-Package: *;version=${ver}
-Bundle-RequiredExecutionEnvironment: J2SE-1.5
diff --git a/java/common/src/main/java/org/apache/configuration/PropertyNameResolver.java b/java/common/src/main/java/org/apache/configuration/PropertyNameResolver.java
deleted file mode 100644
index 73ee747c07..0000000000
--- a/java/common/src/main/java/org/apache/configuration/PropertyNameResolver.java
+++ /dev/null
@@ -1,129 +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.configuration;
-
-import java.util.HashMap;
-import java.util.Map;
-
-public class PropertyNameResolver
-{
- public static interface Accessor
- {
- Object get(String name);
- }
-
- private static Map<Class<?>,Accessor> accessors = new HashMap<Class<?>,Accessor>();
- protected Map<String,QpidProperty> properties;
-
- private static class BooleanAccessor implements Accessor
- {
- public Boolean get(String name)
- {
- return Boolean.getBoolean(name);
- }
- }
-
- private static class IntegerAccessor implements Accessor
- {
- public Integer get(String name)
- {
- return Integer.getInteger(name);
- }
- }
-
- private static class LongAccessor implements Accessor
- {
- public Long get(String name)
- {
- return Long.getLong(name);
- }
- }
-
- private static class StringAccessor implements Accessor
- {
- public String get(String name)
- {
- return System.getProperty(name);
- }
- }
-
- static
- {
- accessors.put(Boolean.class, new BooleanAccessor());
- accessors.put(Integer.class, new IntegerAccessor());
- accessors.put(String.class, new StringAccessor());
- accessors.put(Long.class, new LongAccessor());
- }
-
- public Integer getIntegerValue(String propName)
- {
- return properties.get(propName).get(Integer.class);
- }
-
- public Long getLongValue(String propName)
- {
- return properties.get(propName).get(Long.class);
- }
-
- public String getStringValue(String propName)
- {
- return properties.get(propName).get(String.class);
- }
-
- public Boolean getBooleanValue(String propName)
- {
- return properties.get(propName).get(Boolean.class);
- }
-
- public <T> T get(String propName,Class<T> klass)
- {
- return properties.get(propName).get(klass);
- }
-
- static class QpidProperty
- {
- private Object defValue;
- private String[] names;
-
- QpidProperty(Object defValue, String ... names)
- {
- this.defValue = defValue;
- this.names = names;
- }
-
- <T> T get(Class<T> klass)
- {
- Accessor acc = accessors.get(klass);
- for (String name : names)
- {
- Object obj = acc.get(name);
- if (obj != null)
- {
- return klass.cast(obj);
- }
- }
-
- return klass.cast(defValue);
- }
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/mina/common/FixedSizeByteBufferAllocator.java b/java/common/src/main/java/org/apache/mina/common/FixedSizeByteBufferAllocator.java
deleted file mode 100644
index 0c311b6645..0000000000
--- a/java/common/src/main/java/org/apache/mina/common/FixedSizeByteBufferAllocator.java
+++ /dev/null
@@ -1,467 +0,0 @@
-package org.apache.mina.common;
-
-import org.apache.mina.common.ByteBuffer;
-
-import java.nio.*;
-
-/*
-*
-* 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 FixedSizeByteBufferAllocator implements ByteBufferAllocator
-{
-
-
- private static final int MINIMUM_CAPACITY = 1;
-
- public FixedSizeByteBufferAllocator ()
- {
- }
-
- public ByteBuffer allocate( int capacity, boolean direct )
- {
- java.nio.ByteBuffer nioBuffer;
- if( direct )
- {
- nioBuffer = java.nio.ByteBuffer.allocateDirect( capacity );
- }
- else
- {
- nioBuffer = java.nio.ByteBuffer.allocate( capacity );
- }
- return new FixedSizeByteBuffer( nioBuffer );
- }
-
- public ByteBuffer wrap( java.nio.ByteBuffer nioBuffer )
- {
- return new FixedSizeByteBuffer( nioBuffer );
- }
-
- public void dispose()
- {
- }
-
-
-
- private static final class FixedSizeByteBuffer extends ByteBuffer
- {
- private java.nio.ByteBuffer buf;
- private int mark = -1;
-
-
- protected FixedSizeByteBuffer( java.nio.ByteBuffer buf )
- {
- this.buf = buf;
- buf.order( ByteOrder.BIG_ENDIAN );
- }
-
- public synchronized void acquire()
- {
- }
-
- public void release()
- {
- }
-
- public java.nio.ByteBuffer buf()
- {
- return buf;
- }
-
- public boolean isPooled()
- {
- return false;
- }
-
- public void setPooled( boolean pooled )
- {
- }
-
- public ByteBuffer duplicate() {
- return new FixedSizeByteBuffer( this.buf.duplicate() );
- }
-
- public ByteBuffer slice() {
- return new FixedSizeByteBuffer( this.buf.slice() );
- }
-
- public ByteBuffer asReadOnlyBuffer() {
- return new FixedSizeByteBuffer( this.buf.asReadOnlyBuffer() );
- }
-
- public byte[] array()
- {
- return buf.array();
- }
-
- public int arrayOffset()
- {
- return buf.arrayOffset();
- }
-
- public boolean isDirect()
- {
- return buf.isDirect();
- }
-
- public boolean isReadOnly()
- {
- return buf.isReadOnly();
- }
-
- public int capacity()
- {
- return buf.capacity();
- }
-
- public ByteBuffer capacity( int newCapacity )
- {
- if( newCapacity > capacity() )
- {
- throw new IllegalArgumentException();
- }
-
- return this;
- }
-
-
-
- public boolean isAutoExpand()
- {
- return false;
- }
-
- public ByteBuffer setAutoExpand( boolean autoExpand )
- {
- if(autoExpand) throw new IllegalArgumentException();
- else return this;
- }
-
- public ByteBuffer expand( int pos, int expectedRemaining )
- {
- int end = pos + expectedRemaining;
- if( end > capacity() )
- {
- // The buffer needs expansion.
- capacity( end );
- }
-
- if( end > limit() )
- {
- // We call limit() directly to prevent StackOverflowError
- buf.limit( end );
- }
- return this;
- }
-
- public int position()
- {
- return buf.position();
- }
-
- public ByteBuffer position( int newPosition )
- {
-
- buf.position( newPosition );
- if( mark > newPosition )
- {
- mark = -1;
- }
- return this;
- }
-
- public int limit()
- {
- return buf.limit();
- }
-
- public ByteBuffer limit( int newLimit )
- {
- buf.limit( newLimit );
- if( mark > newLimit )
- {
- mark = -1;
- }
- return this;
- }
-
- public ByteBuffer mark()
- {
- buf.mark();
- mark = position();
- return this;
- }
-
- public int markValue()
- {
- return mark;
- }
-
- public ByteBuffer reset()
- {
- buf.reset();
- return this;
- }
-
- public ByteBuffer clear()
- {
- buf.clear();
- mark = -1;
- return this;
- }
-
- public ByteBuffer flip()
- {
- buf.flip();
- mark = -1;
- return this;
- }
-
- public ByteBuffer rewind()
- {
- buf.rewind();
- mark = -1;
- return this;
- }
-
- public byte get()
- {
- return buf.get();
- }
-
- public ByteBuffer put( byte b )
- {
- buf.put( b );
- return this;
- }
-
- public byte get( int index )
- {
- return buf.get( index );
- }
-
- public ByteBuffer put( int index, byte b )
- {
- buf.put( index, b );
- return this;
- }
-
- public ByteBuffer get( byte[] dst, int offset, int length )
- {
- buf.get( dst, offset, length );
- return this;
- }
-
- public ByteBuffer put( java.nio.ByteBuffer src )
- {
- buf.put( src );
- return this;
- }
-
- public ByteBuffer put( byte[] src, int offset, int length )
- {
- buf.put( src, offset, length );
- return this;
- }
-
- public ByteBuffer compact()
- {
- buf.compact();
- mark = -1;
- return this;
- }
-
- public ByteOrder order()
- {
- return buf.order();
- }
-
- public ByteBuffer order( ByteOrder bo )
- {
- buf.order( bo );
- return this;
- }
-
- public char getChar()
- {
- return buf.getChar();
- }
-
- public ByteBuffer putChar( char value )
- {
- buf.putChar( value );
- return this;
- }
-
- public char getChar( int index )
- {
- return buf.getChar( index );
- }
-
- public ByteBuffer putChar( int index, char value )
- {
- buf.putChar( index, value );
- return this;
- }
-
- public CharBuffer asCharBuffer()
- {
- return buf.asCharBuffer();
- }
-
- public short getShort()
- {
- return buf.getShort();
- }
-
- public ByteBuffer putShort( short value )
- {
- buf.putShort( value );
- return this;
- }
-
- public short getShort( int index )
- {
- return buf.getShort( index );
- }
-
- public ByteBuffer putShort( int index, short value )
- {
- buf.putShort( index, value );
- return this;
- }
-
- public ShortBuffer asShortBuffer()
- {
- return buf.asShortBuffer();
- }
-
- public int getInt()
- {
- return buf.getInt();
- }
-
- public ByteBuffer putInt( int value )
- {
- buf.putInt( value );
- return this;
- }
-
- public int getInt( int index )
- {
- return buf.getInt( index );
- }
-
- public ByteBuffer putInt( int index, int value )
- {
- buf.putInt( index, value );
- return this;
- }
-
- public IntBuffer asIntBuffer()
- {
- return buf.asIntBuffer();
- }
-
- public long getLong()
- {
- return buf.getLong();
- }
-
- public ByteBuffer putLong( long value )
- {
- buf.putLong( value );
- return this;
- }
-
- public long getLong( int index )
- {
- return buf.getLong( index );
- }
-
- public ByteBuffer putLong( int index, long value )
- {
- buf.putLong( index, value );
- return this;
- }
-
- public LongBuffer asLongBuffer()
- {
- return buf.asLongBuffer();
- }
-
- public float getFloat()
- {
- return buf.getFloat();
- }
-
- public ByteBuffer putFloat( float value )
- {
- buf.putFloat( value );
- return this;
- }
-
- public float getFloat( int index )
- {
- return buf.getFloat( index );
- }
-
- public ByteBuffer putFloat( int index, float value )
- {
- buf.putFloat( index, value );
- return this;
- }
-
- public FloatBuffer asFloatBuffer()
- {
- return buf.asFloatBuffer();
- }
-
- public double getDouble()
- {
- return buf.getDouble();
- }
-
- public ByteBuffer putDouble( double value )
- {
- buf.putDouble( value );
- return this;
- }
-
- public double getDouble( int index )
- {
- return buf.getDouble( index );
- }
-
- public ByteBuffer putDouble( int index, double value )
- {
- buf.putDouble( index, value );
- return this;
- }
-
- public DoubleBuffer asDoubleBuffer()
- {
- return buf.asDoubleBuffer();
- }
-
-
- }
-
-
-}
diff --git a/java/common/src/main/java/org/apache/mina/common/support/DefaultIoFuture.java b/java/common/src/main/java/org/apache/mina/common/support/DefaultIoFuture.java
deleted file mode 100644
index 4fd28c4eb5..0000000000
--- a/java/common/src/main/java/org/apache/mina/common/support/DefaultIoFuture.java
+++ /dev/null
@@ -1,227 +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.mina.common.support;
-
-import org.apache.mina.common.IoFuture;
-import org.apache.mina.common.IoSession;
-import org.apache.mina.common.IoFutureListener;
-
-import java.util.List;
-import java.util.ArrayList;
-import java.util.Iterator;
-
-/**
- * A default implementation of {@link org.apache.mina.common.IoFuture}.
- *
- * @author The Apache Directory Project (mina-dev@directory.apache.org)
- */
-public class DefaultIoFuture implements IoFuture
-{
- private final IoSession session;
- private final Object lock;
- private List listeners;
- private Object result;
- private boolean ready;
-
-
- /**
- * Creates a new instance.
- *
- * @param session an {@link IoSession} which is associated with this future
- */
- public DefaultIoFuture( IoSession session )
- {
- this.session = session;
- this.lock = this;
- }
-
- /**
- * Creates a new instance which uses the specified object as a lock.
- */
- public DefaultIoFuture( IoSession session, Object lock )
- {
- if( lock == null )
- {
- throw new NullPointerException( "lock" );
- }
- this.session = session;
- this.lock = lock;
- }
-
- public IoSession getSession()
- {
- return session;
- }
-
- public Object getLock()
- {
- return lock;
- }
-
- public void join()
- {
- synchronized( lock )
- {
- while( !ready )
- {
- try
- {
- lock.wait();
- }
- catch( InterruptedException e )
- {
- }
- }
- }
- }
-
- public boolean join( long timeoutInMillis )
- {
- long startTime = ( timeoutInMillis <= 0 ) ? 0 : System
- .currentTimeMillis();
- long waitTime = timeoutInMillis;
-
- synchronized( lock )
- {
- if( ready )
- {
- return ready;
- }
- else if( waitTime <= 0 )
- {
- return ready;
- }
-
- for( ;; )
- {
- try
- {
- lock.wait( waitTime );
- }
- catch( InterruptedException e )
- {
- }
-
- if( ready )
- return true;
- else
- {
- waitTime = timeoutInMillis - ( System.currentTimeMillis() - startTime );
- if( waitTime <= 0 )
- {
- return ready;
- }
- }
- }
- }
- }
-
- public boolean isReady()
- {
- synchronized( lock )
- {
- return ready;
- }
- }
-
- /**
- * Sets the result of the asynchronous operation, and mark it as finished.
- */
- protected void setValue( Object newValue )
- {
- synchronized( lock )
- {
- // Allow only once.
- if( ready )
- {
- return;
- }
-
- result = newValue;
- ready = true;
- lock.notifyAll();
-
- notifyListeners();
- }
- }
-
- /**
- * Returns the result of the asynchronous operation.
- */
- protected Object getValue()
- {
- synchronized( lock )
- {
- return result;
- }
- }
-
- public void addListener( IoFutureListener listener )
- {
- if( listener == null )
- {
- throw new NullPointerException( "listener" );
- }
-
- synchronized( lock )
- {
- if(listeners == null)
- {
- listeners = new ArrayList();
- }
- listeners.add( listener );
- if( ready )
- {
- listener.operationComplete( this );
- }
- }
- }
-
- public void removeListener( IoFutureListener listener )
- {
- if( listener == null )
- {
- throw new NullPointerException( "listener" );
- }
-
- synchronized( lock )
- {
- listeners.remove( listener );
- }
- }
-
- private void notifyListeners()
- {
- synchronized( lock )
- {
-
- if(listeners != null)
- {
-
- for( Iterator i = listeners.iterator(); i.hasNext(); ) {
- ( ( IoFutureListener ) i.next() ).operationComplete( this );
- }
- }
- }
- }
-}
-
-
-
diff --git a/java/common/src/main/java/org/apache/mina/common/support/IoServiceListenerSupport.java b/java/common/src/main/java/org/apache/mina/common/support/IoServiceListenerSupport.java
deleted file mode 100644
index 5723ffbaa9..0000000000
--- a/java/common/src/main/java/org/apache/mina/common/support/IoServiceListenerSupport.java
+++ /dev/null
@@ -1,351 +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.mina.common.support;
-
-import java.net.SocketAddress;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.CountDownLatch;
-
-import org.apache.mina.common.IoAcceptorConfig;
-import org.apache.mina.common.IoConnector;
-import org.apache.mina.common.IoFuture;
-import org.apache.mina.common.IoFutureListener;
-import org.apache.mina.common.IoHandler;
-import org.apache.mina.common.IoService;
-import org.apache.mina.common.IoServiceConfig;
-import org.apache.mina.common.IoServiceListener;
-import org.apache.mina.common.IoSession;
-import org.apache.mina.util.IdentityHashSet;
-
-/**
- * A helper which provides addition and removal of {@link IoServiceListener}s and firing
- * events.
- *
- * @author The Apache Directory Project (mina-dev@directory.apache.org)
- * @version $Rev: 446526 $, $Date: 2006-09-15 01:44:11 -0400 (Fri, 15 Sep 2006) $
- */
-public class IoServiceListenerSupport
-{
- /**
- * A list of {@link IoServiceListener}s.
- */
- private final List listeners = new ArrayList();
-
- /**
- * Tracks managed <tt>serviceAddress</tt>es.
- */
- private final Set managedServiceAddresses = new HashSet();
-
- /**
- * Tracks managed sesssions with <tt>serviceAddress</tt> as a key.
- */
- private final Map managedSessions = new HashMap();
-
- /**
- * Creates a new instance.
- */
- public IoServiceListenerSupport()
- {
- }
-
- /**
- * Adds a new listener.
- */
- public void add( IoServiceListener listener )
- {
- synchronized( listeners )
- {
- listeners.add( listener );
- }
- }
-
- /**
- * Removes an existing listener.
- */
- public void remove( IoServiceListener listener )
- {
- synchronized( listeners )
- {
- listeners.remove( listener );
- }
- }
-
- public Set getManagedServiceAddresses()
- {
- return Collections.unmodifiableSet( managedServiceAddresses );
- }
-
- public boolean isManaged( SocketAddress serviceAddress )
- {
- synchronized( managedServiceAddresses )
- {
- return managedServiceAddresses.contains( serviceAddress );
- }
- }
-
- public Set getManagedSessions( SocketAddress serviceAddress )
- {
- Set sessions;
- synchronized( managedSessions )
- {
- sessions = ( Set ) managedSessions.get( serviceAddress );
- if( sessions == null )
- {
- sessions = new IdentityHashSet();
- }
- }
-
- synchronized( sessions )
- {
- return new IdentityHashSet( sessions );
- }
- }
-
- /**
- * Calls {@link IoServiceListener#serviceActivated(IoService, SocketAddress, IoHandler, IoServiceConfig)}
- * for all registered listeners.
- */
- public void fireServiceActivated(
- IoService service, SocketAddress serviceAddress,
- IoHandler handler, IoServiceConfig config )
- {
- synchronized( managedServiceAddresses )
- {
- if( !managedServiceAddresses.add( serviceAddress ) )
- {
- return;
- }
- }
-
- synchronized( listeners )
- {
- for( Iterator i = listeners.iterator(); i.hasNext(); )
- {
- ( ( IoServiceListener ) i.next() ).serviceActivated(
- service, serviceAddress, handler, config );
- }
- }
- }
-
- /**
- * Calls {@link IoServiceListener#serviceDeactivated(IoService, SocketAddress, IoHandler, IoServiceConfig)}
- * for all registered listeners.
- */
- public synchronized void fireServiceDeactivated(
- IoService service, SocketAddress serviceAddress,
- IoHandler handler, IoServiceConfig config )
- {
- synchronized( managedServiceAddresses )
- {
- if( !managedServiceAddresses.remove( serviceAddress ) )
- {
- return;
- }
- }
-
- try
- {
- synchronized( listeners )
- {
- for( Iterator i = listeners.iterator(); i.hasNext(); )
- {
- ( ( IoServiceListener ) i.next() ).serviceDeactivated(
- service, serviceAddress, handler, config );
- }
- }
- }
- finally
- {
- disconnectSessions( serviceAddress, config );
- }
- }
-
-
- /**
- * Calls {@link IoServiceListener#sessionCreated(IoSession)} for all registered listeners.
- */
- public void fireSessionCreated( IoSession session )
- {
- SocketAddress serviceAddress = session.getServiceAddress();
-
- // Get the session set.
- boolean firstSession = false;
- Set sessions;
- synchronized( managedSessions )
- {
- sessions = ( Set ) managedSessions.get( serviceAddress );
- if( sessions == null )
- {
- sessions = new IdentityHashSet();
- managedSessions.put( serviceAddress, sessions );
- firstSession = true;
- }
- }
-
- // If already registered, ignore.
- synchronized( sessions )
- {
- if ( !sessions.add( session ) )
- {
- return;
- }
- }
-
- // If the first connector session, fire a virtual service activation event.
- if( session.getService() instanceof IoConnector && firstSession )
- {
- fireServiceActivated(
- session.getService(), session.getServiceAddress(),
- session.getHandler(), session.getServiceConfig() );
- }
-
- // Fire session events.
- session.getFilterChain().fireSessionCreated( session );
- session.getFilterChain().fireSessionOpened( session);
-
- // Fire listener events.
- synchronized( listeners )
- {
- for( Iterator i = listeners.iterator(); i.hasNext(); )
- {
- ( ( IoServiceListener ) i.next() ).sessionCreated( session );
- }
- }
- }
-
- /**
- * Calls {@link IoServiceListener#sessionDestroyed(IoSession)} for all registered listeners.
- */
- public void fireSessionDestroyed( IoSession session )
- {
- SocketAddress serviceAddress = session.getServiceAddress();
-
- // Get the session set.
- Set sessions;
- boolean lastSession = false;
- synchronized( managedSessions )
- {
- sessions = ( Set ) managedSessions.get( serviceAddress );
- // Ignore if unknown.
- if( sessions == null )
- {
- return;
- }
-
- // Try to remove the remaining empty seession set after removal.
- synchronized( sessions )
- {
- sessions.remove( session );
- if( sessions.isEmpty() )
- {
- managedSessions.remove( serviceAddress );
- lastSession = true;
- }
- }
- }
-
- // Fire session events.
- session.getFilterChain().fireSessionClosed( session );
-
- // Fire listener events.
- try
- {
- synchronized( listeners )
- {
- for( Iterator i = listeners.iterator(); i.hasNext(); )
- {
- ( ( IoServiceListener ) i.next() ).sessionDestroyed( session );
- }
- }
- }
- finally
- {
- // Fire a virtual service deactivation event for the last session of the connector.
- //TODO double-check that this is *STILL* the last session. May not be the case
- if( session.getService() instanceof IoConnector && lastSession )
- {
- fireServiceDeactivated(
- session.getService(), session.getServiceAddress(),
- session.getHandler(), session.getServiceConfig() );
- }
- }
- }
-
- private void disconnectSessions( SocketAddress serviceAddress, IoServiceConfig config )
- {
- if( !( config instanceof IoAcceptorConfig ) )
- {
- return;
- }
-
- if( !( ( IoAcceptorConfig ) config ).isDisconnectOnUnbind() )
- {
- return;
- }
-
- Set sessions;
- synchronized( managedSessions )
- {
- sessions = ( Set ) managedSessions.get( serviceAddress );
- }
-
- if( sessions == null )
- {
- return;
- }
-
- Set sessionsCopy;
-
- // Create a copy to avoid ConcurrentModificationException
- synchronized( sessions )
- {
- sessionsCopy = new IdentityHashSet( sessions );
- }
-
- final CountDownLatch latch = new CountDownLatch(sessionsCopy.size());
-
- for( Iterator i = sessionsCopy.iterator(); i.hasNext(); )
- {
- ( ( IoSession ) i.next() ).close().addListener( new IoFutureListener()
- {
- public void operationComplete( IoFuture future )
- {
- latch.countDown();
- }
- } );
- }
-
- try
- {
- latch.await();
- }
- catch( InterruptedException ie )
- {
- // Ignored
- }
- }
-}
diff --git a/java/common/src/main/java/org/apache/mina/filter/WriteBufferFullExeception.java b/java/common/src/main/java/org/apache/mina/filter/WriteBufferFullExeception.java
deleted file mode 100644
index 47f19aa76d..0000000000
--- a/java/common/src/main/java/org/apache/mina/filter/WriteBufferFullExeception.java
+++ /dev/null
@@ -1,48 +0,0 @@
-package org.apache.mina.filter;
-
-import org.apache.mina.common.IoFilter;/*
- *
- * 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 WriteBufferFullExeception extends RuntimeException
-{
- private IoFilter.WriteRequest _writeRequest;
-
- public WriteBufferFullExeception()
- {
- this(null);
- }
-
- public WriteBufferFullExeception(IoFilter.WriteRequest writeRequest)
- {
- _writeRequest = writeRequest;
- }
-
-
- public void setWriteRequest(IoFilter.WriteRequest writeRequest)
- {
- _writeRequest = writeRequest;
- }
-
- public IoFilter.WriteRequest getWriteRequest()
- {
- return _writeRequest;
- }
-}
diff --git a/java/common/src/main/java/org/apache/mina/filter/WriteBufferLimitFilterBuilder.java b/java/common/src/main/java/org/apache/mina/filter/WriteBufferLimitFilterBuilder.java
deleted file mode 100644
index 4e9db9071a..0000000000
--- a/java/common/src/main/java/org/apache/mina/filter/WriteBufferLimitFilterBuilder.java
+++ /dev/null
@@ -1,272 +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.mina.filter;
-
-import org.apache.mina.common.ByteBuffer;
-import org.apache.mina.common.DefaultIoFilterChainBuilder;
-import org.apache.mina.common.IoFilterAdapter;
-import org.apache.mina.common.IoFilterChain;
-import org.apache.mina.common.IoSession;
-import org.apache.mina.filter.executor.ExecutorFilter;
-
-import java.util.Iterator;
-import java.util.List;
-
-/**
- * This filter will turn the asynchronous filterWrite method in to a blocking send when there are more than
- * the prescribed number of messages awaiting filterWrite. It should be used in conjunction with the
- * {@link ReadThrottleFilterBuilder} on a server as the blocking writes will allow the read thread to
- * cause an Out of Memory exception due to a back log of unprocessed messages.
- *
- * This is should only be viewed as a temporary work around for DIRMINA-302.
- *
- * A true solution should not be implemented as a filter as this issue will always occur. On a machine
- * where the network is slower than the local producer.
- *
- * Suggested improvement is to allow implementation of policices on what to do when buffer is full.
- *
- * They could be:
- * Block - As this does
- * Wait on a given Future - to drain more of the queue.. in essence this filter with high/low watermarks
- * Throw Exception - through the client filterWrite() method to allow them to get immediate feedback on buffer state
- *
- * <p/>
- * <p>Usage:
- * <p/>
- * <pre><code>
- * DefaultFilterChainBuilder builder = ...
- * WriteBufferLimitFilterBuilder filter = new WriteBufferLimitFilterBuilder();
- * filter.attach( builder );
- * </code></pre>
- * <p/>
- * or
- * <p/>
- * <pre><code>
- * IoFilterChain chain = ...
- * WriteBufferLimitFilterBuilder filter = new WriteBufferLimitFilterBuilder();
- * filter.attach( chain );
- * </code></pre>
- *
- * @author The Apache Directory Project (mina-dev@directory.apache.org)
- * @version $Rev: 619823 $, $Date: 2008-02-08 10:09:37 +0000 (Fri, 08 Feb 2008) $
- */
-public class WriteBufferLimitFilterBuilder
-{
- public static final String PENDING_SIZE = WriteBufferLimitFilterBuilder.class.getName() + ".pendingSize";
-
- private static int DEFAULT_CONNECTION_BUFFER_MESSAGE_COUNT = 5000;
-
- private volatile boolean throwNotBlock = false;
-
- private volatile int maximumConnectionBufferCount;
- private volatile long maximumConnectionBufferSize;
-
- private final Object _blockLock = new Object();
-
- private int _blockWaiters = 0;
-
-
- public WriteBufferLimitFilterBuilder()
- {
- this(DEFAULT_CONNECTION_BUFFER_MESSAGE_COUNT);
- }
-
- public WriteBufferLimitFilterBuilder(int maxWriteBufferSize)
- {
- setMaximumConnectionBufferCount(maxWriteBufferSize);
- }
-
-
- /**
- * Set the maximum amount pending items in the writeQueue for a given session.
- * Changing the value will only take effect when new data is received for a
- * connection, including existing connections. Default value is 5000 msgs.
- *
- * @param maximumConnectionBufferCount New buffer size. Must be > 0
- */
- public void setMaximumConnectionBufferCount(int maximumConnectionBufferCount)
- {
- this.maximumConnectionBufferCount = maximumConnectionBufferCount;
- this.maximumConnectionBufferSize = 0;
- }
-
- public void setMaximumConnectionBufferSize(long maximumConnectionBufferSize)
- {
- this.maximumConnectionBufferSize = maximumConnectionBufferSize;
- this.maximumConnectionBufferCount = 0;
- }
-
- /**
- * Attach this filter to the specified filter chain. It will search for the ThreadPoolFilter, and attach itself
- * before and after that filter.
- *
- * @param chain {@link IoFilterChain} to attach self to.
- */
- public void attach(IoFilterChain chain)
- {
- String name = getThreadPoolFilterEntryName(chain.getAll());
-
- chain.addBefore(name, getClass().getName() + ".sendlimit", new SendLimit());
- }
-
- /**
- * Attach this filter to the specified builder. It will search for the
- * {@link ExecutorFilter}, and attach itself before and after that filter.
- *
- * @param builder {@link DefaultIoFilterChainBuilder} to attach self to.
- */
- public void attach(DefaultIoFilterChainBuilder builder)
- {
- String name = getThreadPoolFilterEntryName(builder.getAll());
-
- builder.addBefore(name, getClass().getName() + ".sendlimit", new SendLimit());
- }
-
- private String getThreadPoolFilterEntryName(List entries)
- {
- Iterator i = entries.iterator();
-
- while (i.hasNext())
- {
- IoFilterChain.Entry entry = (IoFilterChain.Entry) i.next();
-
- if (entry.getFilter().getClass().isAssignableFrom(ExecutorFilter.class))
- {
- return entry.getName();
- }
- }
-
- throw new IllegalStateException("Chain does not contain a ExecutorFilter");
- }
-
-
- public class SendLimit extends IoFilterAdapter
- {
- public void filterWrite(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) throws Exception
- {
- try
- {
- waitTillSendAllowed(session);
- }
- catch (WriteBufferFullExeception wbfe)
- {
- nextFilter.exceptionCaught(session, wbfe);
- }
-
- if (writeRequest.getMessage() instanceof ByteBuffer)
- {
- increasePendingWriteSize(session, (ByteBuffer) writeRequest.getMessage());
- }
-
- nextFilter.filterWrite(session, writeRequest);
- }
-
- private void increasePendingWriteSize(IoSession session, ByteBuffer message)
- {
- synchronized (session)
- {
- Long pendingSize = getScheduledWriteBytes(session) + message.remaining();
- session.setAttribute(PENDING_SIZE, pendingSize);
- }
- }
-
- private boolean sendAllowed(IoSession session)
- {
- if (session.isClosing())
- {
- return true;
- }
-
- int lmswm = maximumConnectionBufferCount;
- long lmswb = maximumConnectionBufferSize;
-
- return (lmswm == 0 || session.getScheduledWriteRequests() < lmswm)
- && (lmswb == 0 || getScheduledWriteBytes(session) < lmswb);
- }
-
- private long getScheduledWriteBytes(IoSession session)
- {
- synchronized (session)
- {
- Long i = (Long) session.getAttribute(PENDING_SIZE);
- return null == i ? 0 : i;
- }
- }
-
- private void waitTillSendAllowed(IoSession session)
- {
- synchronized (_blockLock)
- {
- if (throwNotBlock)
- {
- throw new WriteBufferFullExeception();
- }
-
- _blockWaiters++;
-
- while (!sendAllowed(session))
- {
- try
- {
- _blockLock.wait();
- }
- catch (InterruptedException e)
- {
- // Ignore.
- }
- }
- _blockWaiters--;
- }
- }
-
- public void messageSent(NextFilter nextFilter, IoSession session, Object message) throws Exception
- {
- if (message instanceof ByteBuffer)
- {
- decrementPendingWriteSize(session, (ByteBuffer) message);
- }
- notifyWaitingWriters();
- nextFilter.messageSent(session, message);
- }
-
- private void decrementPendingWriteSize(IoSession session, ByteBuffer message)
- {
- synchronized (session)
- {
- session.setAttribute(PENDING_SIZE, getScheduledWriteBytes(session) - message.remaining());
- }
- }
-
- private void notifyWaitingWriters()
- {
- synchronized (_blockLock)
- {
- if (_blockWaiters != 0)
- {
- _blockLock.notifyAll();
- }
- }
-
- }
-
- }//SentLimit
-
-
-}
diff --git a/java/common/src/main/java/org/apache/mina/filter/codec/OurCumulativeProtocolDecoder.java b/java/common/src/main/java/org/apache/mina/filter/codec/OurCumulativeProtocolDecoder.java
deleted file mode 100644
index 3f7e206cb4..0000000000
--- a/java/common/src/main/java/org/apache/mina/filter/codec/OurCumulativeProtocolDecoder.java
+++ /dev/null
@@ -1,197 +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.mina.filter.codec;
-
-import org.apache.mina.common.ByteBuffer;
-import org.apache.mina.common.IoSession;
-
-/**
- * A {@link ProtocolDecoder} that cumulates the content of received
- * buffers to a <em>cumulative buffer</em> to help users implement decoders.
- * <p>
- * If the received {@link ByteBuffer} is only a part of a message.
- * decoders should cumulate received buffers to make a message complete or
- * to postpone decoding until more buffers arrive.
- * <p>
- * Here is an example decoder that decodes CRLF terminated lines into
- * <code>Command</code> objects:
- * <pre>
- * public class CRLFTerminatedCommandLineDecoder
- * extends CumulativeProtocolDecoder {
- *
- * private Command parseCommand(ByteBuffer in) {
- * // Convert the bytes in the specified buffer to a
- * // Command object.
- * ...
- * }
- *
- * protected boolean doDecode(IoSession session, ByteBuffer in,
- * ProtocolDecoderOutput out)
- * throws Exception {
- *
- * // Remember the initial position.
- * int start = in.position();
- *
- * // Now find the first CRLF in the buffer.
- * byte previous = 0;
- * while (in.hasRemaining()) {
- * byte current = in.get();
- *
- * if (previous == '\r' && current == '\n') {
- * // Remember the current position and limit.
- * int position = in.position();
- * int limit = in.limit();
- * try {
- * in.position(start);
- * in.limit(position);
- * // The bytes between in.position() and in.limit()
- * // now contain a full CRLF terminated line.
- * out.write(parseCommand(in.slice()));
- * } finally {
- * // Set the position to point right after the
- * // detected line and set the limit to the old
- * // one.
- * in.position(position);
- * in.limit(limit);
- * }
- * // Decoded one line; CumulativeProtocolDecoder will
- * // call me again until I return false. So just
- * // return true until there are no more lines in the
- * // buffer.
- * return true;
- * }
- *
- * previous = current;
- * }
- *
- * // Could not find CRLF in the buffer. Reset the initial
- * // position to the one we recorded above.
- * in.position(start);
- *
- * return false;
- * }
- * }
- * </pre>
- *
- * @author The Apache Directory Project (mina-dev@directory.apache.org)
- * @version $Rev: 619823 $, $Date: 2008-02-08 10:09:37 +0000 (Fri, 08 Feb 2008) $
- */
-public abstract class OurCumulativeProtocolDecoder extends ProtocolDecoderAdapter {
-
- private static final String BUFFER = OurCumulativeProtocolDecoder.class
- .getName()
- + ".Buffer";
-
- /**
- * Creates a new instance.
- */
- protected OurCumulativeProtocolDecoder() {
- }
-
- /**
- * Cumulates content of <tt>in</tt> into internal buffer and forwards
- * decoding request to {@link #doDecode(IoSession, ByteBuffer, ProtocolDecoderOutput)}.
- * <tt>doDecode()</tt> is invoked repeatedly until it returns <tt>false</tt>
- * and the cumulative buffer is NOT compacted after decoding ends.
- *
- * @throws IllegalStateException if your <tt>doDecode()</tt> returned
- * <tt>true</tt> not consuming the cumulative buffer.
- */
- public void decode(IoSession session, ByteBuffer in,
- ProtocolDecoderOutput out) throws Exception {
- boolean usingSessionBuffer = true;
- ByteBuffer buf = (ByteBuffer) session.getAttribute(BUFFER);
- // If we have a session buffer, append data to that; otherwise
- // use the buffer read from the network directly.
- if (buf != null) {
- buf.put(in);
- buf.flip();
- } else {
- buf = in;
- usingSessionBuffer = false;
- }
-
- for (;;) {
- int oldPos = buf.position();
- boolean decoded = doDecode(session, buf, out);
- if (decoded) {
- if (buf.position() == oldPos) {
- throw new IllegalStateException(
- "doDecode() can't return true when buffer is not consumed.");
- }
-
- if (!buf.hasRemaining()) {
- break;
- }
- } else {
- break;
- }
- }
-
-
- // if there is any data left that cannot be decoded, we store
- // it in a buffer in the session and next time this decoder is
- // invoked the session buffer gets appended to
- if (buf.hasRemaining()) {
- storeRemainingInSession(buf, session);
- } else {
- if (usingSessionBuffer)
- removeSessionBuffer(session);
- }
- }
-
- /**
- * Implement this method to consume the specified cumulative buffer and
- * decode its content into message(s).
- *
- * @param in the cumulative buffer
- * @return <tt>true</tt> if and only if there's more to decode in the buffer
- * and you want to have <tt>doDecode</tt> method invoked again.
- * Return <tt>false</tt> if remaining data is not enough to decode,
- * then this method will be invoked again when more data is cumulated.
- * @throws Exception if cannot decode <tt>in</tt>.
- */
- protected abstract boolean doDecode(IoSession session, ByteBuffer in,
- ProtocolDecoderOutput out) throws Exception;
-
- /**
- * Releases the cumulative buffer used by the specified <tt>session</tt>.
- * Please don't forget to call <tt>super.dispose( session )</tt> when
- * you override this method.
- */
- public void dispose(IoSession session) throws Exception {
- removeSessionBuffer(session);
- }
-
- private void removeSessionBuffer(IoSession session) {
- ByteBuffer buf = (ByteBuffer) session.removeAttribute(BUFFER);
- if (buf != null) {
- buf.release();
- }
- }
-
- private void storeRemainingInSession(ByteBuffer buf, IoSession session) {
- ByteBuffer remainingBuf = ByteBuffer.allocate(buf.capacity());
- remainingBuf.setAutoExpand(true);
- remainingBuf.order(buf.order());
- remainingBuf.put(buf);
- session.setAttribute(BUFFER, remainingBuf);
- }
-}
diff --git a/java/common/src/main/java/org/apache/mina/filter/codec/QpidProtocolCodecFilter.java b/java/common/src/main/java/org/apache/mina/filter/codec/QpidProtocolCodecFilter.java
deleted file mode 100644
index b8c6f29720..0000000000
--- a/java/common/src/main/java/org/apache/mina/filter/codec/QpidProtocolCodecFilter.java
+++ /dev/null
@@ -1,440 +0,0 @@
-package org.apache.mina.filter.codec;
-
-
-/*
-*
-* 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.mina.common.*;
-import org.apache.mina.common.support.DefaultWriteFuture;
-import org.apache.mina.filter.codec.support.SimpleProtocolDecoderOutput;
-import org.apache.mina.util.SessionLog;
-import org.apache.mina.util.Queue;
-
-
-public class QpidProtocolCodecFilter extends IoFilterAdapter
-{
- public static final String ENCODER = QpidProtocolCodecFilter.class.getName() + ".encoder";
- public static final String DECODER = QpidProtocolCodecFilter.class.getName() + ".decoder";
-
- private static final Class[] EMPTY_PARAMS = new Class[0];
- private static final ByteBuffer EMPTY_BUFFER = ByteBuffer.wrap( new byte[0] );
-
- private final ProtocolCodecFactory factory;
-
- public QpidProtocolCodecFilter( ProtocolCodecFactory factory )
- {
- if( factory == null )
- {
- throw new NullPointerException( "factory" );
- }
- this.factory = factory;
- }
-
- public QpidProtocolCodecFilter( final ProtocolEncoder encoder, final ProtocolDecoder decoder )
- {
- if( encoder == null )
- {
- throw new NullPointerException( "encoder" );
- }
- if( decoder == null )
- {
- throw new NullPointerException( "decoder" );
- }
-
- this.factory = new ProtocolCodecFactory()
- {
- public ProtocolEncoder getEncoder()
- {
- return encoder;
- }
-
- public ProtocolDecoder getDecoder()
- {
- return decoder;
- }
- };
- }
-
- public QpidProtocolCodecFilter( final Class encoderClass, final Class decoderClass )
- {
- if( encoderClass == null )
- {
- throw new NullPointerException( "encoderClass" );
- }
- if( decoderClass == null )
- {
- throw new NullPointerException( "decoderClass" );
- }
- if( !ProtocolEncoder.class.isAssignableFrom( encoderClass ) )
- {
- throw new IllegalArgumentException( "encoderClass: " + encoderClass.getName() );
- }
- if( !ProtocolDecoder.class.isAssignableFrom( decoderClass ) )
- {
- throw new IllegalArgumentException( "decoderClass: " + decoderClass.getName() );
- }
- try
- {
- encoderClass.getConstructor( EMPTY_PARAMS );
- }
- catch( NoSuchMethodException e )
- {
- throw new IllegalArgumentException( "encoderClass doesn't have a public default constructor." );
- }
- try
- {
- decoderClass.getConstructor( EMPTY_PARAMS );
- }
- catch( NoSuchMethodException e )
- {
- throw new IllegalArgumentException( "decoderClass doesn't have a public default constructor." );
- }
-
- this.factory = new ProtocolCodecFactory()
- {
- public ProtocolEncoder getEncoder() throws Exception
- {
- return ( ProtocolEncoder ) encoderClass.newInstance();
- }
-
- public ProtocolDecoder getDecoder() throws Exception
- {
- return ( ProtocolDecoder ) decoderClass.newInstance();
- }
- };
- }
-
- public void onPreAdd( IoFilterChain parent, String name, IoFilter.NextFilter nextFilter ) throws Exception
- {
- if( parent.contains( ProtocolCodecFilter.class ) )
- {
- throw new IllegalStateException( "A filter chain cannot contain more than one QpidProtocolCodecFilter." );
- }
- }
-
- public void messageReceived( IoFilter.NextFilter nextFilter, IoSession session, Object message ) throws Exception
- {
- if( !( message instanceof ByteBuffer ) )
- {
- nextFilter.messageReceived( session, message );
- return;
- }
-
- ByteBuffer in = ( ByteBuffer ) message;
- ProtocolDecoder decoder = getDecoder( session );
- ProtocolDecoderOutput decoderOut = getDecoderOut( session, nextFilter );
-
- try
- {
- decoder.decode( session, in, decoderOut );
- }
- catch( Throwable t )
- {
- ProtocolDecoderException pde;
- if( t instanceof ProtocolDecoderException )
- {
- pde = ( ProtocolDecoderException ) t;
- }
- else
- {
- pde = new ProtocolDecoderException( t );
- }
- pde.setHexdump( in.getHexDump() );
- throw pde;
- }
- finally
- {
- // Dispose the decoder if this session is connectionless.
- if( session.getTransportType().isConnectionless() )
- {
- disposeDecoder( session );
- }
-
- // Release the read buffer.
- in.release();
-
- decoderOut.flush();
- }
- }
-
- public void messageSent( IoFilter.NextFilter nextFilter, IoSession session, Object message ) throws Exception
- {
- if( message instanceof HiddenByteBuffer )
- {
- return;
- }
-
- if( !( message instanceof MessageByteBuffer ) )
- {
- nextFilter.messageSent( session, message );
- return;
- }
-
- nextFilter.messageSent( session, ( ( MessageByteBuffer ) message ).message );
- }
-
- public void filterWrite( IoFilter.NextFilter nextFilter, IoSession session, IoFilter.WriteRequest writeRequest ) throws Exception
- {
- Object message = writeRequest.getMessage();
- if( message instanceof ByteBuffer )
- {
- nextFilter.filterWrite( session, writeRequest );
- return;
- }
-
- ProtocolEncoder encoder = getEncoder( session );
- ProtocolEncoderOutputImpl encoderOut = getEncoderOut( session, nextFilter, writeRequest );
-
- try
- {
- encoder.encode( session, message, encoderOut );
- encoderOut.flush();
- nextFilter.filterWrite(
- session,
- new IoFilter.WriteRequest(
- new MessageByteBuffer( writeRequest.getMessage() ),
- writeRequest.getFuture(), writeRequest.getDestination() ) );
- }
- catch( Throwable t )
- {
- ProtocolEncoderException pee;
- if( t instanceof ProtocolEncoderException )
- {
- pee = ( ProtocolEncoderException ) t;
- }
- else
- {
- pee = new ProtocolEncoderException( t );
- }
- throw pee;
- }
- finally
- {
- // Dispose the encoder if this session is connectionless.
- if( session.getTransportType().isConnectionless() )
- {
- disposeEncoder( session );
- }
- }
- }
-
- public void sessionClosed( IoFilter.NextFilter nextFilter, IoSession session ) throws Exception
- {
- // Call finishDecode() first when a connection is closed.
- ProtocolDecoder decoder = getDecoder( session );
- ProtocolDecoderOutput decoderOut = getDecoderOut( session, nextFilter );
- try
- {
- decoder.finishDecode( session, decoderOut );
- }
- catch( Throwable t )
- {
- ProtocolDecoderException pde;
- if( t instanceof ProtocolDecoderException )
- {
- pde = ( ProtocolDecoderException ) t;
- }
- else
- {
- pde = new ProtocolDecoderException( t );
- }
- throw pde;
- }
- finally
- {
- // Dispose all.
- disposeEncoder( session );
- disposeDecoder( session );
-
- decoderOut.flush();
- }
-
- nextFilter.sessionClosed( session );
- }
-
- private ProtocolEncoder getEncoder( IoSession session ) throws Exception
- {
- ProtocolEncoder encoder = ( ProtocolEncoder ) session.getAttribute( ENCODER );
- if( encoder == null )
- {
- encoder = factory.getEncoder();
- session.setAttribute( ENCODER, encoder );
- }
- return encoder;
- }
-
- private ProtocolEncoderOutputImpl getEncoderOut( IoSession session, IoFilter.NextFilter nextFilter, IoFilter.WriteRequest writeRequest )
- {
- return new ProtocolEncoderOutputImpl( session, nextFilter, writeRequest );
- }
-
- private ProtocolDecoder getDecoder( IoSession session ) throws Exception
- {
- ProtocolDecoder decoder = ( ProtocolDecoder ) session.getAttribute( DECODER );
- if( decoder == null )
- {
- decoder = factory.getDecoder();
- session.setAttribute( DECODER, decoder );
- }
- return decoder;
- }
-
- private ProtocolDecoderOutput getDecoderOut( IoSession session, IoFilter.NextFilter nextFilter )
- {
- return new SimpleProtocolDecoderOutput( session, nextFilter );
- }
-
- private void disposeEncoder( IoSession session )
- {
- ProtocolEncoder encoder = ( ProtocolEncoder ) session.removeAttribute( ENCODER );
- if( encoder == null )
- {
- return;
- }
-
- try
- {
- encoder.dispose( session );
- }
- catch( Throwable t )
- {
- SessionLog.warn(
- session,
- "Failed to dispose: " + encoder.getClass().getName() +
- " (" + encoder + ')' );
- }
- }
-
- private void disposeDecoder( IoSession session )
- {
- ProtocolDecoder decoder = ( ProtocolDecoder ) session.removeAttribute( DECODER );
- if( decoder == null )
- {
- return;
- }
-
- try
- {
- decoder.dispose( session );
- }
- catch( Throwable t )
- {
- SessionLog.warn(
- session,
- "Falied to dispose: " + decoder.getClass().getName() +
- " (" + decoder + ')' );
- }
- }
-
- private static class HiddenByteBuffer extends ByteBufferProxy
- {
- private HiddenByteBuffer( ByteBuffer buf )
- {
- super( buf );
- }
- }
-
- private static class MessageByteBuffer extends ByteBufferProxy
- {
- private final Object message;
-
- private MessageByteBuffer( Object message )
- {
- super( EMPTY_BUFFER );
- this.message = message;
- }
-
- public void acquire()
- {
- // no-op since we are wraping a zero-byte buffer, this instance is to just curry the message
- }
-
- public void release()
- {
- // no-op since we are wraping a zero-byte buffer, this instance is to just curry the message
- }
- }
-
- private static class ProtocolEncoderOutputImpl implements ProtocolEncoderOutput
- {
- private ByteBuffer buffer;
-
- private final IoSession session;
- private final IoFilter.NextFilter nextFilter;
- private final IoFilter.WriteRequest writeRequest;
-
- public ProtocolEncoderOutputImpl( IoSession session, IoFilter.NextFilter nextFilter, IoFilter.WriteRequest writeRequest )
- {
- this.session = session;
- this.nextFilter = nextFilter;
- this.writeRequest = writeRequest;
- }
-
-
-
- public void write( ByteBuffer buf )
- {
- if(buffer != null)
- {
- flush();
- }
- buffer = buf;
- }
-
- public void mergeAll()
- {
- }
-
- public WriteFuture flush()
- {
- WriteFuture future = null;
- if( buffer == null )
- {
- return null;
- }
- else
- {
- ByteBuffer buf = buffer;
- // Flush only when the buffer has remaining.
- if( buf.hasRemaining() )
- {
- future = doFlush( buf );
- }
-
- }
-
- return future;
- }
-
-
- protected WriteFuture doFlush( ByteBuffer buf )
- {
- WriteFuture future = new DefaultWriteFuture( session );
- nextFilter.filterWrite(
- session,
- new IoFilter.WriteRequest(
- buf,
- future, writeRequest.getDestination() ) );
- return future;
- }
- }
-}
-
diff --git a/java/common/src/main/java/org/apache/mina/transport/socket/nio/MultiThreadSocketAcceptor.java b/java/common/src/main/java/org/apache/mina/transport/socket/nio/MultiThreadSocketAcceptor.java
deleted file mode 100644
index e5360d32e0..0000000000
--- a/java/common/src/main/java/org/apache/mina/transport/socket/nio/MultiThreadSocketAcceptor.java
+++ /dev/null
@@ -1,547 +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.mina.transport.socket.nio;
-
-import java.io.IOException;
-import java.net.InetSocketAddress;
-import java.net.SocketAddress;
-import java.nio.channels.SelectionKey;
-import java.nio.channels.Selector;
-import java.nio.channels.ServerSocketChannel;
-import java.nio.channels.SocketChannel;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.apache.mina.common.ExceptionMonitor;
-import org.apache.mina.common.IoAcceptor;
-import org.apache.mina.common.IoHandler;
-import org.apache.mina.common.IoServiceConfig;
-import org.apache.mina.common.support.BaseIoAcceptor;
-import org.apache.mina.util.Queue;
-import org.apache.mina.util.NewThreadExecutor;
-import org.apache.mina.util.NamePreservingRunnable;
-import edu.emory.mathcs.backport.java.util.concurrent.Executor;
-
-/**
- * {@link IoAcceptor} for socket transport (TCP/IP).
- *
- * @author The Apache Directory Project (mina-dev@directory.apache.org)
- * @version $Rev: 619823 $, $Date: 2008-02-08 10:09:37 +0000 (Fri, 08 Feb 2008) $
- */
-public class MultiThreadSocketAcceptor extends SocketAcceptor
-{
- /**
- * @noinspection StaticNonFinalField
- */
- private static volatile int nextId = 0;
-
- private final Executor executor;
- private final Object lock = new Object();
- private final int id = nextId ++;
- private final String threadName = "SocketAcceptor-" + id;
- private final Map channels = new HashMap();
-
- private final Queue registerQueue = new Queue();
- private final Queue cancelQueue = new Queue();
-
- private final MultiThreadSocketIoProcessor[] ioProcessors;
- private final int processorCount;
-
- /**
- * @noinspection FieldAccessedSynchronizedAndUnsynchronized
- */
- private Selector selector;
- private Worker worker;
- private int processorDistributor = 0;
-
- /**
- * Create an acceptor with a single processing thread using a NewThreadExecutor
- */
- public MultiThreadSocketAcceptor()
- {
- this( 1, new NewThreadExecutor() );
- }
-
- /**
- * Create an acceptor with the desired number of processing threads
- *
- * @param processorCount Number of processing threads
- * @param executor Executor to use for launching threads
- */
- public MultiThreadSocketAcceptor( int processorCount, Executor executor )
- {
- if( processorCount < 1 )
- {
- throw new IllegalArgumentException( "Must have at least one processor" );
- }
-
- this.executor = executor;
- this.processorCount = processorCount;
- ioProcessors = new MultiThreadSocketIoProcessor[processorCount];
-
- for( int i = 0; i < processorCount; i++ )
- {
- ioProcessors[i] = new MultiThreadSocketIoProcessor( "SocketAcceptorIoProcessor-" + id + "." + i, executor );
- }
- }
-
-
- /**
- * Binds to the specified <code>address</code> and handles incoming connections with the specified
- * <code>handler</code>. Backlog value is configured to the value of <code>backlog</code> property.
- *
- * @throws IOException if failed to bind
- */
- public void bind( SocketAddress address, IoHandler handler, IoServiceConfig config ) throws IOException
- {
- if( handler == null )
- {
- throw new NullPointerException( "handler" );
- }
-
- if( address != null && !( address instanceof InetSocketAddress ) )
- {
- throw new IllegalArgumentException( "Unexpected address type: " + address.getClass() );
- }
-
- if( config == null )
- {
- config = getDefaultConfig();
- }
-
- RegistrationRequest request = new RegistrationRequest( address, handler, config );
-
- synchronized( registerQueue )
- {
- registerQueue.push( request );
- }
-
- startupWorker();
-
- selector.wakeup();
-
- synchronized( request )
- {
- while( !request.done )
- {
- try
- {
- request.wait();
- }
- catch( InterruptedException e )
- {
- ExceptionMonitor.getInstance().exceptionCaught( e );
- }
- }
- }
-
- if( request.exception != null )
- {
- throw request.exception;
- }
- }
-
-
- private synchronized void startupWorker() throws IOException
- {
- synchronized( lock )
- {
- if( worker == null )
- {
- selector = Selector.open();
- worker = new Worker();
-
- executor.execute( new NamePreservingRunnable( worker ) );
- }
- }
- }
-
- public void unbind( SocketAddress address )
- {
- if( address == null )
- {
- throw new NullPointerException( "address" );
- }
-
- CancellationRequest request = new CancellationRequest( address );
-
- try
- {
- startupWorker();
- }
- catch( IOException e )
- {
- // IOException is thrown only when Worker thread is not
- // running and failed to open a selector. We simply throw
- // IllegalArgumentException here because we can simply
- // conclude that nothing is bound to the selector.
- throw new IllegalArgumentException( "Address not bound: " + address );
- }
-
- synchronized( cancelQueue )
- {
- cancelQueue.push( request );
- }
-
- selector.wakeup();
-
- synchronized( request )
- {
- while( !request.done )
- {
- try
- {
- request.wait();
- }
- catch( InterruptedException e )
- {
- ExceptionMonitor.getInstance().exceptionCaught( e );
- }
- }
- }
-
- if( request.exception != null )
- {
- request.exception.fillInStackTrace();
-
- throw request.exception;
- }
- }
-
-
- private class Worker implements Runnable
- {
- public void run()
- {
- Thread.currentThread().setName(MultiThreadSocketAcceptor.this.threadName );
-
- for( ; ; )
- {
- try
- {
- int nKeys = selector.select();
-
- registerNew();
-
- if( nKeys > 0 )
- {
- processSessions( selector.selectedKeys() );
- }
-
- cancelKeys();
-
- if( selector.keys().isEmpty() )
- {
- synchronized( lock )
- {
- if( selector.keys().isEmpty() &&
- registerQueue.isEmpty() &&
- cancelQueue.isEmpty() )
- {
- worker = null;
- try
- {
- selector.close();
- }
- catch( IOException e )
- {
- ExceptionMonitor.getInstance().exceptionCaught( e );
- }
- finally
- {
- selector = null;
- }
- break;
- }
- }
- }
- }
- catch( IOException e )
- {
- ExceptionMonitor.getInstance().exceptionCaught( e );
-
- try
- {
- Thread.sleep( 1000 );
- }
- catch( InterruptedException e1 )
- {
- ExceptionMonitor.getInstance().exceptionCaught( e1 );
- }
- }
- }
- }
-
- private void processSessions( Set keys ) throws IOException
- {
- Iterator it = keys.iterator();
- while( it.hasNext() )
- {
- SelectionKey key = ( SelectionKey ) it.next();
-
- it.remove();
-
- if( !key.isAcceptable() )
- {
- continue;
- }
-
- ServerSocketChannel ssc = ( ServerSocketChannel ) key.channel();
-
- SocketChannel ch = ssc.accept();
-
- if( ch == null )
- {
- continue;
- }
-
- boolean success = false;
- try
- {
-
- RegistrationRequest req = ( RegistrationRequest ) key.attachment();
-
- MultiThreadSocketSessionImpl session = new MultiThreadSocketSessionImpl(
- MultiThreadSocketAcceptor.this, nextProcessor(), getListeners(),
- req.config, ch, req.handler, req.address );
-
- // New Interface
-// SocketSessionImpl session = new SocketSessionImpl(
-// SocketAcceptor.this, nextProcessor(), getListeners(),
-// req.config, ch, req.handler, req.address );
-
-
- getFilterChainBuilder().buildFilterChain( session.getFilterChain() );
- req.config.getFilterChainBuilder().buildFilterChain( session.getFilterChain() );
- req.config.getThreadModel().buildFilterChain( session.getFilterChain() );
- session.getIoProcessor().addNew( session );
- success = true;
- }
- catch( Throwable t )
- {
- ExceptionMonitor.getInstance().exceptionCaught( t );
- }
- finally
- {
- if( !success )
- {
- ch.close();
- }
- }
- }
- }
- }
-
- private MultiThreadSocketIoProcessor nextProcessor()
- {
- return ioProcessors[processorDistributor++ % processorCount];
- }
-
-
- private void registerNew()
- {
- if( registerQueue.isEmpty() )
- {
- return;
- }
-
- for( ; ; )
- {
- RegistrationRequest req;
-
- synchronized( registerQueue )
- {
- req = ( RegistrationRequest ) registerQueue.pop();
- }
-
- if( req == null )
- {
- break;
- }
-
- ServerSocketChannel ssc = null;
-
- try
- {
- ssc = ServerSocketChannel.open();
- ssc.configureBlocking( false );
-
- // Configure the server socket,
- SocketAcceptorConfig cfg;
- if( req.config instanceof SocketAcceptorConfig )
- {
- cfg = ( SocketAcceptorConfig ) req.config;
- }
- else
- {
- cfg = ( SocketAcceptorConfig ) getDefaultConfig();
- }
-
- ssc.socket().setReuseAddress( cfg.isReuseAddress() );
- ssc.socket().setReceiveBufferSize(
- ( ( SocketSessionConfig ) cfg.getSessionConfig() ).getReceiveBufferSize() );
-
- // and bind.
- ssc.socket().bind( req.address, cfg.getBacklog() );
- if( req.address == null || req.address.getPort() == 0 )
- {
- req.address = ( InetSocketAddress ) ssc.socket().getLocalSocketAddress();
- }
- ssc.register( selector, SelectionKey.OP_ACCEPT, req );
-
- synchronized( channels )
- {
- channels.put( req.address, ssc );
- }
-
- getListeners().fireServiceActivated(
- this, req.address, req.handler, req.config );
- }
- catch( IOException e )
- {
- req.exception = e;
- }
- finally
- {
- synchronized( req )
- {
- req.done = true;
-
- req.notifyAll();
- }
-
- if( ssc != null && req.exception != null )
- {
- try
- {
- ssc.close();
- }
- catch( IOException e )
- {
- ExceptionMonitor.getInstance().exceptionCaught( e );
- }
- }
- }
- }
- }
-
-
- private void cancelKeys()
- {
- if( cancelQueue.isEmpty() )
- {
- return;
- }
-
- for( ; ; )
- {
- CancellationRequest request;
-
- synchronized( cancelQueue )
- {
- request = ( CancellationRequest ) cancelQueue.pop();
- }
-
- if( request == null )
- {
- break;
- }
-
- ServerSocketChannel ssc;
- synchronized( channels )
- {
- ssc = ( ServerSocketChannel ) channels.remove( request.address );
- }
-
- // close the channel
- try
- {
- if( ssc == null )
- {
- request.exception = new IllegalArgumentException( "Address not bound: " + request.address );
- }
- else
- {
- SelectionKey key = ssc.keyFor( selector );
- request.registrationRequest = ( RegistrationRequest ) key.attachment();
- key.cancel();
-
- selector.wakeup(); // wake up again to trigger thread death
-
- ssc.close();
- }
- }
- catch( IOException e )
- {
- ExceptionMonitor.getInstance().exceptionCaught( e );
- }
- finally
- {
- synchronized( request )
- {
- request.done = true;
- request.notifyAll();
- }
-
- if( request.exception == null )
- {
- getListeners().fireServiceDeactivated(
- this, request.address,
- request.registrationRequest.handler,
- request.registrationRequest.config );
- }
- }
- }
- }
-
- private static class RegistrationRequest
- {
- private InetSocketAddress address;
- private final IoHandler handler;
- private final IoServiceConfig config;
- private IOException exception;
- private boolean done;
-
- private RegistrationRequest( SocketAddress address, IoHandler handler, IoServiceConfig config )
- {
- this.address = ( InetSocketAddress ) address;
- this.handler = handler;
- this.config = config;
- }
- }
-
-
- private static class CancellationRequest
- {
- private final SocketAddress address;
- private boolean done;
- private RegistrationRequest registrationRequest;
- private RuntimeException exception;
-
- private CancellationRequest( SocketAddress address )
- {
- this.address = address;
- }
- }
-}
diff --git a/java/common/src/main/java/org/apache/mina/transport/socket/nio/MultiThreadSocketConnector.java b/java/common/src/main/java/org/apache/mina/transport/socket/nio/MultiThreadSocketConnector.java
deleted file mode 100644
index 7344f70078..0000000000
--- a/java/common/src/main/java/org/apache/mina/transport/socket/nio/MultiThreadSocketConnector.java
+++ /dev/null
@@ -1,486 +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.mina.transport.socket.nio;
-
-import edu.emory.mathcs.backport.java.util.concurrent.Executor;
-import org.apache.mina.common.ConnectFuture;
-import org.apache.mina.common.ExceptionMonitor;
-import org.apache.mina.common.IoConnector;
-import org.apache.mina.common.IoConnectorConfig;
-import org.apache.mina.common.IoHandler;
-import org.apache.mina.common.IoServiceConfig;
-import org.apache.mina.common.support.AbstractIoFilterChain;
-import org.apache.mina.common.support.DefaultConnectFuture;
-import org.apache.mina.util.NamePreservingRunnable;
-import org.apache.mina.util.NewThreadExecutor;
-import org.apache.mina.util.Queue;
-
-import java.io.IOException;
-import java.net.ConnectException;
-import java.net.InetSocketAddress;
-import java.net.SocketAddress;
-import java.nio.channels.SelectionKey;
-import java.nio.channels.Selector;
-import java.nio.channels.SocketChannel;
-import java.util.Iterator;
-import java.util.Set;
-
-/**
- * {@link IoConnector} for socket transport (TCP/IP).
- *
- * @author The Apache Directory Project (mina-dev@directory.apache.org)
- * @version $Rev: 619823 $, $Date: 2008-02-08 10:09:37 +0000 (Fri, 08 Feb 2008) $
- */
-public class MultiThreadSocketConnector extends SocketConnector
-{
- /** @noinspection StaticNonFinalField */
- private static volatile int nextId = 0;
-
- private final Object lock = new Object();
- private final int id = nextId++;
- private final String threadName = "SocketConnector-" + id;
-
- private final Queue connectQueue = new Queue();
- private final MultiThreadSocketIoProcessor[] ioProcessors;
- private final int processorCount;
- private final Executor executor;
-
- /** @noinspection FieldAccessedSynchronizedAndUnsynchronized */
- private Selector selector;
- private Worker worker;
- private int processorDistributor = 0;
- private int workerTimeout = 60; // 1 min.
-
- /** Create a connector with a single processing thread using a NewThreadExecutor */
- public MultiThreadSocketConnector()
- {
- this(1, new NewThreadExecutor());
- }
-
- /**
- * Create a connector with the desired number of processing threads
- *
- * @param processorCount Number of processing threads
- * @param executor Executor to use for launching threads
- */
- public MultiThreadSocketConnector(int processorCount, Executor executor)
- {
- if (processorCount < 1)
- {
- throw new IllegalArgumentException("Must have at least one processor");
- }
-
- this.executor = executor;
- this.processorCount = processorCount;
- ioProcessors = new MultiThreadSocketIoProcessor[processorCount];
-
- for (int i = 0; i < processorCount; i++)
- {
- ioProcessors[i] = new MultiThreadSocketIoProcessor("SocketConnectorIoProcessor-" + id + "." + i, executor);
- }
- }
-
- /**
- * How many seconds to keep the connection thread alive between connection requests
- *
- * @return Number of seconds to keep connection thread alive
- */
- public int getWorkerTimeout()
- {
- return workerTimeout;
- }
-
- /**
- * Set how many seconds the connection worker thread should remain alive once idle before terminating itself.
- *
- * @param workerTimeout Number of seconds to keep thread alive. Must be >=0
- */
- public void setWorkerTimeout(int workerTimeout)
- {
- if (workerTimeout < 0)
- {
- throw new IllegalArgumentException("Must be >= 0");
- }
- this.workerTimeout = workerTimeout;
- }
-
- public ConnectFuture connect(SocketAddress address, IoHandler handler, IoServiceConfig config)
- {
- return connect(address, null, handler, config);
- }
-
- public ConnectFuture connect(SocketAddress address, SocketAddress localAddress,
- IoHandler handler, IoServiceConfig config)
- {
- if (address == null)
- {
- throw new NullPointerException("address");
- }
- if (handler == null)
- {
- throw new NullPointerException("handler");
- }
-
- if (!(address instanceof InetSocketAddress))
- {
- throw new IllegalArgumentException("Unexpected address type: "
- + address.getClass());
- }
-
- if (localAddress != null && !(localAddress instanceof InetSocketAddress))
- {
- throw new IllegalArgumentException("Unexpected local address type: "
- + localAddress.getClass());
- }
-
- if (config == null)
- {
- config = getDefaultConfig();
- }
-
- SocketChannel ch = null;
- boolean success = false;
- try
- {
- ch = SocketChannel.open();
- ch.socket().setReuseAddress(true);
- if (localAddress != null)
- {
- ch.socket().bind(localAddress);
- }
-
- ch.configureBlocking(false);
-
- if (ch.connect(address))
- {
- DefaultConnectFuture future = new DefaultConnectFuture();
- newSession(ch, handler, config, future);
- success = true;
- return future;
- }
-
- success = true;
- }
- catch (IOException e)
- {
- return DefaultConnectFuture.newFailedFuture(e);
- }
- finally
- {
- if (!success && ch != null)
- {
- try
- {
- ch.close();
- }
- catch (IOException e)
- {
- ExceptionMonitor.getInstance().exceptionCaught(e);
- }
- }
- }
-
- ConnectionRequest request = new ConnectionRequest(ch, handler, config);
- synchronized (lock)
- {
- try
- {
- startupWorker();
- }
- catch (IOException e)
- {
- try
- {
- ch.close();
- }
- catch (IOException e2)
- {
- ExceptionMonitor.getInstance().exceptionCaught(e2);
- }
-
- return DefaultConnectFuture.newFailedFuture(e);
- }
- }
-
- synchronized (connectQueue)
- {
- connectQueue.push(request);
- }
- selector.wakeup();
-
- return request;
- }
-
- private synchronized void startupWorker() throws IOException
- {
- if (worker == null)
- {
- selector = Selector.open();
- worker = new Worker();
- executor.execute(new NamePreservingRunnable(worker));
- }
- }
-
- private void registerNew()
- {
- if (connectQueue.isEmpty())
- {
- return;
- }
-
- for (; ;)
- {
- ConnectionRequest req;
- synchronized (connectQueue)
- {
- req = (ConnectionRequest) connectQueue.pop();
- }
-
- if (req == null)
- {
- break;
- }
-
- SocketChannel ch = req.channel;
- try
- {
- ch.register(selector, SelectionKey.OP_CONNECT, req);
- }
- catch (IOException e)
- {
- req.setException(e);
- }
- }
- }
-
- private void processSessions(Set keys)
- {
- Iterator it = keys.iterator();
-
- while (it.hasNext())
- {
- SelectionKey key = (SelectionKey) it.next();
-
- if (!key.isConnectable())
- {
- continue;
- }
-
- SocketChannel ch = (SocketChannel) key.channel();
- ConnectionRequest entry = (ConnectionRequest) key.attachment();
-
- boolean success = false;
- try
- {
- ch.finishConnect();
- newSession(ch, entry.handler, entry.config, entry);
- success = true;
- }
- catch (Throwable e)
- {
- entry.setException(e);
- }
- finally
- {
- key.cancel();
- if (!success)
- {
- try
- {
- ch.close();
- }
- catch (IOException e)
- {
- ExceptionMonitor.getInstance().exceptionCaught(e);
- }
- }
- }
- }
-
- keys.clear();
- }
-
- private void processTimedOutSessions(Set keys)
- {
- long currentTime = System.currentTimeMillis();
- Iterator it = keys.iterator();
-
- while (it.hasNext())
- {
- SelectionKey key = (SelectionKey) it.next();
-
- if (!key.isValid())
- {
- continue;
- }
-
- ConnectionRequest entry = (ConnectionRequest) key.attachment();
-
- if (currentTime >= entry.deadline)
- {
- entry.setException(new ConnectException());
- try
- {
- key.channel().close();
- }
- catch (IOException e)
- {
- ExceptionMonitor.getInstance().exceptionCaught(e);
- }
- finally
- {
- key.cancel();
- }
- }
- }
- }
-
- private void newSession(SocketChannel ch, IoHandler handler, IoServiceConfig config, ConnectFuture connectFuture)
- throws IOException
- {
- MultiThreadSocketSessionImpl session =
- new MultiThreadSocketSessionImpl(this, nextProcessor(), getListeners(),
- config, ch, handler, ch.socket().getRemoteSocketAddress());
-
- //new interface
-// SocketSessionImpl session = new SocketSessionImpl(
-// this, nextProcessor(), getListeners(),
-// config, ch, handler, ch.socket().getRemoteSocketAddress() );
- try
- {
- getFilterChainBuilder().buildFilterChain(session.getFilterChain());
- config.getFilterChainBuilder().buildFilterChain(session.getFilterChain());
- config.getThreadModel().buildFilterChain(session.getFilterChain());
- }
- catch (Throwable e)
- {
- throw (IOException) new IOException("Failed to create a session.").initCause(e);
- }
-
- // Set the ConnectFuture of the specified session, which will be
- // removed and notified by AbstractIoFilterChain eventually.
- session.setAttribute( AbstractIoFilterChain.CONNECT_FUTURE, connectFuture );
-
- // Forward the remaining process to the SocketIoProcessor.
- session.getIoProcessor().addNew(session);
- }
-
- private MultiThreadSocketIoProcessor nextProcessor()
- {
- return ioProcessors[processorDistributor++ % processorCount];
- }
-
- private class Worker implements Runnable
- {
- private long lastActive = System.currentTimeMillis();
-
- public void run()
- {
- Thread.currentThread().setName(MultiThreadSocketConnector.this.threadName);
-
- for (; ;)
- {
- try
- {
- int nKeys = selector.select(1000);
-
- registerNew();
-
- if (nKeys > 0)
- {
- processSessions(selector.selectedKeys());
- }
-
- processTimedOutSessions(selector.keys());
-
- if (selector.keys().isEmpty())
- {
- if (System.currentTimeMillis() - lastActive > workerTimeout * 1000L)
- {
- synchronized (lock)
- {
- if (selector.keys().isEmpty() &&
- connectQueue.isEmpty())
- {
- worker = null;
- try
- {
- selector.close();
- }
- catch (IOException e)
- {
- ExceptionMonitor.getInstance().exceptionCaught(e);
- }
- finally
- {
- selector = null;
- }
- break;
- }
- }
- }
- }
- else
- {
- lastActive = System.currentTimeMillis();
- }
- }
- catch (IOException e)
- {
- ExceptionMonitor.getInstance().exceptionCaught(e);
-
- try
- {
- Thread.sleep(1000);
- }
- catch (InterruptedException e1)
- {
- ExceptionMonitor.getInstance().exceptionCaught(e1);
- }
- }
- }
- }
- }
-
- private class ConnectionRequest extends DefaultConnectFuture
- {
- private final SocketChannel channel;
- private final long deadline;
- private final IoHandler handler;
- private final IoServiceConfig config;
-
- private ConnectionRequest(SocketChannel channel, IoHandler handler, IoServiceConfig config)
- {
- this.channel = channel;
- long timeout;
- if (config instanceof IoConnectorConfig)
- {
- timeout = ((IoConnectorConfig) config).getConnectTimeoutMillis();
- }
- else
- {
- timeout = ((IoConnectorConfig) getDefaultConfig()).getConnectTimeoutMillis();
- }
- this.deadline = System.currentTimeMillis() + timeout;
- this.handler = handler;
- this.config = config;
- }
- }
-}
diff --git a/java/common/src/main/java/org/apache/mina/transport/socket/nio/MultiThreadSocketFilterChain.java b/java/common/src/main/java/org/apache/mina/transport/socket/nio/MultiThreadSocketFilterChain.java
deleted file mode 100644
index 67b8c8d820..0000000000
--- a/java/common/src/main/java/org/apache/mina/transport/socket/nio/MultiThreadSocketFilterChain.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.mina.transport.socket.nio;
-
-import java.io.IOException;
-
-import org.apache.mina.common.ByteBuffer;
-import org.apache.mina.common.IoFilterChain;
-import org.apache.mina.common.IoSession;
-import org.apache.mina.common.IoFilter.WriteRequest;
-import org.apache.mina.common.support.AbstractIoFilterChain;
-import org.apache.mina.util.Queue;
-
-/**
- * An {@link IoFilterChain} for socket transport (TCP/IP).
- *
- * @author The Apache Directory Project (mina-dev@directory.apache.org)
- */
-class MultiThreadSocketFilterChain extends AbstractIoFilterChain {
-
- MultiThreadSocketFilterChain( IoSession parent )
- {
- super( parent );
- }
-
- protected void doWrite( IoSession session, WriteRequest writeRequest )
- {
- MultiThreadSocketSessionImpl s = (MultiThreadSocketSessionImpl) session;
- Queue writeRequestQueue = s.getWriteRequestQueue();
-
- // SocketIoProcessor.doFlush() will reset it after write is finished
- // because the buffer will be passed with messageSent event.
- ( ( ByteBuffer ) writeRequest.getMessage() ).mark();
- synchronized( writeRequestQueue )
- {
- writeRequestQueue.push( writeRequest );
- if( writeRequestQueue.size() == 1 && session.getTrafficMask().isWritable() )
- {
- // Notify SocketIoProcessor only when writeRequestQueue was empty.
- s.getIoProcessor().flush( s );
- }
- }
- }
-
- protected void doClose( IoSession session ) throws IOException
- {
- MultiThreadSocketSessionImpl s = (MultiThreadSocketSessionImpl) session;
- s.getIoProcessor().remove( s );
- }
-}
diff --git a/java/common/src/main/java/org/apache/mina/transport/socket/nio/MultiThreadSocketIoProcessor.java b/java/common/src/main/java/org/apache/mina/transport/socket/nio/MultiThreadSocketIoProcessor.java
deleted file mode 100644
index c23ad8686f..0000000000
--- a/java/common/src/main/java/org/apache/mina/transport/socket/nio/MultiThreadSocketIoProcessor.java
+++ /dev/null
@@ -1,1026 +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.mina.transport.socket.nio;
-
-import edu.emory.mathcs.backport.java.util.concurrent.Executor;
-import edu.emory.mathcs.backport.java.util.concurrent.locks.ReentrantLock;
-import org.apache.mina.common.ByteBuffer;
-import org.apache.mina.common.ExceptionMonitor;
-import org.apache.mina.common.IdleStatus;
-import org.apache.mina.common.IoFilter.WriteRequest;
-import org.apache.mina.common.WriteTimeoutException;
-import org.apache.mina.util.IdentityHashSet;
-import org.apache.mina.util.NamePreservingRunnable;
-import org.apache.mina.util.Queue;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.io.IOException;
-import java.nio.channels.SelectionKey;
-import java.nio.channels.Selector;
-import java.nio.channels.SocketChannel;
-import java.util.Iterator;
-import java.util.Set;
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.LinkedBlockingQueue;
-
-/**
- * Performs all I/O operations for sockets which is connected or bound. This class is used by MINA internally.
- *
- * @author The Apache Directory Project (mina-dev@directory.apache.org)
- * @version $Rev: 619823 $, $Date: 2008-02-08 10:09:37 +0000 (Fri, 08 Feb 2008) $,
- */
-class MultiThreadSocketIoProcessor extends SocketIoProcessor
-{
- Logger _logger = LoggerFactory.getLogger(MultiThreadSocketIoProcessor.class);
- Logger _loggerRead = LoggerFactory.getLogger(MultiThreadSocketIoProcessor.class + ".Reader");
- Logger _loggerWrite = LoggerFactory.getLogger(MultiThreadSocketIoProcessor.class + ".Writer");
-
- private static final long SELECTOR_TIMEOUT = 1000L;
-
- private int MAX_READ_BYTES_PER_SESSION = 524288; //512K
- private int MAX_FLUSH_BYTES_PER_SESSION = 524288; //512K
-
- private final Object readLock = new Object();
- private final Object writeLock = new Object();
-
- private final String threadName;
- private final Executor executor;
-
- private ReentrantLock trafficMaskUpdateLock = new ReentrantLock();
-
- /** @noinspection FieldAccessedSynchronizedAndUnsynchronized */
- private volatile Selector selector, writeSelector;
-
- private final Queue newSessions = new Queue();
- private final Queue removingSessions = new Queue();
- private final BlockingQueue flushingSessions = new LinkedBlockingQueue();
- private final IdentityHashSet flushingSessionsSet = new IdentityHashSet();
-
- private final Queue trafficControllingSessions = new Queue();
-
- private ReadWorker readWorker;
- private WriteWorker writeWorker;
- private long lastIdleReadCheckTime = System.currentTimeMillis();
- private long lastIdleWriteCheckTime = System.currentTimeMillis();
-
- MultiThreadSocketIoProcessor(String threadName, Executor executor)
- {
- super(threadName, executor);
- this.threadName = threadName;
- this.executor = executor;
- }
-
- void addNew(SocketSessionImpl session) throws IOException
- {
- synchronized (newSessions)
- {
- newSessions.push(session);
- }
-
- startupWorker();
-
- selector.wakeup();
- writeSelector.wakeup();
- }
-
- void remove(SocketSessionImpl session) throws IOException
- {
- scheduleRemove(session);
- startupWorker();
- selector.wakeup();
- }
-
- private void startupWorker() throws IOException
- {
- synchronized (readLock)
- {
- if (readWorker == null)
- {
- selector = Selector.open();
- readWorker = new ReadWorker();
- executor.execute(new NamePreservingRunnable(readWorker));
- }
- }
-
- synchronized (writeLock)
- {
- if (writeWorker == null)
- {
- writeSelector = Selector.open();
- writeWorker = new WriteWorker();
- executor.execute(new NamePreservingRunnable(writeWorker));
- }
- }
-
- }
-
- void flush(SocketSessionImpl session)
- {
- scheduleFlush(session);
- Selector selector = this.writeSelector;
-
- if (selector != null)
- {
- selector.wakeup();
- }
- }
-
- void updateTrafficMask(SocketSessionImpl session)
- {
- scheduleTrafficControl(session);
- Selector selector = this.selector;
- if (selector != null)
- {
- selector.wakeup();
- }
- }
-
- private void scheduleRemove(SocketSessionImpl session)
- {
- synchronized (removingSessions)
- {
- removingSessions.push(session);
- }
- }
-
- private void scheduleFlush(SocketSessionImpl session)
- {
- synchronized (flushingSessionsSet)
- {
- //if flushingSessions grows to contain Integer.MAX_VALUE sessions
- // then this will fail.
- if (flushingSessionsSet.add(session))
- {
- flushingSessions.offer(session);
- }
- }
- }
-
- private void scheduleTrafficControl(SocketSessionImpl session)
- {
- synchronized (trafficControllingSessions)
- {
- trafficControllingSessions.push(session);
- }
- }
-
- private void doAddNewReader() throws InterruptedException
- {
- if (newSessions.isEmpty())
- {
- return;
- }
-
- for (; ;)
- {
- MultiThreadSocketSessionImpl session;
-
- synchronized (newSessions)
- {
- session = (MultiThreadSocketSessionImpl) newSessions.peek();
- }
-
- if (session == null)
- {
- break;
- }
-
- SocketChannel ch = session.getChannel();
-
-
- try
- {
-
- ch.configureBlocking(false);
- session.setSelectionKey(ch.register(selector,
- SelectionKey.OP_READ,
- session));
-
- //System.out.println("ReadDebug:"+"Awaiting Registration");
- session.awaitRegistration();
- sessionCreated(session);
- }
- catch (IOException e)
- {
- // Clear the AbstractIoFilterChain.CONNECT_FUTURE attribute
- // and call ConnectFuture.setException().
- session.getFilterChain().fireExceptionCaught(session, e);
- }
- }
- }
-
-
- private void doAddNewWrite() throws InterruptedException
- {
- if (newSessions.isEmpty())
- {
- return;
- }
-
- for (; ;)
- {
- MultiThreadSocketSessionImpl session;
-
- synchronized (newSessions)
- {
- session = (MultiThreadSocketSessionImpl) newSessions.peek();
- }
-
- if (session == null)
- {
- break;
- }
-
- SocketChannel ch = session.getChannel();
-
- try
- {
- ch.configureBlocking(false);
- synchronized (flushingSessionsSet)
- {
- flushingSessionsSet.add(session);
- }
-
- session.setWriteSelectionKey(ch.register(writeSelector,
- SelectionKey.OP_WRITE,
- session));
-
- //System.out.println("WriteDebug:"+"Awaiting Registration");
- session.awaitRegistration();
- sessionCreated(session);
- }
- catch (IOException e)
- {
-
- // Clear the AbstractIoFilterChain.CONNECT_FUTURE attribute
- // and call ConnectFuture.setException().
- session.getFilterChain().fireExceptionCaught(session, e);
- }
- }
- }
-
-
- private void sessionCreated(SocketSessionImpl sessionParam) throws InterruptedException
- {
- MultiThreadSocketSessionImpl session = (MultiThreadSocketSessionImpl) sessionParam;
- synchronized (newSessions)
- {
- if (!session.created())
- {
- _logger.debug("Popping new session");
- newSessions.pop();
-
- // AbstractIoFilterChain.CONNECT_FUTURE is cleared inside here
- // in AbstractIoFilterChain.fireSessionOpened().
- session.getServiceListeners().fireSessionCreated(session);
-
- session.doneCreation();
- }
- }
- }
-
- private void doRemove()
- {
- if (removingSessions.isEmpty())
- {
- return;
- }
-
- for (; ;)
- {
- MultiThreadSocketSessionImpl session;
-
- synchronized (removingSessions)
- {
- session = (MultiThreadSocketSessionImpl) removingSessions.pop();
- }
-
- if (session == null)
- {
- break;
- }
-
- SocketChannel ch = session.getChannel();
- SelectionKey key = session.getReadSelectionKey();
- SelectionKey writeKey = session.getWriteSelectionKey();
-
- // Retry later if session is not yet fully initialized.
- // (In case that Session.close() is called before addSession() is processed)
- if (key == null || writeKey == null)
- {
- scheduleRemove(session);
- break;
- }
- // skip if channel is already closed
- if (!key.isValid() || !writeKey.isValid())
- {
- continue;
- }
-
- try
- {
- //System.out.println("ReadDebug:"+"Removing Session: " + System.identityHashCode(session));
- synchronized (readLock)
- {
- key.cancel();
- }
- synchronized (writeLock)
- {
- writeKey.cancel();
- }
- ch.close();
- }
- catch (IOException e)
- {
- session.getFilterChain().fireExceptionCaught(session, e);
- }
- finally
- {
- releaseWriteBuffers(session);
- session.getServiceListeners().fireSessionDestroyed(session);
- }
- }
- }
-
- private void processRead(Set selectedKeys)
- {
- Iterator it = selectedKeys.iterator();
-
- while (it.hasNext())
- {
- SelectionKey key = (SelectionKey) it.next();
- MultiThreadSocketSessionImpl session = (MultiThreadSocketSessionImpl) key.attachment();
-
- synchronized (readLock)
- {
- if (key.isValid() && key.isReadable() && session.getTrafficMask().isReadable())
- {
- read(session);
- }
- }
-
- }
-
- selectedKeys.clear();
- }
-
- private void processWrite(Set selectedKeys)
- {
- Iterator it = selectedKeys.iterator();
-
- while (it.hasNext())
- {
- SelectionKey key = (SelectionKey) it.next();
- SocketSessionImpl session = (SocketSessionImpl) key.attachment();
-
- synchronized (writeLock)
- {
- if (key.isValid() && key.isWritable() && session.getTrafficMask().isWritable())
- {
-
- // Clear OP_WRITE
- key.interestOps(key.interestOps() & (~SelectionKey.OP_WRITE));
-
- synchronized (flushingSessionsSet)
- {
- flushingSessions.offer(session);
- }
- }
- }
- }
-
- selectedKeys.clear();
- }
-
- private void read(SocketSessionImpl session)
- {
-
- //if (_loggerWrite.isDebugEnabled())
- {
- //System.out.println("WriteDebug:"+"Starting read for Session:" + System.identityHashCode(session));
- }
-
- int totalReadBytes = 0;
-
- while (totalReadBytes <= MAX_READ_BYTES_PER_SESSION)
- {
- ByteBuffer buf = ByteBuffer.allocate(session.getReadBufferSize());
- SocketChannel ch = session.getChannel();
-
- try
- {
- buf.clear();
-
- int readBytes = 0;
- int ret;
-
- try
- {
- while ((ret = ch.read(buf.buf())) > 0)
- {
- readBytes += ret;
- totalReadBytes += ret;
- }
- }
- finally
- {
- buf.flip();
- }
-
-
- if (readBytes > 0)
- {
- session.increaseReadBytes(readBytes);
-
- session.getFilterChain().fireMessageReceived(session, buf);
- buf = null;
- }
-
- if (ret <= 0)
- {
- if (ret == 0)
- {
- if (readBytes == session.getReadBufferSize())
- {
- continue;
- }
- }
- else
- {
- scheduleRemove(session);
- }
-
- break;
- }
- }
- catch (Throwable e)
- {
- if (e instanceof IOException)
- {
- scheduleRemove(session);
- }
- session.getFilterChain().fireExceptionCaught(session, e);
-
- //Stop Reading this session.
- return;
- }
- finally
- {
- if (buf != null)
- {
- buf.release();
- }
- }
- }//for
-
- // if (_loggerWrite.isDebugEnabled())
- {
- //System.out.println("WriteDebug:"+"Read for Session:" + System.identityHashCode(session) + " got: " + totalReadBytes);
- }
- }
-
-
- private void notifyReadIdleness()
- {
- // process idle sessions
- long currentTime = System.currentTimeMillis();
- if ((currentTime - lastIdleReadCheckTime) >= 1000)
- {
- lastIdleReadCheckTime = currentTime;
- Set keys = selector.keys();
- if (keys != null)
- {
- for (Iterator it = keys.iterator(); it.hasNext();)
- {
- SelectionKey key = (SelectionKey) it.next();
- SocketSessionImpl session = (SocketSessionImpl) key.attachment();
- notifyReadIdleness(session, currentTime);
- }
- }
- }
- }
-
- private void notifyWriteIdleness()
- {
- // process idle sessions
- long currentTime = System.currentTimeMillis();
- if ((currentTime - lastIdleWriteCheckTime) >= 1000)
- {
- lastIdleWriteCheckTime = currentTime;
- Set keys = writeSelector.keys();
- if (keys != null)
- {
- for (Iterator it = keys.iterator(); it.hasNext();)
- {
- SelectionKey key = (SelectionKey) it.next();
- SocketSessionImpl session = (SocketSessionImpl) key.attachment();
- notifyWriteIdleness(session, currentTime);
- }
- }
- }
- }
-
- private void notifyReadIdleness(SocketSessionImpl session, long currentTime)
- {
- notifyIdleness0(
- session, currentTime,
- session.getIdleTimeInMillis(IdleStatus.BOTH_IDLE),
- IdleStatus.BOTH_IDLE,
- Math.max(session.getLastIoTime(), session.getLastIdleTime(IdleStatus.BOTH_IDLE)));
- notifyIdleness0(
- session, currentTime,
- session.getIdleTimeInMillis(IdleStatus.READER_IDLE),
- IdleStatus.READER_IDLE,
- Math.max(session.getLastReadTime(), session.getLastIdleTime(IdleStatus.READER_IDLE)));
-
- notifyWriteTimeout(session, currentTime, session
- .getWriteTimeoutInMillis(), session.getLastWriteTime());
- }
-
- private void notifyWriteIdleness(SocketSessionImpl session, long currentTime)
- {
- notifyIdleness0(
- session, currentTime,
- session.getIdleTimeInMillis(IdleStatus.BOTH_IDLE),
- IdleStatus.BOTH_IDLE,
- Math.max(session.getLastIoTime(), session.getLastIdleTime(IdleStatus.BOTH_IDLE)));
- notifyIdleness0(
- session, currentTime,
- session.getIdleTimeInMillis(IdleStatus.WRITER_IDLE),
- IdleStatus.WRITER_IDLE,
- Math.max(session.getLastWriteTime(), session.getLastIdleTime(IdleStatus.WRITER_IDLE)));
-
- notifyWriteTimeout(session, currentTime, session
- .getWriteTimeoutInMillis(), session.getLastWriteTime());
- }
-
- private void notifyIdleness0(SocketSessionImpl session, long currentTime,
- long idleTime, IdleStatus status,
- long lastIoTime)
- {
- if (idleTime > 0 && lastIoTime != 0
- && (currentTime - lastIoTime) >= idleTime)
- {
- session.increaseIdleCount(status);
- session.getFilterChain().fireSessionIdle(session, status);
- }
- }
-
- private void notifyWriteTimeout(SocketSessionImpl session,
- long currentTime,
- long writeTimeout, long lastIoTime)
- {
-
- MultiThreadSocketSessionImpl sesh = (MultiThreadSocketSessionImpl) session;
- SelectionKey key = sesh.getWriteSelectionKey();
-
- synchronized (writeLock)
- {
- if (writeTimeout > 0
- && (currentTime - lastIoTime) >= writeTimeout
- && key != null && key.isValid()
- && (key.interestOps() & SelectionKey.OP_WRITE) != 0)
- {
- session.getFilterChain().fireExceptionCaught(session, new WriteTimeoutException());
- }
- }
- }
-
- private SocketSessionImpl getNextFlushingSession()
- {
- return (SocketSessionImpl) flushingSessions.poll();
- }
-
- private void releaseSession(SocketSessionImpl session)
- {
- synchronized (session.getWriteRequestQueue())
- {
- synchronized (flushingSessionsSet)
- {
- if (session.getScheduledWriteRequests() > 0)
- {
- if (_loggerWrite.isDebugEnabled())
- {
- //System.out.println("WriteDebug:"+"Reflush" + System.identityHashCode(session));
- }
- flushingSessions.offer(session);
- }
- else
- {
- if (_loggerWrite.isDebugEnabled())
- {
- //System.out.println("WriteDebug:"+"Releasing session " + System.identityHashCode(session));
- }
- flushingSessionsSet.remove(session);
- }
- }
- }
- }
-
- private void releaseWriteBuffers(SocketSessionImpl session)
- {
- Queue writeRequestQueue = session.getWriteRequestQueue();
- WriteRequest req;
-
- //Should this be synchronized?
- synchronized (writeRequestQueue)
- {
- while ((req = (WriteRequest) writeRequestQueue.pop()) != null)
- {
- try
- {
- ((ByteBuffer) req.getMessage()).release();
- }
- catch (IllegalStateException e)
- {
- session.getFilterChain().fireExceptionCaught(session, e);
- }
- finally
- {
- req.getFuture().setWritten(false);
- }
- }
- }
- }
-
- private void doFlush()
- {
- MultiThreadSocketSessionImpl session;
-
- while ((session = (MultiThreadSocketSessionImpl) getNextFlushingSession()) != null)
- {
- if (!session.isConnected())
- {
- releaseWriteBuffers(session);
- releaseSession(session);
- continue;
- }
-
- SelectionKey key = session.getWriteSelectionKey();
- // Retry later if session is not yet fully initialized.
- // (In case that Session.write() is called before addSession() is processed)
- if (key == null)
- {
- scheduleFlush(session);
- releaseSession(session);
- continue;
- }
- // skip if channel is already closed
- if (!key.isValid())
- {
- releaseSession(session);
- continue;
- }
-
- try
- {
- if (doFlush(session))
- {
- releaseSession(session);
- }
- }
- catch (IOException e)
- {
- releaseSession(session);
- scheduleRemove(session);
- session.getFilterChain().fireExceptionCaught(session, e);
- }
-
- }
-
- }
-
- private boolean doFlush(SocketSessionImpl sessionParam) throws IOException
- {
- MultiThreadSocketSessionImpl session = (MultiThreadSocketSessionImpl) sessionParam;
- // Clear OP_WRITE
- SelectionKey key = session.getWriteSelectionKey();
- synchronized (writeLock)
- {
- key.interestOps(key.interestOps() & (~SelectionKey.OP_WRITE));
- }
- SocketChannel ch = session.getChannel();
- Queue writeRequestQueue = session.getWriteRequestQueue();
-
- long totalFlushedBytes = 0;
- while (true)
- {
- WriteRequest req;
-
- synchronized (writeRequestQueue)
- {
- req = (WriteRequest) writeRequestQueue.first();
- }
-
- if (req == null)
- {
- break;
- }
-
- ByteBuffer buf = (ByteBuffer) req.getMessage();
- if (buf.remaining() == 0)
- {
- synchronized (writeRequestQueue)
- {
- writeRequestQueue.pop();
- }
-
- session.increaseWrittenMessages();
-
- buf.reset();
- session.getFilterChain().fireMessageSent(session, req);
- continue;
- }
-
-
- int writtenBytes = 0;
-
- // Reported as DIRMINA-362
- //note: todo: fixme: Not sure it is important but if we see NoyYetConnected exceptions or 100% CPU in the kernel then this is it.
- if (key.isWritable())
- {
- writtenBytes = ch.write(buf.buf());
- totalFlushedBytes += writtenBytes;
- }
-
- if (writtenBytes > 0)
- {
- session.increaseWrittenBytes(writtenBytes);
- }
-
- if (buf.hasRemaining() || (totalFlushedBytes <= MAX_FLUSH_BYTES_PER_SESSION))
- {
- // Kernel buffer is full
- synchronized (writeLock)
- {
- key.interestOps(key.interestOps() | SelectionKey.OP_WRITE);
- }
- if (_loggerWrite.isDebugEnabled())
- {
- //System.out.println("WriteDebug:"+"Written BF: " + (session.getWrittenBytes() - totalFlushedBytes) + " bytes");
- }
- return false;
- }
- }
-
- if (_loggerWrite.isDebugEnabled())
- {
- //System.out.println("WriteDebug:"+"Written : " + (session.getWrittenBytes() - totalFlushedBytes) + " bytes");
- }
- return true;
- }
-
- private void doUpdateTrafficMask()
- {
- if (trafficControllingSessions.isEmpty() || trafficMaskUpdateLock.isLocked())
- {
- return;
- }
-
- // Synchronize over entire operation as this method should be called
- // from both read and write thread and we don't want the order of the
- // updates to get changed.
- trafficMaskUpdateLock.lock();
- try
- {
- for (; ;)
- {
- MultiThreadSocketSessionImpl session;
-
- session = (MultiThreadSocketSessionImpl) trafficControllingSessions.pop();
-
- if (session == null)
- {
- break;
- }
-
- SelectionKey key = session.getReadSelectionKey();
- // Retry later if session is not yet fully initialized.
- // (In case that Session.suspend??() or session.resume??() is
- // called before addSession() is processed)
- if (key == null)
- {
- scheduleTrafficControl(session);
- break;
- }
- // skip if channel is already closed
- if (!key.isValid())
- {
- continue;
- }
-
- // The normal is OP_READ and, if there are write requests in the
- // session's write queue, set OP_WRITE to trigger flushing.
-
- //Sset to Read and Write if there is nothing then the cost
- // is one loop through the flusher.
- int ops = SelectionKey.OP_READ;
-
- // Now mask the preferred ops with the mask of the current session
- int mask = session.getTrafficMask().getInterestOps();
- synchronized (readLock)
- {
- key.interestOps(ops & mask);
- }
- //Change key to the WriteSelection Key
- key = session.getWriteSelectionKey();
- if (key != null && key.isValid())
- {
- Queue writeRequestQueue = session.getWriteRequestQueue();
- synchronized (writeRequestQueue)
- {
- if (!writeRequestQueue.isEmpty())
- {
- ops = SelectionKey.OP_WRITE;
- synchronized (writeLock)
- {
- key.interestOps(ops & mask);
- }
- }
- }
- }
- }
- }
- finally
- {
- trafficMaskUpdateLock.unlock();
- }
-
- }
-
- private class WriteWorker implements Runnable
- {
-
- public void run()
- {
- Thread.currentThread().setName(MultiThreadSocketIoProcessor.this.threadName + "Writer");
-
- //System.out.println("WriteDebug:"+"Startup");
- for (; ;)
- {
- try
- {
- int nKeys = writeSelector.select(SELECTOR_TIMEOUT);
-
- doAddNewWrite();
- doUpdateTrafficMask();
-
- if (nKeys > 0)
- {
- //System.out.println("WriteDebug:"+nKeys + " keys from writeselector");
- processWrite(writeSelector.selectedKeys());
- }
- else
- {
- //System.out.println("WriteDebug:"+"No keys from writeselector");
- }
-
- doRemove();
- notifyWriteIdleness();
-
- if (flushingSessionsSet.size() > 0)
- {
- doFlush();
- }
-
- if (writeSelector.keys().isEmpty())
- {
- synchronized (writeLock)
- {
-
- if (writeSelector.keys().isEmpty() && newSessions.isEmpty())
- {
- writeWorker = null;
- try
- {
- writeSelector.close();
- }
- catch (IOException e)
- {
- ExceptionMonitor.getInstance().exceptionCaught(e);
- }
- finally
- {
- writeSelector = null;
- }
-
- break;
- }
- }
- }
-
- }
- catch (Throwable t)
- {
- ExceptionMonitor.getInstance().exceptionCaught(t);
-
- try
- {
- Thread.sleep(1000);
- }
- catch (InterruptedException e1)
- {
- ExceptionMonitor.getInstance().exceptionCaught(e1);
- }
- }
- }
- //System.out.println("WriteDebug:"+"Shutdown");
- }
-
- }
-
- private class ReadWorker implements Runnable
- {
-
- public void run()
- {
- Thread.currentThread().setName(MultiThreadSocketIoProcessor.this.threadName + "Reader");
-
- //System.out.println("ReadDebug:"+"Startup");
- for (; ;)
- {
- try
- {
- int nKeys = selector.select(SELECTOR_TIMEOUT);
-
- doAddNewReader();
- doUpdateTrafficMask();
-
- if (nKeys > 0)
- {
- //System.out.println("ReadDebug:"+nKeys + " keys from selector");
-
- processRead(selector.selectedKeys());
- }
- else
- {
- //System.out.println("ReadDebug:"+"No keys from selector");
- }
-
-
- doRemove();
- notifyReadIdleness();
-
- if (selector.keys().isEmpty())
- {
-
- synchronized (readLock)
- {
- if (selector.keys().isEmpty() && newSessions.isEmpty())
- {
- readWorker = null;
- try
- {
- selector.close();
- }
- catch (IOException e)
- {
- ExceptionMonitor.getInstance().exceptionCaught(e);
- }
- finally
- {
- selector = null;
- }
-
- break;
- }
- }
- }
- }
- catch (Throwable t)
- {
- ExceptionMonitor.getInstance().exceptionCaught(t);
-
- try
- {
- Thread.sleep(1000);
- }
- catch (InterruptedException e1)
- {
- ExceptionMonitor.getInstance().exceptionCaught(e1);
- }
- }
- }
- //System.out.println("ReadDebug:"+"Shutdown");
- }
-
- }
-}
diff --git a/java/common/src/main/java/org/apache/mina/transport/socket/nio/MultiThreadSocketSessionConfigImpl.java b/java/common/src/main/java/org/apache/mina/transport/socket/nio/MultiThreadSocketSessionConfigImpl.java
deleted file mode 100644
index 043d4800b6..0000000000
--- a/java/common/src/main/java/org/apache/mina/transport/socket/nio/MultiThreadSocketSessionConfigImpl.java
+++ /dev/null
@@ -1,240 +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.mina.transport.socket.nio;
-
-import org.apache.mina.common.ExceptionMonitor;
-import org.apache.mina.common.IoConnectorConfig;
-import org.apache.mina.common.support.BaseIoSessionConfig;
-
-import java.io.IOException;
-import java.net.Socket;
-import java.net.SocketException;
-
-/**
- * An {@link IoConnectorConfig} for {@link SocketConnector}.
- *
- * @author The Apache Directory Project (mina-dev@directory.apache.org)
- * @version $Rev: 619823 $, $Date: 2008-02-08 10:09:37 +0000 (Fri, 08 Feb 2008) $
- */
-public class MultiThreadSocketSessionConfigImpl extends org.apache.mina.transport.socket.nio.SocketSessionConfigImpl
-{
- private static boolean SET_RECEIVE_BUFFER_SIZE_AVAILABLE = false;
- private static boolean SET_SEND_BUFFER_SIZE_AVAILABLE = false;
- private static boolean GET_TRAFFIC_CLASS_AVAILABLE = false;
- private static boolean SET_TRAFFIC_CLASS_AVAILABLE = false;
-
- private static boolean DEFAULT_REUSE_ADDRESS;
- private static int DEFAULT_RECEIVE_BUFFER_SIZE;
- private static int DEFAULT_SEND_BUFFER_SIZE;
- private static int DEFAULT_TRAFFIC_CLASS;
- private static boolean DEFAULT_KEEP_ALIVE;
- private static boolean DEFAULT_OOB_INLINE;
- private static int DEFAULT_SO_LINGER;
- private static boolean DEFAULT_TCP_NO_DELAY;
-
- static
- {
- initialize();
- }
-
- private static void initialize()
- {
- Socket socket = null;
-
- socket = new Socket();
-
- try
- {
- DEFAULT_REUSE_ADDRESS = socket.getReuseAddress();
- DEFAULT_RECEIVE_BUFFER_SIZE = socket.getReceiveBufferSize();
- DEFAULT_SEND_BUFFER_SIZE = socket.getSendBufferSize();
- DEFAULT_KEEP_ALIVE = socket.getKeepAlive();
- DEFAULT_OOB_INLINE = socket.getOOBInline();
- DEFAULT_SO_LINGER = socket.getSoLinger();
- DEFAULT_TCP_NO_DELAY = socket.getTcpNoDelay();
-
- // Check if setReceiveBufferSize is supported.
- try
- {
- socket.setReceiveBufferSize(DEFAULT_RECEIVE_BUFFER_SIZE);
- SET_RECEIVE_BUFFER_SIZE_AVAILABLE = true;
- }
- catch( SocketException e )
- {
- SET_RECEIVE_BUFFER_SIZE_AVAILABLE = false;
- }
-
- // Check if setSendBufferSize is supported.
- try
- {
- socket.setSendBufferSize(DEFAULT_SEND_BUFFER_SIZE);
- SET_SEND_BUFFER_SIZE_AVAILABLE = true;
- }
- catch( SocketException e )
- {
- SET_SEND_BUFFER_SIZE_AVAILABLE = false;
- }
-
- // Check if getTrafficClass is supported.
- try
- {
- DEFAULT_TRAFFIC_CLASS = socket.getTrafficClass();
- GET_TRAFFIC_CLASS_AVAILABLE = true;
- }
- catch( SocketException e )
- {
- GET_TRAFFIC_CLASS_AVAILABLE = false;
- DEFAULT_TRAFFIC_CLASS = 0;
- }
- }
- catch( SocketException e )
- {
- throw new ExceptionInInitializerError(e);
- }
- finally
- {
- if( socket != null )
- {
- try
- {
- socket.close();
- }
- catch( IOException e )
- {
- ExceptionMonitor.getInstance().exceptionCaught(e);
- }
- }
- }
- }
-
- public static boolean isSetReceiveBufferSizeAvailable() {
- return SET_RECEIVE_BUFFER_SIZE_AVAILABLE;
- }
-
- public static boolean isSetSendBufferSizeAvailable() {
- return SET_SEND_BUFFER_SIZE_AVAILABLE;
- }
-
- public static boolean isGetTrafficClassAvailable() {
- return GET_TRAFFIC_CLASS_AVAILABLE;
- }
-
- public static boolean isSetTrafficClassAvailable() {
- return SET_TRAFFIC_CLASS_AVAILABLE;
- }
-
- private boolean reuseAddress = DEFAULT_REUSE_ADDRESS;
- private int receiveBufferSize = DEFAULT_RECEIVE_BUFFER_SIZE;
- private int sendBufferSize = DEFAULT_SEND_BUFFER_SIZE;
- private int trafficClass = DEFAULT_TRAFFIC_CLASS;
- private boolean keepAlive = DEFAULT_KEEP_ALIVE;
- private boolean oobInline = DEFAULT_OOB_INLINE;
- private int soLinger = DEFAULT_SO_LINGER;
- private boolean tcpNoDelay = DEFAULT_TCP_NO_DELAY;
-
- /**
- * Creates a new instance.
- */
- MultiThreadSocketSessionConfigImpl()
- {
- }
-
- public boolean isReuseAddress()
- {
- return reuseAddress;
- }
-
- public void setReuseAddress( boolean reuseAddress )
- {
- this.reuseAddress = reuseAddress;
- }
-
- public int getReceiveBufferSize()
- {
- return receiveBufferSize;
- }
-
- public void setReceiveBufferSize( int receiveBufferSize )
- {
- this.receiveBufferSize = receiveBufferSize;
- }
-
- public int getSendBufferSize()
- {
- return sendBufferSize;
- }
-
- public void setSendBufferSize( int sendBufferSize )
- {
- this.sendBufferSize = sendBufferSize;
- }
-
- public int getTrafficClass()
- {
- return trafficClass;
- }
-
- public void setTrafficClass( int trafficClass )
- {
- this.trafficClass = trafficClass;
- }
-
- public boolean isKeepAlive()
- {
- return keepAlive;
- }
-
- public void setKeepAlive( boolean keepAlive )
- {
- this.keepAlive = keepAlive;
- }
-
- public boolean isOobInline()
- {
- return oobInline;
- }
-
- public void setOobInline( boolean oobInline )
- {
- this.oobInline = oobInline;
- }
-
- public int getSoLinger()
- {
- return soLinger;
- }
-
- public void setSoLinger( int soLinger )
- {
- this.soLinger = soLinger;
- }
-
- public boolean isTcpNoDelay()
- {
- return tcpNoDelay;
- }
-
- public void setTcpNoDelay( boolean tcpNoDelay )
- {
- this.tcpNoDelay = tcpNoDelay;
- }
-
-
-}
diff --git a/java/common/src/main/java/org/apache/mina/transport/socket/nio/MultiThreadSocketSessionImpl.java b/java/common/src/main/java/org/apache/mina/transport/socket/nio/MultiThreadSocketSessionImpl.java
deleted file mode 100644
index be4a2d289d..0000000000
--- a/java/common/src/main/java/org/apache/mina/transport/socket/nio/MultiThreadSocketSessionImpl.java
+++ /dev/null
@@ -1,488 +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.mina.transport.socket.nio;
-
-import org.apache.mina.common.IoFilter.WriteRequest;
-import org.apache.mina.common.IoFilterChain;
-import org.apache.mina.common.IoHandler;
-import org.apache.mina.common.IoService;
-import org.apache.mina.common.IoServiceConfig;
-import org.apache.mina.common.IoSession;
-import org.apache.mina.common.IoSessionConfig;
-import org.apache.mina.common.RuntimeIOException;
-import org.apache.mina.common.TransportType;
-import org.apache.mina.common.support.BaseIoSessionConfig;
-import org.apache.mina.common.support.IoServiceListenerSupport;
-import org.apache.mina.util.Queue;
-
-import java.net.SocketAddress;
-import java.net.SocketException;
-import java.nio.channels.SelectionKey;
-import java.nio.channels.SocketChannel;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-/**
- * An {@link IoSession} for socket transport (TCP/IP).
- *
- * @author The Apache Directory Project (mina-dev@directory.apache.org)
- * @version $Rev: 619823 $, $Date: 2008-02-08 10:09:37 +0000 (Fri, 08 Feb 2008) $
- */
-class MultiThreadSocketSessionImpl extends SocketSessionImpl
-{
- private final IoService manager;
- private final IoServiceConfig serviceConfig;
- private final SocketSessionConfig config = new SessionConfigImpl();
- private final MultiThreadSocketIoProcessor ioProcessor;
- private final MultiThreadSocketFilterChain filterChain;
- private final SocketChannel ch;
- private final Queue writeRequestQueue;
- private final IoHandler handler;
- private final SocketAddress remoteAddress;
- private final SocketAddress localAddress;
- private final SocketAddress serviceAddress;
- private final IoServiceListenerSupport serviceListeners;
- private SelectionKey readKey, writeKey;
- private int readBufferSize;
- private CountDownLatch registeredReadyLatch = new CountDownLatch(2);
- private AtomicBoolean created = new AtomicBoolean(false);
-
- /**
- * Creates a new instance.
- */
- MultiThreadSocketSessionImpl( IoService manager,
- SocketIoProcessor ioProcessor,
- IoServiceListenerSupport listeners,
- IoServiceConfig serviceConfig,
- SocketChannel ch,
- IoHandler defaultHandler,
- SocketAddress serviceAddress )
- {
- super(manager, ioProcessor, listeners, serviceConfig, ch,defaultHandler,serviceAddress);
- this.manager = manager;
- this.serviceListeners = listeners;
- this.ioProcessor = (MultiThreadSocketIoProcessor) ioProcessor;
- this.filterChain = new MultiThreadSocketFilterChain(this);
- this.ch = ch;
- this.writeRequestQueue = new Queue();
- this.handler = defaultHandler;
- this.remoteAddress = ch.socket().getRemoteSocketAddress();
- this.localAddress = ch.socket().getLocalSocketAddress();
- this.serviceAddress = serviceAddress;
- this.serviceConfig = serviceConfig;
-
- // Apply the initial session settings
- IoSessionConfig sessionConfig = serviceConfig.getSessionConfig();
- if( sessionConfig instanceof SocketSessionConfig )
- {
- SocketSessionConfig cfg = ( SocketSessionConfig ) sessionConfig;
- this.config.setKeepAlive( cfg.isKeepAlive() );
- this.config.setOobInline( cfg.isOobInline() );
- this.config.setReceiveBufferSize( cfg.getReceiveBufferSize() );
- this.readBufferSize = cfg.getReceiveBufferSize();
- this.config.setReuseAddress( cfg.isReuseAddress() );
- this.config.setSendBufferSize( cfg.getSendBufferSize() );
- this.config.setSoLinger( cfg.getSoLinger() );
- this.config.setTcpNoDelay( cfg.isTcpNoDelay() );
-
- if( this.config.getTrafficClass() != cfg.getTrafficClass() )
- {
- this.config.setTrafficClass( cfg.getTrafficClass() );
- }
- }
- }
-
- void awaitRegistration() throws InterruptedException
- {
- registeredReadyLatch.countDown();
-
- registeredReadyLatch.await();
- }
-
- boolean created() throws InterruptedException
- {
- return created.get();
- }
-
- void doneCreation()
- {
- created.getAndSet(true);
- }
-
- public IoService getService()
- {
- return manager;
- }
-
- public IoServiceConfig getServiceConfig()
- {
- return serviceConfig;
- }
-
- public IoSessionConfig getConfig()
- {
- return config;
- }
-
- SocketIoProcessor getIoProcessor()
- {
- return ioProcessor;
- }
-
- public IoFilterChain getFilterChain()
- {
- return filterChain;
- }
-
- SocketChannel getChannel()
- {
- return ch;
- }
-
- IoServiceListenerSupport getServiceListeners()
- {
- return serviceListeners;
- }
-
- SelectionKey getSelectionKey()
- {
- return readKey;
- }
-
- SelectionKey getReadSelectionKey()
- {
- return readKey;
- }
-
- SelectionKey getWriteSelectionKey()
- {
- return writeKey;
- }
-
- void setSelectionKey(SelectionKey key)
- {
- this.readKey = key;
- }
-
- void setWriteSelectionKey(SelectionKey key)
- {
- this.writeKey = key;
- }
-
- public IoHandler getHandler()
- {
- return handler;
- }
-
- protected void close0()
- {
- filterChain.fireFilterClose( this );
- }
-
- Queue getWriteRequestQueue()
- {
- return writeRequestQueue;
- }
-
- /**
- @return int Number of write scheduled write requests
- @deprecated
- */
- public int getScheduledWriteMessages()
- {
- return getScheduledWriteRequests();
- }
-
- public int getScheduledWriteRequests()
- {
- synchronized( writeRequestQueue )
- {
- return writeRequestQueue.size();
- }
- }
-
- public int getScheduledWriteBytes()
- {
- synchronized( writeRequestQueue )
- {
- return writeRequestQueue.byteSize();
- }
- }
-
- protected void write0( WriteRequest writeRequest )
- {
- filterChain.fireFilterWrite( this, writeRequest );
- }
-
- public TransportType getTransportType()
- {
- return TransportType.SOCKET;
- }
-
- public SocketAddress getRemoteAddress()
- {
- //This is what I had previously
-// return ch.socket().getRemoteSocketAddress();
- return remoteAddress;
- }
-
- public SocketAddress getLocalAddress()
- {
- //This is what I had previously
-// return ch.socket().getLocalSocketAddress();
- return localAddress;
- }
-
- public SocketAddress getServiceAddress()
- {
- return serviceAddress;
- }
-
- protected void updateTrafficMask()
- {
- this.ioProcessor.updateTrafficMask( this );
- }
-
- int getReadBufferSize()
- {
- return readBufferSize;
- }
-
- private class SessionConfigImpl extends BaseIoSessionConfig implements SocketSessionConfig
- {
- public boolean isKeepAlive()
- {
- try
- {
- return ch.socket().getKeepAlive();
- }
- catch( SocketException e )
- {
- throw new RuntimeIOException( e );
- }
- }
-
- public void setKeepAlive( boolean on )
- {
- try
- {
- ch.socket().setKeepAlive( on );
- }
- catch( SocketException e )
- {
- throw new RuntimeIOException( e );
- }
- }
-
- public boolean isOobInline()
- {
- try
- {
- return ch.socket().getOOBInline();
- }
- catch( SocketException e )
- {
- throw new RuntimeIOException( e );
- }
- }
-
- public void setOobInline( boolean on )
- {
- try
- {
- ch.socket().setOOBInline( on );
- }
- catch( SocketException e )
- {
- throw new RuntimeIOException( e );
- }
- }
-
- public boolean isReuseAddress()
- {
- try
- {
- return ch.socket().getReuseAddress();
- }
- catch( SocketException e )
- {
- throw new RuntimeIOException( e );
- }
- }
-
- public void setReuseAddress( boolean on )
- {
- try
- {
- ch.socket().setReuseAddress( on );
- }
- catch( SocketException e )
- {
- throw new RuntimeIOException( e );
- }
- }
-
- public int getSoLinger()
- {
- try
- {
- return ch.socket().getSoLinger();
- }
- catch( SocketException e )
- {
- throw new RuntimeIOException( e );
- }
- }
-
- public void setSoLinger( int linger )
- {
- try
- {
- if( linger < 0 )
- {
- ch.socket().setSoLinger( false, 0 );
- }
- else
- {
- ch.socket().setSoLinger( true, linger );
- }
- }
- catch( SocketException e )
- {
- throw new RuntimeIOException( e );
- }
- }
-
- public boolean isTcpNoDelay()
- {
- try
- {
- return ch.socket().getTcpNoDelay();
- }
- catch( SocketException e )
- {
- throw new RuntimeIOException( e );
- }
- }
-
- public void setTcpNoDelay( boolean on )
- {
- try
- {
- ch.socket().setTcpNoDelay( on );
- }
- catch( SocketException e )
- {
- throw new RuntimeIOException( e );
- }
- }
-
- public int getTrafficClass()
- {
- if( SocketSessionConfigImpl.isGetTrafficClassAvailable() )
- {
- try
- {
- return ch.socket().getTrafficClass();
- }
- catch( SocketException e )
- {
- // Throw an exception only when setTrafficClass is also available.
- if( SocketSessionConfigImpl.isSetTrafficClassAvailable() )
- {
- throw new RuntimeIOException( e );
- }
- }
- }
-
- return 0;
- }
-
- public void setTrafficClass( int tc )
- {
- if( SocketSessionConfigImpl.isSetTrafficClassAvailable() )
- {
- try
- {
- ch.socket().setTrafficClass( tc );
- }
- catch( SocketException e )
- {
- throw new RuntimeIOException( e );
- }
- }
- }
-
- public int getSendBufferSize()
- {
- try
- {
- return ch.socket().getSendBufferSize();
- }
- catch( SocketException e )
- {
- throw new RuntimeIOException( e );
- }
- }
-
- public void setSendBufferSize( int size )
- {
- if( SocketSessionConfigImpl.isSetSendBufferSizeAvailable() )
- {
- try
- {
- ch.socket().setSendBufferSize( size );
- }
- catch( SocketException e )
- {
- throw new RuntimeIOException( e );
- }
- }
- }
-
- public int getReceiveBufferSize()
- {
- try
- {
- return ch.socket().getReceiveBufferSize();
- }
- catch( SocketException e )
- {
- throw new RuntimeIOException( e );
- }
- }
-
- public void setReceiveBufferSize( int size )
- {
- if( SocketSessionConfigImpl.isSetReceiveBufferSizeAvailable() )
- {
- try
- {
- ch.socket().setReceiveBufferSize( size );
- MultiThreadSocketSessionImpl.this.readBufferSize = size;
- }
- catch( SocketException e )
- {
- throw new RuntimeIOException( e );
- }
- }
- }
- }
-}
diff --git a/java/common/src/main/java/org/apache/mina/transport/vmpipe/QpidVmPipeConnector.java b/java/common/src/main/java/org/apache/mina/transport/vmpipe/QpidVmPipeConnector.java
deleted file mode 100644
index a23e546af5..0000000000
--- a/java/common/src/main/java/org/apache/mina/transport/vmpipe/QpidVmPipeConnector.java
+++ /dev/null
@@ -1,151 +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.mina.transport.vmpipe;
-
-import java.io.IOException;
-import java.net.SocketAddress;
-
-import org.apache.mina.common.ConnectFuture;
-import org.apache.mina.common.ExceptionMonitor;
-import org.apache.mina.common.IoFilterChain;
-import org.apache.mina.common.IoHandler;
-import org.apache.mina.common.IoServiceConfig;
-import org.apache.mina.common.IoSessionConfig;
-import org.apache.mina.common.support.AbstractIoFilterChain;
-import org.apache.mina.common.support.BaseIoConnector;
-import org.apache.mina.common.support.BaseIoConnectorConfig;
-import org.apache.mina.common.support.BaseIoSessionConfig;
-import org.apache.mina.common.support.DefaultConnectFuture;
-import org.apache.mina.transport.vmpipe.support.VmPipe;
-import org.apache.mina.transport.vmpipe.support.VmPipeIdleStatusChecker;
-import org.apache.mina.transport.vmpipe.support.VmPipeSessionImpl;
-import org.apache.mina.util.AnonymousSocketAddress;
-
-/**
- * Connects to {@link IoHandler}s which is bound on the specified
- * {@link VmPipeAddress}.
- *
- * @author The Apache Directory Project (mina-dev@directory.apache.org)
- * @version $Rev: 619823 $, $Date: 2008-02-08 10:09:37 +0000 (Fri, 08 Feb 2008) $
- */
-public class QpidVmPipeConnector extends VmPipeConnector
-{
- private static final IoSessionConfig CONFIG = new BaseIoSessionConfig() {};
- private final IoServiceConfig defaultConfig = new BaseIoConnectorConfig()
- {
- public IoSessionConfig getSessionConfig()
- {
- return CONFIG;
- }
- };
-
- /**
- * Creates a new instance.
- */
- public QpidVmPipeConnector()
- {
- }
-
- public ConnectFuture connect( SocketAddress address, IoHandler handler, IoServiceConfig config )
- {
- return connect( address, null, handler, config );
- }
-
- public ConnectFuture connect( SocketAddress address, SocketAddress localAddress, IoHandler handler, IoServiceConfig config )
- {
- if( address == null )
- throw new NullPointerException( "address" );
- if( handler == null )
- throw new NullPointerException( "handler" );
- if( ! ( address instanceof VmPipeAddress ) )
- throw new IllegalArgumentException(
- "address must be VmPipeAddress." );
-
- if( config == null )
- {
- config = getDefaultConfig();
- }
-
- VmPipe entry = ( VmPipe ) VmPipeAcceptor.boundHandlers.get( address );
- if( entry == null )
- {
- return DefaultConnectFuture.newFailedFuture(
- new IOException( "Endpoint unavailable: " + address ) );
- }
-
- DefaultConnectFuture future = new DefaultConnectFuture();
- VmPipeSessionImpl localSession =
- new VmPipeSessionImpl(
- this,
- config,
- getListeners(),
- new Object(), // lock
- new AnonymousSocketAddress(),
- handler,
- entry );
-
- // initialize acceptor session
- VmPipeSessionImpl remoteSession = localSession.getRemoteSession();
- try
- {
- IoFilterChain filterChain = remoteSession.getFilterChain();
- entry.getAcceptor().getFilterChainBuilder().buildFilterChain( filterChain );
- entry.getConfig().getFilterChainBuilder().buildFilterChain( filterChain );
- entry.getConfig().getThreadModel().buildFilterChain( filterChain );
-
- // The following sentences don't throw any exceptions.
- entry.getListeners().fireSessionCreated( remoteSession );
- VmPipeIdleStatusChecker.getInstance().addSession( remoteSession );
- }
- catch( Throwable t )
- {
- ExceptionMonitor.getInstance().exceptionCaught( t );
- remoteSession.close();
- }
-
-
- // initialize connector session
- try
- {
- IoFilterChain filterChain = localSession.getFilterChain();
- this.getFilterChainBuilder().buildFilterChain( filterChain );
- config.getFilterChainBuilder().buildFilterChain( filterChain );
- config.getThreadModel().buildFilterChain( filterChain );
-
- // The following sentences don't throw any exceptions.
- localSession.setAttribute( AbstractIoFilterChain.CONNECT_FUTURE, future );
- getListeners().fireSessionCreated( localSession );
- VmPipeIdleStatusChecker.getInstance().addSession( localSession);
- }
- catch( Throwable t )
- {
- future.setException( t );
- }
-
-
-
- return future;
- }
-
- public IoServiceConfig getDefaultConfig()
- {
- return defaultConfig;
- }
-} \ No newline at end of file
diff --git a/java/common/src/main/java/org/apache/qpid/AMQChannelClosedException.java b/java/common/src/main/java/org/apache/qpid/AMQChannelClosedException.java
deleted file mode 100644
index 1b2eabdc86..0000000000
--- a/java/common/src/main/java/org/apache/qpid/AMQChannelClosedException.java
+++ /dev/null
@@ -1,41 +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;
-
-import org.apache.qpid.protocol.AMQConstant;
-
-/**
- * AMQChannelClosedException indicates that an operation cannot be performed becauase a channel has been closed.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Represents a failed operation on a closed channel.
- * </table>
- *
- * @todo Does this duplicate AMQChannelException?
- */
-public class AMQChannelClosedException extends AMQException
-{
- public AMQChannelClosedException(AMQConstant errorCode, String msg, Throwable cause)
- {
- super(errorCode, msg, cause);
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/AMQChannelException.java b/java/common/src/main/java/org/apache/qpid/AMQChannelException.java
deleted file mode 100644
index ef9420ba87..0000000000
--- a/java/common/src/main/java/org/apache/qpid/AMQChannelException.java
+++ /dev/null
@@ -1,59 +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;
-
-import org.apache.qpid.framing.*;
-import org.apache.qpid.protocol.AMQConstant;
-
-/**
- * AMQChannelException indicates that an error that requires the channel to be closed has occurred.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Represents an error that rquires the channel to be closed.
- * </table>
- *
- * @todo Does this duplicate AMQChannelClosedException?
- */
-public class AMQChannelException extends AMQException
-{
- private final int _classId;
- private final int _methodId;
- /* AMQP version for which exception ocurred */
- private final byte major;
- private final byte minor;
-
- public AMQChannelException(AMQConstant errorCode, String msg, int classId, int methodId, byte major, byte minor,
- Throwable cause)
- {
- super(errorCode, msg, cause);
- _classId = classId;
- _methodId = methodId;
- this.major = major;
- this.minor = minor;
- }
-
- public AMQFrame getCloseFrame(int channel)
- {
- MethodRegistry reg = MethodRegistry.getMethodRegistry(new ProtocolVersion(major,minor));
- return new AMQFrame(channel, reg.createChannelCloseBody(getErrorCode() == null ? AMQConstant.INTERNAL_ERROR.getCode() : getErrorCode().getCode(), new AMQShortString(getMessage()),_classId,_methodId));
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/AMQConnectionClosedException.java b/java/common/src/main/java/org/apache/qpid/AMQConnectionClosedException.java
deleted file mode 100644
index b2ce3c1b32..0000000000
--- a/java/common/src/main/java/org/apache/qpid/AMQConnectionClosedException.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid;
-
-import org.apache.qpid.protocol.AMQConstant;
-
-/**
- * AMQConnectionClosedException indicates that a connection has been closed.
- *
- * <p/>This exception is really used as an event, in order that the method handler that raises it creates an event
- * which is propagated to the io handler, in order to notify it of the connection closure.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Represents a the closure of a connection.
- * </table>
- *
- * @todo Should review where exceptions-as-events
- */
-public class AMQConnectionClosedException extends AMQException
-{
- public AMQConnectionClosedException(AMQConstant errorCode, String msg, Throwable cause)
- {
- super(errorCode, msg, cause);
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/AMQConnectionException.java b/java/common/src/main/java/org/apache/qpid/AMQConnectionException.java
deleted file mode 100644
index 8ef6facef1..0000000000
--- a/java/common/src/main/java/org/apache/qpid/AMQConnectionException.java
+++ /dev/null
@@ -1,70 +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;
-
-import org.apache.qpid.framing.*;
-import org.apache.qpid.protocol.AMQConstant;
-
-/**
- * AMQConnectionException indicates that an error that requires the channel to be closed has occurred.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Represents an error that rquires the channel to be closed.
- * </table>
- *
- * @todo Does this duplicate AMQChannelClosedException?
- */
-public class AMQConnectionException extends AMQException
-{
- private final int _classId;
- private final int _methodId;
-
- /** AMQP version for which exception ocurred, major code. */
- private final byte major;
-
- /** AMQP version for which exception ocurred, minor code. */
- private final byte minor;
-
- boolean _closeConnetion;
-
- public AMQConnectionException(AMQConstant errorCode, String msg, int classId, int methodId, byte major, byte minor,
- Throwable cause)
- {
- super(errorCode, msg, cause);
- _classId = classId;
- _methodId = methodId;
- this.major = major;
- this.minor = minor;
- }
-
- public AMQFrame getCloseFrame(int channel)
- {
- MethodRegistry reg = MethodRegistry.getMethodRegistry(new ProtocolVersion(major,minor));
- return new AMQFrame(0,
- reg.createConnectionCloseBody(getErrorCode().getCode(),
- new AMQShortString(getMessage()),
- _classId,
- _methodId));
-
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/AMQConnectionFailureException.java b/java/common/src/main/java/org/apache/qpid/AMQConnectionFailureException.java
deleted file mode 100644
index f2503e549f..0000000000
--- a/java/common/src/main/java/org/apache/qpid/AMQConnectionFailureException.java
+++ /dev/null
@@ -1,62 +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;
-
-import java.util.Collection;
-
-import org.apache.qpid.protocol.AMQConstant;
-
-/**
- * AMQConnectionFailureException indicates that a connection to a broker could not be formed.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Represents failure to connect to a broker.
- * </table>
- *
- * @todo Not an AMQP exception as no status code.
- */
-public class AMQConnectionFailureException extends AMQException
-{
- Collection<Exception> _exceptions;
-
- public AMQConnectionFailureException(String message, Throwable cause)
- {
- super(cause instanceof AMQException ? ((AMQException) cause).getErrorCode() : null, message, cause);
- }
-
- public AMQConnectionFailureException(AMQConstant errorCode, String message, Throwable cause)
- {
- super(errorCode, message, cause);
- }
-
- public AMQConnectionFailureException(String message, Collection<Exception> exceptions)
- {
- // Blah, I hate ? but java won't let super() be anything other than the first thing, sorry...
- super (null, message, exceptions.isEmpty() ? null : exceptions.iterator().next());
- this._exceptions = exceptions;
- }
-
- public Collection<Exception> getLinkedExceptions()
- {
- return _exceptions;
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/AMQDisconnectedException.java b/java/common/src/main/java/org/apache/qpid/AMQDisconnectedException.java
deleted file mode 100644
index 5ec5c42ab9..0000000000
--- a/java/common/src/main/java/org/apache/qpid/AMQDisconnectedException.java
+++ /dev/null
@@ -1,39 +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;
-
-/**
- * AMQDisconnectedException indicates that a broker disconnected without failover.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Represents disconnection without failover by the broker.
- * </table>
- *
- * @todo Not an AMQP exception as no status code.
- */
-public class AMQDisconnectedException extends AMQException
-{
- public AMQDisconnectedException(String msg, Throwable cause)
- {
- super(null, msg, cause);
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/AMQException.java b/java/common/src/main/java/org/apache/qpid/AMQException.java
deleted file mode 100644
index b0c6fccc9e..0000000000
--- a/java/common/src/main/java/org/apache/qpid/AMQException.java
+++ /dev/null
@@ -1,124 +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;
-
-import org.apache.qpid.protocol.AMQConstant;
-
-/**
- * AMQException forms the root exception of all exceptions relating to the AMQ protocol. It provides space to associate
- * a required AMQ error code with the exception, which is a numeric value, with a meaning defined by the protocol.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Represents an exception condition associated with an AMQ protocol status code.
- * </table>
- *
- * @todo This exception class is also used as a generic exception throughout Qpid code. This usage may not be strictly
- * correct if this is to signify a protocol exception. Should review.
- */
-public class AMQException extends Exception
-{
- /** Holds the AMQ error code constant associated with this exception. */
- private AMQConstant _errorCode;
-
- /**
- * Creates an exception with an optional error code, optional message and optional underlying cause.
- *
- * @param errorCode The error code. May be null if not to be set.
- * @param msg The exception message. May be null if not to be set.
- * @param cause The underlying cause of the exception. May be null if not to be set.
- */
- public AMQException(AMQConstant errorCode, String msg, Throwable cause)
- {
- super(((msg == null) ? "" : msg), cause);
- _errorCode = errorCode;
- }
-
- /*
- * Deprecated constructors brought from M2.1
- */
- @Deprecated
- public AMQException(String msg)
- {
- this(null, (msg == null) ? "" : msg);
- }
-
- @Deprecated
- public AMQException(AMQConstant errorCode, String msg)
- {
- this(errorCode, (msg == null) ? "" : msg, null);
- }
-
- @Deprecated
- public AMQException(String msg, Throwable cause)
- {
- this(null, msg, cause);
- }
-
- @Override
- public String toString()
- {
- return getClass().getName() + ": " + getMessage() + (_errorCode == null ? "" : " [error code " + _errorCode + "]");
- }
-
- /**
- * Gets the AMQ protocol exception code associated with this exception.
- *
- * @return The AMQ protocol exception code associated with this exception.
- */
- public AMQConstant getErrorCode()
- {
- return _errorCode;
- }
-
- public boolean isHardError()
- {
- return true;
- }
-
- /**
- * Rethrown this exception as a new exception.
- *
- * Attempt to create a new exception of the same class if they have the default constructor of:
- * {AMQConstant.class, String.class, Throwable.class}
- * <p>
- * Individual subclasses may override as requried to create a new instance.
- */
- public AMQException cloneForCurrentThread()
- {
- Class amqeClass = this.getClass();
- Class<?>[] paramClasses = {AMQConstant.class, String.class, Throwable.class};
- Object[] params = {getErrorCode(), getMessage(), this};
-
- AMQException newAMQE;
-
- try
- {
- newAMQE = (AMQException) amqeClass.getConstructor(paramClasses).newInstance(params);
- }
- catch (Exception creationException)
- {
- newAMQE = new AMQException(getErrorCode(), getMessage(), this);
- }
-
- return newAMQE;
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/AMQInternalException.java b/java/common/src/main/java/org/apache/qpid/AMQInternalException.java
deleted file mode 100644
index 59dc800c0e..0000000000
--- a/java/common/src/main/java/org/apache/qpid/AMQInternalException.java
+++ /dev/null
@@ -1,49 +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;
-
-import org.apache.qpid.protocol.AMQConstant;
-
-/**
- * InternalException encapsulates error code 541, or {@link AMQConstant#INTERNAL_ERROR} exceptions relating to the
- * AMQ protocol. It is used to report internal failures and errors that occur within the broker.
- */
-public class AMQInternalException extends AMQException
-{
- /** serialVersionUID */
- private static final long serialVersionUID = 2544449432843381112L;
-
- /**
- * Creates an exception with an optional message and optional underlying cause.
- *
- * @param msg The exception message. May be null if not to be set.
- * @param cause The underlying cause of the exception. May be null if not to be set.
- */
- public AMQInternalException(String msg, Throwable cause)
- {
- super(AMQConstant.INTERNAL_ERROR, ((msg == null) ? "Internal error" : msg), cause);
- }
-
- public AMQInternalException(String msg)
- {
- this(msg, null);
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/AMQInvalidArgumentException.java b/java/common/src/main/java/org/apache/qpid/AMQInvalidArgumentException.java
deleted file mode 100644
index baca2a4773..0000000000
--- a/java/common/src/main/java/org/apache/qpid/AMQInvalidArgumentException.java
+++ /dev/null
@@ -1,45 +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;
-
-import org.apache.qpid.protocol.AMQConstant;
-
-/**
- * AMQInvalidArgumentException indicates that an invalid argument has been passed to an AMQP method.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Represents an error due to an invalid argument being passed to an AMQP method.
- * </table>
- */
-public class AMQInvalidArgumentException extends AMQException
-{
- public AMQInvalidArgumentException(String message, Throwable cause)
- {
- super(AMQConstant.INVALID_ARGUMENT, message, cause);
- }
-
- public boolean isHardError()
- {
- return false;
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/AMQInvalidRoutingKeyException.java b/java/common/src/main/java/org/apache/qpid/AMQInvalidRoutingKeyException.java
deleted file mode 100644
index c117968a29..0000000000
--- a/java/common/src/main/java/org/apache/qpid/AMQInvalidRoutingKeyException.java
+++ /dev/null
@@ -1,39 +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;
-
-import org.apache.qpid.protocol.AMQConstant;
-
-/**
- * AMQInvalidRoutingKeyException indicates an error with a routing key having an invalid format.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Represents a format error in a routing key.
- * </table>
- */
-public class AMQInvalidRoutingKeyException extends AMQException
-{
- public AMQInvalidRoutingKeyException(String message, Throwable cause)
- {
- super(AMQConstant.INVALID_ROUTING_KEY, message, cause);
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/AMQPInvalidClassException.java b/java/common/src/main/java/org/apache/qpid/AMQPInvalidClassException.java
deleted file mode 100644
index ab5141be9d..0000000000
--- a/java/common/src/main/java/org/apache/qpid/AMQPInvalidClassException.java
+++ /dev/null
@@ -1,42 +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;
-
-/**
- * AMQPInvalidClassException indicates an error when trying to store an illegally typed argument in a field table.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Represents illegal argument type for field table values.
- * </table>
- *
- * @todo Could just re-use an exising exception like IllegalArgumentException or ClassCastException.
- */
-public class AMQPInvalidClassException extends RuntimeException
-{
- /** Error message text when trying to store an unsupported class or null object */
- public static final String INVALID_OBJECT_MSG = "Only Primitive objects allowed. Object is: ";
-
- public AMQPInvalidClassException(String s)
- {
- super(s);
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/AMQProtocolException.java b/java/common/src/main/java/org/apache/qpid/AMQProtocolException.java
deleted file mode 100644
index bbc569839a..0000000000
--- a/java/common/src/main/java/org/apache/qpid/AMQProtocolException.java
+++ /dev/null
@@ -1,38 +0,0 @@
-package org.apache.qpid;
-
-import org.apache.qpid.protocol.AMQConstant;
-
-/* 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 AMQProtocolException extends AMQException
-{
- /**
- * Constructor for a Protocol Exception
- * <p> This is the only provided constructor and the parameters have to be
- * set to null when they are unknown.
- *
- * @param msg A description of the reason of this exception .
- * @param errorCode A string specifyin the error code of this exception.
- * @param cause The linked Execption.
- */
- public AMQProtocolException(AMQConstant errorCode, String msg, Throwable cause)
- {
- super(errorCode, msg, cause);
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/AMQSecurityException.java b/java/common/src/main/java/org/apache/qpid/AMQSecurityException.java
deleted file mode 100644
index d145d2c21d..0000000000
--- a/java/common/src/main/java/org/apache/qpid/AMQSecurityException.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid;
-
-import org.apache.qpid.protocol.AMQConstant;
-
-/**
- * SecurityException encapsulates error code 403, or {@link AMQConstant#ACCESS_REFUSED} exceptions relating to the
- * AMQ protocol. It is used to report authorisation failures and security errors.
- */
-public class AMQSecurityException extends AMQException
-{
- /** serialVersionUID */
- private static final long serialVersionUID = 8862069852716968394L;
-
- /**
- * Creates an exception with an optional message and optional underlying cause.
- *
- * @param msg The exception message. May be null if not to be set.
- * @param cause The underlying cause of the exception. May be null if not to be set.
- */
- public AMQSecurityException(String msg, Throwable cause)
- {
- super(AMQConstant.ACCESS_REFUSED, ((msg == null) ? "Permission denied" : msg), cause);
- }
-
- public AMQSecurityException(String msg)
- {
- this(msg, null);
- }
-
- public AMQSecurityException()
- {
- this(null);
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/AMQStoreException.java b/java/common/src/main/java/org/apache/qpid/AMQStoreException.java
deleted file mode 100644
index 8389fe5efa..0000000000
--- a/java/common/src/main/java/org/apache/qpid/AMQStoreException.java
+++ /dev/null
@@ -1,48 +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;
-
-import java.sql.SQLException;
-
-/**
- * StoreException is a specific type of internal error relating to errors in the message store, such as {@link SQLException}.
- */
-public class AMQStoreException extends AMQInternalException
-{
- /** serialVersionUID */
- private static final long serialVersionUID = 2859681947490637496L;
-
- /**
- * Creates an exception with an optional message and optional underlying cause.
- *
- * @param msg The exception message. May be null if not to be set.
- * @param cause The underlying cause of the exception. May be null if not to be set.
- */
- public AMQStoreException(String msg, Throwable cause)
- {
- super(((msg == null) ? "Store error" : msg), cause);
- }
-
- public AMQStoreException(String msg)
- {
- this(msg, null);
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/AMQTimeoutException.java b/java/common/src/main/java/org/apache/qpid/AMQTimeoutException.java
deleted file mode 100644
index 4ae8282af5..0000000000
--- a/java/common/src/main/java/org/apache/qpid/AMQTimeoutException.java
+++ /dev/null
@@ -1,39 +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;
-
-import org.apache.qpid.protocol.AMQConstant;
-
-/**
- * AMQTimeoutException indicates that an expected response from a broker took too long.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Indicates that an expected response from a broker took too long.
- * </table>
- */
-public class AMQTimeoutException extends AMQException
-{
- public AMQTimeoutException(String message, Throwable cause)
- {
- super(AMQConstant.REQUEST_TIMEOUT, message, cause);
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/AMQUndeliveredException.java b/java/common/src/main/java/org/apache/qpid/AMQUndeliveredException.java
deleted file mode 100644
index 01a569b693..0000000000
--- a/java/common/src/main/java/org/apache/qpid/AMQUndeliveredException.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid;
-
-import org.apache.qpid.protocol.AMQConstant;
-
-/**
- * AMQUndeliveredException indicates that a message, marked immediate or mandatory, could not be delivered.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Represents failure to delivery a message that must be delivered.
- * </table>
- */
-public class AMQUndeliveredException extends AMQException
-{
- private Object _bounced;
-
- public AMQUndeliveredException(AMQConstant errorCode, String msg, Object bounced, Throwable cause)
- {
- super(errorCode, msg, cause);
-
- _bounced = bounced;
- }
-
- public Object getUndeliveredMessage()
- {
- return _bounced;
- }
-
- public boolean isHardError()
- {
- return false;
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/AMQUnknownExchangeType.java b/java/common/src/main/java/org/apache/qpid/AMQUnknownExchangeType.java
deleted file mode 100644
index 0eefc03016..0000000000
--- a/java/common/src/main/java/org/apache/qpid/AMQUnknownExchangeType.java
+++ /dev/null
@@ -1,43 +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;
-
-/**
- * AMQUnknownExchangeType represents coding error where unknown exchange type requested from exchange factory.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Represents unknown exchange type request.
- * <tr><td>
- *
- * @todo Not an AMQP exception as no status code.
- *
- * @todo Represent coding error, where unknown exchange type is requested by passing a string parameter. Use a type safe
- * enum for the exchange type, or replace with IllegalArgumentException. Should be runtime.
- */
-public class AMQUnknownExchangeType extends AMQException
-{
- public AMQUnknownExchangeType(String message, Throwable cause)
- {
- super(null, message, cause);
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/AMQUnresolvedAddressException.java b/java/common/src/main/java/org/apache/qpid/AMQUnresolvedAddressException.java
deleted file mode 100644
index eee3e6afcf..0000000000
--- a/java/common/src/main/java/org/apache/qpid/AMQUnresolvedAddressException.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid;
-
-/**
- * AMQUnresolvedAddressException indicates failure to resolve a socket address.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Represents failre to resolve a socket address.
- * </table>
- *
- * @todo Not an AMQP exception as no status code.
- *
- * @todo Why replace java.nio.UnresolvedAddressException with this? This is checked, which may explain why, but it
- * doesn't wrap the underlying exception.
- */
-public class AMQUnresolvedAddressException extends AMQException
-{
- String _broker;
-
- public AMQUnresolvedAddressException(String message, String broker, Throwable cause)
- {
- super(null, message, cause);
- _broker = broker;
- }
-
- public String toString()
- {
- return super.toString() + " Broker, \"" + _broker + "\"";
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/ConsoleOutput.java b/java/common/src/main/java/org/apache/qpid/ConsoleOutput.java
deleted file mode 100644
index 00ad5cf08a..0000000000
--- a/java/common/src/main/java/org/apache/qpid/ConsoleOutput.java
+++ /dev/null
@@ -1,62 +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;
-
-import static org.apache.qpid.transport.util.Functions.str;
-
-import java.nio.ByteBuffer;
-
-import org.apache.qpid.transport.Sender;
-
-
-/**
- * ConsoleOutput
- *
- * @author Rafael H. Schloming
- */
-
-public class ConsoleOutput implements Sender<ByteBuffer>
-{
-
- public void send(ByteBuffer buf)
- {
- System.out.println(str(buf));
- }
-
- public void flush()
- {
- // pass
- }
-
- public void close()
- {
- System.out.println("CLOSED");
- }
-
- public void setIdleTimeout(int i)
- {
- // TODO Auto-generated method stub
-
- }
-
-
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/QpidConfig.java b/java/common/src/main/java/org/apache/qpid/QpidConfig.java
deleted file mode 100644
index b4cad44130..0000000000
--- a/java/common/src/main/java/org/apache/qpid/QpidConfig.java
+++ /dev/null
@@ -1,111 +0,0 @@
-package org.apache.qpid;
-/*
- *
- * 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.
- *
- */
-
-
-/**
- * API to configure the Security parameters of the client.
- * The user can choose to pick the config from any source
- * and set it using this class.
- *
- */
-public class QpidConfig
-{
- private static QpidConfig _instance = new QpidConfig();
-
- private SecurityMechanism[] securityMechanisms =
- new SecurityMechanism[]{new SecurityMechanism("PLAIN","org.apache.qpid.security.UsernamePasswordCallbackHandler"),
- new SecurityMechanism("CRAM_MD5","org.apache.qpid.security.UsernamePasswordCallbackHandler")};
-
- private SaslClientFactory[] saslClientFactories =
- new SaslClientFactory[]{new SaslClientFactory("AMQPLAIN","org.apache.qpid.security.amqplain.AmqPlainSaslClientFactory")};
-
- private QpidConfig(){}
-
- public static QpidConfig get()
- {
- return _instance;
- }
-
- public void setSecurityMechanisms(SecurityMechanism... securityMechanisms)
- {
- this.securityMechanisms = securityMechanisms;
- }
-
- public SecurityMechanism[] getSecurityMechanisms()
- {
- return securityMechanisms;
- }
-
- public void setSaslClientFactories(SaslClientFactory... saslClientFactories)
- {
- this.saslClientFactories = saslClientFactories;
- }
-
- public SaslClientFactory[] getSaslClientFactories()
- {
- return saslClientFactories;
- }
-
- public static class SecurityMechanism
- {
- String type;
- String handler;
-
- SecurityMechanism(String type,String handler)
- {
- this.type = type;
- this.handler = handler;
- }
-
- public String getHandler()
- {
- return handler;
- }
-
- public String getType()
- {
- return type;
- }
- }
-
- public static class SaslClientFactory
- {
- String type;
- String factoryClass;
-
- SaslClientFactory(String type,String factoryClass)
- {
- this.type = type;
- this.factoryClass = factoryClass;
- }
-
- public String getFactoryClass()
- {
- return factoryClass;
- }
-
- public String getType()
- {
- return type;
- }
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/SerialException.java b/java/common/src/main/java/org/apache/qpid/SerialException.java
deleted file mode 100644
index c59a6af779..0000000000
--- a/java/common/src/main/java/org/apache/qpid/SerialException.java
+++ /dev/null
@@ -1,40 +0,0 @@
-package org.apache.qpid;
-/*
- *
- * 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 exception is used by the serial class (imp RFC 1982)
- *
- */
-public class SerialException extends ArithmeticException
-{
- /**
- * Constructs an <code>SerialException</code> with the specified
- * detail message.
- *
- * @param message The exception message.
- */
- public SerialException(String message)
- {
- super(message);
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/ToyBroker.java b/java/common/src/main/java/org/apache/qpid/ToyBroker.java
deleted file mode 100644
index 5423bbb68f..0000000000
--- a/java/common/src/main/java/org/apache/qpid/ToyBroker.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;
-
-import org.apache.qpid.transport.*;
-import org.apache.qpid.transport.network.mina.MinaHandler;
-
-import static org.apache.qpid.transport.util.Functions.str;
-
-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.concurrent.ConcurrentHashMap;
-import java.util.concurrent.LinkedBlockingQueue;
-
-
-/**
- * ToyBroker
- *
- * @author Rafael H. Schloming
- */
-
-class ToyBroker extends SessionDelegate
-{
-
- private ToyExchange exchange;
- private Map<String,Consumer> consumers = new ConcurrentHashMap<String,Consumer>();
-
- public ToyBroker(ToyExchange exchange)
- {
- this.exchange = exchange;
- }
-
- public void messageAcquire(Session context, MessageAcquire struct)
- {
- System.out.println("\n==================> messageAcquire " );
- context.executionResult((int) struct.getId(), new Acquired(struct.getTransfers()));
- }
-
- @Override public void queueDeclare(Session ssn, QueueDeclare qd)
- {
- exchange.createQueue(qd.getQueue());
- System.out.println("\n==================> declared queue: " + qd.getQueue() + "\n");
- }
-
- @Override public void exchangeBind(Session ssn, ExchangeBind qb)
- {
- exchange.bindQueue(qb.getExchange(), qb.getBindingKey(),qb.getQueue());
- System.out.println("\n==================> bound queue: " + qb.getQueue() + " with binding key " + qb.getBindingKey() + "\n");
- }
-
- @Override public void queueQuery(Session ssn, QueueQuery qq)
- {
- QueueQueryResult result = new QueueQueryResult().queue(qq.getQueue());
- ssn.executionResult((int) qq.getId(), result);
- }
-
- @Override public void messageSubscribe(Session ssn, MessageSubscribe ms)
- {
- Consumer c = new Consumer();
- c._queueName = ms.getQueue();
- consumers.put(ms.getDestination(),c);
- System.out.println("\n==================> message subscribe : " + ms.getDestination() + " queue: " + ms.getQueue() + "\n");
- }
-
- @Override public void messageFlow(Session ssn,MessageFlow struct)
- {
- Consumer c = consumers.get(struct.getDestination());
- c._credit = struct.getValue();
- System.out.println("\n==================> message flow : " + struct.getDestination() + " credit: " + struct.getValue() + "\n");
- }
-
- @Override public void messageFlush(Session ssn,MessageFlush struct)
- {
- System.out.println("\n==================> message flush for consumer : " + struct.getDestination() + "\n");
- checkAndSendMessagesToConsumer(ssn,struct.getDestination());
- }
-
- @Override public void messageTransfer(Session ssn, MessageTransfer xfr)
- {
- String dest = xfr.getDestination();
- System.out.println("received transfer " + dest);
- Header header = xfr.getHeader();
- DeliveryProperties props = header.get(DeliveryProperties.class);
- if (props != null)
- {
- System.out.println("received headers routing_key " + props.getRoutingKey());
- }
-
- MessageProperties mp = header.get(MessageProperties.class);
- System.out.println("MP: " + mp);
- if (mp != null)
- {
- System.out.println(mp.getApplicationHeaders());
- }
-
- if (exchange.route(dest,props == null ? null : props.getRoutingKey(),xfr))
- {
- System.out.println("queued " + xfr);
- dispatchMessages(ssn);
- }
- else
- {
-
- if (props == null || !props.getDiscardUnroutable())
- {
- RangeSet ranges = new RangeSet();
- ranges.add(xfr.getId());
- ssn.messageReject(ranges, MessageRejectCode.UNROUTABLE,
- "no such destination");
- }
- }
- ssn.processed(xfr);
- }
-
- private void transferMessageToPeer(Session ssn,String dest, MessageTransfer m)
- {
- System.out.println("\n==================> Transfering message to: " +dest + "\n");
- ssn.messageTransfer(m.getDestination(), MessageAcceptMode.EXPLICIT,
- MessageAcquireMode.PRE_ACQUIRED,
- m.getHeader(), m.getBody());
- }
-
- private void dispatchMessages(Session ssn)
- {
- for (String dest: consumers.keySet())
- {
- checkAndSendMessagesToConsumer(ssn,dest);
- }
- }
-
- private void checkAndSendMessagesToConsumer(Session ssn,String dest)
- {
- Consumer c = consumers.get(dest);
- LinkedBlockingQueue<MessageTransfer> queue = exchange.getQueue(c._queueName);
- MessageTransfer m = queue.poll();
- while (m != null && c._credit>0)
- {
- transferMessageToPeer(ssn,dest,m);
- c._credit--;
- m = queue.poll();
- }
- }
-
- // ugly, but who cares :)
- // assumes unit is always no of messages, not bytes
- // assumes it's credit mode and not window
- private static class Consumer
- {
- long _credit;
- String _queueName;
- }
-
- private static final class ToyBrokerSession extends Session
- {
-
- public ToyBrokerSession(Connection connection, Binary name, long expiry, ToyExchange exchange)
- {
- super(connection, new ToyBroker(exchange), name, expiry);
- }
- }
-
- public static final void main(String[] args) throws IOException
- {
- final ToyExchange exchange = new ToyExchange();
- ConnectionDelegate delegate = new ServerDelegate()
- {
- @Override
- public void init(Connection conn, ProtocolHeader hdr)
- {
- conn.setSessionFactory(new Connection.SessionFactory()
- {
- public Session newSession(Connection conn, Binary name, long expiry)
- {
- return new ToyBrokerSession(conn, name, expiry, exchange);
- }
- });
-
- super.init(conn, hdr); //To change body of overridden methods use File | Settings | File Templates.
- }
-
- };
-
- MinaHandler.accept("0.0.0.0", 5672, delegate);
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/ToyClient.java b/java/common/src/main/java/org/apache/qpid/ToyClient.java
deleted file mode 100644
index 5b2db10613..0000000000
--- a/java/common/src/main/java/org/apache/qpid/ToyClient.java
+++ /dev/null
@@ -1,108 +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;
-
-import java.nio.*;
-import java.util.*;
-
-import org.apache.qpid.transport.*;
-import org.apache.qpid.transport.network.mina.MinaHandler;
-
-
-/**
- * ToyClient
- *
- * @author Rafael H. Schloming
- */
-
-class ToyClient implements SessionListener
-{
- public void opened(Session ssn) {}
-
- public void resumed(Session ssn) {}
-
- public void exception(Session ssn, SessionException exc)
- {
- exc.printStackTrace();
- }
-
- public void message(Session ssn, MessageTransfer xfr)
- {
- System.out.println("msg: " + xfr);
- }
-
- public void closed(Session ssn) {}
-
- public static final void main(String[] args)
- {
- Connection conn = new Connection();
- conn.connect("0.0.0.0", 5672, null, "guest", "guest", false);
- Session ssn = conn.createSession();
- ssn.setSessionListener(new ToyClient());
-
- ssn.queueDeclare("asdf", null, null);
- ssn.sync();
-
- Map<String,Object> nested = new LinkedHashMap<String,Object>();
- nested.put("list", Arrays.asList("one", "two", "three"));
- Map<String,Object> map = new LinkedHashMap<String,Object>();
-
- map.put("str", "this is a string");
-
- map.put("+int", 3);
- map.put("-int", -3);
- map.put("maxint", Integer.MAX_VALUE);
- map.put("minint", Integer.MIN_VALUE);
-
- map.put("+short", (short) 1);
- map.put("-short", (short) -1);
- map.put("maxshort", (short) Short.MAX_VALUE);
- map.put("minshort", (short) Short.MIN_VALUE);
-
- map.put("float", (float) 3.3);
- map.put("double", 4.9);
- map.put("char", 'c');
-
- map.put("table", nested);
- map.put("list", Arrays.asList(1, 2, 3));
- map.put("binary", new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10});
-
- ssn.messageTransfer("asdf", MessageAcceptMode.EXPLICIT,
- MessageAcquireMode.PRE_ACQUIRED,
- new Header(new DeliveryProperties(),
- new MessageProperties()
- .setApplicationHeaders(map)),
- "this is the data");
-
- ssn.messageTransfer("fdsa", MessageAcceptMode.EXPLICIT,
- MessageAcquireMode.PRE_ACQUIRED,
- null,
- "this should be rejected");
- ssn.sync();
-
- Future<QueueQueryResult> future = ssn.queueQuery("asdf");
- System.out.println(future.get().getQueue());
- ssn.sync();
- ssn.close();
- conn.close();
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/ToyExchange.java b/java/common/src/main/java/org/apache/qpid/ToyExchange.java
deleted file mode 100644
index da6aed9629..0000000000
--- a/java/common/src/main/java/org/apache/qpid/ToyExchange.java
+++ /dev/null
@@ -1,154 +0,0 @@
-package org.apache.qpid;
-/*
- *
- * 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 java.util.ArrayList;
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.LinkedBlockingQueue;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import org.apache.qpid.transport.MessageTransfer;
-
-
-public class ToyExchange
-{
- final static String DIRECT = "amq.direct";
- final static String TOPIC = "amq.topic";
-
- private Map<String,List<LinkedBlockingQueue<MessageTransfer>>> directEx = new HashMap<String,List<LinkedBlockingQueue<MessageTransfer>>>();
- private Map<String,List<LinkedBlockingQueue<MessageTransfer>>> topicEx = new HashMap<String,List<LinkedBlockingQueue<MessageTransfer>>>();
- private Map<String,LinkedBlockingQueue<MessageTransfer>> queues = new HashMap<String,LinkedBlockingQueue<MessageTransfer>>();
-
- public void createQueue(String name)
- {
- queues.put(name, new LinkedBlockingQueue<MessageTransfer>());
- }
-
- public LinkedBlockingQueue<MessageTransfer> getQueue(String name)
- {
- return queues.get(name);
- }
-
- public void bindQueue(String type,String binding,String queueName)
- {
- LinkedBlockingQueue<MessageTransfer> queue = queues.get(queueName);
- binding = normalizeKey(binding);
- if(DIRECT.equals(type))
- {
-
- if (directEx.containsKey(binding))
- {
- List<LinkedBlockingQueue<MessageTransfer>> list = directEx.get(binding);
- list.add(queue);
- }
- else
- {
- List<LinkedBlockingQueue<MessageTransfer>> list = new LinkedList<LinkedBlockingQueue<MessageTransfer>>();
- list.add(queue);
- directEx.put(binding,list);
- }
- }
- else
- {
- if (topicEx.containsKey(binding))
- {
- List<LinkedBlockingQueue<MessageTransfer>> list = topicEx.get(binding);
- list.add(queue);
- }
- else
- {
- List<LinkedBlockingQueue<MessageTransfer>> list = new LinkedList<LinkedBlockingQueue<MessageTransfer>>();
- list.add(queue);
- topicEx.put(binding,list);
- }
- }
- }
-
- public boolean route(String dest, String routingKey, MessageTransfer msg)
- {
- List<LinkedBlockingQueue<MessageTransfer>> queues;
- if(DIRECT.equals(dest))
- {
- queues = directEx.get(routingKey);
- }
- else
- {
- queues = matchWildCard(routingKey);
- }
- if(queues != null && queues.size()>0)
- {
- System.out.println("Message stored in " + queues.size() + " queues");
- storeMessage(msg,queues);
- return true;
- }
- else
- {
- System.out.println("Message unroutable " + msg);
- return false;
- }
- }
-
- private String normalizeKey(String routingKey)
- {
- if(routingKey.indexOf(".*")>1)
- {
- return routingKey.substring(0,routingKey.indexOf(".*"));
- }
- else
- {
- return routingKey;
- }
- }
-
- private List<LinkedBlockingQueue<MessageTransfer>> matchWildCard(String routingKey)
- {
- List<LinkedBlockingQueue<MessageTransfer>> selected = new ArrayList<LinkedBlockingQueue<MessageTransfer>>();
-
- for(String key: topicEx.keySet())
- {
- Pattern p = Pattern.compile(key);
- Matcher m = p.matcher(routingKey);
- if (m.find())
- {
- for(LinkedBlockingQueue<MessageTransfer> queue : topicEx.get(key))
- {
- selected.add(queue);
- }
- }
- }
-
- return selected;
- }
-
- private void storeMessage(MessageTransfer msg,List<LinkedBlockingQueue<MessageTransfer>> selected)
- {
- for(LinkedBlockingQueue<MessageTransfer> queue : selected)
- {
- queue.offer(msg);
- }
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/api/Message.java b/java/common/src/main/java/org/apache/qpid/api/Message.java
deleted file mode 100644
index df6f279026..0000000000
--- a/java/common/src/main/java/org/apache/qpid/api/Message.java
+++ /dev/null
@@ -1,126 +0,0 @@
-package org.apache.qpid.api;
-
-import java.io.IOException;
-import java.nio.ByteBuffer;
-
-import org.apache.qpid.transport.MessageProperties;
-import org.apache.qpid.transport.DeliveryProperties;
-import org.apache.qpid.transport.Header;
-
-/*
- * 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 interface Message
-{
- public Header getHeader();
-
- public void setHeader(Header header);
-
- public MessageProperties getMessageProperties();
-
- public DeliveryProperties getDeliveryProperties();
-
- /**
- * This will abstract the underlying message data.
- * The Message implementation may not hold all message
- * data in memory (especially in the case of large messages)
- *
- * The appendData function might write data to
- * <ul>
- * <li> Memory (Ex: ByteBuffer)
- * <li> To Disk
- * <li> To Socket (Stream)
- * </ul>
- * @param src - the data to append
- */
- public void appendData(byte[] src) throws IOException;
-
-
- /**
- * This will abstract the underlying message data.
- * The Message implementation may not hold all message
- * data in memory (especially in the case of large messages)
- *
- * The appendData function might write data to
- * <ul>
- * <li> Memory (Ex: ByteBuffer)
- * <li> To Disk
- * <li> To Socket (Stream)
- * </ul>
- * @param src - the data to append
- */
- public void appendData(ByteBuffer src) throws IOException;
-
- /**
- * This will abstract the underlying message data.
- * The Message implementation may not hold all message
- * data in memory (especially in the case of large messages)
- *
- * The read function might copy data from
- * <ul>
- * <li> From memory (Ex: ByteBuffer)
- * <li> From Disk
- * <li> From Socket as and when it gets streamed
- * </ul>
- * @param target The target byte[] which the data gets copied to
- */
- public void readData(byte[] target) throws IOException;
-
- /**
- * * This will abstract the underlying message data.
- * The Message implementation may not hold all message
- * data in memory (especially in the case of large messages)
- *
- * The read function might copy data from
- * <ul>
- * <li> From memory (Ex: ByteBuffer)
- * <li> From Disk
- * <li> From Socket as and when it gets streamed
- * </ul>
- *
- * @return A ByteBuffer containing data
- * @throws IOException
- */
- public ByteBuffer readData() throws IOException;
-
- /**
- * This should clear the body of the message.
- */
- public void clearData();
-
- /**
- * The provides access to the command Id assigned to the
- * message transfer.
- * This id is useful when you do
- * <ul>
- * <li>For message acquiring - If the transfer happend in no-acquire mode
- * you could use this id to accquire it.
- * <li>For releasing a message. You can use this id to release an acquired
- * message
- * <li>For Acknowledging a message - You need to pass this ID, in order to
- * acknowledge the message
- * <li>For Rejecting a message - You need to pass this ID, in order to reject
- * the message.
- * </ul>
- *
- * @return the message transfer id.
- */
- public int getMessageTransferId();
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/codec/AMQCodecFactory.java b/java/common/src/main/java/org/apache/qpid/codec/AMQCodecFactory.java
deleted file mode 100644
index 591dbd085b..0000000000
--- a/java/common/src/main/java/org/apache/qpid/codec/AMQCodecFactory.java
+++ /dev/null
@@ -1,78 +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.codec;
-
-import org.apache.mina.filter.codec.ProtocolCodecFactory;
-import org.apache.mina.filter.codec.ProtocolDecoder;
-import org.apache.mina.filter.codec.ProtocolEncoder;
-import org.apache.qpid.protocol.AMQVersionAwareProtocolSession;
-
-/**
- * AMQCodecFactory is a Mina codec factory. It supplies the encoders and decoders need to read and write the bytes to
- * the wire.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations.
- * <tr><td> Supply the protocol encoder. <td> {@link AMQEncoder}
- * <tr><td> Supply the protocol decoder. <td> {@link AMQDecoder}
- * </table>
- */
-public class AMQCodecFactory implements ProtocolCodecFactory
-{
- /** Holds the protocol encoder. */
- private final AMQEncoder _encoder = new AMQEncoder();
-
- /** Holds the protocol decoder. */
- private final AMQDecoder _frameDecoder;
-
- /**
- * Creates a new codec factory, specifiying whether it is expected that the first frame of data should be an
- * initiation. This is the case for the broker, which always expects to received the protocol initiation on a newly
- * connected client.
- *
- * @param expectProtocolInitiation <tt>true</tt> if the first frame received is going to be a protocol initiation
- * frame, <tt>false</tt> if it is going to be a standard AMQ data block.
- */
- public AMQCodecFactory(boolean expectProtocolInitiation, AMQVersionAwareProtocolSession session)
- {
- _frameDecoder = new AMQDecoder(expectProtocolInitiation, session);
- }
-
- /**
- * Gets the AMQP encoder.
- *
- * @return The AMQP encoder.
- */
- public ProtocolEncoder getEncoder()
- {
- return _encoder;
- }
-
- /**
- * Gets the AMQP decoder.
- *
- * @return The AMQP decoder.
- */
- public AMQDecoder getDecoder()
- {
- return _frameDecoder;
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/codec/AMQDecoder.java b/java/common/src/main/java/org/apache/qpid/codec/AMQDecoder.java
deleted file mode 100644
index 281c0761d9..0000000000
--- a/java/common/src/main/java/org/apache/qpid/codec/AMQDecoder.java
+++ /dev/null
@@ -1,340 +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.codec;
-
-import java.util.ArrayList;
-
-import org.apache.mina.common.ByteBuffer;
-import org.apache.mina.common.IoSession;
-import org.apache.mina.common.SimpleByteBufferAllocator;
-import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
-import org.apache.mina.filter.codec.ProtocolDecoderOutput;
-
-import org.apache.qpid.framing.AMQDataBlock;
-import org.apache.qpid.framing.AMQDataBlockDecoder;
-import org.apache.qpid.framing.AMQFrameDecodingException;
-import org.apache.qpid.framing.AMQMethodBodyFactory;
-import org.apache.qpid.framing.AMQProtocolVersionException;
-import org.apache.qpid.framing.ProtocolInitiation;
-import org.apache.qpid.protocol.AMQVersionAwareProtocolSession;
-
-/**
- * AMQDecoder delegates the decoding of AMQP either to a data block decoder, or in the case of new connections, to a
- * protocol initiation decoder. It is a cumulative decoder, which means that it can accumulate data to decode in the
- * buffer until there is enough data to decode.
- *
- * <p/>One instance of this class is created per session, so any changes or configuration done at run time to the
- * decoder will only affect decoding of the protocol session data to which is it bound.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Delegate protocol initiation to its decoder. <td> {@link ProtocolInitiation.Decoder}
- * <tr><td> Delegate AMQP data to its decoder. <td> {@link AMQDataBlockDecoder}
- * <tr><td> Accept notification that protocol initiation has completed.
- * </table>
- *
- * @todo If protocol initiation decoder not needed, then don't create it. Probably not a big deal, but it adds to the
- * per-session overhead.
- */
-public class AMQDecoder extends CumulativeProtocolDecoder
-{
-
- private static final String BUFFER = AMQDecoder.class.getName() + ".Buffer";
-
- /** Holds the 'normal' AMQP data decoder. */
- private AMQDataBlockDecoder _dataBlockDecoder = new AMQDataBlockDecoder();
-
- /** Holds the protocol initiation decoder. */
- private ProtocolInitiation.Decoder _piDecoder = new ProtocolInitiation.Decoder();
-
- /** Flag to indicate whether this decoder needs to handle protocol initiation. */
- private boolean _expectProtocolInitiation;
- private boolean firstDecode = true;
-
- private AMQMethodBodyFactory _bodyFactory;
-
- private ByteBuffer _remainingBuf;
-
- /**
- * Creates a new AMQP decoder.
- *
- * @param expectProtocolInitiation <tt>true</tt> if this decoder needs to handle protocol initiation.
- */
- public AMQDecoder(boolean expectProtocolInitiation, AMQVersionAwareProtocolSession session)
- {
- _expectProtocolInitiation = expectProtocolInitiation;
- _bodyFactory = new AMQMethodBodyFactory(session);
- }
-
- /**
- * Delegates decoding AMQP from the data buffer that Mina has retrieved from the wire, to the data or protocol
- * intiation decoders.
- *
- * @param session The Mina session.
- * @param in The raw byte buffer.
- * @param out The Mina object output gatherer to write decoded objects to.
- *
- * @return <tt>true</tt> if the data was decoded, <tt>false<tt> if more is needed and the data should accumulate.
- *
- * @throws Exception If the data cannot be decoded for any reason.
- */
- protected boolean doDecode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) throws Exception
- {
-
- boolean decoded;
- if (_expectProtocolInitiation
- || (firstDecode
- && (in.remaining() > 0)
- && (in.get(in.position()) == (byte)'A')))
- {
- decoded = doDecodePI(session, in, out);
- }
- else
- {
- decoded = doDecodeDataBlock(session, in, out);
- }
- if(firstDecode && decoded)
- {
- firstDecode = false;
- }
- return decoded;
- }
-
- /**
- * Decodes AMQP data, delegating the decoding to an {@link AMQDataBlockDecoder}.
- *
- * @param session The Mina session.
- * @param in The raw byte buffer.
- * @param out The Mina object output gatherer to write decoded objects to.
- *
- * @return <tt>true</tt> if the data was decoded, <tt>false<tt> if more is needed and the data should accumulate.
- *
- * @throws Exception If the data cannot be decoded for any reason.
- */
- protected boolean doDecodeDataBlock(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) throws Exception
- {
- int pos = in.position();
- boolean enoughData = _dataBlockDecoder.decodable(in.buf());
- in.position(pos);
- if (!enoughData)
- {
- // returning false means it will leave the contents in the buffer and
- // call us again when more data has been read
- return false;
- }
- else
- {
- _dataBlockDecoder.decode(session, in, out);
-
- return true;
- }
- }
-
- /**
- * Decodes an AMQP initiation, delegating the decoding to a {@link ProtocolInitiation.Decoder}.
- *
- * @param session The Mina session.
- * @param in The raw byte buffer.
- * @param out The Mina object output gatherer to write decoded objects to.
- *
- * @return <tt>true</tt> if the data was decoded, <tt>false<tt> if more is needed and the data should accumulate.
- *
- * @throws Exception If the data cannot be decoded for any reason.
- */
- private boolean doDecodePI(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) throws Exception
- {
- boolean enoughData = _piDecoder.decodable(in.buf());
- if (!enoughData)
- {
- // returning false means it will leave the contents in the buffer and
- // call us again when more data has been read
- return false;
- }
- else
- {
- ProtocolInitiation pi = new ProtocolInitiation(in.buf());
- out.write(pi);
-
- return true;
- }
- }
-
- /**
- * Sets the protocol initation flag, that determines whether decoding is handled by the data decoder of the protocol
- * initation decoder. This method is expected to be called with <tt>false</tt> once protocol initation completes.
- *
- * @param expectProtocolInitiation <tt>true</tt> to use the protocol initiation decoder, <tt>false</tt> to use the
- * data decoder.
- */
- public void setExpectProtocolInitiation(boolean expectProtocolInitiation)
- {
- _expectProtocolInitiation = expectProtocolInitiation;
- }
-
-
- /**
- * Cumulates content of <tt>in</tt> into internal buffer and forwards
- * decoding request to {@link #doDecode(IoSession, ByteBuffer, ProtocolDecoderOutput)}.
- * <tt>doDecode()</tt> is invoked repeatedly until it returns <tt>false</tt>
- * and the cumulative buffer is compacted after decoding ends.
- *
- * @throws IllegalStateException if your <tt>doDecode()</tt> returned
- * <tt>true</tt> not consuming the cumulative buffer.
- */
- public void decode( IoSession session, ByteBuffer in,
- ProtocolDecoderOutput out ) throws Exception
- {
- ByteBuffer buf = ( ByteBuffer ) session.getAttribute( BUFFER );
- // if we have a session buffer, append data to that otherwise
- // use the buffer read from the network directly
- if( buf != null )
- {
- buf.put( in );
- buf.flip();
- }
- else
- {
- buf = in;
- }
-
- for( ;; )
- {
- int oldPos = buf.position();
- boolean decoded = doDecode( session, buf, out );
- if( decoded )
- {
- if( buf.position() == oldPos )
- {
- throw new IllegalStateException(
- "doDecode() can't return true when buffer is not consumed." );
- }
-
- if( !buf.hasRemaining() )
- {
- break;
- }
- }
- else
- {
- break;
- }
- }
-
- // if there is any data left that cannot be decoded, we store
- // it in a buffer in the session and next time this decoder is
- // invoked the session buffer gets appended to
- if ( buf.hasRemaining() )
- {
- storeRemainingInSession( buf, session );
- }
- else
- {
- removeSessionBuffer( session );
- }
- }
-
- /**
- * Releases the cumulative buffer used by the specified <tt>session</tt>.
- * Please don't forget to call <tt>super.dispose( session )</tt> when
- * you override this method.
- */
- public void dispose( IoSession session ) throws Exception
- {
- removeSessionBuffer( session );
- }
-
- private void removeSessionBuffer(IoSession session)
- {
- ByteBuffer buf = ( ByteBuffer ) session.getAttribute( BUFFER );
- if( buf != null )
- {
- buf.release();
- session.removeAttribute( BUFFER );
- }
- }
-
- private static final SimpleByteBufferAllocator SIMPLE_BYTE_BUFFER_ALLOCATOR = new SimpleByteBufferAllocator();
-
- private void storeRemainingInSession(ByteBuffer buf, IoSession session)
- {
- ByteBuffer remainingBuf = SIMPLE_BYTE_BUFFER_ALLOCATOR.allocate( buf.remaining(), false );
- remainingBuf.setAutoExpand( true );
- remainingBuf.put( buf );
- session.setAttribute( BUFFER, remainingBuf );
- }
-
- public ArrayList<AMQDataBlock> decodeBuffer(java.nio.ByteBuffer buf) throws AMQFrameDecodingException, AMQProtocolVersionException
- {
-
- // get prior remaining data from accumulator
- ArrayList<AMQDataBlock> dataBlocks = new ArrayList<AMQDataBlock>();
- ByteBuffer msg;
- // if we have a session buffer, append data to that otherwise
- // use the buffer read from the network directly
- if( _remainingBuf != null )
- {
- _remainingBuf.put(buf);
- _remainingBuf.flip();
- msg = _remainingBuf;
- }
- else
- {
- msg = ByteBuffer.wrap(buf);
- }
-
- if (_expectProtocolInitiation
- || (firstDecode
- && (msg.remaining() > 0)
- && (msg.get(msg.position()) == (byte)'A')))
- {
- if (_piDecoder.decodable(msg.buf()))
- {
- dataBlocks.add(new ProtocolInitiation(msg.buf()));
- }
- }
- else
- {
- boolean enoughData = true;
- while (enoughData)
- {
- int pos = msg.position();
-
- enoughData = _dataBlockDecoder.decodable(msg);
- msg.position(pos);
- if (enoughData)
- {
- dataBlocks.add(_dataBlockDecoder.createAndPopulateFrame(_bodyFactory, msg));
- }
- else
- {
- _remainingBuf = SIMPLE_BYTE_BUFFER_ALLOCATOR.allocate(msg.remaining(), false);
- _remainingBuf.setAutoExpand(true);
- _remainingBuf.put(msg);
- }
- }
- }
- if(firstDecode && dataBlocks.size() > 0)
- {
- firstDecode = false;
- }
- return dataBlocks;
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/codec/AMQEncoder.java b/java/common/src/main/java/org/apache/qpid/codec/AMQEncoder.java
deleted file mode 100644
index 53f48ae1c8..0000000000
--- a/java/common/src/main/java/org/apache/qpid/codec/AMQEncoder.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.
- *
- */
-package org.apache.qpid.codec;
-
-import org.apache.mina.common.IoSession;
-import org.apache.mina.filter.codec.ProtocolEncoder;
-import org.apache.mina.filter.codec.ProtocolEncoderOutput;
-
-import org.apache.qpid.framing.AMQDataBlockEncoder;
-
-/**
- * AMQEncoder delegates encoding of AMQP to a data encoder.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Delegate AMQP encoding. <td> {@link AMQDataBlockEncoder}
- * </table>
- *
- * @todo This class just delegates to another, so seems to be pointless. Unless it is going to handle some
- * responsibilities in the future, then drop it.
- */
-public class AMQEncoder implements ProtocolEncoder
-{
- /** The data encoder that is delegated to. */
- private AMQDataBlockEncoder _dataBlockEncoder = new AMQDataBlockEncoder();
-
- /**
- * Encodes AMQP.
- *
- * @param session The Mina session.
- * @param message The data object to encode.
- * @param out The Mina writer to output the raw byte data to.
- *
- * @throws Exception If the data cannot be encoded for any reason.
- */
- public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception
- {
- _dataBlockEncoder.encode(session, message, out);
- }
-
- /**
- * Does nothing. Called by Mina to allow this to clean up resources when it is no longer needed.
- *
- * @param session The Mina session.
- */
- public void dispose(IoSession session)
- { }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/common/AMQPFilterTypes.java b/java/common/src/main/java/org/apache/qpid/common/AMQPFilterTypes.java
deleted file mode 100644
index 9ed915cc35..0000000000
--- a/java/common/src/main/java/org/apache/qpid/common/AMQPFilterTypes.java
+++ /dev/null
@@ -1,61 +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.common;
-
-import org.apache.qpid.framing.AMQShortString;
-
-/**
- * Specifies the different filter types for consumers that filter their messages.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Represent different consumer filter types.
- * </table>
- */
-public enum AMQPFilterTypes
-{
- JMS_SELECTOR("x-filter-jms-selector"),
- NO_CONSUME("x-filter-no-consume"),
- AUTO_CLOSE("x-filter-auto-close");
-
- /** The identifying string for the filter type. */
- private final AMQShortString _value;
-
- /**
- * Creates a new filter type from its identifying string.
- *
- * @param value The identifying string.
- */
- AMQPFilterTypes(String value)
- {
- _value = new AMQShortString(value);
- }
-
- /**
- * Gets the identifying string of the filter type.
- *
- * @return The identifying string of the filter type.
- */
- public AMQShortString getValue()
- {
- return _value;
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/common/ClientProperties.java b/java/common/src/main/java/org/apache/qpid/common/ClientProperties.java
deleted file mode 100644
index 7371c12519..0000000000
--- a/java/common/src/main/java/org/apache/qpid/common/ClientProperties.java
+++ /dev/null
@@ -1,52 +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.common;
-
-import org.apache.qpid.framing.AMQShortString;
-
-/**
- * Specifies the available client property types that different clients can use to identify themselves with.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Specify the available client property types.
- * </table>
- */
-public enum ClientProperties
-{
- instance("instance"),
- product("product"),
- version("version"),
- platform("platform");
-
- private final AMQShortString _amqShortString;
-
- private ClientProperties(String name)
- {
- _amqShortString = new AMQShortString(name);
- }
-
-
- public AMQShortString toAMQShortString()
- {
- return _amqShortString;
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/common/Closeable.java b/java/common/src/main/java/org/apache/qpid/common/Closeable.java
deleted file mode 100644
index 45a98b5843..0000000000
--- a/java/common/src/main/java/org/apache/qpid/common/Closeable.java
+++ /dev/null
@@ -1,27 +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.common;
-
-
-public interface Closeable
-{
- public void close();
-}
diff --git a/java/common/src/main/java/org/apache/qpid/common/QpidProperties.java b/java/common/src/main/java/org/apache/qpid/common/QpidProperties.java
deleted file mode 100644
index 2c783aeaa4..0000000000
--- a/java/common/src/main/java/org/apache/qpid/common/QpidProperties.java
+++ /dev/null
@@ -1,190 +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.common;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Map;
-import java.util.Properties;
-
-/**
- * QpidProperties captures the project name, version number, and source code repository revision number from a properties
- * file which is generated as part of the build process. Normally, the name and version number are pulled from the module
- * name and version number of the Maven build POM, but could come from other sources if the build system is changed. The
- * idea behind this, is that every build has these values incorporated directly into its jar file, so that code in the
- * wild can be identified, should its origination be forgotten.
- *
- * <p/>To get the build version of any Qpid code call the {@link #main} method. This version string is usually also
- * printed to the console on broker start up.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><td>Load build versioning information into the runtime, for code identification purposes.
- * </table>
- *
- * @todo Code to locate/load/log properties can be factored into a reusable properties utils class. Avoid having this
- * same snippet of loading code scattered in many places.
- *
- * @todo Could also add a build number property for a sequential build number assigned by an automated build system, for
- * build reproducability purposes.
- */
-public class QpidProperties
-{
- /** Used for debugging purposes. */
- private static final Logger _logger = LoggerFactory.getLogger(QpidProperties.class);
-
- /** The name of the version properties file to load from the class path. */
- public static final String VERSION_RESOURCE = "qpidversion.properties";
-
- /** Defines the name of the product property. */
- public static final String PRODUCT_NAME_PROPERTY = "qpid.name";
-
- /** Defines the name of the version property. */
- public static final String RELEASE_VERSION_PROPERTY = "qpid.version";
-
- /** Defines the name of the source code revision property. */
- public static final String BUILD_VERSION_PROPERTY = "qpid.svnversion";
-
- /** Defines the default value for all properties that cannot be loaded. */
- private static final String DEFAULT = "unknown";
-
- /** Holds the product name. */
- private static String productName = DEFAULT;
-
- /** Holds the product version. */
- private static String releaseVersion = DEFAULT;
-
- /** Holds the source code revision. */
- private static String buildVersion = DEFAULT;
-
- // Loads the values from the version properties file.
- static
- {
- Properties props = new Properties();
-
- try
- {
- InputStream propertyStream = QpidProperties.class.getClassLoader().getResourceAsStream(VERSION_RESOURCE);
- if (propertyStream == null)
- {
- _logger.warn("Unable to find resource " + VERSION_RESOURCE + " from classloader");
- }
- else
- {
- props.load(propertyStream);
-
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Dumping QpidProperties");
- for (Map.Entry<Object, Object> entry : props.entrySet())
- {
- _logger.debug("Property: " + entry.getKey() + " Value: " + entry.getValue());
- }
-
- _logger.debug("End of property dump");
- }
-
- productName = readPropertyValue(props, PRODUCT_NAME_PROPERTY);
- releaseVersion = readPropertyValue(props, RELEASE_VERSION_PROPERTY);
- buildVersion = readPropertyValue(props, BUILD_VERSION_PROPERTY);
- }
- }
- catch (IOException e)
- {
- // Log a warning about this and leave the values initialized to unknown.
- _logger.error("Could not load version.properties resource: " + e, e);
- }
- }
-
- /**
- * Gets the product name.
- *
- * @return The product name.
- */
- public static String getProductName()
- {
- return productName;
- }
-
- /**
- * Gets the product version.
- *
- * @return The product version.
- */
- public static String getReleaseVersion()
- {
- return releaseVersion;
- }
-
- /**
- * Gets the source code revision.
- *
- * @return The source code revision.
- */
- public static String getBuildVersion()
- {
- return buildVersion;
- }
-
- /**
- * Extracts all of the version information as a printable string.
- *
- * @return All of the version information as a printable string.
- */
- public static String getVersionString()
- {
- return getProductName() + " - " + getReleaseVersion() + " build: " + getBuildVersion();
- }
-
- /**
- * Helper method to extract a named property from properties.
- *
- * @param props The properties.
- * @param propertyName The named property to extract.
- *
- * @return The extracted property or a default value if the properties do not contain the named property.
- *
- * @todo A bit pointless.
- */
- private static String readPropertyValue(Properties props, String propertyName)
- {
- String retVal = (String) props.get(propertyName);
- if (retVal == null)
- {
- retVal = DEFAULT;
- }
-
- return retVal;
- }
-
- /**
- * Prints the versioning information to the console. This is extremely usefull for identifying Qpid code in the
- * wild, where the origination of the code has been forgotten.
- *
- * @param args Does not require any arguments.
- */
- public static void main(String[] args)
- {
- System.out.println(getVersionString());
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/configuration/Accessor.java b/java/common/src/main/java/org/apache/qpid/configuration/Accessor.java
deleted file mode 100644
index dc5b69dc89..0000000000
--- a/java/common/src/main/java/org/apache/qpid/configuration/Accessor.java
+++ /dev/null
@@ -1,273 +0,0 @@
-package org.apache.qpid.configuration;
-/*
- *
- * 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 java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-
-public interface Accessor
-{
- public Boolean getBoolean(String name);
- public Integer getInt(String name);
- public Long getLong(String name);
- public String getString(String name);
-
- static class SystemPropertyAccessor implements Accessor
- {
- public Boolean getBoolean(String name)
- {
- return Boolean.getBoolean(name);
- }
-
- public Integer getInt(String name)
- {
- return Integer.getInteger(name);
- }
-
- public Long getLong(String name)
- {
- return Long.getLong(name);
- }
-
- public String getString(String name)
- {
- return System.getProperty(name);
- }
- }
-
- static class MapAccessor implements Accessor
- {
- protected Map<Object,Object> source;
-
- public MapAccessor(Map<Object,Object> map)
- {
- source = map;
- }
-
- public Boolean getBoolean(String name)
- {
- if (source != null && source.containsKey(name))
- {
- if (source.get(name) instanceof Boolean)
- {
- return (Boolean)source.get(name);
- }
- else
- {
- return Boolean.parseBoolean((String)source.get(name));
- }
- }
- else
- {
- return null;
- }
- }
-
- public Integer getInt(String name)
- {
- if (source != null && source.containsKey(name))
- {
- if (source.get(name) instanceof Integer)
- {
- return (Integer)source.get(name);
- }
- else
- {
- return Integer.parseInt((String)source.get(name));
- }
- }
- else
- {
- return null;
- }
- }
-
- public Long getLong(String name)
- {
- if (source != null && source.containsKey(name))
- {
- if (source.get(name) instanceof Long)
- {
- return (Long)source.get(name);
- }
- else
- {
- return Long.parseLong((String)source.get(name));
- }
- }
- else
- {
- return null;
- }
- }
-
- public String getString(String name)
- {
- if (source != null && source.containsKey(name))
- {
- if (source.get(name) instanceof String)
- {
- return (String)source.get(name);
- }
- else
- {
- return String.valueOf(source.get(name));
- }
- }
- else
- {
- return null;
- }
- }
- }
-
- static class PropertyFileAccessor extends MapAccessor
- {
- public PropertyFileAccessor(String fileName) throws FileNotFoundException, IOException
- {
- super(null);
- Properties props = new Properties();
- FileInputStream inStream = new FileInputStream(fileName);
- try
- {
- props.load(inStream);
- }
- finally
- {
- inStream.close();
- }
- source = props;
- }
- }
-
- static class CombinedAccessor implements Accessor
- {
- private List<Accessor> accessors;
-
- public CombinedAccessor(Accessor...accessors)
- {
- this.accessors = Arrays.asList(accessors);
- }
-
- public Boolean getBoolean(String name)
- {
- for (Accessor accessor: accessors)
- {
- if (accessor.getBoolean(name) != null)
- {
- return accessor.getBoolean(name);
- }
- }
- return null;
- }
-
- public Integer getInt(String name)
- {
- for (Accessor accessor: accessors)
- {
- if (accessor.getBoolean(name) != null)
- {
- return accessor.getInt(name);
- }
- }
- return null;
- }
-
- public Long getLong(String name)
- {
- for (Accessor accessor: accessors)
- {
- if (accessor.getBoolean(name) != null)
- {
- return accessor.getLong(name);
- }
- }
- return null;
- }
-
- public String getString(String name)
- {
- for (Accessor accessor: accessors)
- {
- if (accessor.getBoolean(name) != null)
- {
- return accessor.getString(name);
- }
- }
- return null;
- }
- }
-
- static class ValidationAccessor implements Accessor
- {
- private List<Validator> validators;
- private Accessor delegate;
-
- public ValidationAccessor(Accessor delegate,Validator...validators)
- {
- this.validators = Arrays.asList(validators);
- this.delegate = delegate;
- }
-
- public Boolean getBoolean(String name)
- {
- // there is nothing to validate in a boolean
- return delegate.getBoolean(name);
- }
-
- public Integer getInt(String name)
- {
- Integer v = delegate.getInt(name);
- for (Validator validator: validators)
- {
- validator.validate(v);
- }
- return v;
- }
-
- public Long getLong(String name)
- {
- Long v = delegate.getLong(name);
- for (Validator validator: validators)
- {
- validator.validate(v);
- }
- return v;
- }
-
- public String getString(String name)
- {
- String v = delegate.getString(name);
- for (Validator validator: validators)
- {
- validator.validate(v);
- }
- return v;
- }
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/configuration/ClientProperties.java b/java/common/src/main/java/org/apache/qpid/configuration/ClientProperties.java
deleted file mode 100644
index 0dd21238a7..0000000000
--- a/java/common/src/main/java/org/apache/qpid/configuration/ClientProperties.java
+++ /dev/null
@@ -1,134 +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;
-
-/**
- * This class centralized the Qpid client properties.
- */
-public class ClientProperties
-{
-
- /**
- * Currently with Qpid it is not possible to change the client ID.
- * If one is not specified upon connection construction, an id is generated automatically.
- * Therefore an exception is always thrown unless this property is set to true.
- * type: boolean
- */
- public static final String IGNORE_SET_CLIENTID_PROP_NAME = "ignore_setclientID";
-
- /**
- * This property is currently used within the 0.10 code path only
- * The maximum number of pre-fetched messages per destination
- * This property is used for all the connection unless it is overwritten by the connectionURL
- * type: long
- */
- public static final String MAX_PREFETCH_PROP_NAME = "max_prefetch";
- public static final String MAX_PREFETCH_DEFAULT = "500";
-
- /**
- * When true a sync command is sent after every persistent messages.
- * type: boolean
- */
- public static final String SYNC_PERSISTENT_PROP_NAME = "sync_persistence";
-
- /**
- * When true a sync command is sent after sending a message ack.
- * type: boolean
- */
- public static final String SYNC_ACK_PROP_NAME = "sync_ack";
-
- /**
- * sync_publish property - {persistent|all}
- * If set to 'persistent',then persistent messages will be publish synchronously
- * If set to 'all', then all messages regardless of the delivery mode will be
- * published synchronously.
- */
- public static final String SYNC_PUBLISH_PROP_NAME = "sync_publish";
-
- /**
- * This value will be used in the following settings
- * To calculate the SO_TIMEOUT option of the socket (2*idle_timeout)
- * If this values is between the max and min values specified for heartbeat
- * by the broker in TuneOK it will be used as the heartbeat interval.
- * If not a warning will be printed and the max value specified for
- * heartbeat in TuneOK will be used
- *
- * The default idle timeout is set to 120 secs
- */
- public static final String IDLE_TIMEOUT_PROP_NAME = "idle_timeout";
- public static final long DEFAULT_IDLE_TIMEOUT = 120000;
-
- public static final String HEARTBEAT = "qpid.heartbeat";
- public static final int HEARTBEAT_DEFAULT = 120;
-
- /**
- * This value will be used to determine the default destination syntax type.
- * Currently the two types are Binding URL (java only) and the Addressing format (used by
- * all clients).
- */
- public static final String DEST_SYNTAX = "qpid.dest_syntax";
-
- public static final String USE_LEGACY_MAP_MESSAGE_FORMAT = "qpid.use_legacy_map_message";
-
- /**
- * ==========================================================
- * Those properties are used when the io size should be bounded
- * ==========================================================
- */
-
- /**
- * When set to true the io layer throttle down producers and consumers
- * when written or read messages are accumulating and exceeding a certain size.
- * This is especially useful when a the producer rate is greater than the network
- * speed.
- * type: boolean
- */
- public static final String PROTECTIO_PROP_NAME = "protectio";
-
- //=== The following properties are only used when the previous one is true.
- /**
- * Max size of read messages that can be stored within the MINA layer
- * type: int
- */
- public static final String READ_BUFFER_LIMIT_PROP_NAME = "qpid.read.buffer.limit";
- public static final String READ_BUFFER_LIMIT_DEFAULT = "262144";
- /**
- * Max size of written messages that can be stored within the MINA layer
- * type: int
- */
- public static final String WRITE_BUFFER_LIMIT_PROP_NAME = "qpid.read.buffer.limit";
- public static final String WRITE_BUFFER_LIMIT_DEFAULT = "262144";
-
- public static final String AMQP_VERSION = "qpid.amqp.version";
-
- private static ClientProperties _instance = new ClientProperties();
-
- /*
- public static final QpidProperty<Boolean> IGNORE_SET_CLIENTID_PROP_NAME =
- QpidProperty.booleanProperty(false,"qpid.ignore_set_client_id","ignore_setclientID");
-
- public static final QpidProperty<Boolean> SYNC_PERSISTENT_PROP_NAME =
- QpidProperty.booleanProperty(false,"qpid.sync_persistence","sync_persistence");
-
-
- public static final QpidProperty<Integer> MAX_PREFETCH_PROP_NAME =
- QpidProperty.intProperty(500,"qpid.max_prefetch","max_prefetch"); */
-
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/configuration/Configured.java b/java/common/src/main/java/org/apache/qpid/configuration/Configured.java
deleted file mode 100644
index 22903888fe..0000000000
--- a/java/common/src/main/java/org/apache/qpid/configuration/Configured.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.configuration;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- * Marks a field as having a "configured" value injected into it by a configurator.
- */
-@Retention(RetentionPolicy.RUNTIME)
-@Target(ElementType.FIELD)
-public @interface Configured
-{
- /**
- * The Commons Configuration path to the configuration element
- */
- String path();
-
- /**
- * The default value to use should the path not be found in the configuration source
- */
- String defaultValue();
-}
diff --git a/java/common/src/main/java/org/apache/qpid/configuration/PropertyException.java b/java/common/src/main/java/org/apache/qpid/configuration/PropertyException.java
deleted file mode 100644
index 73a336321c..0000000000
--- a/java/common/src/main/java/org/apache/qpid/configuration/PropertyException.java
+++ /dev/null
@@ -1,43 +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.qpid.AMQException;
-import org.apache.qpid.protocol.AMQConstant;
-
-/**
- * Indicates a failure to parse a property expansion. See {@link PropertyUtils} for the code that does property
- * expansions.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaboration
- * <tr><td> Represent failure to expand a property name into a value.
- * </table>
- *
- * @todo Not an AMQP exception as no status code.
- */
-public class PropertyException extends AMQException
-{
- public PropertyException(String message, Throwable cause)
- {
- super(null, message, cause);
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/configuration/PropertyUtils.java b/java/common/src/main/java/org/apache/qpid/configuration/PropertyUtils.java
deleted file mode 100644
index 6e2b25fb2c..0000000000
--- a/java/common/src/main/java/org/apache/qpid/configuration/PropertyUtils.java
+++ /dev/null
@@ -1,164 +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 java.util.ArrayList;
-import java.util.Iterator;
-
-/**
- * PropertyUtils provides helper methods for dealing with Java properties.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Expand system properties into strings with named expansions.
- * </table>
- *
- * @todo Make the lookup method generic by passing in the properties to use for the expansion, rather than hard coding
- * as system properties. The expansion code has greater potential for re-use that way.
- *
- * @todo Some more property related code could be added to this utils class, which might more appropriately reside under
- * org.apache.qpid.util. For example standardised code to load properties from a resource name, currently found in
- * QpidProperties and possibly other places could be moved here.
- */
-public class PropertyUtils
-{
- /**
- * Given a string that contains substrings of the form <code>${xxx}</code>, looks up the valuea of 'xxx' as a
- * system properties and substitutes tham back into the original string, to provide a property value expanded
- * string.
- *
- * @param value The string to be scanned for property references. May be <code>null</code>, in which case this
- * method returns immediately with no effect.
- *
- * @return The original string with the properties replaced, or <code>null</code> if the original string is
- * <code>null</code>.
- *
- * @throws PropertyException If the string contains an opening <code>${</code> without a balancing <code>}</code>,
- * or if the property to expand does not exist as a system property.
- */
- public static String replaceProperties(String value) throws PropertyException
- {
- if (value == null)
- {
- return null;
- }
-
- ArrayList<String> fragments = new ArrayList<String>();
- ArrayList<String> propertyRefs = new ArrayList<String>();
- parsePropertyString(value, fragments, propertyRefs);
-
- StringBuffer sb = new StringBuffer();
- Iterator j = propertyRefs.iterator();
-
- for (String fragment : fragments)
- {
- if (fragment == null)
- {
- String propertyName = (String) j.next();
-
- // try to get it from the project or keys
- // Backward compatibility
- String replacement = System.getProperty(propertyName);
-
- if (replacement == null)
- {
- throw new PropertyException("Property ${" + propertyName + "} has not been set", null);
- }
-
- fragment = replacement;
- }
-
- sb.append(fragment);
- }
-
- return sb.toString();
- }
-
- /**
- * Parses the supplied value for properties which are specified using ${foo} syntax. $X is left as is, and $$
- * specifies a single $.
- *
- * @param value The property string to parse.
- * @param fragments Is populated with the string fragments. A null means "insert a property value here. The number
- * of nulls in the list when populated is equal to the size of the propertyRefs list.
- * @param propertyRefs Populated with the property names to be added into the final string.
- */
- private static void parsePropertyString(String value, ArrayList<String> fragments, ArrayList<String> propertyRefs)
- throws PropertyException
- {
- int prev = 0;
- int pos;
- // search for the next instance of $ from the 'prev' position
- while ((pos = value.indexOf("$", prev)) >= 0)
- {
-
- // if there was any text before this, add it as a fragment
- if (pos > 0)
- {
- fragments.add(value.substring(prev, pos));
- }
- // if we are at the end of the string, we tack on a $
- // then move past it
- if (pos == (value.length() - 1))
- {
- fragments.add("$");
- prev = pos + 1;
- }
- else if (value.charAt(pos + 1) != '{')
- {
- // peek ahead to see if the next char is a property or not
- // not a property: insert the char as a literal
- if (value.charAt(pos + 1) == '$')
- {
- // two $ map to one $
- fragments.add("$");
- prev = pos + 2;
- }
- else
- {
- // $X maps to $X for all values of X!='$'
- fragments.add(value.substring(pos, pos + 2));
- prev = pos + 2;
- }
- }
- else
- {
- // property found, extract its name or bail on a typo
- int endName = value.indexOf('}', pos);
- if (endName < 0)
- {
- throw new PropertyException("Syntax error in property: " + value, null);
- }
-
- String propertyName = value.substring(pos + 2, endName);
- fragments.add(null);
- propertyRefs.add(propertyName);
- prev = endName + 1;
- }
- }
- // no more $ signs found
- // if there is any tail to the file, append it
- if (prev < value.length())
- {
- fragments.add(value.substring(prev));
- }
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/configuration/QpidProperty.java b/java/common/src/main/java/org/apache/qpid/configuration/QpidProperty.java
deleted file mode 100644
index 9c0aaaec89..0000000000
--- a/java/common/src/main/java/org/apache/qpid/configuration/QpidProperty.java
+++ /dev/null
@@ -1,181 +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.qpid.configuration.Accessor.SystemPropertyAccessor;
-
-abstract class QpidProperty<T>
-{
- private T defValue;
- private String[] names;
- protected Accessor accessor;
-
- QpidProperty(T defValue, String... names)
- {
- this(new SystemPropertyAccessor(),defValue,names);
- }
-
- QpidProperty(Accessor accessor,T defValue, String... names)
- {
- this.accessor = accessor;
- this.defValue = defValue;
- this.names = names;
- }
-
- T get()
- {
- for (String name : names)
- {
- T obj = getByName(name);
- if (obj != null)
- {
- return obj;
- }
- }
-
- return defValue;
- }
-
- protected abstract T getByName(String name);
-
- public static QpidProperty<Boolean> booleanProperty(Boolean defaultValue,
- String... names)
- {
- return new QpidBooleanProperty(defaultValue, names);
- }
-
- public static QpidProperty<Boolean> booleanProperty(Accessor accessor,
- Boolean defaultValue,String... names)
- {
- return new QpidBooleanProperty(accessor,defaultValue, names);
- }
-
- public static QpidProperty<Integer> intProperty(Integer defaultValue,
- String... names)
- {
- return new QpidIntProperty(defaultValue, names);
- }
-
- public static QpidProperty<Integer> intProperty(Accessor accessor,
- Integer defaultValue, String... names)
- {
- return new QpidIntProperty(accessor,defaultValue, names);
- }
-
- public static QpidProperty<Long> longProperty(Long defaultValue,
- String... names)
- {
- return new QpidLongProperty(defaultValue, names);
- }
-
- public static QpidProperty<Long> longProperty(Accessor accessor,
- Long defaultValue, String... names)
- {
- return new QpidLongProperty(accessor,defaultValue, names);
- }
-
- public static QpidProperty<String> stringProperty(String defaultValue,
- String... names)
- {
- return new QpidStringProperty(defaultValue, names);
- }
-
- public static QpidProperty<String> stringProperty(Accessor accessor,
- String defaultValue,String... names)
- {
- return new QpidStringProperty(accessor,defaultValue, names);
- }
-
- static class QpidBooleanProperty extends QpidProperty<Boolean>
- {
- QpidBooleanProperty(Boolean defValue, String... names)
- {
- super(defValue, names);
- }
-
- QpidBooleanProperty(Accessor accessor,Boolean defValue, String... names)
- {
- super(accessor,defValue, names);
- }
-
- @Override
- protected Boolean getByName(String name)
- {
- return accessor.getBoolean(name);
- }
- }
-
- static class QpidIntProperty extends QpidProperty<Integer>
- {
- QpidIntProperty(Integer defValue, String... names)
- {
- super(defValue, names);
- }
-
- QpidIntProperty(Accessor accessor,Integer defValue, String... names)
- {
- super(accessor,defValue, names);
- }
-
- @Override
- protected Integer getByName(String name)
- {
- return accessor.getInt(name);
- }
- }
-
- static class QpidLongProperty extends QpidProperty<Long>
- {
- QpidLongProperty(Long defValue, String... names)
- {
- super(defValue, names);
- }
-
- QpidLongProperty(Accessor accessor,Long defValue, String... names)
- {
- super(accessor,defValue, names);
- }
-
- @Override
- protected Long getByName(String name)
- {
- return accessor.getLong(name);
- }
- }
-
- static class QpidStringProperty extends QpidProperty<String>
- {
- QpidStringProperty(String defValue, String... names)
- {
- super(defValue, names);
- }
-
- QpidStringProperty(Accessor accessor,String defValue, String... names)
- {
- super(accessor,defValue, names);
- }
-
- @Override
- protected String getByName(String name)
- {
- return accessor.getString(name);
- }
- }
-
-} \ No newline at end of file
diff --git a/java/common/src/main/java/org/apache/qpid/configuration/Validator.java b/java/common/src/main/java/org/apache/qpid/configuration/Validator.java
deleted file mode 100644
index 13f7954bbc..0000000000
--- a/java/common/src/main/java/org/apache/qpid/configuration/Validator.java
+++ /dev/null
@@ -1,31 +0,0 @@
-package org.apache.qpid.configuration;
-/*
- *
- * 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 interface Validator
-{
- public void validate(Integer value);
-
- public void validate(Long value);
-
- public void validate(String value);
-}
diff --git a/java/common/src/main/java/org/apache/qpid/dtx/XidImpl.java b/java/common/src/main/java/org/apache/qpid/dtx/XidImpl.java
deleted file mode 100644
index 69457ca4a9..0000000000
--- a/java/common/src/main/java/org/apache/qpid/dtx/XidImpl.java
+++ /dev/null
@@ -1,259 +0,0 @@
-/* Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.qpid.dtx;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.qpid.AMQInvalidArgumentException;
-
-import javax.transaction.xa.Xid;
-
-import java.io.*;
-import java.util.Arrays;
-
-/**
- * Implements javax.transaction.dtx.Xid
- */
-public class XidImpl implements Xid
-{
- /**
- * this session's logger
- */
- private static final Logger _logger = LoggerFactory.getLogger(XidImpl.class);
-
- /**
- * the transaction branch identifier part of XID as an array of bytes
- */
- private byte[] _branchQualifier;
-
- /**
- * the format identifier part of the XID.
- */
- private int _formatID;
-
- /**
- * the global transaction identifier part of XID as an array of bytes.
- */
- private byte[] _globalTransactionID;
-
- //--- Constructors
-
- /**
- * Create new Xid.
- * this is an empty constructor.
- */
- public XidImpl()
- {
-
- }
-
- /**
- * Create a new XidImpl from an existing Xid.
- * <p> Usefull for casting external Xids
- *
- * @param xid Foreign Xid.
- */
- public XidImpl(Xid xid)
- {
- _branchQualifier = xid.getBranchQualifier();
- _formatID = xid.getFormatId();
- _globalTransactionID = xid.getGlobalTransactionId();
- }
-
- /**
- * Create a new Xid.
- *
- * @param branchQualifier The transaction branch identifier part of XID as an array of bytes.
- * @param format The format identifier part of the XID.
- * @param globalTransactionID The global transaction identifier part of XID as an array of bytes.
- */
- public XidImpl(byte[] branchQualifier, int format, byte[] globalTransactionID)
- {
- _branchQualifier = branchQualifier;
- _formatID = format;
- _globalTransactionID = globalTransactionID;
- }
-
- /**
- * Create a new Xid form its String form
- * 4 1 1 g b
- * +---+---+---+---+---+---+---+- -+---+---+- -+---+
- * | format_id | g | b | txn-id | br-id |
- * +---+---+---+---+---+---+---+- -+---+---+- -+---+
- * 0 4 5 6 6+g 6+g+b
- * format_id: an implementation specific format identifier
- * <p/>
- * gtrid_length: how many bytes of this form the transaction id
- * <p/>
- * bqual_length: how many bytes of this form the branch id
- * <p/>
- * data: a sequence of octets of at most 128 bytes containing the txn id and the
- * branch id
- * <p/>
- * Note - The sum of the two lengths must equal the length of the data field.
- *
- * @param xid an XID STring Form
- * @throws AMQInvalidArgumentException If the string does not represent a valid Xid
- */
- public XidImpl(String xid) throws AMQInvalidArgumentException
- {
- if (_logger.isDebugEnabled())
- {
- _logger.debug("converting string " + xid + " into XidImpl");
- }
- try
- {
- DataInputStream input = new DataInputStream(new ByteArrayInputStream(xid.getBytes()));
- _formatID = (int) input.readLong();
- int g = input.readByte();
- int b = input.readByte();
- _globalTransactionID = new byte[g];
- _branchQualifier = new byte[b];
- if (input.read(_globalTransactionID, 0, g) != g)
- {
- throw new AMQInvalidArgumentException("Cannot convert the string " + xid + " into an Xid", null);
- }
- if (input.read(_branchQualifier, 0, b) != b)
- {
- throw new AMQInvalidArgumentException("Cannot convert the string " + xid + " into an Xid", null);
- }
- }
- catch (IOException e)
- {
- throw new AMQInvalidArgumentException("cannot convert the string " + xid + " into an Xid", e);
- }
- }
-
- //--- Xid interface implementation
-
- /**
- * Format identifier. O means the OSI CCR format.
- *
- * @return Global transaction identifier.
- */
- public byte[] getGlobalTransactionId()
- {
- return _globalTransactionID;
- }
-
- /**
- * Obtain the transaction branch identifier part of XID as an array of bytes.
- *
- * @return Branch identifier part of XID.
- */
- public byte[] getBranchQualifier()
- {
- return _branchQualifier;
- }
-
- /**
- * Obtain the format identifier part of the XID.
- *
- * @return Format identifier. O means the OSI CCR format.
- */
- public int getFormatId()
- {
- return _formatID;
- }
-
- //--- Object operations
-
- /**
- * Indicates whether some other Xid is "equal to" this one.
- * <p> Two Xids are equal if and only if their three elementary parts are equal
- *
- * @param o the object to compare this <code>XidImpl</code> against.
- * @return true if the <code>XidImpl</code> are equal, false otherwise.
- */
- public boolean equals(Object o)
- {
- if (this == o)
- {
- return true;
- }
- if (o instanceof XidImpl)
- {
- XidImpl other = (XidImpl) o;
- if (_formatID == other.getFormatId())
- {
- if (_branchQualifier.length == other.getBranchQualifier().length)
- {
- for (int i = 0; i < _branchQualifier.length; i++)
- {
- if (_branchQualifier[i] != other.getBranchQualifier()[i])
- {
- return false;
- }
- }
- if (_globalTransactionID.length == other.getGlobalTransactionId().length)
- {
- for (int i = 0; i < _globalTransactionID.length; i++)
- {
- if (_globalTransactionID[i] != other.getGlobalTransactionId()[i])
- {
- return false;
- }
- }
- // everithing is equal
- return true;
- }
- }
- }
- }
- return false;
- }
-
- @Override
- public int hashCode()
- {
- int result = _branchQualifier != null ? Arrays.hashCode(_branchQualifier) : 0;
- result = 31 * result + _formatID;
- result = 31 * result + (_globalTransactionID != null ? Arrays.hashCode(_globalTransactionID) : 0);
- return result;
- }
-
- //-- Static helper method
- /**
- * Convert an Xid into the AMQP String format.
- *
- * 4 1 1 g b
- * +---+---+---+---+---+---+---+- -+---+---+- -+---+
- * | format_id | g | b | txn-id | br-id |
- * +---+---+---+---+---+---+---+- -+---+---+- -+---+
- * 0 4 5 6 6+g 6+g+b
- * format_id: an implementation specific format identifier
- * <p/>
- * gtrid_length: how many bytes of this form the transaction id
- * <p/>
- * bqual_length: how many bytes of this form the branch id
- * <p/>
- * data: a sequence of octets of at most 128 bytes containing the txn id and the
- * branch id
- * <p/>
- * Note - The sum of the two lengths must equal the length of the data field.
- *
- * @param xid an Xid to convert.
- * @return The String representation of this Xid
- */
- public static org.apache.qpid.transport.Xid convert(Xid xid)
- {
- return new org.apache.qpid.transport.Xid(xid.getFormatId(),
- xid.getGlobalTransactionId(),
- xid.getBranchQualifier());
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/exchange/ExchangeDefaults.java b/java/common/src/main/java/org/apache/qpid/exchange/ExchangeDefaults.java
deleted file mode 100644
index 1989ade4ac..0000000000
--- a/java/common/src/main/java/org/apache/qpid/exchange/ExchangeDefaults.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.exchange;
-
-import org.apache.qpid.framing.AMQShortString;
-
-/**
- * Defines the names of the standard AMQP exchanges that every AMQP broker should provide. These exchange names
- * and type are given in the specification.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Defines the standard AMQP exchange names.
- * <tr><td> Defines the standard AMQP exchange types.
- * </table>
- *
- * @todo A type safe enum, might be more appropriate for the exchange types.
- */
-public class ExchangeDefaults
-{
- /** The default direct exchange, which is a special internal exchange that cannot be explicitly bound to. */
- public static final AMQShortString DEFAULT_EXCHANGE_NAME = new AMQShortString("<<default>>");
-
- /** The pre-defined topic exchange, the broker SHOULD provide this. */
- public static final AMQShortString TOPIC_EXCHANGE_NAME = new AMQShortString("amq.topic");
-
- /** Defines the identifying type name of topic exchanges. */
- public static final AMQShortString TOPIC_EXCHANGE_CLASS = new AMQShortString("topic");
-
- /** The pre-defined direct exchange, the broker MUST provide this. */
- public static final AMQShortString DIRECT_EXCHANGE_NAME = new AMQShortString("amq.direct");
-
- /** Defines the identifying type name of direct exchanges. */
- public static final AMQShortString DIRECT_EXCHANGE_CLASS = new AMQShortString("direct");
-
- /** The pre-defined headers exchange, the specification does not say this needs to be provided. */
- public static final AMQShortString HEADERS_EXCHANGE_NAME = new AMQShortString("amq.match");
-
- /** Defines the identifying type name of headers exchanges. */
- public static final AMQShortString HEADERS_EXCHANGE_CLASS = new AMQShortString("headers");
-
- /** The pre-defined fanout exchange, the boker MUST provide this. */
- public static final AMQShortString FANOUT_EXCHANGE_NAME = new AMQShortString("amq.fanout");
-
- /** Defines the identifying type name of fanout exchanges. */
- public static final AMQShortString FANOUT_EXCHANGE_CLASS = new AMQShortString("fanout");
-
- public static final AMQShortString WILDCARD_ANY = new AMQShortString("*");
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/AMQBody.java b/java/common/src/main/java/org/apache/qpid/framing/AMQBody.java
deleted file mode 100644
index fe04155bb8..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/AMQBody.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.framing;
-
-import org.apache.mina.common.ByteBuffer;
-import org.apache.qpid.protocol.AMQVersionAwareProtocolSession;
-import org.apache.qpid.AMQException;
-
-public interface AMQBody
-{
- public byte getFrameType();
-
- /**
- * Get the size of the body
- * @return unsigned short
- */
- public abstract int getSize();
-
- public void writePayload(ByteBuffer buffer);
-
- void handle(final int channelId, final AMQVersionAwareProtocolSession amqMinaProtocolSession) throws AMQException;
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlock.java b/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlock.java
deleted file mode 100644
index a2fc3a03ef..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlock.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.framing;
-
-import org.apache.mina.common.ByteBuffer;
-
-/**
- * A data block represents something that has a size in bytes and the ability to write itself to a byte
- * buffer (similar to a byte array).
- */
-public abstract class AMQDataBlock implements EncodableAMQDataBlock
-{
- /**
- * Get the size of buffer needed to store the byte representation of this
- * frame.
- * @return unsigned integer
- */
- public abstract long getSize();
-
- /**
- * Writes the datablock to the specified buffer.
- * @param buffer
- */
- public abstract void writePayload(ByteBuffer buffer);
-
- public ByteBuffer toByteBuffer()
- {
- final ByteBuffer buffer = ByteBuffer.allocate((int)getSize());
-
- writePayload(buffer);
- buffer.flip();
- return buffer;
- }
-
- public java.nio.ByteBuffer toNioByteBuffer()
- {
- final java.nio.ByteBuffer buffer = java.nio.ByteBuffer.allocate((int) getSize());
-
- ByteBuffer buf = ByteBuffer.wrap(buffer);
- writePayload(buf);
- buffer.flip();
- return buffer;
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockDecoder.java b/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockDecoder.java
deleted file mode 100644
index 228867b2b0..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockDecoder.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.framing;
-
-import org.apache.mina.common.ByteBuffer;
-import org.apache.mina.common.IoSession;
-import org.apache.mina.filter.codec.ProtocolDecoderOutput;
-
-import org.apache.qpid.protocol.AMQVersionAwareProtocolSession;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class AMQDataBlockDecoder
-{
- private static final String SESSION_METHOD_BODY_FACTORY = "QPID_SESSION_METHOD_BODY_FACTORY";
-
- private static final BodyFactory[] _bodiesSupported = new BodyFactory[Byte.MAX_VALUE];
-
- static
- {
- _bodiesSupported[ContentHeaderBody.TYPE] = ContentHeaderBodyFactory.getInstance();
- _bodiesSupported[ContentBody.TYPE] = ContentBodyFactory.getInstance();
- _bodiesSupported[HeartbeatBody.TYPE] = new HeartbeatBodyFactory();
- }
-
- Logger _logger = LoggerFactory.getLogger(AMQDataBlockDecoder.class);
-
- public AMQDataBlockDecoder()
- { }
-
- public boolean decodable(java.nio.ByteBuffer in) throws AMQFrameDecodingException
- {
- final int remainingAfterAttributes = in.remaining() - (1 + 2 + 4 + 1);
- // type, channel, body length and end byte
- if (remainingAfterAttributes < 0)
- {
- return false;
- }
-
- in.position(in.position() + 1 + 2);
- // Get an unsigned int, lifted from MINA ByteBuffer getUnsignedInt()
- final long bodySize = in.getInt() & 0xffffffffL;
-
- return (remainingAfterAttributes >= bodySize);
-
- }
-
- public AMQFrame createAndPopulateFrame(AMQMethodBodyFactory methodBodyFactory, ByteBuffer in)
- throws AMQFrameDecodingException, AMQProtocolVersionException
- {
- final byte type = in.get();
-
- BodyFactory bodyFactory;
- if (type == AMQMethodBody.TYPE)
- {
- bodyFactory = methodBodyFactory;
- }
- else
- {
- bodyFactory = _bodiesSupported[type];
- }
-
- if (bodyFactory == null)
- {
- throw new AMQFrameDecodingException(null, "Unsupported frame type: " + type, null);
- }
-
- final int channel = in.getUnsignedShort();
- final long bodySize = in.getUnsignedInt();
-
- // bodySize can be zero
- if ((channel < 0) || (bodySize < 0))
- {
- throw new AMQFrameDecodingException(null, "Undecodable frame: type = " + type + " channel = " + channel
- + " bodySize = " + bodySize, null);
- }
-
- AMQFrame frame = new AMQFrame(in, channel, bodySize, bodyFactory);
-
- byte marker = in.get();
- if ((marker & 0xFF) != 0xCE)
- {
- throw new AMQFrameDecodingException(null, "End of frame marker not found. Read " + marker + " length=" + bodySize
- + " type=" + type, null);
- }
-
- return frame;
- }
-
- public void decode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) throws Exception
- {
- AMQMethodBodyFactory bodyFactory = (AMQMethodBodyFactory) session.getAttribute(SESSION_METHOD_BODY_FACTORY);
- if (bodyFactory == null)
- {
- AMQVersionAwareProtocolSession protocolSession = (AMQVersionAwareProtocolSession) session.getAttachment();
- bodyFactory = new AMQMethodBodyFactory(protocolSession);
- session.setAttribute(SESSION_METHOD_BODY_FACTORY, bodyFactory);
- }
-
- out.write(createAndPopulateFrame(bodyFactory, in));
- }
-
- public boolean decodable(ByteBuffer msg) throws AMQFrameDecodingException
- {
- return decodable(msg.buf());
- }
-
- public AMQDataBlock createAndPopulateFrame(AMQMethodBodyFactory factory, java.nio.ByteBuffer msg) throws AMQProtocolVersionException, AMQFrameDecodingException
- {
- return createAndPopulateFrame(factory, ByteBuffer.wrap(msg));
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockEncoder.java b/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockEncoder.java
deleted file mode 100644
index 374644b4f2..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockEncoder.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.framing;
-
-import org.apache.mina.common.ByteBuffer;
-import org.apache.mina.common.IoSession;
-import org.apache.mina.filter.codec.ProtocolEncoderOutput;
-import org.apache.mina.filter.codec.demux.MessageEncoder;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.Collections;
-import java.util.Set;
-
-public final class AMQDataBlockEncoder implements MessageEncoder
-{
- private static final Logger _logger = LoggerFactory.getLogger(AMQDataBlockEncoder.class);
-
- private final Set _messageTypes = Collections.singleton(EncodableAMQDataBlock.class);
-
- public AMQDataBlockEncoder()
- { }
-
- public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception
- {
- final AMQDataBlock frame = (AMQDataBlock) message;
-
- final ByteBuffer buffer = frame.toByteBuffer();
-
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Encoded frame byte-buffer is '" + EncodingUtils.convertToHexString(buffer) + "'");
- }
-
- out.write(buffer);
- }
-
- public Set getMessageTypes()
- {
- return _messageTypes;
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/AMQFrame.java b/java/common/src/main/java/org/apache/qpid/framing/AMQFrame.java
deleted file mode 100644
index 02a46f3748..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/AMQFrame.java
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.framing;
-
-import org.apache.mina.common.ByteBuffer;
-
-public class AMQFrame extends AMQDataBlock implements EncodableAMQDataBlock
-{
- private final int _channel;
-
- private final AMQBody _bodyFrame;
- public static final byte FRAME_END_BYTE = (byte) 0xCE;
-
-
- public AMQFrame(final int channel, final AMQBody bodyFrame)
- {
- _channel = channel;
- _bodyFrame = bodyFrame;
- }
-
- public AMQFrame(final ByteBuffer in, final int channel, final long bodySize, final BodyFactory bodyFactory) throws AMQFrameDecodingException
- {
- this._channel = channel;
- this._bodyFrame = bodyFactory.createBody(in,bodySize);
- }
-
- public long getSize()
- {
- return 1 + 2 + 4 + _bodyFrame.getSize() + 1;
- }
-
- public static final int getFrameOverhead()
- {
- return 1 + 2 + 4 + 1;
- }
-
-
- public void writePayload(ByteBuffer buffer)
- {
- buffer.put(_bodyFrame.getFrameType());
- EncodingUtils.writeUnsignedShort(buffer, _channel);
- EncodingUtils.writeUnsignedInteger(buffer, _bodyFrame.getSize());
- _bodyFrame.writePayload(buffer);
- buffer.put(FRAME_END_BYTE);
- }
-
- public final int getChannel()
- {
- return _channel;
- }
-
- public final AMQBody getBodyFrame()
- {
- return _bodyFrame;
- }
-
- public String toString()
- {
- return "Frame channelId: " + _channel + ", bodyFrame: " + String.valueOf(_bodyFrame);
- }
-
- public static void writeFrame(ByteBuffer buffer, final int channel, AMQBody body)
- {
- buffer.put(body.getFrameType());
- EncodingUtils.writeUnsignedShort(buffer, channel);
- EncodingUtils.writeUnsignedInteger(buffer, body.getSize());
- body.writePayload(buffer);
- buffer.put(FRAME_END_BYTE);
-
- }
-
- public static void writeFrames(ByteBuffer buffer, final int channel, AMQBody body1, AMQBody body2)
- {
- buffer.put(body1.getFrameType());
- EncodingUtils.writeUnsignedShort(buffer, channel);
- EncodingUtils.writeUnsignedInteger(buffer, body1.getSize());
- body1.writePayload(buffer);
- buffer.put(FRAME_END_BYTE);
- buffer.put(body2.getFrameType());
- EncodingUtils.writeUnsignedShort(buffer, channel);
- EncodingUtils.writeUnsignedInteger(buffer, body2.getSize());
- body2.writePayload(buffer);
- buffer.put(FRAME_END_BYTE);
-
- }
-
- public static void writeFrames(ByteBuffer buffer, final int channel, AMQBody body1, AMQBody body2, AMQBody body3)
- {
- buffer.put(body1.getFrameType());
- EncodingUtils.writeUnsignedShort(buffer, channel);
- EncodingUtils.writeUnsignedInteger(buffer, body1.getSize());
- body1.writePayload(buffer);
- buffer.put(FRAME_END_BYTE);
- buffer.put(body2.getFrameType());
- EncodingUtils.writeUnsignedShort(buffer, channel);
- EncodingUtils.writeUnsignedInteger(buffer, body2.getSize());
- body2.writePayload(buffer);
- buffer.put(FRAME_END_BYTE);
- buffer.put(body3.getFrameType());
- EncodingUtils.writeUnsignedShort(buffer, channel);
- EncodingUtils.writeUnsignedInteger(buffer, body3.getSize());
- body3.writePayload(buffer);
- buffer.put(FRAME_END_BYTE);
-
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/AMQFrameDecodingException.java b/java/common/src/main/java/org/apache/qpid/framing/AMQFrameDecodingException.java
deleted file mode 100644
index 2373edb478..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/AMQFrameDecodingException.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.framing;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.protocol.AMQConstant;
-
-/**
- * AMQFrameDecodingException indicates that an AMQP frame cannot be decoded because it does not have the correct
- * format as defined by the protocol.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Represents a format error in a protocol frame.
- * </table>
- */
-public class AMQFrameDecodingException extends AMQException
-{
- public AMQFrameDecodingException(AMQConstant errorCode, String message, Throwable cause)
- {
- super(errorCode, message, cause);
- }
-
- public AMQFrameDecodingException(AMQConstant errorCode, String message)
- {
- super(errorCode, message, null);
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBody.java b/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBody.java
deleted file mode 100644
index 4763b22290..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBody.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.framing;
-
-import org.apache.mina.common.ByteBuffer;
-import org.apache.qpid.AMQChannelException;
-import org.apache.qpid.AMQConnectionException;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.protocol.AMQConstant;
-
-public interface AMQMethodBody extends AMQBody
-{
- public static final byte TYPE = 1;
-
- /** AMQP version */
- public byte getMajor();
-
- public byte getMinor();
-
-
-
- /** @return unsigned short */
- public int getClazz();
-
- /** @return unsigned short */
- public int getMethod();
-
- public void writeMethodPayload(ByteBuffer buffer);
-
-
- public int getSize();
-
- public void writePayload(ByteBuffer buffer);
-
- //public abstract void populateMethodBodyFromBuffer(ByteBuffer buffer) throws AMQFrameDecodingException;
-
- //public void populateFromBuffer(ByteBuffer buffer, long size) throws AMQFrameDecodingException;
-
- public AMQFrame generateFrame(int channelId);
-
- public String toString();
-
-
-
- /**
- * Convenience Method to create a channel not found exception
- *
- * @param channelId The channel id that is not found
- *
- * @return new AMQChannelException
- */
- public AMQChannelException getChannelNotFoundException(int channelId);
-
- public AMQChannelException getChannelException(AMQConstant code, String message);
-
- public AMQChannelException getChannelException(AMQConstant code, String message, Throwable cause);
-
- public AMQConnectionException getConnectionException(AMQConstant code, String message);
-
-
- public AMQConnectionException getConnectionException(AMQConstant code, String message, Throwable cause);
-
-
- public boolean execute(MethodDispatcher methodDispatcher, int channelId) throws AMQException;
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyFactory.java b/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyFactory.java
deleted file mode 100644
index 1a7022c11b..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyFactory.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.framing;
-
-import org.apache.mina.common.ByteBuffer;
-
-import org.apache.qpid.protocol.AMQVersionAwareProtocolSession;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class AMQMethodBodyFactory implements BodyFactory
-{
- private static final Logger _log = LoggerFactory.getLogger(AMQMethodBodyFactory.class);
-
- private final AMQVersionAwareProtocolSession _protocolSession;
-
- public AMQMethodBodyFactory(AMQVersionAwareProtocolSession protocolSession)
- {
- _protocolSession = protocolSession;
- }
-
- public AMQBody createBody(ByteBuffer in, long bodySize) throws AMQFrameDecodingException
- {
- return _protocolSession.getMethodRegistry().convertToBody(in, bodySize);
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyImpl.java b/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyImpl.java
deleted file mode 100644
index cd3d721065..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyImpl.java
+++ /dev/null
@@ -1,258 +0,0 @@
-package org.apache.qpid.framing;
-
-/*
- *
- * 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.mina.common.ByteBuffer;
-import org.apache.qpid.AMQChannelException;
-import org.apache.qpid.AMQConnectionException;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.protocol.AMQConstant;
-import org.apache.qpid.protocol.AMQVersionAwareProtocolSession;
-
-public abstract class AMQMethodBodyImpl implements AMQMethodBody
-{
- public static final byte TYPE = 1;
-
- public AMQMethodBodyImpl()
- {
- }
-
- public byte getFrameType()
- {
- return TYPE;
- }
-
-
- /** unsigned short */
- abstract protected int getBodySize();
-
-
- public AMQFrame generateFrame(int channelId)
- {
- return new AMQFrame(channelId, this);
- }
-
- /**
- * Creates an AMQChannelException for the corresponding body type (a channel exception should include the class and
- * method ids of the body it resulted from).
- */
-
- /**
- * Convenience Method to create a channel not found exception
- *
- * @param channelId The channel id that is not found
- *
- * @return new AMQChannelException
- */
- public AMQChannelException getChannelNotFoundException(int channelId)
- {
- return getChannelException(AMQConstant.NOT_FOUND, "Channel not found for id:" + channelId);
- }
-
- public AMQChannelException getChannelException(AMQConstant code, String message)
- {
- return new AMQChannelException(code, message, getClazz(), getMethod(), getMajor(), getMinor(), null);
- }
-
- public AMQChannelException getChannelException(AMQConstant code, String message, Throwable cause)
- {
- return new AMQChannelException(code, message, getClazz(), getMethod(), getMajor(), getMinor(), cause);
- }
-
- public AMQConnectionException getConnectionException(AMQConstant code, String message)
- {
- return new AMQConnectionException(code, message, getClazz(), getMethod(), getMajor(), getMinor(), null);
- }
-
- public AMQConnectionException getConnectionException(AMQConstant code, String message, Throwable cause)
- {
- return new AMQConnectionException(code, message, getClazz(), getMethod(), getMajor(), getMinor(), cause);
- }
-
- public void handle(final int channelId, final AMQVersionAwareProtocolSession session) throws AMQException
- {
- session.methodFrameReceived(channelId, this);
- }
-
- public int getSize()
- {
- return 2 + 2 + getBodySize();
- }
-
- public void writePayload(ByteBuffer buffer)
- {
- EncodingUtils.writeUnsignedShort(buffer, getClazz());
- EncodingUtils.writeUnsignedShort(buffer, getMethod());
- writeMethodPayload(buffer);
- }
-
-
- protected byte readByte(ByteBuffer buffer)
- {
- return buffer.get();
- }
-
- protected AMQShortString readAMQShortString(ByteBuffer buffer)
- {
- return EncodingUtils.readAMQShortString(buffer);
- }
-
- protected int getSizeOf(AMQShortString string)
- {
- return EncodingUtils.encodedShortStringLength(string);
- }
-
- protected void writeByte(ByteBuffer buffer, byte b)
- {
- buffer.put(b);
- }
-
- protected void writeAMQShortString(ByteBuffer buffer, AMQShortString string)
- {
- EncodingUtils.writeShortStringBytes(buffer, string);
- }
-
- protected int readInt(ByteBuffer buffer)
- {
- return buffer.getInt();
- }
-
- protected void writeInt(ByteBuffer buffer, int i)
- {
- buffer.putInt(i);
- }
-
- protected FieldTable readFieldTable(ByteBuffer buffer) throws AMQFrameDecodingException
- {
- return EncodingUtils.readFieldTable(buffer);
- }
-
- protected int getSizeOf(FieldTable table)
- {
- return EncodingUtils.encodedFieldTableLength(table); //To change body of created methods use File | Settings | File Templates.
- }
-
- protected void writeFieldTable(ByteBuffer buffer, FieldTable table)
- {
- EncodingUtils.writeFieldTableBytes(buffer, table);
- }
-
- protected long readLong(ByteBuffer buffer)
- {
- return buffer.getLong();
- }
-
- protected void writeLong(ByteBuffer buffer, long l)
- {
- buffer.putLong(l);
- }
-
- protected int getSizeOf(byte[] response)
- {
- return (response == null) ? 4 : response.length + 4;
- }
-
- protected void writeBytes(ByteBuffer buffer, byte[] data)
- {
- EncodingUtils.writeBytes(buffer,data);
- }
-
- protected byte[] readBytes(ByteBuffer buffer)
- {
- return EncodingUtils.readBytes(buffer);
- }
-
- protected short readShort(ByteBuffer buffer)
- {
- return EncodingUtils.readShort(buffer);
- }
-
- protected void writeShort(ByteBuffer buffer, short s)
- {
- EncodingUtils.writeShort(buffer, s);
- }
-
- protected Content readContent(ByteBuffer buffer)
- {
- return null; //To change body of created methods use File | Settings | File Templates.
- }
-
- protected int getSizeOf(Content body)
- {
- return 0; //To change body of created methods use File | Settings | File Templates.
- }
-
- protected void writeContent(ByteBuffer buffer, Content body)
- {
- //To change body of created methods use File | Settings | File Templates.
- }
-
- protected byte readBitfield(ByteBuffer buffer)
- {
- return readByte(buffer); //To change body of created methods use File | Settings | File Templates.
- }
-
- protected int readUnsignedShort(ByteBuffer buffer)
- {
- return buffer.getUnsignedShort(); //To change body of created methods use File | Settings | File Templates.
- }
-
- protected void writeBitfield(ByteBuffer buffer, byte bitfield0)
- {
- buffer.put(bitfield0);
- }
-
- protected void writeUnsignedShort(ByteBuffer buffer, int s)
- {
- EncodingUtils.writeUnsignedShort(buffer, s);
- }
-
- protected long readUnsignedInteger(ByteBuffer buffer)
- {
- return buffer.getUnsignedInt();
- }
- protected void writeUnsignedInteger(ByteBuffer buffer, long i)
- {
- EncodingUtils.writeUnsignedInteger(buffer, i);
- }
-
-
- protected short readUnsignedByte(ByteBuffer buffer)
- {
- return buffer.getUnsigned();
- }
-
- protected void writeUnsignedByte(ByteBuffer buffer, short unsignedByte)
- {
- EncodingUtils.writeUnsignedByte(buffer, unsignedByte);
- }
-
- protected long readTimestamp(ByteBuffer buffer)
- {
- return EncodingUtils.readTimestamp(buffer);
- }
-
- protected void writeTimestamp(ByteBuffer buffer, long t)
- {
- EncodingUtils.writeTimestamp(buffer, t);
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyInstanceFactory.java b/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyInstanceFactory.java
deleted file mode 100644
index 0c61d9db3c..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyInstanceFactory.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.
- *
- */
-
-package org.apache.qpid.framing;
-
-import org.apache.mina.common.ByteBuffer;
-
-
-public abstract interface AMQMethodBodyInstanceFactory
-{
- public AMQMethodBody newInstance(ByteBuffer buffer, long size) throws AMQFrameDecodingException;
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/AMQMethodFactory.java b/java/common/src/main/java/org/apache/qpid/framing/AMQMethodFactory.java
deleted file mode 100644
index bfcc38ad60..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/AMQMethodFactory.java
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.framing;
-
-import org.apache.mina.common.ByteBuffer;
-
-
-public interface AMQMethodFactory
-{
-
- // Connection Methods
-
- ConnectionCloseBody createConnectionClose();
-
- // Access Methods
-
- AccessRequestBody createAccessRequest(boolean active, boolean exclusive, boolean passive, boolean read, AMQShortString realm, boolean write);
-
-
- // Tx Methods
-
- TxSelectBody createTxSelect();
-
- TxCommitBody createTxCommit();
-
- TxRollbackBody createTxRollback();
-
- // Channel Methods
-
- ChannelOpenBody createChannelOpen();
-
- ChannelCloseBody createChannelClose(int replyCode, AMQShortString replyText);
-
- ChannelFlowBody createChannelFlow(boolean active);
-
-
- // Exchange Methods
-
-
- ExchangeBoundBody createExchangeBound(AMQShortString exchangeName,
- AMQShortString queueName,
- AMQShortString routingKey);
-
- ExchangeDeclareBody createExchangeDeclare(AMQShortString name, AMQShortString type, int ticket);
-
-
- // Queue Methods
-
- QueueDeclareBody createQueueDeclare(AMQShortString name, FieldTable arguments, boolean autoDelete, boolean durable, boolean exclusive, boolean passive, int ticket);
-
- QueueBindBody createQueueBind(AMQShortString queueName, AMQShortString exchangeName, AMQShortString routingKey, FieldTable arguments, int ticket);
-
- QueueDeleteBody createQueueDelete(AMQShortString queueName, boolean ifEmpty, boolean ifUnused, int ticket);
-
-
- // Message Methods
-
- // In different versions of the protocol we change the class used for message transfer
- // abstract this out so the appropriate methods are created
- AMQMethodBody createRecover(boolean requeue);
-
- AMQMethodBody createConsumer(AMQShortString tag, AMQShortString queueName, FieldTable arguments, boolean noAck, boolean exclusive, boolean noLocal, int ticket);
-
- AMQMethodBody createConsumerCancel(AMQShortString consumerTag);
-
- AMQMethodBody createAcknowledge(long deliveryTag, boolean multiple);
-
- AMQMethodBody createRejectBody(long deliveryTag, boolean requeue);
-
- AMQMethodBody createMessageQos(int prefetchCount, int prefetchSize);
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/AMQProtocolClassException.java b/java/common/src/main/java/org/apache/qpid/framing/AMQProtocolClassException.java
deleted file mode 100644
index ab09c1de6d..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/AMQProtocolClassException.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.framing;
-
-/**
- * AMQProtocolInstanceException indicates that the protocol class is incorrect in a header.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Represent incorrect protocol class in frame header.
- * </table>
- *
- * @todo Not an AMQP exception as no status code.
- */
-public class AMQProtocolClassException extends AMQProtocolHeaderException
-{
- public AMQProtocolClassException(String message, Throwable cause)
- {
- super(message, cause);
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/AMQProtocolHeaderException.java b/java/common/src/main/java/org/apache/qpid/framing/AMQProtocolHeaderException.java
deleted file mode 100644
index 6b819364da..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/AMQProtocolHeaderException.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.framing;
-
-import org.apache.qpid.AMQException;
-
-/**
- * AMQProtocolHeaderException indicates a format error in an AMQP frame header.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Represent format error in frame header.
- * </table>
- *
- * @todo Not an AMQP exception as no status code.
- */
-public class AMQProtocolHeaderException extends AMQException
-{
- public AMQProtocolHeaderException(String message, Throwable cause)
- {
- super(null, message, cause);
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/AMQProtocolInstanceException.java b/java/common/src/main/java/org/apache/qpid/framing/AMQProtocolInstanceException.java
deleted file mode 100644
index 3165c373a9..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/AMQProtocolInstanceException.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.framing;
-
-/**
- * AMQProtocolInstanceException indicates that the protocol instance is incorrect in a header.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Represent incorrect protocol instance in frame header.
- * </table>
- *
- * @todo Not an AMQP exception as no status code.
- */
-public class AMQProtocolInstanceException extends AMQProtocolHeaderException
-{
- public AMQProtocolInstanceException(String message, Throwable cause)
- {
- super(message, cause);
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/AMQProtocolVersionException.java b/java/common/src/main/java/org/apache/qpid/framing/AMQProtocolVersionException.java
deleted file mode 100644
index c9b0973ea6..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/AMQProtocolVersionException.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.framing;
-
-/**
- * AMQProtocolInstanceException indicates that the client and server differ on expected protocol version in a header.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Represent incorrect protocol version in frame header.
- * </table>
- *
- * @todo Not an AMQP exception as no status code.
- */
-public class AMQProtocolVersionException extends AMQProtocolHeaderException
-{
- public AMQProtocolVersionException(String message, Throwable cause)
- {
- super(message, cause);
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/AMQShortString.java b/java/common/src/main/java/org/apache/qpid/framing/AMQShortString.java
deleted file mode 100644
index 39a9beb9e8..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/AMQShortString.java
+++ /dev/null
@@ -1,779 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.qpid.framing;
-
-import org.apache.mina.common.ByteBuffer;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.*;
-import java.lang.ref.WeakReference;
-
-/**
- * A short string is a representation of an AMQ Short String
- * Short strings differ from the Java String class by being limited to on ASCII characters (0-127)
- * and thus can be held more effectively in a byte buffer.
- *
- */
-public final class AMQShortString implements CharSequence, Comparable<AMQShortString>
-{
- private static final byte MINUS = (byte)'-';
- private static final byte ZERO = (byte) '0';
-
- private final class TokenizerImpl implements AMQShortStringTokenizer
- {
- private final byte _delim;
- private int _count = -1;
- private int _pos = 0;
-
- public TokenizerImpl(final byte delim)
- {
- _delim = delim;
- }
-
- public int countTokens()
- {
- if(_count == -1)
- {
- _count = 1 + AMQShortString.this.occurences(_delim);
- }
- return _count;
- }
-
- public AMQShortString nextToken()
- {
- if(_pos <= AMQShortString.this.length())
- {
- int nextDelim = AMQShortString.this.indexOf(_delim, _pos);
- if(nextDelim == -1)
- {
- nextDelim = AMQShortString.this.length();
- }
-
- AMQShortString nextToken = AMQShortString.this.substring(_pos, nextDelim++);
- _pos = nextDelim;
- return nextToken;
- }
- else
- {
- return null;
- }
- }
-
- public boolean hasMoreTokens()
- {
- return _pos <= AMQShortString.this.length();
- }
- }
-
- private AMQShortString substring(final int from, final int to)
- {
- return new AMQShortString(_data, from+_offset, to+_offset);
- }
-
-
- private static final ThreadLocal<Map<AMQShortString, WeakReference<AMQShortString>>> _localInternMap =
- new ThreadLocal<Map<AMQShortString, WeakReference<AMQShortString>>>()
- {
- protected Map<AMQShortString, WeakReference<AMQShortString>> initialValue()
- {
- return new WeakHashMap<AMQShortString, WeakReference<AMQShortString>>();
- };
- };
-
- private static final Map<AMQShortString, WeakReference<AMQShortString>> _globalInternMap =
- new WeakHashMap<AMQShortString, WeakReference<AMQShortString>>();
-
- private static final Logger _logger = LoggerFactory.getLogger(AMQShortString.class);
-
- private final byte[] _data;
- private final int _offset;
- private int _hashCode;
- private String _asString = null;
-
- private final int _length;
- private static final char[] EMPTY_CHAR_ARRAY = new char[0];
-
- public static final AMQShortString EMPTY_STRING = new AMQShortString((String)null);
-
- public AMQShortString(byte[] data)
- {
-
- _data = data.clone();
- _length = data.length;
- _offset = 0;
- }
-
- public AMQShortString(byte[] data, int pos)
- {
- final int size = data[pos++];
- final byte[] dataCopy = new byte[size];
- System.arraycopy(data,pos,dataCopy,0,size);
- _length = size;
- _data = dataCopy;
- _offset = 0;
- }
-
- public AMQShortString(String data)
- {
- this((data == null) ? EMPTY_CHAR_ARRAY : data.toCharArray());
- _asString = data;
- }
-
- public AMQShortString(char[] data)
- {
- if (data == null)
- {
- throw new NullPointerException("Cannot create AMQShortString with null char[]");
- }
-
- final int length = data.length;
- final byte[] stringBytes = new byte[length];
- int hash = 0;
- for (int i = 0; i < length; i++)
- {
- stringBytes[i] = (byte) (0xFF & data[i]);
- hash = (31 * hash) + stringBytes[i];
- }
- _hashCode = hash;
- _data = stringBytes;
-
- _length = length;
- _offset = 0;
-
- }
-
- public AMQShortString(CharSequence charSequence)
- {
- final int length = charSequence.length();
- final byte[] stringBytes = new byte[length];
- int hash = 0;
- for (int i = 0; i < length; i++)
- {
- stringBytes[i] = ((byte) (0xFF & charSequence.charAt(i)));
- hash = (31 * hash) + stringBytes[i];
-
- }
-
- _data = stringBytes;
- _hashCode = hash;
- _length = length;
- _offset = 0;
-
- }
-
- private AMQShortString(ByteBuffer data, final int length)
- {
- if(data.isDirect() || data.isReadOnly())
- {
- byte[] dataBytes = new byte[length];
- data.get(dataBytes);
- _data = dataBytes;
- _offset = 0;
- }
- else
- {
-
- _data = data.array();
- _offset = data.arrayOffset() + data.position();
- data.skip(length);
-
- }
- _length = length;
-
- }
-
- private AMQShortString(final byte[] data, final int from, final int to)
- {
- _offset = from;
- _length = to - from;
- _data = data;
- }
-
- public AMQShortString shrink()
- {
- if(_data.length != _length)
- {
- byte[] dataBytes = new byte[_length];
- System.arraycopy(_data,_offset,dataBytes,0,_length);
- return new AMQShortString(dataBytes,0,_length);
- }
- else
- {
- return this;
- }
- }
-
- /**
- * Get the length of the short string
- * @return length of the underlying byte array
- */
- public int length()
- {
- return _length;
- }
-
- public char charAt(int index)
- {
-
- return (char) _data[_offset + index];
-
- }
-
- public CharSequence subSequence(int start, int end)
- {
- return new CharSubSequence(start, end);
- }
-
- public int writeToByteArray(byte[] encoding, int pos)
- {
- final int size = length();
- encoding[pos++] = (byte) size;
- System.arraycopy(_data,_offset,encoding,pos,size);
- return pos+size;
- }
-
- public static AMQShortString readFromByteArray(byte[] byteEncodedDestination, int pos)
- {
-
-
- final AMQShortString shortString = new AMQShortString(byteEncodedDestination, pos);
- if(shortString.length() == 0)
- {
- return null;
- }
- else
- {
- return shortString;
- }
- }
-
- public static AMQShortString readFromBuffer(ByteBuffer buffer)
- {
- final short length = buffer.getUnsigned();
- if (length == 0)
- {
- return null;
- }
- else
- {
-
- return new AMQShortString(buffer, length);
- }
- }
-
- public byte[] getBytes()
- {
- if(_offset == 0 && _length == _data.length)
- {
- return _data.clone();
- }
- else
- {
- byte[] data = new byte[_length];
- System.arraycopy(_data,_offset,data,0,_length);
- return data;
- }
- }
-
- public void writeToBuffer(ByteBuffer buffer)
- {
-
- final int size = length();
- //buffer.setAutoExpand(true);
- buffer.put((byte) size);
- buffer.put(_data, _offset, size);
-
- }
-
- public boolean endsWith(String s)
- {
- return endsWith(new AMQShortString(s));
- }
-
-
- public boolean endsWith(AMQShortString otherString)
- {
-
- if (otherString.length() > length())
- {
- return false;
- }
-
-
- int thisLength = length();
- int otherLength = otherString.length();
-
- for (int i = 1; i <= otherLength; i++)
- {
- if (charAt(thisLength - i) != otherString.charAt(otherLength - i))
- {
- return false;
- }
- }
- return true;
- }
-
- public boolean startsWith(String s)
- {
- return startsWith(new AMQShortString(s));
- }
-
- public boolean startsWith(AMQShortString otherString)
- {
-
- if (otherString.length() > length())
- {
- return false;
- }
-
- for (int i = 0; i < otherString.length(); i++)
- {
- if (charAt(i) != otherString.charAt(i))
- {
- return false;
- }
- }
-
- return true;
-
- }
-
- public boolean startsWith(CharSequence otherString)
- {
- if (otherString.length() > length())
- {
- return false;
- }
-
- for (int i = 0; i < otherString.length(); i++)
- {
- if (charAt(i) != otherString.charAt(i))
- {
- return false;
- }
- }
-
- return true;
- }
-
-
- private final class CharSubSequence implements CharSequence
- {
- private final int _sequenceOffset;
- private final int _end;
-
- public CharSubSequence(final int offset, final int end)
- {
- _sequenceOffset = offset;
- _end = end;
- }
-
- public int length()
- {
- return _end - _sequenceOffset;
- }
-
- public char charAt(int index)
- {
- return AMQShortString.this.charAt(index + _sequenceOffset);
- }
-
- public CharSequence subSequence(int start, int end)
- {
- return new CharSubSequence(start + _sequenceOffset, end + _sequenceOffset);
- }
- }
-
- public char[] asChars()
- {
- final int size = length();
- final char[] chars = new char[size];
-
- for (int i = 0; i < size; i++)
- {
- chars[i] = (char) _data[i + _offset];
- }
-
- return chars;
- }
-
-
- public String asString()
- {
- if (_asString == null)
- {
- _asString = new String(asChars());
- }
- return _asString;
- }
-
- public boolean equals(Object o)
- {
-
-
- if(o instanceof AMQShortString)
- {
- return equals((AMQShortString)o);
- }
- if(o instanceof CharSequence)
- {
- return equals((CharSequence)o);
- }
-
- if (o == null)
- {
- return false;
- }
-
- if (o == this)
- {
- return true;
- }
-
-
- return false;
-
- }
-
- public boolean equals(final AMQShortString otherString)
- {
- if (otherString == this)
- {
- return true;
- }
-
- if (otherString == null)
- {
- return false;
- }
-
- final int hashCode = _hashCode;
-
- final int otherHashCode = otherString._hashCode;
-
- if ((hashCode != 0) && (otherHashCode != 0) && (hashCode != otherHashCode))
- {
- return false;
- }
-
- final int length = _length;
-
- if(length != otherString._length)
- {
- return false;
- }
-
-
- final byte[] data = _data;
-
- final byte[] otherData = otherString._data;
-
- final int offset = _offset;
-
- final int otherOffset = otherString._offset;
-
- if(offset == 0 && otherOffset == 0 && length == data.length && length == otherData.length)
- {
- return Arrays.equals(data, otherData);
- }
- else
- {
- int thisIdx = offset;
- int otherIdx = otherOffset;
- for(int i = length; i-- != 0; )
- {
- if(!(data[thisIdx++] == otherData[otherIdx++]))
- {
- return false;
- }
- }
- }
-
- return true;
-
- }
-
- public boolean equals(CharSequence s)
- {
- if(s instanceof AMQShortString)
- {
- return equals((AMQShortString)s);
- }
-
- if (s == null)
- {
- return false;
- }
-
- if (s.length() != length())
- {
- return false;
- }
-
- for (int i = 0; i < length(); i++)
- {
- if (charAt(i) != s.charAt(i))
- {
- return false;
- }
- }
-
- return true;
- }
-
- public int hashCode()
- {
- int hash = _hashCode;
- if (hash == 0)
- {
- final int size = length();
-
- for (int i = 0; i < size; i++)
- {
- hash = (31 * hash) + _data[i+_offset];
- }
-
- _hashCode = hash;
- }
-
- return hash;
- }
-
- public void setDirty()
- {
- _hashCode = 0;
- }
-
- public String toString()
- {
- return asString();
- }
-
- public int compareTo(AMQShortString name)
- {
- if (name == null)
- {
- return 1;
- }
- else
- {
-
- if (name.length() < length())
- {
- return -name.compareTo(this);
- }
-
- for (int i = 0; i < length(); i++)
- {
- final byte d = _data[i+_offset];
- final byte n = name._data[i+name._offset];
- if (d < n)
- {
- return -1;
- }
-
- if (d > n)
- {
- return 1;
- }
- }
-
- return (length() == name.length()) ? 0 : -1;
- }
- }
-
-
- public AMQShortStringTokenizer tokenize(byte delim)
- {
- return new TokenizerImpl(delim);
- }
-
-
- public AMQShortString intern()
- {
-
- hashCode();
-
- Map<AMQShortString, WeakReference<AMQShortString>> localMap =
- _localInternMap.get();
-
- WeakReference<AMQShortString> ref = localMap.get(this);
- AMQShortString internString;
-
- if(ref != null)
- {
- internString = ref.get();
- if(internString != null)
- {
- return internString;
- }
- }
-
-
- synchronized(_globalInternMap)
- {
-
- ref = _globalInternMap.get(this);
- if((ref == null) || ((internString = ref.get()) == null))
- {
- internString = shrink();
- ref = new WeakReference(internString);
- _globalInternMap.put(internString, ref);
- }
-
- }
- localMap.put(internString, ref);
- return internString;
-
- }
-
- private int occurences(final byte delim)
- {
- int count = 0;
- final int end = _offset + _length;
- for(int i = _offset ; i < end ; i++ )
- {
- if(_data[i] == delim)
- {
- count++;
- }
- }
- return count;
- }
-
- private int indexOf(final byte val, final int pos)
- {
-
- for(int i = pos; i < length(); i++)
- {
- if(_data[_offset+i] == val)
- {
- return i;
- }
- }
- return -1;
- }
-
-
- public static AMQShortString join(final Collection<AMQShortString> terms,
- final AMQShortString delim)
- {
- if(terms.size() == 0)
- {
- return EMPTY_STRING;
- }
-
- int size = delim.length() * (terms.size() - 1);
- for(AMQShortString term : terms)
- {
- size += term.length();
- }
-
- byte[] data = new byte[size];
- int pos = 0;
- final byte[] delimData = delim._data;
- final int delimOffset = delim._offset;
- final int delimLength = delim._length;
-
-
- for(AMQShortString term : terms)
- {
-
- if(pos!=0)
- {
- System.arraycopy(delimData, delimOffset,data,pos, delimLength);
- pos+=delimLength;
- }
- System.arraycopy(term._data,term._offset,data,pos,term._length);
- pos+=term._length;
- }
-
-
-
- return new AMQShortString(data,0,size);
- }
-
- public int toIntValue()
- {
- int pos = _offset;
- int val = 0;
-
-
- boolean isNegative = (_data[pos] == MINUS);
- if(isNegative)
- {
- pos++;
- }
-
- final int end = _length + _offset;
-
- while(pos < end)
- {
- int digit = (int) (_data[pos++] - ZERO);
- if((digit < 0) || (digit > 9))
- {
- throw new NumberFormatException("\""+toString()+"\" is not a valid number");
- }
- val = val * 10;
- val += digit;
- }
- if(isNegative)
- {
- val = val * -1;
- }
- return val;
- }
-
- public boolean contains(final byte b)
- {
- final int end = _length + _offset;
- for(int i = _offset; i < end; i++)
- {
- if(_data[i] == b)
- {
- return true;
- }
- }
- return false; //To change body of created methods use File | Settings | File Templates.
- }
-
- public static AMQShortString valueOf(Object obj)
- {
- return obj == null ? null : new AMQShortString(String.valueOf(obj));
- }
-
-
- public static void main(String args[])
- {
- AMQShortString s = new AMQShortString("a.b.c.d.e.f.g.h.i.j.k");
- AMQShortString s2 = s.substring(2, 7);
-
- AMQShortStringTokenizer t = s2.tokenize((byte) '.');
- while(t.hasMoreTokens())
- {
- System.err.println(t.nextToken());
- }
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/AMQShortStringTokenizer.java b/java/common/src/main/java/org/apache/qpid/framing/AMQShortStringTokenizer.java
deleted file mode 100644
index e2db8906a1..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/AMQShortStringTokenizer.java
+++ /dev/null
@@ -1,31 +0,0 @@
-package org.apache.qpid.framing;
-
-/*
-*
-* 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 interface AMQShortStringTokenizer
-{
-
- public int countTokens();
-
- public AMQShortString nextToken();
-
- boolean hasMoreTokens();
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/AMQType.java b/java/common/src/main/java/org/apache/qpid/framing/AMQType.java
deleted file mode 100644
index 14fb63da03..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/AMQType.java
+++ /dev/null
@@ -1,795 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.framing;
-
-import org.apache.mina.common.ByteBuffer;
-
-import java.math.BigDecimal;
-
-/**
- * AMQType is a type that represents the different possible AMQP field table types. It provides operations for each
- * of the types to perform tasks such as calculating the size of an instance of the type, converting types between AMQP
- * and Java native types, and reading and writing instances of AMQP types in binary formats to and from byte buffers.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Get the equivalent one byte identifier for a type.
- * <tr><td> Calculate the size of an instance of an AMQP parameter type. <td> {@link EncodingUtils}
- * <tr><td> Convert an instance of an AMQP parameter into a compatable Java object tagged with its AMQP type.
- * <td> {@link AMQTypedValue}
- * <tr><td> Write an instance of an AMQP parameter type to a byte buffer. <td> {@link EncodingUtils}
- * <tr><td> Read an instance of an AMQP parameter from a byte buffer. <td> {@link EncodingUtils}
- * </table>
- */
-public enum AMQType
-{
- LONG_STRING('S')
- {
- public int getEncodingSize(Object value)
- {
- return EncodingUtils.encodedLongStringLength((String) value);
- }
-
- public String toNativeValue(Object value)
- {
- if (value != null)
- {
- return value.toString();
- }
- else
- {
- throw new NullPointerException("Cannot convert: null to String.");
- }
- }
-
- public void writeValueImpl(Object value, ByteBuffer buffer)
- {
- EncodingUtils.writeLongStringBytes(buffer, (String) value);
- }
-
- public Object readValueFromBuffer(ByteBuffer buffer)
- {
- return EncodingUtils.readLongString(buffer);
- }
- },
-
- INTEGER('i')
- {
- public int getEncodingSize(Object value)
- {
- return EncodingUtils.unsignedIntegerLength();
- }
-
- public Long toNativeValue(Object value)
- {
- if (value instanceof Long)
- {
- return (Long) value;
- }
- else if (value instanceof Integer)
- {
- return ((Integer) value).longValue();
- }
- else if (value instanceof Short)
- {
- return ((Short) value).longValue();
- }
- else if (value instanceof Byte)
- {
- return ((Byte) value).longValue();
- }
- else if ((value instanceof String) || (value == null))
- {
- return Long.valueOf((String) value);
- }
- else
- {
- throw new NumberFormatException("Cannot convert: " + value + "(" + value.getClass().getName() + ") to int.");
- }
- }
-
- public void writeValueImpl(Object value, ByteBuffer buffer)
- {
- EncodingUtils.writeUnsignedInteger(buffer, (Long) value);
- }
-
- public Object readValueFromBuffer(ByteBuffer buffer)
- {
- return EncodingUtils.readUnsignedInteger(buffer);
- }
- },
-
- DECIMAL('D')
- {
- public int getEncodingSize(Object value)
- {
- return EncodingUtils.encodedByteLength() + EncodingUtils.encodedIntegerLength();
- }
-
- public Object toNativeValue(Object value)
- {
- if (value instanceof BigDecimal)
- {
- return (BigDecimal) value;
- }
- else
- {
- throw new NumberFormatException("Cannot convert: " + value + "(" + value.getClass().getName()
- + ") to BigDecimal.");
- }
- }
-
- public void writeValueImpl(Object value, ByteBuffer buffer)
- {
- BigDecimal bd = (BigDecimal) value;
-
- byte places = new Integer(bd.scale()).byteValue();
-
- int unscaled = bd.intValue();
-
- EncodingUtils.writeByte(buffer, places);
-
- EncodingUtils.writeInteger(buffer, unscaled);
- }
-
- public Object readValueFromBuffer(ByteBuffer buffer)
- {
- byte places = EncodingUtils.readByte(buffer);
-
- int unscaled = EncodingUtils.readInteger(buffer);
-
- BigDecimal bd = new BigDecimal(unscaled);
-
- return bd.setScale(places);
- }
- },
-
- TIMESTAMP('T')
- {
- public int getEncodingSize(Object value)
- {
- return EncodingUtils.encodedLongLength();
- }
-
- public Object toNativeValue(Object value)
- {
- if (value instanceof Long)
- {
- return (Long) value;
- }
- else
- {
- throw new NumberFormatException("Cannot convert: " + value + "(" + value.getClass().getName()
- + ") to timestamp.");
- }
- }
-
- public void writeValueImpl(Object value, ByteBuffer buffer)
- {
- EncodingUtils.writeLong(buffer, (Long) value);
- }
-
- public Object readValueFromBuffer(ByteBuffer buffer)
- {
- return EncodingUtils.readLong(buffer);
- }
- },
-
- /**
- * Implements the field table type. The native value of a field table type will be an instance of
- * {@link FieldTable}, which itself may contain name/value pairs encoded as {@link AMQTypedValue}s.
- */
- FIELD_TABLE('F')
- {
- /**
- * Calculates the size of an instance of the type in bytes.
- *
- * @param value An instance of the type.
- *
- * @return The size of the instance of the type in bytes.
- */
- public int getEncodingSize(Object value)
- {
- // Ensure that the value is a FieldTable.
- if (!(value instanceof FieldTable))
- {
- throw new IllegalArgumentException("Value is not a FieldTable.");
- }
-
- FieldTable ftValue = (FieldTable) value;
-
- // Loop over all name/value pairs adding up size of each. FieldTable itself keeps track of its encoded
- // size as entries are added, so no need to loop over all explicitly.
- // EncodingUtils calculation of the encoded field table lenth, will include 4 bytes for its 'size' field.
- return EncodingUtils.encodedFieldTableLength(ftValue);
- }
-
- /**
- * Converts an instance of the type to an equivalent Java native representation.
- *
- * @param value An instance of the type.
- *
- * @return An equivalent Java native representation.
- */
- public Object toNativeValue(Object value)
- {
- // Ensure that the value is a FieldTable.
- if (!(value instanceof FieldTable))
- {
- throw new IllegalArgumentException("Value is not a FieldTable.");
- }
-
- return (FieldTable) value;
- }
-
- /**
- * Writes an instance of the type to a specified byte buffer.
- *
- * @param value An instance of the type.
- * @param buffer The byte buffer to write it to.
- */
- public void writeValueImpl(Object value, ByteBuffer buffer)
- {
- // Ensure that the value is a FieldTable.
- if (!(value instanceof FieldTable))
- {
- throw new IllegalArgumentException("Value is not a FieldTable.");
- }
-
- FieldTable ftValue = (FieldTable) value;
-
- // Loop over all name/values writing out into buffer.
- ftValue.writeToBuffer(buffer);
- }
-
- /**
- * Reads an instance of the type from a specified byte buffer.
- *
- * @param buffer The byte buffer to write it to.
- *
- * @return An instance of the type.
- */
- public Object readValueFromBuffer(ByteBuffer buffer)
- {
- try
- {
- // Read size of field table then all name/value pairs.
- return EncodingUtils.readFieldTable(buffer);
- }
- catch (AMQFrameDecodingException e)
- {
- throw new IllegalArgumentException("Unable to read field table from buffer.", e);
- }
- }
- },
-
- VOID('V')
- {
- public int getEncodingSize(Object value)
- {
- return 0;
- }
-
- public Object toNativeValue(Object value)
- {
- if (value == null)
- {
- return null;
- }
- else
- {
- throw new NumberFormatException("Cannot convert: " + value + "(" + value.getClass().getName()
- + ") to null String.");
- }
- }
-
- public void writeValueImpl(Object value, ByteBuffer buffer)
- { }
-
- public Object readValueFromBuffer(ByteBuffer buffer)
- {
- return null;
- }
- },
-
- BINARY('x')
- {
- public int getEncodingSize(Object value)
- {
- return EncodingUtils.encodedLongstrLength((byte[]) value);
- }
-
- public Object toNativeValue(Object value)
- {
- if ((value instanceof byte[]) || (value == null))
- {
- return value;
- }
- else
- {
- throw new IllegalArgumentException("Value: " + value + " (" + value.getClass().getName()
- + ") cannot be converted to byte[]");
- }
- }
-
- public void writeValueImpl(Object value, ByteBuffer buffer)
- {
- EncodingUtils.writeLongstr(buffer, (byte[]) value);
- }
-
- public Object readValueFromBuffer(ByteBuffer buffer)
- {
- return EncodingUtils.readLongstr(buffer);
- }
- },
-
- ASCII_STRING('c')
- {
- public int getEncodingSize(Object value)
- {
- return EncodingUtils.encodedLongStringLength((String) value);
- }
-
- public String toNativeValue(Object value)
- {
- if (value != null)
- {
- return value.toString();
- }
- else
- {
- throw new NullPointerException("Cannot convert: null to String.");
- }
- }
-
- public void writeValueImpl(Object value, ByteBuffer buffer)
- {
- EncodingUtils.writeLongStringBytes(buffer, (String) value);
- }
-
- public Object readValueFromBuffer(ByteBuffer buffer)
- {
- return EncodingUtils.readLongString(buffer);
- }
- },
-
- WIDE_STRING('C')
- {
- public int getEncodingSize(Object value)
- {
- // FIXME: use proper charset encoder
- return EncodingUtils.encodedLongStringLength((String) value);
- }
-
- public String toNativeValue(Object value)
- {
- if (value != null)
- {
- return value.toString();
- }
- else
- {
- throw new NullPointerException("Cannot convert: null to String.");
- }
- }
-
- public void writeValueImpl(Object value, ByteBuffer buffer)
- {
- EncodingUtils.writeLongStringBytes(buffer, (String) value);
- }
-
- public Object readValueFromBuffer(ByteBuffer buffer)
- {
- return EncodingUtils.readLongString(buffer);
- }
- },
-
- BOOLEAN('t')
- {
- public int getEncodingSize(Object value)
- {
- return EncodingUtils.encodedBooleanLength();
- }
-
- public Object toNativeValue(Object value)
- {
- if (value instanceof Boolean)
- {
- return (Boolean) value;
- }
- else if ((value instanceof String) || (value == null))
- {
- return Boolean.valueOf((String) value);
- }
- else
- {
- throw new NumberFormatException("Cannot convert: " + value + "(" + value.getClass().getName()
- + ") to boolean.");
- }
- }
-
- public void writeValueImpl(Object value, ByteBuffer buffer)
- {
- EncodingUtils.writeBoolean(buffer, (Boolean) value);
- }
-
- public Object readValueFromBuffer(ByteBuffer buffer)
- {
- return EncodingUtils.readBoolean(buffer);
- }
- },
-
- ASCII_CHARACTER('k')
- {
- public int getEncodingSize(Object value)
- {
- return EncodingUtils.encodedCharLength();
- }
-
- public Character toNativeValue(Object value)
- {
- if (value instanceof Character)
- {
- return (Character) value;
- }
- else if (value == null)
- {
- throw new NullPointerException("Cannot convert null into char");
- }
- else
- {
- throw new NumberFormatException("Cannot convert: " + value + "(" + value.getClass().getName()
- + ") to char.");
- }
- }
-
- public void writeValueImpl(Object value, ByteBuffer buffer)
- {
- EncodingUtils.writeChar(buffer, (Character) value);
- }
-
- public Object readValueFromBuffer(ByteBuffer buffer)
- {
- return EncodingUtils.readChar(buffer);
- }
- },
-
- BYTE('b')
- {
- public int getEncodingSize(Object value)
- {
- return EncodingUtils.encodedByteLength();
- }
-
- public Byte toNativeValue(Object value)
- {
- if (value instanceof Byte)
- {
- return (Byte) value;
- }
- else if ((value instanceof String) || (value == null))
- {
- return Byte.valueOf((String) value);
- }
- else
- {
- throw new NumberFormatException("Cannot convert: " + value + "(" + value.getClass().getName()
- + ") to byte.");
- }
- }
-
- public void writeValueImpl(Object value, ByteBuffer buffer)
- {
- EncodingUtils.writeByte(buffer, (Byte) value);
- }
-
- public Object readValueFromBuffer(ByteBuffer buffer)
- {
- return EncodingUtils.readByte(buffer);
- }
- },
-
- SHORT('s')
- {
- public int getEncodingSize(Object value)
- {
- return EncodingUtils.encodedShortLength();
- }
-
- public Short toNativeValue(Object value)
- {
- if (value instanceof Short)
- {
- return (Short) value;
- }
- else if (value instanceof Byte)
- {
- return ((Byte) value).shortValue();
- }
- else if ((value instanceof String) || (value == null))
- {
- return Short.valueOf((String) value);
- }
- else
- {
- throw new NumberFormatException("Cannot convert: " + value + "(" + value.getClass().getName()
- + ") to short.");
- }
- }
-
- public void writeValueImpl(Object value, ByteBuffer buffer)
- {
- EncodingUtils.writeShort(buffer, (Short) value);
- }
-
- public Object readValueFromBuffer(ByteBuffer buffer)
- {
- return EncodingUtils.readShort(buffer);
- }
- },
-
- INT('I')
- {
- public int getEncodingSize(Object value)
- {
- return EncodingUtils.encodedIntegerLength();
- }
-
- public Integer toNativeValue(Object value)
- {
- if (value instanceof Integer)
- {
- return (Integer) value;
- }
- else if (value instanceof Short)
- {
- return ((Short) value).intValue();
- }
- else if (value instanceof Byte)
- {
- return ((Byte) value).intValue();
- }
- else if ((value instanceof String) || (value == null))
- {
- return Integer.valueOf((String) value);
- }
- else
- {
- throw new NumberFormatException("Cannot convert: " + value + "(" + value.getClass().getName() + ") to int.");
- }
- }
-
- public void writeValueImpl(Object value, ByteBuffer buffer)
- {
- EncodingUtils.writeInteger(buffer, (Integer) value);
- }
-
- public Object readValueFromBuffer(ByteBuffer buffer)
- {
- return EncodingUtils.readInteger(buffer);
- }
- },
-
- LONG('l')
- {
- public int getEncodingSize(Object value)
- {
- return EncodingUtils.encodedLongLength();
- }
-
- public Object toNativeValue(Object value)
- {
- if (value instanceof Long)
- {
- return (Long) value;
- }
- else if (value instanceof Integer)
- {
- return ((Integer) value).longValue();
- }
- else if (value instanceof Short)
- {
- return ((Short) value).longValue();
- }
- else if (value instanceof Byte)
- {
- return ((Byte) value).longValue();
- }
- else if ((value instanceof String) || (value == null))
- {
- return Long.valueOf((String) value);
- }
- else
- {
- throw new NumberFormatException("Cannot convert: " + value + "(" + value.getClass().getName()
- + ") to long.");
- }
- }
-
- public void writeValueImpl(Object value, ByteBuffer buffer)
- {
- EncodingUtils.writeLong(buffer, (Long) value);
- }
-
- public Object readValueFromBuffer(ByteBuffer buffer)
- {
- return EncodingUtils.readLong(buffer);
- }
- },
-
- FLOAT('f')
- {
- public int getEncodingSize(Object value)
- {
- return EncodingUtils.encodedFloatLength();
- }
-
- public Float toNativeValue(Object value)
- {
- if (value instanceof Float)
- {
- return (Float) value;
- }
- else if ((value instanceof String) || (value == null))
- {
- return Float.valueOf((String) value);
- }
- else
- {
- throw new NumberFormatException("Cannot convert: " + value + "(" + value.getClass().getName()
- + ") to float.");
- }
- }
-
- public void writeValueImpl(Object value, ByteBuffer buffer)
- {
- EncodingUtils.writeFloat(buffer, (Float) value);
- }
-
- public Object readValueFromBuffer(ByteBuffer buffer)
- {
- return EncodingUtils.readFloat(buffer);
- }
- },
-
- DOUBLE('d')
- {
- public int getEncodingSize(Object value)
- {
- return EncodingUtils.encodedDoubleLength();
- }
-
- public Double toNativeValue(Object value)
- {
- if (value instanceof Double)
- {
- return (Double) value;
- }
- else if (value instanceof Float)
- {
- return ((Float) value).doubleValue();
- }
- else if ((value instanceof String) || (value == null))
- {
- return Double.valueOf((String) value);
- }
- else
- {
- throw new NumberFormatException("Cannot convert: " + value + "(" + value.getClass().getName()
- + ") to double.");
- }
- }
-
- public void writeValueImpl(Object value, ByteBuffer buffer)
- {
- EncodingUtils.writeDouble(buffer, (Double) value);
- }
-
- public Object readValueFromBuffer(ByteBuffer buffer)
- {
- return EncodingUtils.readDouble(buffer);
- }
- };
-
- /** Holds the defined one byte identifier for the type. */
- private final byte _identifier;
-
- /**
- * Creates an instance of an AMQP type from its defined one byte identifier.
- *
- * @param identifier The one byte identifier for the type.
- */
- AMQType(char identifier)
- {
- _identifier = (byte) identifier;
- }
-
- /**
- * Extracts the byte identifier for the typ.
- *
- * @return The byte identifier for the typ.
- */
- public final byte identifier()
- {
- return _identifier;
- }
-
- /**
- * Calculates the size of an instance of the type in bytes.
- *
- * @param value An instance of the type.
- *
- * @return The size of the instance of the type in bytes.
- */
- public abstract int getEncodingSize(Object value);
-
- /**
- * Converts an instance of the type to an equivalent Java native representation.
- *
- * @param value An instance of the type.
- *
- * @return An equivalent Java native representation.
- */
- public abstract Object toNativeValue(Object value);
-
- /**
- * Converts an instance of the type to an equivalent Java native representation, packaged as an
- * {@link AMQTypedValue} tagged with its AMQP type.
- *
- * @param value An instance of the type.
- *
- * @return An equivalent Java native representation, tagged with its AMQP type.
- */
- public AMQTypedValue asTypedValue(Object value)
- {
- return new AMQTypedValue(this, toNativeValue(value));
- }
-
- /**
- * Writes an instance of the type to a specified byte buffer, preceded by its one byte identifier. As the type and
- * value are both written, this provides a fully encoded description of a parameters type and value.
- *
- * @param value An instance of the type.
- * @param buffer The byte buffer to write it to.
- */
- public void writeToBuffer(Object value, ByteBuffer buffer)
- {
- buffer.put(identifier());
- writeValueImpl(value, buffer);
- }
-
- /**
- * Writes an instance of the type to a specified byte buffer.
- *
- * @param value An instance of the type.
- * @param buffer The byte buffer to write it to.
- */
- abstract void writeValueImpl(Object value, ByteBuffer buffer);
-
- /**
- * Reads an instance of the type from a specified byte buffer.
- *
- * @param buffer The byte buffer to write it to.
- *
- * @return An instance of the type.
- */
- abstract Object readValueFromBuffer(ByteBuffer buffer);
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/AMQTypeMap.java b/java/common/src/main/java/org/apache/qpid/framing/AMQTypeMap.java
deleted file mode 100644
index a07fd78c8c..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/AMQTypeMap.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.framing;
-
-import java.util.HashMap;
-import java.util.Map;
-
-public class AMQTypeMap
-{
- public static final Map<Byte, AMQType> _reverseTypeMap = new HashMap<Byte, AMQType>();
-
- static
- {
- for(AMQType type : AMQType.values())
- {
- _reverseTypeMap.put(type.identifier(), type);
- }
- }
-
- public static AMQType getType(Byte identifier)
- {
- AMQType result = _reverseTypeMap.get(identifier);
- if (result == null) {
- throw new IllegalArgumentException
- ("no such type code: " + Integer.toHexString(identifier.intValue()));
- }
- return result;
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/AMQTypedValue.java b/java/common/src/main/java/org/apache/qpid/framing/AMQTypedValue.java
deleted file mode 100644
index 647d531476..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/AMQTypedValue.java
+++ /dev/null
@@ -1,179 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.framing;
-
-import org.apache.mina.common.ByteBuffer;
-
-import java.util.Date;
-import java.util.Map;
-import java.math.BigDecimal;
-
-/**
- * AMQTypedValue combines together a native Java Object value, and an {@link AMQType}, as a fully typed AMQP parameter
- * value. It provides the ability to read and write fully typed parameters to and from byte buffers. It also provides
- * the ability to create such parameters from Java native value and a type tag or to extract the native value and type
- * from one.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Create a fully typed AMQP value from a native type and a type tag. <td> {@link AMQType}
- * <tr><td> Create a fully typed AMQP value from a binary representation in a byte buffer. <td> {@link AMQType}
- * <tr><td> Write a fully typed AMQP value to a binary representation in a byte buffer. <td> {@link AMQType}
- * <tr><td> Extract the type from a fully typed AMQP value.
- * <tr><td> Extract the value from a fully typed AMQP value.
- * </table>
- */
-public class AMQTypedValue
-{
- /** The type of the value. */
- private final AMQType _type;
-
- /** The Java native representation of the AMQP typed value. */
- private final Object _value;
-
- public AMQTypedValue(AMQType type, Object value)
- {
- if (type == null)
- {
- throw new NullPointerException("Cannot create a typed value with null type");
- }
-
- _type = type;
- _value = type.toNativeValue(value);
- }
-
- private AMQTypedValue(AMQType type, ByteBuffer buffer)
- {
- _type = type;
- _value = type.readValueFromBuffer(buffer);
- }
-
- public AMQType getType()
- {
- return _type;
- }
-
- public Object getValue()
- {
- return _value;
- }
-
- public void writeToBuffer(ByteBuffer buffer)
- {
- _type.writeToBuffer(_value, buffer);
- }
-
- public int getEncodingSize()
- {
- return _type.getEncodingSize(_value);
- }
-
- public static AMQTypedValue readFromBuffer(ByteBuffer buffer)
- {
- AMQType type = AMQTypeMap.getType(buffer.get());
-
- return new AMQTypedValue(type, buffer);
- }
-
- public String toString()
- {
- return "[" + getType() + ": " + getValue() + "]";
- }
-
-
- public boolean equals(Object o)
- {
- if(o instanceof AMQTypedValue)
- {
- AMQTypedValue other = (AMQTypedValue) o;
- return _type == other._type && (_value == null ? other._value == null : _value.equals(other._value));
- }
- else
- {
- return false;
- }
- }
-
- public int hashCode()
- {
- return _type.hashCode() ^ (_value == null ? 0 : _value.hashCode());
- }
-
-
- public static AMQTypedValue toTypedValue(Object val)
- {
- if(val == null)
- {
- return AMQType.VOID.asTypedValue(null);
- }
-
- Class klass = val.getClass();
- if(klass == String.class)
- {
- return AMQType.ASCII_STRING.asTypedValue(val);
- }
- else if(klass == Character.class)
- {
- return AMQType.ASCII_CHARACTER.asTypedValue(val);
- }
- else if(klass == Integer.class)
- {
- return AMQType.INT.asTypedValue(val);
- }
- else if(klass == Long.class)
- {
- return AMQType.LONG.asTypedValue(val);
- }
- else if(klass == Float.class)
- {
- return AMQType.FLOAT.asTypedValue(val);
- }
- else if(klass == Double.class)
- {
- return AMQType.DOUBLE.asTypedValue(val);
- }
- else if(klass == Date.class)
- {
- return AMQType.TIMESTAMP.asTypedValue(val);
- }
- else if(klass == Byte.class)
- {
- return AMQType.BYTE.asTypedValue(val);
- }
- else if(klass == Boolean.class)
- {
- return AMQType.BOOLEAN.asTypedValue(val);
- }
- else if(klass == byte[].class)
- {
- return AMQType.BINARY.asTypedValue(val);
- }
- else if(klass == BigDecimal.class)
- {
- return AMQType.DECIMAL.asTypedValue(val);
- }
- else if(val instanceof Map)
- {
- return AMQType.FIELD_TABLE.asTypedValue(FieldTable.convertToFieldTable((Map)val));
- }
- return null;
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/BasicContentHeaderProperties.java b/java/common/src/main/java/org/apache/qpid/framing/BasicContentHeaderProperties.java
deleted file mode 100644
index c7d89a9927..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/BasicContentHeaderProperties.java
+++ /dev/null
@@ -1,838 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.framing;
-
-import org.apache.mina.common.ByteBuffer;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class BasicContentHeaderProperties implements CommonContentHeaderProperties
-{
- //persistent & non-persistent constants, values as per JMS DeliveryMode
- public static final int NON_PERSISTENT = 1;
- public static final int PERSISTENT = 2;
-
- private static final Logger _logger = LoggerFactory.getLogger(BasicContentHeaderProperties.class);
-
- private static final AMQShortString ZERO_STRING = null;
-
- /**
- * We store the encoded form when we decode the content header so that if we need to write it out without modifying
- * it we can do so without incurring the expense of reencoding it
- */
- private byte[] _encodedForm;
-
- /** Flag indicating whether the entire content header has been decoded yet */
- private boolean _decoded = true;
-
- /**
- * We have some optimisations for partial decoding for maximum performance. The headers are used in the broker for
- * routing in some cases so we can decode that separately.
- */
- private boolean _decodedHeaders = true;
-
- /**
- * We have some optimisations for partial decoding for maximum performance. The content type is used by all clients
- * to determine the message type
- */
- private boolean _decodedContentType = true;
-
- private AMQShortString _contentType;
-
- private AMQShortString _encoding;
-
- private FieldTable _headers;
-
- private byte _deliveryMode;
-
- private byte _priority;
-
- private AMQShortString _correlationId;
-
- private AMQShortString _replyTo;
-
- private long _expiration;
-
- private AMQShortString _messageId;
-
- private long _timestamp;
-
- private AMQShortString _type;
-
- private AMQShortString _userId;
-
- private AMQShortString _appId;
-
- private AMQShortString _clusterId;
-
- private int _propertyFlags = 0;
- private static final int CONTENT_TYPE_MASK = 1 << 15;
- private static final int ENCONDING_MASK = 1 << 14;
- private static final int HEADERS_MASK = 1 << 13;
- private static final int DELIVERY_MODE_MASK = 1 << 12;
- private static final int PROPRITY_MASK = 1 << 11;
- private static final int CORRELATION_ID_MASK = 1 << 10;
- private static final int REPLY_TO_MASK = 1 << 9;
- private static final int EXPIRATION_MASK = 1 << 8;
- private static final int MESSAGE_ID_MASK = 1 << 7;
- private static final int TIMESTAMP_MASK = 1 << 6;
- private static final int TYPE_MASK = 1 << 5;
- private static final int USER_ID_MASK = 1 << 4;
- private static final int APPLICATION_ID_MASK = 1 << 3;
- private static final int CLUSTER_ID_MASK = 1 << 2;
-
-
- /**
- * This is 0_10 specific. We use this property to check if some message properties have been changed.
- */
- private boolean _hasBeenUpdated = false;
-
- public boolean reset()
- {
- boolean result = _hasBeenUpdated;
- _hasBeenUpdated = false;
- return result;
- }
-
- public void updated()
- {
- _hasBeenUpdated = true;
- }
-
- public BasicContentHeaderProperties()
- { }
-
- public int getPropertyListSize()
- {
- if (_encodedForm != null)
- {
- return _encodedForm.length;
- }
- else
- {
- int size = 0;
-
- if ((_propertyFlags & (CONTENT_TYPE_MASK)) > 0)
- {
- size += EncodingUtils.encodedShortStringLength(_contentType);
- }
-
- if ((_propertyFlags & ENCONDING_MASK) > 0)
- {
- size += EncodingUtils.encodedShortStringLength(_encoding);
- }
-
- if ((_propertyFlags & HEADERS_MASK) > 0)
- {
- size += EncodingUtils.encodedFieldTableLength(_headers);
- }
-
- if ((_propertyFlags & DELIVERY_MODE_MASK) > 0)
- {
- size += 1;
- }
-
- if ((_propertyFlags & PROPRITY_MASK) > 0)
- {
- size += 1;
- }
-
- if ((_propertyFlags & CORRELATION_ID_MASK) > 0)
- {
- size += EncodingUtils.encodedShortStringLength(_correlationId);
- }
-
- if ((_propertyFlags & REPLY_TO_MASK) > 0)
- {
- size += EncodingUtils.encodedShortStringLength(_replyTo);
- }
-
- if ((_propertyFlags & EXPIRATION_MASK) > 0)
- {
- if (_expiration == 0L)
- {
- size += EncodingUtils.encodedShortStringLength(ZERO_STRING);
- }
- else
- {
- size += EncodingUtils.encodedShortStringLength(_expiration);
- }
- }
-
- if ((_propertyFlags & MESSAGE_ID_MASK) > 0)
- {
- size += EncodingUtils.encodedShortStringLength(_messageId);
- }
-
- if ((_propertyFlags & TIMESTAMP_MASK) > 0)
- {
- size += 8;
- }
-
- if ((_propertyFlags & TYPE_MASK) > 0)
- {
- size += EncodingUtils.encodedShortStringLength(_type);
- }
-
- if ((_propertyFlags & USER_ID_MASK) > 0)
- {
- size += EncodingUtils.encodedShortStringLength(_userId);
- }
-
- if ((_propertyFlags & APPLICATION_ID_MASK) > 0)
- {
- size += EncodingUtils.encodedShortStringLength(_appId);
- }
-
- if ((_propertyFlags & CLUSTER_ID_MASK) > 0)
- {
- size += EncodingUtils.encodedShortStringLength(_clusterId);
- }
-
- return size;
- }
- }
-
- private void clearEncodedForm()
- {
- if (!_decoded && (_encodedForm != null))
- {
- // decode();
- }
-
- _encodedForm = null;
- }
-
- public void setPropertyFlags(int propertyFlags)
- {
- _hasBeenUpdated = true;
- clearEncodedForm();
- _propertyFlags = propertyFlags;
- }
-
- public int getPropertyFlags()
- {
- return _propertyFlags;
- }
-
- public void writePropertyListPayload(ByteBuffer buffer)
- {
- if (_encodedForm != null)
- {
- buffer.put(_encodedForm);
- }
- else
- {
- if ((_propertyFlags & (CONTENT_TYPE_MASK)) != 0)
- {
- EncodingUtils.writeShortStringBytes(buffer, _contentType);
- }
-
- if ((_propertyFlags & ENCONDING_MASK) != 0)
- {
- EncodingUtils.writeShortStringBytes(buffer, _encoding);
- }
-
- if ((_propertyFlags & HEADERS_MASK) != 0)
- {
- EncodingUtils.writeFieldTableBytes(buffer, _headers);
- }
-
- if ((_propertyFlags & DELIVERY_MODE_MASK) != 0)
- {
- buffer.put(_deliveryMode);
- }
-
- if ((_propertyFlags & PROPRITY_MASK) != 0)
- {
- buffer.put(_priority);
- }
-
- if ((_propertyFlags & CORRELATION_ID_MASK) != 0)
- {
- EncodingUtils.writeShortStringBytes(buffer, _correlationId);
- }
-
- if ((_propertyFlags & REPLY_TO_MASK) != 0)
- {
- EncodingUtils.writeShortStringBytes(buffer, _replyTo);
- }
-
- if ((_propertyFlags & EXPIRATION_MASK) != 0)
- {
- if (_expiration == 0L)
- {
- EncodingUtils.writeShortStringBytes(buffer, ZERO_STRING);
- }
- else
- {
- EncodingUtils.writeShortStringBytes(buffer, String.valueOf(_expiration));
- }
- }
-
- if ((_propertyFlags & MESSAGE_ID_MASK) != 0)
- {
- EncodingUtils.writeShortStringBytes(buffer, _messageId);
- }
-
- if ((_propertyFlags & TIMESTAMP_MASK) != 0)
- {
- EncodingUtils.writeTimestamp(buffer, _timestamp);
- }
-
- if ((_propertyFlags & TYPE_MASK) != 0)
- {
- EncodingUtils.writeShortStringBytes(buffer, _type);
- }
-
- if ((_propertyFlags & USER_ID_MASK) != 0)
- {
- EncodingUtils.writeShortStringBytes(buffer, _userId);
- }
-
- if ((_propertyFlags & APPLICATION_ID_MASK) != 0)
- {
- EncodingUtils.writeShortStringBytes(buffer, _appId);
- }
-
- if ((_propertyFlags & CLUSTER_ID_MASK) != 0)
- {
- EncodingUtils.writeShortStringBytes(buffer, _clusterId);
- }
- }
- }
-
- public void populatePropertiesFromBuffer(ByteBuffer buffer, int propertyFlags, int size) throws AMQFrameDecodingException
- {
- _propertyFlags = propertyFlags;
-
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Property flags: " + _propertyFlags);
- }
-
- decode(buffer);
- /*_encodedForm = new byte[size];
- buffer.get(_encodedForm, 0, size);
- _decoded = false;
- _decodedHeaders = false;
- _decodedContentType = false;*/
- }
-
- private void decode(ByteBuffer buffer)
- {
- // ByteBuffer buffer = ByteBuffer.wrap(_encodedForm);
- int pos = buffer.position();
- try
- {
- if ((_propertyFlags & (CONTENT_TYPE_MASK)) != 0)
- {
- _contentType = EncodingUtils.readAMQShortString(buffer);
- }
-
- if ((_propertyFlags & ENCONDING_MASK) != 0)
- {
- _encoding = EncodingUtils.readAMQShortString(buffer);
- }
-
- if ((_propertyFlags & HEADERS_MASK) != 0)
- {
- _headers = EncodingUtils.readFieldTable(buffer);
- }
-
- if ((_propertyFlags & DELIVERY_MODE_MASK) != 0)
- {
- _deliveryMode = buffer.get();
- }
-
- if ((_propertyFlags & PROPRITY_MASK) != 0)
- {
- _priority = buffer.get();
- }
-
- if ((_propertyFlags & CORRELATION_ID_MASK) != 0)
- {
- _correlationId = EncodingUtils.readAMQShortString(buffer);
- }
-
- if ((_propertyFlags & REPLY_TO_MASK) != 0)
- {
- _replyTo = EncodingUtils.readAMQShortString(buffer);
- }
-
- if ((_propertyFlags & EXPIRATION_MASK) != 0)
- {
- _expiration = EncodingUtils.readLongAsShortString(buffer);
- }
-
- if ((_propertyFlags & MESSAGE_ID_MASK) != 0)
- {
- _messageId = EncodingUtils.readAMQShortString(buffer);
- }
-
- if ((_propertyFlags & TIMESTAMP_MASK) != 0)
- {
- _timestamp = EncodingUtils.readTimestamp(buffer);
- }
-
- if ((_propertyFlags & TYPE_MASK) != 0)
- {
- _type = EncodingUtils.readAMQShortString(buffer);
- }
-
- if ((_propertyFlags & USER_ID_MASK) != 0)
- {
- _userId = EncodingUtils.readAMQShortString(buffer);
- }
-
- if ((_propertyFlags & APPLICATION_ID_MASK) != 0)
- {
- _appId = EncodingUtils.readAMQShortString(buffer);
- }
-
- if ((_propertyFlags & CLUSTER_ID_MASK) != 0)
- {
- _clusterId = EncodingUtils.readAMQShortString(buffer);
- }
- }
- catch (AMQFrameDecodingException e)
- {
- throw new RuntimeException("Error in content header data: " + e, e);
- }
-
- final int endPos = buffer.position();
- buffer.position(pos);
- final int len = endPos - pos;
- _encodedForm = new byte[len];
- final int limit = buffer.limit();
- buffer.limit(endPos);
- buffer.get(_encodedForm, 0, len);
- buffer.limit(limit);
- buffer.position(endPos);
- _decoded = true;
- }
-
- private void decodeUpToHeaders()
- {
- ByteBuffer buffer = ByteBuffer.wrap(_encodedForm);
- try
- {
- if ((_propertyFlags & (CONTENT_TYPE_MASK)) != 0)
- {
- byte length = buffer.get();
- buffer.skip(length);
- }
-
- if ((_propertyFlags & ENCONDING_MASK) != 0)
- {
- byte length = buffer.get();
- buffer.skip(length);
- }
-
- if ((_propertyFlags & HEADERS_MASK) != 0)
- {
- _headers = EncodingUtils.readFieldTable(buffer);
-
- }
-
- _decodedHeaders = true;
- }
- catch (AMQFrameDecodingException e)
- {
- throw new RuntimeException("Error in content header data: " + e, e);
- }
- }
-
- private void decodeUpToContentType()
- {
- ByteBuffer buffer = ByteBuffer.wrap(_encodedForm);
-
- if ((_propertyFlags & (CONTENT_TYPE_MASK)) != 0)
- {
- _contentType = EncodingUtils.readAMQShortString(buffer);
- }
-
- _decodedContentType = true;
- }
-
- private void decodeIfNecessary()
- {
- if (!_decoded)
- {
- // decode();
- }
- }
-
- private void decodeHeadersIfNecessary()
- {
- if (!_decoded && !_decodedHeaders)
- {
- decodeUpToHeaders();
- }
- }
-
- private void decodeContentTypeIfNecessary()
- {
- if (!_decoded && !_decodedContentType)
- {
- decodeUpToContentType();
- }
- }
-
- public AMQShortString getContentType()
- {
- decodeContentTypeIfNecessary();
-
- return _contentType;
- }
-
- public String getContentTypeAsString()
- {
- decodeContentTypeIfNecessary();
-
- return (_contentType == null) ? null : _contentType.toString();
- }
-
- public void setContentType(AMQShortString contentType)
- {
- _hasBeenUpdated = true;
- clearEncodedForm();
- _propertyFlags |= (CONTENT_TYPE_MASK);
- _contentType = contentType;
- }
-
- public void setContentType(String contentType)
- {
- _hasBeenUpdated = true;
- setContentType((contentType == null) ? null : new AMQShortString(contentType));
- }
-
- public String getEncodingAsString()
- {
-
- return (getEncoding() == null) ? null : getEncoding().toString();
- }
-
- public AMQShortString getEncoding()
- {
- decodeIfNecessary();
-
- return _encoding;
- }
-
- public void setEncoding(String encoding)
- {
- _hasBeenUpdated = true;
- clearEncodedForm();
- _propertyFlags |= ENCONDING_MASK;
- _encoding = (encoding == null) ? null : new AMQShortString(encoding);
- }
-
- public void setEncoding(AMQShortString encoding)
- {
- _hasBeenUpdated = true;
- clearEncodedForm();
- _propertyFlags |= ENCONDING_MASK;
- _encoding = encoding;
- }
-
- public FieldTable getHeaders()
- {
- decodeHeadersIfNecessary();
-
- if (_headers == null)
- {
- setHeaders(FieldTableFactory.newFieldTable());
- }
-
- return _headers;
- }
-
- public void setHeaders(FieldTable headers)
- {
- _hasBeenUpdated = true;
- clearEncodedForm();
- _propertyFlags |= HEADERS_MASK;
- _headers = headers;
- }
-
- public byte getDeliveryMode()
- {
- decodeIfNecessary();
-
- return _deliveryMode;
- }
-
- public void setDeliveryMode(byte deliveryMode)
- {
- clearEncodedForm();
- _propertyFlags |= DELIVERY_MODE_MASK;
- _deliveryMode = deliveryMode;
- }
-
- public byte getPriority()
- {
- decodeIfNecessary();
-
- return _priority;
- }
-
- public void setPriority(byte priority)
- {
- clearEncodedForm();
- _propertyFlags |= PROPRITY_MASK;
- _priority = priority;
- }
-
- public AMQShortString getCorrelationId()
- {
- decodeIfNecessary();
-
- return _correlationId;
- }
-
- public String getCorrelationIdAsString()
- {
- decodeIfNecessary();
-
- return (_correlationId == null) ? null : _correlationId.toString();
- }
-
- public void setCorrelationId(String correlationId)
- {
- _hasBeenUpdated = true;
- setCorrelationId((correlationId == null) ? null : new AMQShortString(correlationId));
- }
-
- public void setCorrelationId(AMQShortString correlationId)
- {
- _hasBeenUpdated = true;
- clearEncodedForm();
- _propertyFlags |= CORRELATION_ID_MASK;
- _correlationId = correlationId;
- }
-
- public String getReplyToAsString()
- {
- decodeIfNecessary();
-
- return (_replyTo == null) ? null : _replyTo.toString();
- }
-
- public AMQShortString getReplyTo()
- {
- decodeIfNecessary();
-
- return _replyTo;
- }
-
- public void setReplyTo(String replyTo)
- {
- _hasBeenUpdated = true;
- setReplyTo((replyTo == null) ? null : new AMQShortString(replyTo));
- }
-
- public void setReplyTo(AMQShortString replyTo)
- {
- _hasBeenUpdated = true;
- clearEncodedForm();
- _propertyFlags |= REPLY_TO_MASK;
- _replyTo = replyTo;
- }
-
- public long getExpiration()
- {
- decodeIfNecessary();
- return _expiration;
- }
-
- public void setExpiration(long expiration)
- {
- clearEncodedForm();
- _propertyFlags |= EXPIRATION_MASK;
- _expiration = expiration;
- }
-
- public AMQShortString getMessageId()
- {
- decodeIfNecessary();
-
- return _messageId;
- }
-
- public String getMessageIdAsString()
- {
- decodeIfNecessary();
-
- return (_messageId == null) ? null : _messageId.toString();
- }
-
- public void setMessageId(String messageId)
- {
- _hasBeenUpdated = true;
- clearEncodedForm();
- _propertyFlags |= MESSAGE_ID_MASK;
- _messageId = (messageId == null) ? null : new AMQShortString(messageId);
- }
-
- public void setMessageId(AMQShortString messageId)
- {
- _hasBeenUpdated = true;
- clearEncodedForm();
- _propertyFlags |= MESSAGE_ID_MASK;
- _messageId = messageId;
- }
-
- public long getTimestamp()
- {
- decodeIfNecessary();
- return _timestamp;
- }
-
- public void setTimestamp(long timestamp)
- {
- clearEncodedForm();
- _propertyFlags |= TIMESTAMP_MASK;
- _timestamp = timestamp;
- }
-
- public String getTypeAsString()
- {
- decodeIfNecessary();
-
- return (_type == null) ? null : _type.toString();
- }
-
- public AMQShortString getType()
- {
- decodeIfNecessary();
-
- return _type;
- }
-
- public void setType(String type)
- {
- _hasBeenUpdated = true;
- setType((type == null) ? null : new AMQShortString(type));
- }
-
- public void setType(AMQShortString type)
- {
- _hasBeenUpdated = true;
- clearEncodedForm();
- _propertyFlags |= TYPE_MASK;
- _type = type;
- }
-
- public String getUserIdAsString()
- {
- decodeIfNecessary();
-
- return (_userId == null) ? null : _userId.toString();
- }
-
- public AMQShortString getUserId()
- {
- decodeIfNecessary();
-
- return _userId;
- }
-
- public void setUserId(String userId)
- {
- setUserId((userId == null) ? null : new AMQShortString(userId));
- }
-
- public void setUserId(AMQShortString userId)
- {
- _hasBeenUpdated = true;
- clearEncodedForm();
- _propertyFlags |= USER_ID_MASK;
- _userId = userId;
- }
-
- public String getAppIdAsString()
- {
- decodeIfNecessary();
-
- return (_appId == null) ? null : _appId.toString();
- }
-
- public AMQShortString getAppId()
- {
- decodeIfNecessary();
-
- return _appId;
- }
-
- public void setAppId(String appId)
- {
- _hasBeenUpdated = true;
- setAppId((appId == null) ? null : new AMQShortString(appId));
- }
-
- public void setAppId(AMQShortString appId)
- {
- _hasBeenUpdated = true;
- clearEncodedForm();
- _propertyFlags |= APPLICATION_ID_MASK;
- _appId = appId;
- _hasBeenUpdated = true;
- }
-
- public String getClusterIdAsString()
- {
- _hasBeenUpdated = true;
- decodeIfNecessary();
- return (_clusterId == null) ? null : _clusterId.toString();
- }
-
- public AMQShortString getClusterId()
- {
- _hasBeenUpdated = true;
- decodeIfNecessary();
- return _clusterId;
- }
-
- public void setClusterId(String clusterId)
- {
- _hasBeenUpdated = true;
- setClusterId((clusterId == null) ? null : new AMQShortString(clusterId));
- }
-
- public void setClusterId(AMQShortString clusterId)
- {
- _hasBeenUpdated = true;
- clearEncodedForm();
- _propertyFlags |= CLUSTER_ID_MASK;
- _clusterId = clusterId;
- }
-
- public String toString()
- {
- return "reply-to = " + _replyTo + ",propertyFlags = " + _propertyFlags + ",ApplicationID = " + _appId
- + ",ClusterID = " + _clusterId + ",UserId = " + _userId + ",JMSMessageID = " + _messageId
- + ",JMSCorrelationID = " + _correlationId + ",JMSDeliveryMode = " + _deliveryMode + ",JMSExpiration = "
- + _expiration + ",JMSPriority = " + _priority + ",JMSTimestamp = " + _timestamp + ",JMSType = " + _type;
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/BodyFactory.java b/java/common/src/main/java/org/apache/qpid/framing/BodyFactory.java
deleted file mode 100644
index 59646577e1..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/BodyFactory.java
+++ /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.
- *
- */
-package org.apache.qpid.framing;
-
-import org.apache.mina.common.ByteBuffer;
-
-/**
- * Any class that is capable of turning a stream of bytes into an AMQ structure must implement this interface.
- */
-public interface BodyFactory
-{
- AMQBody createBody(ByteBuffer in, long bodySize) throws AMQFrameDecodingException;
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/CommonContentHeaderProperties.java b/java/common/src/main/java/org/apache/qpid/framing/CommonContentHeaderProperties.java
deleted file mode 100644
index 7162c37062..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/CommonContentHeaderProperties.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.qpid.framing;
-
-public interface CommonContentHeaderProperties extends ContentHeaderProperties
-{
- AMQShortString getContentType();
-
- void setContentType(AMQShortString contentType);
-
- FieldTable getHeaders();
-
- void setHeaders(FieldTable headers);
-
- byte getDeliveryMode();
-
- void setDeliveryMode(byte deliveryMode);
-
- byte getPriority();
-
- void setPriority(byte priority);
-
- AMQShortString getCorrelationId();
-
- void setCorrelationId(AMQShortString correlationId);
-
- AMQShortString getReplyTo();
-
- void setReplyTo(AMQShortString replyTo);
-
- long getExpiration();
-
- void setExpiration(long expiration);
-
- AMQShortString getMessageId();
-
- void setMessageId(AMQShortString messageId);
-
- long getTimestamp();
-
- void setTimestamp(long timestamp);
-
- AMQShortString getType();
-
- void setType(AMQShortString type);
-
- AMQShortString getUserId();
-
- void setUserId(AMQShortString userId);
-
- AMQShortString getAppId();
-
- void setAppId(AMQShortString appId);
-
- AMQShortString getClusterId();
-
- void setClusterId(AMQShortString clusterId);
-
- AMQShortString getEncoding();
-
- void setEncoding(AMQShortString encoding);
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/CompositeAMQDataBlock.java b/java/common/src/main/java/org/apache/qpid/framing/CompositeAMQDataBlock.java
deleted file mode 100644
index 94030f383e..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/CompositeAMQDataBlock.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.framing;
-
-import org.apache.mina.common.ByteBuffer;
-
-public class CompositeAMQDataBlock extends AMQDataBlock implements EncodableAMQDataBlock
-{
-
- private AMQDataBlock[] _blocks;
-
- public CompositeAMQDataBlock(AMQDataBlock[] blocks)
- {
- _blocks = blocks;
- }
-
-
- public AMQDataBlock[] getBlocks()
- {
- return _blocks;
- }
-
-
- public long getSize()
- {
- long frameSize = 0;
- for (int i = 0; i < _blocks.length; i++)
- {
- frameSize += _blocks[i].getSize();
- }
- return frameSize;
- }
-
- public void writePayload(ByteBuffer buffer)
- {
- for (int i = 0; i < _blocks.length; i++)
- {
- _blocks[i].writePayload(buffer);
- }
- }
-
- public String toString()
- {
- if (_blocks == null)
- {
- return "No blocks contained in composite frame";
- }
- else
- {
- StringBuilder buf = new StringBuilder(this.getClass().getName());
- buf.append("{");
- for (int i = 0 ; i < _blocks.length; i++)
- {
- buf.append(" ").append(i).append("=[").append(_blocks[i].toString()).append("]");
- }
- buf.append("}");
- return buf.toString();
- }
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/Content.java b/java/common/src/main/java/org/apache/qpid/framing/Content.java
deleted file mode 100644
index e5feeec2a4..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/Content.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.framing;
-
-public interface Content
-{
- // TODO: New Content class required for AMQP 0-9.
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/ContentBody.java b/java/common/src/main/java/org/apache/qpid/framing/ContentBody.java
deleted file mode 100644
index 9d39f8aa86..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/ContentBody.java
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.framing;
-
-import org.apache.mina.common.ByteBuffer;
-import org.apache.qpid.protocol.AMQVersionAwareProtocolSession;
-import org.apache.qpid.AMQException;
-
-public class ContentBody implements AMQBody
-{
- public static final byte TYPE = 3;
-
- public ByteBuffer payload;
-
- public ContentBody()
- {
- }
-
- public ContentBody(ByteBuffer buffer, long size) throws AMQFrameDecodingException
- {
- if (size > 0)
- {
- payload = buffer.slice();
- payload.limit((int) size);
- buffer.skip((int) size);
- }
-
- }
-
-
- public ContentBody(ByteBuffer payload)
- {
- this.payload = payload;
- }
-
- public byte getFrameType()
- {
- return TYPE;
- }
-
- public int getSize()
- {
- return (payload == null ? 0 : payload.limit());
- }
-
- public void writePayload(ByteBuffer buffer)
- {
- if (payload != null)
- {
- if(payload.isDirect() || payload.isReadOnly())
- {
- ByteBuffer copy = payload.duplicate();
- buffer.put(copy.rewind());
- }
- else
- {
- buffer.put(payload.array(),payload.arrayOffset(),payload.limit());
- }
- }
- }
-
- public void handle(final int channelId, final AMQVersionAwareProtocolSession session)
- throws AMQException
- {
- session.contentBodyReceived(channelId, this);
- }
-
- protected void populateFromBuffer(ByteBuffer buffer, long size) throws AMQFrameDecodingException
- {
- if (size > 0)
- {
- payload = buffer.slice();
- payload.limit((int) size);
- buffer.skip((int) size);
- }
-
- }
-
- public void reduceBufferToFit()
- {
- if (payload != null && (payload.remaining() < payload.capacity() / 2))
- {
- int size = payload.limit();
- ByteBuffer newPayload = ByteBuffer.allocate(size);
-
- newPayload.put(payload);
- newPayload.flip();
-
- //reduce reference count on payload
- payload.release();
-
- payload = newPayload;
- }
- }
-
-
-
- public static AMQFrame createAMQFrame(int channelId, ContentBody body)
- {
- final AMQFrame frame = new AMQFrame(channelId, body);
- return frame;
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/ContentBodyFactory.java b/java/common/src/main/java/org/apache/qpid/framing/ContentBodyFactory.java
deleted file mode 100644
index c42995d148..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/ContentBodyFactory.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.framing;
-
-import org.apache.mina.common.ByteBuffer;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class ContentBodyFactory implements BodyFactory
-{
- private static final Logger _log = LoggerFactory.getLogger(AMQMethodBodyFactory.class);
-
- private static final ContentBodyFactory _instance = new ContentBodyFactory();
-
- public static ContentBodyFactory getInstance()
- {
- return _instance;
- }
-
- private ContentBodyFactory()
- {
- _log.debug("Creating content body factory");
- }
-
- public AMQBody createBody(ByteBuffer in, long bodySize) throws AMQFrameDecodingException
- {
- return new ContentBody(in, bodySize);
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderBody.java b/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderBody.java
deleted file mode 100644
index 30db3b8be7..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderBody.java
+++ /dev/null
@@ -1,141 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.framing;
-
-import org.apache.mina.common.ByteBuffer;
-import org.apache.qpid.protocol.AMQVersionAwareProtocolSession;
-import org.apache.qpid.AMQException;
-
-public class ContentHeaderBody implements AMQBody
-{
- public static final byte TYPE = 2;
-
- public int classId;
-
- public int weight;
-
- /** unsigned long but java can't handle that anyway when allocating byte array */
- public long bodySize;
-
- /** must never be null */
- private ContentHeaderProperties properties;
-
- public ContentHeaderBody()
- {
- }
-
- public ContentHeaderBody(ByteBuffer buffer, long size) throws AMQFrameDecodingException
- {
- classId = buffer.getUnsignedShort();
- weight = buffer.getUnsignedShort();
- bodySize = buffer.getLong();
- int propertyFlags = buffer.getUnsignedShort();
- ContentHeaderPropertiesFactory factory = ContentHeaderPropertiesFactory.getInstance();
- properties = factory.createContentHeaderProperties(classId, propertyFlags, buffer, (int)size - 14);
-
- }
-
-
- public ContentHeaderBody(ContentHeaderProperties props, int classId)
- {
- properties = props;
- this.classId = classId;
- }
-
- public ContentHeaderBody(int classId, int weight, ContentHeaderProperties props, long bodySize)
- {
- this(props, classId);
- this.weight = weight;
- this.bodySize = bodySize;
- }
-
- public byte getFrameType()
- {
- return TYPE;
- }
-
- protected void populateFromBuffer(ByteBuffer buffer, long size)
- throws AMQFrameDecodingException, AMQProtocolVersionException
- {
- classId = buffer.getUnsignedShort();
- weight = buffer.getUnsignedShort();
- bodySize = buffer.getLong();
- int propertyFlags = buffer.getUnsignedShort();
- ContentHeaderPropertiesFactory factory = ContentHeaderPropertiesFactory.getInstance();
- properties = factory.createContentHeaderProperties(classId, propertyFlags, buffer, (int)size - 14);
- }
-
- /**
- * Helper method that is used currently by the persistence layer (by BDB at the moment).
- * @param buffer
- * @param size
- * @return
- * @throws AMQFrameDecodingException
- */
- public static ContentHeaderBody createFromBuffer(ByteBuffer buffer, long size)
- throws AMQFrameDecodingException, AMQProtocolVersionException
- {
- ContentHeaderBody body = new ContentHeaderBody(buffer, size);
-
- return body;
- }
-
- public int getSize()
- {
- return 2 + 2 + 8 + 2 + properties.getPropertyListSize();
- }
-
- public void writePayload(ByteBuffer buffer)
- {
- EncodingUtils.writeUnsignedShort(buffer, classId);
- EncodingUtils.writeUnsignedShort(buffer, weight);
- buffer.putLong(bodySize);
- EncodingUtils.writeUnsignedShort(buffer, properties.getPropertyFlags());
- properties.writePropertyListPayload(buffer);
- }
-
- public void handle(final int channelId, final AMQVersionAwareProtocolSession session)
- throws AMQException
- {
- session.contentHeaderReceived(channelId, this);
- }
-
- public static AMQFrame createAMQFrame(int channelId, int classId, int weight, BasicContentHeaderProperties properties,
- long bodySize)
- {
- return new AMQFrame(channelId, new ContentHeaderBody(classId, weight, properties, bodySize));
- }
-
- public static AMQFrame createAMQFrame(int channelId, ContentHeaderBody body)
- {
- return new AMQFrame(channelId, body);
- }
-
- public ContentHeaderProperties getProperties()
- {
- return properties;
- }
-
- public void setProperties(ContentHeaderProperties props)
- {
- properties = props;
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderBodyFactory.java b/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderBodyFactory.java
deleted file mode 100644
index 8d5e2f9fb4..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderBodyFactory.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.framing;
-
-import org.apache.mina.common.ByteBuffer;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class ContentHeaderBodyFactory implements BodyFactory
-{
- private static final Logger _log = LoggerFactory.getLogger(AMQMethodBodyFactory.class);
-
- private static final ContentHeaderBodyFactory _instance = new ContentHeaderBodyFactory();
-
- public static ContentHeaderBodyFactory getInstance()
- {
- return _instance;
- }
-
- private ContentHeaderBodyFactory()
- {
- _log.debug("Creating content header body factory");
- }
-
- public AMQBody createBody(ByteBuffer in, long bodySize) throws AMQFrameDecodingException
- {
- // all content headers are the same - it is only the properties that differ.
- // the content header body further delegates construction of properties
- return new ContentHeaderBody(in, bodySize);
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderProperties.java b/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderProperties.java
deleted file mode 100644
index 7ef538cfdc..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderProperties.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.framing;
-
-import org.apache.mina.common.ByteBuffer;
-
-/**
- * There will be an implementation of this interface for each content type. All content types have associated
- * header properties and this provides a way to encode and decode them.
- */
-public interface ContentHeaderProperties
-{
- /**
- * Writes the property list to the buffer, in a suitably encoded form.
- * @param buffer The buffer to write to
- */
- void writePropertyListPayload(ByteBuffer buffer);
-
- /**
- * Populates the properties from buffer.
- * @param buffer The buffer to read from.
- * @param propertyFlags he property flags.
- * @throws AMQFrameDecodingException when the buffer does not contain valid data
- */
- void populatePropertiesFromBuffer(ByteBuffer buffer, int propertyFlags, int size)
- throws AMQFrameDecodingException;
-
- /**
- * @return the size of the encoded property list in bytes.
- */
- int getPropertyListSize();
-
- /**
- * Gets the property flags. Property flags indicate which properties are set in the list. The
- * position and meaning of each flag is defined in the protocol specification for the particular
- * content type with which these properties are associated.
- * @return flags
- */
- int getPropertyFlags();
-
- void updated();
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderPropertiesFactory.java b/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderPropertiesFactory.java
deleted file mode 100644
index 46189b63d7..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderPropertiesFactory.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.framing;
-
-import org.apache.mina.common.ByteBuffer;
-
-import org.apache.qpid.framing.amqp_8_0.BasicConsumeBodyImpl;
-
-public class ContentHeaderPropertiesFactory
-{
- private static final ContentHeaderPropertiesFactory _instance = new ContentHeaderPropertiesFactory();
-
- public static ContentHeaderPropertiesFactory getInstance()
- {
- return _instance;
- }
-
- private ContentHeaderPropertiesFactory()
- {
- }
-
- public ContentHeaderProperties createContentHeaderProperties(int classId, int propertyFlags,
- ByteBuffer buffer, int size)
- throws AMQFrameDecodingException
- {
- ContentHeaderProperties properties;
- // AMQP version change: "Hardwired" version to major=8, minor=0
- // TODO: Change so that the actual version is obtained from
- // the ProtocolInitiation object for this session.
- if (classId == BasicConsumeBodyImpl.CLASS_ID)
- {
- properties = new BasicContentHeaderProperties();
- }
- else
- {
- throw new AMQFrameDecodingException(null, "Unsupport content header class id: " + classId, null);
- }
- properties.populatePropertiesFromBuffer(buffer, propertyFlags, size);
- return properties;
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/DeferredDataBlock.java b/java/common/src/main/java/org/apache/qpid/framing/DeferredDataBlock.java
deleted file mode 100644
index f6795ff200..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/DeferredDataBlock.java
+++ /dev/null
@@ -1,50 +0,0 @@
-package org.apache.qpid.framing;
-
-import org.apache.mina.common.ByteBuffer;
-
-/*
-*
-* 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 abstract class DeferredDataBlock extends AMQDataBlock
-{
- private AMQDataBlock _underlyingDataBlock;
-
-
- public long getSize()
- {
- if(_underlyingDataBlock == null)
- {
- _underlyingDataBlock = createAMQDataBlock();
- }
- return _underlyingDataBlock.getSize();
- }
-
- public void writePayload(ByteBuffer buffer)
- {
- if(_underlyingDataBlock == null)
- {
- _underlyingDataBlock = createAMQDataBlock();
- }
- _underlyingDataBlock.writePayload(buffer);
- }
-
- abstract protected AMQDataBlock createAMQDataBlock();
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/EncodableAMQDataBlock.java b/java/common/src/main/java/org/apache/qpid/framing/EncodableAMQDataBlock.java
deleted file mode 100644
index 9cf96e698c..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/EncodableAMQDataBlock.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.framing;
-
-/**
- * Marker interface to indicate to MINA that a data block should be encoded with the
- * single encoder/decoder that we have defined.
- *
- * Note that due to a bug in MINA all classes must directly implement this interface, even if
- * a superclass implements it.
- * TODO: fix MINA so that this is not necessary
- *
- */
-public interface EncodableAMQDataBlock
-{
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/EncodingUtils.java b/java/common/src/main/java/org/apache/qpid/framing/EncodingUtils.java
deleted file mode 100644
index 6425f8c591..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/EncodingUtils.java
+++ /dev/null
@@ -1,1033 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.framing;
-
-import org.apache.mina.common.ByteBuffer;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.nio.charset.Charset;
-
-public class EncodingUtils
-{
- private static final Logger _logger = LoggerFactory.getLogger(EncodingUtils.class);
-
- private static final String STRING_ENCODING = "iso8859-15";
-
- private static final Charset _charset = Charset.forName("iso8859-15");
-
- public static final int SIZEOF_UNSIGNED_SHORT = 2;
- public static final int SIZEOF_UNSIGNED_INT = 4;
- private static final boolean[] ALL_FALSE_ARRAY = new boolean[8];
-
- public static int encodedShortStringLength(String s)
- {
- if (s == null)
- {
- return 1;
- }
- else
- {
- return (short) (1 + s.length());
- }
- }
-
- public static int encodedShortStringLength(short s)
- {
- if (s == 0)
- {
- return 1 + 1;
- }
-
- int len = 0;
- if (s < 0)
- {
- len = 1;
- // sloppy - doesn't work of Integer.MIN_VALUE
- s = (short) -s;
- }
-
- if (s > 9999)
- {
- return 1 + 5;
- }
- else if (s > 999)
- {
- return 1 + 4;
- }
- else if (s > 99)
- {
- return 1 + 3;
- }
- else if (s > 9)
- {
- return 1 + 2;
- }
- else
- {
- return 1 + 1;
- }
-
- }
-
- public static int encodedShortStringLength(int i)
- {
- if (i == 0)
- {
- return 1 + 1;
- }
-
- int len = 0;
- if (i < 0)
- {
- len = 1;
- // sloppy - doesn't work of Integer.MIN_VALUE
- i = -i;
- }
-
- // range is now 1 - 2147483647
- if (i < Short.MAX_VALUE)
- {
- return len + encodedShortStringLength((short) i);
- }
- else if (i > 999999)
- {
- return len + 6 + encodedShortStringLength((short) (i / 1000000));
- }
- else // if (i > 99999)
- {
- return len + 5 + encodedShortStringLength((short) (i / 100000));
- }
-
- }
-
- public static int encodedShortStringLength(long l)
- {
- if (l == 0)
- {
- return 1 + 1;
- }
-
- int len = 0;
- if (l < 0)
- {
- len = 1;
- // sloppy - doesn't work of Long.MIN_VALUE
- l = -l;
- }
-
- if (l < Integer.MAX_VALUE)
- {
- return len + encodedShortStringLength((int) l);
- }
- else if (l > 9999999999L)
- {
- return len + 10 + encodedShortStringLength((int) (l / 10000000000L));
- }
- else
- {
- return len + 1 + encodedShortStringLength((int) (l / 10L));
- }
-
- }
-
- public static int encodedShortStringLength(AMQShortString s)
- {
- if (s == null)
- {
- return 1;
- }
- else
- {
- return (1 + s.length());
- }
- }
-
- public static int encodedLongStringLength(String s)
- {
- if (s == null)
- {
- return 4;
- }
- else
- {
- return 4 + s.length();
- }
- }
-
- public static int encodedLongStringLength(char[] s)
- {
- if (s == null)
- {
- return 4;
- }
- else
- {
- return 4 + s.length;
- }
- }
-
- public static int encodedLongstrLength(byte[] bytes)
- {
- if (bytes == null)
- {
- return 4;
- }
- else
- {
- return 4 + bytes.length;
- }
- }
-
- public static int encodedFieldTableLength(FieldTable table)
- {
- if (table == null)
- {
- // length is encoded as 4 octets
- return 4;
- }
- else
- {
- // length of the table plus 4 octets for the length
- return (int) table.getEncodedSize() + 4;
- }
- }
-
- public static int encodedContentLength(Content table)
- {
- // TODO: New Content class required for AMQP 0-9.
- return 0;
- }
-
- public static void writeShortStringBytes(ByteBuffer buffer, String s)
- {
- if (s != null)
- {
- byte[] encodedString = new byte[s.length()];
- char[] cha = s.toCharArray();
- for (int i = 0; i < cha.length; i++)
- {
- encodedString[i] = (byte) cha[i];
- }
-
- // TODO: check length fits in an unsigned byte
- writeUnsignedByte(buffer, (short)encodedString.length);
- buffer.put(encodedString);
-
-
- }
- else
- {
- // really writing out unsigned byte
- buffer.put((byte) 0);
- }
- }
-
- public static void writeShortStringBytes(ByteBuffer buffer, AMQShortString s)
- {
- if (s != null)
- {
-
- s.writeToBuffer(buffer);
- }
- else
- {
- // really writing out unsigned byte
- buffer.put((byte) 0);
- }
- }
-
- public static void writeLongStringBytes(ByteBuffer buffer, String s)
- {
- assert (s == null) || (s.length() <= 0xFFFE);
- if (s != null)
- {
- int len = s.length();
- writeUnsignedInteger(buffer, s.length());
- byte[] encodedString = new byte[len];
- char[] cha = s.toCharArray();
- for (int i = 0; i < cha.length; i++)
- {
- encodedString[i] = (byte) cha[i];
- }
-
- buffer.put(encodedString);
- }
- else
- {
- writeUnsignedInteger(buffer, 0);
- }
- }
-
- public static void writeLongStringBytes(ByteBuffer buffer, char[] s)
- {
- assert (s == null) || (s.length <= 0xFFFE);
- if (s != null)
- {
- int len = s.length;
- writeUnsignedInteger(buffer, s.length);
- byte[] encodedString = new byte[len];
- for (int i = 0; i < s.length; i++)
- {
- encodedString[i] = (byte) s[i];
- }
-
- buffer.put(encodedString);
- }
- else
- {
- writeUnsignedInteger(buffer, 0);
- }
- }
-
- public static void writeLongStringBytes(ByteBuffer buffer, byte[] bytes)
- {
- assert (bytes == null) || (bytes.length <= 0xFFFE);
- if (bytes != null)
- {
- writeUnsignedInteger(buffer, bytes.length);
- buffer.put(bytes);
- }
- else
- {
- writeUnsignedInteger(buffer, 0);
- }
- }
-
- public static void writeUnsignedByte(ByteBuffer buffer, short b)
- {
- byte bv = (byte) b;
- buffer.put(bv);
- }
-
- public static void writeUnsignedShort(ByteBuffer buffer, int s)
- {
- // TODO: Is this comparison safe? Do I need to cast RHS to long?
- if (s < Short.MAX_VALUE)
- {
- buffer.putShort((short) s);
- }
- else
- {
- short sv = (short) s;
- buffer.put((byte) (0xFF & (sv >> 8)));
- buffer.put((byte) (0xFF & sv));
- }
- }
-
- public static int unsignedIntegerLength()
- {
- return 4;
- }
-
- public static void writeUnsignedInteger(ByteBuffer buffer, long l)
- {
- // TODO: Is this comparison safe? Do I need to cast RHS to long?
- if (l < Integer.MAX_VALUE)
- {
- buffer.putInt((int) l);
- }
- else
- {
- int iv = (int) l;
-
- // FIXME: This *may* go faster if we build this into a local 4-byte array and then
- // put the array in a single call.
- buffer.put((byte) (0xFF & (iv >> 24)));
- buffer.put((byte) (0xFF & (iv >> 16)));
- buffer.put((byte) (0xFF & (iv >> 8)));
- buffer.put((byte) (0xFF & iv));
- }
- }
-
- public static void writeFieldTableBytes(ByteBuffer buffer, FieldTable table)
- {
- if (table != null)
- {
- table.writeToBuffer(buffer);
- }
- else
- {
- EncodingUtils.writeUnsignedInteger(buffer, 0);
- }
- }
-
- public static void writeContentBytes(ByteBuffer buffer, Content content)
- {
- // TODO: New Content class required for AMQP 0-9.
- }
-
- public static void writeBooleans(ByteBuffer buffer, boolean[] values)
- {
- byte packedValue = 0;
- for (int i = 0; i < values.length; i++)
- {
- if (values[i])
- {
- packedValue = (byte) (packedValue | (1 << i));
- }
- }
-
- buffer.put(packedValue);
- }
-
- public static void writeBooleans(ByteBuffer buffer, boolean value)
- {
-
- buffer.put(value ? (byte) 1 : (byte) 0);
- }
-
- public static void writeBooleans(ByteBuffer buffer, boolean value0, boolean value1)
- {
- byte packedValue = value0 ? (byte) 1 : (byte) 0;
-
- if (value1)
- {
- packedValue = (byte) (packedValue | (byte) (1 << 1));
- }
-
- buffer.put(packedValue);
- }
-
- public static void writeBooleans(ByteBuffer buffer, boolean value0, boolean value1, boolean value2)
- {
- byte packedValue = value0 ? (byte) 1 : (byte) 0;
-
- if (value1)
- {
- packedValue = (byte) (packedValue | (byte) (1 << 1));
- }
-
- if (value2)
- {
- packedValue = (byte) (packedValue | (byte) (1 << 2));
- }
-
- buffer.put(packedValue);
- }
-
- public static void writeBooleans(ByteBuffer buffer, boolean value0, boolean value1, boolean value2, boolean value3)
- {
- byte packedValue = value0 ? (byte) 1 : (byte) 0;
-
- if (value1)
- {
- packedValue = (byte) (packedValue | (byte) (1 << 1));
- }
-
- if (value2)
- {
- packedValue = (byte) (packedValue | (byte) (1 << 2));
- }
-
- if (value3)
- {
- packedValue = (byte) (packedValue | (byte) (1 << 3));
- }
-
- buffer.put(packedValue);
- }
-
- public static void writeBooleans(ByteBuffer buffer, boolean value0, boolean value1, boolean value2, boolean value3,
- boolean value4)
- {
- byte packedValue = value0 ? (byte) 1 : (byte) 0;
-
- if (value1)
- {
- packedValue = (byte) (packedValue | (byte) (1 << 1));
- }
-
- if (value2)
- {
- packedValue = (byte) (packedValue | (byte) (1 << 2));
- }
-
- if (value3)
- {
- packedValue = (byte) (packedValue | (byte) (1 << 3));
- }
-
- if (value4)
- {
- packedValue = (byte) (packedValue | (byte) (1 << 4));
- }
-
- buffer.put(packedValue);
- }
-
- public static void writeBooleans(ByteBuffer buffer, boolean value0, boolean value1, boolean value2, boolean value3,
- boolean value4, boolean value5)
- {
- byte packedValue = value0 ? (byte) 1 : (byte) 0;
-
- if (value1)
- {
- packedValue = (byte) (packedValue | (byte) (1 << 1));
- }
-
- if (value2)
- {
- packedValue = (byte) (packedValue | (byte) (1 << 2));
- }
-
- if (value3)
- {
- packedValue = (byte) (packedValue | (byte) (1 << 3));
- }
-
- if (value4)
- {
- packedValue = (byte) (packedValue | (byte) (1 << 4));
- }
-
- if (value5)
- {
- packedValue = (byte) (packedValue | (byte) (1 << 5));
- }
-
- buffer.put(packedValue);
- }
-
- public static void writeBooleans(ByteBuffer buffer, boolean value0, boolean value1, boolean value2, boolean value3,
- boolean value4, boolean value5, boolean value6)
- {
- byte packedValue = value0 ? (byte) 1 : (byte) 0;
-
- if (value1)
- {
- packedValue = (byte) (packedValue | (byte) (1 << 1));
- }
-
- if (value2)
- {
- packedValue = (byte) (packedValue | (byte) (1 << 2));
- }
-
- if (value3)
- {
- packedValue = (byte) (packedValue | (byte) (1 << 3));
- }
-
- if (value4)
- {
- packedValue = (byte) (packedValue | (byte) (1 << 4));
- }
-
- if (value5)
- {
- packedValue = (byte) (packedValue | (byte) (1 << 5));
- }
-
- if (value6)
- {
- packedValue = (byte) (packedValue | (byte) (1 << 6));
- }
-
- buffer.put(packedValue);
- }
-
- public static void writeBooleans(ByteBuffer buffer, boolean value0, boolean value1, boolean value2, boolean value3,
- boolean value4, boolean value5, boolean value6, boolean value7)
- {
- byte packedValue = value0 ? (byte) 1 : (byte) 0;
-
- if (value1)
- {
- packedValue = (byte) (packedValue | (byte) (1 << 1));
- }
-
- if (value2)
- {
- packedValue = (byte) (packedValue | (byte) (1 << 2));
- }
-
- if (value3)
- {
- packedValue = (byte) (packedValue | (byte) (1 << 3));
- }
-
- if (value4)
- {
- packedValue = (byte) (packedValue | (byte) (1 << 4));
- }
-
- if (value5)
- {
- packedValue = (byte) (packedValue | (byte) (1 << 5));
- }
-
- if (value6)
- {
- packedValue = (byte) (packedValue | (byte) (1 << 6));
- }
-
- if (value7)
- {
- packedValue = (byte) (packedValue | (byte) (1 << 7));
- }
-
- buffer.put(packedValue);
- }
-
- /**
- * This is used for writing longstrs.
- *
- * @param buffer
- * @param data
- */
- public static void writeLongstr(ByteBuffer buffer, byte[] data)
- {
- if (data != null)
- {
- writeUnsignedInteger(buffer, data.length);
- buffer.put(data);
- }
- else
- {
- writeUnsignedInteger(buffer, 0);
- }
- }
-
- public static void writeTimestamp(ByteBuffer buffer, long timestamp)
- {
- writeLong(buffer, timestamp);
- }
-
- public static boolean[] readBooleans(ByteBuffer buffer)
- {
- final byte packedValue = buffer.get();
- if (packedValue == 0)
- {
- return ALL_FALSE_ARRAY;
- }
-
- final boolean[] result = new boolean[8];
-
- result[0] = ((packedValue & 1) != 0);
- result[1] = ((packedValue & (1 << 1)) != 0);
- result[2] = ((packedValue & (1 << 2)) != 0);
- result[3] = ((packedValue & (1 << 3)) != 0);
- if ((packedValue & 0xF0) == 0)
- {
- result[0] = ((packedValue & 1) != 0);
- }
-
- result[4] = ((packedValue & (1 << 4)) != 0);
- result[5] = ((packedValue & (1 << 5)) != 0);
- result[6] = ((packedValue & (1 << 6)) != 0);
- result[7] = ((packedValue & (1 << 7)) != 0);
-
- return result;
- }
-
- public static FieldTable readFieldTable(ByteBuffer buffer) throws AMQFrameDecodingException
- {
- long length = buffer.getUnsignedInt();
- if (length == 0)
- {
- return null;
- }
- else
- {
- return FieldTableFactory.newFieldTable(buffer, length);
- }
- }
-
- public static Content readContent(ByteBuffer buffer) throws AMQFrameDecodingException
- {
- // TODO: New Content class required for AMQP 0-9.
- return null;
- }
-
- public static AMQShortString readAMQShortString(ByteBuffer buffer)
- {
- return AMQShortString.readFromBuffer(buffer);
-
- }
-
- public static String readShortString(ByteBuffer buffer)
- {
- short length = buffer.getUnsigned();
- if (length == 0)
- {
- return null;
- }
- else
- {
- // this may seem rather odd to declare two array but testing has shown
- // that constructing a string from a byte array is 5 (five) times slower
- // than constructing one from a char array.
- // this approach here is valid since we know that all the chars are
- // ASCII (0-127)
- byte[] stringBytes = new byte[length];
- buffer.get(stringBytes, 0, length);
- char[] stringChars = new char[length];
- for (int i = 0; i < stringChars.length; i++)
- {
- stringChars[i] = (char) stringBytes[i];
- }
-
- return new String(stringChars);
- }
- }
-
- public static String readLongString(ByteBuffer buffer)
- {
- long length = buffer.getUnsignedInt();
- if (length == 0)
- {
- return "";
- }
- else
- {
- // this may seem rather odd to declare two array but testing has shown
- // that constructing a string from a byte array is 5 (five) times slower
- // than constructing one from a char array.
- // this approach here is valid since we know that all the chars are
- // ASCII (0-127)
- byte[] stringBytes = new byte[(int) length];
- buffer.get(stringBytes, 0, (int) length);
- char[] stringChars = new char[(int) length];
- for (int i = 0; i < stringChars.length; i++)
- {
- stringChars[i] = (char) stringBytes[i];
- }
-
- return new String(stringChars);
- }
- }
-
- public static byte[] readLongstr(ByteBuffer buffer)
- {
- long length = buffer.getUnsignedInt();
- if (length == 0)
- {
- return null;
- }
- else
- {
- byte[] result = new byte[(int) length];
- buffer.get(result);
-
- return result;
- }
- }
-
- public static long readTimestamp(ByteBuffer buffer)
- {
- // Discard msb from AMQ timestamp
- // buffer.getUnsignedInt();
- return buffer.getLong();
- }
-
- static byte[] hexToByteArray(String id)
- {
- // Should check param for null, long enough for this check, upper-case and trailing char
- String s = (id.charAt(1) == 'x') ? id.substring(2) : id; // strip 0x
-
- int len = s.length();
- int byte_len = len / 2;
- byte[] b = new byte[byte_len];
-
- for (int i = 0; i < byte_len; i++)
- {
- // fixme: refine these repetitive subscript calcs.
- int ch = i * 2;
-
- byte b1 = Byte.parseByte(s.substring(ch, ch + 1), 16);
- byte b2 = Byte.parseByte(s.substring(ch + 1, ch + 2), 16);
-
- b[i] = (byte) ((b1 * 16) + b2);
- }
-
- return (b);
- }
-
- public static char[] convertToHexCharArray(byte[] from)
- {
- int length = from.length;
- char[] result_buff = new char[(length * 2) + 2];
-
- result_buff[0] = '0';
- result_buff[1] = 'x';
-
- int bite;
- int dest = 2;
-
- for (int i = 0; i < length; i++)
- {
- bite = from[i];
-
- if (bite < 0)
- {
- bite += 256;
- }
-
- result_buff[dest++] = hex_chars[bite >> 4];
- result_buff[dest++] = hex_chars[bite & 0x0f];
- }
-
- return (result_buff);
- }
-
- public static String convertToHexString(byte[] from)
- {
- return (new String(convertToHexCharArray(from)));
- }
-
- public static String convertToHexString(ByteBuffer bb)
- {
- int size = bb.limit();
-
- byte[] from = new byte[size];
-
- // Is this not the same.
- // bb.get(from, 0, length);
- for (int i = 0; i < size; i++)
- {
- from[i] = bb.get(i);
- }
-
- return (new String(convertToHexCharArray(from)));
- }
-
- private static char[] hex_chars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
-
- // **** new methods
-
- // AMQP_BOOLEAN_PROPERTY_PREFIX
-
- public static void writeBoolean(ByteBuffer buffer, Boolean aBoolean)
- {
- buffer.put((byte) (aBoolean ? 1 : 0));
- }
-
- public static boolean readBoolean(ByteBuffer buffer)
- {
- byte packedValue = buffer.get();
-
- return (packedValue == 1);
- }
-
- public static int encodedBooleanLength()
- {
- return 1;
- }
-
- // AMQP_BYTE_PROPERTY_PREFIX
- public static void writeByte(ByteBuffer buffer, Byte aByte)
- {
- buffer.put(aByte);
- }
-
- public static byte readByte(ByteBuffer buffer)
- {
- return buffer.get();
- }
-
- public static int encodedByteLength()
- {
- return 1;
- }
-
- // AMQP_SHORT_PROPERTY_PREFIX
- public static void writeShort(ByteBuffer buffer, Short aShort)
- {
- buffer.putShort(aShort);
- }
-
- public static short readShort(ByteBuffer buffer)
- {
- return buffer.getShort();
- }
-
- public static int encodedShortLength()
- {
- return 2;
- }
-
- // INTEGER_PROPERTY_PREFIX
- public static void writeInteger(ByteBuffer buffer, Integer aInteger)
- {
- buffer.putInt(aInteger);
- }
-
- public static int readInteger(ByteBuffer buffer)
- {
- return buffer.getInt();
- }
-
- public static int encodedIntegerLength()
- {
- return 4;
- }
-
- // AMQP_LONG_PROPERTY_PREFIX
- public static void writeLong(ByteBuffer buffer, Long aLong)
- {
- buffer.putLong(aLong);
- }
-
- public static long readLong(ByteBuffer buffer)
- {
- return buffer.getLong();
- }
-
- public static int encodedLongLength()
- {
- return 8;
- }
-
- // Float_PROPERTY_PREFIX
- public static void writeFloat(ByteBuffer buffer, Float aFloat)
- {
- buffer.putFloat(aFloat);
- }
-
- public static float readFloat(ByteBuffer buffer)
- {
- return buffer.getFloat();
- }
-
- public static int encodedFloatLength()
- {
- return 4;
- }
-
- // Double_PROPERTY_PREFIX
- public static void writeDouble(ByteBuffer buffer, Double aDouble)
- {
- buffer.putDouble(aDouble);
- }
-
- public static double readDouble(ByteBuffer buffer)
- {
- return buffer.getDouble();
- }
-
- public static int encodedDoubleLength()
- {
- return 8;
- }
-
- public static byte[] readBytes(ByteBuffer buffer)
- {
- long length = buffer.getUnsignedInt();
- if (length == 0)
- {
- return null;
- }
- else
- {
- byte[] dataBytes = new byte[(int)length];
- buffer.get(dataBytes, 0, (int)length);
-
- return dataBytes;
- }
- }
-
- public static void writeBytes(ByteBuffer buffer, byte[] data)
- {
- if (data != null)
- {
- // TODO: check length fits in an unsigned byte
- writeUnsignedInteger(buffer, (long)data.length);
- buffer.put(data);
- }
- else
- {
- // really writing out unsigned byte
- //buffer.put((byte) 0);
- writeUnsignedInteger(buffer, 0L);
- }
- }
-
- // CHAR_PROPERTY
- public static int encodedCharLength()
- {
- return encodedByteLength();
- }
-
- public static char readChar(ByteBuffer buffer)
- {
- // This is valid as we know that the Character is ASCII 0..127
- return (char) buffer.get();
- }
-
- public static void writeChar(ByteBuffer buffer, char character)
- {
- // This is valid as we know that the Character is ASCII 0..127
- writeByte(buffer, (byte) character);
- }
-
- public static long readLongAsShortString(ByteBuffer buffer)
- {
- short length = buffer.getUnsigned();
- short pos = 0;
- if (length == 0)
- {
- return 0L;
- }
-
- byte digit = buffer.get();
- boolean isNegative;
- long result = 0;
- if (digit == (byte) '-')
- {
- isNegative = true;
- pos++;
- digit = buffer.get();
- }
- else
- {
- isNegative = false;
- }
-
- result = digit - (byte) '0';
- pos++;
-
- while (pos < length)
- {
- pos++;
- digit = buffer.get();
- result = (result << 3) + (result << 1);
- result += digit - (byte) '0';
- }
-
- return result;
- }
-
- public static long readUnsignedInteger(ByteBuffer buffer)
- {
- long l = 0xFF & buffer.get();
- l <<= 8;
- l = l | (0xFF & buffer.get());
- l <<= 8;
- l = l | (0xFF & buffer.get());
- l <<= 8;
- l = l | (0xFF & buffer.get());
-
- return l;
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/FieldTable.java b/java/common/src/main/java/org/apache/qpid/framing/FieldTable.java
deleted file mode 100644
index 22205d49f8..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/FieldTable.java
+++ /dev/null
@@ -1,1246 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.framing;
-
-import org.apache.mina.common.ByteBuffer;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import org.apache.qpid.AMQPInvalidClassException;
-
-import java.math.BigDecimal;
-import java.util.Collections;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.LinkedHashSet;
-import java.util.Map;
-import java.util.Set;
-
-// extends FieldTable
-public class FieldTable
-{
- private static final Logger _logger = LoggerFactory.getLogger(FieldTable.class);
- private static final String STRICT_AMQP = "STRICT_AMQP";
- private final boolean _strictAMQP = Boolean.valueOf(System.getProperty(STRICT_AMQP, "false"));
-
- private ByteBuffer _encodedForm;
- private LinkedHashMap<AMQShortString, AMQTypedValue> _properties;
- private long _encodedSize;
- private static final int INITIAL_HASHMAP_CAPACITY = 16;
- private static final int INITIAL_ENCODED_FORM_SIZE = 256;
-
- public FieldTable()
- {
- super();
- // _encodedForm = ByteBuffer.allocate(INITIAL_ENCODED_FORM_SIZE);
- // _encodedForm.setAutoExpand(true);
- // _encodedForm.limit(0);
- }
-
- /**
- * Construct a new field table.
- *
- * @param buffer the buffer from which to read data. The length byte must be read already
- * @param length the length of the field table. Must be > 0.
- */
- public FieldTable(ByteBuffer buffer, long length)
- {
- this();
- ByteBuffer encodedForm = buffer.slice();
- encodedForm.limit((int) length);
- _encodedForm = ByteBuffer.allocate((int)length);
- _encodedForm.put(encodedForm);
- _encodedForm.flip();
- _encodedSize = length;
- buffer.skip((int) length);
- }
-
- public AMQTypedValue getProperty(AMQShortString string)
- {
- checkPropertyName(string);
-
- synchronized (this)
- {
- if (_properties == null)
- {
- if (_encodedForm == null)
- {
- return null;
- }
- else
- {
- populateFromBuffer();
- }
- }
- }
-
- if (_properties == null)
- {
- return null;
- }
- else
- {
- return _properties.get(string);
- }
- }
-
- private void populateFromBuffer()
- {
- try
- {
- setFromBuffer(_encodedForm, _encodedSize);
- }
- catch (AMQFrameDecodingException e)
- {
- _logger.error("Error decoding FieldTable in deferred decoding mode ", e);
- throw new IllegalArgumentException(e);
- }
- }
-
- private AMQTypedValue setProperty(AMQShortString key, AMQTypedValue val)
- {
- checkPropertyName(key);
- initMapIfNecessary();
- if (_properties.containsKey(key))
- {
- _encodedForm = null;
-
- if (val == null)
- {
- return removeKey(key);
- }
- }
- else if ((_encodedForm != null) && (val != null))
- {
- // We have updated data to store in the buffer
- // So clear the _encodedForm to allow it to be rebuilt later
- // this is safer than simply appending to any existing buffer.
- _encodedForm = null;
- }
- else if (val == null)
- {
- return null;
- }
-
- AMQTypedValue oldVal = _properties.put(key, val);
- if (oldVal != null)
- {
- _encodedSize -= oldVal.getEncodingSize();
- }
- else
- {
- _encodedSize += EncodingUtils.encodedShortStringLength(key) + 1;
- }
-
- _encodedSize += val.getEncodingSize();
-
- return oldVal;
- }
-
- private void initMapIfNecessary()
- {
- synchronized (this)
- {
- if (_properties == null)
- {
- if ((_encodedForm == null) || (_encodedSize == 0))
- {
- _properties = new LinkedHashMap<AMQShortString, AMQTypedValue>();
- }
- else
- {
- populateFromBuffer();
- }
- }
-
- }
- }
-
- public Boolean getBoolean(String string)
- {
- return getBoolean(new AMQShortString(string));
- }
-
- public Boolean getBoolean(AMQShortString string)
- {
- AMQTypedValue value = getProperty(string);
- if ((value != null) && (value.getType() == AMQType.BOOLEAN))
- {
- return (Boolean) value.getValue();
- }
- else
- {
- return null;
- }
- }
-
- public Byte getByte(String string)
- {
- return getByte(new AMQShortString(string));
- }
-
- public Byte getByte(AMQShortString string)
- {
- AMQTypedValue value = getProperty(string);
- if ((value != null) && (value.getType() == AMQType.BYTE))
- {
- return (Byte) value.getValue();
- }
- else
- {
- return null;
- }
- }
-
- public Short getShort(String string)
- {
- return getShort(new AMQShortString(string));
- }
-
- public Short getShort(AMQShortString string)
- {
- AMQTypedValue value = getProperty(string);
- if ((value != null) && (value.getType() == AMQType.SHORT))
- {
- return (Short) value.getValue();
- }
- else
- {
- return null;
- }
- }
-
- public Integer getInteger(String string)
- {
- return getInteger(new AMQShortString(string));
- }
-
- public Integer getInteger(AMQShortString string)
- {
- AMQTypedValue value = getProperty(string);
- if ((value != null) && (value.getType() == AMQType.INT))
- {
- return (Integer) value.getValue();
- }
- else
- {
- return null;
- }
- }
-
- public Long getLong(String string)
- {
- return getLong(new AMQShortString(string));
- }
-
- public Long getLong(AMQShortString string)
- {
- AMQTypedValue value = getProperty(string);
- if ((value != null) && (value.getType() == AMQType.LONG))
- {
- return (Long) value.getValue();
- }
- else
- {
- return null;
- }
- }
-
- public Float getFloat(String string)
- {
- return getFloat(new AMQShortString(string));
- }
-
- public Float getFloat(AMQShortString string)
- {
- AMQTypedValue value = getProperty(string);
- if ((value != null) && (value.getType() == AMQType.FLOAT))
- {
- return (Float) value.getValue();
- }
- else
- {
- return null;
- }
- }
-
- public Double getDouble(String string)
- {
- return getDouble(new AMQShortString(string));
- }
-
- public Double getDouble(AMQShortString string)
- {
- AMQTypedValue value = getProperty(string);
- if ((value != null) && (value.getType() == AMQType.DOUBLE))
- {
- return (Double) value.getValue();
- }
- else
- {
- return null;
- }
- }
-
- public String getString(String string)
- {
- return getString(new AMQShortString(string));
- }
-
- public String getString(AMQShortString string)
- {
- AMQTypedValue value = getProperty(string);
- if ((value != null) && ((value.getType() == AMQType.WIDE_STRING) || (value.getType() == AMQType.ASCII_STRING)))
- {
- return (String) value.getValue();
- }
- else if ((value != null) && (value.getValue() != null) && !(value.getValue() instanceof byte[]))
- {
- return String.valueOf(value.getValue());
- }
- else
- {
- return null;
- }
-
- }
-
- public Character getCharacter(String string)
- {
- return getCharacter(new AMQShortString(string));
- }
-
- public Character getCharacter(AMQShortString string)
- {
- AMQTypedValue value = getProperty(string);
- if ((value != null) && (value.getType() == AMQType.ASCII_CHARACTER))
- {
- return (Character) value.getValue();
- }
- else
- {
- return null;
- }
- }
-
- public byte[] getBytes(String string)
- {
- return getBytes(new AMQShortString(string));
- }
-
- public byte[] getBytes(AMQShortString string)
- {
- AMQTypedValue value = getProperty(string);
- if ((value != null) && (value.getType() == AMQType.BINARY))
- {
- return (byte[]) value.getValue();
- }
- else
- {
- return null;
- }
- }
-
- /**
- * Extracts a value from the field table that is itself a FieldTable associated with the specified parameter name.
- *
- * @param string The name of the parameter to get the associated FieldTable value for.
- *
- * @return The associated FieldTable value, or <tt>null</tt> if the associated value is not of FieldTable type or
- * not present in the field table at all.
- */
- public FieldTable getFieldTable(String string)
- {
- return getFieldTable(new AMQShortString(string));
- }
-
- /**
- * Extracts a value from the field table that is itself a FieldTable associated with the specified parameter name.
- *
- * @param string The name of the parameter to get the associated FieldTable value for.
- *
- * @return The associated FieldTable value, or <tt>null</tt> if the associated value is not of FieldTable type or
- * not present in the field table at all.
- */
- public FieldTable getFieldTable(AMQShortString string)
- {
- AMQTypedValue value = getProperty(string);
-
- if ((value != null) && (value.getType() == AMQType.FIELD_TABLE))
- {
- return (FieldTable) value.getValue();
- }
- else
- {
- return null;
- }
- }
-
- public Object getObject(String string)
- {
- return getObject(new AMQShortString(string));
- }
-
- public Object getObject(AMQShortString string)
- {
- AMQTypedValue value = getProperty(string);
- if (value != null)
- {
- return value.getValue();
- }
- else
- {
- return value;
- }
-
- }
-
- public Long getTimestamp(AMQShortString name)
- {
- AMQTypedValue value = getProperty(name);
- if ((value != null) && (value.getType() == AMQType.TIMESTAMP))
- {
- return (Long) value.getValue();
- }
- else
- {
- return null;
- }
- }
-
- public BigDecimal getDecimal(AMQShortString propertyName)
- {
- AMQTypedValue value = getProperty(propertyName);
- if ((value != null) && (value.getType() == AMQType.DECIMAL))
- {
- return (BigDecimal) value.getValue();
- }
- else
- {
- return null;
- }
- }
-
- // ************ Setters
- public Object setBoolean(String string, Boolean b)
- {
- return setBoolean(new AMQShortString(string), b);
- }
-
- public Object setBoolean(AMQShortString string, Boolean b)
- {
- return setProperty(string, AMQType.BOOLEAN.asTypedValue(b));
- }
-
- public Object setByte(String string, Byte b)
- {
- return setByte(new AMQShortString(string), b);
- }
-
- public Object setByte(AMQShortString string, Byte b)
- {
- return setProperty(string, AMQType.BYTE.asTypedValue(b));
- }
-
- public Object setShort(String string, Short i)
- {
- return setShort(new AMQShortString(string), i);
- }
-
- public Object setShort(AMQShortString string, Short i)
- {
- return setProperty(string, AMQType.SHORT.asTypedValue(i));
- }
-
- public Object setInteger(String string, Integer i)
- {
- return setInteger(new AMQShortString(string), i);
- }
-
- public Object setInteger(AMQShortString string, Integer i)
- {
- return setProperty(string, AMQType.INT.asTypedValue(i));
- }
-
- public Object setLong(String string, Long l)
- {
- return setLong(new AMQShortString(string), l);
- }
-
- public Object setLong(AMQShortString string, Long l)
- {
- return setProperty(string, AMQType.LONG.asTypedValue(l));
- }
-
- public Object setFloat(String string, Float f)
- {
- return setFloat(new AMQShortString(string), f);
- }
-
- public Object setFloat(AMQShortString string, Float v)
- {
- return setProperty(string, AMQType.FLOAT.asTypedValue(v));
- }
-
- public Object setDouble(String string, Double d)
- {
- return setDouble(new AMQShortString(string), d);
- }
-
- public Object setDouble(AMQShortString string, Double v)
- {
- return setProperty(string, AMQType.DOUBLE.asTypedValue(v));
- }
-
- public Object setString(String string, String s)
- {
- return setString(new AMQShortString(string), s);
- }
-
- public Object setAsciiString(AMQShortString string, String value)
- {
- if (value == null)
- {
- return setProperty(string, AMQType.VOID.asTypedValue(null));
- }
- else
- {
- return setProperty(string, AMQType.ASCII_STRING.asTypedValue(value));
- }
- }
-
- public Object setString(AMQShortString string, String value)
- {
- if (value == null)
- {
- return setProperty(string, AMQType.VOID.asTypedValue(null));
- }
- else
- {
- return setProperty(string, AMQType.LONG_STRING.asTypedValue(value));
- }
- }
-
- public Object setChar(String string, char c)
- {
- return setChar(new AMQShortString(string), c);
- }
-
- public Object setChar(AMQShortString string, char c)
- {
- return setProperty(string, AMQType.ASCII_CHARACTER.asTypedValue(c));
- }
-
- public Object setBytes(String string, byte[] b)
- {
- return setBytes(new AMQShortString(string), b);
- }
-
- public Object setBytes(AMQShortString string, byte[] bytes)
- {
- return setProperty(string, AMQType.BINARY.asTypedValue(bytes));
- }
-
- public Object setBytes(String string, byte[] bytes, int start, int length)
- {
- return setBytes(new AMQShortString(string), bytes, start, length);
- }
-
- public Object setBytes(AMQShortString string, byte[] bytes, int start, int length)
- {
- byte[] newBytes = new byte[length];
- System.arraycopy(bytes, start, newBytes, 0, length);
-
- return setBytes(string, bytes);
- }
-
- public Object setObject(String string, Object o)
- {
- return setObject(new AMQShortString(string), o);
- }
-
- public Object setTimestamp(AMQShortString string, long datetime)
- {
- return setProperty(string, AMQType.TIMESTAMP.asTypedValue(datetime));
- }
-
- public Object setDecimal(AMQShortString string, BigDecimal decimal)
- {
- if (decimal.longValue() > Integer.MAX_VALUE)
- {
- throw new UnsupportedOperationException("AMQP doesnot support decimals larger than " + Integer.MAX_VALUE);
- }
-
- if (decimal.scale() > Byte.MAX_VALUE)
- {
- throw new UnsupportedOperationException("AMQP doesnot support decimal scales larger than " + Byte.MAX_VALUE);
- }
-
- return setProperty(string, AMQType.DECIMAL.asTypedValue(decimal));
- }
-
- public Object setVoid(AMQShortString string)
- {
- return setProperty(string, AMQType.VOID.asTypedValue(null));
- }
-
- /**
- * Associates a nested field table with the specified parameter name.
- *
- * @param string The name of the parameter to store in the table.
- * @param ftValue The field table value to associate with the parameter name.
- *
- * @return The stored value.
- */
- public Object setFieldTable(String string, FieldTable ftValue)
- {
- return setFieldTable(new AMQShortString(string), ftValue);
- }
-
- /**
- * Associates a nested field table with the specified parameter name.
- *
- * @param string The name of the parameter to store in the table.
- * @param ftValue The field table value to associate with the parameter name.
- *
- * @return The stored value.
- */
- public Object setFieldTable(AMQShortString string, FieldTable ftValue)
- {
- return setProperty(string, AMQType.FIELD_TABLE.asTypedValue(ftValue));
- }
-
- public Object setObject(AMQShortString string, Object object)
- {
- if (object instanceof Boolean)
- {
- return setBoolean(string, (Boolean) object);
- }
- else if (object instanceof Byte)
- {
- return setByte(string, (Byte) object);
- }
- else if (object instanceof Short)
- {
- return setShort(string, (Short) object);
- }
- else if (object instanceof Integer)
- {
- return setInteger(string, (Integer) object);
- }
- else if (object instanceof Long)
- {
- return setLong(string, (Long) object);
- }
- else if (object instanceof Float)
- {
- return setFloat(string, (Float) object);
- }
- else if (object instanceof Double)
- {
- return setDouble(string, (Double) object);
- }
- else if (object instanceof String)
- {
- return setString(string, (String) object);
- }
- else if (object instanceof Character)
- {
- return setChar(string, (Character) object);
- }
- else if (object instanceof byte[])
- {
- return setBytes(string, (byte[]) object);
- }
-
- throw new AMQPInvalidClassException(AMQPInvalidClassException.INVALID_OBJECT_MSG + (object == null ? "null" : object.getClass()));
- }
-
- public boolean isNullStringValue(String name)
- {
- AMQTypedValue value = getProperty(new AMQShortString(name));
-
- return (value != null) && (value.getType() == AMQType.VOID);
- }
-
- // ***** Methods
-
- public Enumeration getPropertyNames()
- {
- return Collections.enumeration(keys());
- }
-
- public boolean propertyExists(AMQShortString propertyName)
- {
- return itemExists(propertyName);
- }
-
- public boolean propertyExists(String propertyName)
- {
- return itemExists(propertyName);
- }
-
- public boolean itemExists(AMQShortString propertyName)
- {
- checkPropertyName(propertyName);
- initMapIfNecessary();
-
- return _properties.containsKey(propertyName);
- }
-
- public boolean itemExists(String string)
- {
- return itemExists(new AMQShortString(string));
- }
-
- public String toString()
- {
- initMapIfNecessary();
-
- return _properties.toString();
- }
-
- private void checkPropertyName(AMQShortString propertyName)
- {
- if (propertyName == null)
- {
- throw new IllegalArgumentException("Property name must not be null");
- }
- else if (propertyName.length() == 0)
- {
- throw new IllegalArgumentException("Property name must not be the empty string");
- }
-
- if (_strictAMQP)
- {
- checkIdentiferFormat(propertyName);
- }
- }
-
- protected static void checkIdentiferFormat(AMQShortString propertyName)
- {
- // AMQP Spec: 4.2.5.5 Field Tables
- // Guidelines for implementers:
- // * Field names MUST start with a letter, '$' or '#' and may continue with
- // letters, '$' or '#', digits, or underlines, to a maximum length of 128
- // characters.
- // * The server SHOULD validate field names and upon receiving an invalid
- // field name, it SHOULD signal a connection exception with reply code
- // 503 (syntax error). Conformance test: amq_wlp_table_01.
- // * A peer MUST handle duplicate fields by using only the first instance.
-
- // AMQP length limit
- if (propertyName.length() > 128)
- {
- throw new IllegalArgumentException("AMQP limits property names to 128 characters");
- }
-
- // AMQ start character
- if (!(Character.isLetter(propertyName.charAt(0)) || (propertyName.charAt(0) == '$')
- || (propertyName.charAt(0) == '#') || (propertyName.charAt(0) == '_'))) // Not official AMQP added for JMS.
- {
- throw new IllegalArgumentException("Identifier '" + propertyName
- + "' does not start with a valid AMQP start character");
- }
- }
-
- // ************************* Byte Buffer Processing
-
- public void writeToBuffer(ByteBuffer buffer)
- {
- final boolean trace = _logger.isDebugEnabled();
-
- if (trace)
- {
- _logger.debug("FieldTable::writeToBuffer: Writing encoded length of " + getEncodedSize() + "...");
- if (_properties != null)
- {
- _logger.debug(_properties.toString());
- }
- }
-
- EncodingUtils.writeUnsignedInteger(buffer, getEncodedSize());
-
- putDataInBuffer(buffer);
- }
-
- public byte[] getDataAsBytes()
- {
- final int encodedSize = (int) getEncodedSize();
- final ByteBuffer buffer = ByteBuffer.allocate(encodedSize); // FIXME XXX: Is cast a problem?
-
- putDataInBuffer(buffer);
-
- final byte[] result = new byte[encodedSize];
- buffer.flip();
- buffer.get(result);
- buffer.release();
-
- return result;
- }
-
- public long getEncodedSize()
- {
- return _encodedSize;
- }
-
- private void recalculateEncodedSize()
- {
-
- int encodedSize = 0;
- if (_properties != null)
- {
- for (Map.Entry<AMQShortString, AMQTypedValue> e : _properties.entrySet())
- {
- encodedSize += EncodingUtils.encodedShortStringLength(e.getKey());
- encodedSize++; // the byte for the encoding Type
- encodedSize += e.getValue().getEncodingSize();
-
- }
- }
-
- _encodedSize = encodedSize;
- }
-
- public void addAll(FieldTable fieldTable)
- {
- initMapIfNecessary();
- _encodedForm = null;
- _properties.putAll(fieldTable._properties);
- recalculateEncodedSize();
- }
-
- public static Map<String, Object> convertToMap(final FieldTable fieldTable)
- {
- final Map<String, Object> map = new HashMap<String, Object>();
-
- if(fieldTable != null)
- {
- fieldTable.processOverElements(
- new FieldTableElementProcessor()
- {
-
- public boolean processElement(String propertyName, AMQTypedValue value)
- {
- Object val = value.getValue();
- if(val instanceof AMQShortString)
- {
- val = val.toString();
- }
- map.put(propertyName, val);
- return true;
- }
-
- public Object getResult()
- {
- return map;
- }
- });
- }
- return map;
- }
-
-
- public static interface FieldTableElementProcessor
- {
- public boolean processElement(String propertyName, AMQTypedValue value);
-
- public Object getResult();
- }
-
- public Object processOverElements(FieldTableElementProcessor processor)
- {
- initMapIfNecessary();
- if (_properties != null)
- {
- for (Map.Entry<AMQShortString, AMQTypedValue> e : _properties.entrySet())
- {
- boolean result = processor.processElement(e.getKey().toString(), e.getValue());
- if (!result)
- {
- break;
- }
- }
- }
-
- return processor.getResult();
-
- }
-
- public int size()
- {
- initMapIfNecessary();
-
- return _properties.size();
-
- }
-
- public boolean isEmpty()
- {
- return size() == 0;
- }
-
- public boolean containsKey(AMQShortString key)
- {
- initMapIfNecessary();
-
- return _properties.containsKey(key);
- }
-
- public boolean containsKey(String key)
- {
- return containsKey(new AMQShortString(key));
- }
-
- public Set<String> keys()
- {
- initMapIfNecessary();
- Set<String> keys = new LinkedHashSet<String>();
- for (AMQShortString key : _properties.keySet())
- {
- keys.add(key.toString());
- }
-
- return keys;
- }
-
- public Iterator<Map.Entry<AMQShortString, AMQTypedValue>> iterator()
- {
- if(_encodedForm != null)
- {
- return new FieldTableIterator(_encodedForm.duplicate().rewind(),(int)_encodedSize);
- }
- else
- {
- initMapIfNecessary();
- return _properties.entrySet().iterator();
- }
- }
-
- public Object get(String key)
- {
- return get(new AMQShortString(key));
- }
-
- public Object get(AMQShortString key)
- {
- return getObject(key);
- }
-
- public Object put(AMQShortString key, Object value)
- {
- return setObject(key, value);
- }
-
- public Object remove(String key)
- {
-
- return remove(new AMQShortString(key));
-
- }
-
- public Object remove(AMQShortString key)
- {
- AMQTypedValue val = removeKey(key);
-
- return (val == null) ? null : val.getValue();
-
- }
-
- public AMQTypedValue removeKey(AMQShortString key)
- {
- initMapIfNecessary();
- _encodedForm = null;
- AMQTypedValue value = _properties.remove(key);
- if (value == null)
- {
- return null;
- }
- else
- {
- _encodedSize -= EncodingUtils.encodedShortStringLength(key);
- _encodedSize--;
- _encodedSize -= value.getEncodingSize();
-
- return value;
- }
-
- }
-
- public void clear()
- {
- initMapIfNecessary();
- _encodedForm = null;
- _properties.clear();
- _encodedSize = 0;
- }
-
- public Set<AMQShortString> keySet()
- {
- initMapIfNecessary();
-
- return _properties.keySet();
- }
-
- private void putDataInBuffer(ByteBuffer buffer)
- {
-
- if (_encodedForm != null)
- {
- if(buffer.isDirect() || buffer.isReadOnly())
- {
- ByteBuffer encodedForm = _encodedForm.duplicate();
-
- if (encodedForm.position() != 0)
- {
- encodedForm.flip();
- }
-
- buffer.put(encodedForm);
- }
- else
- {
- buffer.put(_encodedForm.array(),_encodedForm.arrayOffset(),(int)_encodedSize);
- }
- }
- else if (_properties != null)
- {
- final Iterator<Map.Entry<AMQShortString, AMQTypedValue>> it = _properties.entrySet().iterator();
-
- // If there are values then write out the encoded Size... could check _encodedSize != 0
- // write out the total length, which we have kept up to date as data is added
-
- while (it.hasNext())
- {
- final Map.Entry<AMQShortString, AMQTypedValue> me = it.next();
- try
- {
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Writing Property:" + me.getKey() + " Type:" + me.getValue().getType() + " Value:"
- + me.getValue().getValue());
- _logger.debug("Buffer Position:" + buffer.position() + " Remaining:" + buffer.remaining());
- }
-
- // Write the actual parameter name
- EncodingUtils.writeShortStringBytes(buffer, me.getKey());
- me.getValue().writeToBuffer(buffer);
- }
- catch (Exception e)
- {
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Exception thrown:" + e);
- _logger.debug("Writing Property:" + me.getKey() + " Type:" + me.getValue().getType() + " Value:"
- + me.getValue().getValue());
- _logger.debug("Buffer Position:" + buffer.position() + " Remaining:" + buffer.remaining());
- }
-
- throw new RuntimeException(e);
- }
- }
- }
- }
-
- private void setFromBuffer(ByteBuffer buffer, long length) throws AMQFrameDecodingException
- {
-
- final boolean trace = _logger.isDebugEnabled();
- if (length > 0)
- {
-
- final int expectedRemaining = buffer.remaining() - (int) length;
-
- _properties = new LinkedHashMap<AMQShortString, AMQTypedValue>(INITIAL_HASHMAP_CAPACITY);
-
- do
- {
-
- final AMQShortString key = EncodingUtils.readAMQShortString(buffer);
-
- _logger.debug("FieldTable::PropFieldTable(buffer," + length + "): Read key '" + key);
-
- AMQTypedValue value = AMQTypedValue.readFromBuffer(buffer);
-
- if (trace)
- {
- _logger.debug("FieldTable::PropFieldTable(buffer," + length + "): Read type '" + value.getType()
- + "', key '" + key + "', value '" + value.getValue() + "'");
- }
-
- _properties.put(key, value);
-
- }
- while (buffer.remaining() > expectedRemaining);
-
- }
-
- _encodedSize = length;
-
- if (trace)
- {
- _logger.debug("FieldTable::FieldTable(buffer," + length + "): Done.");
- }
- }
-
- private static final class FieldTableEntry implements Map.Entry<AMQShortString, AMQTypedValue>
- {
- private final AMQTypedValue _value;
- private final AMQShortString _key;
-
- public FieldTableEntry(final AMQShortString key, final AMQTypedValue value)
- {
- _key = key;
- _value = value;
- }
-
- public AMQShortString getKey()
- {
- return _key;
- }
-
- public AMQTypedValue getValue()
- {
- return _value;
- }
-
- public AMQTypedValue setValue(final AMQTypedValue value)
- {
- throw new UnsupportedOperationException();
- }
-
- public boolean equals(Object o)
- {
- if(o instanceof FieldTableEntry)
- {
- FieldTableEntry other = (FieldTableEntry) o;
- return (_key == null ? other._key == null : _key.equals(other._key))
- && (_value == null ? other._value == null : _value.equals(other._value));
- }
- else
- {
- return false;
- }
- }
-
- public int hashCode()
- {
- return (getKey()==null ? 0 : getKey().hashCode())
- ^ (getValue()==null ? 0 : getValue().hashCode());
- }
-
- }
-
-
- private static final class FieldTableIterator implements Iterator<Map.Entry<AMQShortString, AMQTypedValue>>
- {
-
- private final ByteBuffer _buffer;
- private int _expectedRemaining;
-
- public FieldTableIterator(ByteBuffer buffer, int length)
- {
- _buffer = buffer;
- _expectedRemaining = buffer.remaining() - length;
- }
-
- public boolean hasNext()
- {
- return (_buffer.remaining() > _expectedRemaining);
- }
-
- public Map.Entry<AMQShortString, AMQTypedValue> next()
- {
- if(hasNext())
- {
- final AMQShortString key = EncodingUtils.readAMQShortString(_buffer);
- AMQTypedValue value = AMQTypedValue.readFromBuffer(_buffer);
- return new FieldTableEntry(key, value);
- }
- else
- {
- return null;
- }
- }
-
- public void remove()
- {
- throw new UnsupportedOperationException();
- }
- }
-
-
-
-
- public int hashCode()
- {
- initMapIfNecessary();
-
- return _properties.hashCode();
- }
-
- public boolean equals(Object o)
- {
- if (o == this)
- {
- return true;
- }
-
- if (o == null)
- {
- return false;
- }
-
- if (!(o instanceof FieldTable))
- {
- return false;
- }
-
- initMapIfNecessary();
-
- FieldTable f = (FieldTable) o;
- f.initMapIfNecessary();
-
- return _properties.equals(f._properties);
- }
-
- public static FieldTable convertToFieldTable(Map<String, Object> map)
- {
- if (map != null)
- {
- FieldTable table = new FieldTable();
- for(Map.Entry<String,Object> entry : map.entrySet())
- {
- table.put(new AMQShortString(entry.getKey()), entry.getValue());
- }
-
- return table;
- }
- else
- {
- return null;
- }
- }
-
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/FieldTableFactory.java b/java/common/src/main/java/org/apache/qpid/framing/FieldTableFactory.java
deleted file mode 100644
index e9d75137ef..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/FieldTableFactory.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.framing;
-
-import org.apache.mina.common.ByteBuffer;
-
-public class FieldTableFactory
-{
- public static FieldTable newFieldTable()
- {
- return new FieldTable();
- }
-
- public static FieldTable newFieldTable(ByteBuffer byteBuffer, long length) throws AMQFrameDecodingException
- {
- return new FieldTable(byteBuffer, length);
- }
-
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/HeartbeatBody.java b/java/common/src/main/java/org/apache/qpid/framing/HeartbeatBody.java
deleted file mode 100644
index 18ab05ffa1..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/HeartbeatBody.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.framing;
-
-import org.apache.mina.common.ByteBuffer;
-import org.apache.qpid.protocol.AMQVersionAwareProtocolSession;
-import org.apache.qpid.AMQException;
-
-public class HeartbeatBody implements AMQBody
-{
- public static final byte TYPE = 8;
- public static final AMQFrame FRAME = new HeartbeatBody().toFrame();
-
- public HeartbeatBody()
- {
-
- }
-
- public HeartbeatBody(ByteBuffer buffer, long size)
- {
- if(size > 0)
- {
- //allow other implementations to have a payload, but ignore it:
- buffer.skip((int) size);
- }
- }
-
- public byte getFrameType()
- {
- return TYPE;
- }
-
- public int getSize()
- {
- return 0;//heartbeats we generate have no payload
- }
-
- public void writePayload(ByteBuffer buffer)
- {
- }
-
- public void handle(final int channelId, final AMQVersionAwareProtocolSession session)
- throws AMQException
- {
- session.heartbeatBodyReceived(channelId, this);
- }
-
- protected void populateFromBuffer(ByteBuffer buffer, long size) throws AMQFrameDecodingException
- {
- if(size > 0)
- {
- //allow other implementations to have a payload, but ignore it:
- buffer.skip((int) size);
- }
- }
-
- public AMQFrame toFrame()
- {
- return new AMQFrame(0, this);
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/HeartbeatBodyFactory.java b/java/common/src/main/java/org/apache/qpid/framing/HeartbeatBodyFactory.java
deleted file mode 100644
index c7ada708dc..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/HeartbeatBodyFactory.java
+++ /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.
- *
- */
-package org.apache.qpid.framing;
-
-import org.apache.mina.common.ByteBuffer;
-
-public class HeartbeatBodyFactory implements BodyFactory
-{
- public AMQBody createBody(ByteBuffer in, long bodySize) throws AMQFrameDecodingException
- {
- return new HeartbeatBody();
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/ProtocolInitiation.java b/java/common/src/main/java/org/apache/qpid/framing/ProtocolInitiation.java
deleted file mode 100644
index fb3dd89717..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/ProtocolInitiation.java
+++ /dev/null
@@ -1,223 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.framing;
-
-import org.apache.qpid.AMQException;
-
-import java.io.UnsupportedEncodingException;
-import java.nio.ByteBuffer;
-import java.util.Arrays;
-
-public class ProtocolInitiation extends AMQDataBlock implements EncodableAMQDataBlock
-{
-
- // TODO: generate these constants automatically from the xml protocol spec file
- private static final byte[] AMQP_HEADER = new byte[]{(byte)'A',(byte)'M',(byte)'Q',(byte)'P'};
-
- private static final byte CURRENT_PROTOCOL_CLASS = 1;
- private static final byte TCP_PROTOCOL_INSTANCE = 1;
-
- public final byte[] _protocolHeader;
- public final byte _protocolClass;
- public final byte _protocolInstance;
- public final byte _protocolMajor;
- public final byte _protocolMinor;
-
-
-// public ProtocolInitiation() {}
-
- public ProtocolInitiation(byte[] protocolHeader, byte protocolClass, byte protocolInstance, byte protocolMajor, byte protocolMinor)
- {
- _protocolHeader = protocolHeader;
- _protocolClass = protocolClass;
- _protocolInstance = protocolInstance;
- _protocolMajor = protocolMajor;
- _protocolMinor = protocolMinor;
- }
-
- public ProtocolInitiation(ProtocolVersion pv)
- {
- this(AMQP_HEADER,
- pv.equals(ProtocolVersion.v0_91) ? 0 : CURRENT_PROTOCOL_CLASS,
- pv.equals(ProtocolVersion.v0_91) ? 0 : TCP_PROTOCOL_INSTANCE,
- pv.equals(ProtocolVersion.v0_91) ? 9 : pv.getMajorVersion(),
- pv.equals(ProtocolVersion.v0_91) ? 1 : pv.getMinorVersion());
- }
-
- public ProtocolInitiation(ByteBuffer in)
- {
- _protocolHeader = new byte[4];
- in.get(_protocolHeader);
-
- _protocolClass = in.get();
- _protocolInstance = in.get();
- _protocolMajor = in.get();
- _protocolMinor = in.get();
- }
-
- public void writePayload(org.apache.mina.common.ByteBuffer buffer)
- {
- writePayload(buffer.buf());
- }
-
- public long getSize()
- {
- return 4 + 1 + 1 + 1 + 1;
- }
-
- public void writePayload(ByteBuffer buffer)
- {
-
- buffer.put(_protocolHeader);
- buffer.put(_protocolClass);
- buffer.put(_protocolInstance);
- buffer.put(_protocolMajor);
- buffer.put(_protocolMinor);
- }
-
- public boolean equals(Object o)
- {
- if (!(o instanceof ProtocolInitiation))
- {
- return false;
- }
-
- ProtocolInitiation pi = (ProtocolInitiation) o;
- if (pi._protocolHeader == null)
- {
- return false;
- }
-
- if (_protocolHeader.length != pi._protocolHeader.length)
- {
- return false;
- }
-
- for (int i = 0; i < _protocolHeader.length; i++)
- {
- if (_protocolHeader[i] != pi._protocolHeader[i])
- {
- return false;
- }
- }
-
- return (_protocolClass == pi._protocolClass &&
- _protocolInstance == pi._protocolInstance &&
- _protocolMajor == pi._protocolMajor &&
- _protocolMinor == pi._protocolMinor);
- }
-
- @Override
- public int hashCode()
- {
- int result = _protocolHeader != null ? Arrays.hashCode(_protocolHeader) : 0;
- result = 31 * result + (int) _protocolClass;
- result = 31 * result + (int) _protocolInstance;
- result = 31 * result + (int) _protocolMajor;
- result = 31 * result + (int) _protocolMinor;
- return result;
- }
-
- public static class Decoder //implements MessageDecoder
- {
- /**
- *
- * @param in input buffer
- * @return true if we have enough data to decode the PI frame fully, false if more
- * data is required
- */
- public boolean decodable(ByteBuffer in)
- {
- return (in.remaining() >= 8);
- }
-
- }
-
- public ProtocolVersion checkVersion() throws AMQException
- {
-
- if(_protocolHeader.length != 4)
- {
- throw new AMQProtocolHeaderException("Protocol header should have exactly four octets", null);
- }
- for(int i = 0; i < 4; i++)
- {
- if(_protocolHeader[i] != AMQP_HEADER[i])
- {
- try
- {
- throw new AMQProtocolHeaderException("Protocol header is not correct: Got " + new String(_protocolHeader,"ISO-8859-1") + " should be: " + new String(AMQP_HEADER, "ISO-8859-1"), null);
- }
- catch (UnsupportedEncodingException e)
- {
-
- }
- }
- }
-
- ProtocolVersion pv;
-
- // Hack for 0-9-1 which changed how the header was defined
- if(_protocolInstance == 0 && _protocolMajor == 9 && _protocolMinor == 1)
- {
- pv = ProtocolVersion.v0_91;
- if (_protocolClass != 0)
- {
- throw new AMQProtocolClassException("Protocol class " + 0 + " was expected; received " +
- _protocolClass, null);
- }
- }
- else if (_protocolClass != CURRENT_PROTOCOL_CLASS)
- {
- throw new AMQProtocolClassException("Protocol class " + CURRENT_PROTOCOL_CLASS + " was expected; received " +
- _protocolClass, null);
- }
- else if (_protocolInstance != TCP_PROTOCOL_INSTANCE)
- {
- throw new AMQProtocolInstanceException("Protocol instance " + TCP_PROTOCOL_INSTANCE + " was expected; received " +
- _protocolInstance, null);
- }
- else
- {
- pv = new ProtocolVersion(_protocolMajor, _protocolMinor);
- }
-
-
- if (!pv.isSupported())
- {
- // TODO: add list of available versions in list to msg...
- throw new AMQProtocolVersionException("Protocol version " +
- _protocolMajor + "." + _protocolMinor + " not suppoerted by this version of the Qpid broker.", null);
- }
- return pv;
- }
-
- public String toString()
- {
- StringBuffer buffer = new StringBuffer(new String(_protocolHeader));
- buffer.append(Integer.toHexString(_protocolClass));
- buffer.append(Integer.toHexString(_protocolInstance));
- buffer.append(Integer.toHexString(_protocolMajor));
- buffer.append(Integer.toHexString(_protocolMinor));
- return buffer.toString();
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/SmallCompositeAMQDataBlock.java b/java/common/src/main/java/org/apache/qpid/framing/SmallCompositeAMQDataBlock.java
deleted file mode 100644
index bd763599b0..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/SmallCompositeAMQDataBlock.java
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.qpid.framing;
-
-import org.apache.mina.common.ByteBuffer;
-
-public class SmallCompositeAMQDataBlock extends AMQDataBlock implements EncodableAMQDataBlock
-{
- private AMQDataBlock _firstFrame;
-
- private AMQDataBlock _block;
-
- public SmallCompositeAMQDataBlock(AMQDataBlock block)
- {
- _block = block;
- }
-
- /**
- * The encoded block will be logically first before the AMQDataBlocks which are encoded
- * into the buffer afterwards.
- * @param encodedBlock already-encoded data
- * @param block a block to be encoded.
- */
- public SmallCompositeAMQDataBlock(AMQDataBlock encodedBlock, AMQDataBlock block)
- {
- this(block);
- _firstFrame = encodedBlock;
- }
-
- public AMQDataBlock getBlock()
- {
- return _block;
- }
-
- public AMQDataBlock getFirstFrame()
- {
- return _firstFrame;
- }
-
- public long getSize()
- {
- long frameSize = _block.getSize();
-
- if (_firstFrame != null)
- {
-
- frameSize += _firstFrame.getSize();
- }
- return frameSize;
- }
-
- public void writePayload(ByteBuffer buffer)
- {
- if (_firstFrame != null)
- {
- _firstFrame.writePayload(buffer);
- }
- _block.writePayload(buffer);
-
- }
-
- public String toString()
- {
- if (_block == null)
- {
- return "No blocks contained in composite frame";
- }
- else
- {
- StringBuilder buf = new StringBuilder(this.getClass().getName());
- buf.append("{encodedBlock=").append(_firstFrame);
-
- buf.append(" _block=[").append(_block.toString()).append("]");
-
- buf.append("}");
- return buf.toString();
- }
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/VersionSpecificRegistry.java b/java/common/src/main/java/org/apache/qpid/framing/VersionSpecificRegistry.java
deleted file mode 100644
index 76c154581d..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/VersionSpecificRegistry.java
+++ /dev/null
@@ -1,198 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.framing;
-
-import org.apache.mina.common.ByteBuffer;
-
-import org.apache.qpid.framing.abstraction.ProtocolVersionMethodConverter;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class VersionSpecificRegistry
-{
- private static final Logger _log = LoggerFactory.getLogger(VersionSpecificRegistry.class);
-
- private final byte _protocolMajorVersion;
- private final byte _protocolMinorVersion;
-
- private static final int DEFAULT_MAX_CLASS_ID = 200;
- private static final int DEFAULT_MAX_METHOD_ID = 50;
-
- private AMQMethodBodyInstanceFactory[][] _registry = new AMQMethodBodyInstanceFactory[DEFAULT_MAX_CLASS_ID][];
-
- private ProtocolVersionMethodConverter _protocolVersionConverter;
-
- public VersionSpecificRegistry(byte major, byte minor)
- {
- _protocolMajorVersion = major;
- _protocolMinorVersion = minor;
-
- _protocolVersionConverter = loadProtocolVersionConverters(major, minor);
- }
-
- private static ProtocolVersionMethodConverter loadProtocolVersionConverters(byte protocolMajorVersion,
- byte protocolMinorVersion)
- {
- try
- {
- Class<ProtocolVersionMethodConverter> versionMethodConverterClass =
- (Class<ProtocolVersionMethodConverter>) Class.forName("org.apache.qpid.framing.MethodConverter_"
- + protocolMajorVersion + "_" + protocolMinorVersion);
-
- return versionMethodConverterClass.newInstance();
-
- }
- catch (ClassNotFoundException e)
- {
- _log.warn("Could not find protocol conversion classes for " + protocolMajorVersion + "-" + protocolMinorVersion);
- if (protocolMinorVersion != 0)
- {
- protocolMinorVersion--;
-
- return loadProtocolVersionConverters(protocolMajorVersion, protocolMinorVersion);
- }
- else if (protocolMajorVersion != 0)
- {
- protocolMajorVersion--;
-
- return loadProtocolVersionConverters(protocolMajorVersion, protocolMinorVersion);
- }
- else
- {
- return null;
- }
-
- }
- catch (IllegalAccessException e)
- {
- throw new IllegalStateException("Unable to load protocol version converter: ", e);
- }
- catch (InstantiationException e)
- {
- throw new IllegalStateException("Unable to load protocol version converter: ", e);
- }
- }
-
- public byte getProtocolMajorVersion()
- {
- return _protocolMajorVersion;
- }
-
- public byte getProtocolMinorVersion()
- {
- return _protocolMinorVersion;
- }
-
- public AMQMethodBodyInstanceFactory getMethodBody(final short classID, final short methodID)
- {
- try
- {
- return _registry[classID][methodID];
- }
- catch (IndexOutOfBoundsException e)
- {
- return null;
- }
- catch (NullPointerException e)
- {
- return null;
- }
- }
-
- public void registerMethod(final short classID, final short methodID, final AMQMethodBodyInstanceFactory instanceFactory)
- {
- if (_registry.length <= classID)
- {
- AMQMethodBodyInstanceFactory[][] oldRegistry = _registry;
- _registry = new AMQMethodBodyInstanceFactory[classID + 1][];
- System.arraycopy(oldRegistry, 0, _registry, 0, oldRegistry.length);
- }
-
- if (_registry[classID] == null)
- {
- _registry[classID] =
- new AMQMethodBodyInstanceFactory[(methodID > DEFAULT_MAX_METHOD_ID) ? (methodID + 1)
- : (DEFAULT_MAX_METHOD_ID + 1)];
- }
- else if (_registry[classID].length <= methodID)
- {
- AMQMethodBodyInstanceFactory[] oldMethods = _registry[classID];
- _registry[classID] = new AMQMethodBodyInstanceFactory[methodID + 1];
- System.arraycopy(oldMethods, 0, _registry[classID], 0, oldMethods.length);
- }
-
- _registry[classID][methodID] = instanceFactory;
-
- }
-
- public AMQMethodBody get(short classID, short methodID, ByteBuffer in, long size) throws AMQFrameDecodingException
- {
- AMQMethodBodyInstanceFactory bodyFactory;
- try
- {
- bodyFactory = _registry[classID][methodID];
- }
- catch (NullPointerException e)
- {
- throw new AMQFrameDecodingException(null, "Class " + classID + " unknown in AMQP version "
- + _protocolMajorVersion + "-" + _protocolMinorVersion + " (while trying to decode class " + classID
- + " method " + methodID + ".", e);
- }
- catch (IndexOutOfBoundsException e)
- {
- if (classID >= _registry.length)
- {
- throw new AMQFrameDecodingException(null, "Class " + classID + " unknown in AMQP version "
- + _protocolMajorVersion + "-" + _protocolMinorVersion + " (while trying to decode class " + classID
- + " method " + methodID + ".", e);
-
- }
- else
- {
- throw new AMQFrameDecodingException(null, "Method " + methodID + " unknown in AMQP version "
- + _protocolMajorVersion + "-" + _protocolMinorVersion + " (while trying to decode class " + classID
- + " method " + methodID + ".", e);
-
- }
- }
-
- if (bodyFactory == null)
- {
- throw new AMQFrameDecodingException(null, "Method " + methodID + " unknown in AMQP version "
- + _protocolMajorVersion + "-" + _protocolMinorVersion + " (while trying to decode class " + classID
- + " method " + methodID + ".", null);
- }
-
- return bodyFactory.newInstance( in, size);
-
- }
-
- public ProtocolVersionMethodConverter getProtocolVersionMethodConverter()
- {
- return _protocolVersionConverter;
- }
-
- public void configure()
- {
- _protocolVersionConverter.configure();
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/abstraction/AbstractMethodConverter.java b/java/common/src/main/java/org/apache/qpid/framing/abstraction/AbstractMethodConverter.java
deleted file mode 100644
index 1d7c05e9cc..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/abstraction/AbstractMethodConverter.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.qpid.framing.abstraction;
-
-public abstract class AbstractMethodConverter implements ProtocolVersionMethodConverter
-{
- private final byte _protocolMajorVersion;
-
-
- private final byte _protocolMinorVersion;
-
- public AbstractMethodConverter(byte major, byte minor)
- {
- _protocolMajorVersion = major;
- _protocolMinorVersion = minor;
- }
-
-
- public final byte getProtocolMajorVersion()
- {
- return _protocolMajorVersion;
- }
-
- public final byte getProtocolMinorVersion()
- {
- return _protocolMinorVersion;
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/abstraction/ContentChunk.java b/java/common/src/main/java/org/apache/qpid/framing/abstraction/ContentChunk.java
deleted file mode 100644
index 0695349f76..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/abstraction/ContentChunk.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.qpid.framing.abstraction;
-
-import org.apache.mina.common.ByteBuffer;
-
-public interface ContentChunk
-{
- int getSize();
- ByteBuffer getData();
-
- void reduceToFit();
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/abstraction/MessagePublishInfo.java b/java/common/src/main/java/org/apache/qpid/framing/abstraction/MessagePublishInfo.java
deleted file mode 100644
index a96bdcc171..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/abstraction/MessagePublishInfo.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.framing.abstraction;
-
-import org.apache.qpid.framing.AMQShortString;
-
-public interface MessagePublishInfo
-{
-
- public AMQShortString getExchange();
-
- public void setExchange(AMQShortString exchange);
-
- public boolean isImmediate();
-
- public boolean isMandatory();
-
- public AMQShortString getRoutingKey();
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/abstraction/MessagePublishInfoConverter.java b/java/common/src/main/java/org/apache/qpid/framing/abstraction/MessagePublishInfoConverter.java
deleted file mode 100644
index 01d1a8a17b..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/abstraction/MessagePublishInfoConverter.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.qpid.framing.abstraction;
-
-import org.apache.qpid.framing.AMQMethodBody;
-
-
-public interface MessagePublishInfoConverter
-{
- public MessagePublishInfo convertToInfo(AMQMethodBody body);
- public AMQMethodBody convertToBody(MessagePublishInfo info);
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/abstraction/MessagePublishInfoImpl.java b/java/common/src/main/java/org/apache/qpid/framing/abstraction/MessagePublishInfoImpl.java
deleted file mode 100644
index e3d5da73da..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/abstraction/MessagePublishInfoImpl.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.framing.abstraction;
-
-import org.apache.qpid.framing.abstraction.MessagePublishInfo;
-import org.apache.qpid.framing.AMQShortString;
-
-public class MessagePublishInfoImpl implements MessagePublishInfo
-{
- private AMQShortString _exchange;
- private boolean _immediate;
- private boolean _mandatory;
- private AMQShortString _routingKey;
-
- public MessagePublishInfoImpl()
- {
- }
-
- public MessagePublishInfoImpl(AMQShortString exchange, boolean immediate, boolean mandatory,
- AMQShortString routingKey)
- {
- _exchange = exchange;
- _immediate = immediate;
- _mandatory = mandatory;
- _routingKey = routingKey;
- }
-
- public AMQShortString getExchange()
- {
- return _exchange;
- }
-
- public void setExchange(AMQShortString exchange)
- {
- _exchange = exchange;
- }
-
- public boolean isImmediate()
- {
- return _immediate;
- }
-
- public void setImmediate(boolean immedate)
- {
- _immediate = immedate;
- }
-
- public boolean isMandatory()
- {
- return _mandatory;
- }
-
- public void setMandatory(boolean mandatory)
- {
- _mandatory = mandatory;
- }
-
- public AMQShortString getRoutingKey()
- {
- return _routingKey;
- }
-
- public void setRoutingKey(AMQShortString routingKey)
- {
- _routingKey = routingKey;
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/abstraction/ProtocolVersionMethodConverter.java b/java/common/src/main/java/org/apache/qpid/framing/abstraction/ProtocolVersionMethodConverter.java
deleted file mode 100644
index 7544d9b7e7..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/abstraction/ProtocolVersionMethodConverter.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.framing.abstraction;
-
-import org.apache.qpid.framing.AMQBody;
-
-import java.nio.ByteBuffer;
-
-public interface ProtocolVersionMethodConverter extends MessagePublishInfoConverter
-{
- AMQBody convertToBody(ContentChunk contentBody);
- ContentChunk convertToContentChunk(AMQBody body);
-
- void configure();
-
- AMQBody convertToBody(ByteBuffer buf);
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/amqp_0_9/AMQMethodBody_0_9.java b/java/common/src/main/java/org/apache/qpid/framing/amqp_0_9/AMQMethodBody_0_9.java
deleted file mode 100644
index 8d51343507..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/amqp_0_9/AMQMethodBody_0_9.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.qpid.framing.amqp_0_9;
-
-public abstract class AMQMethodBody_0_9 extends org.apache.qpid.framing.AMQMethodBodyImpl
-{
-
- public byte getMajor()
- {
- return 0;
- }
-
- public byte getMinor()
- {
- return 9;
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/amqp_0_9/MethodConverter_0_9.java b/java/common/src/main/java/org/apache/qpid/framing/amqp_0_9/MethodConverter_0_9.java
deleted file mode 100644
index 1c4a29b106..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/amqp_0_9/MethodConverter_0_9.java
+++ /dev/null
@@ -1,134 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.qpid.framing.amqp_0_9;
-
-import org.apache.mina.common.ByteBuffer;
-
-import org.apache.qpid.framing.abstraction.AbstractMethodConverter;
-import org.apache.qpid.framing.abstraction.ProtocolVersionMethodConverter;
-import org.apache.qpid.framing.abstraction.ContentChunk;
-import org.apache.qpid.framing.abstraction.MessagePublishInfo;
-import org.apache.qpid.framing.abstraction.MessagePublishInfoImpl;
-import org.apache.qpid.framing.*;
-import org.apache.qpid.framing.amqp_0_9.*;
-import org.apache.qpid.framing.amqp_0_9.BasicPublishBodyImpl;
-
-public class MethodConverter_0_9 extends AbstractMethodConverter implements ProtocolVersionMethodConverter
-{
- private int _basicPublishClassId;
- private int _basicPublishMethodId;
-
- public MethodConverter_0_9()
- {
- super((byte)0,(byte)9);
-
-
- }
-
- public AMQBody convertToBody(ContentChunk contentChunk)
- {
- if(contentChunk instanceof ContentChunk_0_9)
- {
- return ((ContentChunk_0_9)contentChunk).toBody();
- }
- else
- {
- return new ContentBody(contentChunk.getData());
- }
- }
-
- public ContentChunk convertToContentChunk(AMQBody body)
- {
- final ContentBody contentBodyChunk = (ContentBody) body;
-
- return new ContentChunk_0_9(contentBodyChunk);
-
- }
-
- public void configure()
- {
-
- _basicPublishClassId = org.apache.qpid.framing.amqp_0_9.BasicPublishBodyImpl.CLASS_ID;
- _basicPublishMethodId = BasicPublishBodyImpl.METHOD_ID;
-
- }
-
- public AMQBody convertToBody(java.nio.ByteBuffer buf)
- {
- return new ContentBody(ByteBuffer.wrap(buf));
- }
-
- public MessagePublishInfo convertToInfo(AMQMethodBody methodBody)
- {
- final BasicPublishBody publishBody = ((BasicPublishBody) methodBody);
-
- final AMQShortString exchange = publishBody.getExchange();
- final AMQShortString routingKey = publishBody.getRoutingKey();
-
- return new MessagePublishInfoImpl(exchange,
- publishBody.getImmediate(),
- publishBody.getMandatory(),
- routingKey);
-
- }
-
- public AMQMethodBody convertToBody(MessagePublishInfo info)
- {
-
- return new BasicPublishBodyImpl(0,
- info.getExchange(),
- info.getRoutingKey(),
- info.isMandatory(),
- info.isImmediate()) ;
-
- }
-
- private static class ContentChunk_0_9 implements ContentChunk
- {
- private final ContentBody _contentBodyChunk;
-
- public ContentChunk_0_9(final ContentBody contentBodyChunk)
- {
- _contentBodyChunk = contentBodyChunk;
- }
-
- public int getSize()
- {
- return _contentBodyChunk.getSize();
- }
-
- public ByteBuffer getData()
- {
- return _contentBodyChunk.payload;
- }
-
- public void reduceToFit()
- {
- _contentBodyChunk.reduceBufferToFit();
- }
-
- public AMQBody toBody()
- {
- return _contentBodyChunk;
- }
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/amqp_0_91/AMQMethodBody_0_91.java b/java/common/src/main/java/org/apache/qpid/framing/amqp_0_91/AMQMethodBody_0_91.java
deleted file mode 100644
index 60b8a7e1a6..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/amqp_0_91/AMQMethodBody_0_91.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.qpid.framing.amqp_0_91;
-
-public abstract class AMQMethodBody_0_91 extends org.apache.qpid.framing.AMQMethodBodyImpl
-{
-
- public byte getMajor()
- {
- return 0;
- }
-
- public byte getMinor()
- {
- return 91;
- }
-
-} \ No newline at end of file
diff --git a/java/common/src/main/java/org/apache/qpid/framing/amqp_0_91/MethodConverter_0_91.java b/java/common/src/main/java/org/apache/qpid/framing/amqp_0_91/MethodConverter_0_91.java
deleted file mode 100644
index 6e330574bc..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/amqp_0_91/MethodConverter_0_91.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.framing.amqp_0_91;
-
-import org.apache.mina.common.ByteBuffer;
-
-import org.apache.qpid.framing.abstraction.AbstractMethodConverter;
-import org.apache.qpid.framing.abstraction.ProtocolVersionMethodConverter;
-import org.apache.qpid.framing.abstraction.ContentChunk;
-import org.apache.qpid.framing.abstraction.MessagePublishInfo;
-import org.apache.qpid.framing.abstraction.MessagePublishInfoImpl;
-import org.apache.qpid.framing.*;
-
-public class MethodConverter_0_91 extends AbstractMethodConverter implements ProtocolVersionMethodConverter
-{
- private int _basicPublishClassId;
- private int _basicPublishMethodId;
-
- public MethodConverter_0_91()
- {
- super((byte)0,(byte)9);
-
-
- }
-
- public AMQBody convertToBody(ContentChunk contentChunk)
- {
- if(contentChunk instanceof ContentChunk_0_9)
- {
- return ((ContentChunk_0_9)contentChunk).toBody();
- }
- else
- {
- return new ContentBody(contentChunk.getData());
- }
- }
-
- public ContentChunk convertToContentChunk(AMQBody body)
- {
- final ContentBody contentBodyChunk = (ContentBody) body;
-
- return new ContentChunk_0_9(contentBodyChunk);
-
- }
-
- public void configure()
- {
-
- _basicPublishClassId = BasicPublishBodyImpl.CLASS_ID;
- _basicPublishMethodId = BasicPublishBodyImpl.METHOD_ID;
-
- }
-
- public AMQBody convertToBody(java.nio.ByteBuffer buf)
- {
- return new ContentBody(ByteBuffer.wrap(buf));
- }
-
- public MessagePublishInfo convertToInfo(AMQMethodBody methodBody)
- {
- final BasicPublishBody publishBody = ((BasicPublishBody) methodBody);
-
- final AMQShortString exchange = publishBody.getExchange();
- final AMQShortString routingKey = publishBody.getRoutingKey();
-
- return new MessagePublishInfoImpl(exchange,
- publishBody.getImmediate(),
- publishBody.getMandatory(),
- routingKey);
-
- }
-
- public AMQMethodBody convertToBody(MessagePublishInfo info)
- {
-
- return new BasicPublishBodyImpl(0,
- info.getExchange(),
- info.getRoutingKey(),
- info.isMandatory(),
- info.isImmediate()) ;
-
- }
-
- private static class ContentChunk_0_9 implements ContentChunk
- {
- private final ContentBody _contentBodyChunk;
-
- public ContentChunk_0_9(final ContentBody contentBodyChunk)
- {
- _contentBodyChunk = contentBodyChunk;
- }
-
- public int getSize()
- {
- return _contentBodyChunk.getSize();
- }
-
- public ByteBuffer getData()
- {
- return _contentBodyChunk.payload;
- }
-
- public void reduceToFit()
- {
- _contentBodyChunk.reduceBufferToFit();
- }
-
- public AMQBody toBody()
- {
- return _contentBodyChunk;
- }
- }
-} \ No newline at end of file
diff --git a/java/common/src/main/java/org/apache/qpid/framing/amqp_8_0/AMQMethodBody_8_0.java b/java/common/src/main/java/org/apache/qpid/framing/amqp_8_0/AMQMethodBody_8_0.java
deleted file mode 100644
index 35645854c0..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/amqp_8_0/AMQMethodBody_8_0.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.framing.amqp_8_0;
-
-public abstract class AMQMethodBody_8_0 extends org.apache.qpid.framing.AMQMethodBodyImpl
-{
-
- public byte getMajor()
- {
- return 8;
- }
-
- public byte getMinor()
- {
- return 0;
- }
-
-
-
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/amqp_8_0/MethodConverter_8_0.java b/java/common/src/main/java/org/apache/qpid/framing/amqp_8_0/MethodConverter_8_0.java
deleted file mode 100644
index c87820b9b2..0000000000
--- a/java/common/src/main/java/org/apache/qpid/framing/amqp_8_0/MethodConverter_8_0.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.qpid.framing.amqp_8_0;
-
-import org.apache.qpid.framing.abstraction.ProtocolVersionMethodConverter;
-import org.apache.qpid.framing.abstraction.ContentChunk;
-import org.apache.qpid.framing.abstraction.MessagePublishInfo;
-import org.apache.qpid.framing.abstraction.AbstractMethodConverter;
-import org.apache.qpid.framing.abstraction.MessagePublishInfoImpl;
-import org.apache.qpid.framing.amqp_8_0.BasicPublishBodyImpl;
-import org.apache.qpid.framing.*;
-
-import org.apache.mina.common.ByteBuffer;
-
-public class MethodConverter_8_0 extends AbstractMethodConverter implements ProtocolVersionMethodConverter
-{
- private int _basicPublishClassId;
- private int _basicPublishMethodId;
-
- public MethodConverter_8_0()
- {
- super((byte)8,(byte)0);
-
-
- }
-
- public AMQBody convertToBody(ContentChunk contentChunk)
- {
- return new ContentBody(contentChunk.getData());
- }
-
- public ContentChunk convertToContentChunk(AMQBody body)
- {
- final ContentBody contentBodyChunk = (ContentBody) body;
-
- return new ContentChunk()
- {
-
- public int getSize()
- {
- return contentBodyChunk.getSize();
- }
-
- public ByteBuffer getData()
- {
- return contentBodyChunk.payload;
- }
-
- public void reduceToFit()
- {
- contentBodyChunk.reduceBufferToFit();
- }
- };
-
- }
-
- public void configure()
- {
-
- _basicPublishClassId = BasicPublishBodyImpl.CLASS_ID;
- _basicPublishMethodId = BasicPublishBodyImpl.METHOD_ID;
-
- }
-
- public AMQBody convertToBody(java.nio.ByteBuffer buf)
- {
- return new ContentBody(ByteBuffer.wrap(buf));
- }
-
- public MessagePublishInfo convertToInfo(AMQMethodBody methodBody)
- {
- final BasicPublishBody publishBody = ((BasicPublishBody) methodBody);
-
- final AMQShortString exchange = publishBody.getExchange();
- final AMQShortString routingKey = publishBody.getRoutingKey();
-
- return new MessagePublishInfoImpl(exchange == null ? null : exchange.intern(),
- publishBody.getImmediate(),
- publishBody.getMandatory(),
- routingKey == null ? null : routingKey.intern());
-
- }
-
- public AMQMethodBody convertToBody(MessagePublishInfo info)
- {
-
- return new BasicPublishBodyImpl(0,
- info.getExchange(),
- info.getRoutingKey(),
- info.isMandatory(),
- info.isImmediate()) ;
-
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/messaging/Address.java b/java/common/src/main/java/org/apache/qpid/messaging/Address.java
deleted file mode 100644
index 2c7fe7b8ed..0000000000
--- a/java/common/src/main/java/org/apache/qpid/messaging/Address.java
+++ /dev/null
@@ -1,75 +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.messaging;
-
-import java.util.Map;
-
-import org.apache.qpid.messaging.util.AddressParser;
-
-import static org.apache.qpid.messaging.util.PyPrint.pprint;
-
-
-/**
- * Address
- *
- */
-
-public class Address
-{
-
- public static Address parse(String address)
- {
- return new AddressParser(address).parse();
- }
-
- private String name;
- private String subject;
- private Map options;
-
- public Address(String name, String subject, Map options)
- {
- this.name = name;
- this.subject = subject;
- this.options = options;
- }
-
- public String getName()
- {
- return name;
- }
-
- public String getSubject()
- {
- return subject;
- }
-
- public Map getOptions()
- {
- return options;
- }
-
- public String toString()
- {
- return String.format("%s/%s; %s", pprint(name), pprint(subject),
- pprint(options));
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/messaging/util/AddressParser.java b/java/common/src/main/java/org/apache/qpid/messaging/util/AddressParser.java
deleted file mode 100644
index 7b31436ba0..0000000000
--- a/java/common/src/main/java/org/apache/qpid/messaging/util/AddressParser.java
+++ /dev/null
@@ -1,380 +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.messaging.util;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.qpid.messaging.Address;
-
-
-/**
- * AddressParser
- *
- */
-
-public class AddressParser extends Parser
-{
-
- private static Lexicon lxi = new Lexicon();
-
- private static Token.Type LBRACE = lxi.define("LBRACE", "\\{");
- private static Token.Type RBRACE = lxi.define("RBRACE", "\\}");
- private static Token.Type LBRACK = lxi.define("LBRACK", "\\[");
- private static Token.Type RBRACK = lxi.define("RBRACK", "\\]");
- private static Token.Type COLON = lxi.define("COLON", ":");
- private static Token.Type SEMI = lxi.define("SEMI", ";");
- private static Token.Type SLASH = lxi.define("SLASH", "/");
- private static Token.Type COMMA = lxi.define("COMMA", ",");
- private static Token.Type NUMBER = lxi.define("NUMBER", "[+-]?[0-9]*\\.?[0-9]+");
- private static Token.Type TRUE = lxi.define("TRUE", "True");
- private static Token.Type FALSE = lxi.define("FALSE", "False");
- private static Token.Type ID = lxi.define("ID", "[a-zA-Z_](?:[a-zA-Z0-9_-]*[a-zA-Z0-9_])?");
- private static Token.Type STRING = lxi.define("STRING", "\"(?:[^\\\"]|\\.)*\"|'(?:[^\\']|\\.)*'");
- private static Token.Type ESC = lxi.define("ESC", "\\\\[^ux]|\\\\x[0-9a-fA-F][0-9a-fA-F]|\\\\u[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]");
- private static Token.Type SYM = lxi.define("SYM", "[.#*%@$^!+-]");
- private static Token.Type WSPACE = lxi.define("WSPACE", "[\\s]+");
- private static Token.Type EOF = lxi.eof("EOF");
-
- private static Lexer LEXER = lxi.compile();
-
- public static List<Token> lex(String input)
- {
- return LEXER.lex(input);
- }
-
- static List<Token> wlex(String input)
- {
- List<Token> tokens = new ArrayList<Token>();
- for (Token t : lex(input))
- {
- if (t.getType() != WSPACE)
- {
- tokens.add(t);
- }
- }
- return tokens;
- }
-
- static String unquote(String st, Token tok)
- {
- StringBuilder result = new StringBuilder();
- for (int i = 1; i < st.length() - 1; i++)
- {
- char ch = st.charAt(i);
- if (ch == '\\')
- {
- char code = st.charAt(i+1);
- switch (code)
- {
- case '\n':
- break;
- case '\\':
- result.append('\\');
- break;
- case '\'':
- result.append('\'');
- break;
- case '"':
- result.append('"');
- break;
- case 'a':
- result.append((char) 0x07);
- break;
- case 'b':
- result.append((char) 0x08);
- break;
- case 'f':
- result.append('\f');
- break;
- case 'n':
- result.append('\n');
- break;
- case 'r':
- result.append('\r');
- break;
- case 't':
- result.append('\t');
- break;
- case 'u':
- result.append(decode(st.substring(i+2, i+6)));
- i += 4;
- break;
- case 'v':
- result.append((char) 0x0b);
- break;
- case 'o':
- result.append(decode(st.substring(i+2, i+4), 8));
- i += 2;
- break;
- case 'x':
- result.append(decode(st.substring(i+2, i+4)));
- i += 2;
- break;
- default:
- throw new ParseError(tok);
- }
- i += 1;
- }
- else
- {
- result.append(ch);
- }
- }
-
- return result.toString();
- }
-
- static char[] decode(String hex)
- {
- return decode(hex, 16);
- }
-
- static char[] decode(String code, int radix)
- {
- return Character.toChars(Integer.parseInt(code, radix));
- }
-
- static String tok2str(Token tok)
- {
- Token.Type type = tok.getType();
- String value = tok.getValue();
-
- if (type == STRING)
- {
- return unquote(value, tok);
- }
- else if (type == ESC)
- {
- if (value.charAt(1) == 'x' || value.charAt(1) == 'u')
- {
- return new String(decode(value.substring(2)));
- }
- else
- {
- return value.substring(1);
- }
- }
- else
- {
- return value;
- }
- }
-
- static Object tok2obj(Token tok)
- {
- Token.Type type = tok.getType();
- String value = tok.getValue();
- if (type == STRING)
- {
- return unquote(value, tok);
- }
- else if (type == NUMBER)
- {
- if (value.indexOf('.') >= 0)
- {
- return Double.valueOf(value);
- }
- else
- {
- return Integer.decode(value);
- }
- }
- else if (type == TRUE)
- {
- return true;
- }
- else if (type == FALSE)
- {
- return false;
- }
- else
- {
- return value;
- }
- }
-
- static String toks2str(List<Token> toks)
- {
- if (toks.size() > 0)
- {
- StringBuilder result = new StringBuilder();
- for (Token t : toks)
- {
- result.append(tok2str(t));
- }
- return result.toString();
- }
- else
- {
- return null;
- }
- }
-
- public AddressParser(String input)
- {
- super(wlex(input));
- }
-
- public Address parse()
- {
- Address result = address();
- eat(EOF);
- return result;
- }
-
- public Address address()
- {
- String name = toks2str(eat_until(SLASH, SEMI, EOF));
-
- if (name == null)
- {
- throw new ParseError(next());
- }
-
- String subject;
- if (matches(SLASH))
- {
- eat(SLASH);
- subject = toks2str(eat_until(SEMI, EOF));
- }
- else
- {
- subject = null;
- }
-
- Map options;
- if (matches(SEMI))
- {
- eat(SEMI);
- options = map();
- }
- else
- {
- options = null;
- }
-
- return new Address(name, subject, options);
- }
-
- public Map<Object,Object> map()
- {
- eat(LBRACE);
-
- Map<Object,Object> result = new HashMap<Object,Object>();
- while (true)
- {
- if (matches(NUMBER, STRING, ID, LBRACE, LBRACK))
- {
- keyval(result);
- if (matches(COMMA))
- {
- eat(COMMA);
- }
- else if (matches(RBRACE))
- {
- break;
- }
- else
- {
- throw new ParseError(next(), COMMA, RBRACE);
- }
- }
- else if (matches(RBRACE))
- {
- break;
- }
- else
- {
- throw new ParseError(next(), NUMBER, STRING, ID, LBRACE, LBRACK,
- RBRACE);
- }
- }
-
- eat(RBRACE);
- return result;
- }
-
- void keyval(Map<Object,Object> map)
- {
- Object key = value();
- eat(COLON);
- Object val = value();
- map.put(key, val);
- }
-
- Object value()
- {
- if (matches(NUMBER, STRING, ID, TRUE, FALSE))
- {
- return tok2obj(eat());
- }
- else if (matches(LBRACE))
- {
- return map();
- }
- else if (matches(LBRACK))
- {
- return list();
- }
- else
- {
- throw new ParseError(next(), NUMBER, STRING, ID, LBRACE, LBRACK);
- }
- }
-
- List<Object> list()
- {
- eat(LBRACK);
-
- List<Object> result = new ArrayList<Object>();
-
- while (true)
- {
- if (matches(RBRACK))
- {
- break;
- }
- else
- {
- result.add(value());
- if (matches(COMMA))
- {
- eat(COMMA);
- }
- else if (matches(RBRACK))
- {
- break;
- }
- else
- {
- throw new ParseError(next(), COMMA, RBRACK);
- }
- }
- }
-
- eat(RBRACK);
- return result;
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/messaging/util/JAddr.java b/java/common/src/main/java/org/apache/qpid/messaging/util/JAddr.java
deleted file mode 100644
index 93df052af1..0000000000
--- a/java/common/src/main/java/org/apache/qpid/messaging/util/JAddr.java
+++ /dev/null
@@ -1,97 +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.messaging.util;
-
-import java.io.InputStreamReader;
-
-import java.util.List;
-
-import org.apache.qpid.messaging.Address;
-import org.apache.qpid.messaging.util.ParseError;
-import org.apache.qpid.messaging.util.Token;
-
-import static org.apache.qpid.messaging.util.PyPrint.pprint;
-
-
-/**
- * JAddr
- *
- */
-
-public class JAddr
-{
-
- public static final void main(String[] args) throws Exception
- {
- StringBuilder addr = new StringBuilder();
- InputStreamReader reader = new InputStreamReader(System.in);
-
- char[] buf = new char[1024];
- while (true)
- {
- int n = reader.read(buf, 0, buf.length);
- if (n < 0)
- {
- break;
- }
- addr.append(buf, 0, n);
- }
-
- if ("parse".equals(args[0]))
- {
- try
- {
- Address address = Address.parse(addr.toString());
- System.out.println(pprint_address(address));
- }
- catch (ParseError e)
- {
- System.out.println(String.format("ERROR: %s", e.getMessage()));
- }
- }
- else
- {
- List<Token> tokens = AddressParser.lex(addr.toString());
- for (Token t : tokens)
- {
- String value = t.getValue();
- if (value != null)
- {
- value = value.replace("\\", "\\\\").replace("\n", "\\n");
- System.out.println(String.format("%s:%s:%s", t.getType(), t.getPosition(), value));
- }
- else
- {
- System.out.println(String.format("%s:%s", t.getType(), t.getPosition()));
- }
- }
- }
- }
-
- private static String pprint_address(Address addr)
- {
- return String.format("NAME: %s\nSUBJECT: %s\nOPTIONS: %s",
- pprint(addr.getName()),
- pprint(addr.getSubject()),
- pprint(addr.getOptions()));
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/messaging/util/LexError.java b/java/common/src/main/java/org/apache/qpid/messaging/util/LexError.java
deleted file mode 100644
index b8d346dca4..0000000000
--- a/java/common/src/main/java/org/apache/qpid/messaging/util/LexError.java
+++ /dev/null
@@ -1,37 +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.messaging.util;
-
-
-/**
- * LexError
- *
- */
-
-public class LexError extends RuntimeException
-{
-
- public LexError(String msg)
- {
- super(msg);
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/messaging/util/Lexer.java b/java/common/src/main/java/org/apache/qpid/messaging/util/Lexer.java
deleted file mode 100644
index 8226cc77cb..0000000000
--- a/java/common/src/main/java/org/apache/qpid/messaging/util/Lexer.java
+++ /dev/null
@@ -1,84 +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.messaging.util;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.NoSuchElementException;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-
-/**
- * Lexer
- *
- */
-
-public class Lexer
-{
-
- private List<Token.Type> types;
- private Token.Type eof;
- private Pattern rexp;
-
- public Lexer(List<Token.Type> types, Token.Type eof, Pattern rexp)
- {
- this.types = types;
- this.eof = eof;
- this.rexp = rexp;
- }
-
- public List<Token> lex(final String st)
- {
- List<Token> tokens = new ArrayList<Token>();
-
- int position = 0;
- Matcher m = rexp.matcher(st);
- OUTER: while (position < st.length())
- {
- m.region(position, st.length());
- if (m.lookingAt())
- {
- for (int i = 1; i <= m.groupCount(); i++)
- {
- String value = m.group(i);
- if (value != null)
- {
- tokens.add(new Token(types.get(i-1), value, st, m.start(i)));
- position = m.end(i);
- continue OUTER;
- }
- }
- throw new RuntimeException("no group matched");
- }
- else
- {
- throw new LexError("unrecognized characters line:" + LineInfo.get(st, position));
- }
- }
-
- tokens.add(new Token(eof, null, st, position));
-
- return tokens;
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/messaging/util/Lexicon.java b/java/common/src/main/java/org/apache/qpid/messaging/util/Lexicon.java
deleted file mode 100644
index 9ab610f37a..0000000000
--- a/java/common/src/main/java/org/apache/qpid/messaging/util/Lexicon.java
+++ /dev/null
@@ -1,103 +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.messaging.util;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.regex.Pattern;
-
-
-/**
- * Lexicon
- *
- */
-
-public class Lexicon
-{
-
- private List<Token.Type> types;
- private Token.Type eof;
-
- public Lexicon()
- {
- this.types = new ArrayList<Token.Type>();
- this.eof = null;
- }
-
- public Token.Type define(String name, String pattern)
- {
- Token.Type t = new Token.Type(name, pattern);
- types.add(t);
- return t;
- }
-
- public Token.Type eof(String name)
- {
- Token.Type t = new Token.Type(name, null);
- eof = t;
- return t;
- }
-
- public Lexer compile()
- {
- StringBuilder joined = new StringBuilder();
- for (Token.Type t : types)
- {
- if (joined.length() > 0)
- {
- joined.append('|');
- }
- joined.append('(').append(t.getPattern()).append(')');
- }
- Pattern rexp = Pattern.compile(joined.toString());
- return new Lexer(new ArrayList<Token.Type>(types), eof, rexp);
- }
-
- public static final void main(String[] args)
- {
- StringBuilder input = new StringBuilder();
- for (String a : args)
- {
- if (input.length() > 0)
- {
- input.append(" ");
- }
-
- input.append(a);
- }
-
- Lexicon lxi = new Lexicon();
- lxi.define("FOR", "for");
- lxi.define("IF", "if");
- lxi.define("LPAREN", "\\(");
- lxi.define("RPAREN", "\\)");
- lxi.define("ID", "[\\S]+");
- lxi.define("WSPACE", "[\\s]+");
- lxi.eof("EOF");
- Lexer lx = lxi.compile();
-
- for (Token t : lx.lex(input.toString()))
- {
- System.out.println(t);
- }
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/messaging/util/LineInfo.java b/java/common/src/main/java/org/apache/qpid/messaging/util/LineInfo.java
deleted file mode 100644
index 4952fc38a3..0000000000
--- a/java/common/src/main/java/org/apache/qpid/messaging/util/LineInfo.java
+++ /dev/null
@@ -1,93 +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.messaging.util;
-
-
-/**
- * LineInfo
- *
- */
-
-public class LineInfo
-{
-
- public static LineInfo get(String st, int position)
- {
- int idx = 0;
- int line = 1;
- int column = 0;
- int line_pos = 0;
- while (idx < position)
- {
- if (st.charAt(idx) == '\n')
- {
- line += 1;
- column = 0;
- line_pos = idx;
- }
-
- column += 1;
- idx += 1;
- }
-
- int end = st.indexOf('\n', line_pos);
- if (end < 0)
- {
- end = st.length();
- }
-
- String text = st.substring(line_pos, end);
-
- return new LineInfo(line, column, text);
- }
-
- private int line;
- private int column;
- private String text;
-
- public LineInfo(int line, int column, String text)
- {
- this.line = line;
- this.column = column;
- this.text = text;
- }
-
- public int getLine()
- {
- return line;
- }
-
- public int getColumn()
- {
- return column;
- }
-
- public String getText()
- {
- return text;
- }
-
- public String toString()
- {
- return String.format("%s,%s:%s", line, column, text);
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/messaging/util/ParseError.java b/java/common/src/main/java/org/apache/qpid/messaging/util/ParseError.java
deleted file mode 100644
index ce758e15fa..0000000000
--- a/java/common/src/main/java/org/apache/qpid/messaging/util/ParseError.java
+++ /dev/null
@@ -1,58 +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.messaging.util;
-
-import org.apache.qpid.util.Strings;
-
-
-/**
- * ParseError
- *
- */
-
-public class ParseError extends RuntimeException
-{
-
- private static String msg(Token token, Token.Type ... expected)
- {
- LineInfo li = token.getLineInfo();
- String exp = Strings.join(", ", expected);
- if (expected.length > 1)
- {
- exp = String.format("(%s)", exp);
- }
-
- if (expected.length > 0)
- {
- return String.format("expecting %s, got %s line:%s", exp, token, li);
- }
- else
- {
- return String.format("unexpected token %s line:%s", token, li);
- }
- }
-
- public ParseError(Token token, Token.Type ... expected)
- {
- super(msg(token, expected));
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/messaging/util/Parser.java b/java/common/src/main/java/org/apache/qpid/messaging/util/Parser.java
deleted file mode 100644
index 2e983f5165..0000000000
--- a/java/common/src/main/java/org/apache/qpid/messaging/util/Parser.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.messaging.util;
-
-import java.util.ArrayList;
-import java.util.List;
-
-
-/**
- * Parser
- *
- */
-
-class Parser
-{
-
- private List<Token> tokens;
- private int idx = 0;
-
- Parser(List<Token> tokens)
- {
- this.tokens = tokens;
- this.idx = 0;
- }
-
- Token next()
- {
- return tokens.get(idx);
- }
-
- boolean matches(Token.Type ... types)
- {
- for (Token.Type t : types)
- {
- if (next().getType() == t)
- {
- return true;
- }
- }
- return false;
- }
-
- Token eat(Token.Type ... types)
- {
- if (types.length > 0 && !matches(types))
- {
- throw new ParseError(next(), types);
- }
- else
- {
- Token t = next();
- idx += 1;
- return t;
- }
- }
-
- List<Token> eat_until(Token.Type ... types)
- {
- List<Token> result = new ArrayList();
- while (!matches(types))
- {
- result.add(eat());
- }
- return result;
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/messaging/util/PyPrint.java b/java/common/src/main/java/org/apache/qpid/messaging/util/PyPrint.java
deleted file mode 100644
index ef6c724371..0000000000
--- a/java/common/src/main/java/org/apache/qpid/messaging/util/PyPrint.java
+++ /dev/null
@@ -1,146 +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.messaging.util;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-
-
-/**
- * PyPrint
- *
- */
-
-public class PyPrint
-{
-
- public static String pprint(Object obj)
- {
- if (obj instanceof Map)
- {
- return pprint_map((Map) obj);
- }
- else if (obj instanceof List)
- {
- return pprint_list((List) obj);
- }
- else if (obj instanceof String)
- {
- return pprint_string((String) obj);
- }
- else if (obj instanceof Boolean)
- {
- return ((Boolean) obj).booleanValue() ? "True" : "False";
- }
- else if (obj == null)
- {
- return "None";
- }
- else
- {
- return obj.toString();
- }
- }
-
- private static String indent(String st)
- {
- return " " + st.replace("\n", "\n ");
- }
-
- private static String pprint_map(Map<Object,Object> map)
- {
- List<String> items = new ArrayList<String>();
- for (Map.Entry me : map.entrySet())
- {
- items.add(String.format("%s: %s", pprint(me.getKey()),
- pprint(me.getValue())));
- }
- Collections.sort(items);
- return pprint_items("{", items, "}");
- }
-
- private static String pprint_list(List list)
- {
- List<String> items = new ArrayList<String>();
- for (Object o : list)
- {
- items.add(pprint(o));
- }
- return pprint_items("[", items, "]");
- }
-
- private static String pprint_items(String start, List<String> items,
- String end)
- {
- StringBuilder result = new StringBuilder();
- for (String item : items)
- {
- if (result.length() > 0)
- {
- result.append(",\n");
- }
- result.append(indent(item));
- }
-
- if (result.length() > 0)
- {
- return String.format("%s\n%s\n%s", start, result, end);
- }
- else
- {
- return String.format("%s%s", start, end);
- }
- }
-
- private static String pprint_string(String st)
- {
- StringBuilder result = new StringBuilder();
- result.append('\'');
- for (int i = 0; i < st.length(); i++)
- {
- char c = st.charAt(i);
- switch (c)
- {
- case '\'':
- result.append("\\'");
- break;
- case '\n':
- result.append("\\n");
- break;
- default:
- if (c >= 0x80)
- {
- result.append(String.format("\\u%04x", (int)c));
- }
- else
- {
- result.append(c);
- }
- break;
- }
- }
- result.append('\'');
- return result.toString();
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/messaging/util/Token.java b/java/common/src/main/java/org/apache/qpid/messaging/util/Token.java
deleted file mode 100644
index b9458d7997..0000000000
--- a/java/common/src/main/java/org/apache/qpid/messaging/util/Token.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.messaging.util;
-
-
-/**
- * Token
- *
- */
-
-public class Token
-{
-
- public static class Type
- {
-
- private String name;
- private String pattern;
-
- Type(String name, String pattern)
- {
- this.name = name;
- this.pattern = pattern;
- }
-
- public String getName()
- {
- return name;
- }
-
- public String getPattern()
- {
- return pattern;
- }
-
- public String toString()
- {
- return name;
- }
-
- }
-
- private Type type;
- private String value;
- private String input;
- private int position;
-
- Token(Type type, String value, String input, int position)
- {
- this.type = type;
- this.value = value;
- this.input = input;
- this.position = position;
- }
-
- public Type getType()
- {
- return type;
- }
-
- public String getValue()
- {
- return value;
- }
-
- public int getPosition()
- {
- return position;
- }
-
- public LineInfo getLineInfo()
- {
- return LineInfo.get(input, position);
- }
-
- public String toString()
- {
- if (value == null)
- {
- return type.toString();
- }
- else
- {
- return String.format("%s(%s)", type, value);
- }
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/pool/Job.java b/java/common/src/main/java/org/apache/qpid/pool/Job.java
deleted file mode 100644
index 82b600de88..0000000000
--- a/java/common/src/main/java/org/apache/qpid/pool/Job.java
+++ /dev/null
@@ -1,253 +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.pool;
-
-import java.util.concurrent.ConcurrentLinkedQueue;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.RejectedExecutionException;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * A Job is a continuation that batches together other continuations, specifically {@link Event}s, into one continuation.
- * The {@link Event}s themselves provide methods to process themselves, so processing a job simply consists of sequentially
- * processing all of its aggregated events.
- *
- * The constructor accepts a maximum number of events for the job, and only runs up to that maximum number when
- * processing the job, but the add method does not enforce this maximum. In other words, not all the enqueued events
- * may be processed in each run of the job, several runs may be required to clear the queue.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Aggregate many coninuations together into a single continuation.
- * <tr><td> Sequentially process aggregated continuations. <td> {@link Event}
- * <tr><td> Provide running and completion status of the aggregate continuation.
- * <tr><td> Execute a terminal continuation upon job completion. <td> {@link JobCompletionHandler}
- * </table>
- *
- * @todo Could make Job implement Runnable, FutureTask, or a custom Continuation interface, to clarify its status as a
- * continuation. Job is a continuation that aggregates other continuations and as such is a usefull re-usable
- * piece of code. There may be other palces than the mina filter chain where continuation batching is used within
- * qpid, so abstracting this out could provide a usefull building block. This also opens the way to different
- * kinds of job with a common interface, e.g. parallel or sequential jobs etc.
- *
- * @todo For better re-usability could make the completion handler optional. Only run it when one is set.
- */
-public class Job implements ReadWriteRunnable
-{
-
- /** Defines the maximum number of events that will be batched into a single job. */
- public static final int MAX_JOB_EVENTS = Integer.getInteger("amqj.server.read_write_pool.max_events", 10);
-
- /** The maximum number of events to process per run of the job. More events than this may be queued in the job. */
- private final int _maxEvents;
-
- /** Holds the queue of events that make up the job. */
- private final java.util.Queue<Runnable> _eventQueue = new ConcurrentLinkedQueue<Runnable>();
-
- /** Holds a status flag, that indicates when the job is actively running. */
- private final AtomicBoolean _active = new AtomicBoolean();
-
- private final boolean _readJob;
-
- private ReferenceCountingExecutorService _poolReference;
-
- private final static Logger _logger = LoggerFactory.getLogger(Job.class);
-
- public Job(ReferenceCountingExecutorService poolReference, int maxEvents, boolean readJob)
- {
- _poolReference = poolReference;
- _maxEvents = maxEvents;
- _readJob = readJob;
- }
-
- /**
- * Enqueus a continuation for sequential processing by this job.
- *
- * @param evt The continuation to enqueue.
- */
- public void add(Runnable evt)
- {
- _eventQueue.add(evt);
- }
-
- /**
- * Sequentially processes, up to the maximum number per job, the aggregated continuations in enqueued in this job.
- */
- boolean processAll()
- {
- // limit the number of events processed in one run
- int i = _maxEvents;
- while( --i != 0 )
- {
- Runnable e = _eventQueue.poll();
- if (e == null)
- {
- return true;
- }
- else
- {
- e.run();
- }
- }
- return false;
- }
-
- /**
- * Tests if there are no more enqueued continuations to process.
- *
- * @return <tt>true</tt> if there are no enqueued continuations in this job, <tt>false</tt> otherwise.
- */
- public boolean isComplete()
- {
- return _eventQueue.peek() == null;
- }
-
- /**
- * Marks this job as active if it is inactive. This method is thread safe.
- *
- * @return <tt>true</tt> if this job was inactive and has now been marked as active, <tt>false</tt> otherwise.
- */
- public boolean activate()
- {
- return _active.compareAndSet(false, true);
- }
-
- /**
- * Marks this job as inactive. This method is thread safe.
- */
- public void deactivate()
- {
- _active.set(false);
- }
-
- /**
- * Processes a batch of aggregated continuations, marks this job as inactive and call the terminal continuation.
- */
- public void run()
- {
- if(processAll())
- {
- deactivate();
- completed();
- }
- else
- {
- notCompleted();
- }
- }
-
- public boolean isRead()
- {
- return _readJob;
- }
-
- /**
- * Adds an {@link Event} to a {@link Job}, triggering the execution of the job if it is not already running.
- *
- * @param job The job.
- * @param event The event to hand off asynchronously.
- */
- public static void fireAsynchEvent(ExecutorService pool, Job job, Runnable event)
- {
-
- job.add(event);
-
-
- if(pool == null)
- {
- return;
- }
-
- // rather than perform additional checks on pool to check that it hasn't shutdown.
- // catch the RejectedExecutionException that will result from executing on a shutdown pool
- if (job.activate())
- {
- try
- {
- pool.execute(job);
- }
- catch(RejectedExecutionException e)
- {
- _logger.warn("Thread pool shutdown while tasks still outstanding");
- }
- }
-
- }
-
- /**
- * Implements a terminal continuation for the {@link Job} for this filter. Whenever the Job completes its processing
- * of a batch of events this is called. This method simply re-activates the job, if it has more events to process.
- *
- * @param session The Mina session to work in.
- * @param job The job that completed.
- */
- public void completed()
- {
- if (!isComplete())
- {
- final ExecutorService pool = _poolReference.getPool();
-
- if(pool == null)
- {
- return;
- }
-
-
- // ritchiem : 2006-12-13 Do we need to perform the additional checks here?
- // Can the pool be shutdown at this point?
- if (activate())
- {
- try
- {
- pool.execute(this);
- }
- catch(RejectedExecutionException e)
- {
- _logger.warn("Thread pool shutdown while tasks still outstanding");
- }
-
- }
- }
- }
-
- public void notCompleted()
- {
- final ExecutorService pool = _poolReference.getPool();
-
- if(pool == null)
- {
- return;
- }
-
- try
- {
- pool.execute(this);
- }
- catch(RejectedExecutionException e)
- {
- _logger.warn("Thread pool shutdown while tasks still outstanding");
- }
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/pool/ReadWriteJobQueue.java b/java/common/src/main/java/org/apache/qpid/pool/ReadWriteJobQueue.java
deleted file mode 100644
index 8de0f93ce9..0000000000
--- a/java/common/src/main/java/org/apache/qpid/pool/ReadWriteJobQueue.java
+++ /dev/null
@@ -1,432 +0,0 @@
-package org.apache.qpid.pool;
-
-import java.util.AbstractQueue;
-import java.util.Iterator;
-import java.util.Collection;
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.ConcurrentLinkedQueue;
-import java.util.concurrent.locks.ReentrantLock;
-import java.util.concurrent.locks.Condition;
-import java.util.concurrent.atomic.AtomicInteger;
-
-/*
-*
-* 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 ReadWriteJobQueue extends AbstractQueue<Runnable> implements BlockingQueue<Runnable>
-{
-
- private final AtomicInteger _count = new AtomicInteger(0);
-
- private final ReentrantLock _takeLock = new ReentrantLock();
-
- private final Condition _notEmpty = _takeLock.newCondition();
-
- private final ReentrantLock _putLock = new ReentrantLock();
-
- private final ConcurrentLinkedQueue<ReadWriteRunnable> _readJobQueue = new ConcurrentLinkedQueue<ReadWriteRunnable>();
-
- private final ConcurrentLinkedQueue<ReadWriteRunnable> _writeJobQueue = new ConcurrentLinkedQueue<ReadWriteRunnable>();
-
-
- private class ReadWriteJobIterator implements Iterator<Runnable>
- {
-
- private boolean _onReads;
- private Iterator<ReadWriteRunnable> _iter = _writeJobQueue.iterator();
-
- public boolean hasNext()
- {
- if(!_iter.hasNext())
- {
- if(_onReads)
- {
- _iter = _readJobQueue.iterator();
- _onReads = true;
- return _iter.hasNext();
- }
- else
- {
- return false;
- }
- }
- else
- {
- return true;
- }
- }
-
- public Runnable next()
- {
- if(_iter.hasNext())
- {
- return _iter.next();
- }
- else
- {
- return null;
- }
- }
-
- public void remove()
- {
- _takeLock.lock();
- try
- {
- _iter.remove();
- _count.decrementAndGet();
- }
- finally
- {
- _takeLock.unlock();
- }
- }
- }
-
- public Iterator<Runnable> iterator()
- {
- return new ReadWriteJobIterator();
- }
-
- public int size()
- {
- return _count.get();
- }
-
- public boolean offer(final Runnable runnable)
- {
- final ReadWriteRunnable job = (ReadWriteRunnable) runnable;
- final ReentrantLock putLock = _putLock;
- putLock.lock();
- try
- {
- if(job.isRead())
- {
- _readJobQueue.offer(job);
- }
- else
- {
- _writeJobQueue.offer(job);
- }
- if(_count.getAndIncrement() == 0)
- {
- _takeLock.lock();
- try
- {
- _notEmpty.signal();
- }
- finally
- {
- _takeLock.unlock();
- }
- }
- return true;
- }
- finally
- {
- putLock.unlock();
- }
- }
-
- public void put(final Runnable runnable) throws InterruptedException
- {
- final ReadWriteRunnable job = (ReadWriteRunnable) runnable;
- final ReentrantLock putLock = _putLock;
- putLock.lock();
-
- try
- {
- if(job.isRead())
- {
- _readJobQueue.offer(job);
- }
- else
- {
- _writeJobQueue.offer(job);
- }
- if(_count.getAndIncrement() == 0)
- {
- _takeLock.lock();
- try
- {
- _notEmpty.signal();
- }
- finally
- {
- _takeLock.unlock();
- }
- }
-
- }
- finally
- {
- putLock.unlock();
- }
- }
-
-
-
- public boolean offer(final Runnable runnable, final long timeout, final TimeUnit unit) throws InterruptedException
- {
- final ReadWriteRunnable job = (ReadWriteRunnable) runnable;
- final ReentrantLock putLock = _putLock;
- putLock.lock();
-
- try
- {
- if(job.isRead())
- {
- _readJobQueue.offer(job);
- }
- else
- {
- _writeJobQueue.offer(job);
- }
- if(_count.getAndIncrement() == 0)
- {
- _takeLock.lock();
- try
- {
- _notEmpty.signal();
- }
- finally
- {
- _takeLock.unlock();
- }
- }
-
- return true;
- }
- finally
- {
- putLock.unlock();
- }
-
- }
-
- public Runnable take() throws InterruptedException
- {
- final ReentrantLock takeLock = _takeLock;
- takeLock.lockInterruptibly();
- try
- {
- try
- {
- while (_count.get() == 0)
- {
- _notEmpty.await();
- }
- }
- catch (InterruptedException ie)
- {
- _notEmpty.signal();
- throw ie;
- }
-
- ReadWriteRunnable job = _writeJobQueue.poll();
- if(job == null)
- {
- job = _readJobQueue.poll();
- }
- int c = _count.getAndDecrement();
- if (c > 1)
- {
- _notEmpty.signal();
- }
- return job;
- }
- finally
- {
- takeLock.unlock();
- }
-
-
- }
-
- public Runnable poll(final long timeout, final TimeUnit unit) throws InterruptedException
- {
- final ReentrantLock takeLock = _takeLock;
- final AtomicInteger count = _count;
- long nanos = unit.toNanos(timeout);
- takeLock.lockInterruptibly();
- ReadWriteRunnable job = null;
- try
- {
-
- for (;;)
- {
- if (count.get() > 0)
- {
- job = _writeJobQueue.poll();
- if(job == null)
- {
- job = _readJobQueue.poll();
- }
- int c = count.getAndDecrement();
- if (c > 1)
- {
- _notEmpty.signal();
- }
- break;
- }
- if (nanos <= 0)
- {
- return null;
- }
- try
- {
- nanos = _notEmpty.awaitNanos(nanos);
- }
- catch (InterruptedException ie)
- {
- _notEmpty.signal();
- throw ie;
- }
- }
- }
- finally
- {
- takeLock.unlock();
- }
-
- return job;
- }
-
- public int remainingCapacity()
- {
- return Integer.MAX_VALUE;
- }
-
- public int drainTo(final Collection<? super Runnable> c)
- {
- int total = 0;
-
- _putLock.lock();
- _takeLock.lock();
- try
- {
- ReadWriteRunnable job;
- while((job = _writeJobQueue.peek())!= null)
- {
- c.add(job);
- _writeJobQueue.poll();
- _count.decrementAndGet();
- total++;
- }
-
- while((job = _readJobQueue.peek())!= null)
- {
- c.add(job);
- _readJobQueue.poll();
- _count.decrementAndGet();
- total++;
- }
-
- }
- finally
- {
- _takeLock.unlock();
- _putLock.unlock();
- }
- return total;
- }
-
- public int drainTo(final Collection<? super Runnable> c, final int maxElements)
- {
- int total = 0;
-
- _putLock.lock();
- _takeLock.lock();
- try
- {
- ReadWriteRunnable job;
- while(total<=maxElements && (job = _writeJobQueue.peek())!= null)
- {
- c.add(job);
- _writeJobQueue.poll();
- _count.decrementAndGet();
- total++;
- }
-
- while(total<=maxElements && (job = _readJobQueue.peek())!= null)
- {
- c.add(job);
- _readJobQueue.poll();
- _count.decrementAndGet();
- total++;
- }
-
- }
- finally
- {
- _takeLock.unlock();
- _putLock.unlock();
- }
- return total;
-
- }
-
- public Runnable poll()
- {
- final ReentrantLock takeLock = _takeLock;
- takeLock.lock();
- try
- {
- if(_count.get() > 0)
- {
- ReadWriteRunnable job = _writeJobQueue.poll();
- if(job == null)
- {
- job = _readJobQueue.poll();
- }
- _count.decrementAndGet();
- return job;
- }
- else
- {
- return null;
- }
- }
- finally
- {
- takeLock.unlock();
- }
-
- }
-
- public Runnable peek()
- {
- final ReentrantLock takeLock = _takeLock;
- takeLock.lock();
- try
- {
- ReadWriteRunnable job = _writeJobQueue.peek();
- if(job == null)
- {
- job = _readJobQueue.peek();
- }
- return job;
- }
- finally
- {
- takeLock.unlock();
- }
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/pool/ReadWriteRunnable.java b/java/common/src/main/java/org/apache/qpid/pool/ReadWriteRunnable.java
deleted file mode 100644
index 140c93ca8d..0000000000
--- a/java/common/src/main/java/org/apache/qpid/pool/ReadWriteRunnable.java
+++ /dev/null
@@ -1,26 +0,0 @@
-package org.apache.qpid.pool;
-
-/*
-*
-* 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 interface ReadWriteRunnable extends Runnable
-{
- boolean isRead();
-}
diff --git a/java/common/src/main/java/org/apache/qpid/pool/ReferenceCountingExecutorService.java b/java/common/src/main/java/org/apache/qpid/pool/ReferenceCountingExecutorService.java
deleted file mode 100644
index 8152a1f5e9..0000000000
--- a/java/common/src/main/java/org/apache/qpid/pool/ReferenceCountingExecutorService.java
+++ /dev/null
@@ -1,215 +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.pool;
-
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ThreadFactory;
-import java.util.concurrent.ThreadPoolExecutor;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.LinkedBlockingQueue;
-
-
-/**
- * ReferenceCountingExecutorService wraps an ExecutorService in order to provide shared reference to it. It counts
- * the references taken, instantiating the service on the first reference, and shutting it down when the last
- * reference is released.
- *
- * <p/>It is important to ensure that an executor service is correctly shut down as failing to do so prevents the JVM
- * from terminating due to the existence of non-daemon threads.
- *
- * <p/><table id="crc><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Provide a shared executor service. <td> {@link Executors}
- * <tr><td> Shutdown the executor service when not needed. <td> {@link ExecutorService}
- * <tr><td> Track references to the executor service.
- * <tr><td> Provide configuration of the executor service.
- * </table>
- *
- * @todo Might be more elegant to make this actually implement ExecutorService, providing better hiding of the
- * implementation details. Also this class introduces a pattern (albeit specific to this usage) that could be
- * generalized to reference count anything. That is, on first instance call a create method, on release of last
- * instance call a destroy method. This could definitely be abstracted out as a re-usable piece of code; a
- * reference counting factory. It could then be re-used to do reference counting in other places (such as
- * messages). Countable objects have a simple create/destroy life cycle, capturable by an interface that the
- * ref counting factory can call to manage the lifecycle.
- *
- * @todo {@link #_poolSize} should be static?
- *
- * @todo The {@link #getPool()} method breaks the encapsulation of the reference counter. Generally when getPool is used
- * further checks are applied to ensure that the executor service has not been shutdown. This passes responsibility
- * for managing the lifecycle of the reference counted object onto the caller rather than neatly encapsulating it
- * here. Could think about adding more state to the lifecycle, to mark ref counted objects as invalid, and have an
- * isValid method, or could make calling code deal with RejectedExecutionException raised by shutdown executors.
- */
-public class ReferenceCountingExecutorService
-{
-
-
- /** Defines the smallest thread pool that will be allocated, irrespective of the number of processors. */
- private static final int MINIMUM_POOL_SIZE = 4;
-
- /** Holds the number of processors on the machine. */
- private static final int NUM_CPUS = Runtime.getRuntime().availableProcessors();
-
- /** Defines the thread pool size to use, which is the larger of the number of CPUs or the minimum size. */
- private static final int DEFAULT_POOL_SIZE = Math.max(NUM_CPUS, MINIMUM_POOL_SIZE);
-
- /**
- * Holds the singleton instance of this reference counter. This is only created once, statically, so the
- * {@link #getInstance()} method does not need to be synchronized.
- */
- private static final ReferenceCountingExecutorService _instance = new ReferenceCountingExecutorService();
-
- /** This lock is used to ensure that reference counts are updated atomically with create/destroy operations. */
- private final Object _lock = new Object();
-
- /** The shared executor service that is reference counted. */
- private ExecutorService _pool;
-
- /** Holds the number of references given out to the executor service. */
- private int _refCount = 0;
-
- /** Holds the number of executor threads to create. */
- private int _poolSize = Integer.getInteger("amqj.read_write_pool_size", DEFAULT_POOL_SIZE);
-
- /** Thread Factory used to create thread of the pool. Uses the default implementation provided by
- * {@link java.util.concurrent.Executors#defaultThreadFactory()} unless reset by the caller.
- */
- private ThreadFactory _threadFactory = Executors.defaultThreadFactory();
-
- private final boolean _useBiasedPool = Boolean.getBoolean("org.apache.qpid.use_write_biased_pool");
-
- /**
- * Retrieves the singleton instance of this reference counter.
- *
- * @return The singleton instance of this reference counter.
- */
- public static ReferenceCountingExecutorService getInstance()
- {
- return _instance;
- }
-
- /**
- * Private constructor to ensure that only a singleton instance can be created.
- */
- private ReferenceCountingExecutorService()
- { }
-
- /**
- * Provides a reference to a shared executor service, incrementing the reference count.
- *
- * @return An executor service.
- */
- public ExecutorService acquireExecutorService()
- {
- synchronized (_lock)
- {
- if (_refCount++ == 0)
- {
- // Use a job queue that biases to writes
- if(_useBiasedPool)
- {
- _pool = new ThreadPoolExecutor(_poolSize, _poolSize,
- 0L, TimeUnit.MILLISECONDS,
- new ReadWriteJobQueue(),
- _threadFactory);
-
- }
- else
- {
- _pool = new ThreadPoolExecutor(_poolSize, _poolSize,
- 0L, TimeUnit.MILLISECONDS,
- new LinkedBlockingQueue<Runnable>(),
- _threadFactory);
- }
-
- }
-
-
- return _pool;
- }
- }
-
- /**
- * Releases a reference to a shared executor service, decrementing the reference count. If the reference count falls
- * to zero, the executor service is shut down.
- */
- public void releaseExecutorService()
- {
- synchronized (_lock)
- {
- if (--_refCount == 0)
- {
- _pool.shutdownNow();
- }
- }
- }
-
- /**
- * Provides access to the executor service, without touching the reference count.
- *
- * @return The shared executor service, or <tt>null</tt> if none has been instantiated yet.
- */
- public ExecutorService getPool()
- {
- return _pool;
- }
-
- /**
- * Return the ReferenceCount to this ExecutorService
- * @return reference count
- */
- public int getReferenceCount()
- {
- return _refCount;
- }
-
- /**
- *
- * Return the thread factory used by the {@link ThreadPoolExecutor} to create new threads.
- *
- * @return thread factory
- */
- public ThreadFactory getThreadFactory()
- {
- return _threadFactory;
- }
-
- /**
- * Sets the thread factory used by the {@link ThreadPoolExecutor} to create new threads.
- * <p>
- * If the pool has been already created, the change will have no effect until
- * {@link #getReferenceCount()} reaches zero and the pool recreated. For this reason,
- * callers must invoke this method <i>before</i> calling {@link #acquireExecutorService()}.
- *
- * @param threadFactory thread factory
- */
- public void setThreadFactory(final ThreadFactory threadFactory)
- {
- if (threadFactory == null)
- {
- throw new NullPointerException("threadFactory cannot be null");
- }
- _threadFactory = threadFactory;
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/protocol/AMQConstant.java b/java/common/src/main/java/org/apache/qpid/protocol/AMQConstant.java
deleted file mode 100644
index f0f2652ce3..0000000000
--- a/java/common/src/main/java/org/apache/qpid/protocol/AMQConstant.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.protocol;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.apache.qpid.framing.AMQShortString;
-
-/**
- * Defines constants for AMQP codes and also acts as a factory for creating such constants from the raw codes. Each
- * constant also defines a short human readable description of the constant.
- *
- * @todo Why would a constant be defined that is not in the map? Seems more natural that getConstant should raise an
- * exception for an unknown constant. Or else provide an explanation of why this is so. Also, there is no way for
- * callers to determine the unknown status of a code except by comparing its name to "unknown code", which would
- * seem to render this scheme a little bit pointless?
- *
- * @todo Java has a nice enum construct for doing this sort of thing. Maybe this is done in the old style for Java 1.4
- * backward compatability? Now that is handled through retrotranslater it may be time to use enum.
- *
- * <p/><tabld id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Define the set of AMQP status codes.
- * <tr><td> Provide a factory to lookup constants by their code.
- * <tr><td>
- */
-public final class AMQConstant
-{
- /** Defines a map from codes to constants. */
- private static Map<Integer, AMQConstant> _codeMap = new HashMap<Integer, AMQConstant>();
-
- /** Indicates that the method completed successfully. */
- public static final AMQConstant REPLY_SUCCESS = new AMQConstant(200, "reply success", true);
-
- public static final AMQConstant FRAME_END = new AMQConstant(206, "frame end", true);
-
- /**
- * The client asked for a specific message that is no longer available. The message was delivered to another
- * client, or was purged from the queue for some other reason.
- */
- public static final AMQConstant NOT_DELIVERED = new AMQConstant(310, "not delivered", true);
-
- /**
- * The client attempted to transfer content larger than the server could accept at the present time. The client
- * may retry at a later time.
- */
- public static final AMQConstant MESSAGE_TOO_LARGE = new AMQConstant(311, "message too large", true);
-
- /**
- * When the exchange cannot route the result of a .Publish, most likely due to an invalid routing key. Only when
- * the mandatory flag is set.
- */
- public static final AMQConstant NO_ROUTE = new AMQConstant(312, "no route", true);
-
- /**
- * When the exchange cannot deliver to a consumer when the immediate flag is set. As a result of pending data on
- * the queue or the absence of any consumers of the queue.
- */
- public static final AMQConstant NO_CONSUMERS = new AMQConstant(313, "no consumers", true);
-
- /**
- * An operator intervened to close the connection for some reason. The client may retry at some later date.
- */
- public static final AMQConstant CONTEXT_IN_USE = new AMQConstant(320, "context in use", true);
-
- /** The client tried to work with an unknown virtual host or cluster. */
- public static final AMQConstant INVALID_PATH = new AMQConstant(402, "invalid path", true);
-
- /** The client attempted to work with a server entity to which it has no access due to security settings. */
- public static final AMQConstant ACCESS_REFUSED = new AMQConstant(403, "access refused", true);
-
- /** The client attempted to work with a server entity that does not exist. */
- public static final AMQConstant NOT_FOUND = new AMQConstant(404, "not found", true);
-
- /**
- * The client attempted to work with a server entity to which it has no access because another client is
- * working with it.
- */
- public static final AMQConstant ALREADY_EXISTS = new AMQConstant(405, "Already exists", true);
-
- /** The client requested a method that was not allowed because some precondition failed. */
- public static final AMQConstant IN_USE = new AMQConstant(406, "In use", true);
-
- public static final AMQConstant INVALID_ROUTING_KEY = new AMQConstant(407, "routing key invalid", true);
-
- public static final AMQConstant REQUEST_TIMEOUT = new AMQConstant(408, "Request Timeout", true);
-
- public static final AMQConstant INVALID_ARGUMENT = new AMQConstant(409, "argument invalid", true);
-
- /**
- * The client sent a malformed frame that the server could not decode. This strongly implies a programming error
- * in the client.
- */
- public static final AMQConstant FRAME_ERROR = new AMQConstant(501, "frame error", true);
-
- /**
- * The client sent a frame that contained illegal values for one or more fields. This strongly implies a
- * programming error in the client.
- */
- public static final AMQConstant SYNTAX_ERROR = new AMQConstant(502, "syntax error", true);
-
- /**
- * The client sent an invalid sequence of frames, attempting to perform an operation that was considered invalid
- * by the server. This usually implies a programming error in the client.
- */
- public static final AMQConstant COMMAND_INVALID = new AMQConstant(503, "command invalid", true);
-
- /**
- * The client attempted to work with a channel that had not been correctly opened. This most likely indicates a
- * fault in the client layer.
- */
- public static final AMQConstant CHANNEL_ERROR = new AMQConstant(504, "channel error", true);
-
- /**
- * The server could not complete the method because it lacked sufficient resources. This may be due to the client
- * creating too many of some type of entity.
- */
- public static final AMQConstant RESOURCE_ERROR = new AMQConstant(506, "resource error", true);
-
- /**
- * The client tried to work with some entity in a manner that is prohibited by the server, due to security settings
- * or by some other criteria.
- */
- public static final AMQConstant NOT_ALLOWED = new AMQConstant(530, "not allowed", true);
-
- /** The client tried to use functionality that is not implemented in the server. */
- public static final AMQConstant NOT_IMPLEMENTED = new AMQConstant(540, "not implemented", true);
-
- /**
- * The server could not complete the method because of an internal error. The server may require intervention by
- * an operator in order to resume normal operations.
- */
- public static final AMQConstant INTERNAL_ERROR = new AMQConstant(541, "internal error", true);
-
- public static final AMQConstant FRAME_MIN_SIZE = new AMQConstant(4096, "frame min size", true);
-
- /**
- * The server does not support the protocol version
- */
- public static final AMQConstant UNSUPPORTED_BROKER_PROTOCOL_ERROR = new AMQConstant(542, "broker unsupported protocol", true);
- /**
- * The client imp does not support the protocol version
- */
- public static final AMQConstant UNSUPPORTED_CLIENT_PROTOCOL_ERROR = new AMQConstant(543, "client unsupported protocol", true);
-
- /** The AMQP status code. */
- private int _code;
-
- /** A short description of the status code. */
- private AMQShortString _name;
-
- /**
- * Creates a new AMQP status code.
- *
- * @param code The code.
- * @param name A short description of the code.
- * @param map <tt>true</tt> to register the code as a known code, <tt>false</tt> otherwise.
- */
- private AMQConstant(int code, String name, boolean map)
- {
- _code = code;
- _name = new AMQShortString(name);
- if (map)
- {
- _codeMap.put(Integer.valueOf(code), this);
- }
- }
-
- /**
- * Creates a constant for a status code by looking up the code in the map of known codes. If the code is not known
- * a constant is still created for it, but it is marked as unknown.
- *
- * @param code The AMQP status code.
- *
- * @return The AMQP status code encapsulated as a constant.
- */
- public static AMQConstant getConstant(int code)
- {
- AMQConstant c = _codeMap.get(Integer.valueOf(code));
- if (c == null)
- {
- c = new AMQConstant(code, "unknown code", false);
- }
-
- return c;
- }
-
- /**
- * Gets the underlying AMQP status code.
- *
- * @return The AMQP status code.
- */
- public int getCode()
- {
- return _code;
- }
-
- /**
- * Gets a short description of the status code.
- *
- * @return A short description of the status code.
- */
- public AMQShortString getName()
- {
- return _name;
- }
-
- /**
- * Renders the constant as a string, mainly for debugging purposes.
- *
- * @return The status code and its description.
- */
- public String toString()
- {
- return _code + ": " + _name;
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/protocol/AMQMethodEvent.java b/java/common/src/main/java/org/apache/qpid/protocol/AMQMethodEvent.java
deleted file mode 100644
index fd6907a152..0000000000
--- a/java/common/src/main/java/org/apache/qpid/protocol/AMQMethodEvent.java
+++ /dev/null
@@ -1,95 +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.protocol;
-
-import org.apache.qpid.framing.AMQMethodBody;
-
-/**
- * AMQMethodEvent encapsulates an AMQP method call, and the channel on which that method call occurred.
- *
- * <p/>Supplies the:
- * <ul>
- * <li>channel id</li>
- * <li>protocol method</li>
- * </ul>
- *
- * <p/>As the event contains the context in which it occurred, event listeners do not need to be statefull.
- * to listeners. Events are often handled by {@link AMQMethodListener}s.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Encapsulate an AMQP method call and the channel as the context for the method call.
- * </table>
- */
-public class AMQMethodEvent<M extends AMQMethodBody>
-{
- /** Holds the method call. */
- private final M _method;
-
- /** Holds the channel handle for the method call. */
- private final int _channelId;
-
- /**
- * Creates a method event to encasulate a method call and channel.
- *
- * @param channelId The channel on which the method call occurred.
- * @param method The method call.
- */
- public AMQMethodEvent(int channelId, M method)
- {
- _channelId = channelId;
- _method = method;
- }
-
- /**
- * Gets the method call.
- *
- * @return The method call.
- */
- public M getMethod()
- {
- return _method;
- }
-
- /**
- * Gets the channel handle for the method call.
- *
- * @return The channel handle for the method call.
- */
- public int getChannelId()
- {
- return _channelId;
- }
-
- /**
- * Prints the method call as a string, mainly for debugging purposes.
- *
- * @return The method call as a string, mainly for debugging purposes.
- */
- public String toString()
- {
- StringBuilder buf = new StringBuilder("Method event: ");
- buf.append("\nChannel id: ").append(_channelId);
- buf.append("\nMethod: ").append(_method);
-
- return buf.toString();
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/protocol/AMQMethodListener.java b/java/common/src/main/java/org/apache/qpid/protocol/AMQMethodListener.java
deleted file mode 100644
index 5a7679a972..0000000000
--- a/java/common/src/main/java/org/apache/qpid/protocol/AMQMethodListener.java
+++ /dev/null
@@ -1,70 +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.protocol;
-
-import org.apache.qpid.framing.AMQMethodBody;
-import org.apache.qpid.AMQException;
-
-/**
- * AMQMethodListener is a listener that receives notifications of AMQP methods. The methods are packaged as events in
- * {@link AMQMethodEvent}.
- *
- * <p/>An event listener may be associated with a particular context, usually an AMQP channel, and in addition to
- * receiving method events will be notified of errors on that context. This enables listeners to perform any clean
- * up that they need to do before the context is closed or retried.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities
- * <tr><td> Accept notification of AMQP method events. <td> {@link AMQMethodEvent}
- * <tr><td> Accept notification of errors on the event context.
- * </table>
- *
- * @todo Document why the exception is passed to the error method. Is it so that the exception can be passed
- * from the event handling thread to another thread and rethown from there? It is unusual to pass exceptions as
- * method arguments, because they have their own mechanism for propagating through the call stack, so some
- * explanation ought to be provided.
- */
-public interface AMQMethodListener
-{
- /**
- * Notifies the listener that an AMQP method event has occurred.
- *
- * @param evt The AMQP method event (contains the method and channel).
- *
- * @return <tt>true</tt> if the handler processes the method frame, <tt>false<tt> otherwise. Note that this does
- * not prohibit the method event being delivered to subsequent listeners but can be used to determine if
- * nobody has dealt with an incoming method frame.
- *
- * @throws Exception if an error has occurred. This exception may be delivered to all registered listeners using
- * the error() method (see below) allowing them to perform cleanup if necessary.
- *
- * @todo Consider narrowing the exception.
- */
- <B extends AMQMethodBody> boolean methodReceived(AMQMethodEvent<B> evt) throws AMQException;
-
- /**
- * Notifies the listener of an error on the event context to which it is listening. The listener should perform
- * any necessary clean-up for the context.
- *
- * @param e The underlying exception that is the source of the error.
- */
- void error(Exception e);
-}
diff --git a/java/common/src/main/java/org/apache/qpid/protocol/AMQProtocolWriter.java b/java/common/src/main/java/org/apache/qpid/protocol/AMQProtocolWriter.java
deleted file mode 100644
index 65884e4950..0000000000
--- a/java/common/src/main/java/org/apache/qpid/protocol/AMQProtocolWriter.java
+++ /dev/null
@@ -1,43 +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.protocol;
-
-import org.apache.qpid.framing.AMQDataBlock;
-
-/**
- * AMQProtocolWriter provides a method to write a frame of data 'to the wire', in the context of the object
- * that implements the method, usually some sort of session. The block of data, encapsulated by {@link AMQDataBlock},
- * will be encoded as it is written.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities
- * <tr><td> Write an encoded block of data to the write, in the context of a session.
- * </table>
- */
-public interface AMQProtocolWriter
-{
- /**
- * Writes a frame to the wire, encoding it as necessary, for example, into a sequence of bytes.
- *
- * @param frame The frame to be encoded and written.
- */
- public void writeFrame(AMQDataBlock frame);
-}
diff --git a/java/common/src/main/java/org/apache/qpid/protocol/AMQVersionAwareProtocolSession.java b/java/common/src/main/java/org/apache/qpid/protocol/AMQVersionAwareProtocolSession.java
deleted file mode 100644
index b58e7d01dc..0000000000
--- a/java/common/src/main/java/org/apache/qpid/protocol/AMQVersionAwareProtocolSession.java
+++ /dev/null
@@ -1,64 +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.protocol;
-
-import org.apache.qpid.framing.*;
-import org.apache.qpid.transport.Sender;
-import org.apache.qpid.AMQException;
-
-import java.nio.ByteBuffer;
-
-
-/**
- * AMQVersionAwareProtocolSession is implemented by all AMQP session classes, that need to provide an awareness to
- * callers of the version of the AMQP protocol that they are able to work with.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities
- * <tr><td> Provide the method registry for a specific version of the AMQP.
- * </table>
- *
- * @todo Why is this a seperate interface to {@link ProtocolVersionAware}, could they be combined into a single
- * interface and one of them eliminated? Move getRegistry method to ProtocolVersionAware, make the sessions
- * implement AMQProtocolWriter directly and drop this interface.
- */
-public interface AMQVersionAwareProtocolSession extends AMQProtocolWriter, ProtocolVersionAware
-{
- /**
- * Gets the method registry for a specific version of the AMQP.
- *
- * @return The method registry for a specific version of the AMQP.
- */
-// public VersionSpecificRegistry getRegistry();
-
- MethodRegistry getMethodRegistry();
-
-
- public void methodFrameReceived(int channelId, AMQMethodBody body) throws AMQException;
- public void contentHeaderReceived(int channelId, ContentHeaderBody body) throws AMQException;
- public void contentBodyReceived(int channelId, ContentBody body) throws AMQException;
- public void heartbeatBodyReceived(int channelId, HeartbeatBody body) throws AMQException;
-
-
- public void setSender(Sender<ByteBuffer> sender);
- public void init();
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/protocol/ProtocolEngine.java b/java/common/src/main/java/org/apache/qpid/protocol/ProtocolEngine.java
deleted file mode 100644
index 31953ea6ab..0000000000
--- a/java/common/src/main/java/org/apache/qpid/protocol/ProtocolEngine.java
+++ /dev/null
@@ -1,61 +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.protocol;
-
-import java.net.SocketAddress;
-
-import org.apache.qpid.framing.AMQDataBlock;
-import org.apache.qpid.transport.NetworkDriver;
-import org.apache.qpid.transport.Receiver;
-
-/**
- * A ProtocolEngine is a Receiver for java.nio.ByteBuffers. It takes the data passed to it in the received
- * decodes it and then process the result.
- */
-public interface ProtocolEngine extends Receiver<java.nio.ByteBuffer>
-{
- // Sets the network driver providing data for this ProtocolEngine
- void setNetworkDriver (NetworkDriver driver);
-
- // Returns the remote address of the NetworkDriver
- SocketAddress getRemoteAddress();
-
- // Returns the local address of the NetworkDriver
- SocketAddress getLocalAddress();
-
- // Returns number of bytes written
- long getWrittenBytes();
-
- // Returns number of bytes read
- long getReadBytes();
-
- // Called by the NetworkDriver when the socket has been closed for reading
- void closed();
-
- // Called when the NetworkEngine has not written data for the specified period of time (will trigger a
- // heartbeat)
- void writerIdle();
-
- // Called when the NetworkEngine has not read data for the specified period of time (will close the connection)
- void readerIdle();
-
-
-} \ No newline at end of file
diff --git a/java/common/src/main/java/org/apache/qpid/protocol/ProtocolEngineFactory.java b/java/common/src/main/java/org/apache/qpid/protocol/ProtocolEngineFactory.java
deleted file mode 100644
index 9df84eef90..0000000000
--- a/java/common/src/main/java/org/apache/qpid/protocol/ProtocolEngineFactory.java
+++ /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.
- *
- */
-package org.apache.qpid.protocol;
-
-import org.apache.qpid.transport.NetworkDriver;
-
-public interface ProtocolEngineFactory
-{
-
- // Returns a new instance of a ProtocolEngine
- ProtocolEngine newProtocolEngine(NetworkDriver networkDriver);
-
-} \ No newline at end of file
diff --git a/java/common/src/main/java/org/apache/qpid/protocol/ProtocolVersionAware.java b/java/common/src/main/java/org/apache/qpid/protocol/ProtocolVersionAware.java
deleted file mode 100644
index 56f950dd85..0000000000
--- a/java/common/src/main/java/org/apache/qpid/protocol/ProtocolVersionAware.java
+++ /dev/null
@@ -1,53 +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.protocol;
-
-import org.apache.qpid.framing.ProtocolVersion;
-
-/**
- * ProtocolVersionAware is implemented by all AMQP handling classes, that need to provide an awareness to callers of
- * the version of the AMQP protocol that they are able to handle.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities
- * <tr><td> Report the major and minor AMQP version handled.
- * </table>
- */
-public interface ProtocolVersionAware
-{
- /**
- * @deprecated
- * Reports the AMQP minor version, that the implementer can handle.
- *
- * @return The AMQP minor version.
- */
- public byte getProtocolMinorVersion();
-
- /**
- * @deprecated
- * Reports the AMQP major version, that the implementer can handle.
- *
- * @return The AMQP major version.
- */
- public byte getProtocolMajorVersion();
-
- public ProtocolVersion getProtocolVersion();
-}
diff --git a/java/common/src/main/java/org/apache/qpid/security/AMQPCallbackHandler.java b/java/common/src/main/java/org/apache/qpid/security/AMQPCallbackHandler.java
deleted file mode 100644
index a3dad9acdc..0000000000
--- a/java/common/src/main/java/org/apache/qpid/security/AMQPCallbackHandler.java
+++ /dev/null
@@ -1,28 +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.security;
-
-import javax.security.auth.callback.CallbackHandler;
-
-public interface AMQPCallbackHandler extends CallbackHandler
-{
- void initialise(String username,String password);
-}
diff --git a/java/common/src/main/java/org/apache/qpid/security/UsernamePasswordCallbackHandler.java b/java/common/src/main/java/org/apache/qpid/security/UsernamePasswordCallbackHandler.java
deleted file mode 100644
index 89a63abeab..0000000000
--- a/java/common/src/main/java/org/apache/qpid/security/UsernamePasswordCallbackHandler.java
+++ /dev/null
@@ -1,60 +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.security;
-
-import java.io.IOException;
-
-import javax.security.auth.callback.Callback;
-import javax.security.auth.callback.NameCallback;
-import javax.security.auth.callback.PasswordCallback;
-import javax.security.auth.callback.UnsupportedCallbackException;
-
-public class UsernamePasswordCallbackHandler implements AMQPCallbackHandler
-{
- private String _username;
- private String _password;
-
- public void initialise(String username,String password)
- {
- _username = username;
- _password = password;
- }
-
- public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException
- {
- for (int i = 0; i < callbacks.length; i++)
- {
- Callback cb = callbacks[i];
- if (cb instanceof NameCallback)
- {
- ((NameCallback)cb).setName(_username);
- }
- else if (cb instanceof PasswordCallback)
- {
- ((PasswordCallback)cb).setPassword((_password).toCharArray());
- }
- else
- {
- throw new UnsupportedCallbackException(cb);
- }
- }
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/ssl/SSLContextFactory.java b/java/common/src/main/java/org/apache/qpid/ssl/SSLContextFactory.java
deleted file mode 100644
index 702746b3da..0000000000
--- a/java/common/src/main/java/org/apache/qpid/ssl/SSLContextFactory.java
+++ /dev/null
@@ -1,195 +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.ssl;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.security.GeneralSecurityException;
-import java.security.KeyStore;
-
-import javax.net.ssl.KeyManager;
-import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.TrustManagerFactory;
-
-import org.apache.qpid.transport.network.security.ssl.SSLUtil;
-
-/**
- * Factory used to create SSLContexts. SSL needs to be configured
- * before this will work.
- *
- */
-public class SSLContextFactory {
-
- /**
- * Path to the Java keystore file
- */
- private String _keyStorePath;
-
- /**
- * Password for the keystore
- */
- private String _keyStorePassword;
-
- /**
- * Cert type to use in keystore
- */
- private String _keyStoreCertType;
-
- /**
- * Path to the Java truststore file
- */
- private String _trustStorePath;
-
- /**
- * Password for the truststore
- */
- private String _trustStorePassword;
-
- /**
- * Cert type to use in truststore
- */
- private String _trustStoreCertType;
-
- private KeyManager customKeyManager;
-
- public SSLContextFactory(String trustStorePath, String trustStorePassword,
- String trustStoreCertType)
- {
- this(trustStorePath,trustStorePassword,trustStoreCertType,
- trustStorePath,trustStorePassword,trustStoreCertType);
- }
-
- /**
- * Create a factory instance
- * @param keystorePath path to the Java keystore file
- * @param keystorePassword password for the Java keystore
- * @param certType certificate type
- */
- public SSLContextFactory(String trustStorePath, String trustStorePassword, String trustStoreCertType,
- String keyStorePath, String keyStorePassword, String keyStoreCertType)
- {
-
- _trustStorePath = trustStorePath;
- _trustStorePassword = trustStorePassword;
-
- if (_trustStorePassword != null && _trustStorePassword.equals("none"))
- {
- _trustStorePassword = null;
- }
- _trustStoreCertType = trustStoreCertType;
-
- _keyStorePath = keyStorePath;
- _keyStorePassword = keyStorePassword;
-
- if (_keyStorePassword != null && _keyStorePassword.equals("none"))
- {
- _keyStorePassword = null;
- }
- _keyStoreCertType = keyStoreCertType;
-
- if (_trustStorePath == null) {
- throw new IllegalArgumentException("A TrustStore path or KeyStore path must be specified");
- }
- if (_trustStoreCertType == null) {
- throw new IllegalArgumentException("Cert type must be specified");
- }
- }
-
- public SSLContextFactory(String trustStorePath, String trustStorePassword, String trustStoreCertType,
- KeyManager customKeyManager)
- {
-
- _trustStorePath = trustStorePath;
- _trustStorePassword = trustStorePassword;
-
- if (_trustStorePassword != null && _trustStorePassword.equals("none"))
- {
- _trustStorePassword = null;
- }
- _trustStoreCertType = trustStoreCertType;
-
- if (_trustStorePath == null) {
- throw new IllegalArgumentException("A TrustStore path or KeyStore path must be specified");
- }
- if (_trustStoreCertType == null) {
- throw new IllegalArgumentException("Cert type must be specified");
- }
-
- this.customKeyManager = customKeyManager;
- }
-
-
- /**
- * Builds a SSLContext appropriate for use with a server
- * @return SSLContext
- * @throws GeneralSecurityException
- * @throws IOException
- */
-
- public SSLContext buildServerContext() throws GeneralSecurityException, IOException
- {
- KeyStore ts = SSLUtil.getInitializedKeyStore(_trustStorePath,_trustStorePassword);
- TrustManagerFactory tmf = TrustManagerFactory.getInstance(_trustStoreCertType);
- tmf.init(ts);
-
- // Initialize the SSLContext to work with our key managers.
- SSLContext sslContext = SSLContext.getInstance("TLS");
-
- if (customKeyManager != null)
- {
- sslContext.init(new KeyManager[]{customKeyManager},
- tmf.getTrustManagers(), null);
-
- }
- else
- {
- // Create keystore
- KeyStore ks = SSLUtil.getInitializedKeyStore(_keyStorePath,_keyStorePassword);
- // Set up key manager factory to use our key store
- KeyManagerFactory kmf = KeyManagerFactory.getInstance(_keyStoreCertType);
- kmf.init(ks, _keyStorePassword.toCharArray());
-
- sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
- }
-
- return sslContext;
- }
-
- /**
- * Creates a SSLContext factory appropriate for use with a client
- * @return SSLContext
- * @throws GeneralSecurityException
- * @throws IOException
- */
- public SSLContext buildClientContext() throws GeneralSecurityException, IOException
- {
- KeyStore ks = SSLUtil.getInitializedKeyStore(_trustStorePath,_trustStorePassword);
- TrustManagerFactory tmf = TrustManagerFactory.getInstance(_trustStoreCertType);
- tmf.init(ks);
- SSLContext context = SSLContext.getInstance("TLS");
- context.init(null, tmf.getTrustManagers(), null);
- return context;
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/thread/DefaultThreadFactory.java b/java/common/src/main/java/org/apache/qpid/thread/DefaultThreadFactory.java
deleted file mode 100644
index a96dac4109..0000000000
--- a/java/common/src/main/java/org/apache/qpid/thread/DefaultThreadFactory.java
+++ /dev/null
@@ -1,45 +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.thread;
-
-
-
-public class DefaultThreadFactory implements ThreadFactory
-{
-
- private final LoggingUncaughtExceptionHandler _loggingUncaughtExceptionHandler = new LoggingUncaughtExceptionHandler();
-
- public Thread createThread(Runnable r)
- {
- Thread t = new Thread(r);
- t.setUncaughtExceptionHandler(_loggingUncaughtExceptionHandler);
- return t;
- }
-
- public Thread createThread(Runnable r, int priority)
- {
- Thread t = createThread(r);
- t.setPriority(priority);
- return t;
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/thread/LoggingUncaughtExceptionHandler.java b/java/common/src/main/java/org/apache/qpid/thread/LoggingUncaughtExceptionHandler.java
deleted file mode 100644
index 192675edcd..0000000000
--- a/java/common/src/main/java/org/apache/qpid/thread/LoggingUncaughtExceptionHandler.java
+++ /dev/null
@@ -1,60 +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.thread;
-
-import java.lang.Thread.UncaughtExceptionHandler;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- *
- * An {@link UncaughtExceptionHandler} that writes the exception to the application log via
- * the SLF4J framework. Once registered with {@link Thread#setUncaughtExceptionHandler(UncaughtExceptionHandler)}
- * it will be invoked by the JVM when a thread has been <i>abruptly</i> terminated due to an uncaught exception.
- * Owing to the contract of {@link Runnable#run()}, the only possible exception types which can cause such a termination
- * are instances of {@link RuntimeException} and {@link Error}. These exceptions are catastrophic and the client must
- * restart the JVM.
- * <p>
- * The implementation also invokes {@link ThreadGroup#uncaughtException(Thread, Throwable)}. This
- * is done to retain compatibility with any monitoring solutions (for example, log scraping of
- * standard error) that existing users of older Qpid client libraries may have in place.
- *
- */
-public class LoggingUncaughtExceptionHandler implements UncaughtExceptionHandler
-{
- private static final Logger _logger = LoggerFactory.getLogger(LoggingUncaughtExceptionHandler.class);
-
- @Override
- public void uncaughtException(Thread t, Throwable e)
- {
- try
- {
- _logger.error("Uncaught exception in thread \"{}\"", t.getName(), e);
- }
- finally
- {
- // Invoke the thread group's handler too for compatibility with any
- // existing clients who are already scraping stderr for such conditions.
- t.getThreadGroup().uncaughtException(t, e);
- }
- }
-} \ No newline at end of file
diff --git a/java/common/src/main/java/org/apache/qpid/thread/QpidThreadExecutor.java b/java/common/src/main/java/org/apache/qpid/thread/QpidThreadExecutor.java
deleted file mode 100644
index 38f60c04fe..0000000000
--- a/java/common/src/main/java/org/apache/qpid/thread/QpidThreadExecutor.java
+++ /dev/null
@@ -1,42 +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.thread;
-
-import org.apache.qpid.thread.Threading;
-
-import edu.emory.mathcs.backport.java.util.concurrent.Executor;
-
-public class QpidThreadExecutor implements Executor
-{
- public void execute(Runnable command)
- {
- try
- {
- Threading.getThreadFactory().createThread(command).start();
- }
- catch(Exception e)
- {
- throw new RuntimeException("Error creating a thread using Qpid thread factory",e);
- }
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/thread/RealtimeThreadFactory.java b/java/common/src/main/java/org/apache/qpid/thread/RealtimeThreadFactory.java
deleted file mode 100644
index 95a8d192c5..0000000000
--- a/java/common/src/main/java/org/apache/qpid/thread/RealtimeThreadFactory.java
+++ /dev/null
@@ -1,72 +0,0 @@
-package org.apache.qpid.thread;
-/*
- *
- * 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 java.lang.reflect.Constructor;
-
-public class RealtimeThreadFactory implements ThreadFactory
-{
- private final LoggingUncaughtExceptionHandler _loggingUncaughtExceptionHandler = new LoggingUncaughtExceptionHandler();
-
- private Class threadClass;
- private Constructor threadConstructor;
- private Constructor priorityParameterConstructor;
- private int defaultRTThreadPriority = 20;
-
- public RealtimeThreadFactory() throws Exception
- {
- defaultRTThreadPriority = Integer.getInteger("qpid.rt_thread_priority",20);
- threadClass = Class.forName("javax.realtime.RealtimeThread");
-
- Class schedulingParametersClass = Class.forName("javax.realtime.SchedulingParameters");
- Class releaseParametersClass = Class.forName("javax.realtime.ReleaseParameters");
- Class memoryParametersClass = Class.forName("javax.realtime.MemoryParameters");
- Class memoryAreaClass = Class.forName("javax.realtime.MemoryArea");
- Class processingGroupParametersClass = Class.forName("javax.realtime.ProcessingGroupParameters");
-
- Class[] paramTypes = new Class[]{schedulingParametersClass,
- releaseParametersClass,
- memoryParametersClass,
- memoryAreaClass,
- processingGroupParametersClass,
- java.lang.Runnable.class};
-
- threadConstructor = threadClass.getConstructor(paramTypes);
-
- Class priorityParameterClass = Class.forName("javax.realtime.PriorityParameters");
- priorityParameterConstructor = priorityParameterClass.getConstructor(new Class[]{int.class});
- }
-
- public Thread createThread(Runnable r) throws Exception
- {
- return createThread(r,defaultRTThreadPriority);
- }
-
- public Thread createThread(Runnable r, int priority) throws Exception
- {
- Object priorityParams = priorityParameterConstructor.newInstance(priority);
- Thread thread = (Thread)threadConstructor.newInstance(priorityParams,null,null,null,null,r);
- thread.setUncaughtExceptionHandler(_loggingUncaughtExceptionHandler);
- return thread;
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/thread/ThreadFactory.java b/java/common/src/main/java/org/apache/qpid/thread/ThreadFactory.java
deleted file mode 100644
index 4b8937acbd..0000000000
--- a/java/common/src/main/java/org/apache/qpid/thread/ThreadFactory.java
+++ /dev/null
@@ -1,28 +0,0 @@
-package org.apache.qpid.thread;
-/*
- *
- * 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 interface ThreadFactory
-{
- public Thread createThread(Runnable r) throws Exception;
- public Thread createThread(Runnable r, int priority) throws Exception;
-}
diff --git a/java/common/src/main/java/org/apache/qpid/thread/Threading.java b/java/common/src/main/java/org/apache/qpid/thread/Threading.java
deleted file mode 100644
index 603e8a7441..0000000000
--- a/java/common/src/main/java/org/apache/qpid/thread/Threading.java
+++ /dev/null
@@ -1,47 +0,0 @@
-package org.apache.qpid.thread;
-/*
- *
- * 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 final class Threading
-{
- private static ThreadFactory threadFactory;
-
- static {
- try
- {
- Class threadFactoryClass =
- Class.forName(System.getProperty("qpid.thread_factory",
- "org.apache.qpid.thread.DefaultThreadFactory"));
-
- threadFactory = (ThreadFactory)threadFactoryClass.newInstance();
- }
- catch(Exception e)
- {
- throw new Error("Error occured while loading thread factory",e);
- }
- }
-
- public static ThreadFactory getThreadFactory()
- {
- return threadFactory;
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/Binary.java b/java/common/src/main/java/org/apache/qpid/transport/Binary.java
deleted file mode 100644
index 491a7ac218..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/Binary.java
+++ /dev/null
@@ -1,154 +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.transport;
-
-import java.nio.ByteBuffer;
-
-import static org.apache.qpid.transport.util.Functions.*;
-
-
-/**
- * Binary
- *
- */
-
-public final class Binary
-{
-
- private byte[] bytes;
- private int offset;
- private int size;
- private int hash = 0;
-
- public Binary(byte[] bytes, int offset, int size)
- {
- if (offset + size > bytes.length)
- {
- throw new ArrayIndexOutOfBoundsException();
- }
-
- this.bytes = bytes;
- this.offset = offset;
- this.size = size;
- }
-
- public Binary(byte[] bytes)
- {
- this(bytes, 0, bytes.length);
- }
-
- public final byte[] getBytes()
- {
- byte[] result = new byte[size];
- System.arraycopy(bytes, offset, result, 0, size);
- return result;
- }
-
- public final byte[] array()
- {
- return bytes;
- }
-
- public final int offset()
- {
- return offset;
- }
-
- public final int size()
- {
- return size;
- }
-
- public final Binary slice(int low, int high)
- {
- int sz;
-
- if (high < 0)
- {
- sz = size + high;
- }
- else
- {
- sz = high - low;
- }
-
- if (sz < 0)
- {
- sz = 0;
- }
-
- return new Binary(bytes, offset + low, sz);
- }
-
- public final int hashCode()
- {
- if (hash == 0)
- {
- int hc = 0;
- for (int i = 0; i < size; i++)
- {
- hc = 31*hc + (0xFF & bytes[offset + i]);
- }
- hash = hc;
- }
-
- return hash;
- }
-
- public final boolean equals(Object o)
- {
- if (!(o instanceof Binary))
- {
- return false;
- }
-
- Binary buf = (Binary) o;
- if (this.size != buf.size)
- {
- return false;
- }
-
- for (int i = 0; i < size; i++)
- {
- if (bytes[offset + i] != buf.bytes[buf.offset + i])
- {
- return false;
- }
- }
-
- return true;
- }
-
- public String toString()
- {
- return str(ByteBuffer.wrap(bytes, offset, size));
- }
-
- public boolean hasExcessCapacity()
- {
- return size != bytes.length;
- }
-
- public Binary copy()
- {
- return new Binary(getBytes());
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/Binding.java b/java/common/src/main/java/org/apache/qpid/transport/Binding.java
deleted file mode 100644
index 8418c42189..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/Binding.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.transport;
-
-
-/**
- * Binding
- *
- */
-
-public interface Binding<E,T>
-{
-
- E endpoint(Sender<T> sender);
-
- Receiver<T> receiver(E endpoint);
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/ClientDelegate.java b/java/common/src/main/java/org/apache/qpid/transport/ClientDelegate.java
deleted file mode 100644
index c8b7ad2a5e..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/ClientDelegate.java
+++ /dev/null
@@ -1,320 +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.transport;
-
-import org.ietf.jgss.GSSContext;
-import org.ietf.jgss.GSSException;
-import org.ietf.jgss.GSSManager;
-import org.ietf.jgss.GSSName;
-import org.ietf.jgss.Oid;
-
-import org.apache.qpid.security.UsernamePasswordCallbackHandler;
-import static org.apache.qpid.transport.Connection.State.OPEN;
-import static org.apache.qpid.transport.Connection.State.RESUMING;
-import org.apache.qpid.transport.util.Logger;
-
-import javax.security.sasl.Sasl;
-import javax.security.sasl.SaslClient;
-import javax.security.sasl.SaslException;
-import java.lang.management.ManagementFactory;
-import java.lang.management.RuntimeMXBean;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-
-/**
- * ClientDelegate
- *
- */
-
-public class ClientDelegate extends ConnectionDelegate
-{
- private static final Logger log = Logger.get(ClientDelegate.class);
-
- private static final String KRB5_OID_STR = "1.2.840.113554.1.2.2";
- protected static final Oid KRB5_OID;
-
- static
- {
- Oid oid;
- try
- {
- oid = new Oid(KRB5_OID_STR);
- }
- catch (GSSException ignore)
- {
- oid = null;
- }
-
- KRB5_OID = oid;
- }
-
- private List<String> clientMechs;
- private ConnectionSettings conSettings;
-
- public ClientDelegate(ConnectionSettings settings)
- {
- this.conSettings = settings;
- this.clientMechs = Arrays.asList(settings.getSaslMechs().split(" "));
- }
-
- public void init(Connection conn, ProtocolHeader hdr)
- {
- if (!(hdr.getMajor() == 0 && hdr.getMinor() == 10))
- {
- conn.exception(new ProtocolVersionException(hdr.getMajor(), hdr.getMinor()));
- }
- }
-
- @Override
- public void connectionStart(Connection conn, ConnectionStart start)
- {
- Map<String,Object> clientProperties = new HashMap<String,Object>();
-
- if(this.conSettings.getClientProperties() != null)
- {
- clientProperties.putAll(this.conSettings.getClientProperties());
- }
-
- clientProperties.put("qpid.session_flow", 1);
- clientProperties.put("qpid.client_pid",getPID());
- clientProperties.put("qpid.client_process",
- System.getProperty("qpid.client_process","Qpid Java Client"));
-
- List<Object> brokerMechs = start.getMechanisms();
- if (brokerMechs == null || brokerMechs.isEmpty())
- {
- conn.connectionStartOk
- (clientProperties, null, null, conn.getLocale());
- return;
- }
-
- List<String> choosenMechs = new ArrayList<String>();
- for (String mech:clientMechs)
- {
- if (brokerMechs.contains(mech))
- {
- choosenMechs.add(mech);
- }
- }
-
- if (choosenMechs.size() == 0)
- {
- conn.exception(new ConnectionException("The following SASL mechanisms " +
- clientMechs.toString() +
- " specified by the client are not supported by the broker"));
- return;
- }
-
- String[] mechs = new String[choosenMechs.size()];
- choosenMechs.toArray(mechs);
-
- conn.setServerProperties(start.getServerProperties());
-
- try
- {
- Map<String,Object> saslProps = new HashMap<String,Object>();
- if (conSettings.isUseSASLEncryption())
- {
- saslProps.put(Sasl.QOP, "auth-conf");
- }
- UsernamePasswordCallbackHandler handler =
- new UsernamePasswordCallbackHandler();
- handler.initialise(conSettings.getUsername(), conSettings.getPassword());
- SaslClient sc = Sasl.createSaslClient
- (mechs, null, conSettings.getSaslProtocol(), conSettings.getSaslServerName(), saslProps, handler);
- conn.setSaslClient(sc);
-
- byte[] response = sc.hasInitialResponse() ?
- sc.evaluateChallenge(new byte[0]) : null;
- conn.connectionStartOk
- (clientProperties, sc.getMechanismName(), response,
- conn.getLocale());
- }
- catch (SaslException e)
- {
- conn.exception(e);
- }
- }
-
- @Override
- public void connectionSecure(Connection conn, ConnectionSecure secure)
- {
- SaslClient sc = conn.getSaslClient();
- try
- {
- byte[] response = sc.evaluateChallenge(secure.getChallenge());
- conn.connectionSecureOk(response);
- }
- catch (SaslException e)
- {
- conn.exception(e);
- }
- }
-
- @Override
- public void connectionTune(Connection conn, ConnectionTune tune)
- {
- int hb_interval = calculateHeartbeatInterval(conSettings.getHeartbeatInterval(),
- tune.getHeartbeatMin(),
- tune.getHeartbeatMax()
- );
- conn.connectionTuneOk(tune.getChannelMax(),
- tune.getMaxFrameSize(),
- hb_interval);
- // The idle timeout is twice the heartbeat amount (in milisecs)
- conn.setIdleTimeout(hb_interval*1000*2);
-
- int channelMax = tune.getChannelMax();
- //0 means no implied limit, except available server resources
- //(or that forced by protocol limitations [0xFFFF])
- conn.setChannelMax(channelMax == 0 ? Connection.MAX_CHANNEL_MAX : channelMax);
-
- conn.connectionOpen(conSettings.getVhost(), null, Option.INSIST);
- }
-
- @Override
- public void connectionOpenOk(Connection conn, ConnectionOpenOk ok)
- {
- SaslClient sc = conn.getSaslClient();
- if (sc != null)
- {
- if (sc.getMechanismName().equals("GSSAPI"))
- {
- String id = getKerberosUser();
- if (id != null)
- {
- conn.setUserID(id);
- }
- }
- else if (sc.getMechanismName().equals("EXTERNAL"))
- {
- if (conn.getSecurityLayer() != null)
- {
- conn.setUserID(conn.getSecurityLayer().getUserID());
- }
- }
- }
-
- if (conn.isConnectionResuming())
- {
- conn.setState(RESUMING);
- }
- else
- {
- conn.setState(OPEN);
- }
- }
-
- @Override
- public void connectionRedirect(Connection conn, ConnectionRedirect redir)
- {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void connectionHeartbeat(Connection conn, ConnectionHeartbeat hearbeat)
- {
- conn.connectionHeartbeat();
- }
-
- /**
- * Currently the spec specified the min and max for heartbeat using secs
- */
- private int calculateHeartbeatInterval(int heartbeat,int min, int max)
- {
- int i = heartbeat;
- if (i == 0)
- {
- log.info("Idle timeout is 0 sec. Heartbeats are disabled.");
- return 0; // heartbeats are disabled.
- }
- else if (i >= min && i <= max)
- {
- return i;
- }
- else
- {
- log.info("The broker does not support the configured connection idle timeout of %s sec," +
- " using the brokers max supported value of %s sec instead.", i,max);
- return max;
- }
- }
-
- private int getPID()
- {
- RuntimeMXBean rtb = ManagementFactory.getRuntimeMXBean();
- String processName = rtb.getName();
- if (processName != null && processName.indexOf('@')>0)
- {
- try
- {
- return Integer.parseInt(processName.substring(0,processName.indexOf('@')));
- }
- catch(Exception e)
- {
- log.warn("Unable to get the client PID due to error",e);
- return -1;
- }
- }
- else
- {
- log.warn("Unable to get the client PID due to unsupported format : " + processName);
- return -1;
- }
-
- }
-
- private String getKerberosUser()
- {
- log.debug("Obtaining userID from kerberos");
- String service = conSettings.getSaslProtocol() + "@" + conSettings.getSaslServerName();
- GSSManager manager = GSSManager.getInstance();
-
- try
- {
- GSSName acceptorName = manager.createName(service,
- GSSName.NT_HOSTBASED_SERVICE, KRB5_OID);
-
- GSSContext secCtx = manager.createContext(acceptorName,
- KRB5_OID,
- null,
- GSSContext.INDEFINITE_LIFETIME);
-
- secCtx.initSecContext(new byte[0], 0, 1);
-
- if (secCtx.getSrcName() != null)
- {
- return secCtx.getSrcName().toString();
- }
-
- }
- catch (GSSException e)
- {
- log.warn("Unable to retrieve userID from Kerberos due to error",e);
- }
-
- return null;
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/Connection.java b/java/common/src/main/java/org/apache/qpid/transport/Connection.java
deleted file mode 100644
index dc32569ee8..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/Connection.java
+++ /dev/null
@@ -1,703 +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.transport;
-
-import static org.apache.qpid.transport.Connection.State.CLOSED;
-import static org.apache.qpid.transport.Connection.State.CLOSING;
-import static org.apache.qpid.transport.Connection.State.NEW;
-import static org.apache.qpid.transport.Connection.State.OPEN;
-import static org.apache.qpid.transport.Connection.State.OPENING;
-import static org.apache.qpid.transport.Connection.State.RESUMING;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.UUID;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicLong;
-
-import javax.security.sasl.SaslClient;
-import javax.security.sasl.SaslServer;
-
-import org.apache.qpid.transport.network.security.SecurityLayer;
-import org.apache.qpid.transport.util.Logger;
-import org.apache.qpid.transport.util.Waiter;
-import org.apache.qpid.util.Strings;
-
-
-/**
- * Connection
- *
- * @author Rafael H. Schloming
- *
- * @todo the channels map should probably be replaced with something
- * more efficient, e.g. an array or a map implementation that can use
- * short instead of Short
- */
-
-public class Connection extends ConnectionInvoker
- implements Receiver<ProtocolEvent>, Sender<ProtocolEvent>
-{
-
- protected static final Logger log = Logger.get(Connection.class);
-
- //Usable channels are numbered 0 to <ChannelMax> - 1
- public static final int MAX_CHANNEL_MAX = 0xFFFF;
- public static final int MIN_USABLE_CHANNEL_NUM = 0;
-
- public enum State { NEW, CLOSED, OPENING, OPEN, CLOSING, CLOSE_RCVD, RESUMING }
-
- static class DefaultConnectionListener implements ConnectionListener
- {
- public void opened(Connection conn) {}
- public void exception(Connection conn, ConnectionException exception)
- {
- log.error(exception, "connection exception");
- }
- public void closed(Connection conn) {}
- }
-
- public static interface SessionFactory
- {
- Session newSession(Connection conn, Binary name, long expiry);
- }
-
- private static final class DefaultSessionFactory implements SessionFactory
- {
-
- public Session newSession(final Connection conn, final Binary name, final long expiry)
- {
- return new Session(conn, name, expiry);
- }
- }
-
- private static final SessionFactory DEFAULT_SESSION_FACTORY = new DefaultSessionFactory();
-
- private SessionFactory _sessionFactory = DEFAULT_SESSION_FACTORY;
-
- private ConnectionDelegate delegate;
- private Sender<ProtocolEvent> sender;
-
- final private Map<Binary,Session> sessions = new HashMap<Binary,Session>();
- final private Map<Integer,Session> channels = new HashMap<Integer,Session>();
-
- private State state = NEW;
- final private Object lock = new Object();
- private long timeout = 60000;
- private List<ConnectionListener> listeners = new ArrayList<ConnectionListener>();
- private ConnectionException error = null;
-
- private int channelMax = 1;
- private String locale;
- private SaslServer saslServer;
- private SaslClient saslClient;
- private int idleTimeout = 0;
- private String _authorizationID;
- private Map<String,Object> _serverProperties;
- private String userID;
- private ConnectionSettings conSettings;
- private SecurityLayer securityLayer;
- private String _clientId;
-
- private static final AtomicLong idGenerator = new AtomicLong(0);
- private final long _connectionId = idGenerator.incrementAndGet();
- private final AtomicBoolean connectionLost = new AtomicBoolean(false);
-
- public Connection() {}
-
- public void setConnectionDelegate(ConnectionDelegate delegate)
- {
- this.delegate = delegate;
- }
-
- public void addConnectionListener(ConnectionListener listener)
- {
- listeners.add(listener);
- }
-
- public Sender<ProtocolEvent> getSender()
- {
- return sender;
- }
-
- public void setSender(Sender<ProtocolEvent> sender)
- {
- this.sender = sender;
- sender.setIdleTimeout(idleTimeout);
- }
-
- protected void setState(State state)
- {
- synchronized (lock)
- {
- this.state = state;
- lock.notifyAll();
- }
- }
-
- public String getClientId()
- {
- return _clientId;
- }
-
- public void setClientId(String id)
- {
- _clientId = id;
- }
-
- void setLocale(String locale)
- {
- this.locale = locale;
- }
-
- String getLocale()
- {
- return locale;
- }
-
- void setSaslServer(SaslServer saslServer)
- {
- this.saslServer = saslServer;
- }
-
- SaslServer getSaslServer()
- {
- return saslServer;
- }
-
- void setSaslClient(SaslClient saslClient)
- {
- this.saslClient = saslClient;
- }
-
- public SaslClient getSaslClient()
- {
- return saslClient;
- }
-
- public void connect(String host, int port, String vhost, String username, String password)
- {
- connect(host, port, vhost, username, password, false);
- }
-
- public void connect(String host, int port, String vhost, String username, String password, boolean ssl)
- {
- connect(host, port, vhost, username, password, ssl,"PLAIN");
- }
-
- public void connect(String host, int port, String vhost, String username, String password, boolean ssl,String saslMechs)
- {
- connect(host, port, vhost, username, password, ssl,saslMechs, Collections.EMPTY_MAP);
- }
-
-
- public void connect(String host, int port, String vhost, String username, String password, boolean ssl,String saslMechs,Map<String,Object> clientProps)
- {
- ConnectionSettings settings = new ConnectionSettings();
- settings.setHost(host);
- settings.setPort(port);
- settings.setVhost(vhost);
- settings.setUsername(username);
- settings.setPassword(password);
- settings.setUseSSL(ssl);
- settings.setSaslMechs(saslMechs);
- settings.setClientProperties(clientProps);
- connect(settings);
- }
-
- public void connect(ConnectionSettings settings)
- {
-
- synchronized (lock)
- {
- conSettings = settings;
- state = OPENING;
- userID = settings.getUsername();
- delegate = new ClientDelegate(settings);
-
- TransportBuilder transport = new TransportBuilder();
- transport.init(this);
- this.sender = transport.buildSenderPipe();
- transport.buildReceiverPipe(this);
- this.securityLayer = transport.getSecurityLayer();
-
- send(new ProtocolHeader(1, 0, 10));
-
- Waiter w = new Waiter(lock, timeout);
- while (w.hasTime() && state == OPENING && error == null)
- {
- w.await();
- }
-
- if (error != null)
- {
- ConnectionException t = error;
- error = null;
- try
- {
- close();
- }
- catch (ConnectionException ce)
- {
- if (!(t instanceof ProtocolVersionException))
- {
- throw ce;
- }
- }
- t.rethrow();
- }
-
- switch (state)
- {
- case OPENING:
- close();
- throw new ConnectionException("connect() timed out");
- case OPEN:
- case RESUMING:
- connectionLost.set(false);
- break;
- case CLOSED:
- throw new ConnectionException("connect() aborted");
- default:
- throw new IllegalStateException(String.valueOf(state));
- }
- }
-
- for (ConnectionListener listener: listeners)
- {
- listener.opened(this);
- }
- }
-
- public Session createSession()
- {
- return createSession(0);
- }
-
- public Session createSession(long expiry)
- {
- return createSession(UUID.randomUUID().toString(), expiry);
- }
-
- public Session createSession(String name)
- {
- return createSession(name, 0);
- }
-
- public Session createSession(String name, long expiry)
- {
- return createSession(Strings.toUTF8(name), expiry);
- }
-
- public Session createSession(byte[] name, long expiry)
- {
- return createSession(new Binary(name), expiry);
- }
-
- public Session createSession(Binary name, long expiry)
- {
- synchronized (lock)
- {
- Waiter w = new Waiter(lock, timeout);
- while (w.hasTime() && state != OPEN && error == null)
- {
- w.await();
- }
-
- if (state != OPEN)
- {
- throw new ConnectionException("Timed out waiting for connection to be ready. Current state is :" + state);
- }
-
- Session ssn = _sessionFactory.newSession(this, name, expiry);
- sessions.put(name, ssn);
- map(ssn);
- ssn.attach();
- return ssn;
- }
- }
-
- void removeSession(Session ssn)
- {
- synchronized (lock)
- {
- sessions.remove(ssn.getName());
- }
- }
-
- public void setSessionFactory(SessionFactory sessionFactory)
- {
- assert sessionFactory != null;
-
- _sessionFactory = sessionFactory;
- }
-
- public long getConnectionId()
- {
- return _connectionId;
- }
-
- public ConnectionDelegate getConnectionDelegate()
- {
- return delegate;
- }
-
- public void received(ProtocolEvent event)
- {
- log.debug("RECV: [%s] %s", this, event);
- event.delegate(this, delegate);
- }
-
- public void send(ProtocolEvent event)
- {
- log.debug("SEND: [%s] %s", this, event);
- Sender s = sender;
- if (s == null)
- {
- throw new ConnectionException("connection closed");
- }
- s.send(event);
- }
-
- public void flush()
- {
- log.debug("FLUSH: [%s]", this);
- sender.flush();
- }
-
- protected void invoke(Method method)
- {
- method.setChannel(0);
- send(method);
- if (!method.isBatch())
- {
- flush();
- }
- }
-
- public void dispatch(Method method)
- {
- Session ssn = getSession(method.getChannel());
- if(ssn != null)
- {
- ssn.received(method);
- }
- else
- {
- throw new ProtocolViolationException(
- "Received frames for an already dettached session", null);
- }
- }
-
- public int getChannelMax()
- {
- return channelMax;
- }
-
- void setChannelMax(int max)
- {
- channelMax = max;
- }
-
- private int map(Session ssn)
- {
- synchronized (lock)
- {
- //For a negotiated channelMax N, there are channels 0 to N-1 available.
- for (int i = 0; i < getChannelMax(); i++)
- {
- if (!channels.containsKey(i))
- {
- map(ssn, i);
- return i;
- }
- }
-
- throw new RuntimeException("no more channels available");
- }
- }
-
- void map(Session ssn, int channel)
- {
- synchronized (lock)
- {
- channels.put(channel, ssn);
- ssn.setChannel(channel);
- }
- }
-
- void unmap(Session ssn)
- {
- synchronized (lock)
- {
- channels.remove(ssn.getChannel());
- }
- }
-
- protected Session getSession(int channel)
- {
- synchronized (lock)
- {
- return channels.get(channel);
- }
- }
-
- public void resume()
- {
- synchronized (lock)
- {
- for (Session ssn : sessions.values())
- {
- if (ssn.isTransacted())
- {
- removeSession(ssn);
- ssn.setState(Session.State.CLOSED);
- }
- else
- {
- map(ssn);
- ssn.attach();
- ssn.resume();
- }
- }
- setState(OPEN);
- }
- }
-
- public void exception(ConnectionException e)
- {
- connectionLost.set(true);
- synchronized (lock)
- {
- switch (state)
- {
- case OPENING:
- case CLOSING:
- error = e;
- lock.notifyAll();
- return;
- }
- }
-
- for (ConnectionListener listener: listeners)
- {
- listener.exception(this, e);
- }
-
- }
-
- public void exception(Throwable t)
- {
- exception(new ConnectionException(t));
- }
-
- void closeCode(ConnectionClose close)
- {
- synchronized (lock)
- {
- for (Session ssn : channels.values())
- {
- ssn.closeCode(close);
- }
- ConnectionCloseCode code = close.getReplyCode();
- if (code != ConnectionCloseCode.NORMAL)
- {
- exception(new ConnectionException(close));
- }
- }
- }
-
- public void closed()
- {
- if (state == OPEN)
- {
- exception(new ConnectionException("connection aborted"));
- }
-
- log.debug("connection closed: %s", this);
-
- synchronized (lock)
- {
- List<Session> values = new ArrayList<Session>(channels.values());
- for (Session ssn : values)
- {
- ssn.closed();
- }
-
- try
- {
- sender.close();
- }
- catch(Exception e)
- {
- // ignore.
- }
- sender = null;
- setState(CLOSED);
- }
-
- for (ConnectionListener listener: listeners)
- {
- listener.closed(this);
- }
- }
-
- public void close()
- {
- close(ConnectionCloseCode.NORMAL, null);
- }
-
- public void mgmtClose()
- {
- close(ConnectionCloseCode.CONNECTION_FORCED, "The connection was closed using the broker's management interface.");
- }
-
- public void close(ConnectionCloseCode replyCode, String replyText, Option ... _options)
- {
- synchronized (lock)
- {
- switch (state)
- {
- case OPEN:
- state = CLOSING;
- connectionClose(replyCode, replyText, _options);
- Waiter w = new Waiter(lock, timeout);
- while (w.hasTime() && state == CLOSING && error == null)
- {
- w.await();
- }
-
- if (error != null)
- {
- close(replyCode, replyText, _options);
- throw new ConnectionException(error);
- }
-
- switch (state)
- {
- case CLOSING:
- close(replyCode, replyText, _options);
- throw new ConnectionException("close() timed out");
- case CLOSED:
- break;
- default:
- throw new IllegalStateException(String.valueOf(state));
- }
- break;
- case CLOSED:
- break;
- default:
- if (sender != null)
- {
- sender.close();
- w = new Waiter(lock, timeout);
- while (w.hasTime() && sender != null && error == null)
- {
- w.await();
- }
-
- if (error != null)
- {
- throw new ConnectionException(error);
- }
-
- if (sender != null)
- {
- throw new ConnectionException("close() timed out");
- }
- }
- break;
- }
- }
- }
-
- public void setIdleTimeout(int i)
- {
- idleTimeout = i;
- if (sender != null)
- {
- sender.setIdleTimeout(i);
- }
- }
-
- public int getIdleTimeout()
- {
- return idleTimeout;
- }
-
- public void setAuthorizationID(String authorizationID)
- {
- _authorizationID = authorizationID;
- }
-
- public String getAuthorizationID()
- {
- return _authorizationID;
- }
-
- public String getUserID()
- {
- return userID;
- }
-
- public void setUserID(String id)
- {
- userID = id;
- }
-
- public void setServerProperties(final Map<String, Object> serverProperties)
- {
- _serverProperties = serverProperties == null ? Collections.EMPTY_MAP : serverProperties;
- }
-
- public Map<String, Object> getServerProperties()
- {
- return _serverProperties;
- }
-
- public String toString()
- {
- return String.format("conn:%x", System.identityHashCode(this));
- }
-
- public ConnectionSettings getConnectionSettings()
- {
- return conSettings;
- }
-
- public SecurityLayer getSecurityLayer()
- {
- return securityLayer;
- }
-
- public boolean isConnectionResuming()
- {
- return connectionLost.get();
- }
-
- protected Collection<Session> getChannels()
- {
- return channels.values();
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/ConnectionDelegate.java b/java/common/src/main/java/org/apache/qpid/transport/ConnectionDelegate.java
deleted file mode 100644
index 88dd2d6afa..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/ConnectionDelegate.java
+++ /dev/null
@@ -1,102 +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.transport;
-
-import org.apache.qpid.transport.util.Logger;
-
-import static org.apache.qpid.transport.Connection.State.*;
-
-
-/**
- * ConnectionDelegate
- *
- * @author Rafael H. Schloming
- */
-
-/**
- * Currently only implemented client specific methods
- * the server specific methods are dummy impls for testing
- *
- * the connectionClose is kind of different for both sides
- */
-public abstract class ConnectionDelegate
- extends MethodDelegate<Connection>
- implements ProtocolDelegate<Connection>
-{
-
- private static final Logger log = Logger.get(ConnectionDelegate.class);
-
- public void control(Connection conn, Method method)
- {
- method.dispatch(conn, this);
- }
-
- public void command(Connection conn, Method method)
- {
- method.dispatch(conn, this);
- }
-
- public void error(Connection conn, ProtocolError error)
- {
- conn.exception(new ConnectionException(error.getMessage()));
- }
-
- public void handle(Connection conn, Method method)
- {
- conn.dispatch(method);
- }
-
- @Override public void connectionHeartbeat(Connection conn, ConnectionHeartbeat hearbeat)
- {
- // do nothing
- }
-
- @Override public void connectionClose(Connection conn, ConnectionClose close)
- {
- conn.connectionCloseOk();
- conn.getSender().close();
- conn.closeCode(close);
- conn.setState(CLOSE_RCVD);
- }
-
- @Override public void connectionCloseOk(Connection conn, ConnectionCloseOk ok)
- {
- conn.getSender().close();
- }
-
- @Override public void sessionDetach(Connection conn, SessionDetach dtc)
- {
- Session ssn = conn.getSession(dtc.getChannel());
- ssn.sessionDetached(dtc.getName(), SessionDetachCode.NORMAL);
- conn.unmap(ssn);
- ssn.closed();
- }
-
- @Override public void sessionDetached(Connection conn, SessionDetached dtc)
- {
- Session ssn = conn.getSession(dtc.getChannel());
- if (ssn != null)
- {
- conn.unmap(ssn);
- ssn.closed();
- }
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/ConnectionException.java b/java/common/src/main/java/org/apache/qpid/transport/ConnectionException.java
deleted file mode 100644
index 6d3972eb43..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/ConnectionException.java
+++ /dev/null
@@ -1,70 +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.transport;
-
-
-/**
- * ConnectionException
- *
- */
-
-public class ConnectionException extends TransportException
-{
-
- private ConnectionClose close;
-
- public ConnectionException(String message, ConnectionClose close, Throwable cause)
- {
- super(message, cause);
- this.close = close;
- }
-
- public ConnectionException(String message)
- {
- this(message, null, null);
- }
-
- public ConnectionException(String message, Throwable cause)
- {
- this(message, null, cause);
- }
-
- public ConnectionException(Throwable cause)
- {
- this(cause.getMessage(), null, cause);
- }
-
- public ConnectionException(ConnectionClose close)
- {
- this(close.getReplyText(), close, null);
- }
-
- public ConnectionClose getClose()
- {
- return close;
- }
-
- @Override public void rethrow()
- {
- throw new ConnectionException(getMessage(), close, this);
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/ConnectionListener.java b/java/common/src/main/java/org/apache/qpid/transport/ConnectionListener.java
deleted file mode 100644
index 616e76825a..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/ConnectionListener.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.transport;
-
-
-/**
- * ConnectionListener
- *
- */
-
-public interface ConnectionListener
-{
-
- void opened(Connection connection);
-
- void exception(Connection connection, ConnectionException exception);
-
- void closed(Connection connection);
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/ConnectionSettings.java b/java/common/src/main/java/org/apache/qpid/transport/ConnectionSettings.java
deleted file mode 100644
index 08678b213b..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/ConnectionSettings.java
+++ /dev/null
@@ -1,336 +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.transport;
-
-import java.util.Map;
-
-/**
- * A ConnectionSettings object can only be associated with
- * one Connection object. I have added an assertion that will
- * throw an exception if it is used by more than on Connection
- *
- */
-public class ConnectionSettings
-{
- String protocol = "tcp";
- String host = "localhost";
- String vhost;
- String username = "guest";
- String password = "guest";
- int port = 5672;
- boolean tcpNodelay = Boolean.getBoolean("amqj.tcp_nodelay");
- int maxChannelCount = 32767;
- int maxFrameSize = 65535;
- int heartbeatInterval;
- int readBufferSize = 65535;
- int writeBufferSize = 65535;
- long transportTimeout = 60000;
-
- // SSL props
- boolean useSSL;
- String keyStorePath = System.getProperty("javax.net.ssl.keyStore");
- String keyStorePassword = System.getProperty("javax.net.ssl.keyStorePassword");
- String keyStoreCertType = System.getProperty("qpid.ssl.keyStoreCertType","SunX509");;
- String trustStoreCertType = System.getProperty("qpid.ssl.trustStoreCertType","SunX509");;
- String trustStorePath = System.getProperty("javax.net.ssl.trustStore");;
- String trustStorePassword = System.getProperty("javax.net.ssl.trustStorePassword");;
- String certAlias;
- boolean verifyHostname;
-
- // SASL props
- String saslMechs = System.getProperty("qpid.sasl_mechs", "PLAIN");
- String saslProtocol = System.getProperty("qpid.sasl_protocol", "AMQP");
- String saslServerName = System.getProperty("qpid.sasl_server_name", "localhost");
- boolean useSASLEncryption;
-
- private Map<String, Object> _clientProperties;
-
- public boolean isTcpNodelay()
- {
- return tcpNodelay;
- }
-
- public void setTcpNodelay(boolean tcpNodelay)
- {
- this.tcpNodelay = tcpNodelay;
- }
-
- public int getHeartbeatInterval()
- {
- return heartbeatInterval;
- }
-
- public void setHeartbeatInterval(int heartbeatInterval)
- {
- this.heartbeatInterval = heartbeatInterval;
- }
-
- public String getProtocol()
- {
- return protocol;
- }
-
- public void setProtocol(String protocol)
- {
- this.protocol = protocol;
- }
-
- public String getHost()
- {
- return host;
- }
-
- public void setHost(String host)
- {
- this.host = host;
- }
-
- public int getPort()
- {
- return port;
- }
-
- public void setPort(int port)
- {
- this.port = port;
- }
-
- public String getVhost()
- {
- return vhost;
- }
-
- public void setVhost(String vhost)
- {
- this.vhost = vhost;
- }
-
- public String getUsername()
- {
- return username;
- }
-
- public void setUsername(String username)
- {
- this.username = username;
- }
-
- public String getPassword()
- {
- return password;
- }
-
- public void setPassword(String password)
- {
- this.password = password;
- }
-
- public boolean isUseSSL()
- {
- return useSSL;
- }
-
- public void setUseSSL(boolean useSSL)
- {
- this.useSSL = useSSL;
- }
-
- public boolean isUseSASLEncryption()
- {
- return useSASLEncryption;
- }
-
- public void setUseSASLEncryption(boolean useSASLEncryption)
- {
- this.useSASLEncryption = useSASLEncryption;
- }
-
- public String getSaslMechs()
- {
- return saslMechs;
- }
-
- public void setSaslMechs(String saslMechs)
- {
- this.saslMechs = saslMechs;
- }
-
- public String getSaslProtocol()
- {
- return saslProtocol;
- }
-
- public void setSaslProtocol(String saslProtocol)
- {
- this.saslProtocol = saslProtocol;
- }
-
- public String getSaslServerName()
- {
- return saslServerName;
- }
-
- public void setSaslServerName(String saslServerName)
- {
- this.saslServerName = saslServerName;
- }
-
- public int getMaxChannelCount()
- {
- return maxChannelCount;
- }
-
- public void setMaxChannelCount(int maxChannelCount)
- {
- this.maxChannelCount = maxChannelCount;
- }
-
- public int getMaxFrameSize()
- {
- return maxFrameSize;
- }
-
- public void setMaxFrameSize(int maxFrameSize)
- {
- this.maxFrameSize = maxFrameSize;
- }
-
- public void setClientProperties(final Map<String, Object> clientProperties)
- {
- _clientProperties = clientProperties;
- }
-
- public Map<String, Object> getClientProperties()
- {
- return _clientProperties;
- }
-
- public String getKeyStorePath()
- {
- return keyStorePath;
- }
-
- public void setKeyStorePath(String keyStorePath)
- {
- this.keyStorePath = keyStorePath;
- }
-
- public String getKeyStorePassword()
- {
- return keyStorePassword;
- }
-
- public void setKeyStorePassword(String keyStorePassword)
- {
- this.keyStorePassword = keyStorePassword;
- }
-
- public String getTrustStorePath()
- {
- return trustStorePath;
- }
-
- public void setTrustStorePath(String trustStorePath)
- {
- this.trustStorePath = trustStorePath;
- }
-
- public String getTrustStorePassword()
- {
- return trustStorePassword;
- }
-
- public void setTrustStorePassword(String trustStorePassword)
- {
- this.trustStorePassword = trustStorePassword;
- }
-
- public String getCertAlias()
- {
- return certAlias;
- }
-
- public void setCertAlias(String certAlias)
- {
- this.certAlias = certAlias;
- }
-
- public boolean isVerifyHostname()
- {
- return verifyHostname;
- }
-
- public void setVerifyHostname(boolean verifyHostname)
- {
- this.verifyHostname = verifyHostname;
- }
-
- public String getKeyStoreCertType()
- {
- return keyStoreCertType;
- }
-
- public void setKeyStoreCertType(String keyStoreCertType)
- {
- this.keyStoreCertType = keyStoreCertType;
- }
-
- public String getTrustStoreCertType()
- {
- return trustStoreCertType;
- }
-
- public void setTrustStoreCertType(String trustStoreCertType)
- {
- this.trustStoreCertType = trustStoreCertType;
- }
-
- public int getReadBufferSize()
- {
- return readBufferSize;
- }
-
- public void setReadBufferSize(int readBufferSize)
- {
- this.readBufferSize = readBufferSize;
- }
-
- public int getWriteBufferSize()
- {
- return writeBufferSize;
- }
-
- public void setWriteBufferSize(int writeBufferSize)
- {
- this.writeBufferSize = writeBufferSize;
- }
-
- public long getTransportTimeout()
- {
- return transportTimeout;
- }
-
- public void setTransportTimeout(long transportTimeout)
- {
- this.transportTimeout = transportTimeout;
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/Field.java b/java/common/src/main/java/org/apache/qpid/transport/Field.java
deleted file mode 100644
index bc6bf10041..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/Field.java
+++ /dev/null
@@ -1,83 +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.transport;
-
-import org.apache.qpid.transport.codec.Decoder;
-import org.apache.qpid.transport.codec.Encoder;
-
-
-/**
- * Field
- *
- */
-
-public abstract class Field<C,T>
-{
-
- private final Class<C> container;
- private final Class<T> type;
- private final String name;
- private final int index;
-
- Field(Class<C> container, Class<T> type, String name, int index)
- {
- this.container = container;
- this.type = type;
- this.name = name;
- this.index = index;
- }
-
- public final Class<C> getContainer()
- {
- return container;
- }
-
- public final Class<T> getType()
- {
- return type;
- }
-
- public final String getName()
- {
- return name;
- }
-
- public final int getIndex()
- {
- return index;
- }
-
- protected final C check(Object struct)
- {
- return container.cast(struct);
- }
-
- public abstract boolean has(Object struct);
-
- public abstract void has(Object struct, boolean value);
-
- public abstract T get(Object struct);
-
- public abstract void read(Decoder dec, Object struct);
-
- public abstract void write(Encoder enc, Object struct);
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/Future.java b/java/common/src/main/java/org/apache/qpid/transport/Future.java
deleted file mode 100644
index d8cde61af5..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/Future.java
+++ /dev/null
@@ -1,37 +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.transport;
-
-
-/**
- * Future
- *
- * @author Rafael H. Schloming
- */
-
-public interface Future<T>
-{
-
- T get();
-
- boolean isDone();
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/Header.java b/java/common/src/main/java/org/apache/qpid/transport/Header.java
deleted file mode 100644
index 9439e5e0de..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/Header.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.transport;
-
-import org.apache.qpid.transport.network.Frame;
-
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-import java.util.LinkedHashMap;
-import java.nio.ByteBuffer;
-
-
-/**
- * Header
- *
- * @author Rafael H. Schloming
- */
-
-public class Header {
-
- private final Struct[] structs;
-
- public Header(List<Struct> structs)
- {
- this(structs.toArray(new Struct[structs.size()]));
- }
-
- public Header(Struct ... structs)
- {
- this.structs = structs;
- }
-
- public Struct[] getStructs()
- {
- return structs;
- }
-
-
- public <T> T get(Class<T> klass)
- {
- for (Struct st : structs)
- {
- if (klass.isInstance(st))
- {
- return (T) st;
- }
- }
-
- return null;
- }
-
- public String toString()
- {
- StringBuffer str = new StringBuffer();
- str.append(" Header(");
- boolean first = true;
- for (Struct s : structs)
- {
- if (first)
- {
- first = false;
- }
- else
- {
- str.append(", ");
- }
- str.append(s);
- }
- str.append(")");
- return str.toString();
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/Method.java b/java/common/src/main/java/org/apache/qpid/transport/Method.java
deleted file mode 100644
index 3c80180d0b..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/Method.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.transport;
-
-import org.apache.qpid.transport.network.Frame;
-
-import java.nio.ByteBuffer;
-
-import static org.apache.qpid.transport.util.Functions.*;
-
-/**
- * Method
- *
- * @author Rafael H. Schloming
- */
-
-public abstract class Method extends Struct implements ProtocolEvent
-{
-
-
- public static final Method create(int type)
- {
- // XXX: should generate separate factories for separate
- // namespaces
- return (Method) StructFactory.createInstruction(type);
- }
-
- // XXX: command subclass?
- public static interface CompletionListener
- {
- public void onComplete(Method method);
- }
-
- private int id;
- private int channel;
- private boolean idSet = false;
- private boolean sync = false;
- private boolean batch = false;
- private boolean unreliable = false;
- private CompletionListener completionListener;
-
- public final int getId()
- {
- return id;
- }
-
- void setId(int id)
- {
- this.id = id;
- this.idSet = true;
- }
-
- boolean idSet()
- {
- return idSet;
- }
-
- public final int getChannel()
- {
- return channel;
- }
-
- public final void setChannel(int channel)
- {
- this.channel = channel;
- }
-
- public final boolean isSync()
- {
- return sync;
- }
-
- public final void setSync(boolean value)
- {
- this.sync = value;
- }
-
- public final boolean isBatch()
- {
- return batch;
- }
-
- final void setBatch(boolean value)
- {
- this.batch = value;
- }
-
- public final boolean isUnreliable()
- {
- return unreliable;
- }
-
- final void setUnreliable(boolean value)
- {
- this.unreliable = value;
- }
-
- public abstract boolean hasPayload();
-
- public Header getHeader()
- {
- return null;
- }
-
- public void setHeader(Header header)
- {
- throw new UnsupportedOperationException();
- }
-
- public ByteBuffer getBody()
- {
- return null;
- }
-
- public void setBody(ByteBuffer body)
- {
- throw new UnsupportedOperationException();
- }
-
- public int getBodySize()
- {
- ByteBuffer body = getBody();
- if (body == null)
- {
- return 0;
- }
- else
- {
- return body.remaining();
- }
- }
-
- public abstract byte getEncodedTrack();
-
- public abstract <C> void dispatch(C context, MethodDelegate<C> delegate);
-
- public <C> void delegate(C context, ProtocolDelegate<C> delegate)
- {
- if (getEncodedTrack() == Frame.L4)
- {
- delegate.command(context, this);
- }
- else
- {
- delegate.control(context, this);
- }
- }
-
-
- public void setCompletionListener(CompletionListener completionListener)
- {
- this.completionListener = completionListener;
- }
-
- public void complete()
- {
- if(completionListener!= null)
- {
- completionListener.onComplete(this);
- completionListener = null;
- }
- }
-
- public boolean hasCompletionListener()
- {
- return completionListener != null;
- }
-
- public String toString()
- {
- StringBuilder str = new StringBuilder();
-
- str.append("ch=");
- str.append(channel);
-
- if (getEncodedTrack() == Frame.L4 && idSet)
- {
- str.append(" id=");
- str.append(id);
- }
-
- if (sync || batch)
- {
- str.append(" ");
- str.append("[");
- if (sync)
- {
- str.append("S");
- }
- if (batch)
- {
- str.append("B");
- }
- str.append("]");
- }
-
- str.append(" ");
- str.append(super.toString());
- Header hdr = getHeader();
- if (hdr != null)
- {
- for (Struct st : hdr.getStructs())
- {
- str.append("\n ");
- str.append(st);
- }
- }
- ByteBuffer body = getBody();
- if (body != null)
- {
- str.append("\n body=");
- str.append(str(body, 64));
- }
-
- return str.toString();
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/NetworkDriver.java b/java/common/src/main/java/org/apache/qpid/transport/NetworkDriver.java
deleted file mode 100644
index 86af97bf7e..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/NetworkDriver.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.transport;
-
-import java.net.BindException;
-import java.net.InetAddress;
-import java.net.SocketAddress;
-
-import org.apache.qpid.protocol.ProtocolEngine;
-import org.apache.qpid.protocol.ProtocolEngineFactory;
-import org.apache.qpid.ssl.SSLContextFactory;
-
-public interface NetworkDriver extends Sender<java.nio.ByteBuffer>
-{
- // Creates a NetworkDriver which attempts to connect to destination on port and attaches the ProtocolEngine to
- // it using the SSLContextFactory if provided
- void open(int port, InetAddress destination, ProtocolEngine engine,
- NetworkDriverConfiguration config, SSLContextFactory sslFactory)
- throws OpenException;
-
- // listens for incoming connections on the specified ports and address and creates a new NetworkDriver which
- // processes incoming connections with ProtocolEngines and SSLEngines created from the factories
- // (in the case of an SSLContextFactory, if provided)
- void bind (int port, InetAddress[] addresses, ProtocolEngineFactory protocolFactory,
- NetworkDriverConfiguration config, SSLContextFactory sslFactory) throws BindException;
-
- // Returns the remote address of the underlying socket
- SocketAddress getRemoteAddress();
-
- // Returns the local address of the underlying socket
- SocketAddress getLocalAddress();
-
- /**
- * The length of time after which the ProtocolEngines readIdle() method should be called if no data has been
- * read in seconds
- */
- void setMaxReadIdle(int idleTime);
-
- /**
- * The length of time after which the ProtocolEngines writeIdle() method should be called if no data has been
- * written in seconds
- */
- void setMaxWriteIdle(int idleTime);
-
-} \ No newline at end of file
diff --git a/java/common/src/main/java/org/apache/qpid/transport/NetworkDriverConfiguration.java b/java/common/src/main/java/org/apache/qpid/transport/NetworkDriverConfiguration.java
deleted file mode 100644
index c38afe5dd5..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/NetworkDriverConfiguration.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.transport;
-
-/**
- * This interface provides a means for NetworkDrivers to configure TCP options such as incoming and outgoing
- * buffer sizes and set particular options on the socket. NetworkDrivers should honour the values returned
- * from here if the underlying implementation supports them.
- */
-public interface NetworkDriverConfiguration
-{
- // Taken from Socket
- Boolean getKeepAlive();
- Boolean getOOBInline();
- Boolean getReuseAddress();
- Integer getSoLinger(); // null means off
- Integer getSoTimeout();
- Boolean getTcpNoDelay();
- Integer getTrafficClass();
-
- // The amount of memory in bytes to allocate to the incoming buffer
- Integer getReceiveBufferSize();
-
- // The amount of memory in bytes to allocate to the outgoing buffer
- Integer getSendBufferSize();
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/OpenException.java b/java/common/src/main/java/org/apache/qpid/transport/OpenException.java
deleted file mode 100644
index 68fbb5e8ec..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/OpenException.java
+++ /dev/null
@@ -1,34 +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.transport;
-
-import java.io.IOException;
-
-public class OpenException extends IOException
-{
-
- public OpenException(String string, Throwable lastException)
- {
- super(string, lastException);
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/ProtocolDelegate.java b/java/common/src/main/java/org/apache/qpid/transport/ProtocolDelegate.java
deleted file mode 100644
index a90948fc1d..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/ProtocolDelegate.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.transport;
-
-
-/**
- * ProtocolDelegate
- *
- */
-
-public interface ProtocolDelegate<C>
-{
-
- void init(C context, ProtocolHeader header);
-
- void control(C context, Method control);
-
- void command(C context, Method command);
-
- void error(C context, ProtocolError error);
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/ProtocolError.java b/java/common/src/main/java/org/apache/qpid/transport/ProtocolError.java
deleted file mode 100644
index 8a5edc302e..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/ProtocolError.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.transport;
-
-import org.apache.qpid.transport.network.NetworkDelegate;
-import org.apache.qpid.transport.network.NetworkEvent;
-
-
-/**
- * ProtocolError
- *
- * @author Rafael H. Schloming
- */
-
-public final class ProtocolError implements NetworkEvent, ProtocolEvent
-{
-
- private int channel;
- private final byte track;
- private final String format;
- private final Object[] args;
-
- public ProtocolError(byte track, String format, Object ... args)
- {
- this.track = track;
- this.format = format;
- this.args = args;
- }
-
- public int getChannel()
- {
- return channel;
- }
-
- public void setChannel(int channel)
- {
- this.channel = channel;
- }
-
- public byte getEncodedTrack()
- {
- return track;
- }
-
- public boolean isConnectionControl()
- {
- return false;
- }
-
- public String getMessage()
- {
- return String.format(format, args);
- }
-
- public <C> void delegate(C context, ProtocolDelegate<C> delegate)
- {
- delegate.error(context, this);
- }
-
- public void delegate(NetworkDelegate delegate)
- {
- delegate.error(this);
- }
-
- public String toString()
- {
- return String.format("protocol error: %s", getMessage());
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/ProtocolEvent.java b/java/common/src/main/java/org/apache/qpid/transport/ProtocolEvent.java
deleted file mode 100644
index b51a540701..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/ProtocolEvent.java
+++ /dev/null
@@ -1,41 +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.transport;
-
-
-/**
- * ProtocolEvent
- *
- */
-
-public interface ProtocolEvent
-{
-
- int getChannel();
-
- void setChannel(int channel);
-
- byte getEncodedTrack();
-
- <C> void delegate(C context, ProtocolDelegate<C> delegate);
-
- boolean isConnectionControl();
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/ProtocolHeader.java b/java/common/src/main/java/org/apache/qpid/transport/ProtocolHeader.java
deleted file mode 100644
index e5b93e40a9..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/ProtocolHeader.java
+++ /dev/null
@@ -1,123 +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.transport;
-
-import java.nio.ByteBuffer;
-
-import org.apache.qpid.transport.network.NetworkDelegate;
-import org.apache.qpid.transport.network.NetworkEvent;
-import org.apache.qpid.transport.network.Frame;
-
-
-/**
- * ProtocolHeader
- *
- * @author Rafael H. Schloming
- */
-
-public final class ProtocolHeader implements NetworkEvent, ProtocolEvent
-{
-
- private static final byte[] AMQP = {'A', 'M', 'Q', 'P' };
- private static final byte CLASS = 1;
-
- final private byte protoClass;
- final private byte instance;
- final private byte major;
- final private byte minor;
- private int channel;
-
- public ProtocolHeader(byte protoClass, byte instance, byte major, byte minor)
- {
- this.protoClass = protoClass;
- this.instance = instance;
- this.major = major;
- this.minor = minor;
- }
-
- public ProtocolHeader(int instance, int major, int minor)
- {
- this(CLASS, (byte) instance, (byte) major, (byte) minor);
- }
-
- public byte getInstance()
- {
- return instance;
- }
-
- public byte getMajor()
- {
- return major;
- }
-
- public byte getMinor()
- {
- return minor;
- }
-
- public int getChannel()
- {
- return channel;
- }
-
- public void setChannel(int channel)
- {
- this.channel = channel;
- }
-
- public byte getEncodedTrack()
- {
- return Frame.L1;
- }
-
- public boolean isConnectionControl()
- {
- return false;
- }
-
- public ByteBuffer toByteBuffer()
- {
- ByteBuffer buf = ByteBuffer.allocate(8);
- buf.put(AMQP);
- buf.put(protoClass);
- buf.put(instance);
- buf.put(major);
- buf.put(minor);
- buf.flip();
- return buf;
- }
-
- public <C> void delegate(C context, ProtocolDelegate<C> delegate)
- {
- delegate.init(context, this);
- }
-
- public void delegate(NetworkDelegate delegate)
- {
- delegate.init(this);
- }
-
- public String toString()
- {
- return String.format("AMQP.%d %d-%d", instance, major, minor);
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/ProtocolVersionException.java b/java/common/src/main/java/org/apache/qpid/transport/ProtocolVersionException.java
deleted file mode 100644
index db8064268c..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/ProtocolVersionException.java
+++ /dev/null
@@ -1,62 +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.transport;
-
-
-/**
- * ProtocolVersionException
- *
- */
-
-public final class ProtocolVersionException extends ConnectionException
-{
-
- private final byte major;
- private final byte minor;
-
- public ProtocolVersionException(byte major, byte minor, Throwable cause)
- {
- super(String.format("version mismatch: %s-%s", major, minor), cause);
- this.major = major;
- this.minor = minor;
- }
-
- public ProtocolVersionException(byte major, byte minor)
- {
- this(major, minor, null);
- }
-
- public byte getMajor()
- {
- return this.major;
- }
-
- public byte getMinor()
- {
- return this.minor;
- }
-
- @Override public void rethrow()
- {
- throw new ProtocolVersionException(major, minor, this);
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/ProtocolViolationException.java b/java/common/src/main/java/org/apache/qpid/transport/ProtocolViolationException.java
deleted file mode 100644
index 6787157e8e..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/ProtocolViolationException.java
+++ /dev/null
@@ -1,35 +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.transport;
-
-
-/**
- * ProtocolViolationException
- *
- */
-
-public final class ProtocolViolationException extends ConnectionException
-{
- public ProtocolViolationException(String msg,Throwable cause)
- {
- super(msg, cause);
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/Range.java b/java/common/src/main/java/org/apache/qpid/transport/Range.java
deleted file mode 100644
index f4335dc8a6..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/Range.java
+++ /dev/null
@@ -1,125 +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.transport;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import static org.apache.qpid.util.Serial.*;
-
-
-/**
- * Range
- *
- * @author Rafael H. Schloming
- */
-
-public final class Range
-{
- private final int lower;
- private final int upper;
-
- public Range(int lower, int upper)
- {
- this.lower = lower;
- this.upper = upper;
- }
-
- public int getLower()
- {
- return lower;
- }
-
- public int getUpper()
- {
- return upper;
- }
-
- public boolean includes(int value)
- {
- return le(lower, value) && le(value, upper);
- }
-
- public boolean includes(Range range)
- {
- return includes(range.lower) && includes(range.upper);
- }
-
- public boolean intersects(Range range)
- {
- return (includes(range.lower) || includes(range.upper) ||
- range.includes(lower) || range.includes(upper));
- }
-
- public boolean touches(Range range)
- {
- return (intersects(range) ||
- includes(range.upper + 1) || includes(range.lower - 1) ||
- range.includes(upper + 1) || range.includes(lower - 1));
- }
-
- public Range span(Range range)
- {
- return new Range(min(lower, range.lower), max(upper, range.upper));
- }
-
- public List<Range> subtract(Range range)
- {
- List<Range> result = new ArrayList<Range>();
-
- if (includes(range.lower) && le(lower, range.lower - 1))
- {
- result.add(new Range(lower, range.lower - 1));
- }
-
- if (includes(range.upper) && le(range.upper + 1, upper))
- {
- result.add(new Range(range.upper + 1, upper));
- }
-
- if (result.isEmpty() && !range.includes(this))
- {
- result.add(this);
- }
-
- return result;
- }
-
- public Range intersect(Range range)
- {
- int l = max(lower, range.lower);
- int r = min(upper, range.upper);
- if (gt(l, r))
- {
- return null;
- }
- else
- {
- return new Range(l, r);
- }
- }
-
- public String toString()
- {
- return "[" + lower + ", " + upper + "]";
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/RangeSet.java b/java/common/src/main/java/org/apache/qpid/transport/RangeSet.java
deleted file mode 100644
index 3850dc162b..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/RangeSet.java
+++ /dev/null
@@ -1,152 +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.transport;
-
-import java.util.Iterator;
-import java.util.ListIterator;
-import java.util.LinkedList;
-
-import static org.apache.qpid.util.Serial.*;
-
-/**
- * RangeSet
- *
- * @author Rafael H. Schloming
- */
-
-public final class RangeSet implements Iterable<Range>
-{
-
- private LinkedList<Range> ranges = new LinkedList<Range>();
-
- public int size()
- {
- return ranges.size();
- }
-
- public Iterator<Range> iterator()
- {
- return ranges.iterator();
- }
-
- public Range getFirst()
- {
- return ranges.getFirst();
- }
-
- public Range getLast()
- {
- return ranges.getLast();
- }
-
- public boolean includes(Range range)
- {
- for (Range r : this)
- {
- if (r.includes(range))
- {
- return true;
- }
- }
-
- return false;
- }
-
- public boolean includes(int n)
- {
- for (Range r : this)
- {
- if (r.includes(n))
- {
- return true;
- }
- }
-
- return false;
- }
-
- public void add(Range range)
- {
- ListIterator<Range> it = ranges.listIterator();
-
- while (it.hasNext())
- {
- Range next = it.next();
- if (range.touches(next))
- {
- it.remove();
- range = range.span(next);
- }
- else if (lt(range.getUpper(), next.getLower()))
- {
- it.previous();
- it.add(range);
- return;
- }
- }
-
- it.add(range);
- }
-
- public void add(int lower, int upper)
- {
- add(new Range(lower, upper));
- }
-
- public void add(int value)
- {
- add(value, value);
- }
-
- public void clear()
- {
- ranges.clear();
- }
-
- public RangeSet copy()
- {
- RangeSet copy = new RangeSet();
- copy.ranges.addAll(ranges);
- return copy;
- }
-
- public String toString()
- {
- StringBuffer str = new StringBuffer();
- str.append("{");
- boolean first = true;
- for (Range range : ranges)
- {
- if (first)
- {
- first = false;
- }
- else
- {
- str.append(", ");
- }
- str.append(range);
- }
- str.append("}");
- return str.toString();
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/Receiver.java b/java/common/src/main/java/org/apache/qpid/transport/Receiver.java
deleted file mode 100644
index 2a994580dc..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/Receiver.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.transport;
-
-
-/**
- * Receiver
- *
- */
-
-public interface Receiver<T>
-{
-
- void received(T msg);
-
- void exception(Throwable t);
-
- void closed();
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/Sender.java b/java/common/src/main/java/org/apache/qpid/transport/Sender.java
deleted file mode 100644
index 6519702c76..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/Sender.java
+++ /dev/null
@@ -1,39 +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.transport;
-
-
-/**
- * Sender
- *
- */
-
-public interface Sender<T>
-{
- void setIdleTimeout(int i);
-
- void send(T msg);
-
- void flush();
-
- void close();
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/SenderException.java b/java/common/src/main/java/org/apache/qpid/transport/SenderException.java
deleted file mode 100644
index a96079dc27..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/SenderException.java
+++ /dev/null
@@ -1,52 +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.transport;
-
-
-/**
- * SenderException
- *
- */
-
-public class SenderException extends TransportException
-{
-
- public SenderException(String message, Throwable cause)
- {
- super(message, cause);
- }
-
- public SenderException(String message)
- {
- super(message);
- }
-
- public SenderException(Throwable cause)
- {
- super(cause);
- }
-
- public void rethrow()
- {
- throw new SenderException(getMessage(), this);
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/ServerDelegate.java b/java/common/src/main/java/org/apache/qpid/transport/ServerDelegate.java
deleted file mode 100644
index f21df251da..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/ServerDelegate.java
+++ /dev/null
@@ -1,203 +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.transport;
-
-import static org.apache.qpid.transport.Connection.State.*;
-
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-
-import javax.security.sasl.Sasl;
-import javax.security.sasl.SaslException;
-import javax.security.sasl.SaslServer;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * ServerDelegate
- */
-public class ServerDelegate extends ConnectionDelegate
-{
- protected static final Logger _logger = LoggerFactory.getLogger(ServerDelegate.class);
-
- private List<Object> _locales;
- private List<Object> _mechanisms;
- private Map<String, Object> _clientProperties;
-
-
- public ServerDelegate()
- {
- this(null, Collections.emptyList(), Collections.singletonList((Object)"utf8"));
- }
-
- protected ServerDelegate(Map<String, Object> clientProperties, List<Object> mechanisms, List<Object> locales)
- {
- _clientProperties = clientProperties;
- _mechanisms = mechanisms;
- _locales = locales;
- }
-
- public void init(Connection conn, ProtocolHeader hdr)
- {
- conn.send(new ProtocolHeader(1, 0, 10));
-
- conn.connectionStart(_clientProperties, _mechanisms, _locales);
- }
-
- @Override
- public void connectionStartOk(Connection conn, ConnectionStartOk ok)
- {
- conn.setLocale(ok.getLocale());
- String mechanism = ok.getMechanism();
-
- String clientName = (String) ok.getClientProperties().get("clientName");
- conn.setClientId(clientName);
-
- if (mechanism == null || mechanism.length() == 0)
- {
- conn.connectionTune
- (getChannelMax(),
- org.apache.qpid.transport.network.ConnectionBinding.MAX_FRAME_SIZE,
- 0, getHeartbeatMax());
- return;
- }
-
- try
- {
-
- SaslServer ss = createSaslServer(mechanism);
- if (ss == null)
- {
- conn.connectionClose(ConnectionCloseCode.CONNECTION_FORCED,
- "null SASL mechanism: " + mechanism);
- return;
- }
- conn.setSaslServer(ss);
- secure(conn, ok.getResponse());
- }
- catch (SaslException e)
- {
- conn.exception(e);
- conn.connectionClose(ConnectionCloseCode.CONNECTION_FORCED, e.getMessage());
- }
- }
-
- protected SaslServer createSaslServer(String mechanism)
- throws SaslException
- {
- SaslServer ss = Sasl.createSaslServer(mechanism, "AMQP", "localhost", null, null);
- return ss;
- }
-
- private void secure(Connection conn, byte[] response)
- {
- SaslServer ss = conn.getSaslServer();
- try
- {
- byte[] challenge = ss.evaluateResponse(response);
- if (ss.isComplete())
- {
- ss.dispose();
- conn.connectionTune
- (getChannelMax(),
- org.apache.qpid.transport.network.ConnectionBinding.MAX_FRAME_SIZE,
- 0, getHeartbeatMax());
- conn.setAuthorizationID(ss.getAuthorizationID());
- }
- else
- {
- conn.connectionSecure(challenge);
- }
- }
- catch (SaslException e)
- {
- conn.exception(e);
- conn.connectionClose(ConnectionCloseCode.CONNECTION_FORCED, e.getMessage());
- }
- }
-
- protected int getHeartbeatMax()
- {
- return 0xFFFF;
- }
-
- protected int getChannelMax()
- {
- return 0xFFFF;
- }
-
- @Override
- public void connectionSecureOk(Connection conn, ConnectionSecureOk ok)
- {
- secure(conn, ok.getResponse());
- }
-
- @Override
- public void connectionTuneOk(Connection conn, ConnectionTuneOk ok)
- {
- int okChannelMax = ok.getChannelMax();
-
- if (okChannelMax > getChannelMax())
- {
- _logger.error("Connection '" + conn.getConnectionId() + "' being severed, " +
- "client connectionTuneOk returned a channelMax (" + okChannelMax +
- ") above the servers offered limit (" + getChannelMax() +")");
-
- //Due to the error we must forcefully close the connection without negotiation
- conn.getSender().close();
- return;
- }
-
- //0 means no implied limit, except available server resources
- //(or that forced by protocol limitations [0xFFFF])
- conn.setChannelMax(okChannelMax == 0 ? Connection.MAX_CHANNEL_MAX : okChannelMax);
- }
-
- @Override
- public void connectionOpen(Connection conn, ConnectionOpen open)
- {
- conn.connectionOpenOk(Collections.emptyList());
-
- conn.setState(OPEN);
- }
-
- protected Session getSession(Connection conn, SessionDelegate delegate, SessionAttach atc)
- {
- return new Session(conn, delegate, new Binary(atc.getName()), 0);
- }
-
-
- public Session getSession(Connection conn, SessionAttach atc)
- {
- return new Session(conn, new Binary(atc.getName()), 0);
- }
-
- @Override
- public void sessionAttach(Connection conn, SessionAttach atc)
- {
- Session ssn = getSession(conn, atc);
- conn.map(ssn, atc.getChannel());
- ssn.sessionAttached(atc.getName());
- ssn.setState(Session.State.OPEN);
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/Session.java b/java/common/src/main/java/org/apache/qpid/transport/Session.java
deleted file mode 100644
index 862c37283b..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/Session.java
+++ /dev/null
@@ -1,1057 +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.transport;
-
-
-import static org.apache.qpid.transport.Option.COMPLETED;
-import static org.apache.qpid.transport.Option.SYNC;
-import static org.apache.qpid.transport.Option.TIMELY_REPLY;
-import static org.apache.qpid.transport.Session.State.CLOSED;
-import static org.apache.qpid.transport.Session.State.CLOSING;
-import static org.apache.qpid.transport.Session.State.DETACHED;
-import static org.apache.qpid.transport.Session.State.NEW;
-import static org.apache.qpid.transport.Session.State.OPEN;
-import static org.apache.qpid.transport.Session.State.RESUMING;
-import org.apache.qpid.transport.network.Frame;
-import static org.apache.qpid.transport.util.Functions.mod;
-import org.apache.qpid.transport.util.Logger;
-import org.apache.qpid.transport.util.Waiter;
-import static org.apache.qpid.util.Serial.ge;
-import static org.apache.qpid.util.Serial.gt;
-import static org.apache.qpid.util.Serial.le;
-import static org.apache.qpid.util.Serial.lt;
-import static org.apache.qpid.util.Serial.max;
-import static org.apache.qpid.util.Strings.toUTF8;
-
-import java.nio.ByteBuffer;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.Semaphore;
-import java.util.concurrent.TimeUnit;
-
-/**
- * Session
- *
- * @author Rafael H. Schloming
- */
-
-public class Session extends SessionInvoker
-{
-
- private static final Logger log = Logger.get(Session.class);
-
- public enum State { NEW, DETACHED, RESUMING, OPEN, CLOSING, CLOSED }
-
- static class DefaultSessionListener implements SessionListener
- {
-
- public void opened(Session ssn) {}
-
- public void resumed(Session ssn) {}
-
- public void message(Session ssn, MessageTransfer xfr)
- {
- log.info("message: %s", xfr);
- }
-
- public void exception(Session ssn, SessionException exc)
- {
- log.error(exc, "session exception");
- }
-
- public void closed(Session ssn) {}
- }
-
- public static final int UNLIMITED_CREDIT = 0xFFFFFFFF;
-
- private Connection connection;
- private Binary name;
- private long expiry;
- private boolean closing;
- private int channel;
- private SessionDelegate delegate;
- private SessionListener listener = new DefaultSessionListener();
- private long timeout = 60000;
- private boolean autoSync = false;
-
- private boolean incomingInit;
- // incoming command count
- private int commandsIn;
- // completed incoming commands
- private final Object processedLock = new Object();
- private RangeSet processed;
- private int maxProcessed;
- private int syncPoint;
-
- // outgoing command count
- private int commandsOut = 0;
- private Method[] commands = new Method[Integer.getInteger("qpid.session.command_limit", 64*1024)];
- private int commandBytes = 0;
- private int byteLimit = Integer.getInteger("qpid.session.byte_limit", 1024*1024);
- private int maxComplete = commandsOut - 1;
- private boolean needSync = false;
-
- private State state = NEW;
-
- // transfer flow control
- private volatile boolean flowControl = false;
- private Semaphore credit = new Semaphore(0);
-
- private Thread resumer = null;
- private boolean transacted = false;
-
- protected Session(Connection connection, Binary name, long expiry)
- {
- this(connection, new SessionDelegate(), name, expiry);
- }
-
- protected Session(Connection connection, SessionDelegate delegate, Binary name, long expiry)
- {
- this.connection = connection;
- this.delegate = delegate;
- this.name = name;
- this.expiry = expiry;
- this.closing = false;
- initReceiver();
- }
-
- public Connection getConnection()
- {
- return connection;
- }
-
- public Binary getName()
- {
- return name;
- }
-
- void setExpiry(long expiry)
- {
- this.expiry = expiry;
- }
-
- void setClose(boolean close)
- {
- this.closing = close;
- }
-
- public int getChannel()
- {
- return channel;
- }
-
- void setChannel(int channel)
- {
- this.channel = channel;
- }
-
- public void setSessionListener(SessionListener listener)
- {
- if (listener == null)
- {
- this.listener = new DefaultSessionListener();
- }
- else
- {
- this.listener = listener;
- }
- }
-
- public SessionListener getSessionListener()
- {
- return listener;
- }
-
- public void setAutoSync(boolean value)
- {
- synchronized (commands)
- {
- this.autoSync = value;
- }
- }
-
- protected void setState(State state)
- {
- synchronized (commands)
- {
- this.state = state;
- commands.notifyAll();
- }
- }
-
- void setFlowControl(boolean value)
- {
- flowControl = value;
- }
-
- void addCredit(int value)
- {
- credit.release(value);
- }
-
- void drainCredit()
- {
- credit.drainPermits();
- }
-
- void acquireCredit()
- {
- if (flowControl)
- {
- try
- {
- if (!credit.tryAcquire(timeout, TimeUnit.MILLISECONDS))
- {
- throw new SessionException
- ("timed out waiting for message credit");
- }
- }
- catch (InterruptedException e)
- {
- throw new SessionException
- ("interrupted while waiting for credit", null, e);
- }
- }
- }
-
- private void initReceiver()
- {
- synchronized (processedLock)
- {
- incomingInit = false;
- processed = new RangeSet();
- }
- }
-
- void attach()
- {
- initReceiver();
- sessionAttach(name.getBytes());
- sessionRequestTimeout(0);//use expiry here only if/when session resume is supported
- }
-
- void resume()
- {
- synchronized (commands)
- {
- for (int i = maxComplete + 1; lt(i, commandsOut); i++)
- {
- Method m = commands[mod(i, commands.length)];
- if (m == null)
- {
- m = new ExecutionSync();
- m.setId(i);
- }
- else if (m instanceof MessageTransfer)
- {
- MessageTransfer xfr = (MessageTransfer)m;
-
- if (xfr.getHeader() != null)
- {
- if (xfr.getHeader().get(DeliveryProperties.class) != null)
- {
- xfr.getHeader().get(DeliveryProperties.class).setRedelivered(true);
- }
- else
- {
- Struct[] structs = xfr.getHeader().getStructs();
- DeliveryProperties deliveryProps = new DeliveryProperties();
- deliveryProps.setRedelivered(true);
-
- List<Struct> list = Arrays.asList(structs);
- list.add(deliveryProps);
- xfr.setHeader(new Header(list));
- }
-
- }
- else
- {
- DeliveryProperties deliveryProps = new DeliveryProperties();
- deliveryProps.setRedelivered(true);
- xfr.setHeader(new Header(deliveryProps));
- }
- }
- sessionCommandPoint(m.getId(), 0);
- send(m);
- }
-
- sessionCommandPoint(commandsOut, 0);
- sessionFlush(COMPLETED);
- resumer = Thread.currentThread();
- state = RESUMING;
- listener.resumed(this);
- resumer = null;
- }
- }
-
- void dump()
- {
- synchronized (commands)
- {
- for (Method m : commands)
- {
- if (m != null)
- {
- log.debug("%s", m);
- }
- }
- }
- }
-
- final void commandPoint(int id)
- {
- synchronized (processedLock)
- {
- this.commandsIn = id;
- if (!incomingInit)
- {
- incomingInit = true;
- maxProcessed = commandsIn - 1;
- syncPoint = maxProcessed;
- }
- }
- }
-
- public int getCommandsOut()
- {
- return commandsOut;
- }
-
- public int getCommandsIn()
- {
- return commandsIn;
- }
-
- public int nextCommandId()
- {
- return commandsIn++;
- }
-
- final void identify(Method cmd)
- {
- if (!incomingInit)
- {
- throw new IllegalStateException();
- }
-
- int id = nextCommandId();
- cmd.setId(id);
-
- if(log.isDebugEnabled())
- {
- log.debug("ID: [%s] %s", this.channel, id);
- }
-
- //if ((id % 65536) == 0)
- if ((id & 0xff) == 0)
- {
- flushProcessed(TIMELY_REPLY);
- }
- }
-
- public void processed(Method command)
- {
- processed(command.getId());
- }
-
- public void processed(int command)
- {
- processed(new Range(command, command));
- }
-
- public void processed(int lower, int upper)
- {
-
- processed(new Range(lower, upper));
- }
-
- public void processed(Range range)
- {
- log.debug("%s processed(%s) %s %s", this, range, syncPoint, maxProcessed);
-
- boolean flush;
- synchronized (processedLock)
- {
- log.debug("%s", processed);
-
- if (ge(range.getUpper(), commandsIn))
- {
- throw new IllegalArgumentException
- ("range exceeds max received command-id: " + range);
- }
-
- processed.add(range);
- Range first = processed.getFirst();
- int lower = first.getLower();
- int upper = first.getUpper();
- int old = maxProcessed;
- if (le(lower, maxProcessed + 1))
- {
- maxProcessed = max(maxProcessed, upper);
- }
- boolean synced = ge(maxProcessed, syncPoint);
- flush = lt(old, syncPoint) && synced;
- if (synced)
- {
- syncPoint = maxProcessed;
- }
- }
- if (flush)
- {
- flushProcessed();
- }
- }
-
- void flushExpected()
- {
- RangeSet rs = new RangeSet();
- synchronized (processedLock)
- {
- if (incomingInit)
- {
- rs.add(commandsIn);
- }
- }
- sessionExpected(rs, null);
- }
-
- public void flushProcessed(Option ... options)
- {
- RangeSet copy;
- synchronized (processedLock)
- {
- copy = processed.copy();
- }
-
- synchronized (commands)
- {
- if (state == DETACHED || state == CLOSING)
- {
- return;
- }
- if (copy.size() > 0)
- {
- sessionCompleted(copy, options);
- }
- }
- }
-
- void knownComplete(RangeSet kc)
- {
- synchronized (processedLock)
- {
- RangeSet newProcessed = new RangeSet();
- for (Range pr : processed)
- {
- for (Range kr : kc)
- {
- for (Range r : pr.subtract(kr))
- {
- newProcessed.add(r);
- }
- }
- }
- this.processed = newProcessed;
- }
- }
-
- void syncPoint()
- {
- int id = getCommandsIn() - 1;
- log.debug("%s synced to %d", this, id);
- boolean flush;
- synchronized (processedLock)
- {
- syncPoint = id;
- flush = ge(maxProcessed, syncPoint);
- }
- if (flush)
- {
- flushProcessed();
- }
- }
-
- protected boolean complete(int lower, int upper)
- {
- //avoid autoboxing
- if(log.isDebugEnabled())
- {
- log.debug("%s complete(%d, %d)", this, lower, upper);
- }
- synchronized (commands)
- {
- int old = maxComplete;
- for (int id = max(maxComplete, lower); le(id, upper); id++)
- {
- int idx = mod(id, commands.length);
- Method m = commands[idx];
- if (m != null)
- {
- commandBytes -= m.getBodySize();
- m.complete();
- commands[idx] = null;
- }
- }
- if (le(lower, maxComplete + 1))
- {
- maxComplete = max(maxComplete, upper);
- }
- log.debug("%s commands remaining: %s", this, commandsOut - maxComplete);
- commands.notifyAll();
- return gt(maxComplete, old);
- }
- }
-
- void received(Method m)
- {
- m.delegate(this, delegate);
- }
-
- private void send(Method m)
- {
- m.setChannel(channel);
- connection.send(m);
-
- if (!m.isBatch())
- {
- connection.flush();
- }
- }
-
- protected boolean isFull(int id)
- {
- return isCommandsFull(id) || isBytesFull();
- }
-
- protected boolean isBytesFull()
- {
- return commandBytes >= byteLimit;
- }
-
- protected boolean isCommandsFull(int id)
- {
- return id - maxComplete >= commands.length;
- }
-
- public void invoke(Method m)
- {
- invoke(m,(Runnable)null);
- }
-
- public void invoke(Method m, Runnable postIdSettingAction)
- {
- if (m.getEncodedTrack() == Frame.L4)
- {
-
- if (state == DETACHED && transacted)
- {
- state = CLOSED;
- delegate.closed(this);
- connection.removeSession(this);
- throw new SessionException(
- "Session failed over, possibly in the middle of a transaction. " +
- "Closing the session. Any Transaction in progress will be rolledback.");
- }
-
- if (m.hasPayload())
- {
- acquireCredit();
- }
-
- synchronized (commands)
- {
- if (state == DETACHED && m.isUnreliable())
- {
- Thread current = Thread.currentThread();
- if (!current.equals(resumer))
- {
- return;
- }
- }
-
- if (state != OPEN && state != CLOSED && state != CLOSING)
- {
- Thread current = Thread.currentThread();
- if (!current.equals(resumer))
- {
- Waiter w = new Waiter(commands, timeout);
- while (w.hasTime() && (state != OPEN && state != CLOSED))
- {
- w.await();
- }
- }
- }
-
- switch (state)
- {
- case OPEN:
- break;
- case RESUMING:
- Thread current = Thread.currentThread();
- if (!current.equals(resumer))
- {
- throw new SessionException
- ("timed out waiting for resume to finish");
- }
- break;
- case CLOSING:
- case CLOSED:
- ExecutionException exc = getException();
- if (exc != null)
- {
- throw new SessionException(exc);
- }
- else
- {
- throw new SessionClosedException();
- }
- default:
- throw new SessionException
- (String.format
- ("timed out waiting for session to become open " +
- "(state=%s)", state));
- }
-
- int next;
- next = commandsOut++;
- m.setId(next);
- if(postIdSettingAction != null)
- {
- postIdSettingAction.run();
- }
-
- if (isFull(next))
- {
- Waiter w = new Waiter(commands, timeout);
- while (w.hasTime() && isFull(next) && state != CLOSED)
- {
- if (state == OPEN || state == RESUMING)
- {
- try
- {
- sessionFlush(COMPLETED);
- }
- catch (SenderException e)
- {
- if (!closing)
- {
- // if expiry is > 0 then this will
- // happen again on resume
- log.error(e, "error sending flush (full replay buffer)");
- }
- else
- {
- e.rethrow();
- }
- }
- }
- w.await();
- }
- }
-
- if (state == CLOSED)
- {
- ExecutionException exc = getException();
- if (exc != null)
- {
- throw new SessionException(exc);
- }
- else
- {
- throw new SessionClosedException();
- }
- }
-
- if (isFull(next))
- {
- throw new SessionException("timed out waiting for completion");
- }
-
- if (next == 0)
- {
- sessionCommandPoint(0, 0);
- }
-
- boolean replayTransfer = !closing && !transacted &&
- m instanceof MessageTransfer &&
- ! m.isUnreliable();
-
- if ((replayTransfer) || m.hasCompletionListener())
- {
- commands[mod(next, commands.length)] = m;
- commandBytes += m.getBodySize();
- }
- if (autoSync)
- {
- m.setSync(true);
- }
- needSync = !m.isSync();
-
- try
- {
- send(m);
- }
- catch (SenderException e)
- {
- if (!closing)
- {
- // if we are not closing then this will happen
- // again on resume
- log.error(e, "error sending command");
- }
- else
- {
- e.rethrow();
- }
- }
- if (autoSync)
- {
- sync();
- }
-
- // flush every 64K commands to avoid ambiguity on
- // wraparound
- if (shouldIssueFlush(next))
- {
- try
- {
- sessionFlush(COMPLETED);
- }
- catch (SenderException e)
- {
- if (!closing)
- {
- // if expiry is > 0 then this will happen
- // again on resume
- log.error(e, "error sending flush (periodic)");
- }
- else
- {
- e.rethrow();
- }
- }
- }
- }
- }
- else
- {
- send(m);
- }
- }
-
- protected boolean shouldIssueFlush(int next)
- {
- return (next % 65536) == 0;
- }
-
- public void sync()
- {
- sync(timeout);
- }
-
- public void sync(long timeout)
- {
- log.debug("%s sync()", this);
- synchronized (commands)
- {
- int point = commandsOut - 1;
-
- if (needSync && lt(maxComplete, point))
- {
- executionSync(SYNC);
- }
-
- Waiter w = new Waiter(commands, timeout);
- while (w.hasTime() && state != CLOSED && lt(maxComplete, point))
- {
- log.debug("%s waiting for[%d]: %d, %s", this, point, maxComplete, commands);
- w.await();
- }
-
- if (lt(maxComplete, point))
- {
- if (state != CLOSED)
- {
- throw new SessionException(
- String.format("timed out waiting for sync: complete = %s, point = %s",
- maxComplete, point));
- }
- else
- {
- ExecutionException ee = getException();
- if (ee != null)
- {
- throw new SessionException(ee);
- }
- }
- }
- }
- }
-
- private Map<Integer,ResultFuture<?>> results = new HashMap<Integer,ResultFuture<?>>();
- private ExecutionException exception = null;
-
- void result(int command, Struct result)
- {
- ResultFuture<?> future;
- synchronized (results)
- {
- future = results.remove(command);
- }
-
- if (future != null)
- {
- future.set(result);
- }
- else
- {
- log.warn("Received a response to a command" +
- " that's no longer valid on the client side." +
- " [ command id : %s , result : %s ]",command, result);
- }
- }
-
- void setException(ExecutionException exc)
- {
- synchronized (results)
- {
- if (exception != null)
- {
- throw new IllegalStateException(
- String.format("too many exceptions: %s, %s", exception, exc));
- }
- exception = exc;
- }
- }
-
- private ConnectionClose close = null;
-
- void closeCode(ConnectionClose close)
- {
- this.close = close;
- }
-
- ExecutionException getException()
- {
- synchronized (results)
- {
- return exception;
- }
- }
-
- protected <T> Future<T> invoke(Method m, Class<T> klass)
- {
- synchronized (commands)
- {
- int command = commandsOut;
- ResultFuture<T> future = new ResultFuture<T>(klass);
- synchronized (results)
- {
- results.put(command, future);
- }
- invoke(m);
- return future;
- }
- }
-
- private class ResultFuture<T> implements Future<T>
- {
-
- private final Class<T> klass;
- private T result;
-
- private ResultFuture(Class<T> klass)
- {
- this.klass = klass;
- }
-
- private void set(Struct result)
- {
- synchronized (this)
- {
- this.result = klass.cast(result);
- notifyAll();
- }
- }
-
- public T get(long timeout)
- {
- synchronized (this)
- {
- Waiter w = new Waiter(this, timeout);
- while (w.hasTime() && state != CLOSED && !isDone())
- {
- log.debug("%s waiting for result: %s", Session.this, this);
- w.await();
- }
- }
-
- if (isDone())
- {
- return result;
- }
- else if (state == CLOSED)
- {
- throw new SessionException(getException());
- }
- else
- {
- throw new SessionException(
- String.format("%s timed out waiting for result: %s",
- Session.this, this));
- }
- }
-
- public T get()
- {
- return get(timeout);
- }
-
- public boolean isDone()
- {
- return result != null;
- }
-
- public String toString()
- {
- return String.format("Future(%s)", isDone() ? result : klass);
- }
-
- }
-
- public final void messageTransfer(String destination,
- MessageAcceptMode acceptMode,
- MessageAcquireMode acquireMode,
- Header header,
- byte[] body,
- Option ... _options) {
- messageTransfer(destination, acceptMode, acquireMode, header,
- ByteBuffer.wrap(body), _options);
- }
-
- public final void messageTransfer(String destination,
- MessageAcceptMode acceptMode,
- MessageAcquireMode acquireMode,
- Header header,
- String body,
- Option ... _options) {
- messageTransfer(destination, acceptMode, acquireMode, header,
- toUTF8(body), _options);
- }
-
- public void close()
- {
- synchronized (commands)
- {
- state = CLOSING;
- setClose(true);
- sessionRequestTimeout(0);
- sessionDetach(name.getBytes());
-
- awaitClose();
-
-
- }
- }
-
- protected void awaitClose()
- {
- Waiter w = new Waiter(commands, timeout);
- while (w.hasTime() && state != CLOSED)
- {
- w.await();
- }
-
- if (state != CLOSED)
- {
- throw new SessionException("close() timed out");
- }
- }
-
- public void exception(Throwable t)
- {
- log.error(t, "caught exception");
- }
-
- public void closed()
- {
- synchronized (commands)
- {
- if (closing || getException() != null)
- {
- state = CLOSED;
- }
- else
- {
- state = DETACHED;
- }
-
- commands.notifyAll();
-
- synchronized (results)
- {
- for (ResultFuture<?> result : results.values())
- {
- synchronized(result)
- {
- result.notifyAll();
- }
- }
- }
- if(state == CLOSED)
- {
- delegate.closed(this);
- }
- else
- {
- delegate.detached(this);
- }
- }
-
- if(state == CLOSED)
- {
- connection.removeSession(this);
- listener.closed(this);
- }
- }
-
- public boolean isClosing()
- {
- return state == CLOSED || state == CLOSING;
- }
-
- public String toString()
- {
- return String.format("ssn:%s", name);
- }
-
- public void setTransacted(boolean b) {
- this.transacted = b;
- }
-
- public boolean isTransacted(){
- return transacted;
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/SessionClosedException.java b/java/common/src/main/java/org/apache/qpid/transport/SessionClosedException.java
deleted file mode 100644
index 64f9039484..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/SessionClosedException.java
+++ /dev/null
@@ -1,49 +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.transport;
-
-import java.util.Collections;
-
-
-/**
- * SessionClosedException
- *
- */
-
-public class SessionClosedException extends SessionException
-{
-
- public SessionClosedException()
- {
- this(null);
- }
-
- public SessionClosedException(Throwable cause)
- {
- super("session closed", null, cause);
- }
-
- @Override public void rethrow()
- {
- throw new SessionClosedException(this);
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/SessionDelegate.java b/java/common/src/main/java/org/apache/qpid/transport/SessionDelegate.java
deleted file mode 100644
index 9a02961dc4..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/SessionDelegate.java
+++ /dev/null
@@ -1,212 +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.transport;
-
-import org.apache.qpid.transport.util.Logger;
-
-
-/**
- * SessionDelegate
- *
- * @author Rafael H. Schloming
- */
-
-public class SessionDelegate
- extends MethodDelegate<Session>
- implements ProtocolDelegate<Session>
-{
- protected static final Logger log = Logger.get(SessionDelegate.class);
-
- public void init(Session ssn, ProtocolHeader hdr)
- {
- log.warn("INIT: [%s] %s", ssn, hdr);
- }
-
- public void control(Session ssn, Method method)
- {
- method.dispatch(ssn, this);
- }
-
- public void command(Session ssn, Method method) {
- ssn.identify(method);
- method.dispatch(ssn, this);
- if (!method.hasPayload())
- {
- ssn.processed(method);
- }
- }
-
- public void error(Session ssn, ProtocolError error)
- {
- log.warn("ERROR: [%s] %s", ssn, error);
- }
-
- public void handle(Session ssn, Method method)
- {
- log.warn("UNHANDLED: [%s] %s", ssn, method);
- }
-
- @Override public void sessionRequestTimeout(Session ssn, SessionRequestTimeout t)
- {
- if (t.getTimeout() == 0)
- {
- ssn.setClose(true);
- }
- ssn.sessionTimeout(0); // Always report back an expiry of 0 until it is implemented
- }
-
- @Override public void sessionAttached(Session ssn, SessionAttached atc)
- {
- ssn.setState(Session.State.OPEN);
- }
-
- @Override public void sessionTimeout(Session ssn, SessionTimeout t)
- {
- // Setting of expiry is not implemented
- }
-
- @Override public void sessionCompleted(Session ssn, SessionCompleted cmp)
- {
- RangeSet ranges = cmp.getCommands();
- RangeSet known = null;
- if (cmp.getTimelyReply())
- {
- known = new RangeSet();
- }
-
- if (ranges != null)
- {
- for (Range range : ranges)
- {
- boolean advanced = ssn.complete(range.getLower(), range.getUpper());
- if (advanced && known != null)
- {
- known.add(range);
- }
- }
- }
-
- if (known != null)
- {
- ssn.sessionKnownCompleted(known);
- }
- }
-
- @Override public void sessionKnownCompleted(Session ssn, SessionKnownCompleted kcmp)
- {
- RangeSet kc = kcmp.getCommands();
- if (kc != null)
- {
- ssn.knownComplete(kc);
- }
- }
-
- @Override public void sessionFlush(Session ssn, SessionFlush flush)
- {
- if (flush.getCompleted())
- {
- ssn.flushProcessed();
- }
- if (flush.getConfirmed())
- {
- ssn.flushProcessed();
- }
- if (flush.getExpected())
- {
- ssn.flushExpected();
- }
- }
-
- @Override public void sessionCommandPoint(Session ssn, SessionCommandPoint scp)
- {
- ssn.commandPoint(scp.getCommandId());
- }
-
- @Override public void executionSync(Session ssn, ExecutionSync sync)
- {
- ssn.syncPoint();
- }
-
- @Override public void executionResult(Session ssn, ExecutionResult result)
- {
- ssn.result(result.getCommandId(), result.getValue());
- }
-
- @Override public void executionException(Session ssn, ExecutionException exc)
- {
- ssn.setException(exc);
- ssn.getSessionListener().exception(ssn, new SessionException(exc));
- ssn.closed();
- }
-
- @Override public void messageTransfer(Session ssn, MessageTransfer xfr)
- {
- ssn.getSessionListener().message(ssn, xfr);
- }
-
- @Override public void messageSetFlowMode(Session ssn, MessageSetFlowMode sfm)
- {
- if ("".equals(sfm.getDestination()) &&
- MessageFlowMode.CREDIT.equals(sfm.getFlowMode()))
- {
- ssn.setFlowControl(true);
- }
- else
- {
- super.messageSetFlowMode(ssn, sfm);
- }
- }
-
- @Override public void messageFlow(Session ssn, MessageFlow flow)
- {
- if ("".equals(flow.getDestination()) &&
- MessageCreditUnit.MESSAGE.equals(flow.getUnit()))
- {
- ssn.addCredit((int) flow.getValue());
- }
- else
- {
- super.messageFlow(ssn, flow);
- }
- }
-
- @Override public void messageStop(Session ssn, MessageStop stop)
- {
- if ("".equals(stop.getDestination()))
- {
- ssn.drainCredit();
- }
- else
- {
- super.messageStop(ssn, stop);
- }
- }
-
- public void closed(Session session)
- {
- log.debug("CLOSED: [%s]", session);
- }
-
- public void detached(Session session)
- {
- log.debug("DETACHED: [%s]", session);
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/SessionException.java b/java/common/src/main/java/org/apache/qpid/transport/SessionException.java
deleted file mode 100644
index c4fc9558a1..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/SessionException.java
+++ /dev/null
@@ -1,61 +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.transport;
-
-import java.util.List;
-
-/**
- * SessionException
- *
- */
-
-public class SessionException extends TransportException
-{
-
- private ExecutionException exception;
-
- public SessionException(String message, ExecutionException exception, Throwable cause)
- {
- super(message, cause);
- this.exception = exception;
- }
-
- public SessionException(ExecutionException exception)
- {
- this(String.valueOf(exception), exception, null);
- }
-
- public SessionException(String message)
- {
- this(message, null, null);
- }
-
- public ExecutionException getException()
- {
- return exception;
- }
-
- @Override public void rethrow()
- {
- throw new SessionException(getMessage(), exception, this);
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/SessionListener.java b/java/common/src/main/java/org/apache/qpid/transport/SessionListener.java
deleted file mode 100644
index eb650eb9ed..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/SessionListener.java
+++ /dev/null
@@ -1,42 +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.transport;
-
-
-/**
- * SessionListener
- *
- */
-
-public interface SessionListener
-{
-
- void opened(Session session);
-
- void resumed(Session session);
-
- void message(Session ssn, MessageTransfer xfr);
-
- void exception(Session session, SessionException exception);
-
- void closed(Session session);
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/Struct.java b/java/common/src/main/java/org/apache/qpid/transport/Struct.java
deleted file mode 100644
index 22bd9f34ad..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/Struct.java
+++ /dev/null
@@ -1,142 +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.transport;
-
-import java.util.List;
-import java.util.Map;
-
-import org.apache.qpid.transport.codec.Decoder;
-import org.apache.qpid.transport.codec.Encodable;
-import org.apache.qpid.transport.codec.Encoder;
-
-
-/**
- * Struct
- *
- * @author Rafael H. Schloming
- */
-
-public abstract class Struct implements Encodable
-{
-
- public static Struct create(int type)
- {
- return StructFactory.create(type);
- }
-
- boolean dirty = true;
-
- public boolean isDirty()
- {
- return dirty;
- }
-
- public void setDirty(boolean dirty)
- {
- this.dirty = dirty;
- }
-
- public abstract int getStructType();
-
- public abstract int getSizeWidth();
-
- public abstract int getPackWidth();
-
- public final int getEncodedType()
- {
- int type = getStructType();
- if (type < 0)
- {
- throw new UnsupportedOperationException();
- }
- return type;
- }
-
- private final boolean isBit(Field<?,?> f)
- {
- return f.getType().equals(Boolean.class);
- }
-
- private final boolean packed()
- {
- return getPackWidth() > 0;
- }
-
- private final boolean encoded(Field<?,?> f)
- {
- return !packed() || !isBit(f) && f.has(this);
- }
-
- private final int getFlagWidth()
- {
- return (getFields().size() + 7)/8;
- }
-
- private final int getPaddWidth()
- {
- int pw = getPackWidth() - getFlagWidth();
- assert pw > 0;
- return pw;
- }
-
- private final int getFlagCount()
- {
- return 8*getPackWidth();
- }
-
- private final int getReservedFlagCount()
- {
- return getFlagCount() - getFields().size();
- }
-
- public abstract void read(Decoder dec);
-
- public abstract void write(Encoder enc);
-
- public abstract Map<String,Object> getFields();
-
- public String toString()
- {
- StringBuilder str = new StringBuilder();
- str.append(getClass().getSimpleName());
-
- str.append("(");
- boolean first = true;
- for (Map.Entry<String,Object> me : getFields().entrySet())
- {
- if (first)
- {
- first = false;
- }
- else
- {
- str.append(", ");
- }
- str.append(me.getKey());
- str.append("=");
- str.append(me.getValue());
- }
- str.append(")");
-
- return str.toString();
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/TransportBuilder.java b/java/common/src/main/java/org/apache/qpid/transport/TransportBuilder.java
deleted file mode 100644
index c08909c6e4..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/TransportBuilder.java
+++ /dev/null
@@ -1,78 +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.transport;
-
-import java.nio.ByteBuffer;
-
-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.NetworkTransport;
-import org.apache.qpid.transport.network.Transport;
-import org.apache.qpid.transport.network.security.SecurityLayer;
-
-public class TransportBuilder
-{
- private Connection con;
- private ConnectionSettings settings;
- private NetworkTransport transport;
- private SecurityLayer securityLayer = new SecurityLayer();
-
- public void init(Connection con) throws TransportException
- {
- this.con = con;
- this.settings = con.getConnectionSettings();
- transport = Transport.getTransport();
- transport.init(settings);
- securityLayer.init(con);
- }
-
- public Sender<ProtocolEvent> buildSenderPipe()
- {
- ConnectionSettings settings = con.getConnectionSettings();
-
- // Io layer
- Sender<ByteBuffer> sender = transport.sender();
-
- // Security layer
- sender = securityLayer.sender(sender);
-
- Disassembler dis = new Disassembler(sender, settings.getMaxFrameSize());
- return dis;
- }
-
- public void buildReceiverPipe(Receiver<ProtocolEvent> delegate)
- {
- Receiver<ByteBuffer> receiver = new InputHandler(new Assembler(delegate));
-
- // Security layer
- receiver = securityLayer.receiver(receiver);
-
- //Io layer
- transport.receiver(receiver);
- }
-
- public SecurityLayer getSecurityLayer()
- {
- return securityLayer;
- }
-
-} \ No newline at end of file
diff --git a/java/common/src/main/java/org/apache/qpid/transport/TransportException.java b/java/common/src/main/java/org/apache/qpid/transport/TransportException.java
deleted file mode 100644
index 0de190dfad..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/TransportException.java
+++ /dev/null
@@ -1,51 +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.transport;
-
-
-/**
- * TransportException
- */
-
-public class TransportException extends RuntimeException
-{
-
- public TransportException(String msg)
- {
- super(msg);
- }
-
- public TransportException(String msg, Throwable cause)
- {
- super(msg, cause);
- }
-
- public TransportException(Throwable cause)
- {
- super(cause);
- }
-
- public void rethrow()
- {
- throw new TransportException(getMessage(), this);
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/codec/AbstractDecoder.java b/java/common/src/main/java/org/apache/qpid/transport/codec/AbstractDecoder.java
deleted file mode 100644
index 09ce6a7eb1..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/codec/AbstractDecoder.java
+++ /dev/null
@@ -1,478 +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.transport.codec;
-
-import java.io.UnsupportedEncodingException;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.UUID;
-
-import org.apache.qpid.transport.Binary;
-import org.apache.qpid.transport.RangeSet;
-import org.apache.qpid.transport.Struct;
-import org.apache.qpid.transport.Type;
-
-import static org.apache.qpid.transport.util.Functions.*;
-
-
-/**
- * AbstractDecoder
- *
- * @author Rafael H. Schloming
- */
-
-abstract class AbstractDecoder implements Decoder
-{
-
- private final Map<Binary,String> str8cache = new LinkedHashMap<Binary,String>()
- {
- @Override protected boolean removeEldestEntry(Map.Entry<Binary,String> me)
- {
- return size() > 4*1024;
- }
- };
-
- protected abstract byte doGet();
-
- protected abstract void doGet(byte[] bytes);
-
- protected byte get()
- {
- return doGet();
- }
-
- protected void get(byte[] bytes)
- {
- doGet(bytes);
- }
-
- protected Binary get(int size)
- {
- byte[] bytes = new byte[size];
- get(bytes);
- return new Binary(bytes);
- }
-
- protected short uget()
- {
- return (short) (0xFF & get());
- }
-
- public short readUint8()
- {
- return uget();
- }
-
- public int readUint16()
- {
- int i = uget() << 8;
- i |= uget();
- return i;
- }
-
- public long readUint32()
- {
- long l = uget() << 24;
- l |= uget() << 16;
- l |= uget() << 8;
- l |= uget();
- return l;
- }
-
- public int readSequenceNo()
- {
- return (int) readUint32();
- }
-
- public long readUint64()
- {
- long l = 0;
- for (int i = 0; i < 8; i++)
- {
- l |= ((long) (0xFF & get())) << (56 - i*8);
- }
- return l;
- }
-
- public long readDatetime()
- {
- return readUint64();
- }
-
- private static final String decode(byte[] bytes, int offset, int length, String charset)
- {
- try
- {
- return new String(bytes, offset, length, charset);
- }
- catch (UnsupportedEncodingException e)
- {
- throw new RuntimeException(e);
- }
- }
-
- private static final String decode(byte[] bytes, String charset)
- {
- return decode(bytes, 0, bytes.length, charset);
- }
-
- public String readStr8()
- {
- short size = readUint8();
- Binary bin = get(size);
- String str = str8cache.get(bin);
-
- if (str == null)
- {
- str = decode(bin.array(), bin.offset(), bin.size(), "UTF-8");
- if(bin.hasExcessCapacity())
- {
- str8cache.put(bin.copy(), str);
- }
- else
- {
- str8cache.put(bin, str);
- }
- }
- return str;
- }
-
- public String readStr16()
- {
- int size = readUint16();
- byte[] bytes = new byte[size];
- get(bytes);
- return decode(bytes, "UTF-8");
- }
-
- public byte[] readVbin8()
- {
- int size = readUint8();
- byte[] bytes = new byte[size];
- get(bytes);
- return bytes;
- }
-
- public byte[] readVbin16()
- {
- int size = readUint16();
- byte[] bytes = new byte[size];
- get(bytes);
- return bytes;
- }
-
- public byte[] readVbin32()
- {
- int size = (int) readUint32();
- byte[] bytes = new byte[size];
- get(bytes);
- return bytes;
- }
-
- public RangeSet readSequenceSet()
- {
- int count = readUint16()/8;
- if (count == 0)
- {
- return null;
- }
- else
- {
- RangeSet ranges = new RangeSet();
- for (int i = 0; i < count; i++)
- {
- ranges.add(readSequenceNo(), readSequenceNo());
- }
- return ranges;
- }
- }
-
- public RangeSet readByteRanges()
- {
- throw new Error("not implemented");
- }
-
- public UUID readUuid()
- {
- long msb = readUint64();
- long lsb = readUint64();
- return new UUID(msb, lsb);
- }
-
- public String readContent()
- {
- throw new Error("Deprecated");
- }
-
- public Struct readStruct(int type)
- {
- Struct st = Struct.create(type);
- int width = st.getSizeWidth();
- if (width > 0)
- {
- long size = readSize(width);
- if (size == 0)
- {
- return null;
- }
- }
- if (type > 0)
- {
- int code = readUint16();
- assert code == type;
- }
- st.read(this);
- return st;
- }
-
- public Struct readStruct32()
- {
- long size = readUint32();
- if (size == 0)
- {
- return null;
- }
- else
- {
- int type = readUint16();
- Struct result = Struct.create(type);
- result.read(this);
- return result;
- }
- }
-
- public Map<String,Object> readMap()
- {
- long size = readUint32();
-
- if (size == 0)
- {
- return null;
- }
-
- long count = readUint32();
-
- if (count == 0)
- {
- return Collections.EMPTY_MAP;
- }
-
- Map<String,Object> result = new LinkedHashMap();
- for (int i = 0; i < count; i++)
- {
- String key = readStr8();
- byte code = get();
- Type t = getType(code);
- Object value = read(t);
- result.put(key, value);
- }
-
- return result;
- }
-
- public List<Object> readList()
- {
- long size = readUint32();
-
- if (size == 0)
- {
- return null;
- }
-
- long count = readUint32();
-
- if (count == 0)
- {
- return Collections.EMPTY_LIST;
- }
-
- List<Object> result = new ArrayList();
- for (int i = 0; i < count; i++)
- {
- byte code = get();
- Type t = getType(code);
- Object value = read(t);
- result.add(value);
- }
- return result;
- }
-
- public List<Object> readArray()
- {
- long size = readUint32();
-
- if (size == 0)
- {
- return null;
- }
-
- byte code = get();
- Type t = getType(code);
- long count = readUint32();
-
- if (count == 0)
- {
- return Collections.EMPTY_LIST;
- }
-
- List<Object> result = new ArrayList<Object>();
- for (int i = 0; i < count; i++)
- {
- Object value = read(t);
- result.add(value);
- }
- return result;
- }
-
- private Type getType(byte code)
- {
- Type type = Type.get(code);
- if (type == null)
- {
- throw new IllegalArgumentException("unknown code: " + code);
- }
- else
- {
- return type;
- }
- }
-
- private long readSize(Type t)
- {
- if (t.fixed)
- {
- return t.width;
- }
- else
- {
- return readSize(t.width);
- }
- }
-
- private long readSize(int width)
- {
- switch (width)
- {
- case 1:
- return readUint8();
- case 2:
- return readUint16();
- case 4:
- return readUint32();
- default:
- throw new IllegalStateException("illegal width: " + width);
- }
- }
-
- private byte[] readBytes(Type t)
- {
- long size = readSize(t);
- byte[] result = new byte[(int) size];
- get(result);
- return result;
- }
-
- private Object read(Type t)
- {
- switch (t)
- {
- case BIN8:
- case UINT8:
- return readUint8();
- case INT8:
- return get();
- case CHAR:
- return (char) get();
- case BOOLEAN:
- return get() > 0;
-
- case BIN16:
- case UINT16:
- return readUint16();
-
- case INT16:
- return (short) readUint16();
-
- case BIN32:
- case UINT32:
- return readUint32();
-
- case CHAR_UTF32:
- case INT32:
- return (int) readUint32();
-
- case FLOAT:
- return Float.intBitsToFloat((int) readUint32());
-
- case BIN64:
- case UINT64:
- case INT64:
- case DATETIME:
- return readUint64();
-
- case DOUBLE:
- return Double.longBitsToDouble(readUint64());
-
- case UUID:
- return readUuid();
-
- case STR8:
- return readStr8();
-
- case STR16:
- return readStr16();
-
- case STR8_LATIN:
- case STR8_UTF16:
- case STR16_LATIN:
- case STR16_UTF16:
- // XXX: need to do character conversion
- return new String(readBytes(t));
-
- case MAP:
- return readMap();
- case LIST:
- return readList();
- case ARRAY:
- return readArray();
- case STRUCT32:
- return readStruct32();
-
- case BIN40:
- case DEC32:
- case BIN72:
- case DEC64:
- // XXX: what types are we supposed to use here?
- return readBytes(t);
-
- case VOID:
- return null;
-
- default:
- return readBytes(t);
- }
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/codec/AbstractEncoder.java b/java/common/src/main/java/org/apache/qpid/transport/codec/AbstractEncoder.java
deleted file mode 100644
index 0ccfcfcb70..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/codec/AbstractEncoder.java
+++ /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.
- *
- */
-package org.apache.qpid.transport.codec;
-
-import java.io.UnsupportedEncodingException;
-
-import java.nio.ByteBuffer;
-
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.UUID;
-
-import org.apache.qpid.transport.Range;
-import org.apache.qpid.transport.RangeSet;
-import org.apache.qpid.transport.Struct;
-import org.apache.qpid.transport.Type;
-
-import static org.apache.qpid.transport.util.Functions.*;
-
-
-/**
- * AbstractEncoder
- *
- * @author Rafael H. Schloming
- */
-
-abstract class AbstractEncoder implements Encoder
-{
-
- private static Map<Class<?>,Type> ENCODINGS = new HashMap<Class<?>,Type>();
- static
- {
- ENCODINGS.put(Boolean.class, Type.BOOLEAN);
- ENCODINGS.put(String.class, Type.STR16);
- ENCODINGS.put(Long.class, Type.INT64);
- ENCODINGS.put(Integer.class, Type.INT32);
- ENCODINGS.put(Short.class, Type.INT16);
- ENCODINGS.put(Byte.class, Type.INT8);
- ENCODINGS.put(Map.class, Type.MAP);
- ENCODINGS.put(List.class, Type.LIST);
- ENCODINGS.put(Float.class, Type.FLOAT);
- ENCODINGS.put(Double.class, Type.DOUBLE);
- ENCODINGS.put(Character.class, Type.CHAR);
- ENCODINGS.put(byte[].class, Type.VBIN32);
- ENCODINGS.put(UUID.class, Type.UUID);
- }
-
- private final Map<String,byte[]> str8cache = new LinkedHashMap<String,byte[]>()
- {
- @Override protected boolean removeEldestEntry(Map.Entry<String,byte[]> me)
- {
- return size() > 4*1024;
- }
- };
-
- protected abstract void doPut(byte b);
-
- protected abstract void doPut(ByteBuffer src);
-
- protected void put(byte b)
- {
- doPut(b);
- }
-
- protected void put(ByteBuffer src)
- {
- doPut(src);
- }
-
- protected void put(byte[] bytes)
- {
- put(ByteBuffer.wrap(bytes));
- }
-
- protected abstract int beginSize8();
- protected abstract void endSize8(int pos);
-
- protected abstract int beginSize16();
- protected abstract void endSize16(int pos);
-
- protected abstract int beginSize32();
- protected abstract void endSize32(int pos);
-
- public void writeUint8(short b)
- {
- assert b < 0x100;
-
- put((byte) b);
- }
-
- public void writeUint16(int s)
- {
- assert s < 0x10000;
-
- put(lsb(s >>> 8));
- put(lsb(s));
- }
-
- public void writeUint32(long i)
- {
- assert i < 0x100000000L;
-
- put(lsb(i >>> 24));
- put(lsb(i >>> 16));
- put(lsb(i >>> 8));
- put(lsb(i));
- }
-
- public void writeSequenceNo(int i)
- {
- writeUint32(i);
- }
-
- public void writeUint64(long l)
- {
- for (int i = 0; i < 8; i++)
- {
- put(lsb(l >> (56 - i*8)));
- }
- }
-
-
- public void writeDatetime(long l)
- {
- writeUint64(l);
- }
-
- private static final byte[] encode(String s, String charset)
- {
- try
- {
- return s.getBytes(charset);
- }
- catch (UnsupportedEncodingException e)
- {
- throw new RuntimeException(e);
- }
- }
-
- public void writeStr8(String s)
- {
- if (s == null)
- {
- s = "";
- }
-
- byte[] bytes = str8cache.get(s);
- if (bytes == null)
- {
- bytes = encode(s, "UTF-8");
- str8cache.put(s, bytes);
- }
- writeUint8((short) bytes.length);
- put(bytes);
- }
-
- public void writeStr16(String s)
- {
- if (s == null)
- {
- s = "";
- }
-
- byte[] bytes = encode(s, "UTF-8");
- writeUint16(bytes.length);
- put(bytes);
- }
-
- public void writeVbin8(byte[] bytes)
- {
- if (bytes == null) { bytes = new byte[0]; }
- if (bytes.length > 255)
- {
- throw new IllegalArgumentException("array too long: " + bytes.length);
- }
- writeUint8((short) bytes.length);
- put(ByteBuffer.wrap(bytes));
- }
-
- public void writeVbin16(byte[] bytes)
- {
- if (bytes == null) { bytes = new byte[0]; }
- writeUint16(bytes.length);
- put(ByteBuffer.wrap(bytes));
- }
-
- public void writeVbin32(byte[] bytes)
- {
- if (bytes == null) { bytes = new byte[0]; }
- writeUint32(bytes.length);
- put(ByteBuffer.wrap(bytes));
- }
-
- public void writeSequenceSet(RangeSet ranges)
- {
- if (ranges == null)
- {
- writeUint16((short) 0);
- }
- else
- {
- writeUint16(ranges.size() * 8);
- for (Range range : ranges)
- {
- writeSequenceNo(range.getLower());
- writeSequenceNo(range.getUpper());
- }
- }
- }
-
- public void writeByteRanges(RangeSet ranges)
- {
- throw new Error("not implemented");
- }
-
- public void writeUuid(UUID uuid)
- {
- long msb = 0;
- long lsb = 0;
- if (uuid != null)
- {
- msb = uuid.getMostSignificantBits();
- lsb = uuid.getLeastSignificantBits();
- }
- writeUint64(msb);
- writeUint64(lsb);
- }
-
- public void writeStruct(int type, Struct s)
- {
- boolean empty = false;
- if (s == null)
- {
- s = Struct.create(type);
- empty = true;
- }
-
- int width = s.getSizeWidth();
- int pos = -1;
- if (width > 0)
- {
- pos = beginSize(width);
- }
-
- if (type > 0)
- {
- writeUint16(type);
- }
-
- s.write(this);
-
- if (width > 0)
- {
- endSize(width, pos);
- }
- }
-
- public void writeStruct32(Struct s)
- {
- if (s == null)
- {
- writeUint32(0);
- }
- else
- {
- int pos = beginSize32();
- writeUint16(s.getEncodedType());
- s.write(this);
- endSize32(pos);
- }
- }
-
- private Type encoding(Object value)
- {
- if (value == null)
- {
- return Type.VOID;
- }
-
- Class klass = value.getClass();
- Type type = resolve(klass);
-
- if (type == null)
- {
- throw new IllegalArgumentException
- ("unable to resolve type: " + klass + ", " + value);
- }
- else
- {
- return type;
- }
- }
-
- static final Type resolve(Class klass)
- {
- Type type = ENCODINGS.get(klass);
- if (type != null)
- {
- return type;
- }
-
- Class sup = klass.getSuperclass();
- if (sup != null)
- {
- type = resolve(klass.getSuperclass());
-
- if (type != null)
- {
- return type;
- }
- }
-
- for (Class iface : klass.getInterfaces())
- {
- type = resolve(iface);
- if (type != null)
- {
- return type;
- }
- }
-
- return null;
- }
-
- public void writeMap(Map<String,Object> map)
- {
- int pos = beginSize32();
- if (map != null)
- {
- writeUint32(map.size());
- writeMapEntries(map);
- }
- endSize32(pos);
- }
-
- protected void writeMapEntries(Map<String,Object> map)
- {
- for (Map.Entry<String,Object> entry : map.entrySet())
- {
- String key = entry.getKey();
- Object value = entry.getValue();
- Type type = encoding(value);
- writeStr8(key);
- put(type.code);
- write(type, value);
- }
- }
-
- public void writeList(List<Object> list)
- {
- int pos = beginSize32();
- if (list != null)
- {
- writeUint32(list.size());
- writeListEntries(list);
- }
- endSize32(pos);
- }
-
- protected void writeListEntries(List<Object> list)
- {
- for (Object value : list)
- {
- Type type = encoding(value);
- put(type.code);
- write(type, value);
- }
- }
-
- public void writeArray(List<Object> array)
- {
- int pos = beginSize32();
- if (array != null)
- {
- writeArrayEntries(array);
- }
- endSize32(pos);
- }
-
- protected void writeArrayEntries(List<Object> array)
- {
- Type type;
-
- if (array.isEmpty())
- {
- return;
- }
- else
- {
- type = encoding(array.get(0));
- }
-
- put(type.code);
-
- writeUint32(array.size());
-
- for (Object value : array)
- {
- write(type, value);
- }
- }
-
- private void writeSize(Type t, int size)
- {
- if (t.fixed)
- {
- if (size != t.width)
- {
- throw new IllegalArgumentException
- ("size does not match fixed width " + t.width + ": " +
- size);
- }
- }
- else
- {
- writeSize(t.width, size);
- }
- }
-
- private void writeSize(int width, int size)
- {
- // XXX: should check lengths
- switch (width)
- {
- case 1:
- writeUint8((short) size);
- break;
- case 2:
- writeUint16(size);
- break;
- case 4:
- writeUint32(size);
- break;
- default:
- throw new IllegalStateException("illegal width: " + width);
- }
- }
-
- private int beginSize(int width)
- {
- switch (width)
- {
- case 1:
- return beginSize8();
- case 2:
- return beginSize16();
- case 4:
- return beginSize32();
- default:
- throw new IllegalStateException("illegal width: " + width);
- }
- }
-
- private void endSize(int width, int pos)
- {
- switch (width)
- {
- case 1:
- endSize8(pos);
- break;
- case 2:
- endSize16(pos);
- break;
- case 4:
- endSize32(pos);
- break;
- default:
- throw new IllegalStateException("illegal width: " + width);
- }
- }
-
- private void writeBytes(Type t, byte[] bytes)
- {
- writeSize(t, bytes.length);
- put(bytes);
- }
-
- private <T> T coerce(Class<T> klass, Object value)
- {
- if (klass.isInstance(value))
- {
- return klass.cast(value);
- }
- else
- {
- throw new IllegalArgumentException("" + value);
- }
- }
-
- private void write(Type t, Object value)
- {
- switch (t)
- {
- case BIN8:
- case UINT8:
- writeUint8(coerce(Short.class, value));
- break;
- case INT8:
- put(coerce(Byte.class, value));
- break;
- case CHAR:
- put((byte) ((char)coerce(Character.class, value)));
- break;
- case BOOLEAN:
- if (coerce(Boolean.class, value))
- {
- put((byte) 1);
- }
- else
- {
- put((byte) 0);
- }
- break;
-
- case BIN16:
- case UINT16:
- writeUint16(coerce(Integer.class, value));
- break;
-
- case INT16:
- writeUint16(coerce(Short.class, value));
- break;
-
- case BIN32:
- case UINT32:
- writeUint32(coerce(Long.class, value));
- break;
-
- case CHAR_UTF32:
- case INT32:
- writeUint32(coerce(Integer.class, value));
- break;
-
- case FLOAT:
- writeUint32(Float.floatToIntBits(coerce(Float.class, value)));
- break;
-
- case BIN64:
- case UINT64:
- case INT64:
- case DATETIME:
- writeUint64(coerce(Long.class, value));
- break;
-
- case DOUBLE:
- long bits = Double.doubleToLongBits(coerce(Double.class, value));
- writeUint64(bits);
- break;
-
- case UUID:
- writeUuid(coerce(UUID.class, value));
- break;
-
- case STR8:
- writeStr8(coerce(String.class, value));
- break;
-
- case STR16:
- writeStr16(coerce(String.class, value));
- break;
-
- case STR8_LATIN:
- case STR8_UTF16:
- case STR16_LATIN:
- case STR16_UTF16:
- // XXX: need to do character conversion
- writeBytes(t, coerce(String.class, value).getBytes());
- break;
-
- case MAP:
- writeMap((Map<String,Object>) coerce(Map.class, value));
- break;
- case LIST:
- writeList(coerce(List.class, value));
- break;
- case ARRAY:
- writeArray(coerce(List.class, value));
- break;
- case STRUCT32:
- writeStruct32(coerce(Struct.class, value));
- break;
-
- case BIN40:
- case DEC32:
- case BIN72:
- case DEC64:
- // XXX: what types are we supposed to use here?
- writeBytes(t, coerce(byte[].class, value));
- break;
-
- case VOID:
- break;
-
- default:
- writeBytes(t, coerce(byte[].class, value));
- break;
- }
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/codec/BBDecoder.java b/java/common/src/main/java/org/apache/qpid/transport/codec/BBDecoder.java
deleted file mode 100644
index 10f67e1cd6..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/codec/BBDecoder.java
+++ /dev/null
@@ -1,149 +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.transport.codec;
-
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-
-import org.apache.qpid.transport.Binary;
-
-/**
- * Byte Buffer Decoder.
- * Decoder concrete implementor using a backing byte buffer for decoding data.
- *
- * @author Rafael H. Schloming
- */
-public final class BBDecoder extends AbstractDecoder
-{
- private ByteBuffer in;
-
- public void init(ByteBuffer in)
- {
- this.in = in;
- this.in.order(ByteOrder.BIG_ENDIAN);
- }
-
- public void releaseBuffer()
- {
- in = null;
- }
-
- protected byte doGet()
- {
- return in.get();
- }
-
- protected void doGet(byte[] bytes)
- {
- in.get(bytes);
- }
-
- protected Binary get(int size)
- {
- if (in.hasArray())
- {
- byte[] bytes = in.array();
- Binary bin = new Binary(bytes, in.arrayOffset() + in.position(), size);
- in.position(in.position() + size);
- return bin;
- }
- else
- {
- return super.get(size);
- }
- }
-
- public boolean hasRemaining()
- {
- return in.hasRemaining();
- }
-
- public short readUint8()
- {
- return (short) (0xFF & in.get());
- }
-
- public int readUint16()
- {
- return 0xFFFF & in.getShort();
- }
-
- public long readUint32()
- {
- return 0xFFFFFFFFL & in.getInt();
- }
-
- public long readUint64()
- {
- return in.getLong();
- }
-
- public byte[] readBin128()
- {
- byte[] result = new byte[16];
- get(result);
- return result;
- }
-
- public byte[] readBytes(int howManyBytes)
- {
- byte[] result = new byte[howManyBytes];
- get(result);
- return result;
- }
-
- public double readDouble()
- {
- return in.getDouble();
- }
-
- public float readFloat()
- {
- return in.getFloat();
- }
-
- public short readInt16()
- {
- return in.getShort();
- }
-
- public int readInt32()
- {
- return in.getInt();
- }
-
- public byte readInt8()
- {
- return in.get();
- }
-
- public byte[] readReaminingBytes()
- {
- byte[] result = new byte[in.limit() - in.position()];
- get(result);
- return result;
- }
-
- public long readInt64()
- {
- return in.getLong();
- }
-} \ No newline at end of file
diff --git a/java/common/src/main/java/org/apache/qpid/transport/codec/BBEncoder.java b/java/common/src/main/java/org/apache/qpid/transport/codec/BBEncoder.java
deleted file mode 100644
index 4486b03a67..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/codec/BBEncoder.java
+++ /dev/null
@@ -1,357 +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.transport.codec;
-
-import java.nio.BufferOverflowException;
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-import java.util.UUID;
-
-
-/**
- * Byte Buffer Encoder.
- * Encoder concrete implementor using a backing byte buffer for encoding data.
- *
- * @author Rafael H. Schloming
- */
-public final class BBEncoder extends AbstractEncoder
-{
- private ByteBuffer out;
- private int segment;
-
- public BBEncoder(int capacity) {
- out = ByteBuffer.allocate(capacity);
- out.order(ByteOrder.BIG_ENDIAN);
- segment = 0;
- }
-
- public void init()
- {
- out.clear();
- segment = 0;
- }
-
- public ByteBuffer segment()
- {
- int pos = out.position();
- out.position(segment);
- ByteBuffer slice = out.slice();
- slice.limit(pos - segment);
- out.position(pos);
- segment = pos;
- return slice;
- }
-
- public ByteBuffer buffer()
- {
- int pos = out.position();
- out.position(segment);
- ByteBuffer slice = out.slice();
- slice.limit(pos - segment);
- out.position(pos);
- return slice;
- }
-
- private void grow(int size)
- {
- ByteBuffer old = out;
- int capacity = old.capacity();
- out = ByteBuffer.allocate(Math.max(capacity + size, 2*capacity));
- out.order(ByteOrder.BIG_ENDIAN);
- old.flip();
- out.put(old);
- }
-
- protected void doPut(byte b)
- {
- try
- {
- out.put(b);
- }
- catch (BufferOverflowException e)
- {
- grow(1);
- out.put(b);
- }
- }
-
- protected void doPut(ByteBuffer src)
- {
- try
- {
- out.put(src);
- }
- catch (BufferOverflowException e)
- {
- grow(src.remaining());
- out.put(src);
- }
- }
-
- protected void put(byte[] bytes)
- {
- try
- {
- out.put(bytes);
- }
- catch (BufferOverflowException e)
- {
- grow(bytes.length);
- out.put(bytes);
- }
- }
-
- public void writeUint8(short b)
- {
- assert b < 0x100;
-
- try
- {
- out.put((byte) b);
- }
- catch (BufferOverflowException e)
- {
- grow(1);
- out.put((byte) b);
- }
- }
-
- public void writeUint16(int s)
- {
- assert s < 0x10000;
-
- try
- {
- out.putShort((short) s);
- }
- catch (BufferOverflowException e)
- {
- grow(2);
- out.putShort((short) s);
- }
- }
-
- public void writeUint32(long i)
- {
- assert i < 0x100000000L;
-
- try
- {
- out.putInt((int) i);
- }
- catch (BufferOverflowException e)
- {
- grow(4);
- out.putInt((int) i);
- }
- }
-
- public void writeUint64(long l)
- {
- try
- {
- out.putLong(l);
- }
- catch (BufferOverflowException e)
- {
- grow(8);
- out.putLong(l);
- }
- }
-
- public int beginSize8()
- {
- int pos = out.position();
- try
- {
- out.put((byte) 0);
- }
- catch (BufferOverflowException e)
- {
- grow(1);
- out.put((byte) 0);
- }
- return pos;
- }
-
- public void endSize8(int pos)
- {
- int cur = out.position();
- out.put(pos, (byte) (cur - pos - 1));
- }
-
- public int beginSize16()
- {
- int pos = out.position();
- try
- {
- out.putShort((short) 0);
- }
- catch (BufferOverflowException e)
- {
- grow(2);
- out.putShort((short) 0);
- }
- return pos;
- }
-
- public void endSize16(int pos)
- {
- int cur = out.position();
- out.putShort(pos, (short) (cur - pos - 2));
- }
-
- public int beginSize32()
- {
- int pos = out.position();
- try
- {
- out.putInt(0);
- }
- catch (BufferOverflowException e)
- {
- grow(4);
- out.putInt(0);
- }
- return pos;
- }
-
- public void endSize32(int pos)
- {
- int cur = out.position();
- out.putInt(pos, (cur - pos - 4));
- }
-
- public void writeDouble(double aDouble)
- {
- try
- {
- out.putDouble(aDouble);
- } catch(BufferOverflowException exception)
- {
- grow(8);
- out.putDouble(aDouble);
- }
- }
-
- public void writeInt16(short aShort)
- {
- try
- {
- out.putShort(aShort);
- } catch(BufferOverflowException exception)
- {
- grow(2);
- out.putShort(aShort);
- }
- }
-
- public void writeInt32(int anInt)
- {
- try
- {
- out.putInt(anInt);
- } catch(BufferOverflowException exception)
- {
- grow(4);
- out.putInt(anInt);
- }
- }
-
- public void writeInt64(long aLong)
- {
- try
- {
- out.putLong(aLong);
- } catch(BufferOverflowException exception)
- {
- grow(8);
- out.putLong(aLong);
- }
- }
-
- public void writeInt8(byte aByte)
- {
- try
- {
- out.put(aByte);
- } catch(BufferOverflowException exception)
- {
- grow(1);
- out.put(aByte);
- }
- }
-
- public void writeBin128(byte[] byteArray)
- {
- byteArray = (byteArray != null) ? byteArray : new byte [16];
-
- assert byteArray.length == 16;
-
- try
- {
- out.put(byteArray);
- } catch(BufferOverflowException exception)
- {
- grow(16);
- out.put(byteArray);
- }
- }
-
- public void writeBin128(UUID id)
- {
- byte[] data = new byte[16];
-
- long msb = id.getMostSignificantBits();
- long lsb = id.getLeastSignificantBits();
-
- assert data.length == 16;
- for (int i=7; i>=0; i--)
- {
- data[i] = (byte)(msb & 0xff);
- msb = msb >> 8;
- }
-
- for (int i=15; i>=8; i--)
- {
- data[i] = (byte)(lsb & 0xff);
- lsb = (lsb >> 8);
- }
- writeBin128(data);
- }
-
- public void writeFloat(float aFloat)
- {
- try
- {
- out.putFloat(aFloat);
- } catch(BufferOverflowException exception)
- {
- grow(4);
- out.putFloat(aFloat);
- }
- }
-
- public void writeMagicNumber()
- {
- out.put("AM2".getBytes());
- }
-} \ No newline at end of file
diff --git a/java/common/src/main/java/org/apache/qpid/transport/codec/Decoder.java b/java/common/src/main/java/org/apache/qpid/transport/codec/Decoder.java
deleted file mode 100644
index a4df5b5fcb..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/codec/Decoder.java
+++ /dev/null
@@ -1,283 +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.transport.codec;
-
-import java.util.List;
-import java.util.Map;
-import java.util.UUID;
-
-import org.apache.qpid.transport.RangeSet;
-import org.apache.qpid.transport.Struct;
-
-
-/**
- * Decoder interface.
- * Each concrete implementor must specify how to decode given values.
- *
- * @author Rafael H. Schloming
- */
-public interface Decoder
-{
- /**
- * Tells whether there are any remaining byte(s) to be read.
- *
- * @return true if there are remaining bytes, false otherwise.
- */
- boolean hasRemaining();
-
- /**
- * The uint8 type is an 8-bit unsigned integral value.
- *
- * @return an 8-bit unsigned integral value.
- */
- short readUint8();
-
- /**
- *The uint16 type is a 16-bit unsigned integral value encoded in network byte order.
- *
- * @return a 16-bit unsigned integral value encoded in network byte order.
- */
- int readUint16();
-
- /**
- *The uint32 type is a 32-bit unsigned integral value encoded in network byte order.
- *
- * @return a 32-bit unsigned integral value encoded in network byte order.
- */
- long readUint32();
-
- /**
- * The uint64 type is a 64-bit unsigned integral value encoded in network byte order.
- *
- * @return a 64-bit unsigned integral value encoded in network byte order.
- */
- long readUint64();
-
- /**
- * The datetime type encodes a date and time using the 64 bit POSIX time_t format.
- *
- * @return a date and time using the 64 bit POSIX time_t format.
- */
- long readDatetime();
-
- /**
- * The uuid type encodes a universally unique id as defined by RFC-4122.
- * The format and operations for this type can be found in section 4.1.2 of RFC-4122.
- *
- * return a universally unique id as defined by RFC-4122.
- */
- UUID readUuid();
-
- /**
-// *The sequence-no type encodes, in network byte order, a serial number as defined in RFC-1982.
- *
- * @return a serial number as defined in RFC-1982.
- */
- int readSequenceNo();
-
- RangeSet readSequenceSet(); // XXX
- RangeSet readByteRanges(); // XXX
-
- /**
- * The str8 type encodes up to 255 octets worth of UTF-8 unicode.
- * The number of octets of unicode is first encoded as an 8-bit unsigned integral value.
- * This is followed by the actual UTF-8 unicode.
- * Note that the encoded size refers to the number of octets of unicode, not necessarily the number of characters since
- * the UTF-8 unicode may include multi-byte character sequences.
- *
- * @return a string.
- */
- String readStr8();
-
- /**
- * The str16 type encodes up to 65535 octets worth of UTF-8 unicode.
- * The number of octets is first encoded as a 16-bit unsigned integral value in network byte order.
- * This is followed by the actual UTF-8 unicode.
- * Note that the encoded size refers to the number of octets of unicode, not necessarily the number of unicode
- * characters since the UTF-8 unicode may include multi-byte character sequences.
- *
- * return a string.
- */
- String readStr16();
-
- /**
- * The vbin8 type encodes up to 255 octets of opaque binary data.
- *
- * return a byte array.
- */
- byte[] readVbin8();
-
- /**
- * The vbin16 type encodes up to 65535 octets of opaque binary data.
- *
- * @return the corresponding byte array.
- */
- byte[] readVbin16();
-
- /**
- * The vbin32 type encodes up to 4294967295 octets of opaque binary data.
- *
- * @return the corresponding byte array.
- */
- byte[] readVbin32();
-
- /**
- * The struct32 type describes any coded struct with a 32-bit (4 octet) size.
- * The type is restricted to be only coded structs with a 32-bit size, consequently the first six octets of any encoded
- * value for this type MUST always contain the size, class-code, and struct-code in that order.
- * The size is encoded as a 32-bit unsigned integral value in network byte order that is equal to the size of the
- * encoded field-data, packing-flags, class-code, and struct-code. The class-code is a single octet that may be set to any
- * valid class code.
- * The struct-code is a single octet that may be set to any valid struct code within the given class-code.
- * The first six octets are then followed by the packing flags and encoded field data.
- * The presence and quantity of packingflags, as well as the specific fields are determined by the struct definition
- * identified with the encoded class-code and struct-code.
- *
- * @return the decoded struct.
- */
- Struct readStruct32();
-
- /**
- * A map is a set of distinct keys where each key has an associated (type,value) pair.
- * The triple of the key, type, and value, form an entry within a map. Each entry within a given map MUST have a
- * distinct key.
- * A map is encoded as a size in octets, a count of the number of entries, followed by the encoded entries themselves.
- * An encoded map may contain up to (4294967295 - 4) octets worth of encoded entries.
- * The size is encoded as a 32-bit unsigned integral value in network byte order equal to the number of octets worth of
- * encoded entries plus 4. (The extra 4 octets is added for the entry count.)
- * The size is then followed by the number of entries encoded as a 32-bit unsigned integral value in network byte order.
- * Finally the entries are encoded sequentially.
- * An entry is encoded as the key, followed by the type, and then the value. The key is always a string encoded as a str8.
- * The type is a single octet that may contain any valid AMQP type code.
- * The value is encoded according to the rules defined by the type code for that entry.
- *
- * @return the decoded map.
- */
- Map<String,Object> readMap();
-
- /**
- * A list is an ordered sequence of (type, value) pairs. The (type, value) pair forms an item within the list.
- * The list may contain items of many distinct types. A list is encoded as a size in octets, followed by a count of the
- * number of items, followed by the items themselves encoded in their defined order.
- * An encoded list may contain up to (4294967295 - 4) octets worth of encoded items.
- * The size is encoded as a 32-bit unsigned integral value in network byte order equal to the number of octets worth
- * of encoded items plus 4. (The extra4 octets is added for the item count.)
- * The size is then followed by the number of items encoded as a 32-bit unsigned integral value in network byte order.
- * Finally the items are encoded sequentially in their defined order.
- * An item is encoded as the type followed by the value. The type is a single octet that may contain any valid AMQP type
- * code.
- * The value is encoded according to the rules defined by the type code for that item.
- *
- * @return the decoded list.
- */
- List<Object> readList();
-
- /**
- * An array is an ordered sequence of values of the same type.
- * The array is encoded in as a size in octets, followed by a type code, then a count of the number values in the array,
- * and finally the values encoded in their defined order.
- * An encoded array may contain up to (4294967295 - 5) octets worth of encoded values.
- * The size is encoded as a 32-bit unsigned integral value in network byte order equal to the number of octets worth of
- * encoded values plus 5. (The extra 5 octets consist of 4 octets for the count of the number of values, and one octet to
- * hold the type code for the items inthe array.)
- * The size is then followed by a single octet that may contain any valid AMQP type code.
- * The type code is then followed by the number of values encoded as a 32-bit unsigned integral value in network byte
- * order.
- * Finally the values are encoded sequentially in their defined order according to the rules defined by the type code for
- * the array.
- *
- * @return the decoded array.
- */
- List<Object> readArray();
-
- /**
- *
- * @param type the type of the struct.
- * @return the decoded struct.
- */
- Struct readStruct(int type);
-
- /**
- * The float type encodes a single precision 32-bit floating point number.
- * The format and operations are defined by the IEEE 754 standard for 32-bit single precision floating point numbers.
- *
- * @return the decoded float.
- */
- float readFloat();
-
- /**
- * The double type encodes a double precision 64-bit floating point number.
- * The format and operations are defined by the IEEE 754 standard for 64-bit double precision floating point numbers.
- *
- * @return the decoded double
- */
- double readDouble();
-
- /**
- * The int8 type is a signed integral value encoded using an 8-bit two's complement representation.
- *
- * @return the decoded integer.
- */
- byte readInt8();
-
- /**
- * The int16 type is a signed integral value encoded using a 16-bit two's complement representation in network byte order.
- *
- * @return the decoded integer.
- */
- short readInt16();
-
- /**
- * The int32 type is a signed integral value encoded using a 32-bit two's complement representation in network byte order.
- *
- * @return the decoded integer.
- */
- int readInt32();
-
- /**
- * The int64 type is a signed integral value encoded using a 64-bit two's complement representation in network byte order.
- *
- * @return the decoded integer (as long).
- */
- long readInt64();
-
- /**
- * The bin128 type consists of 16 consecutive octets of opaque binary data.
- *
- * @return the decoded byte array.
- */
- byte [] readBin128();
-
- /**
- * Reads the remaining bytes on the underlying buffer.
- *
- * @return the remaining bytes on the underlying buffer.
- */
- byte[] readReaminingBytes ();
-
- /**
- * Reads the given number of bytes.
- *
- * @param howManyBytes how many bytes need to be read?
- * @return a byte array containing the requested data.
- */
- byte[] readBytes (int howManyBytes);
-} \ No newline at end of file
diff --git a/java/common/src/main/java/org/apache/qpid/transport/codec/Encodable.java b/java/common/src/main/java/org/apache/qpid/transport/codec/Encodable.java
deleted file mode 100644
index 37ce8a5cb7..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/codec/Encodable.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.transport.codec;
-
-
-/**
- * Encodable
- *
- * @author Rafael H. Schloming
- */
-public interface Encodable
-{
- /**
- * Encodes this encodable using the given encoder.
- *
- * @param encoder the encoder.
- */
- void write(Encoder encoder);
-
- /**
- * Decodes this encodable using the given decoder.
- *
- * @param decoder the decoder.
- */
- void read(Decoder decoder);
-} \ No newline at end of file
diff --git a/java/common/src/main/java/org/apache/qpid/transport/codec/Encoder.java b/java/common/src/main/java/org/apache/qpid/transport/codec/Encoder.java
deleted file mode 100644
index 7d4f02af31..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/codec/Encoder.java
+++ /dev/null
@@ -1,282 +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.transport.codec;
-
-import java.util.List;
-import java.util.Map;
-import java.util.UUID;
-
-import org.apache.qpid.transport.RangeSet;
-import org.apache.qpid.transport.Struct;
-
-
-/**
- * Encoder interface.
- * Each concrete implementor must specify how to encode given values.
- *
- * @author Rafael H. Schloming
- */
-public interface Encoder
-{
- /**
- * The uint8 type is an 8-bit unsigned integral value.
- *
- * @param b the unsigned integer to be encoded.
- */
- void writeUint8(short b);
-
- /**
- *The uint16 type is a 16-bit unsigned integral value encoded in network byte order.
- *
- * @param s the unsigned integer to be encoded.
- */
- void writeUint16(int s);
-
- /**
- *The uint32 type is a 32-bit unsigned integral value encoded in network byte order.
- *
- * @param i the unsigned integer to be encoded.
- */
- void writeUint32(long i);
-
- /**
- * The uint64 type is a 64-bit unsigned integral value encoded in network byte order.
- *
- * @param b the unsigned integer to be encoded.
- */
- void writeUint64(long l);
-
- /**
- * The datetime type encodes a date and time using the 64 bit POSIX time_t format.
- *
- * @param l the datetime (as long) to be encoded.
- */
- void writeDatetime(long l);
-
- /**
- * The uuid type encodes a universally unique id as defined by RFC-4122.
- * The format and operations for this type can be found in section 4.1.2 of RFC-4122.
- *
- * @param uuid the uuid to be encoded.
- */
- void writeUuid(UUID uuid);
-
- /**
- *The sequence-no type encodes, in network byte order, a serial number as defined in RFC-1982.
- *
- * @param s the sequence number to be encoded.
- */
- void writeSequenceNo(int s);
-
- void writeSequenceSet(RangeSet ranges); // XXX
- void writeByteRanges(RangeSet ranges); // XXX
-
- /**
- * The str8 type encodes up to 255 octets worth of UTF-8 unicode.
- * The number of octets of unicode is first encoded as an 8-bit unsigned integral value.
- * This is followed by the actual UTF-8 unicode.
- * Note that the encoded size refers to the number of octets of unicode, not necessarily the number of characters since
- * the UTF-8 unicode may include multi-byte character sequences.
- *
- * @param s the string to be encoded.
- */
- void writeStr8(String s);
-
- /**
- * The str16 type encodes up to 65535 octets worth of UTF-8 unicode.
- * The number of octets is first encoded as a 16-bit unsigned integral value in network byte order.
- * This is followed by the actual UTF-8 unicode.
- * Note that the encoded size refers to the number of octets of unicode, not necessarily the number of unicode
- * characters since the UTF-8 unicode may include multi-byte character sequences.
- *
- * @param s the string to be encoded.
- */
- void writeStr16(String s);
-
- /**
- * The vbin8 type encodes up to 255 octets of opaque binary data.
- * The number of octets is first encoded as an 8-bit unsigned integral value.
- * This is followed by the actual data.
- *
- * @param bytes the byte array to be encoded.
- */
- void writeVbin8(byte[] bytes);
-
- /**
- * The vbin16 type encodes up to 65535 octets of opaque binary data.
- * The number of octets is first encoded as a 16-bit unsigned integral value in network byte order.
- * This is followed by the actual data.
- *
- * @param bytes the byte array to be encoded.
- */
- void writeVbin16(byte[] bytes);
-
- /**
- * The vbin32 type encodes up to 4294967295 octets of opaque binary data.
- * The number of octets is first encoded as a 32-bit unsigned integral value in network byte order.
- * This is followed by the actual data.
- *
- * @param bytes the byte array to be encoded.
- */
- void writeVbin32(byte[] bytes);
-
- /**
- * The struct32 type describes any coded struct with a 32-bit (4 octet) size.
- * The type is restricted to be only coded structs with a 32-bit size, consequently the first six octets of any encoded
- * value for this type MUST always contain the size, class-code, and struct-code in that order.
- * The size is encoded as a 32-bit unsigned integral value in network byte order that is equal to the size of the
- * encoded field-data, packing-flags, class-code, and struct-code. The class-code is a single octet that may be set to any
- * valid class code.
- * The struct-code is a single octet that may be set to any valid struct code within the given class-code.
- * The first six octets are then followed by the packing flags and encoded field data.
- * The presence and quantity of packingflags, as well as the specific fields are determined by the struct definition
- * identified with the encoded class-code and struct-code.
- *
- * @param struct the struct to be encoded.
- */
- void writeStruct32(Struct struct);
-
- /**
- * A map is a set of distinct keys where each key has an associated (type,value) pair.
- * The triple of the key, type, and value, form an entry within a map. Each entry within a given map MUST have a
- * distinct key.
- * A map is encoded as a size in octets, a count of the number of entries, followed by the encoded entries themselves.
- * An encoded map may contain up to (4294967295 - 4) octets worth of encoded entries.
- * The size is encoded as a 32-bit unsigned integral value in network byte order equal to the number of octets worth of
- * encoded entries plus 4. (The extra 4 octets is added for the entry count.)
- * The size is then followed by the number of entries encoded as a 32-bit unsigned integral value in network byte order.
- * Finally the entries are encoded sequentially.
- * An entry is encoded as the key, followed by the type, and then the value. The key is always a string encoded as a str8.
- * The type is a single octet that may contain any valid AMQP type code.
- * The value is encoded according to the rules defined by the type code for that entry.
- *
- * @param map the map to be encoded.
- */
- void writeMap(Map<String,Object> map);
-
- /**
- * A list is an ordered sequence of (type, value) pairs. The (type, value) pair forms an item within the list.
- * The list may contain items of many distinct types. A list is encoded as a size in octets, followed by a count of the
- * number of items, followed by the items themselves encoded in their defined order.
- * An encoded list may contain up to (4294967295 - 4) octets worth of encoded items.
- * The size is encoded as a 32-bit unsigned integral value in network byte order equal to the number of octets worth
- * of encoded items plus 4. (The extra4 octets is added for the item count.)
- * The size is then followed by the number of items encoded as a 32-bit unsigned integral value in network byte order.
- * Finally the items are encoded sequentially in their defined order.
- * An item is encoded as the type followed by the value. The type is a single octet that may contain any valid AMQP type
- * code.
- * The value is encoded according to the rules defined by the type code for that item.
- *
- * @param list the list to be encoded.
- */
- void writeList(List<Object> list);
-
- /**
- * An array is an ordered sequence of values of the same type.
- * The array is encoded in as a size in octets, followed by a type code, then a count of the number values in the array,
- * and finally the values encoded in their defined order.
- * An encoded array may contain up to (4294967295 - 5) octets worth of encoded values.
- * The size is encoded as a 32-bit unsigned integral value in network byte order equal to the number of octets worth of
- * encoded values plus 5. (The extra 5 octets consist of 4 octets for the count of the number of values, and one octet to
- * hold the type code for the items inthe array.)
- * The size is then followed by a single octet that may contain any valid AMQP type code.
- * The type code is then followed by the number of values encoded as a 32-bit unsigned integral value in network byte
- * order.
- * Finally the values are encoded sequentially in their defined order according to the rules defined by the type code for
- * the array.
- *
- * @param array the array to be encoded.
- */
- void writeArray(List<Object> array);
-
- /**
- * The struct32 type describes any coded struct with a 32-bit (4 octet) size.
- * The type is restricted to be only coded structs with a 32-bit size, consequently the first six octets of any encoded
- * value for this type MUST always contain the size, class-code, and struct-code in that order.
- * The size is encoded as a 32-bit unsigned integral value in network byte order that is equal to the size of the
- * encoded field-data, packing-flags, class-code, and struct-code. The class-code is a single octet that may be set to any
- * valid class code.
- * The struct-code is a single octet that may be set to any valid struct code within the given class-code.
- * The first six octets are then followed by the packing flags and encoded field data.
- * The presence and quantity of packingflags, as well as the specific fields are determined by the struct definition
- * identified with the encoded class-code and struct-code.
- *
- * @param type the type of the struct.
- * @param struct the struct to be encoded.
- */
- void writeStruct(int type, Struct struct);
-
- /**
- * The float type encodes a single precision 32-bit floating point number.
- * The format and operations are defined by the IEEE 754 standard for 32-bit single precision floating point numbers.
- *
- * @param aFloat the float to be encoded.
- */
- void writeFloat(float aFloat);
-
- /**
- * The double type encodes a double precision 64-bit floating point number.
- * The format and operations are defined by the IEEE 754 standard for 64-bit double precision floating point numbers.
- *
- * @param aDouble the double to be encoded.
- */
- void writeDouble(double aDouble);
-
- /**
- * The int8 type is a signed integral value encoded using an 8-bit two's complement representation.
- *
- * @param aByte the integer to be encoded.
- */
- void writeInt8(byte aByte);
-
- /**
- * The int16 type is a signed integral value encoded using a 16-bit two's complement representation in network byte order.
- *
- * @param aShort the integer to be encoded.
- */
- void writeInt16(short aShort);
-
- /**
- * The int32 type is a signed integral value encoded using a 32-bit two's complement representation in network byte order.
- *
- * @param anInt the integer to be encoded.
- */
- void writeInt32(int anInt);
-
- /**
- * The int64 type is a signed integral value encoded using a 64-bit two's complement representation in network byte order.
- *
- * @param aLong the integer to be encoded.
- */
- void writeInt64(long aLong);
-
- /**
- * The bin128 type consists of 16 consecutive octets of opaque binary data.
- *
- * @param bytes the bytes array to be encoded.
- */
- void writeBin128(byte [] bytes);
-
- /**
- * Encodes the AMQP magic number.
- */
- void writeMagicNumber();
-} \ No newline at end of file
diff --git a/java/common/src/main/java/org/apache/qpid/transport/network/Assembler.java b/java/common/src/main/java/org/apache/qpid/transport/network/Assembler.java
deleted file mode 100644
index 1a85ab88a5..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/network/Assembler.java
+++ /dev/null
@@ -1,256 +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.transport.network;
-
-import java.nio.ByteBuffer;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.qpid.transport.Header;
-import org.apache.qpid.transport.Method;
-import org.apache.qpid.transport.ProtocolError;
-import org.apache.qpid.transport.ProtocolEvent;
-import org.apache.qpid.transport.ProtocolHeader;
-import org.apache.qpid.transport.Receiver;
-import org.apache.qpid.transport.Struct;
-import org.apache.qpid.transport.codec.BBDecoder;
-
-/**
- * Assembler
- *
- */
-public class Assembler implements Receiver<NetworkEvent>, NetworkDelegate
-{
- // Use a small array to store incomplete Methods for low-value channels, instead of allocating a huge
- // array or always boxing the channelId and looking it up in the map. This value must be of the form 2^X - 1.
- private static final int ARRAY_SIZE = 0xFF;
- private final Method[] _incompleteMethodArray = new Method[ARRAY_SIZE + 1];
- private final Map<Integer, Method> _incompleteMethodMap = new HashMap<Integer, Method>();
-
- private final Receiver<ProtocolEvent> receiver;
- private final Map<Integer,List<Frame>> segments;
- private static final ThreadLocal<BBDecoder> _decoder = new ThreadLocal<BBDecoder>()
- {
- public BBDecoder initialValue()
- {
- return new BBDecoder();
- }
- };
-
- public Assembler(Receiver<ProtocolEvent> receiver)
- {
- this.receiver = receiver;
- segments = new HashMap<Integer,List<Frame>>();
- }
-
- private int segmentKey(Frame frame)
- {
- return (frame.getTrack() + 1) * frame.getChannel();
- }
-
- private List<Frame> getSegment(Frame frame)
- {
- return segments.get(segmentKey(frame));
- }
-
- private void setSegment(Frame frame, List<Frame> segment)
- {
- int key = segmentKey(frame);
- if (segments.containsKey(key))
- {
- error(new ProtocolError(Frame.L2, "segment in progress: %s",
- frame));
- }
- segments.put(segmentKey(frame), segment);
- }
-
- private void clearSegment(Frame frame)
- {
- segments.remove(segmentKey(frame));
- }
-
- private void emit(int channel, ProtocolEvent event)
- {
- event.setChannel(channel);
- receiver.received(event);
- }
-
- public void received(NetworkEvent event)
- {
- event.delegate(this);
- }
-
- public void exception(Throwable t)
- {
- this.receiver.exception(t);
- }
-
- public void closed()
- {
- this.receiver.closed();
- }
-
- public void init(ProtocolHeader header)
- {
- emit(0, header);
- }
-
- public void error(ProtocolError error)
- {
- emit(0, error);
- }
-
- public void frame(Frame frame)
- {
- ByteBuffer segment;
- if (frame.isFirstFrame() && frame.isLastFrame())
- {
- segment = frame.getBody();
- assemble(frame, segment);
- }
- else
- {
- List<Frame> frames;
- if (frame.isFirstFrame())
- {
- frames = new ArrayList<Frame>();
- setSegment(frame, frames);
- }
- else
- {
- frames = getSegment(frame);
- }
-
- frames.add(frame);
-
- if (frame.isLastFrame())
- {
- clearSegment(frame);
-
- int size = 0;
- for (Frame f : frames)
- {
- size += f.getSize();
- }
- segment = ByteBuffer.allocate(size);
- for (Frame f : frames)
- {
- segment.put(f.getBody());
- }
- segment.flip();
- assemble(frame, segment);
- }
- }
-
- }
-
- private void assemble(Frame frame, ByteBuffer segment)
- {
- BBDecoder dec = _decoder.get();
- dec.init(segment);
-
- int channel = frame.getChannel();
- Method command;
-
- switch (frame.getType())
- {
- case CONTROL:
- int controlType = dec.readUint16();
- Method control = Method.create(controlType);
- control.read(dec);
- emit(channel, control);
- break;
- case COMMAND:
- int commandType = dec.readUint16();
- // read in the session header, right now we don't use it
- int hdr = dec.readUint16();
- command = Method.create(commandType);
- command.setSync((0x0001 & hdr) != 0);
- command.read(dec);
- if (command.hasPayload())
- {
- setIncompleteCommand(channel, command);
- }
- else
- {
- emit(channel, command);
- }
- break;
- case HEADER:
- command = getIncompleteCommand(channel);
- List<Struct> structs = new ArrayList<Struct>(2);
- while (dec.hasRemaining())
- {
- structs.add(dec.readStruct32());
- }
- command.setHeader(new Header(structs));
- if (frame.isLastSegment())
- {
- setIncompleteCommand(channel, null);
- emit(channel, command);
- }
- break;
- case BODY:
- command = getIncompleteCommand(channel);
- command.setBody(segment);
- setIncompleteCommand(channel, null);
- emit(channel, command);
- break;
- default:
- throw new IllegalStateException("unknown frame type: " + frame.getType());
- }
-
- dec.releaseBuffer();
- }
-
- private void setIncompleteCommand(int channelId, Method incomplete)
- {
- if ((channelId & ARRAY_SIZE) == channelId)
- {
- _incompleteMethodArray[channelId] = incomplete;
- }
- else
- {
- if(incomplete != null)
- {
- _incompleteMethodMap.put(channelId, incomplete);
- }
- else
- {
- _incompleteMethodMap.remove(channelId);
- }
- }
- }
-
- private Method getIncompleteCommand(int channelId)
- {
- if ((channelId & ARRAY_SIZE) == channelId)
- {
- return _incompleteMethodArray[channelId];
- }
- else
- {
- return _incompleteMethodMap.get(channelId);
- }
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/network/ConnectionBinding.java b/java/common/src/main/java/org/apache/qpid/transport/network/ConnectionBinding.java
deleted file mode 100644
index 1a8d277bba..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/network/ConnectionBinding.java
+++ /dev/null
@@ -1,103 +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.transport.network;
-
-import java.nio.ByteBuffer;
-
-import org.apache.qpid.transport.Binding;
-import org.apache.qpid.transport.Connection;
-import org.apache.qpid.transport.ConnectionDelegate;
-import org.apache.qpid.transport.ConnectionListener;
-import org.apache.qpid.transport.Receiver;
-import org.apache.qpid.transport.Sender;
-import org.apache.qpid.transport.network.security.sasl.SASLReceiver;
-import org.apache.qpid.transport.network.security.sasl.SASLSender;
-
-/**
- * ConnectionBinding
- *
- */
-
-public abstract class ConnectionBinding
- implements Binding<Connection,ByteBuffer>
-{
-
- public static Binding<Connection,ByteBuffer> get(final Connection connection)
- {
- return new ConnectionBinding()
- {
- public Connection connection()
- {
- return connection;
- }
- };
- }
-
- public static Binding<Connection,ByteBuffer> get(final ConnectionDelegate delegate)
- {
- return new ConnectionBinding()
- {
- public Connection connection()
- {
- Connection conn = new Connection();
- conn.setConnectionDelegate(delegate);
- return conn;
- }
- };
- }
-
- public static final int MAX_FRAME_SIZE = 64 * 1024 - 1;
-
- public abstract Connection connection();
-
- public Connection endpoint(Sender<ByteBuffer> sender)
- {
- Connection conn = connection();
-
- if (conn.getConnectionSettings() != null &&
- conn.getConnectionSettings().isUseSASLEncryption())
- {
- sender = new SASLSender(sender);
- conn.addConnectionListener((ConnectionListener)sender);
- }
-
- // XXX: hardcoded max-frame
- Disassembler dis = new Disassembler(sender, MAX_FRAME_SIZE);
- conn.setSender(dis);
- return conn;
- }
-
- public Receiver<ByteBuffer> receiver(Connection conn)
- {
- if (conn.getConnectionSettings() != null &&
- conn.getConnectionSettings().isUseSASLEncryption())
- {
- SASLReceiver receiver = new SASLReceiver(new InputHandler(new Assembler(conn)));
- conn.addConnectionListener((ConnectionListener)receiver);
- return receiver;
- }
- else
- {
- return new InputHandler(new Assembler(conn));
- }
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/network/Disassembler.java b/java/common/src/main/java/org/apache/qpid/transport/network/Disassembler.java
deleted file mode 100644
index 685034d1a9..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/network/Disassembler.java
+++ /dev/null
@@ -1,233 +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.transport.network;
-
-import org.apache.qpid.transport.Header;
-import org.apache.qpid.transport.Method;
-import org.apache.qpid.transport.ProtocolDelegate;
-import org.apache.qpid.transport.ProtocolError;
-import org.apache.qpid.transport.ProtocolEvent;
-import org.apache.qpid.transport.ProtocolHeader;
-import org.apache.qpid.transport.SegmentType;
-import org.apache.qpid.transport.Sender;
-import org.apache.qpid.transport.Struct;
-import org.apache.qpid.transport.codec.BBEncoder;
-import static org.apache.qpid.transport.network.Frame.FIRST_FRAME;
-import static org.apache.qpid.transport.network.Frame.FIRST_SEG;
-import static org.apache.qpid.transport.network.Frame.HEADER_SIZE;
-import static org.apache.qpid.transport.network.Frame.LAST_FRAME;
-import static org.apache.qpid.transport.network.Frame.LAST_SEG;
-
-import static java.lang.Math.min;
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-
-/**
- * Disassembler
- */
-public final class Disassembler implements Sender<ProtocolEvent>, ProtocolDelegate<Void>
-{
- private final Sender<ByteBuffer> sender;
- private final int maxPayload;
- private final Object sendlock = new Object();
- private final static ThreadLocal<BBEncoder> _encoder = new ThreadLocal<BBEncoder>()
- {
- public BBEncoder initialValue()
- {
- return new BBEncoder(4*1024);
- }
- };
-
- public Disassembler(Sender<ByteBuffer> sender, int maxFrame)
- {
- if (maxFrame <= HEADER_SIZE || maxFrame >= 64*1024)
- {
- throw new IllegalArgumentException("maxFrame must be > HEADER_SIZE and < 64K: " + maxFrame);
- }
- this.sender = sender;
- this.maxPayload = maxFrame - HEADER_SIZE;
- }
-
- public void send(ProtocolEvent event)
- {
- event.delegate(null, this);
- }
-
- public void flush()
- {
- synchronized (sendlock)
- {
- sender.flush();
- }
- }
-
- public void close()
- {
- synchronized (sendlock)
- {
- sender.close();
- }
- }
-
- private void frame(byte flags, byte type, byte track, int channel, int size, ByteBuffer buf)
- {
- synchronized (sendlock)
- {
- ByteBuffer data = ByteBuffer.allocate(size + HEADER_SIZE);
- data.order(ByteOrder.BIG_ENDIAN);
-
- data.put(0, flags);
- data.put(1, type);
- data.putShort(2, (short) (size + HEADER_SIZE));
- data.put(5, track);
- data.putShort(6, (short) channel);
- data.position(HEADER_SIZE);
-
- int limit = buf.limit();
- buf.limit(buf.position() + size);
- data.put(buf);
- buf.limit(limit);
-
- data.rewind();
- sender.send(data);
- }
- }
-
- private void fragment(byte flags, SegmentType type, ProtocolEvent event, ByteBuffer buf)
- {
- byte typeb = (byte) type.getValue();
- byte track = event.getEncodedTrack() == Frame.L4 ? (byte) 1 : (byte) 0;
-
- int remaining = buf.remaining();
- boolean first = true;
- while (true)
- {
- int size = min(maxPayload, remaining);
- remaining -= size;
-
- byte newflags = flags;
- if (first)
- {
- newflags |= FIRST_FRAME;
- first = false;
- }
- if (remaining == 0)
- {
- newflags |= LAST_FRAME;
- }
-
- frame(newflags, typeb, track, event.getChannel(), size, buf);
-
- if (remaining == 0)
- {
- break;
- }
- }
- }
-
- public void init(Void v, ProtocolHeader header)
- {
- synchronized (sendlock)
- {
- sender.send(header.toByteBuffer());
- sender.flush();
- }
- }
-
- public void control(Void v, Method method)
- {
- method(method, SegmentType.CONTROL);
- }
-
- public void command(Void v, Method method)
- {
- method(method, SegmentType.COMMAND);
- }
-
- private void method(Method method, SegmentType type)
- {
- BBEncoder enc = _encoder.get();
- enc.init();
- enc.writeUint16(method.getEncodedType());
- if (type == SegmentType.COMMAND)
- {
- if (method.isSync())
- {
- enc.writeUint16(0x0101);
- }
- else
- {
- enc.writeUint16(0x0100);
- }
- }
- method.write(enc);
- ByteBuffer methodSeg = enc.segment();
-
- byte flags = FIRST_SEG;
-
- boolean payload = method.hasPayload();
- if (!payload)
- {
- flags |= LAST_SEG;
- }
-
- ByteBuffer headerSeg = null;
- if (payload)
- {
- final Header hdr = method.getHeader();
- if (hdr != null)
- {
- final Struct[] structs = hdr.getStructs();
-
- for (Struct st : structs)
- {
- enc.writeStruct32(st);
- }
- }
- headerSeg = enc.segment();
- }
-
- synchronized (sendlock)
- {
- fragment(flags, type, method, methodSeg);
- if (payload)
- {
- ByteBuffer body = method.getBody();
- fragment(body == null ? LAST_SEG : 0x0, SegmentType.HEADER, method, headerSeg);
- if (body != null)
- {
- fragment(LAST_SEG, SegmentType.BODY, method, body);
- }
-
- }
- }
- }
-
- public void error(Void v, ProtocolError error)
- {
- throw new IllegalArgumentException(String.valueOf(error));
- }
-
- public void setIdleTimeout(int i)
- {
- sender.setIdleTimeout(i);
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/network/Frame.java b/java/common/src/main/java/org/apache/qpid/transport/network/Frame.java
deleted file mode 100644
index 849355276e..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/network/Frame.java
+++ /dev/null
@@ -1,151 +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.transport.network;
-
-import org.apache.qpid.transport.SegmentType;
-import org.apache.qpid.transport.util.SliceIterator;
-
-import java.nio.ByteBuffer;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Iterator;
-
-import static org.apache.qpid.transport.util.Functions.*;
-
-
-/**
- * Frame
- *
- * @author Rafael H. Schloming
- */
-
-public final class Frame implements NetworkEvent
-{
- public static final int HEADER_SIZE = 12;
-
- // XXX: enums?
- public static final byte L1 = 0;
- public static final byte L2 = 1;
- public static final byte L3 = 2;
- public static final byte L4 = 3;
-
- public static final byte RESERVED = 0x0;
-
- public static final byte VERSION = 0x0;
-
- public static final byte FIRST_SEG = 0x8;
- public static final byte LAST_SEG = 0x4;
- public static final byte FIRST_FRAME = 0x2;
- public static final byte LAST_FRAME = 0x1;
-
- final private byte flags;
- final private SegmentType type;
- final private byte track;
- final private int channel;
- final private ByteBuffer body;
-
- public Frame(byte flags, SegmentType type, byte track, int channel,
- ByteBuffer body)
- {
- this.flags = flags;
- this.type = type;
- this.track = track;
- this.channel = channel;
- this.body = body;
- }
-
- public ByteBuffer getBody()
- {
- return body.slice();
- }
-
- public byte getFlags()
- {
- return flags;
- }
-
- public int getChannel()
- {
- return channel;
- }
-
- public int getSize()
- {
- return body.remaining();
- }
-
- public SegmentType getType()
- {
- return type;
- }
-
- public byte getTrack()
- {
- return track;
- }
-
- private boolean flag(byte mask)
- {
- return (flags & mask) != 0;
- }
-
- public boolean isFirstSegment()
- {
- return flag(FIRST_SEG);
- }
-
- public boolean isLastSegment()
- {
- return flag(LAST_SEG);
- }
-
- public boolean isFirstFrame()
- {
- return flag(FIRST_FRAME);
- }
-
- public boolean isLastFrame()
- {
- return flag(LAST_FRAME);
- }
-
- public void delegate(NetworkDelegate delegate)
- {
- delegate.frame(this);
- }
-
- public String toString()
- {
- StringBuilder str = new StringBuilder();
-
- str.append(String.format
- ("[%05d %05d %1d %s %d%d%d%d] ", getChannel(), getSize(),
- getTrack(), getType(),
- isFirstSegment() ? 1 : 0, isLastSegment() ? 1 : 0,
- isFirstFrame() ? 1 : 0, isLastFrame() ? 1 : 0));
-
- str.append(str(body));
-
- return str.toString();
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/network/InputHandler.java b/java/common/src/main/java/org/apache/qpid/transport/network/InputHandler.java
deleted file mode 100644
index a2885f97bc..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/network/InputHandler.java
+++ /dev/null
@@ -1,205 +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.transport.network;
-
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-
-import org.apache.qpid.transport.ProtocolError;
-import org.apache.qpid.transport.ProtocolHeader;
-import org.apache.qpid.transport.Receiver;
-import org.apache.qpid.transport.SegmentType;
-
-import static org.apache.qpid.transport.util.Functions.*;
-
-import static org.apache.qpid.transport.network.InputHandler.State.*;
-
-
-/**
- * InputHandler
- *
- * @author Rafael H. Schloming
- */
-
-public class InputHandler implements Receiver<ByteBuffer>
-{
-
- public enum State
- {
- PROTO_HDR,
- FRAME_HDR,
- FRAME_BODY,
- ERROR;
- }
-
- private final Receiver<NetworkEvent> receiver;
- private State state;
- private ByteBuffer input = null;
- private int needed;
-
- private byte flags;
- private SegmentType type;
- private byte track;
- private int channel;
-
- public InputHandler(Receiver<NetworkEvent> receiver, State state)
- {
- this.receiver = receiver;
- this.state = state;
-
- switch (state)
- {
- case PROTO_HDR:
- needed = 8;
- break;
- case FRAME_HDR:
- needed = Frame.HEADER_SIZE;
- break;
- }
- }
-
- public InputHandler(Receiver<NetworkEvent> receiver)
- {
- this(receiver, PROTO_HDR);
- }
-
- private void error(String fmt, Object ... args)
- {
- receiver.received(new ProtocolError(Frame.L1, fmt, args));
- }
-
- public void received(ByteBuffer buf)
- {
- int limit = buf.limit();
- int remaining = buf.remaining();
- while (remaining > 0)
- {
- if (remaining >= needed)
- {
- int consumed = needed;
- int pos = buf.position();
- if (input == null)
- {
- buf.limit(pos + needed);
- input = buf;
- state = next(pos);
- buf.limit(limit);
- buf.position(pos + consumed);
- }
- else
- {
- buf.limit(pos + needed);
- input.put(buf);
- buf.limit(limit);
- input.flip();
- state = next(0);
- }
-
- remaining -= consumed;
- input = null;
- }
- else
- {
- if (input == null)
- {
- input = ByteBuffer.allocate(needed);
- }
- input.put(buf);
- needed -= remaining;
- remaining = 0;
- }
- }
- }
-
- private State next(int pos)
- {
- input.order(ByteOrder.BIG_ENDIAN);
-
- switch (state) {
- case PROTO_HDR:
- if (input.get(pos) != 'A' &&
- input.get(pos + 1) != 'M' &&
- input.get(pos + 2) != 'Q' &&
- input.get(pos + 3) != 'P')
- {
- error("bad protocol header: %s", str(input));
- return ERROR;
- }
-
- byte protoClass = input.get(pos + 4);
- byte instance = input.get(pos + 5);
- byte major = input.get(pos + 6);
- byte minor = input.get(pos + 7);
- receiver.received(new ProtocolHeader(protoClass, instance, major, minor));
- needed = Frame.HEADER_SIZE;
- return FRAME_HDR;
- case FRAME_HDR:
- flags = input.get(pos);
- type = SegmentType.get(input.get(pos + 1));
- int size = (0xFFFF & input.getShort(pos + 2));
- size -= Frame.HEADER_SIZE;
- if (size < 0 || size > (64*1024 - 12))
- {
- error("bad frame size: %d", size);
- return ERROR;
- }
- byte b = input.get(pos + 5);
- if ((b & 0xF0) != 0) {
- error("non-zero reserved bits in upper nibble of " +
- "frame header byte 5: '%x'", b);
- return ERROR;
- } else {
- track = (byte) (b & 0xF);
- }
- channel = (0xFFFF & input.getShort(pos + 6));
- if (size == 0)
- {
- Frame frame = new Frame(flags, type, track, channel, ByteBuffer.allocate(0));
- receiver.received(frame);
- needed = Frame.HEADER_SIZE;
- return FRAME_HDR;
- }
- else
- {
- needed = size;
- return FRAME_BODY;
- }
- case FRAME_BODY:
- Frame frame = new Frame(flags, type, track, channel, input.slice());
- receiver.received(frame);
- needed = Frame.HEADER_SIZE;
- return FRAME_HDR;
- default:
- throw new IllegalStateException();
- }
- }
-
- public void exception(Throwable t)
- {
- receiver.exception(t);
- }
-
- public void closed()
- {
- receiver.closed();
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/network/NetworkDelegate.java b/java/common/src/main/java/org/apache/qpid/transport/network/NetworkDelegate.java
deleted file mode 100644
index fbdfe6e84c..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/network/NetworkDelegate.java
+++ /dev/null
@@ -1,42 +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.transport.network;
-
-import org.apache.qpid.transport.ProtocolError;
-import org.apache.qpid.transport.ProtocolHeader;
-
-
-/**
- * NetworkDelegate
- *
- * @author Rafael H. Schloming
- */
-
-public interface NetworkDelegate
-{
-
- void init(ProtocolHeader header);
-
- void frame(Frame frame);
-
- void error(ProtocolError error);
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/network/NetworkEvent.java b/java/common/src/main/java/org/apache/qpid/transport/network/NetworkEvent.java
deleted file mode 100644
index 91314cd4ad..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/network/NetworkEvent.java
+++ /dev/null
@@ -1,34 +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.transport.network;
-
-
-/**
- * NetworkEvent
- *
- */
-
-public interface NetworkEvent
-{
-
- void delegate(NetworkDelegate delegate);
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/network/NetworkTransport.java b/java/common/src/main/java/org/apache/qpid/transport/network/NetworkTransport.java
deleted file mode 100644
index 5e12d7e7c6..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/network/NetworkTransport.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.transport.network;
-
-import java.nio.ByteBuffer;
-
-import org.apache.qpid.transport.Receiver;
-import org.apache.qpid.transport.Sender;
-import org.apache.qpid.transport.ConnectionSettings;
-
-public interface NetworkTransport
-{
- public void init(ConnectionSettings settings);
-
- public Sender<ByteBuffer> sender();
-
- public void receiver(Receiver<ByteBuffer> delegate);
-
- public void close();
-} \ No newline at end of file
diff --git a/java/common/src/main/java/org/apache/qpid/transport/network/Transport.java b/java/common/src/main/java/org/apache/qpid/transport/network/Transport.java
deleted file mode 100644
index f0bf04d04f..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/network/Transport.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.transport.network;
-
-import org.apache.qpid.transport.TransportException;
-
-public class Transport
-{
- private final static Class<?> transportClass;
-
- static
- {
- try
- {
- transportClass =
- Class.forName(System.getProperty("qpid.transport",
- "org.apache.qpid.transport.network.io.IoNetworkTransport"));
-
- }
- catch(Exception e)
- {
- throw new Error("Error occured while loading Qpid Transport",e);
- }
- }
-
- public static NetworkTransport getTransport() throws TransportException
- {
- try
- {
- return (NetworkTransport)transportClass.newInstance();
- }
- catch (Exception e)
- {
- throw new TransportException("Error while creating a new transport instance",e);
- }
- }
-} \ No newline at end of file
diff --git a/java/common/src/main/java/org/apache/qpid/transport/network/io/InputHandler_0_9.java b/java/common/src/main/java/org/apache/qpid/transport/network/io/InputHandler_0_9.java
deleted file mode 100644
index ecc5f6d07c..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/network/io/InputHandler_0_9.java
+++ /dev/null
@@ -1,130 +0,0 @@
-package org.apache.qpid.transport.network.io;
-/*
- *
- * 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 java.nio.ByteBuffer;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.AMQFrame;
-import org.apache.qpid.framing.AMQFrameDecodingException;
-import org.apache.qpid.framing.AMQMethodBody;
-import org.apache.qpid.framing.AMQMethodBodyFactory;
-import org.apache.qpid.framing.BodyFactory;
-import org.apache.qpid.framing.ContentBody;
-import org.apache.qpid.framing.ContentBodyFactory;
-import org.apache.qpid.framing.ContentHeaderBody;
-import org.apache.qpid.framing.ContentHeaderBodyFactory;
-import org.apache.qpid.framing.HeartbeatBody;
-import org.apache.qpid.framing.HeartbeatBodyFactory;
-import org.apache.qpid.framing.MethodRegistry;
-import org.apache.qpid.protocol.AMQVersionAwareProtocolSession;
-import org.apache.qpid.transport.Receiver;
-
-public class InputHandler_0_9 implements Receiver<ByteBuffer>
-{
-
- private AMQVersionAwareProtocolSession _session;
- private MethodRegistry _registry;
- private BodyFactory bodyFactory;
- private static final BodyFactory[] _bodiesSupported = new BodyFactory[Byte.MAX_VALUE];
-
- static
- {
- _bodiesSupported[ContentHeaderBody.TYPE] = ContentHeaderBodyFactory.getInstance();
- _bodiesSupported[ContentBody.TYPE] = ContentBodyFactory.getInstance();
- _bodiesSupported[HeartbeatBody.TYPE] = new HeartbeatBodyFactory();
- }
-
- public InputHandler_0_9(AMQVersionAwareProtocolSession session)
- {
- _session = session;
- _registry = _session.getMethodRegistry();
- }
-
- public void closed()
- {
- // AS FIXME: implement
- }
-
- public void exception(Throwable t)
- {
- // TODO: propogate exception to things
- t.printStackTrace();
- }
-
- public void received(ByteBuffer buf)
- {
- org.apache.mina.common.ByteBuffer in = org.apache.mina.common.ByteBuffer.wrap(buf);
- try
- {
- final byte type = in.get();
- if (type == AMQMethodBody.TYPE)
- {
- bodyFactory = new AMQMethodBodyFactory(_session);
- }
- else
- {
- bodyFactory = _bodiesSupported[type];
- }
-
- if (bodyFactory == null)
- {
- throw new AMQFrameDecodingException(null, "Unsupported frame type: " + type, null);
- }
-
- final int channel = in.getUnsignedShort();
- final long bodySize = in.getUnsignedInt();
-
- // bodySize can be zero
- if ((channel < 0) || (bodySize < 0))
- {
- throw new AMQFrameDecodingException(null, "Undecodable frame: type = " + type + " channel = " + channel
- + " bodySize = " + bodySize, null);
- }
-
- AMQFrame frame = new AMQFrame(in, channel, bodySize, bodyFactory);
-
- byte marker = in.get();
- if ((marker & 0xFF) != 0xCE)
- {
- throw new AMQFrameDecodingException(null, "End of frame marker not found. Read " + marker + " length=" + bodySize
- + " type=" + type, null);
- }
-
- try
- {
- frame.getBodyFrame().handle(frame.getChannel(), _session);
- }
- catch (AMQException e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- catch (AMQFrameDecodingException e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/network/io/IoAcceptor.java b/java/common/src/main/java/org/apache/qpid/transport/network/io/IoAcceptor.java
deleted file mode 100644
index 8530240dcc..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/network/io/IoAcceptor.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.transport.network.io;
-
-import org.apache.qpid.transport.Binding;
-import org.apache.qpid.transport.TransportException;
-
-import java.io.IOException;
-
-import java.net.InetSocketAddress;
-import java.net.ServerSocket;
-import java.net.Socket;
-import java.net.SocketAddress;
-
-import java.nio.ByteBuffer;
-
-
-/**
- * IoAcceptor
- *
- */
-
-public class IoAcceptor<E> extends Thread
-{
-
-
- private ServerSocket socket;
- private Binding<E,ByteBuffer> binding;
-
- public IoAcceptor(SocketAddress address, Binding<E,ByteBuffer> binding)
- throws IOException
- {
- socket = new ServerSocket();
- socket.setReuseAddress(true);
- socket.bind(address);
- this.binding = binding;
-
- setName(String.format("IoAcceptor - %s", socket.getInetAddress()));
- }
-
- /**
- Close the underlying ServerSocket if it has not already been closed.
- */
- public void close() throws IOException
- {
- if (!socket.isClosed())
- {
- socket.close();
- }
- }
-
- public IoAcceptor(String host, int port, Binding<E,ByteBuffer> binding)
- throws IOException
- {
- this(new InetSocketAddress(host, port), binding);
- }
-
- public void run()
- {
- while (true)
- {
- try
- {
- Socket sock = socket.accept();
- IoTransport<E> transport = new IoTransport<E>(sock, binding,false);
- }
- catch (IOException e)
- {
- throw new TransportException(e);
- }
- }
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/network/io/IoContext.java b/java/common/src/main/java/org/apache/qpid/transport/network/io/IoContext.java
deleted file mode 100644
index 69b3a0ce45..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/network/io/IoContext.java
+++ /dev/null
@@ -1,35 +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.transport.network.io;
-
-import java.net.Socket;
-import java.nio.ByteBuffer;
-
-import org.apache.qpid.transport.Sender;
-
-public interface IoContext
-{
- Sender<ByteBuffer> getSender();
-
- IoReceiver getReceiver();
-
- Socket getSocket();
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/network/io/IoNetworkTransport.java b/java/common/src/main/java/org/apache/qpid/transport/network/io/IoNetworkTransport.java
deleted file mode 100644
index dd6a37eca2..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/network/io/IoNetworkTransport.java
+++ /dev/null
@@ -1,116 +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.transport.network.io;
-
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.Socket;
-import java.net.SocketException;
-import java.nio.ByteBuffer;
-
-import org.apache.qpid.transport.ConnectionSettings;
-import org.apache.qpid.transport.Receiver;
-import org.apache.qpid.transport.Sender;
-import org.apache.qpid.transport.TransportException;
-import org.apache.qpid.transport.network.NetworkTransport;
-import org.apache.qpid.transport.util.Logger;
-
-public class IoNetworkTransport implements NetworkTransport, IoContext
-{
- static
- {
- org.apache.mina.common.ByteBuffer.setAllocator
- (new org.apache.mina.common.SimpleByteBufferAllocator());
- org.apache.mina.common.ByteBuffer.setUseDirectBuffers
- (Boolean.getBoolean("amqj.enableDirectBuffers"));
- }
-
- private static final Logger log = Logger.get(IoNetworkTransport.class);
-
- private Socket socket;
- private Sender<ByteBuffer> sender;
- private IoReceiver receiver;
- private long timeout = 60000;
- private ConnectionSettings settings;
-
- public void init(ConnectionSettings settings)
- {
- try
- {
- this.settings = settings;
- InetAddress address = InetAddress.getByName(settings.getHost());
- socket = new Socket();
- socket.setReuseAddress(true);
- socket.setTcpNoDelay(settings.isTcpNodelay());
-
- log.debug("default-SO_RCVBUF : %s", socket.getReceiveBufferSize());
- log.debug("default-SO_SNDBUF : %s", socket.getSendBufferSize());
-
- socket.setSendBufferSize(settings.getWriteBufferSize());
- socket.setReceiveBufferSize(settings.getReadBufferSize());
-
- log.debug("new-SO_RCVBUF : %s", socket.getReceiveBufferSize());
- log.debug("new-SO_SNDBUF : %s", socket.getSendBufferSize());
-
- socket.connect(new InetSocketAddress(address, settings.getPort()));
- }
- catch (SocketException e)
- {
- throw new TransportException("Error connecting to broker", e);
- }
- catch (IOException e)
- {
- throw new TransportException("Error connecting to broker", e);
- }
- }
-
- public void receiver(Receiver<ByteBuffer> delegate)
- {
- receiver = new IoReceiver(this, delegate,
- 2*settings.getReadBufferSize() , timeout);
- }
-
- public Sender<ByteBuffer> sender()
- {
- return new IoSender(this, 2*settings.getWriteBufferSize(), timeout);
- }
-
- public void close()
- {
-
- }
-
- public Sender<ByteBuffer> getSender()
- {
- return sender;
- }
-
- public IoReceiver getReceiver()
- {
- return receiver;
- }
-
- public Socket getSocket()
- {
- return socket;
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/network/io/IoReceiver.java b/java/common/src/main/java/org/apache/qpid/transport/network/io/IoReceiver.java
deleted file mode 100644
index 19a683d505..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/network/io/IoReceiver.java
+++ /dev/null
@@ -1,162 +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.transport.network.io;
-
-import org.apache.qpid.thread.Threading;
-import org.apache.qpid.transport.Receiver;
-import org.apache.qpid.transport.TransportException;
-import org.apache.qpid.transport.util.Logger;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.Socket;
-import java.net.SocketException;
-import java.nio.ByteBuffer;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-/**
- * IoReceiver
- *
- */
-
-final class IoReceiver implements Runnable
-{
-
- private static final Logger log = Logger.get(IoReceiver.class);
-
- private final IoContext ioCtx;
- private final Receiver<ByteBuffer> receiver;
- private final int bufferSize;
- private final Socket socket;
- private final long timeout;
- private final AtomicBoolean closed = new AtomicBoolean(false);
- private final Thread receiverThread;
- private final boolean shutdownBroken =
- ((String) System.getProperties().get("os.name")).matches("(?i).*windows.*");
-
- public IoReceiver(IoContext ioCtx, Receiver<ByteBuffer> receiver,
- int bufferSize, long timeout)
- {
- this.ioCtx = ioCtx;
- this.receiver = receiver;
- this.bufferSize = bufferSize;
- this.socket = ioCtx.getSocket();
- this.timeout = timeout;
-
- try
- {
- receiverThread = Threading.getThreadFactory().createThread(this);
- }
- catch(Exception e)
- {
- throw new Error("Error creating IOReceiver thread",e);
- }
- receiverThread.setDaemon(true);
- receiverThread.setName(String.format("IoReceiver - %s", socket.getRemoteSocketAddress()));
- receiverThread.start();
- }
-
- void close(boolean block)
- {
- if (!closed.getAndSet(true))
- {
- try
- {
- if (shutdownBroken)
- {
- socket.close();
- }
- else
- {
- socket.shutdownInput();
- }
- if (block && Thread.currentThread() != receiverThread)
- {
- receiverThread.join(timeout);
- if (receiverThread.isAlive())
- {
- throw new TransportException("join timed out");
- }
- }
- }
- catch (InterruptedException e)
- {
- throw new TransportException(e);
- }
- catch (IOException e)
- {
- throw new TransportException(e);
- }
- }
- }
-
- public void run()
- {
- final int threshold = bufferSize / 2;
-
- // I set the read buffer size simillar to SO_RCVBUF
- // Haven't tested with a lower value to see if it's better or worse
- byte[] buffer = new byte[bufferSize];
- try
- {
- InputStream in = socket.getInputStream();
- int read = 0;
- int offset = 0;
- while ((read = in.read(buffer, offset, bufferSize-offset)) != -1)
- {
- if (read > 0)
- {
- ByteBuffer b = ByteBuffer.wrap(buffer,offset,read);
- receiver.received(b);
- offset+=read;
- if (offset > threshold)
- {
- offset = 0;
- buffer = new byte[bufferSize];
- }
- }
- }
- }
- catch (Throwable t)
- {
- if (!(shutdownBroken &&
- t instanceof SocketException &&
- t.getMessage().equalsIgnoreCase("socket closed") &&
- closed.get()))
- {
- receiver.exception(t);
- }
- }
- finally
- {
- receiver.closed();
- try
- {
- socket.close();
- }
- catch(Exception e)
- {
- log.warn(e, "Error closing socket");
- }
- }
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/network/io/IoSender.java b/java/common/src/main/java/org/apache/qpid/transport/network/io/IoSender.java
deleted file mode 100644
index 66b97e8225..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/network/io/IoSender.java
+++ /dev/null
@@ -1,307 +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.transport.network.io;
-
-import static org.apache.qpid.transport.util.Functions.mod;
-
-import java.io.IOException;
-import java.io.OutputStream;
-import java.net.Socket;
-import java.nio.ByteBuffer;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import org.apache.qpid.thread.Threading;
-import org.apache.qpid.transport.Sender;
-import org.apache.qpid.transport.SenderException;
-import org.apache.qpid.transport.TransportException;
-import org.apache.qpid.transport.util.Logger;
-
-
-public final class IoSender implements Runnable, Sender<ByteBuffer>
-{
-
- private static final Logger log = Logger.get(IoSender.class);
-
- // by starting here, we ensure that we always test the wraparound
- // case, we should probably make this configurable somehow so that
- // we can test other cases as well
- private final static int START = Integer.MAX_VALUE - 10;
-
- private final IoContext ioCtx;
- private final long timeout;
- private final Socket socket;
- private final OutputStream out;
-
- private final byte[] buffer;
- private volatile int head = START;
- private volatile int tail = START;
- private volatile boolean idle = true;
- private final Object notFull = new Object();
- private final Object notEmpty = new Object();
- private final AtomicBoolean closed = new AtomicBoolean(false);
- private final Thread senderThread;
-
- private volatile Throwable exception = null;
-
-
- public IoSender(IoContext ioCtx, int bufferSize, long timeout)
- {
- this.ioCtx = ioCtx;
- this.socket = ioCtx.getSocket();
- this.buffer = new byte[pof2(bufferSize)]; // buffer size must be a power of 2
- this.timeout = timeout;
-
- try
- {
- out = socket.getOutputStream();
- }
- catch (IOException e)
- {
- throw new TransportException("Error getting output stream for socket", e);
- }
-
- try
- {
- senderThread = Threading.getThreadFactory().createThread(this);
- }
- catch(Exception e)
- {
- throw new Error("Error creating IOSender thread",e);
- }
-
- senderThread.setDaemon(true);
- senderThread.setName(String.format("IoSender - %s", socket.getRemoteSocketAddress()));
- senderThread.start();
- }
-
- private static final int pof2(int n)
- {
- int result = 1;
- while (result < n)
- {
- result *= 2;
- }
- return result;
- }
-
- public void send(ByteBuffer buf)
- {
- if (closed.get())
- {
- throw new SenderException("sender is closed", exception);
- }
-
- final int size = buffer.length;
- int remaining = buf.remaining();
-
- while (remaining > 0)
- {
- final int hd = head;
- final int tl = tail;
-
- if (hd - tl >= size)
- {
- flush();
- synchronized (notFull)
- {
- long start = System.currentTimeMillis();
- long elapsed = 0;
- while (!closed.get() && head - tail >= size && elapsed < timeout)
- {
- try
- {
- notFull.wait(timeout - elapsed);
- }
- catch (InterruptedException e)
- {
- // pass
- }
- elapsed += System.currentTimeMillis() - start;
- }
-
- if (closed.get())
- {
- throw new SenderException("sender is closed", exception);
- }
-
- if (head - tail >= size)
- {
- throw new SenderException(String.format("write timed out: %s, %s", head, tail));
- }
- }
- continue;
- }
-
- final int hd_idx = mod(hd, size);
- final int tl_idx = mod(tl, size);
- final int length;
-
- if (tl_idx > hd_idx)
- {
- length = Math.min(tl_idx - hd_idx, remaining);
- }
- else
- {
- length = Math.min(size - hd_idx, remaining);
- }
-
- buf.get(buffer, hd_idx, length);
- head += length;
- remaining -= length;
- }
- }
-
- public void flush()
- {
- if (idle)
- {
- synchronized (notEmpty)
- {
- notEmpty.notify();
- }
- }
- }
-
- public void close()
- {
- close(true);
- }
-
- void close(boolean reportException)
- {
- if (!closed.getAndSet(true))
- {
- synchronized (notFull)
- {
- notFull.notify();
- }
-
- synchronized (notEmpty)
- {
- notEmpty.notify();
- }
-
- try
- {
- if (Thread.currentThread() != senderThread)
- {
- senderThread.join(timeout);
- if (senderThread.isAlive())
- {
- throw new SenderException("join timed out");
- }
- }
- ioCtx.getReceiver().close(false);
- }
- catch (InterruptedException e)
- {
- throw new SenderException(e);
- }
-
- if (reportException && exception != null)
- {
- throw new SenderException(exception);
- }
- }
- }
-
- public void run()
- {
- final int size = buffer.length;
- while (true)
- {
- final int hd = head;
- final int tl = tail;
-
- if (hd == tl)
- {
- if (closed.get())
- {
- break;
- }
-
- idle = true;
-
- synchronized (notEmpty)
- {
- while (head == tail && !closed.get())
- {
- try
- {
- notEmpty.wait();
- }
- catch (InterruptedException e)
- {
- // pass
- }
- }
- }
-
- idle = false;
-
- continue;
- }
-
- final int hd_idx = mod(hd, size);
- final int tl_idx = mod(tl, size);
-
- final int length;
- if (tl_idx < hd_idx)
- {
- length = hd_idx - tl_idx;
- }
- else
- {
- length = size - tl_idx;
- }
-
- try
- {
- out.write(buffer, tl_idx, length);
- }
- catch (IOException e)
- {
- log.error(e, "error in write thread");
- exception = e;
- close(false);
- break;
- }
- tail += length;
- if (head - tl >= size)
- {
- synchronized (notFull)
- {
- notFull.notify();
- }
- }
- }
- }
-
- public void setIdleTimeout(int i)
- {
- try
- {
- socket.setSoTimeout(i);
- }
- catch (Exception e)
- {
- throw new SenderException(e);
- }
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/network/io/IoTransport.java b/java/common/src/main/java/org/apache/qpid/transport/network/io/IoTransport.java
deleted file mode 100644
index bfdbb34978..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/network/io/IoTransport.java
+++ /dev/null
@@ -1,231 +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.transport.network.io;
-
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.Socket;
-import java.net.SocketException;
-import java.nio.ByteBuffer;
-
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLEngine;
-
-import org.apache.qpid.protocol.AMQVersionAwareProtocolSession;
-import org.apache.qpid.ssl.SSLContextFactory;
-import org.apache.qpid.transport.Binding;
-import org.apache.qpid.transport.Connection;
-import org.apache.qpid.transport.ConnectionDelegate;
-import org.apache.qpid.transport.Receiver;
-import org.apache.qpid.transport.Sender;
-import org.apache.qpid.transport.TransportException;
-import org.apache.qpid.transport.network.ConnectionBinding;
-import org.apache.qpid.transport.network.security.ssl.SSLReceiver;
-import org.apache.qpid.transport.network.security.ssl.SSLSender;
-import org.apache.qpid.transport.util.Logger;
-
-/**
- * This class provides a socket based transport using the java.io
- * classes.
- *
- * The following params are configurable via JVM arguments
- * TCP_NO_DELAY - amqj.tcpNoDelay
- * SO_RCVBUF - amqj.receiveBufferSize
- * SO_SNDBUF - amqj.sendBufferSize
- */
-public final class IoTransport<E> implements IoContext
-{
-
- static
- {
- org.apache.mina.common.ByteBuffer.setAllocator
- (new org.apache.mina.common.SimpleByteBufferAllocator());
- org.apache.mina.common.ByteBuffer.setUseDirectBuffers
- (Boolean.getBoolean("amqj.enableDirectBuffers"));
- }
-
- private static final Logger log = Logger.get(IoTransport.class);
-
- private static int DEFAULT_READ_WRITE_BUFFER_SIZE = 64 * 1024;
- private static int readBufferSize = Integer.getInteger
- ("amqj.receiveBufferSize", DEFAULT_READ_WRITE_BUFFER_SIZE);
- private static int writeBufferSize = Integer.getInteger
- ("amqj.sendBufferSize", DEFAULT_READ_WRITE_BUFFER_SIZE);
-
- private Socket socket;
- private Sender<ByteBuffer> sender;
- private E endpoint;
- private IoReceiver receiver;
- private long timeout = 60000;
-
- IoTransport(Socket socket, Binding<E,ByteBuffer> binding, boolean ssl)
- {
- this.socket = socket;
-
- if (ssl)
- {
- SSLEngine engine = null;
- SSLContext sslCtx;
- try
- {
- sslCtx = createSSLContext();
- }
- catch (Exception e)
- {
- throw new TransportException("Error creating SSL Context", e);
- }
-
- try
- {
- engine = sslCtx.createSSLEngine();
- engine.setUseClientMode(true);
- }
- catch(Exception e)
- {
- throw new TransportException("Error creating SSL Engine", e);
- }
-
- this.sender = new SSLSender(engine,new IoSender(this, 2*writeBufferSize, timeout));
- this.endpoint = binding.endpoint(sender);
- this.receiver = new IoReceiver(this, new SSLReceiver(engine,binding.receiver(endpoint),(SSLSender)sender),
- 2*readBufferSize, timeout);
-
- log.info("SSL Sender and Receiver initiated");
- }
- else
- {
- this.sender = new IoSender(this, 2*writeBufferSize, timeout);
- this.endpoint = binding.endpoint(sender);
- this.receiver = new IoReceiver(this, binding.receiver(endpoint),
- 2*readBufferSize, timeout);
- }
- }
-
- public Sender<ByteBuffer> getSender()
- {
- return sender;
- }
-
- public IoReceiver getReceiver()
- {
- return receiver;
- }
-
- public Socket getSocket()
- {
- return socket;
- }
-
- public static final <E> E connect(String host, int port,
- Binding<E,ByteBuffer> binding,
- boolean ssl)
- {
- Socket socket = createSocket(host, port);
- IoTransport<E> transport = new IoTransport<E>(socket, binding,ssl);
- return transport.endpoint;
- }
-
- public static final Connection connect(String host, int port,
- ConnectionDelegate delegate,
- boolean ssl)
- {
- return connect(host, port, ConnectionBinding.get(delegate),ssl);
- }
-
- public static void connect_0_9(AMQVersionAwareProtocolSession session, String host, int port, boolean ssl)
- {
- connect(host, port, new Binding_0_9(session),ssl);
- }
-
- private static class Binding_0_9
- implements Binding<AMQVersionAwareProtocolSession,ByteBuffer>
- {
-
- private AMQVersionAwareProtocolSession session;
-
- Binding_0_9(AMQVersionAwareProtocolSession session)
- {
- this.session = session;
- }
-
- public AMQVersionAwareProtocolSession endpoint(Sender<ByteBuffer> sender)
- {
- session.setSender(sender);
- return session;
- }
-
- public Receiver<ByteBuffer> receiver(AMQVersionAwareProtocolSession ssn)
- {
- return new InputHandler_0_9(ssn);
- }
-
- }
-
- private static Socket createSocket(String host, int port)
- {
- try
- {
- InetAddress address = InetAddress.getByName(host);
- Socket socket = new Socket();
- socket.setReuseAddress(true);
- socket.setTcpNoDelay(Boolean.getBoolean("amqj.tcpNoDelay"));
-
- log.debug("default-SO_RCVBUF : %s", socket.getReceiveBufferSize());
- log.debug("default-SO_SNDBUF : %s", socket.getSendBufferSize());
-
- socket.setSendBufferSize(writeBufferSize);
- socket.setReceiveBufferSize(readBufferSize);
-
- log.debug("new-SO_RCVBUF : %s", socket.getReceiveBufferSize());
- log.debug("new-SO_SNDBUF : %s", socket.getSendBufferSize());
-
- socket.connect(new InetSocketAddress(address, port));
- return socket;
- }
- catch (SocketException e)
- {
- throw new TransportException("Error connecting to broker", e);
- }
- catch (IOException e)
- {
- throw new TransportException("Error connecting to broker", e);
- }
- }
-
- private SSLContext createSSLContext() throws Exception
- {
- String trustStorePath = System.getProperty("javax.net.ssl.trustStore");
- String trustStorePassword = System.getProperty("javax.net.ssl.trustStorePassword");
- String trustStoreCertType = System.getProperty("qpid.ssl.trustStoreCertType","SunX509");
-
- String keyStorePath = System.getProperty("javax.net.ssl.keyStore",trustStorePath);
- String keyStorePassword = System.getProperty("javax.net.ssl.keyStorePassword",trustStorePassword);
- String keyStoreCertType = System.getProperty("qpid.ssl.keyStoreCertType","SunX509");
-
- SSLContextFactory sslContextFactory = new SSLContextFactory(trustStorePath,trustStorePassword,
- trustStoreCertType,keyStorePath,
- keyStorePassword,keyStoreCertType);
-
- return sslContextFactory.buildServerContext();
-
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/network/mina/MINANetworkDriver.java b/java/common/src/main/java/org/apache/qpid/transport/network/mina/MINANetworkDriver.java
deleted file mode 100644
index 0f2c0d0226..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/network/mina/MINANetworkDriver.java
+++ /dev/null
@@ -1,435 +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.transport.network.mina;
-
-import org.apache.mina.common.ConnectFuture;
-import org.apache.mina.common.ExecutorThreadModel;
-import org.apache.mina.common.IdleStatus;
-import org.apache.mina.common.IoAcceptor;
-import org.apache.mina.common.IoConnector;
-import org.apache.mina.common.IoFilterChain;
-import org.apache.mina.common.IoHandlerAdapter;
-import org.apache.mina.common.IoSession;
-import org.apache.mina.common.SimpleByteBufferAllocator;
-import org.apache.mina.common.WriteFuture;
-import org.apache.mina.filter.ReadThrottleFilterBuilder;
-import org.apache.mina.filter.SSLFilter;
-import org.apache.mina.filter.WriteBufferLimitFilterBuilder;
-import org.apache.mina.filter.executor.ExecutorFilter;
-import org.apache.mina.transport.socket.nio.MultiThreadSocketConnector;
-import org.apache.mina.transport.socket.nio.SocketAcceptorConfig;
-import org.apache.mina.transport.socket.nio.SocketConnector;
-import org.apache.mina.transport.socket.nio.SocketConnectorConfig;
-import org.apache.mina.transport.socket.nio.SocketSessionConfig;
-import org.apache.mina.util.NewThreadExecutor;
-import org.apache.mina.util.SessionUtil;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import org.apache.qpid.protocol.ProtocolEngine;
-import org.apache.qpid.protocol.ProtocolEngineFactory;
-import org.apache.qpid.ssl.SSLContextFactory;
-import org.apache.qpid.thread.QpidThreadExecutor;
-import org.apache.qpid.transport.NetworkDriver;
-import org.apache.qpid.transport.NetworkDriverConfiguration;
-import org.apache.qpid.transport.OpenException;
-
-import java.io.IOException;
-import java.net.BindException;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.SocketAddress;
-import java.nio.ByteBuffer;
-
-public class MINANetworkDriver extends IoHandlerAdapter implements NetworkDriver
-{
-
- private static final int DEFAULT_BUFFER_SIZE = 32 * 1024;
-
- ProtocolEngine _protocolEngine;
- private boolean _useNIO = false;
- private int _processors = 4;
- private boolean _executorPool = false;
- private SSLContextFactory _sslFactory = null;
- private IoConnector _socketConnector;
- private IoAcceptor _acceptor;
- private IoSession _ioSession;
- private ProtocolEngineFactory _factory;
- private boolean _protectIO;
- private NetworkDriverConfiguration _config;
- private Throwable _lastException;
- private boolean _acceptingConnections = false;
-
- private WriteFuture _lastWriteFuture;
-
- private static final Logger _logger = LoggerFactory.getLogger(MINANetworkDriver.class);
-
- static
- {
- org.apache.mina.common.ByteBuffer.setUseDirectBuffers(Boolean.getBoolean("amqj.enableDirectBuffers"));
-
- //override the MINA defaults to prevent use of the PooledByteBufferAllocator
- org.apache.mina.common.ByteBuffer.setAllocator(new SimpleByteBufferAllocator());
- }
-
- public MINANetworkDriver(boolean useNIO, int processors, boolean executorPool, boolean protectIO)
- {
- _useNIO = useNIO;
- _processors = processors;
- _executorPool = executorPool;
- _protectIO = protectIO;
- }
-
- public MINANetworkDriver(boolean useNIO, int processors, boolean executorPool, boolean protectIO,
- ProtocolEngine protocolEngine, IoSession session)
- {
- _useNIO = useNIO;
- _processors = processors;
- _executorPool = executorPool;
- _protectIO = protectIO;
- _protocolEngine = protocolEngine;
- _ioSession = session;
- _ioSession.setAttachment(_protocolEngine);
- }
-
- public MINANetworkDriver()
- {
-
- }
-
- public MINANetworkDriver(IoConnector ioConnector)
- {
- _socketConnector = ioConnector;
- }
-
- public MINANetworkDriver(IoConnector ioConnector, ProtocolEngine engine)
- {
- _socketConnector = ioConnector;
- _protocolEngine = engine;
- }
-
- public void bind(int port, InetAddress[] addresses, ProtocolEngineFactory factory,
- NetworkDriverConfiguration config, SSLContextFactory sslFactory) throws BindException
- {
-
- _factory = factory;
- _config = config;
-
- if (_useNIO)
- {
- _acceptor = new org.apache.mina.transport.socket.nio.MultiThreadSocketAcceptor(_processors,
- new NewThreadExecutor());
- }
- else
- {
- _acceptor = new org.apache.mina.transport.socket.nio.SocketAcceptor(_processors, new NewThreadExecutor());
- }
-
- SocketAcceptorConfig sconfig = (SocketAcceptorConfig) _acceptor.getDefaultConfig();
- sconfig.setThreadModel(ExecutorThreadModel.getInstance("MINANetworkDriver(Acceptor)"));
- SocketSessionConfig sc = (SocketSessionConfig) sconfig.getSessionConfig();
-
- if (config != null)
- {
- sc.setReceiveBufferSize(config.getReceiveBufferSize());
- sc.setSendBufferSize(config.getSendBufferSize());
- sc.setTcpNoDelay(config.getTcpNoDelay());
- }
-
- if (sslFactory != null)
- {
- _sslFactory = sslFactory;
- }
-
- if (addresses != null && addresses.length > 0)
- {
- for (InetAddress addr : addresses)
- {
- try
- {
- _acceptor.bind(new InetSocketAddress(addr, port), this, sconfig);
- }
- catch (IOException e)
- {
- throw new BindException(String.format("Could not bind to %1s:%2s", addr, port));
- }
- }
- }
- else
- {
- try
- {
- _acceptor.bind(new InetSocketAddress(port), this, sconfig);
- }
- catch (IOException e)
- {
- throw new BindException(String.format("Could not bind to *:%1s", port));
- }
- }
- _acceptingConnections = true;
- }
-
- public SocketAddress getRemoteAddress()
- {
- return _ioSession.getRemoteAddress();
- }
-
- public SocketAddress getLocalAddress()
- {
- return _ioSession.getLocalAddress();
- }
-
-
- public void open(int port, InetAddress destination, ProtocolEngine engine, NetworkDriverConfiguration config,
- SSLContextFactory sslFactory) throws OpenException
- {
- if (sslFactory != null)
- {
- _sslFactory = sslFactory;
- }
-
- if (_useNIO)
- {
- _socketConnector = new MultiThreadSocketConnector(1, new QpidThreadExecutor());
- }
- else
- {
- _socketConnector = new SocketConnector(1, new QpidThreadExecutor()); // non-blocking
- // connector
- }
-
- SocketConnectorConfig cfg = (SocketConnectorConfig) _socketConnector.getDefaultConfig();
- String s = "";
- StackTraceElement[] trace = Thread.currentThread().getStackTrace();
- for(StackTraceElement elt : trace)
- {
- if(elt.getClassName().contains("Test"))
- {
- s = elt.getClassName();
- break;
- }
- }
- cfg.setThreadModel(ExecutorThreadModel.getInstance("MINANetworkDriver(Client)-"+s));
-
- SocketSessionConfig scfg = (SocketSessionConfig) cfg.getSessionConfig();
- scfg.setTcpNoDelay((config != null) ? config.getTcpNoDelay() : true);
- scfg.setSendBufferSize((config != null) ? config.getSendBufferSize() : DEFAULT_BUFFER_SIZE);
- scfg.setReceiveBufferSize((config != null) ? config.getReceiveBufferSize() : DEFAULT_BUFFER_SIZE);
-
- // Don't have the connector's worker thread wait around for other
- // connections (we only use
- // one SocketConnector per connection at the moment anyway). This allows
- // short-running
- // clients (like unit tests) to complete quickly.
- if (_socketConnector instanceof SocketConnector)
- {
- ((SocketConnector) _socketConnector).setWorkerTimeout(0);
- }
-
- ConnectFuture future = _socketConnector.connect(new InetSocketAddress(destination, port), this, cfg);
- future.join();
- if (!future.isConnected())
- {
- throw new OpenException("Could not open connection", _lastException);
- }
- _ioSession = future.getSession();
- _ioSession.setAttachment(engine);
- engine.setNetworkDriver(this);
- _protocolEngine = engine;
- }
-
- public void setMaxReadIdle(int idleTime)
- {
- _ioSession.setIdleTime(IdleStatus.READER_IDLE, idleTime);
- }
-
- public void setMaxWriteIdle(int idleTime)
- {
- _ioSession.setIdleTime(IdleStatus.WRITER_IDLE, idleTime);
- }
-
- public void close()
- {
- if (_lastWriteFuture != null)
- {
- _lastWriteFuture.join();
- }
- if (_acceptor != null)
- {
- _acceptor.unbindAll();
- }
- if (_ioSession != null)
- {
- _ioSession.close();
- }
- }
-
- public void flush()
- {
- if (_lastWriteFuture != null)
- {
- _lastWriteFuture.join();
- }
- }
-
- public void send(ByteBuffer msg)
- {
- org.apache.mina.common.ByteBuffer minaBuf = org.apache.mina.common.ByteBuffer.allocate(msg.capacity());
- minaBuf.put(msg);
- minaBuf.flip();
- _lastWriteFuture = _ioSession.write(minaBuf);
- }
-
- public void setIdleTimeout(int i)
- {
- // MINA doesn't support setting SO_TIMEOUT
- }
-
- public void exceptionCaught(IoSession protocolSession, Throwable throwable) throws Exception
- {
- if (_protocolEngine != null)
- {
- _protocolEngine.exception(throwable);
- }
- else
- {
- _logger.error("Exception thrown and no ProtocolEngine to handle it", throwable);
- }
- _lastException = throwable;
- }
-
- /**
- * Invoked when a message is received on a particular protocol session. Note
- * that a protocol session is directly tied to a particular physical
- * connection.
- *
- * @param protocolSession
- * the protocol session that received the message
- * @param message
- * the message itself (i.e. a decoded frame)
- *
- * @throws Exception
- * if the message cannot be processed
- */
- public void messageReceived(IoSession protocolSession, Object message) throws Exception
- {
- if (message instanceof org.apache.mina.common.ByteBuffer)
- {
- ((ProtocolEngine) protocolSession.getAttachment()).received(((org.apache.mina.common.ByteBuffer) message).buf());
- }
- else
- {
- throw new IllegalStateException("Handed unhandled message. message.class = " + message.getClass() + " message = " + message);
- }
- }
-
- public void sessionClosed(IoSession protocolSession) throws Exception
- {
- ((ProtocolEngine) protocolSession.getAttachment()).closed();
- }
-
- public void sessionCreated(IoSession protocolSession) throws Exception
- {
- // Configure the session with SSL if necessary
- SessionUtil.initialize(protocolSession);
- if (_executorPool)
- {
- if (_sslFactory != null)
- {
- protocolSession.getFilterChain().addAfter("AsynchronousReadFilter", "sslFilter",
- new SSLFilter(_sslFactory.buildServerContext()));
- }
- }
- else
- {
- if (_sslFactory != null)
- {
- protocolSession.getFilterChain().addBefore("protocolFilter", "sslFilter",
- new SSLFilter(_sslFactory.buildServerContext()));
- }
- }
- // Do we want to have read/write buffer limits?
- if (_protectIO)
- {
- //Add IO Protection Filters
- IoFilterChain chain = protocolSession.getFilterChain();
-
- protocolSession.getFilterChain().addLast("tempExecutorFilterForFilterBuilder", new ExecutorFilter());
-
- ReadThrottleFilterBuilder readfilter = new ReadThrottleFilterBuilder();
- readfilter.setMaximumConnectionBufferSize(_config.getReceiveBufferSize());
- readfilter.attach(chain);
-
- WriteBufferLimitFilterBuilder writefilter = new WriteBufferLimitFilterBuilder();
- writefilter.setMaximumConnectionBufferSize(_config.getSendBufferSize());
- writefilter.attach(chain);
-
- protocolSession.getFilterChain().remove("tempExecutorFilterForFilterBuilder");
- }
-
- if (_ioSession == null)
- {
- _ioSession = protocolSession;
- }
-
- if (_acceptingConnections)
- {
- // Set up the protocol engine
- ProtocolEngine protocolEngine = _factory.newProtocolEngine(this);
- MINANetworkDriver newDriver = new MINANetworkDriver(_useNIO, _processors, _executorPool, _protectIO, protocolEngine, protocolSession);
- protocolEngine.setNetworkDriver(newDriver);
- }
- }
-
- public void sessionIdle(IoSession session, IdleStatus status) throws Exception
- {
- if (IdleStatus.WRITER_IDLE.equals(status))
- {
- ((ProtocolEngine) session.getAttachment()).writerIdle();
- }
- else if (IdleStatus.READER_IDLE.equals(status))
- {
- ((ProtocolEngine) session.getAttachment()).readerIdle();
- }
- }
-
- private ProtocolEngine getProtocolEngine()
- {
- return _protocolEngine;
- }
-
- public void setProtocolEngineFactory(ProtocolEngineFactory engineFactory, boolean acceptingConnections)
- {
- _factory = engineFactory;
- _acceptingConnections = acceptingConnections;
- }
-
- public void setProtocolEngine(ProtocolEngine protocolEngine)
- {
- _protocolEngine = protocolEngine;
- if (_ioSession != null)
- {
- _ioSession.setAttachment(protocolEngine);
- }
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/network/mina/MinaHandler.java b/java/common/src/main/java/org/apache/qpid/transport/network/mina/MinaHandler.java
deleted file mode 100644
index b89eed48b0..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/network/mina/MinaHandler.java
+++ /dev/null
@@ -1,274 +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.transport.network.mina;
-
-import java.io.IOException;
-import java.net.InetSocketAddress;
-import java.net.SocketAddress;
-
-import org.apache.mina.common.*;
-
-import org.apache.mina.transport.socket.nio.SocketAcceptor;
-import org.apache.mina.transport.socket.nio.SocketSessionConfig;
-import org.apache.mina.transport.socket.nio.SocketConnector;
-import org.apache.mina.filter.ReadThrottleFilterBuilder;
-import org.apache.mina.filter.WriteBufferLimitFilterBuilder;
-import org.apache.mina.filter.executor.ExecutorFilter;
-
-import org.apache.qpid.transport.Binding;
-import org.apache.qpid.transport.Connection;
-import org.apache.qpid.transport.ConnectionDelegate;
-import org.apache.qpid.transport.Receiver;
-import org.apache.qpid.transport.Sender;
-import org.apache.qpid.transport.network.ConnectionBinding;
-
-import org.apache.qpid.transport.util.Logger;
-
-import org.apache.qpid.transport.network.Assembler;
-import org.apache.qpid.transport.network.Disassembler;
-import org.apache.qpid.transport.network.InputHandler;
-
-import static org.apache.qpid.transport.util.Functions.*;
-
-/**
- * MinaHandler
- *
- * @author Rafael H. Schloming
- */
-//RA making this public until we sort out the package issues
-public class MinaHandler<E> implements IoHandler
-{
- /** Default buffer size for pending messages reads */
- private static final String DEFAULT_READ_BUFFER_LIMIT = "262144";
- /** Default buffer size for pending messages writes */
- private static final String DEFAULT_WRITE_BUFFER_LIMIT = "262144";
- private static final int MAX_RCVBUF = 64*1024;
-
- private static final Logger log = Logger.get(MinaHandler.class);
-
- static
- {
- ByteBuffer.setAllocator(new SimpleByteBufferAllocator());
- ByteBuffer.setUseDirectBuffers(Boolean.getBoolean("amqj.enableDirectBuffers"));
- }
-
- private final Binding<E,java.nio.ByteBuffer> binding;
-
- private MinaHandler(Binding<E,java.nio.ByteBuffer> binding)
- {
- this.binding = binding;
- }
-
- public void messageReceived(IoSession ssn, Object obj)
- {
- Attachment<E> attachment = (Attachment<E>) ssn.getAttachment();
- ByteBuffer buf = (ByteBuffer) obj;
- try
- {
- attachment.receiver.received(buf.buf());
- }
- catch (Throwable t)
- {
- log.error(t, "exception handling buffer %s", str(buf.buf()));
- throw new RuntimeException(t);
- }
- }
-
- public void messageSent(IoSession ssn, Object obj)
- {
- // do nothing
- }
-
- public void exceptionCaught(IoSession ssn, Throwable e)
- {
- Attachment<E> attachment = (Attachment<E>) ssn.getAttachment();
- attachment.receiver.exception(e);
- }
-
- /**
- * Invoked by MINA when a MINA session for a new connection is created. This method sets up the filter chain on the
- * session, which filters the events handled by this handler. The filter chain consists of, handing off events
- * to an optional protectio
- *
- * @param session The MINA session.
- * @throws Exception Any underlying exceptions are allowed to fall through to MINA.
- */
- public void sessionCreated(IoSession session) throws Exception
- {
- log.debug("Protocol session created for session " + System.identityHashCode(session));
-
- if (Boolean.getBoolean("protectio"))
- {
- try
- {
- //Add IO Protection Filters
- IoFilterChain chain = session.getFilterChain();
-
- session.getFilterChain().addLast("tempExecutorFilterForFilterBuilder", new ExecutorFilter());
-
- ReadThrottleFilterBuilder readfilter = new ReadThrottleFilterBuilder();
- readfilter.setMaximumConnectionBufferSize(
- Integer.parseInt(System.getProperty("qpid.read.buffer.limit", DEFAULT_READ_BUFFER_LIMIT)));
- readfilter.attach(chain);
-
- WriteBufferLimitFilterBuilder writefilter = new WriteBufferLimitFilterBuilder();
- writefilter.setMaximumConnectionBufferSize(
- Integer.parseInt(System.getProperty("qpid.write.buffer.limit", DEFAULT_WRITE_BUFFER_LIMIT)));
- writefilter.attach(chain);
- session.getFilterChain().remove("tempExecutorFilterForFilterBuilder");
-
- log.info("Using IO Read/Write Filter Protection");
- }
- catch (Exception e)
- {
- log.error("Unable to attach IO Read/Write Filter Protection :" + e.getMessage());
- }
- }
- }
-
- public void sessionOpened(final IoSession ssn)
- {
- log.debug("opened: %s", this);
- E endpoint = binding.endpoint(new MinaSender(ssn));
- Attachment<E> attachment =
- new Attachment<E>(endpoint, binding.receiver(endpoint));
-
- // We need to synchronize and notify here because the MINA
- // connect future returns the session prior to the attachment
- // being set. This is arguably a bug in MINA.
- synchronized (ssn)
- {
- ssn.setAttachment(attachment);
- ssn.notifyAll();
- }
- }
-
- public void sessionClosed(IoSession ssn)
- {
- log.debug("closed: %s", ssn);
- Attachment<E> attachment = (Attachment<E>) ssn.getAttachment();
- attachment.receiver.closed();
- ssn.setAttachment(null);
- }
-
- public void sessionIdle(IoSession ssn, IdleStatus status)
- {
- // do nothing
- }
-
- private static class Attachment<E>
- {
-
- E endpoint;
- Receiver<java.nio.ByteBuffer> receiver;
-
- Attachment(E endpoint, Receiver<java.nio.ByteBuffer> receiver)
- {
- this.endpoint = endpoint;
- this.receiver = receiver;
- }
- }
-
- public static final void accept(String host, int port,
- Binding<?,java.nio.ByteBuffer> binding)
- throws IOException
- {
- accept(new InetSocketAddress(host, port), binding);
- }
-
- public static final <E> void accept(SocketAddress address,
- Binding<E,java.nio.ByteBuffer> binding)
- throws IOException
- {
- IoAcceptor acceptor = new SocketAcceptor();
- acceptor.bind(address, new MinaHandler<E>(binding));
- }
-
- public static final <E> E connect(String host, int port,
- Binding<E,java.nio.ByteBuffer> binding)
- {
- return connect(new InetSocketAddress(host, port), binding);
- }
-
- public static final <E> E connect(SocketAddress address,
- Binding<E,java.nio.ByteBuffer> binding)
- {
- MinaHandler<E> handler = new MinaHandler<E>(binding);
- SocketConnector connector = new SocketConnector();
- IoServiceConfig acceptorConfig = connector.getDefaultConfig();
- acceptorConfig.setThreadModel(ThreadModel.MANUAL);
- SocketSessionConfig scfg = (SocketSessionConfig) acceptorConfig.getSessionConfig();
- scfg.setTcpNoDelay(Boolean.getBoolean("amqj.tcpNoDelay"));
- Integer sendBufferSize = Integer.getInteger("amqj.sendBufferSize");
- if (sendBufferSize != null && sendBufferSize > 0)
- {
- scfg.setSendBufferSize(sendBufferSize);
- }
- Integer receiveBufferSize = Integer.getInteger("amqj.receiveBufferSize");
- if (receiveBufferSize != null && receiveBufferSize > 0)
- {
- scfg.setReceiveBufferSize(receiveBufferSize);
- }
- else if (scfg.getReceiveBufferSize() > MAX_RCVBUF)
- {
- scfg.setReceiveBufferSize(MAX_RCVBUF);
- }
- connector.setWorkerTimeout(0);
- ConnectFuture cf = connector.connect(address, handler);
- cf.join();
- IoSession ssn = cf.getSession();
-
- // We need to synchronize and wait here because the MINA
- // connect future returns the session prior to the attachment
- // being set. This is arguably a bug in MINA.
- synchronized (ssn)
- {
- while (ssn.getAttachment() == null)
- {
- try
- {
- ssn.wait();
- }
- catch (InterruptedException e)
- {
- throw new RuntimeException(e);
- }
- }
- }
-
- Attachment<E> attachment = (Attachment<E>) ssn.getAttachment();
- return attachment.endpoint;
- }
-
- public static final void accept(String host, int port,
- ConnectionDelegate delegate)
- throws IOException
- {
- accept(host, port, ConnectionBinding.get(delegate));
- }
-
- public static final Connection connect(String host, int port,
- ConnectionDelegate delegate)
- {
- return connect(host, port, ConnectionBinding.get(delegate));
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/network/mina/MinaSender.java b/java/common/src/main/java/org/apache/qpid/transport/network/mina/MinaSender.java
deleted file mode 100644
index 22b9c5e784..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/network/mina/MinaSender.java
+++ /dev/null
@@ -1,90 +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.transport.network.mina;
-
-import org.apache.mina.common.ByteBuffer;
-import org.apache.mina.common.CloseFuture;
-import org.apache.mina.common.IoSession;
-import org.apache.mina.common.WriteFuture;
-import org.apache.qpid.transport.Sender;
-import org.apache.qpid.transport.TransportException;
-
-
-/**
- * MinaSender
- */
-
-public class MinaSender implements Sender<java.nio.ByteBuffer>
-{
- private static final int TIMEOUT = 2 * 60 * 1000;
-
- private final IoSession session;
- private WriteFuture lastWrite = null;
-
- public MinaSender(IoSession session)
- {
- this.session = session;
- }
-
- public void send(java.nio.ByteBuffer buf)
- {
- if (session.isClosing())
- {
- throw new TransportException("attempted to write to a closed socket");
- }
-
- synchronized (this)
- {
- lastWrite = session.write(ByteBuffer.wrap(buf));
- }
- }
-
- public void flush()
- {
- // pass
- }
-
- public synchronized void close()
- {
- // MINA will sometimes throw away in-progress writes when you
- // ask it to close
- synchronized (this)
- {
- if (lastWrite != null)
- {
- lastWrite.join();
- }
- }
- CloseFuture closed = session.close();
- closed.join();
- }
-
- public void setIdleTimeout(int i)
- {
- //noop
- }
-
- public long getIdleTimeout()
- {
- return 0;
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/network/nio/NioHandler.java b/java/common/src/main/java/org/apache/qpid/transport/network/nio/NioHandler.java
deleted file mode 100644
index 84e66c25bd..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/network/nio/NioHandler.java
+++ /dev/null
@@ -1,135 +0,0 @@
-package org.apache.qpid.transport.network.nio;
-/*
- *
- * 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 java.io.IOException;
-import java.net.InetSocketAddress;
-import java.net.SocketAddress;
-import java.net.SocketException;
-import java.nio.ByteBuffer;
-import java.nio.channels.SocketChannel;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-import org.apache.qpid.transport.Connection;
-import org.apache.qpid.transport.ConnectionDelegate;
-import org.apache.qpid.transport.Receiver;
-import org.apache.qpid.transport.network.Assembler;
-import org.apache.qpid.transport.network.Disassembler;
-import org.apache.qpid.transport.network.InputHandler;
-
-public class NioHandler implements Runnable
-{
- private Receiver<ByteBuffer> _receiver;
- private SocketChannel _ch;
- private ByteBuffer _readBuf;
- private static Map<Long,NioSender> _handlers = new ConcurrentHashMap<Long,NioSender>();
-
- private NioHandler(){}
-
- public static final Connection connect(String host, int port,
- ConnectionDelegate delegate)
- {
- NioHandler handler = new NioHandler();
- return handler.connectInternal(host,port,delegate);
- }
-
- private Connection connectInternal(String host, int port,
- ConnectionDelegate delegate)
- {
- try
- {
- SocketAddress address = new InetSocketAddress(host,port);
- _ch = SocketChannel.open();
- _ch.socket().setReuseAddress(true);
- _ch.configureBlocking(true);
- _ch.socket().setTcpNoDelay(true);
- if (address != null)
- {
- _ch.socket().connect(address);
- }
- while (_ch.isConnectionPending())
- {
-
- }
-
- }
- catch (SocketException e)
- {
-
- e.printStackTrace();
- }
- catch (IOException e)
- {
- e.printStackTrace();
- }
-
- NioSender sender = new NioSender(_ch);
- Connection con = new Connection();
- con.setSender(new Disassembler(sender, 64*1024 - 1));
- con.setConnectionDelegate(delegate);
-
- _handlers.put(con.getConnectionId(),sender);
-
- _receiver = new InputHandler(new Assembler(con), InputHandler.State.FRAME_HDR);
-
- Thread t = new Thread(this);
- t.start();
-
- return con;
- }
-
- public void run()
- {
- _readBuf = ByteBuffer.allocate(512);
- long read = 0;
- while(_ch.isConnected() && _ch.isOpen())
- {
- try
- {
- read = _ch.read(_readBuf);
- if (read > 0)
- {
- _readBuf.flip();
- ByteBuffer b = ByteBuffer.allocate(_readBuf.remaining());
- b.put(_readBuf);
- b.flip();
- _readBuf.clear();
- _receiver.received(b);
- }
- }
- catch(Exception e)
- {
- e.printStackTrace();
- }
- }
-
- //throw new EOFException("The underlying socket/channel has closed");
- }
-
- public static void startBatchingFrames(int connectionId)
- {
- NioSender sender = _handlers.get(connectionId);
- sender.setStartBatching();
- }
-
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/network/nio/NioSender.java b/java/common/src/main/java/org/apache/qpid/transport/network/nio/NioSender.java
deleted file mode 100644
index 2fa875f279..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/network/nio/NioSender.java
+++ /dev/null
@@ -1,126 +0,0 @@
-package org.apache.qpid.transport.network.nio;
-/*
- *
- * 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 java.nio.ByteBuffer;
-import java.nio.channels.SocketChannel;
-
-import org.apache.qpid.transport.Sender;
-
-public class NioSender implements Sender<java.nio.ByteBuffer>
-{
- private final Object lock = new Object();
- private SocketChannel _ch;
- private boolean _batch = false;
- private ByteBuffer _batcher;
-
- public NioSender(SocketChannel ch)
- {
- this._ch = ch;
- }
-
- public void send(java.nio.ByteBuffer buf)
- {
- if (_batch)
- {
- //System.out.println(_batcher.position() + " , " + buf.remaining() + " , " + buf.position() + ","+_batcher.capacity());
- if (_batcher.position() + buf.remaining() >= _batcher.capacity())
- {
- _batcher.flip();
- write(_batcher);
- _batcher.clear();
- if (buf.remaining() > _batcher.capacity())
- {
- write(buf);
- }
- else
- {
- _batcher.put(buf);
- }
- }
- else
- {
- _batcher.put(buf);
- }
- }
- else
- {
- write(buf);
- }
- }
-
- public void flush()
- {
- // pass
- }
-
- private void write(java.nio.ByteBuffer buf)
- {
- synchronized (lock)
- {
- if( _ch.isConnected() && _ch.isOpen())
- {
- try
- {
- _ch.write(buf);
- }
- catch(Exception e)
- {
- e.fillInStackTrace();
- }
- }
- else
- {
- throw new RuntimeException("Trying to write on a closed socket");
- }
-
- }
- }
-
- public void setStartBatching()
- {
- _batch = true;
- _batcher = ByteBuffer.allocate(1024);
- }
-
- public void close()
- {
- // MINA will sometimes throw away in-progress writes when you
- // ask it to close
- synchronized (lock)
- {
- try
- {
- _ch.close();
- }
- catch(Exception e)
- {
- e.printStackTrace();
- }
- }
- }
-
- public void setIdleTimeout(int i)
- {
- //noop
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/network/security/SecurityLayer.java b/java/common/src/main/java/org/apache/qpid/transport/network/security/SecurityLayer.java
deleted file mode 100644
index 3f0966903d..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/network/security/SecurityLayer.java
+++ /dev/null
@@ -1,185 +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.transport.network.security;
-
-import java.nio.ByteBuffer;
-
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLEngine;
-
-import org.apache.qpid.transport.Connection;
-import org.apache.qpid.transport.ConnectionListener;
-import org.apache.qpid.transport.ConnectionSettings;
-import org.apache.qpid.transport.Receiver;
-import org.apache.qpid.transport.Sender;
-import org.apache.qpid.transport.TransportException;
-import org.apache.qpid.transport.network.security.sasl.SASLReceiver;
-import org.apache.qpid.transport.network.security.sasl.SASLSender;
-import org.apache.qpid.transport.network.security.ssl.SSLReceiver;
-import org.apache.qpid.transport.network.security.ssl.SSLSender;
-import org.apache.qpid.transport.network.security.ssl.SSLUtil;
-
-public class SecurityLayer
-{
- ConnectionSettings settings;
- Connection con;
- SSLSecurityLayer sslLayer;
- SASLSecurityLayer saslLayer;
-
- public void init(Connection con) throws TransportException
- {
- this.con = con;
- this.settings = con.getConnectionSettings();
- if (settings.isUseSSL())
- {
- sslLayer = new SSLSecurityLayer();
- }
- if (settings.isUseSASLEncryption())
- {
- saslLayer = new SASLSecurityLayer();
- }
-
- }
-
- public Sender<ByteBuffer> sender(Sender<ByteBuffer> delegate)
- {
- Sender<ByteBuffer> sender = delegate;
-
- if (settings.isUseSSL())
- {
- sender = sslLayer.sender(sender);
- }
-
- if (settings.isUseSASLEncryption())
- {
- sender = saslLayer.sender(sender);
- }
-
- return sender;
- }
-
- public Receiver<ByteBuffer> receiver(Receiver<ByteBuffer> delegate)
- {
- Receiver<ByteBuffer> receiver = delegate;
-
- if (settings.isUseSSL())
- {
- receiver = sslLayer.receiver(receiver);
- }
-
- if (settings.isUseSASLEncryption())
- {
- receiver = saslLayer.receiver(receiver);
- }
-
- return receiver;
- }
-
- public String getUserID()
- {
- if (settings.isUseSSL())
- {
- return sslLayer.getUserID();
- }
- else
- {
- return null;
- }
- }
-
- class SSLSecurityLayer
- {
- SSLEngine engine;
- SSLSender sender;
-
- public SSLSecurityLayer()
- {
- SSLContext sslCtx;
- try
- {
- sslCtx = SSLUtil.createSSLContext(settings);
- }
- catch (Exception e)
- {
- throw new TransportException("Error creating SSL Context", e);
- }
-
- try
- {
- engine = sslCtx.createSSLEngine();
- engine.setUseClientMode(true);
- }
- catch(Exception e)
- {
- throw new TransportException("Error creating SSL Engine", e);
- }
- }
-
- public SSLSender sender(Sender<ByteBuffer> delegate)
- {
- sender = new SSLSender(engine,delegate);
- sender.setConnectionSettings(settings);
- return sender;
- }
-
- public SSLReceiver receiver(Receiver<ByteBuffer> delegate)
- {
- if (sender == null)
- {
- throw new
- IllegalStateException("SecurityLayer.sender method should be " +
- "invoked before SecurityLayer.receiver");
- }
-
- SSLReceiver receiver = new SSLReceiver(engine,delegate,sender);
- receiver.setConnectionSettings(settings);
- return receiver;
- }
-
- public String getUserID()
- {
- return SSLUtil.retriveIdentity(engine);
- }
-
- }
-
- class SASLSecurityLayer
- {
- public SASLSecurityLayer()
- {
- }
-
- public SASLSender sender(Sender<ByteBuffer> delegate)
- {
- SASLSender sender = new SASLSender(delegate);
- con.addConnectionListener((ConnectionListener)sender);
- return sender;
- }
-
- public SASLReceiver receiver(Receiver<ByteBuffer> delegate)
- {
- SASLReceiver receiver = new SASLReceiver(delegate);
- con.addConnectionListener((ConnectionListener)receiver);
- return receiver;
- }
-
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/network/security/sasl/SASLEncryptor.java b/java/common/src/main/java/org/apache/qpid/transport/network/security/sasl/SASLEncryptor.java
deleted file mode 100644
index 7964239e31..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/network/security/sasl/SASLEncryptor.java
+++ /dev/null
@@ -1,66 +0,0 @@
-package org.apache.qpid.transport.network.security.sasl;
-/*
- *
- * 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 java.util.concurrent.atomic.AtomicBoolean;
-
-import javax.security.sasl.Sasl;
-import javax.security.sasl.SaslClient;
-
-import org.apache.qpid.transport.Connection;
-import org.apache.qpid.transport.ConnectionException;
-import org.apache.qpid.transport.ConnectionListener;
-
-public abstract class SASLEncryptor implements ConnectionListener
-{
- protected SaslClient saslClient;
- protected boolean securityLayerEstablished = false;
- protected int sendBuffSize;
- protected int recvBuffSize;
-
- public boolean isSecurityLayerEstablished()
- {
- return securityLayerEstablished;
- }
-
- public void opened(Connection conn)
- {
- if (conn.getSaslClient() != null)
- {
- saslClient = conn.getSaslClient();
- if (saslClient.isComplete() && saslClient.getNegotiatedProperty(Sasl.QOP) == "auth-conf")
- {
- sendBuffSize = Integer.parseInt(
- (String)saslClient.getNegotiatedProperty(Sasl.RAW_SEND_SIZE));
- recvBuffSize = Integer.parseInt(
- (String)saslClient.getNegotiatedProperty(Sasl.MAX_BUFFER));
- securityLayerEstablished();
- securityLayerEstablished = true;
- }
- }
- }
-
- public void exception(Connection conn, ConnectionException exception){}
- public void closed(Connection conn) {}
-
- public abstract void securityLayerEstablished();
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/network/security/sasl/SASLReceiver.java b/java/common/src/main/java/org/apache/qpid/transport/network/security/sasl/SASLReceiver.java
deleted file mode 100644
index 86106318ef..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/network/security/sasl/SASLReceiver.java
+++ /dev/null
@@ -1,86 +0,0 @@
-package org.apache.qpid.transport.network.security.sasl;
-/*
- *
- * 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 java.nio.ByteBuffer;
-
-import javax.security.sasl.SaslClient;
-import javax.security.sasl.SaslException;
-
-import org.apache.qpid.transport.Receiver;
-import org.apache.qpid.transport.SenderException;
-import org.apache.qpid.transport.util.Logger;
-
-public class SASLReceiver extends SASLEncryptor implements Receiver<ByteBuffer> {
-
- Receiver<ByteBuffer> delegate;
- private byte[] netData;
- private static final Logger log = Logger.get(SASLReceiver.class);
-
- public SASLReceiver(Receiver<ByteBuffer> delegate)
- {
- this.delegate = delegate;
- }
-
- public void closed()
- {
- delegate.closed();
- }
-
-
- public void exception(Throwable t)
- {
- delegate.exception(t);
- }
-
- public void received(ByteBuffer buf)
- {
- if (isSecurityLayerEstablished())
- {
- while (buf.hasRemaining())
- {
- int length = Math.min(buf.remaining(),recvBuffSize);
- buf.get(netData, 0, length);
- try
- {
- byte[] out = saslClient.unwrap(netData, 0, length);
- delegate.received(ByteBuffer.wrap(out));
- }
- catch (SaslException e)
- {
- throw new SenderException("SASL Sender, Error occurred while encrypting data",e);
- }
- }
- }
- else
- {
- delegate.received(buf);
- }
- }
-
- public void securityLayerEstablished()
- {
- netData = new byte[recvBuffSize];
- log.debug("SASL Security Layer Established");
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/network/security/sasl/SASLSender.java b/java/common/src/main/java/org/apache/qpid/transport/network/security/sasl/SASLSender.java
deleted file mode 100644
index 27255f79f6..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/network/security/sasl/SASLSender.java
+++ /dev/null
@@ -1,123 +0,0 @@
-package org.apache.qpid.transport.network.security.sasl;
-/*
- *
- * 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 java.nio.ByteBuffer;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import javax.security.sasl.SaslClient;
-import javax.security.sasl.SaslException;
-
-import org.apache.qpid.transport.Sender;
-import org.apache.qpid.transport.SenderException;
-import org.apache.qpid.transport.util.Logger;
-
-public class SASLSender extends SASLEncryptor implements Sender<ByteBuffer> {
-
- protected Sender<ByteBuffer> delegate;
- private byte[] appData;
- private final AtomicBoolean closed = new AtomicBoolean(false);
- private static final Logger log = Logger.get(SASLSender.class);
-
- public SASLSender(Sender<ByteBuffer> delegate)
- {
- this.delegate = delegate;
- log.debug("SASL Sender enabled");
- }
-
- @Override
- public void close()
- {
-
- if (!closed.getAndSet(true))
- {
- delegate.close();
- if (isSecurityLayerEstablished())
- {
- try
- {
- saslClient.dispose();
- }
- catch (SaslException e)
- {
- throw new SenderException("Error closing SASL Sender",e);
- }
- }
- }
- }
-
- @Override
- public void flush()
- {
- delegate.flush();
- }
-
- @Override
- public void send(ByteBuffer buf)
- {
- if (closed.get())
- {
- throw new SenderException("SSL Sender is closed");
- }
-
- if (isSecurityLayerEstablished())
- {
- while (buf.hasRemaining())
- {
- int length = Math.min(buf.remaining(),sendBuffSize);
- log.debug("sendBuffSize %s", sendBuffSize);
- log.debug("buf.remaining() %s", buf.remaining());
-
- buf.get(appData, 0, length);
- try
- {
- byte[] out = saslClient.wrap(appData, 0, length);
- log.debug("out.length %s", out.length);
-
- delegate.send(ByteBuffer.wrap(out));
- }
- catch (SaslException e)
- {
- log.error("Exception while encrypting data.",e);
- throw new SenderException("SASL Sender, Error occurred while encrypting data",e);
- }
- }
- }
- else
- {
- delegate.send(buf);
- }
- }
-
- @Override
- public void setIdleTimeout(int i)
- {
- delegate.setIdleTimeout(i);
- }
-
- public void securityLayerEstablished()
- {
- appData = new byte[sendBuffSize];
- log.debug("SASL Security Layer Established");
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/network/security/ssl/QpidClientX509KeyManager.java b/java/common/src/main/java/org/apache/qpid/transport/network/security/ssl/QpidClientX509KeyManager.java
deleted file mode 100644
index 14f28f8828..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/network/security/ssl/QpidClientX509KeyManager.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.transport.network.security.ssl;
-
-import java.net.Socket;
-import java.security.KeyStore;
-import java.security.Principal;
-import java.security.PrivateKey;
-import java.security.cert.X509Certificate;
-
-import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.SSLEngine;
-import javax.net.ssl.X509ExtendedKeyManager;
-
-import org.apache.qpid.transport.util.Logger;
-
-public class QpidClientX509KeyManager extends X509ExtendedKeyManager
-{
- private static final Logger log = Logger.get(QpidClientX509KeyManager.class);
-
- X509ExtendedKeyManager delegate;
- String alias;
-
- public QpidClientX509KeyManager(String alias, String keyStorePath,
- String keyStorePassword,String keyStoreCertType) throws Exception
- {
- this.alias = alias;
- KeyStore ks = SSLUtil.getInitializedKeyStore(keyStorePath,keyStorePassword);
- KeyManagerFactory kmf = KeyManagerFactory.getInstance(keyStoreCertType);
- kmf.init(ks, keyStorePassword.toCharArray());
- this.delegate = (X509ExtendedKeyManager)kmf.getKeyManagers()[0];
- }
-
- @Override
- public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket)
- {
- log.debug("chooseClientAlias:Returning alias " + alias);
- return alias;
- }
-
- @Override
- public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket)
- {
- return delegate.chooseServerAlias(keyType, issuers, socket);
- }
-
- @Override
- public X509Certificate[] getCertificateChain(String alias)
- {
- return delegate.getCertificateChain(alias);
- }
-
- @Override
- public String[] getClientAliases(String keyType, Principal[] issuers)
- {
- log.debug("getClientAliases:Returning alias " + alias);
- return new String[]{alias};
- }
-
- @Override
- public PrivateKey getPrivateKey(String alias)
- {
- return delegate.getPrivateKey(alias);
- }
-
- @Override
- public String[] getServerAliases(String keyType, Principal[] issuers)
- {
- return delegate.getServerAliases(keyType, issuers);
- }
-
- public String chooseEngineClientAlias(String[] keyType, Principal[] issuers, SSLEngine engine)
- {
- log.debug("chooseEngineClientAlias:Returning alias " + alias);
- return alias;
- }
-
- public String chooseEngineServerAlias(String keyType, Principal[] issuers, SSLEngine engine)
- {
- return delegate.chooseEngineServerAlias(keyType, issuers, engine);
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/network/security/ssl/SSLReceiver.java b/java/common/src/main/java/org/apache/qpid/transport/network/security/ssl/SSLReceiver.java
deleted file mode 100644
index e227a51729..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/network/security/ssl/SSLReceiver.java
+++ /dev/null
@@ -1,202 +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.transport.network.security.ssl;
-
-import java.nio.ByteBuffer;
-
-import javax.net.ssl.SSLEngine;
-import javax.net.ssl.SSLEngineResult;
-import javax.net.ssl.SSLException;
-import javax.net.ssl.SSLEngineResult.HandshakeStatus;
-import javax.net.ssl.SSLEngineResult.Status;
-
-import org.apache.qpid.transport.ConnectionSettings;
-import org.apache.qpid.transport.Receiver;
-import org.apache.qpid.transport.TransportException;
-import org.apache.qpid.transport.util.Logger;
-
-public class SSLReceiver implements Receiver<ByteBuffer>
-{
- private Receiver<ByteBuffer> delegate;
- private SSLEngine engine;
- private SSLSender sender;
- private int sslBufSize;
- private ByteBuffer appData;
- private ByteBuffer localBuffer;
- private boolean dataCached = false;
- private final Object notificationToken;
- private ConnectionSettings settings;
-
- private static final Logger log = Logger.get(SSLReceiver.class);
-
- public SSLReceiver(SSLEngine engine, Receiver<ByteBuffer> delegate,SSLSender sender)
- {
- this.engine = engine;
- this.delegate = delegate;
- this.sender = sender;
- this.sslBufSize = engine.getSession().getApplicationBufferSize();
- appData = ByteBuffer.allocate(sslBufSize);
- localBuffer = ByteBuffer.allocate(sslBufSize);
- notificationToken = sender.getNotificationToken();
- }
-
- public void setConnectionSettings(ConnectionSettings settings)
- {
- this.settings = settings;
- }
-
- public void closed()
- {
- delegate.closed();
- }
-
- public void exception(Throwable t)
- {
- delegate.exception(t);
- }
-
- private ByteBuffer addPreviouslyUnreadData(ByteBuffer buf)
- {
- if (dataCached)
- {
- ByteBuffer b = ByteBuffer.allocate(localBuffer.remaining() + buf.remaining());
- b.put(localBuffer);
- b.put(buf);
- b.flip();
- dataCached = false;
- return b;
- }
- else
- {
- return buf;
- }
- }
-
- public void received(ByteBuffer buf)
- {
- ByteBuffer netData = addPreviouslyUnreadData(buf);
-
- HandshakeStatus handshakeStatus;
- Status status;
-
- while (netData.hasRemaining())
- {
- try
- {
- SSLEngineResult result = engine.unwrap(netData, appData);
- synchronized (notificationToken)
- {
- notificationToken.notifyAll();
- }
-
- int read = result.bytesProduced();
- status = result.getStatus();
- handshakeStatus = result.getHandshakeStatus();
-
- if (read > 0)
- {
- int limit = appData.limit();
- appData.limit(appData.position());
- appData.position(appData.position() - read);
-
- ByteBuffer data = appData.slice();
-
- appData.limit(limit);
- appData.position(appData.position() + read);
-
- delegate.received(data);
- }
-
-
- switch(status)
- {
- case CLOSED:
- synchronized(notificationToken)
- {
- notificationToken.notifyAll();
- }
- return;
-
- case BUFFER_OVERFLOW:
- appData = ByteBuffer.allocate(sslBufSize);
- continue;
-
- case BUFFER_UNDERFLOW:
- localBuffer.clear();
- localBuffer.put(netData);
- localBuffer.flip();
- dataCached = true;
- break;
-
- case OK:
- break; // do nothing
-
- default:
- throw new IllegalStateException("SSLReceiver: Invalid State " + status);
- }
-
- switch (handshakeStatus)
- {
- case NEED_UNWRAP:
- if (netData.hasRemaining())
- {
- continue;
- }
- break;
-
- case NEED_TASK:
- sender.doTasks();
- handshakeStatus = engine.getHandshakeStatus();
-
- case FINISHED:
- if (this.settings != null && this.settings.isVerifyHostname() )
- {
- SSLUtil.verifyHostname(engine, this.settings.getHost());
- }
-
- case NEED_WRAP:
- case NOT_HANDSHAKING:
- synchronized(notificationToken)
- {
- notificationToken.notifyAll();
- }
- break;
-
- default:
- throw new IllegalStateException("SSLReceiver: Invalid State " + status);
- }
-
-
- }
- catch(SSLException e)
- {
- log.error(e, "Error caught in SSLReceiver");
- sender.setErrorFlag();
- synchronized(notificationToken)
- {
- notificationToken.notifyAll();
- }
- exception(new TransportException("Error in SSLReceiver",e));
- }
-
- }
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/network/security/ssl/SSLSender.java b/java/common/src/main/java/org/apache/qpid/transport/network/security/ssl/SSLSender.java
deleted file mode 100644
index cd47a11825..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/network/security/ssl/SSLSender.java
+++ /dev/null
@@ -1,274 +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.transport.network.security.ssl;
-
-import java.nio.ByteBuffer;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import javax.net.ssl.SSLEngine;
-import javax.net.ssl.SSLEngineResult;
-import javax.net.ssl.SSLException;
-import javax.net.ssl.SSLEngineResult.HandshakeStatus;
-import javax.net.ssl.SSLEngineResult.Status;
-
-import org.apache.qpid.transport.ConnectionSettings;
-import org.apache.qpid.transport.Sender;
-import org.apache.qpid.transport.SenderException;
-import org.apache.qpid.transport.util.Logger;
-
-public class SSLSender implements Sender<ByteBuffer>
-{
- private Sender<ByteBuffer> delegate;
- private SSLEngine engine;
- private int sslBufSize;
- private ByteBuffer netData;
- private long timeout = 30000;
- private ConnectionSettings settings;
-
- private final Object engineState = new Object();
- private final AtomicBoolean closed = new AtomicBoolean(false);
- private final AtomicBoolean error = new AtomicBoolean(false);
-
- private static final Logger log = Logger.get(SSLSender.class);
-
- public SSLSender(SSLEngine engine, Sender<ByteBuffer> delegate)
- {
- this.engine = engine;
- this.delegate = delegate;
- sslBufSize = engine.getSession().getPacketBufferSize();
- netData = ByteBuffer.allocate(sslBufSize);
- timeout = Long.getLong("qpid.ssl_timeout", 60000);
- }
-
- public void setConnectionSettings(ConnectionSettings settings)
- {
- this.settings = settings;
- }
-
- public void close()
- {
- if (!closed.getAndSet(true))
- {
- if (engine.isOutboundDone())
- {
- return;
- }
- log.debug("Closing SSL connection");
-
- engine.closeOutbound();
- try
- {
- tearDownSSLConnection();
- }
- catch(Exception e)
- {
- throw new SenderException("Error closing SSL connection",e);
- }
-
-
- synchronized(engineState)
- {
- while (!engine.isOutboundDone())
- {
- try
- {
- engineState.wait();
- }
- catch(InterruptedException e)
- {
- // pass
- }
-
- }
- }
- delegate.close();
- }
- }
-
- private void tearDownSSLConnection() throws Exception
- {
- SSLEngineResult result = engine.wrap(ByteBuffer.allocate(0), netData);
- Status status = result.getStatus();
- int read = result.bytesProduced();
- while (status != Status.CLOSED)
- {
- if (status == Status.BUFFER_OVERFLOW)
- {
- netData.clear();
- }
- if(read > 0)
- {
- int limit = netData.limit();
- netData.limit(netData.position());
- netData.position(netData.position() - read);
-
- ByteBuffer data = netData.slice();
-
- netData.limit(limit);
- netData.position(netData.position() + read);
-
- delegate.send(data);
- flush();
- }
- result = engine.wrap(ByteBuffer.allocate(0), netData);
- status = result.getStatus();
- read = result.bytesProduced();
- }
- }
-
- public void flush()
- {
- delegate.flush();
- }
-
- public void send(ByteBuffer appData)
- {
- if (closed.get())
- {
- throw new SenderException("SSL Sender is closed");
- }
-
- HandshakeStatus handshakeStatus;
- Status status;
-
- while(appData.hasRemaining() && !error.get())
- {
- int read = 0;
- try
- {
- SSLEngineResult result = engine.wrap(appData, netData);
- read = result.bytesProduced();
- status = result.getStatus();
- handshakeStatus = result.getHandshakeStatus();
- }
- catch(SSLException e)
- {
- throw new SenderException("SSL, Error occurred while encrypting data",e);
- }
-
- if(read > 0)
- {
- int limit = netData.limit();
- netData.limit(netData.position());
- netData.position(netData.position() - read);
-
- ByteBuffer data = netData.slice();
-
- netData.limit(limit);
- netData.position(netData.position() + read);
-
- delegate.send(data);
- }
-
- switch(status)
- {
- case CLOSED:
- throw new SenderException("SSLEngine is closed");
-
- case BUFFER_OVERFLOW:
- netData.clear();
- continue;
-
- case OK:
- break; // do nothing
-
- default:
- throw new IllegalStateException("SSLReceiver: Invalid State " + status);
- }
-
- switch (handshakeStatus)
- {
- case NEED_WRAP:
- if (netData.hasRemaining())
- {
- continue;
- }
-
- case NEED_TASK:
- doTasks();
- break;
-
- case NEED_UNWRAP:
- flush();
- synchronized(engineState)
- {
- switch (engine.getHandshakeStatus())
- {
- case NEED_UNWRAP:
- long start = System.currentTimeMillis();
- try
- {
- engineState.wait(timeout);
- }
- catch(InterruptedException e)
- {
- // pass
- }
-
- if (System.currentTimeMillis()- start >= timeout)
- {
- throw new SenderException(
- "SSL Engine timed out waiting for a response." +
- "To get more info,run with -Djavax.net.debug=ssl");
- }
- break;
- }
- }
- break;
-
- case FINISHED:
- if (this.settings != null && this.settings.isVerifyHostname() )
- {
- SSLUtil.verifyHostname(engine, this.settings.getHost());
- }
-
- case NOT_HANDSHAKING:
- break; //do nothing
-
- default:
- throw new IllegalStateException("SSLSender: Invalid State " + status);
- }
-
- }
- }
-
- public void doTasks()
- {
- Runnable runnable;
- while ((runnable = engine.getDelegatedTask()) != null) {
- runnable.run();
- }
- }
-
- public Object getNotificationToken()
- {
- return engineState;
- }
-
- public void setErrorFlag()
- {
- error.set(true);
- }
-
- public void setIdleTimeout(int i)
- {
- delegate.setIdleTimeout(i);
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/network/security/ssl/SSLUtil.java b/java/common/src/main/java/org/apache/qpid/transport/network/security/ssl/SSLUtil.java
deleted file mode 100644
index fd73915b65..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/network/security/ssl/SSLUtil.java
+++ /dev/null
@@ -1,197 +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.transport.network.security.ssl;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.security.GeneralSecurityException;
-import java.security.KeyStore;
-import java.security.Principal;
-import java.security.cert.Certificate;
-import java.security.cert.X509Certificate;
-
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLEngine;
-import javax.net.ssl.SSLPeerUnverifiedException;
-
-import org.apache.qpid.ssl.SSLContextFactory;
-import org.apache.qpid.transport.ConnectionSettings;
-import org.apache.qpid.transport.TransportException;
-import org.apache.qpid.transport.util.Logger;
-
-public class SSLUtil
-{
- private static final Logger log = Logger.get(SSLUtil.class);
-
- public static void verifyHostname(SSLEngine engine,String hostnameExpected)
- {
- try
- {
- Certificate cert = engine.getSession().getPeerCertificates()[0];
- Principal p = ((X509Certificate)cert).getSubjectDN();
- String dn = p.getName();
- String hostname = null;
-
- if (dn.contains("CN="))
- {
- hostname = dn.substring(3,
- dn.indexOf(",") == -1? dn.length(): dn.indexOf(","));
- }
-
- if (log.isDebugEnabled())
- {
- log.debug("Hostname expected : " + hostnameExpected);
- log.debug("Distinguished Name for server certificate : " + dn);
- log.debug("Host Name obtained from DN : " + hostname);
- }
-
- if (hostname != null && !(hostname.equalsIgnoreCase(hostnameExpected) ||
- hostname.equalsIgnoreCase(hostnameExpected + ".localdomain")))
- {
- throw new TransportException("SSL hostname verification failed." +
- " Expected : " + hostnameExpected +
- " Found in cert : " + hostname);
- }
-
- }
- catch(SSLPeerUnverifiedException e)
- {
- log.warn("Exception received while trying to verify hostname",e);
- // For some reason the SSL engine sets the handshake status to FINISH twice
- // in succession. The first time the peer certificate
- // info is not available. The second time it works !
- // Therefore have no choice but to ignore the exception here.
- }
- }
-
- public static String retriveIdentity(SSLEngine engine)
- {
- StringBuffer id = new StringBuffer();
- try
- {
- Certificate cert = engine.getSession().getLocalCertificates()[0];
- Principal p = ((X509Certificate)cert).getSubjectDN();
- String dn = p.getName();
-
- if (dn.contains("CN="))
- {
- id.append(dn.substring(3,
- dn.indexOf(",") == -1? dn.length(): dn.indexOf(",")));
- }
-
- if (dn.contains("DC="))
- {
- id.append("@");
- int c = 0;
- for (String toks : dn.split(","))
- {
- if (toks.contains("DC"))
- {
- if (c > 0) {id.append(".");}
- id.append(toks.substring(
- toks.indexOf("=")+1,
- toks.indexOf(",") == -1? toks.length(): toks.indexOf(",")));
- c++;
- }
- }
- }
- }
- catch(Exception e)
- {
- log.info("Exception received while trying to retrive client identity from SSL cert",e);
- }
-
- log.debug("Extracted Identity from client certificate : " + id);
- return id.toString();
- }
-
- public static SSLContext createSSLContext(ConnectionSettings settings) throws Exception
- {
- SSLContextFactory sslContextFactory;
-
- if (settings.getCertAlias() == null)
- {
- sslContextFactory =
- new SSLContextFactory(settings.getTrustStorePath(),
- settings.getTrustStorePassword(),
- settings.getTrustStoreCertType(),
- settings.getKeyStorePath(),
- settings.getKeyStorePassword(),
- settings.getKeyStoreCertType());
-
- } else
- {
- sslContextFactory =
- new SSLContextFactory(settings.getTrustStorePath(),
- settings.getTrustStorePassword(),
- settings.getTrustStoreCertType(),
- new QpidClientX509KeyManager(settings.getCertAlias(),
- settings.getKeyStorePath(),
- settings.getKeyStorePassword(),
- settings.getKeyStoreCertType()));
-
- log.debug("Using custom key manager");
- }
-
- return sslContextFactory.buildServerContext();
-
- }
-
- public static KeyStore getInitializedKeyStore(String storePath, String storePassword) throws GeneralSecurityException, IOException
- {
- KeyStore ks = KeyStore.getInstance("JKS");
- InputStream in = null;
- try
- {
- File f = new File(storePath);
- if (f.exists())
- {
- in = new FileInputStream(f);
- }
- else
- {
- in = Thread.currentThread().getContextClassLoader().getResourceAsStream(storePath);
- }
- if (in == null)
- {
- throw new IOException("Unable to load keystore resource: " + storePath);
- }
- ks.load(in, storePassword.toCharArray());
- }
- finally
- {
- if (in != null)
- {
- //noinspection EmptyCatchBlock
- try
- {
- in.close();
- }
- catch (IOException ignored)
- {
- }
- }
- }
- return ks;
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/util/Functions.java b/java/common/src/main/java/org/apache/qpid/transport/util/Functions.java
deleted file mode 100644
index 5761228642..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/util/Functions.java
+++ /dev/null
@@ -1,102 +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.transport.util;
-
-import java.nio.ByteBuffer;
-
-import static java.lang.Math.*;
-
-
-/**
- * Functions
- *
- * @author Rafael H. Schloming
- */
-
-public class Functions
-{
-
- public static final int mod(int n, int m)
- {
- int r = n % m;
- return r < 0 ? m + r : r;
- }
-
- public static final byte lsb(int i)
- {
- return (byte) (0xFF & i);
- }
-
- public static final byte lsb(long l)
- {
- return (byte) (0xFF & l);
- }
-
- public static final String str(ByteBuffer buf)
- {
- return str(buf, buf.remaining());
- }
-
- public static final String str(ByteBuffer buf, int limit)
- {
- return str(buf, limit,buf.position());
- }
-
- public static final String str(ByteBuffer buf, int limit,int start)
- {
- StringBuilder str = new StringBuilder();
- str.append('"');
-
- for (int i = start; i < min(buf.limit(), limit); i++)
- {
- byte c = buf.get(i);
-
- if (c > 31 && c < 127 && c != '\\')
- {
- str.append((char)c);
- }
- else
- {
- str.append(String.format("\\x%02x", c));
- }
- }
-
- str.append('"');
-
- if (limit < buf.remaining())
- {
- str.append("...");
- }
-
- return str.toString();
- }
-
- public static final String str(byte[] bytes)
- {
- return str(ByteBuffer.wrap(bytes));
- }
-
- public static final String str(byte[] bytes, int limit)
- {
- return str(ByteBuffer.wrap(bytes), limit);
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/util/Logger.java b/java/common/src/main/java/org/apache/qpid/transport/util/Logger.java
deleted file mode 100644
index 8c4818df92..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/util/Logger.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.transport.util;
-
-import org.slf4j.LoggerFactory;
-
-/**
- * Logger
- *
- */
-
-public final class Logger
-{
-
- public static final Logger get(Class<?> klass)
- {
- return new Logger(LoggerFactory.getLogger(klass));
- }
-
- private final org.slf4j.Logger log;
-
- private Logger(org.slf4j.Logger log)
- {
- this.log = log;
- }
-
- public boolean isDebugEnabled()
- {
- return log.isDebugEnabled();
- }
-
- public void debug(String message, Object ... args)
- {
- if (log.isDebugEnabled())
- {
- log.debug(String.format(message, args));
- }
- }
-
- public void debug(Throwable t, String message, Object ... args)
- {
- if (log.isDebugEnabled())
- {
- log.debug(String.format(message, args), t);
- }
- }
-
- public void error(String message, Object ... args)
- {
- if (log.isErrorEnabled())
- {
- log.error(String.format(message, args));
- }
- }
-
- public void error(Throwable t, String message, Object ... args)
- {
- if (log.isErrorEnabled())
- {
- log.error(String.format(message, args), t);
- }
- }
-
- public void warn(String message, Object ... args)
- {
- if (log.isWarnEnabled())
- {
- log.warn(String.format(message, args));
- }
- }
-
- public void warn(Throwable t, String message, Object ... args)
- {
- if (log.isWarnEnabled())
- {
- log.warn(String.format(message, args), t);
- }
- }
-
- public void info(String message, Object ... args)
- {
- if (log.isInfoEnabled())
- {
- log.info(String.format(message, args));
- }
- }
-
- public void info(Throwable t, String message, Object ... args)
- {
- if (log.isInfoEnabled())
- {
- log.info(String.format(message, args), t);
- }
- }
-
- public void trace(String message, Object ... args)
- {
- if (log.isTraceEnabled())
- {
- log.trace(String.format(message, args));
- }
- }
-
- public void trace(Throwable t, String message, Object ... args)
- {
- if (log.isTraceEnabled())
- {
- log.trace(String.format(message, args), t);
- }
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/util/SliceIterator.java b/java/common/src/main/java/org/apache/qpid/transport/util/SliceIterator.java
deleted file mode 100644
index 3db29847b2..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/util/SliceIterator.java
+++ /dev/null
@@ -1,59 +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.transport.util;
-
-import java.nio.ByteBuffer;
-
-import java.util.Iterator;
-
-
-/**
- * SliceIterator
- *
- * @author Rafael H. Schloming
- */
-
-public class SliceIterator implements Iterator<ByteBuffer>
-{
-
- final private Iterator<ByteBuffer> iterator;
-
- public SliceIterator(Iterator<ByteBuffer> iterator)
- {
- this.iterator = iterator;
- }
-
- public boolean hasNext()
- {
- return iterator.hasNext();
- }
-
- public ByteBuffer next()
- {
- return iterator.next().slice();
- }
-
- public void remove()
- {
- throw new UnsupportedOperationException();
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/transport/util/Waiter.java b/java/common/src/main/java/org/apache/qpid/transport/util/Waiter.java
deleted file mode 100644
index e034d779ca..0000000000
--- a/java/common/src/main/java/org/apache/qpid/transport/util/Waiter.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.transport.util;
-
-
-/**
- * Waiter
- *
- */
-
-public final class Waiter
-{
-
- private final Object lock;
- private final long timeout;
- private final long start;
- private long elapsed;
-
- public Waiter(Object lock, long timeout)
- {
- this.lock = lock;
- this.timeout = timeout;
- this.start = System.currentTimeMillis();
- this.elapsed = 0;
- }
-
- public boolean hasTime()
- {
- return elapsed < timeout;
- }
-
- public void await()
- {
- try
- {
- lock.wait(timeout - elapsed);
- }
- catch (InterruptedException e)
- {
- // pass
- }
- elapsed = System.currentTimeMillis() - start;
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/url/AMQBindingURL.java b/java/common/src/main/java/org/apache/qpid/url/AMQBindingURL.java
deleted file mode 100644
index 26cb56ea97..0000000000
--- a/java/common/src/main/java/org/apache/qpid/url/AMQBindingURL.java
+++ /dev/null
@@ -1,237 +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.url;
-
-import java.net.URISyntaxException;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-
-import org.apache.qpid.exchange.ExchangeDefaults;
-import org.apache.qpid.framing.AMQShortString;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class AMQBindingURL implements BindingURL
-{
- private static final Logger _logger = LoggerFactory.getLogger(AMQBindingURL.class);
-
- String _url;
- AMQShortString _exchangeClass = ExchangeDefaults.DIRECT_EXCHANGE_CLASS;
- AMQShortString _exchangeName = new AMQShortString("");
- AMQShortString _destinationName = new AMQShortString("");;
- AMQShortString _queueName = new AMQShortString("");
- AMQShortString[] _bindingKeys = new AMQShortString[0];
- private HashMap<String, String> _options;
-
- public AMQBindingURL(String url) throws URISyntaxException
- {
- // format:
- // <exch_class>://<exch_name>/[<destination>]/[<queue>]?<option>='<value>'[,<option>='<value>']*
- _logger.debug("Parsing URL: " + url);
- _url = url;
- _options = new HashMap<String, String>();
-
- parseBindingURL();
- }
-
- private void parseBindingURL() throws URISyntaxException
- {
- BindingURLParser parser = new BindingURLParser();
- parser.parse(_url,this);
- processOptions();
- _logger.debug("URL Parsed: " + this);
- }
-
- public void setExchangeClass(String exchangeClass)
- {
- setExchangeClass(new AMQShortString(exchangeClass));
- }
-
- public void setQueueName(String name)
- {
- setQueueName(new AMQShortString(name));
- }
-
- public void setDestinationName(String name)
- {
- setDestinationName(new AMQShortString(name));
- }
-
- public void setExchangeName(String exchangeName)
- {
- setExchangeName(new AMQShortString(exchangeName));
- }
-
- private void processOptions() throws URISyntaxException
- {
- }
-
- public String getURL()
- {
- return _url;
- }
-
- public AMQShortString getExchangeClass()
- {
- return _exchangeClass;
- }
-
- private void setExchangeClass(AMQShortString exchangeClass)
- {
-
- _exchangeClass = exchangeClass;
- if (exchangeClass.equals(ExchangeDefaults.TOPIC_EXCHANGE_CLASS))
- {
- setOption(BindingURL.OPTION_EXCLUSIVE, "true");
- }
-
- }
-
- public AMQShortString getExchangeName()
- {
- return _exchangeName;
- }
-
- private void setExchangeName(AMQShortString name)
- {
- _exchangeName = name;
- }
-
- public AMQShortString getDestinationName()
- {
- return _destinationName;
- }
-
- private void setDestinationName(AMQShortString name)
- {
- _destinationName = name;
- }
-
- public AMQShortString getQueueName()
- {
- return _queueName;
- }
-
- public void setQueueName(AMQShortString name)
- {
- _queueName = name;
- }
-
- public String getOption(String key)
- {
- return _options.get(key);
- }
-
- public void setOption(String key, String value)
- {
- _options.put(key, value);
- }
-
- public boolean containsOption(String key)
- {
- return _options.containsKey(key);
- }
-
- public AMQShortString getRoutingKey()
- {
- if (_exchangeClass.equals(ExchangeDefaults.DIRECT_EXCHANGE_CLASS))
- {
- if (containsOption(BindingURL.OPTION_ROUTING_KEY))
- {
- return new AMQShortString((String)getOption(OPTION_ROUTING_KEY));
- }
- else
- {
- return getQueueName();
- }
- }
-
- if (containsOption(BindingURL.OPTION_ROUTING_KEY))
- {
- return new AMQShortString((String)getOption(OPTION_ROUTING_KEY));
- }
-
- return getDestinationName();
- }
-
- public AMQShortString[] getBindingKeys()
- {
- if (_bindingKeys != null && _bindingKeys.length>0)
- {
- return _bindingKeys;
- }
- else
- {
- return new AMQShortString[]{getRoutingKey()};
- }
- }
-
- public void setBindingKeys(AMQShortString[] keys)
- {
- _bindingKeys = keys;
- }
-
- public void setRoutingKey(AMQShortString key)
- {
- setOption(OPTION_ROUTING_KEY, key.toString());
- }
-
- public String toString()
- {
- StringBuffer sb = new StringBuffer();
-
- sb.append(_exchangeClass);
- sb.append("://");
- sb.append(_exchangeName);
- sb.append('/');
- sb.append(_destinationName);
- sb.append('/');
- sb.append(_queueName);
-
- sb.append(URLHelper.printOptions(_options));
-
- // temp hack
- if (getRoutingKey() == null || getRoutingKey().toString().equals(""))
- {
-
- if (sb.toString().indexOf("?") == -1)
- {
- sb.append("?");
- }
- else
- {
- sb.append("&");
- }
-
- for (AMQShortString key :_bindingKeys)
- {
- sb.append(BindingURL.OPTION_BINDING_KEY).append("='").append(key.toString()).append("'&");
- }
-
- return sb.toString().substring(0,sb.toString().length()-1);
- }
- else
- {
- return sb.toString();
- }
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/url/BindingURL.java b/java/common/src/main/java/org/apache/qpid/url/BindingURL.java
deleted file mode 100644
index 9996fff311..0000000000
--- a/java/common/src/main/java/org/apache/qpid/url/BindingURL.java
+++ /dev/null
@@ -1,60 +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.url;
-
-import org.apache.qpid.framing.AMQShortString;
-
-/*
- Binding URL format:
- <exch_class>://<exch_name>/[<destination>]/[<queue>]?<option>='<value>'[,<option>='<value>']*
-*/
-public interface BindingURL
-{
- public static final String OPTION_EXCLUSIVE = "exclusive";
- public static final String OPTION_AUTODELETE = "autodelete";
- public static final String OPTION_DURABLE = "durable";
- public static final String OPTION_BROWSE = "browse";
- public static final String OPTION_CLIENTID = "clientid";
- public static final String OPTION_SUBSCRIPTION = "subscription";
- public static final String OPTION_ROUTING_KEY = "routingkey";
- public static final String OPTION_BINDING_KEY = "bindingkey";
-
-
- String getURL();
-
- AMQShortString getExchangeClass();
-
- AMQShortString getExchangeName();
-
- AMQShortString getDestinationName();
-
- AMQShortString getQueueName();
-
- String getOption(String key);
-
- boolean containsOption(String key);
-
- AMQShortString getRoutingKey();
-
- AMQShortString[] getBindingKeys();
-
- String toString();
-}
diff --git a/java/common/src/main/java/org/apache/qpid/url/BindingURLParser.java b/java/common/src/main/java/org/apache/qpid/url/BindingURLParser.java
deleted file mode 100644
index 0ebfe0e869..0000000000
--- a/java/common/src/main/java/org/apache/qpid/url/BindingURLParser.java
+++ /dev/null
@@ -1,478 +0,0 @@
-package org.apache.qpid.url;
-/*
- *
- * 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 java.net.URISyntaxException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.qpid.exchange.ExchangeDefaults;
-import org.apache.qpid.framing.AMQShortString;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class BindingURLParser
-{
- private static final char PROPERTY_EQUALS_CHAR = '=';
- private static final char PROPERTY_SEPARATOR_CHAR = '&';
- private static final char ALTERNATIVE_PROPERTY_SEPARATOR_CHAR = ',';
- private static final char FORWARD_SLASH_CHAR = '/';
- private static final char QUESTION_MARK_CHAR = '?';
- private static final char SINGLE_QUOTE_CHAR = '\'';
- private static final char COLON_CHAR = ':';
- private static final char END_OF_URL_MARKER_CHAR = '%';
-
- private static final Logger _logger = LoggerFactory.getLogger(BindingURLParser.class);
-
- private char[] _url;
- private AMQBindingURL _bindingURL;
- private BindingURLParserState _currentParserState;
- private String _error;
- private int _index = 0;
- private String _currentPropName;
- private Map<String,Object> _options;
-
-
- public BindingURLParser()
- {
- }
-
- //<exch_class>://<exch_name>/[<destination>]/[<queue>]?<option>='<value>'[,<option>='<value>']*
- public synchronized void parse(String url,AMQBindingURL bindingURL) throws URISyntaxException
- {
- _url = (url + END_OF_URL_MARKER_CHAR).toCharArray();
- _bindingURL = bindingURL;
- _currentParserState = BindingURLParserState.BINDING_URL_START;
- BindingURLParserState prevState = _currentParserState;
- _index = 0;
- _currentPropName = null;
- _error = null;
- _options = new HashMap<String,Object>();
-
- try
- {
- while (_currentParserState != BindingURLParserState.ERROR && _currentParserState != BindingURLParserState.BINDING_URL_END)
- {
- prevState = _currentParserState;
- _currentParserState = next();
- }
-
- if (_currentParserState == BindingURLParserState.ERROR)
- {
- _error =
- "Invalid URL format [current_state = " + prevState + ", details parsed so far " + _bindingURL + " ] error at (" + _index + ") due to " + _error;
- _logger.debug(_error);
- URISyntaxException ex;
- ex = new URISyntaxException(markErrorLocation(),"Error occured while parsing URL",_index);
- throw ex;
- }
-
- processOptions();
- }
- catch (ArrayIndexOutOfBoundsException e)
- {
- _error = "Invalid URL format [current_state = " + prevState + ", details parsed so far " + _bindingURL + " ] error at (" + _index + ")";
- URISyntaxException ex = new URISyntaxException(markErrorLocation(),"Error occured while parsing URL",_index);
- ex.initCause(e);
- throw ex;
- }
- }
-
- enum BindingURLParserState
- {
- BINDING_URL_START,
- EXCHANGE_CLASS,
- COLON_CHAR,
- DOUBLE_SEP,
- EXCHANGE_NAME,
- EXCHANGE_SEPERATOR_CHAR,
- DESTINATION,
- DESTINATION_SEPERATOR_CHAR,
- QUEUE_NAME,
- QUESTION_MARK_CHAR,
- PROPERTY_NAME,
- PROPERTY_EQUALS,
- START_PROPERTY_VALUE,
- PROPERTY_VALUE,
- END_PROPERTY_VALUE,
- PROPERTY_SEPARATOR,
- BINDING_URL_END,
- ERROR
- }
-
- /**
- * I am fully ware that there are few optimizations
- * that can speed up things a wee bit. But I have opted
- * for readability and maintainability at the expense of
- * speed, as speed is not a critical factor here.
- *
- * One can understand the full parse logic by just looking at this method.
- */
- private BindingURLParserState next()
- {
- switch (_currentParserState)
- {
- case BINDING_URL_START:
- return extractExchangeClass();
- case COLON_CHAR:
- _index++; //skip ":"
- return BindingURLParserState.DOUBLE_SEP;
- case DOUBLE_SEP:
- _index = _index + 2; //skip "//"
- return BindingURLParserState.EXCHANGE_NAME;
- case EXCHANGE_NAME:
- return extractExchangeName();
- case EXCHANGE_SEPERATOR_CHAR:
- _index++; // skip '/'
- return BindingURLParserState.DESTINATION;
- case DESTINATION:
- return extractDestination();
- case DESTINATION_SEPERATOR_CHAR:
- _index++; // skip '/'
- return BindingURLParserState.QUEUE_NAME;
- case QUEUE_NAME:
- return extractQueueName();
- case QUESTION_MARK_CHAR:
- _index++; // skip '?'
- return BindingURLParserState.PROPERTY_NAME;
- case PROPERTY_NAME:
- return extractPropertyName();
- case PROPERTY_EQUALS:
- _index++; // skip the equal sign
- return BindingURLParserState.START_PROPERTY_VALUE;
- case START_PROPERTY_VALUE:
- _index++; // skip the '\''
- return BindingURLParserState.PROPERTY_VALUE;
- case PROPERTY_VALUE:
- return extractPropertyValue();
- case END_PROPERTY_VALUE:
- _index ++;
- return checkEndOfURL();
- case PROPERTY_SEPARATOR:
- _index++; // skip '&'
- return BindingURLParserState.PROPERTY_NAME;
- default:
- return BindingURLParserState.ERROR;
- }
- }
-
- private BindingURLParserState extractExchangeClass()
- {
- char nextChar = _url[_index];
-
- // check for the following special cases.
- // "myQueue?durable='true'" or just "myQueue";
-
- StringBuilder builder = new StringBuilder();
- while (nextChar != COLON_CHAR && nextChar != QUESTION_MARK_CHAR && nextChar != END_OF_URL_MARKER_CHAR)
- {
- builder.append(nextChar);
- _index++;
- nextChar = _url[_index];
- }
-
- // normal use case
- if (nextChar == COLON_CHAR)
- {
- _bindingURL.setExchangeClass(builder.toString());
- return BindingURLParserState.COLON_CHAR;
- }
- // "myQueue?durable='true'" use case
- else if (nextChar == QUESTION_MARK_CHAR)
- {
- _bindingURL.setExchangeClass(ExchangeDefaults.DIRECT_EXCHANGE_CLASS.asString());
- _bindingURL.setExchangeName("");
- _bindingURL.setQueueName(builder.toString());
- return BindingURLParserState.QUESTION_MARK_CHAR;
- }
- else
- {
- _bindingURL.setExchangeClass(ExchangeDefaults.DIRECT_EXCHANGE_CLASS.asString());
- _bindingURL.setExchangeName("");
- _bindingURL.setQueueName(builder.toString());
- return BindingURLParserState.BINDING_URL_END;
- }
- }
-
- private BindingURLParserState extractExchangeName()
- {
- char nextChar = _url[_index];
- StringBuilder builder = new StringBuilder();
- while (nextChar != FORWARD_SLASH_CHAR)
- {
- builder.append(nextChar);
- _index++;
- nextChar = _url[_index];
- }
-
- _bindingURL.setExchangeName(builder.toString());
- return BindingURLParserState.EXCHANGE_SEPERATOR_CHAR;
- }
-
- private BindingURLParserState extractDestination()
- {
- char nextChar = _url[_index];
-
- //The destination is and queue name are both optional
- // This is checking for the case where both are not specified.
- if (nextChar == QUESTION_MARK_CHAR)
- {
- return BindingURLParserState.QUESTION_MARK_CHAR;
- }
-
- StringBuilder builder = new StringBuilder();
- while (nextChar != FORWARD_SLASH_CHAR && nextChar != QUESTION_MARK_CHAR)
- {
- builder.append(nextChar);
- _index++;
- nextChar = _url[_index];
- }
-
- // This is the case where the destination is explictily stated.
- // ex direct://amq.direct/myDest/myQueue?option1='1' ... OR
- // direct://amq.direct//myQueue?option1='1' ...
- if (nextChar == FORWARD_SLASH_CHAR)
- {
- _bindingURL.setDestinationName(builder.toString());
- return BindingURLParserState.DESTINATION_SEPERATOR_CHAR;
- }
- // This is the case where destination is not explictly stated.
- // ex direct://amq.direct/myQueue?option1='1' ...
- else
- {
- _bindingURL.setQueueName(builder.toString());
- return BindingURLParserState.QUESTION_MARK_CHAR;
- }
- }
-
- private BindingURLParserState extractQueueName()
- {
- char nextChar = _url[_index];
- StringBuilder builder = new StringBuilder();
- while (nextChar != QUESTION_MARK_CHAR && nextChar != END_OF_URL_MARKER_CHAR)
- {
- builder.append(nextChar);
- nextChar = _url[++_index];
- }
- _bindingURL.setQueueName(builder.toString());
-
- if(nextChar == QUESTION_MARK_CHAR)
- {
- return BindingURLParserState.QUESTION_MARK_CHAR;
- }
- else
- {
- return BindingURLParserState.BINDING_URL_END;
- }
- }
-
- private BindingURLParserState extractPropertyName()
- {
- StringBuilder builder = new StringBuilder();
- char next = _url[_index];
- while (next != PROPERTY_EQUALS_CHAR)
- {
- builder.append(next);
- next = _url[++_index];
- }
- _currentPropName = builder.toString();
-
- if (_currentPropName.trim().equals(""))
- {
- _error = "Property name cannot be empty";
- return BindingURLParserState.ERROR;
- }
-
- return BindingURLParserState.PROPERTY_EQUALS;
- }
-
- private BindingURLParserState extractPropertyValue()
- {
- StringBuilder builder = new StringBuilder();
- char next = _url[_index];
- while (next != SINGLE_QUOTE_CHAR)
- {
- builder.append(next);
- next = _url[++_index];
- }
- String propValue = builder.toString();
-
- if (propValue.trim().equals(""))
- {
- _error = "Property values cannot be empty";
- return BindingURLParserState.ERROR;
- }
- else
- {
- if (_options.containsKey(_currentPropName))
- {
- Object obj = _options.get(_currentPropName);
- if (obj instanceof List)
- {
- List list = (List)obj;
- list.add(propValue);
- }
- else // it has to be a string
- {
- List<String> list = new ArrayList();
- list.add((String)obj);
- list.add(propValue);
- _options.put(_currentPropName, list);
- }
- }
- else
- {
- _options.put(_currentPropName, propValue);
- }
-
-
- return BindingURLParserState.END_PROPERTY_VALUE;
- }
- }
-
- private BindingURLParserState checkEndOfURL()
- {
- char nextChar = _url[_index];
- if ( nextChar == END_OF_URL_MARKER_CHAR)
- {
- return BindingURLParserState.BINDING_URL_END;
- }
- else if (nextChar == PROPERTY_SEPARATOR_CHAR || nextChar == ALTERNATIVE_PROPERTY_SEPARATOR_CHAR)
- {
- return BindingURLParserState.PROPERTY_SEPARATOR;
- }
- else
- {
- return BindingURLParserState.ERROR;
- }
- }
-
- private String markErrorLocation()
- {
- String tmp = String.valueOf(_url);
- // length -1 to remove ENDOF URL marker
- return tmp.substring(0,_index) + "^" + tmp.substring(_index+1> tmp.length()-1?tmp.length()-1:_index+1,tmp.length()-1);
- }
-
- private void processOptions() throws URISyntaxException
- {
-// check for bindingKey
- if (_options.containsKey(BindingURL.OPTION_BINDING_KEY) && _options.get(BindingURL.OPTION_BINDING_KEY) != null)
- {
- Object obj = _options.get(BindingURL.OPTION_BINDING_KEY);
-
- if (obj instanceof String)
- {
- AMQShortString[] bindingKeys = new AMQShortString[]{new AMQShortString((String)obj)};
- _bindingURL.setBindingKeys(bindingKeys);
- }
- else // it would be a list
- {
- List list = (List)obj;
- AMQShortString[] bindingKeys = new AMQShortString[list.size()];
- int i=0;
- for (Iterator it = list.iterator(); it.hasNext();)
- {
- bindingKeys[i] = new AMQShortString((String)it.next());
- i++;
- }
- _bindingURL.setBindingKeys(bindingKeys);
- }
-
- }
- for (String key: _options.keySet())
- {
- // We want to skip the bindingKey list
- if (_options.get(key) instanceof String)
- {
- _bindingURL.setOption(key, (String)_options.get(key));
- }
- }
-
-
- // check if both a binding key and a routing key is specified.
- if (_options.containsKey(BindingURL.OPTION_BINDING_KEY) && _options.containsKey(BindingURL.OPTION_ROUTING_KEY))
- {
- throw new URISyntaxException(String.valueOf(_url),"It is illegal to specify both a routingKey and a bindingKey in the same URL",-1);
- }
-
- // check for durable subscriptions
- if (_bindingURL.getExchangeClass().equals(ExchangeDefaults.TOPIC_EXCHANGE_CLASS))
- {
- String queueName = null;
- if (Boolean.parseBoolean(_bindingURL.getOption(BindingURL.OPTION_DURABLE)))
- {
- if (_bindingURL.containsOption(BindingURL.OPTION_CLIENTID) && _bindingURL.containsOption(BindingURL.OPTION_SUBSCRIPTION))
- {
- queueName = _bindingURL.getOption(BindingURL.OPTION_CLIENTID) + ":" + _bindingURL.getOption(BindingURL.OPTION_SUBSCRIPTION);
- }
- else
- {
- throw new URISyntaxException(String.valueOf(_url),"Durable subscription must have values for " + BindingURL.OPTION_CLIENTID
- + " and " + BindingURL.OPTION_SUBSCRIPTION , -1);
-
- }
- }
- _bindingURL.setQueueName(queueName);
- }
- }
-
- public static void main(String[] args)
- {
-
- String[] urls = new String[]
- {
- "topic://amq.topic//myTopic?routingkey='stocks.#'",
- "topic://amq.topic/message_queue?bindingkey='usa.*'&bindingkey='control',exclusive='true'",
- "topic://amq.topic//?bindingKey='usa.*',bindingkey='control',exclusive='true'",
- "direct://amq.direct/dummyDest/myQueue?routingkey='abc.*'",
- "exchange.Class://exchangeName/Destination/Queue",
- "exchangeClass://exchangeName/Destination/?option='value',option2='value2'",
- "IBMPerfQueue1?durable='true'",
- "exchangeClass://exchangeName/Destination/?bindingkey='key1',bindingkey='key2'",
- "exchangeClass://exchangeName/Destination/?bindingkey='key1'&routingkey='key2'"
- };
-
- try
- {
- BindingURLParser parser = new BindingURLParser();
-
- for (String url: urls)
- {
- System.out.println("URL " + url);
- AMQBindingURL bindingURL = new AMQBindingURL(url);
- parser.parse(url,bindingURL);
- System.out.println("\nX " + bindingURL.toString() + " \n");
-
- }
-
- }
- catch(Exception e)
- {
- e.printStackTrace();
- }
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/url/URLHelper.java b/java/common/src/main/java/org/apache/qpid/url/URLHelper.java
deleted file mode 100644
index 6f21c327e7..0000000000
--- a/java/common/src/main/java/org/apache/qpid/url/URLHelper.java
+++ /dev/null
@@ -1,173 +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.url;
-
-import java.util.HashMap;
-import java.util.Map;
-
-public class URLHelper
-{
- public static final char DEFAULT_OPTION_SEPERATOR = '&';
- public static final char ALTERNATIVE_OPTION_SEPARATOR = ',';
- public static final char BROKER_SEPARATOR = ';';
-
- public static void parseOptions(Map<String, String> optionMap, String options) throws URLSyntaxException
- {
- // options looks like this
- // brokerlist='tcp://host:port?option='value',option='value';vm://:3/virtualpath?option='value'',failover='method?option='value',option='value''
-
- if ((options == null) || (options.indexOf('=') == -1))
- {
- return;
- }
-
- int optionIndex = options.indexOf('=');
-
- String option = options.substring(0, optionIndex);
-
- int length = options.length();
-
- int nestedQuotes = 0;
-
- // to store index of final "'"
- int valueIndex = optionIndex;
-
- // Walk remainder of url.
- while ((nestedQuotes > 0) || (valueIndex < length))
- {
- valueIndex++;
-
- if (valueIndex >= length)
- {
- break;
- }
-
- if (options.charAt(valueIndex) == '\'')
- {
- if ((valueIndex + 1) < options.length())
- {
- if ((options.charAt(valueIndex + 1) == DEFAULT_OPTION_SEPERATOR)
- || (options.charAt(valueIndex + 1) == ALTERNATIVE_OPTION_SEPARATOR)
- || (options.charAt(valueIndex + 1) == BROKER_SEPARATOR)
- || (options.charAt(valueIndex + 1) == '\''))
- {
- nestedQuotes--;
-
- if (nestedQuotes == 0)
- {
- // We've found the value of an option
- break;
- }
- }
- else
- {
- nestedQuotes++;
- }
- }
- else
- {
- // We are at the end of the string
- // Check to see if we are corectly closing quotes
- if (options.charAt(valueIndex) == '\'')
- {
- nestedQuotes--;
- }
-
- break;
- }
- }
- }
-
- if ((nestedQuotes != 0) || (valueIndex < (optionIndex + 2)))
- {
- int sepIndex = 0;
-
- // Try and identify illegal separator character
- if (nestedQuotes > 1)
- {
- for (int i = 0; i < nestedQuotes; i++)
- {
- sepIndex = options.indexOf('\'', sepIndex);
- sepIndex++;
- }
- }
-
- if ((sepIndex >= options.length()) || (sepIndex == 0))
- {
- throw parseError(valueIndex, "Unterminated option", options);
- }
- else
- {
- throw parseError(sepIndex, "Unterminated option. Possible illegal option separator:'"
- + options.charAt(sepIndex) + "'", options);
- }
- }
-
- // optionIndex +2 to skip "='"
- String value = options.substring(optionIndex + 2, valueIndex);
-
- optionMap.put(option, value);
-
- if (valueIndex < (options.length() - 1))
- {
- // Recurse to get remaining options
- parseOptions(optionMap, options.substring(valueIndex + 2));
- }
- }
-
- public static URLSyntaxException parseError(int index, String error, String url)
- {
- return parseError(index, 1, error, url);
- }
-
- public static URLSyntaxException parseError(int index, int length, String error, String url)
- {
- return new URLSyntaxException(url, error, index, length);
- }
-
- public static String printOptions(Map<String, String> options)
- {
- if (options.isEmpty())
- {
- return "";
- }
- else
- {
- StringBuffer sb = new StringBuffer();
- sb.append('?');
- for (String key : options.keySet())
- {
- sb.append(key);
-
- sb.append("='");
-
- sb.append(options.get(key));
-
- sb.append("'");
- sb.append(DEFAULT_OPTION_SEPERATOR);
- }
-
- sb.deleteCharAt(sb.length() - 1);
-
- return sb.toString();
- }
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/url/URLSyntaxException.java b/java/common/src/main/java/org/apache/qpid/url/URLSyntaxException.java
deleted file mode 100644
index 3ff7195794..0000000000
--- a/java/common/src/main/java/org/apache/qpid/url/URLSyntaxException.java
+++ /dev/null
@@ -1,97 +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.url;
-
-import java.net.URISyntaxException;
-
-public class URLSyntaxException extends URISyntaxException
-{
- private int _length;
-
- public URLSyntaxException(String url, String error, int index, int length)
- {
- super(url, error, index);
-
- _length = length;
- }
-
- private static String getPositionString(int index, int length)
- {
- StringBuffer sb = new StringBuffer(index + 1);
-
- for (int i = 0; i < index; i++)
- {
- sb.append(" ");
- }
-
- if (length > -1)
- {
- for (int i = 0; i < length; i++)
- {
- sb.append('^');
- }
- }
-
- return sb.toString();
- }
-
-
- public String toString()
- {
- StringBuffer sb = new StringBuffer();
-
- sb.append(getReason());
-
- if (getIndex() > -1)
- {
- if (_length != -1)
- {
- sb.append(" between indicies ");
- sb.append(getIndex());
- sb.append(" and ");
- sb.append(_length);
- }
- else
- {
- sb.append(" at index ");
- sb.append(getIndex());
- }
- }
-
- sb.append(" ");
- if (getIndex() != -1)
- {
- sb.append("\n");
- }
-
- sb.append(getInput());
-
- if (getIndex() != -1)
- {
- sb.append("\n");
- sb.append(getPositionString(getIndex(), _length));
- }
-
- return sb.toString();
- }
-
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/util/CommandLineParser.java b/java/common/src/main/java/org/apache/qpid/util/CommandLineParser.java
deleted file mode 100644
index 09478d4157..0000000000
--- a/java/common/src/main/java/org/apache/qpid/util/CommandLineParser.java
+++ /dev/null
@@ -1,695 +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.util;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-import java.util.regex.*;
-
-/**
- * CommandLineParser provides a utility for specifying the format of a command line and parsing command lines to ensure
- * that they fit their specified format. A command line is made up of flags and options, both may be refered to as
- * options. A flag is an option that does not take an argument (specifying it means it has the value 'true' and not
- * specifying it means it has the value 'false'). Options must take arguments but they can be set up with defaults so
- * that they take a default value when not set. Options may be mandatory in wich case it is an error not to specify
- * them on the command line. Flags are never mandatory because they are implicitly set to false when not specified.
- *
- * <p/>Some example command lines are:
- *
- * <ul>
- * <li>This one has two options that expect arguments:
- * <pre>
- * cruisecontrol -configfile cruisecontrol.xml -port 9000
- * </pre>
- * <li>This has one no-arg flag and two 'free' arguments:
- * <pre>
- * zip -r project.zip project/*
- * </pre>
- * <li>This one concatenates multiple flags into a single block with only one '-':
- * <pre>
- * jar -tvf mytar.tar
- * </pre>
- *
- * <p/>The parsing rules are:
- *
- * <ol>
- * <li>Flags may be combined after a single '-' because they never take arguments. Normally such flags are single letter
- * flags but this is only a convention and not enforced. Flags of more than one letter are usually specified on their own.
- * <li>Options expecting arguments must always be on their own.
- * <li>The argument to an option may be seperated from it by whitespace or appended directly onto the option.
- * <li>The argument to an option may never begin with a '-' character.
- * <li>All other arguments not beginning with a '-' character are free arguments that do not belong to any option.
- * <li>The second or later of a set of duplicate or repeated flags are ignored.
- * <li>Options are matched up to the shortest matching option. This is because of the possibility of having no space
- * between an option and its argument. This rules out the possibility of using two options where one is an opening
- * substring of the other. For example, the options "foo" and "foobar" cannot be used on the same command line because
- * it is not possible to distinguish the argument "-foobar" from being the "foobar" option or the "foo" option with
- * the "bar" argument.
- * </ol>
- *
- * <p/>By default, unknown options are simply ignored if specified on the command line. This behaviour may be changed
- * so that the parser reports all unknowns as errors by using the {@link #setErrorsOnUnknowns} method.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Accept a command line specification.
- * <tr><td> Parse a command line into properties, validating it against its specification.
- * <tr><td> Report all errors between a command line and its specification.
- * <tr><td> Provide a formatted usage string for a command line.
- * <tr><td> Provide a formatted options in force string for a command line.
- * <tr><td> Allow errors on unknowns behaviour to be turned on or off.
- * </table>
- */
-public class CommandLineParser
-{
- /** Holds a mapping from command line option names to detailed information about those options. */
- private Map<String, CommandLineOption> optionMap = new HashMap<String, CommandLineOption>();
-
- /** Holds a list of parsing errors. */
- private List<String> parsingErrors = new ArrayList<String>();
-
- /** Holds the regular expression matcher to match command line options with. */
- private Matcher optionMatcher = null;
-
- /** Holds the parsed command line properties after parsing. */
- private Properties parsedProperties = null;
-
- /** Flag used to indicate that errors should be created for unknown options. False by default. */
- private boolean errorsOnUnknowns = false;
-
- /**
- * Creates a command line options parser from a command line specification. This is passed to this constructor
- * as an array of arrays of strings. Each array of strings specifies the command line for a single option. A static
- * array may therefore easily be used to configure the command line parser in a single method call with an easily
- * readable format.
- *
- * <p/>Each array of strings must be 2, 3, 4 or 5 elements long. If any of the last three elements are missing they
- * are assumed to be null. The elements specify the following parameters:
- * <ol>
- * <li>The name of the option without the leading '-'. For example, "file". To specify the format of the 'free'
- * arguments use the option names "1", "2", ... and so on.
- * <li>The option comment. A line of text describing the usage of the option. For example, "The file to be processed."
- * <li>The options argument. This is a very short description of the argument to the option, often a single word
- * or a reminder as to the arguments format. When this element is null the option is a flag and does not
- * accept any arguments. For example, "filename" or "(unix | windows)" or null. The actual text specified
- * is only used to print in the usage message to remind the user of the usage of the option.
- * <li>The mandatory flag. When set to "true" an option must always be specified. Any other value, including null,
- * means that the option is mandatory. Flags are always mandatory (see class javadoc for explanation of why) so
- * this is ignored for flags.
- * <li>A regular expression describing the format that the argument must take. Ignored if null.
- * </ol>
- * <p/>An example call to this constructor is:
- *
- * <pre>
- * CommandLineParser commandLine = new CommandLineParser(
- * new String[][] {{"file", "The file to be processed. ", "filename", "true"},
- * {"dir", "Directory to store results in. Current dir used if not set.", "out dir"},
- * {"os", "Operating system EOL format to use.", "(windows | unix)", null, "windows\|unix"},
- * {"v", "Verbose mode. Prints information about the processing as it goes."},
- * {"1", "The processing command to run.", "command", "true", "add\|remove\|list"}});
- * </pre>
- *
- * @param config The configuration as an array of arrays of strings.
- */
- public CommandLineParser(String[][] config)
- {
- // Loop through all the command line option specifications creating details for each in the options map.
- for (int i = 0; i < config.length; i++)
- {
- String[] nextOptionSpec = config[i];
-
- addOption(nextOptionSpec[0], nextOptionSpec[1], (nextOptionSpec.length > 2) ? nextOptionSpec[2] : null,
- (nextOptionSpec.length > 3) ? ("true".equals(nextOptionSpec[3]) ? true : false) : false,
- (nextOptionSpec.length > 4) ? nextOptionSpec[4] : null);
- }
- }
-
- /**
- * Lists all the parsing errors from the most recent parsing in a string.
- *
- * @return All the parsing errors from the most recent parsing.
- */
- public String getErrors()
- {
- // Return the empty string if there are no errors.
- if (parsingErrors.isEmpty())
- {
- return "";
- }
-
- // Concatenate all the parsing errors together.
- StringBuilder result = new StringBuilder();
-
- for (String s : parsingErrors)
- {
- result.append(s);
- }
-
- return result.toString();
- }
-
- /**
- * Lists the properties set from the most recent parsing or an empty string if no parsing has been done yet.
- *
- * @return The properties set from the most recent parsing or an empty string if no parsing has been done yet.
- */
- public String getOptionsInForce()
- {
- // Check if there are no properties to report and return and empty string if so.
- if (parsedProperties == null)
- {
- return "";
- }
-
- // List all the properties.
- StringBuilder result = new StringBuilder("Options in force:\n");
-
- for (Map.Entry<Object, Object> property : parsedProperties.entrySet())
- {
- result.append(property.getKey())
- .append(" = ")
- .append(property.getValue())
- .append('\n');
- }
-
- return result.toString();
- }
-
- /**
- * Generates a usage string consisting of the name of each option and each options argument description and
- * comment.
- *
- * @return A usage string for all the options.
- */
- public String getUsage()
- {
- String result = "Options:\n";
-
- // Print usage on each of the command line options.
- for (CommandLineOption optionInfo : optionMap.values())
- {
- result +=
- "-" + optionInfo.option + " " + ((optionInfo.argument != null) ? (optionInfo.argument + " ") : "")
- + optionInfo.comment + "\n";
- }
-
- return result;
- }
-
- /**
- * Control the behaviour of the errors on unkowns reporting. When turned on this reports all unkowns options
- * as errors. When turned off, all unknowns are simply ignored.
- *
- * @param errors The setting of the errors on unkown flag. True to turn it on.
- */
- public void setErrorsOnUnknowns(boolean errors)
- {
- errorsOnUnknowns = errors;
- }
-
- /**
- * Parses a set of command line arguments into a set of properties, keyed by the argument flag. The free arguments
- * are keyed by integers as strings starting at "1" and then "2", ... and so on.
- *
- * <p/>See the class level comment for a description of the parsing rules.
- *
- * @param args The command line arguments.
- *
- * @return The arguments as a set of properties.
- *
- * @throws IllegalArgumentException If the command line cannot be parsed against its specification. If this exception
- * is thrown a call to {@link #getErrors} will provide a diagnostic of the command
- * line errors.
- */
- public Properties parseCommandLine(String[] args) throws IllegalArgumentException
- {
- Properties options = new Properties();
-
- // Used to keep count of the current 'free' argument.
- int free = 1;
-
- // Used to indicate that the most recently parsed option is expecting arguments.
- boolean expectingArgs = false;
-
- // The option that is expecting arguments from the next element of the command line.
- String optionExpectingArgs = null;
-
- // Used to indicate that the most recently parsed option is a duplicate and should be ignored.
- boolean ignore = false;
-
- // Create the regular expression matcher for the command line options.
- StringBuilder regexp = new StringBuilder("^(");
- int optionsAdded = 0;
-
- for (Iterator<String> i = optionMap.keySet().iterator(); i.hasNext();)
- {
- String nextOption = i.next();
-
- // Check that the option is not a free argument definition.
- boolean notFree = false;
-
- try
- {
- Integer.parseInt(nextOption);
- }
- catch (NumberFormatException e)
- {
- notFree = true;
- }
-
- // Add the option to the regular expression matcher if it is not a free argument definition.
- if (notFree)
- {
- regexp.append(nextOption)
- .append(i.hasNext() ? "|" : "");
- optionsAdded++;
- }
- }
-
- // There has to be more that one option in the regular expression or else the compiler complains that the close
- // cannot be nullable if the '?' token is used to make the matched option string optional.
- regexp.append(')')
- .append(((optionsAdded > 0) ? "?" : ""))
- .append("(.*)");
- Pattern pattern = Pattern.compile(regexp.toString());
-
- // Loop through all the command line arguments.
- for (int i = 0; i < args.length; i++)
- {
- // Check if the next command line argument begins with a '-' character and is therefore the start of
- // an option.
- if (args[i].startsWith("-"))
- {
- // Extract the value of the option without the leading '-'.
- String arg = args[i].substring(1);
-
- // Match up to the longest matching option.
- optionMatcher = pattern.matcher(arg);
- optionMatcher.matches();
-
- String matchedOption = optionMatcher.group(1);
-
- // Match any argument directly appended onto the longest matching option.
- String matchedArg = optionMatcher.group(2);
-
- // Check that a known option was matched.
- if ((matchedOption != null) && !"".equals(matchedOption))
- {
- // Get the command line option information for the matched option.
- CommandLineOption optionInfo = optionMap.get(matchedOption);
-
- // Check if this option is expecting arguments.
- if (optionInfo.expectsArgs)
- {
- // The option is expecting arguments so swallow the next command line argument as an
- // argument to this option.
- expectingArgs = true;
- optionExpectingArgs = matchedOption;
-
- // In the mean time set this options argument to the empty string in case no argument is ever
- // supplied.
- // options.put(matchedOption, "");
- }
-
- // Check if the option was matched on its own and is a flag in which case set that flag.
- if ("".equals(matchedArg) && !optionInfo.expectsArgs)
- {
- options.put(matchedOption, "true");
- }
- // The option was matched as a substring with its argument appended to it or is a flag that is
- // condensed together with other flags.
- else if (!"".equals(matchedArg))
- {
- // Check if the option is a flag and therefore is allowed to be condensed together
- // with other flags.
- if (!optionInfo.expectsArgs)
- {
- // Set the first matched flag.
- options.put(matchedOption, "true");
-
- // Repeat the longest matching process on the remainder but ensure that the remainder
- // consists only of flags as only flags may be condensed together in this fashion.
- do
- {
- // Match the remainder against the options.
- optionMatcher = pattern.matcher(matchedArg);
- optionMatcher.matches();
-
- matchedOption = optionMatcher.group(1);
- matchedArg = optionMatcher.group(2);
-
- // Check that an option was matched.
- if (matchedOption != null)
- {
- // Get the command line option information for the next matched option.
- optionInfo = optionMap.get(matchedOption);
-
- // Ensure that the next option is a flag or raise an error if not.
- if (optionInfo.expectsArgs == true)
- {
- parsingErrors.add("Option " + matchedOption + " cannot be combined with flags.\n");
- }
-
- options.put(matchedOption, "true");
- }
- // The remainder could not be matched against a flag it is either an unknown flag
- // or an illegal argument to a flag.
- else
- {
- parsingErrors.add("Illegal argument to a flag in the option " + arg + "\n");
-
- break;
- }
- }
- // Continue until the remainder of the argument has all been matched with flags.
- while (!"".equals(matchedArg));
- }
- // The option is expecting an argument, so store the unmatched portion against it
- // as its argument.
- else
- {
- // Check the arguments format is correct against any specified format.
- checkArgumentFormat(optionInfo, matchedArg);
-
- // Store the argument against its option (regardless of its format).
- options.put(matchedOption, matchedArg);
-
- // The argument to this flag has already been supplied to it. Do not swallow the
- // next command line argument as an argument to this flag.
- expectingArgs = false;
- }
- }
- }
- else // No matching option was found.
- {
- // Add this to the list of parsing errors if errors on unkowns is being used.
- if (errorsOnUnknowns)
- {
- parsingErrors.add("Option " + matchedOption + " is not a recognized option.\n");
- }
- }
- }
- // The command line argument did not being with a '-' so it is an argument to the previous flag or it
- // is a free argument.
- else
- {
- // Check if a previous flag is expecting to swallow this next argument as its argument.
- if (expectingArgs)
- {
- // Get the option info for the option waiting for arguments.
- CommandLineOption optionInfo = optionMap.get(optionExpectingArgs);
-
- // Check the arguments format is correct against any specified format.
- checkArgumentFormat(optionInfo, args[i]);
-
- // Store the argument against its option (regardless of its format).
- options.put(optionExpectingArgs, args[i]);
-
- // Clear the expecting args flag now that the argument has been swallowed.
- expectingArgs = false;
- optionExpectingArgs = null;
- }
- // This command line option is not an argument to any option. Add it to the set of 'free' options.
- else
- {
- // Get the option info for the free option, if there is any.
- CommandLineOption optionInfo = optionMap.get(Integer.toString(free));
-
- if (optionInfo != null)
- {
- // Check the arguments format is correct against any specified format.
- checkArgumentFormat(optionInfo, args[i]);
- }
-
- // Add to the list of free options.
- options.put(Integer.toString(free), args[i]);
-
- // Move on to the next free argument.
- free++;
- }
- }
- }
-
- // Scan through all the specified options to check that all mandatory options have been set and that all flags
- // that were not set are set to false in the set of properties.
- for (CommandLineOption optionInfo : optionMap.values())
- {
- // Check if this is a flag.
- if (!optionInfo.expectsArgs)
- {
- // Check if the flag is not set in the properties and set it to false if so.
- if (!options.containsKey(optionInfo.option))
- {
- options.put(optionInfo.option, "false");
- }
- }
- // Check if this is a mandatory option and was not set.
- else if (optionInfo.mandatory && !options.containsKey(optionInfo.option))
- {
- // Create an error for the missing option.
- parsingErrors.add("Option -" + optionInfo.option + " is mandatory but not was not specified.\n");
- }
- }
-
- // Check if there were any errors.
- if (!parsingErrors.isEmpty())
- {
- // Throw an illegal argument exception to signify that there were parsing errors.
- throw new IllegalArgumentException();
- }
-
- // Convert any name/value pairs in the free arguments into properties in the parsed options.
- options = takeFreeArgsAsProperties(options, 1);
-
- parsedProperties = options;
-
- return options;
- }
-
- /**
- * If a command line has been parsed, calling this method sets all of its parsed options into the specified properties.
- */
- public void addCommandLineToProperties(Properties properties)
- {
- if (parsedProperties != null)
- {
- for (Object propKey : parsedProperties.keySet())
- {
- String name = (String) propKey;
- String value = parsedProperties.getProperty(name);
-
- properties.setProperty(name, value);
- }
- }
- }
-
- /**
- * Resets this command line parser after it has been used to parse a command line. This method will only need
- * to be called to use this parser a second time which is not likely seeing as a command line is usually only
- * specified once. However, it is exposed as a public method for the rare case where this may be done.
- *
- * <p/>Cleans the internal state of this parser, removing all stored errors and information about the options in
- * force.
- */
- public void reset()
- {
- parsingErrors = new ArrayList<String>();
- parsedProperties = null;
- }
-
- /**
- * Adds the option to list of available command line options.
- *
- * @param option The option to add as an available command line option.
- * @param comment A comment for the option.
- * @param argument The text that appears after the option in the usage string.
- * @param mandatory When true, indicates that this option is mandatory.
- * @param formatRegexp The format that the argument must take, defined as a regular expression.
- */
- protected void addOption(String option, String comment, String argument, boolean mandatory, String formatRegexp)
- {
- // Check if usage text has been set in which case this option is expecting arguments.
- boolean expectsArgs = ((argument == null) || argument.equals("")) ? false : true;
-
- // Add the option to the map of command line options.
- CommandLineOption opt = new CommandLineOption(option, expectsArgs, comment, argument, mandatory, formatRegexp);
- optionMap.put(option, opt);
- }
-
- /**
- * Converts the free arguments into property declarations. After parsing the command line the free arguments
- * are numbered from 1, such that the parsed properties contain values for the keys "1", "2", ... This method
- * converts any free arguments declared using the 'name=value' syntax into properties with key 'name', value
- * 'value'.
- *
- * <p/>For example the comand line:
- * <pre>
- * ... debug=true
- * </pre>
- *
- * <p/>After parsing has properties:
- * <pre>[[1, debug=true]]</pre>
- *
- * <p/>After applying this method the properties are:
- * <pre>[[1, debug=true], [debug, true]]</pre>
- *
- * @param properties The parsed command line properties.
- * @param from The free argument index to convert to properties from.
- *
- * @return The parsed command line properties, with free argument name value pairs too.
- */
- private Properties takeFreeArgsAsProperties(Properties properties, int from)
- {
- for (int i = from; true; i++)
- {
- String nextFreeArg = properties.getProperty(Integer.toString(i));
-
- // Terminate the loop once all free arguments have been consumed.
- if (nextFreeArg == null)
- {
- break;
- }
-
- // Split it on the =, strip any whitespace and set it as a system property.
- String[] nameValuePair = nextFreeArg.split("=");
-
- if (nameValuePair.length == 2)
- {
- properties.setProperty(nameValuePair[0], nameValuePair[1]);
- }
- }
-
- return properties;
- }
-
- /**
- * Checks the format of an argument to an option against its specified regular expression format if one has
- * been set. Any errors are added to the list of parsing errors.
- *
- * @param optionInfo The command line option information for the option which is havings its argument checked.
- * @param matchedArg The string argument to the option.
- */
- private void checkArgumentFormat(CommandLineOption optionInfo, String matchedArg)
- {
- // Check if this option enforces a format for its argument.
- if (optionInfo.argumentFormatRegexp != null)
- {
- Pattern pattern = Pattern.compile(optionInfo.argumentFormatRegexp);
- Matcher argumentMatcher = pattern.matcher(matchedArg);
-
- // Check if the argument does not meet its required format.
- if (!argumentMatcher.matches())
- {
- // Create an error for this badly formed argument.
- parsingErrors.add("The argument to option -" + optionInfo.option + " does not meet its required format.\n");
- }
- }
- }
-
- /**
- * Extracts all name=value pairs from the command line, sets them all as system properties and also returns
- * a map of properties containing them.
- *
- * @param args The command line.
- * @param commandLine The command line parser.
- * @param properties The properties object to inject all parsed properties into (optional may be <tt>null</tt>).
- *
- * @return A set of properties containing all name=value pairs from the command line.
- */
- public static Properties processCommandLine(String[] args, CommandLineParser commandLine, Properties properties)
- {
- // Capture the command line arguments or display errors and correct usage and then exit.
- Properties options = null;
-
- try
- {
- options = commandLine.parseCommandLine(args);
-
- // Add all the trailing command line options (name=value pairs) to system properties. They may be picked up
- // from there.
- commandLine.addCommandLineToProperties(properties);
- }
- catch (IllegalArgumentException e)
- {
- System.out.println(commandLine.getErrors());
- System.out.println(commandLine.getUsage());
- System.exit(1);
- }
-
- return options;
- }
-
- /**
- * Holds information about a command line options. This includes what its name is, whether or not it is a flag,
- * whether or not it is mandatory, what its user comment is, what its argument reminder text is and what its
- * regular expression format is.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Hold details of a command line option.
- * </table>
- */
- protected static class CommandLineOption
- {
- /** Holds the text for the flag to match this argument with. */
- public String option = null;
-
- /** Holds a string describing how to use this command line argument. */
- public String argument = null;
-
- /** Flag that determines whether or not this command line argument can take arguments. */
- public boolean expectsArgs = false;
-
- /** Holds a short comment describing what this command line argument is for. */
- public String comment = null;
-
- /** Flag that determines whether or not this is an mandatory command line argument. */
- public boolean mandatory = false;
-
- /** A regular expression describing what format the argument to this option muist have. */
- public String argumentFormatRegexp = null;
-
- /**
- * Create a command line option object that holds specific information about a command line option.
- *
- * @param option The text that matches the option.
- * @param expectsArgs Whether or not the option expects arguments. It is a flag if this is false.
- * @param comment A comment explaining how to use this option.
- * @param argument A short reminder of the format of the argument to this option/
- * @param mandatory Set to true if this option is mandatory.
- * @param formatRegexp The regular expression that the argument to this option must meet to be valid.
- */
- public CommandLineOption(String option, boolean expectsArgs, String comment, String argument, boolean mandatory,
- String formatRegexp)
- {
- this.option = option;
- this.expectsArgs = expectsArgs;
- this.comment = comment;
- this.argument = argument;
- this.mandatory = mandatory;
- this.argumentFormatRegexp = formatRegexp;
- }
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/util/ConcurrentLinkedMessageQueueAtomicSize.java b/java/common/src/main/java/org/apache/qpid/util/ConcurrentLinkedMessageQueueAtomicSize.java
deleted file mode 100644
index 633cf4fe3a..0000000000
--- a/java/common/src/main/java/org/apache/qpid/util/ConcurrentLinkedMessageQueueAtomicSize.java
+++ /dev/null
@@ -1,258 +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.util;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.Queue;
-import java.util.concurrent.atomic.AtomicInteger;
-
-public class ConcurrentLinkedMessageQueueAtomicSize<E> extends ConcurrentLinkedQueueAtomicSize<E> implements MessageQueue<E>
-{
- private static final Logger _logger = LoggerFactory.getLogger(ConcurrentLinkedMessageQueueAtomicSize.class);
-
- protected Queue<E> _messageHead = new ConcurrentLinkedQueueAtomicSize<E>();
-
- protected AtomicInteger _messageHeadSize = new AtomicInteger(0);
-
- @Override
- public int size()
- {
- return super.size() + _messageHeadSize.get();
- }
-
- public int headSize()
- {
- return _messageHeadSize.get();
- }
-
- @Override
- public E poll()
- {
- if (_messageHead.isEmpty())
- {
- return super.poll();
- }
- else
- {
- E e = _messageHead.poll();
-
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Providing item(" + e + ")from message head");
- }
-
- if (e != null)
- {
- _messageHeadSize.decrementAndGet();
- }
-
- return e;
- }
- }
-
- @Override
- public boolean remove(Object o)
- {
-
- if (_messageHead.isEmpty())
- {
- return super.remove(o);
- }
- else
- {
- if (_messageHead.remove(o))
- {
- _messageHeadSize.decrementAndGet();
-
- return true;
- }
-
- return super.remove(o);
- }
- }
-
- @Override
- public boolean removeAll(Collection<?> c)
- {
- if (_messageHead.isEmpty())
- {
- return super.removeAll(c);
- }
- else
- {
- // fixme this is super.removeAll but iterator here doesn't work
- // we need to be able to correctly decrement _messageHeadSize
- // boolean modified = false;
- // Iterator<?> e = iterator();
- // while (e.hasNext())
- // {
- // if (c.contains(e.next()))
- // {
- // e.remove();
- // modified = true;
- // _size.decrementAndGet();
- // }
- // }
- // return modified;
-
- throw new RuntimeException("Not implemented");
- }
- }
-
- @Override
- public boolean isEmpty()
- {
- return (_messageHead.isEmpty() && super.isEmpty());
- }
-
- @Override
- public void clear()
- {
- super.clear();
- _messageHead.clear();
- }
-
- @Override
- public boolean contains(Object o)
- {
- return _messageHead.contains(o) || super.contains(o);
- }
-
- @Override
- public boolean containsAll(Collection<?> o)
- {
- return _messageHead.containsAll(o) || super.containsAll(o);
- }
-
- @Override
- public E element()
- {
- if (_messageHead.isEmpty())
- {
- return super.element();
- }
- else
- {
- return _messageHead.element();
- }
- }
-
- @Override
- public E peek()
- {
- if (_messageHead.isEmpty())
- {
- return super.peek();
- }
- else
- {
- E o = _messageHead.peek();
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Peeking item (" + o + ") from message head");
- }
-
- return o;
- }
-
- }
-
- @Override
- public Iterator<E> iterator()
- {
- final Iterator<E> mainMessageIterator = super.iterator();
-
- return new Iterator<E>()
- {
- final Iterator<E> _headIterator = _messageHead.iterator();
- final Iterator<E> _mainIterator = mainMessageIterator;
-
- Iterator<E> last;
-
- public boolean hasNext()
- {
- return _headIterator.hasNext() || _mainIterator.hasNext();
- }
-
- public E next()
- {
- if (_headIterator.hasNext())
- {
- last = _headIterator;
-
- return _headIterator.next();
- }
- else
- {
- last = _mainIterator;
-
- return _mainIterator.next();
- }
- }
-
- public void remove()
- {
- last.remove();
- if(last == _mainIterator)
- {
- _size.decrementAndGet();
- }
- else
- {
- _messageHeadSize.decrementAndGet();
- }
- }
- };
- }
-
- @Override
- public boolean retainAll(Collection<?> c)
- {
- throw new RuntimeException("Not Implemented");
- }
-
- @Override
- public Object[] toArray()
- {
- throw new RuntimeException("Not Implemented");
- }
-
- public boolean pushHead(E o)
- {
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Adding item(" + o + ") to head of queue");
- }
-
- if (_messageHead.offer(o))
- {
- _messageHeadSize.incrementAndGet();
-
- return true;
- }
-
- return false;
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/util/ConcurrentLinkedQueueAtomicSize.java b/java/common/src/main/java/org/apache/qpid/util/ConcurrentLinkedQueueAtomicSize.java
deleted file mode 100644
index c4d7683a02..0000000000
--- a/java/common/src/main/java/org/apache/qpid/util/ConcurrentLinkedQueueAtomicSize.java
+++ /dev/null
@@ -1,70 +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.util;
-
-import java.util.concurrent.ConcurrentLinkedQueue;
-import java.util.concurrent.atomic.AtomicInteger;
-
-public class ConcurrentLinkedQueueAtomicSize<E> extends ConcurrentLinkedQueue<E>
-{
- AtomicInteger _size = new AtomicInteger(0);
-
- public int size()
- {
- return _size.get();
- }
-
- public boolean offer(E o)
- {
-
- if (super.offer(o))
- {
- _size.incrementAndGet();
- return true;
- }
-
- return false;
- }
-
- public E poll()
- {
- E e = super.poll();
-
- if (e != null)
- {
- _size.decrementAndGet();
- }
-
- return e;
- }
-
- @Override
- public boolean remove(Object o)
- {
- if (super.remove(o))
- {
- _size.decrementAndGet();
- return true;
- }
-
- return false;
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/util/ConcurrentLinkedQueueNoSize.java b/java/common/src/main/java/org/apache/qpid/util/ConcurrentLinkedQueueNoSize.java
deleted file mode 100644
index 1f168345a1..0000000000
--- a/java/common/src/main/java/org/apache/qpid/util/ConcurrentLinkedQueueNoSize.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.util;
-
-import java.util.concurrent.ConcurrentLinkedQueue;
-
-public class ConcurrentLinkedQueueNoSize<E> extends ConcurrentLinkedQueue<E>
-{
- public int size()
- {
- if (isEmpty())
- {
- return 0;
- }
- else
- {
- return 1;
- }
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/util/FileUtils.java b/java/common/src/main/java/org/apache/qpid/util/FileUtils.java
deleted file mode 100644
index 1a57af9bf7..0000000000
--- a/java/common/src/main/java/org/apache/qpid/util/FileUtils.java
+++ /dev/null
@@ -1,395 +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.util;
-
-import java.io.BufferedInputStream;
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.FileReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.LinkedList;
-import java.util.List;
-
-/**
- * FileUtils provides some simple helper methods for working with files. It follows the convention of wrapping all
- * checked exceptions as runtimes, so code using these methods is free of try-catch blocks but does not expect to
- * recover from errors.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Read a text file as a string.
- * <tr><td> Open a file or default resource as an input stream.
- * </table>
- */
-public class FileUtils
-{
- /**
- * Reads a text file as a string.
- *
- * @param filename The name of the file.
- *
- * @return The contents of the file.
- */
- public static String readFileAsString(String filename)
- {
- BufferedInputStream is = null;
-
- try
- {
- try
- {
- is = new BufferedInputStream(new FileInputStream(filename));
- }
- catch (FileNotFoundException e)
- {
- throw new RuntimeException(e);
- }
-
- return readStreamAsString(is);
- }
- finally
- {
- if (is != null)
- {
- try
- {
- is.close();
- }
- catch (IOException e)
- {
- throw new RuntimeException(e);
- }
- }
- }
- }
-
- /**
- * Reads a text file as a string.
- *
- * @param file The file.
- *
- * @return The contents of the file.
- */
- public static String readFileAsString(File file)
- {
- BufferedInputStream is = null;
-
- try
- {
- is = new BufferedInputStream(new FileInputStream(file));
- }
- catch (FileNotFoundException e)
- {
- throw new RuntimeException(e);
- }
-
- return readStreamAsString(is);
- }
-
- /**
- * Reads the contents of a reader, one line at a time until the end of stream is encountered, and returns all
- * together as a string.
- *
- * @param is The reader.
- *
- * @return The contents of the reader.
- */
- private static String readStreamAsString(BufferedInputStream is)
- {
- try
- {
- byte[] data = new byte[4096];
-
- StringBuffer inBuffer = new StringBuffer();
-
- String line;
- int read;
-
- while ((read = is.read(data)) != -1)
- {
- String s = new String(data, 0, read);
- inBuffer.append(s);
- }
-
- return inBuffer.toString();
- }
- catch (IOException e)
- {
- throw new RuntimeException(e);
- }
- }
-
- /**
- * Either opens the specified filename as an input stream, or uses the default resource loaded using the
- * specified class loader, if opening the file fails or no file name is specified.
- *
- * @param filename The name of the file to open.
- * @param defaultResource The name of the default resource on the classpath if the file cannot be opened.
- * @param cl The classloader to load the default resource with.
- *
- * @return An input stream for the file or resource, or null if one could not be opened.
- */
- public static InputStream openFileOrDefaultResource(String filename, String defaultResource, ClassLoader cl)
- {
- InputStream is = null;
-
- // Flag to indicate whether the default resource should be used. By default this is true, so that the default
- // is used when opening the file fails.
- boolean useDefault = true;
-
- // Try to open the file if one was specified.
- if (filename != null)
- {
- try
- {
- is = new BufferedInputStream(new FileInputStream(new File(filename)));
-
- // Clear the default flag because the file was succesfully opened.
- useDefault = false;
- }
- catch (FileNotFoundException e)
- {
- // Ignore this exception, the default will be used instead.
- }
- }
-
- // Load the default resource if a file was not specified, or if opening the file failed.
- if (useDefault)
- {
- is = cl.getResourceAsStream(defaultResource);
- }
-
- return is;
- }
-
- /**
- * Copies the specified source file to the specified destintaion file. If the destinationst file does not exist,
- * it is created.
- *
- * @param src The source file name.
- * @param dst The destination file name.
- */
- public static void copy(File src, File dst)
- {
- try
- {
- copyCheckedEx(src, dst);
- }
- catch (IOException e)
- {
- throw new RuntimeException(e);
- }
- }
-
- /**
- * Copies the specified source file to the specified destination file. If the destination file does not exist,
- * it is created.
- *
- * @param src The source file name.
- * @param dst The destination file name.
- * @throws IOException
- */
- public static void copyCheckedEx(File src, File dst) throws IOException
- {
- InputStream in = new FileInputStream(src);
- try
- {
- if (!dst.exists())
- {
- dst.createNewFile();
- }
-
- OutputStream out = new FileOutputStream(dst);
-
- try
- {
- // Transfer bytes from in to out
- byte[] buf = new byte[1024];
- int len;
- while ((len = in.read(buf)) > 0)
- {
- out.write(buf, 0, len);
- }
- }
- finally
- {
- out.close();
- }
- }
- finally
- {
- in.close();
- }
- }
-
- /*
- * Deletes a given file
- */
- public static boolean deleteFile(String filePath)
- {
- return delete(new File(filePath), false);
- }
-
- /*
- * Deletes a given empty directory
- */
- public static boolean deleteDirectory(String directoryPath)
- {
- File directory = new File(directoryPath);
-
- if (directory.isDirectory())
- {
- if (directory.listFiles().length == 0)
- {
- return delete(directory, true);
- }
- }
-
- return false;
- }
-
- /**
- * Delete a given file/directory,
- * A directory will always require the recursive flag to be set.
- * if a directory is specified and recursive set then delete the whole tree
- *
- * @param file the File object to start at
- * @param recursive boolean to recurse if a directory is specified.
- *
- * @return <code>true</code> if and only if the file or directory is
- * successfully deleted; <code>false</code> otherwise
- */
- public static boolean delete(File file, boolean recursive)
- {
- boolean success = true;
-
- if (file.isDirectory())
- {
- if (recursive)
- {
- File[] files = file.listFiles();
-
- // This can occur if the file is deleted outside the JVM
- if (files == null)
- {
- return false;
- }
-
- for (int i = 0; i < files.length; i++)
- {
- success = delete(files[i], true) && success;
- }
-
- return success && file.delete();
- }
-
- return false;
- }
-
- return file.delete();
- }
-
- public static class UnableToCopyException extends Exception
- {
- UnableToCopyException(String msg)
- {
- super(msg);
- }
- }
-
- public static void copyRecursive(File source, File dst) throws FileNotFoundException, UnableToCopyException
- {
-
- if (!source.exists())
- {
- throw new FileNotFoundException("Unable to copy '" + source.toString() + "' as it does not exist.");
- }
-
- if (dst.exists() && !dst.isDirectory())
- {
- throw new IllegalArgumentException("Unable to copy '" + source.toString() + "' to '" + dst + "' a file with same name exists.");
- }
-
- if (source.isFile())
- {
- copy(source, dst);
- }
-
- //else we have a source directory
- if (!dst.isDirectory() && !dst.mkdirs())
- {
- throw new UnableToCopyException("Unable to create destination directory");
- }
-
- for (File file : source.listFiles())
- {
- if (file.isFile())
- {
- copy(file, new File(dst.toString() + File.separator + file.getName()));
- }
- else
- {
- copyRecursive(file, new File(dst + File.separator + file.getName()));
- }
- }
-
- }
-
- /**
- * Checks the specified file for instances of the search string.
- *
- * @param file the file to search
- * @param search the search String
- *
- * @throws java.io.IOException
- * @return the list of matching entries
- */
- public static List<String> searchFile(File file, String search)
- throws IOException
- {
-
- List<String> results = new LinkedList<String>();
-
- BufferedReader reader = new BufferedReader(new FileReader(file));
- try
- {
- while (reader.ready())
- {
- String line = reader.readLine();
- if (line.contains(search))
- {
- results.add(line);
- }
- }
- }
- finally
- {
- reader.close();
- }
-
- return results;
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/util/MessageQueue.java b/java/common/src/main/java/org/apache/qpid/util/MessageQueue.java
deleted file mode 100644
index b5efaa61b6..0000000000
--- a/java/common/src/main/java/org/apache/qpid/util/MessageQueue.java
+++ /dev/null
@@ -1,43 +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.util;
-
-import java.util.Queue;
-
-/**
- * Defines a queue that has a push operation to add an element to the head of the queue.
- *
- * @todo Seems like this may be pointless, the implementation uses this method to increment the message count
- * then calls offer. Why not simply override offer and drop this interface?
- */
-public interface MessageQueue<E> extends Queue<E>
-{
- /**
- * Inserts the specified element into this queue, if possible. When using queues that may impose insertion
- * restrictions (for example capacity bounds), method offer is generally preferable to method Collection.add(E),
- * which can fail to insert an element only by throwing an exception.
- *
- * @param o The element to insert.
- *
- * @return <tt>true</tt> if it was possible to add the element to this queue, else <tt>false</tt>
- */
- boolean pushHead(E o);
-}
diff --git a/java/common/src/main/java/org/apache/qpid/util/NameUUIDGen.java b/java/common/src/main/java/org/apache/qpid/util/NameUUIDGen.java
deleted file mode 100644
index e764c8536b..0000000000
--- a/java/common/src/main/java/org/apache/qpid/util/NameUUIDGen.java
+++ /dev/null
@@ -1,59 +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.util;
-
-import java.nio.ByteBuffer;
-import java.util.UUID;
-
-
-/**
- * NameUUIDGen
- *
- */
-
-public final class NameUUIDGen implements UUIDGen
-{
-
- private static final int WIDTH = 8;
-
- final private byte[] seed;
- final private ByteBuffer seedBuf;
- private long counter;
-
- public NameUUIDGen()
- {
- String namespace = UUID.randomUUID().toString();
- this.seed = new byte[namespace.length() + WIDTH];
- for (int i = WIDTH; i < seed.length; i++)
- {
- seed[i] = (byte) namespace.charAt(i - WIDTH);
- }
- this.seedBuf = ByteBuffer.wrap(seed);
- this.counter = 0;
- }
-
- public UUID generate()
- {
- seedBuf.putLong(0, counter++);
- return UUID.nameUUIDFromBytes(seed);
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/util/NetMatcher.java b/java/common/src/main/java/org/apache/qpid/util/NetMatcher.java
deleted file mode 100644
index 4c653e6ca0..0000000000
--- a/java/common/src/main/java/org/apache/qpid/util/NetMatcher.java
+++ /dev/null
@@ -1,264 +0,0 @@
-/***********************************************************************
- * Copyright (c) 2000-2006 The Apache Software Foundation. *
- * All rights reserved. *
- * ------------------------------------------------------------------- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you *
- * may not use this file except in compliance with the License. You *
- * may obtain a copy of the License at: *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, software *
- * distributed under the License is distributed on an "AS IS" BASIS, *
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *
- * implied. See the License for the specific language governing *
- * permissions and limitations under the License. *
- ***********************************************************************/
-
-package org.apache.qpid.util;
-
-import java.net.InetAddress;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Iterator;
-
-public class NetMatcher
-{
- private ArrayList networks;
-
- public void initInetNetworks(final Collection nets)
- {
- networks = new ArrayList();
- for (Iterator iter = nets.iterator(); iter.hasNext(); ) try
- {
- InetNetwork net = InetNetwork.getFromString((String) iter.next());
- if (!networks.contains(net)) networks.add(net);
- }
- catch (java.net.UnknownHostException uhe)
- {
- log("Cannot resolve address: " + uhe.getMessage());
- }
- networks.trimToSize();
- }
-
- public void initInetNetworks(final String[] nets)
- {
- networks = new ArrayList();
- for (int i = 0; i < nets.length; i++) try
- {
- InetNetwork net = InetNetwork.getFromString(nets[i]);
- if (!networks.contains(net)) networks.add(net);
- }
- catch (java.net.UnknownHostException uhe)
- {
- log("Cannot resolve address: " + uhe.getMessage());
- }
- networks.trimToSize();
- }
-
- public boolean matchInetNetwork(final String hostIP)
- {
- InetAddress ip = null;
-
- try
- {
- ip = InetAddress.getByName(hostIP);
- }
- catch (java.net.UnknownHostException uhe)
- {
- log("Cannot resolve address for " + hostIP + ": " + uhe.getMessage());
- }
-
- boolean sameNet = false;
-
- if (ip != null) for (Iterator iter = networks.iterator(); (!sameNet) && iter.hasNext(); )
- {
- InetNetwork network = (InetNetwork) iter.next();
- sameNet = network.contains(ip);
- }
- return sameNet;
- }
-
- public boolean matchInetNetwork(final InetAddress ip)
- {
- boolean sameNet = false;
-
- for (Iterator iter = networks.iterator(); (!sameNet) && iter.hasNext(); )
- {
- InetNetwork network = (InetNetwork) iter.next();
- sameNet = network.contains(ip);
- }
- return sameNet;
- }
-
- public NetMatcher()
- {
- }
-
- public NetMatcher(final String[] nets)
- {
- initInetNetworks(nets);
- }
-
- public NetMatcher(final Collection nets)
- {
- initInetNetworks(nets);
- }
-
- public String toString() {
- return networks.toString();
- }
-
- protected void log(String s) { }
-}
-
-class InetNetwork
-{
- /*
- * Implements network masking, and is compatible with RFC 1518 and
- * RFC 1519, which describe CIDR: Classless Inter-Domain Routing.
- */
-
- private InetAddress network;
- private InetAddress netmask;
-
- public InetNetwork(InetAddress ip, InetAddress netmask)
- {
- network = maskIP(ip, netmask);
- this.netmask = netmask;
- }
-
- public boolean contains(final String name) throws java.net.UnknownHostException
- {
- return network.equals(maskIP(InetAddress.getByName(name), netmask));
- }
-
- public boolean contains(final InetAddress ip)
- {
- return network.equals(maskIP(ip, netmask));
- }
-
- public String toString()
- {
- return network.getHostAddress() + "/" + netmask.getHostAddress();
- }
-
- public int hashCode()
- {
- return maskIP(network, netmask).hashCode();
- }
-
- public boolean equals(Object obj)
- {
- return (obj != null) && (obj instanceof InetNetwork) &&
- ((((InetNetwork)obj).network.equals(network)) && (((InetNetwork)obj).netmask.equals(netmask)));
- }
-
- public static InetNetwork getFromString(String netspec) throws java.net.UnknownHostException
- {
- if (netspec.endsWith("*")) netspec = normalizeFromAsterisk(netspec);
- else
- {
- int iSlash = netspec.indexOf('/');
- if (iSlash == -1) netspec += "/255.255.255.255";
- else if (netspec.indexOf('.', iSlash) == -1) netspec = normalizeFromCIDR(netspec);
- }
-
- return new InetNetwork(InetAddress.getByName(netspec.substring(0, netspec.indexOf('/'))),
- InetAddress.getByName(netspec.substring(netspec.indexOf('/') + 1)));
- }
-
- public static InetAddress maskIP(final byte[] ip, final byte[] mask)
- {
- try
- {
- return getByAddress(new byte[]
- {
- (byte) (mask[0] & ip[0]),
- (byte) (mask[1] & ip[1]),
- (byte) (mask[2] & ip[2]),
- (byte) (mask[3] & ip[3])
- });
- }
- catch(Exception _) {}
- {
- return null;
- }
- }
-
- public static InetAddress maskIP(final InetAddress ip, final InetAddress mask)
- {
- return maskIP(ip.getAddress(), mask.getAddress());
- }
-
- /*
- * This converts from an uncommon "wildcard" CIDR format
- * to "address + mask" format:
- *
- * * => 000.000.000.0/000.000.000.0
- * xxx.* => xxx.000.000.0/255.000.000.0
- * xxx.xxx.* => xxx.xxx.000.0/255.255.000.0
- * xxx.xxx.xxx.* => xxx.xxx.xxx.0/255.255.255.0
- */
- static private String normalizeFromAsterisk(final String netspec)
- {
- String[] masks = { "0.0.0.0/0.0.0.0", "0.0.0/255.0.0.0", "0.0/255.255.0.0", "0/255.255.255.0" };
- char[] srcb = netspec.toCharArray();
- int octets = 0;
- for (int i = 1; i < netspec.length(); i++) {
- if (srcb[i] == '.') octets++;
- }
- return (octets == 0) ? masks[0] : netspec.substring(0, netspec.length() -1 ).concat(masks[octets]);
- }
-
- /*
- * RFC 1518, 1519 - Classless Inter-Domain Routing (CIDR)
- * This converts from "prefix + prefix-length" format to
- * "address + mask" format, e.g. from xxx.xxx.xxx.xxx/yy
- * to xxx.xxx.xxx.xxx/yyy.yyy.yyy.yyy.
- */
- static private String normalizeFromCIDR(final String netspec)
- {
- final int bits = 32 - Integer.parseInt(netspec.substring(netspec.indexOf('/')+1));
- final int mask = (bits == 32) ? 0 : 0xFFFFFFFF - ((1 << bits)-1);
-
- return netspec.substring(0, netspec.indexOf('/') + 1) +
- Integer.toString(mask >> 24 & 0xFF, 10) + "." +
- Integer.toString(mask >> 16 & 0xFF, 10) + "." +
- Integer.toString(mask >> 8 & 0xFF, 10) + "." +
- Integer.toString(mask >> 0 & 0xFF, 10);
- }
-
- private static java.lang.reflect.Method getByAddress = null;
-
- static {
- try {
- Class inetAddressClass = Class.forName("java.net.InetAddress");
- Class[] parameterTypes = { byte[].class };
- getByAddress = inetAddressClass.getMethod("getByAddress", parameterTypes);
- } catch (Exception e) {
- getByAddress = null;
- }
- }
-
- private static InetAddress getByAddress(byte[] ip) throws java.net.UnknownHostException
- {
- InetAddress addr = null;
- if (getByAddress != null) try {
- addr = (InetAddress) getByAddress.invoke(null, new Object[] { ip });
- } catch (IllegalAccessException e) {
- } catch (java.lang.reflect.InvocationTargetException e) {
- }
-
- if (addr == null) {
- addr = InetAddress.getByName
- (
- Integer.toString(ip[0] & 0xFF, 10) + "." +
- Integer.toString(ip[1] & 0xFF, 10) + "." +
- Integer.toString(ip[2] & 0xFF, 10) + "." +
- Integer.toString(ip[3] & 0xFF, 10)
- );
- }
- return addr;
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/util/PrettyPrintingUtils.java b/java/common/src/main/java/org/apache/qpid/util/PrettyPrintingUtils.java
deleted file mode 100644
index 93266f2486..0000000000
--- a/java/common/src/main/java/org/apache/qpid/util/PrettyPrintingUtils.java
+++ /dev/null
@@ -1,75 +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.util;
-
-/**
- * Contains pretty printing convenienve methods for producing formatted logging output, mostly for debugging purposes.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * </table>
- *
- * @todo Drop this. There are already array pretty printing methods it java.utils.Arrays.
- */
-public class PrettyPrintingUtils
-{
- /**
- * Pretty prints an array of ints as a string.
- *
- * @param array The array to pretty print.
- *
- * @return The pretty printed string.
- */
- public static String printArray(int[] array)
- {
- StringBuilder result = new StringBuilder("[");
- for (int i = 0; i < array.length; i++)
- {
- result.append(array[i])
- .append((i < (array.length - 1)) ? ", " : "");
- }
-
- result.append(']');
-
- return result.toString();
- }
-
- /**
- * Pretty prints an array of strings as a string.
- *
- * @param array The array to pretty print.
- *
- * @return The pretty printed string.
- */
- public static String printArray(String[] array)
- {
- String result = "[";
- for (int i = 0; i < array.length; i++)
- {
- result += array[i];
- result += (i < (array.length - 1)) ? ", " : "";
- }
-
- result += "]";
-
- return result;
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/util/RandomUUIDGen.java b/java/common/src/main/java/org/apache/qpid/util/RandomUUIDGen.java
deleted file mode 100644
index 60b402a105..0000000000
--- a/java/common/src/main/java/org/apache/qpid/util/RandomUUIDGen.java
+++ /dev/null
@@ -1,39 +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.util;
-
-import java.util.UUID;
-
-
-/**
- * RandomUUIDGen
- *
- */
-
-public final class RandomUUIDGen implements UUIDGen
-{
-
- public UUID generate()
- {
- return UUID.randomUUID();
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/util/Serial.java b/java/common/src/main/java/org/apache/qpid/util/Serial.java
deleted file mode 100644
index 8ad9d00f54..0000000000
--- a/java/common/src/main/java/org/apache/qpid/util/Serial.java
+++ /dev/null
@@ -1,108 +0,0 @@
-package org.apache.qpid.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.
- *
- */
-
-
-import java.util.Comparator;
-
-import org.apache.qpid.SerialException;
-
-/**
- * This class provides basic serial number comparisons as defined in
- * RFC 1982.
- */
-
-public class Serial
-{
-
- public static final Comparator<Integer> COMPARATOR = new Comparator<Integer>()
- {
- public int compare(Integer s1, Integer s2)
- {
- return Serial.compare(s1, s2);
- }
- };
-
- /**
- * Compares two numbers using serial arithmetic.
- *
- * @param s1 the first serial number
- * @param s2 the second serial number
- *
- * @return a negative integer, zero, or a positive integer as the
- * first argument is less than, equal to, or greater than the
- * second
- */
- public static final int compare(int s1, int s2)
- {
- return s1 - s2;
- }
-
- public static final boolean lt(int s1, int s2)
- {
- return compare(s1, s2) < 0;
- }
-
- public static final boolean le(int s1, int s2)
- {
- return compare(s1, s2) <= 0;
- }
-
- public static final boolean gt(int s1, int s2)
- {
- return compare(s1, s2) > 0;
- }
-
- public static final boolean ge(int s1, int s2)
- {
- return compare(s1, s2) >= 0;
- }
-
- public static final boolean eq(int s1, int s2)
- {
- return s1 == s2;
- }
-
- public static final int min(int s1, int s2)
- {
- if (lt(s1, s2))
- {
- return s1;
- }
- else
- {
- return s2;
- }
- }
-
- public static final int max(int s1, int s2)
- {
- if (gt(s1, s2))
- {
- return s1;
- }
- else
- {
- return s2;
- }
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/util/Strings.java b/java/common/src/main/java/org/apache/qpid/util/Strings.java
deleted file mode 100644
index a6a8b8beb4..0000000000
--- a/java/common/src/main/java/org/apache/qpid/util/Strings.java
+++ /dev/null
@@ -1,260 +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.util;
-
-import java.io.UnsupportedEncodingException;
-
-import java.util.Arrays;
-import java.util.Map;
-import java.util.Properties;
-import java.util.Stack;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-
-/**
- * Strings
- *
- */
-
-public final class Strings
-{
-
- private static final byte[] EMPTY = new byte[0];
-
- private static final ThreadLocal<char[]> charbuf = new ThreadLocal<char[]>()
- {
- public char[] initialValue()
- {
- return new char[4096];
- }
- };
-
- public static final byte[] toUTF8(String str)
- {
- if (str == null)
- {
- return EMPTY;
- }
- else
- {
- final int size = str.length();
- char[] chars = charbuf.get();
- if (size > chars.length)
- {
- chars = new char[Math.max(size, 2*chars.length)];
- charbuf.set(chars);
- }
-
- str.getChars(0, size, chars, 0);
- final byte[] bytes = new byte[size];
- for (int i = 0; i < size; i++)
- {
- if (chars[i] > 127)
- {
- try
- {
- return str.getBytes("UTF-8");
- }
- catch (UnsupportedEncodingException e)
- {
- throw new RuntimeException(e);
- }
- }
-
- bytes[i] = (byte) chars[i];
- }
- return bytes;
- }
- }
-
- public static final String fromUTF8(byte[] bytes)
- {
- try
- {
- return new String(bytes, "UTF-8");
- }
- catch (UnsupportedEncodingException e)
- {
- throw new RuntimeException(e);
- }
- }
-
- private static final Pattern VAR = Pattern.compile("(?:\\$\\{([^\\}]*)\\})|(?:\\$(\\$))");
-
- public static interface Resolver
- {
- String resolve(String variable);
- }
-
- public static class MapResolver implements Resolver
- {
-
- private final Map<String,String> map;
-
- public MapResolver(Map<String,String> map)
- {
- this.map = map;
- }
-
- public String resolve(String variable)
- {
- return map.get(variable);
- }
- }
-
- public static class PropertiesResolver implements Resolver
- {
-
- private final Properties properties;
-
- public PropertiesResolver(Properties properties)
- {
- this.properties = properties;
- }
-
- public String resolve(String variable)
- {
- return properties.getProperty(variable);
- }
- }
-
- public static class ChainedResolver implements Resolver
- {
- private final Resolver primary;
- private final Resolver secondary;
-
- public ChainedResolver(Resolver primary, Resolver secondary)
- {
- this.primary = primary;
- this.secondary = secondary;
- }
-
- public String resolve(String variable)
- {
- String result = primary.resolve(variable);
- if (result == null)
- {
- result = secondary.resolve(variable);
- }
- return result;
- }
- }
-
- public static final Resolver SYSTEM_RESOLVER = new Resolver()
- {
- public String resolve(String variable)
- {
- String result = System.getProperty(variable);
- if (result == null)
- {
- result = System.getenv(variable);
- }
- return result;
- }
- };
-
- public static final String expand(String input)
- {
- return expand(input, SYSTEM_RESOLVER);
- }
-
- public static final String expand(String input, Resolver resolver)
- {
- return expand(input, resolver, new Stack<String>());
- }
-
- private static final String expand(String input, Resolver resolver, Stack<String> stack)
- {
- Matcher m = VAR.matcher(input);
- StringBuffer result = new StringBuffer();
- while (m.find())
- {
- String var = m.group(1);
- if (var == null)
- {
- String esc = m.group(2);
- if ("$".equals(esc))
- {
- m.appendReplacement(result, Matcher.quoteReplacement("$"));
- }
- else
- {
- throw new IllegalArgumentException(esc);
- }
- }
- else
- {
- m.appendReplacement(result, Matcher.quoteReplacement(resolve(var, resolver, stack)));
- }
- }
- m.appendTail(result);
- return result.toString();
- }
-
- private static final String resolve(String var, Resolver resolver, Stack<String> stack)
- {
- if (stack.contains(var))
- {
- throw new IllegalArgumentException
- (String.format("recursively defined variable: %s stack=%s", var,
- stack));
- }
-
- String result = resolver.resolve(var);
- if (result == null)
- {
- throw new IllegalArgumentException("no such variable: " + var);
- }
-
- stack.push(var);
- try
- {
- return expand(result, resolver, stack);
- }
- finally
- {
- stack.pop();
- }
- }
-
- public static final String join(String sep, Iterable items)
- {
- StringBuilder result = new StringBuilder();
-
- for (Object o : items)
- {
- if (result.length() > 0)
- {
- result.append(sep);
- }
- result.append(o.toString());
- }
-
- return result.toString();
- }
-
- public static final String join(String sep, Object[] items)
- {
- return join(sep, Arrays.asList(items));
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/util/UUIDGen.java b/java/common/src/main/java/org/apache/qpid/util/UUIDGen.java
deleted file mode 100644
index 3cfe5afdac..0000000000
--- a/java/common/src/main/java/org/apache/qpid/util/UUIDGen.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.util;
-
-
-import java.util.UUID;
-
-/**
- * UUIDGen
- *
- */
-
-public interface UUIDGen
-{
-
- public UUID generate();
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/util/UUIDs.java b/java/common/src/main/java/org/apache/qpid/util/UUIDs.java
deleted file mode 100644
index 4bf6b7f0a2..0000000000
--- a/java/common/src/main/java/org/apache/qpid/util/UUIDs.java
+++ /dev/null
@@ -1,59 +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.util;
-
-
-/**
- * UUIDs
- *
- */
-
-public final class UUIDs
-{
-
- public static final UUIDGen newGenerator()
- {
- return newGenerator(System.getProperty("qpid.uuid.generator",
- NameUUIDGen.class.getName()));
- }
-
- public static UUIDGen newGenerator(String name)
- {
- try
- {
- Class cls = Class.forName(name);
- return (UUIDGen) cls.newInstance();
- }
- catch (InstantiationException e)
- {
- throw new RuntimeException(e);
- }
- catch (IllegalAccessException e)
- {
- throw new RuntimeException(e);
- }
- catch (ClassNotFoundException e)
- {
- throw new RuntimeException(e);
- }
- }
-
-}
diff --git a/java/common/src/main/java/org/apache/qpid/util/concurrent/AlreadyUnblockedException.java b/java/common/src/main/java/org/apache/qpid/util/concurrent/AlreadyUnblockedException.java
deleted file mode 100644
index e0c0337898..0000000000
--- a/java/common/src/main/java/org/apache/qpid/util/concurrent/AlreadyUnblockedException.java
+++ /dev/null
@@ -1,34 +0,0 @@
-package org.apache.qpid.util.concurrent;
-/*
- *
- * 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.
- *
- */
-
-
-/**
- * Used to signal that a data element and its producer cannot be requeued or sent an error message when using a
- * {@link BatchSynchQueue} because the producer has already been unblocked by an unblocking take on the queue.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Signal that an unblocking take has already occurred.
- * </table>
- */
-public class AlreadyUnblockedException extends RuntimeException
-{ }
diff --git a/java/common/src/main/java/org/apache/qpid/util/concurrent/BatchSynchQueue.java b/java/common/src/main/java/org/apache/qpid/util/concurrent/BatchSynchQueue.java
deleted file mode 100644
index 63d8f77edb..0000000000
--- a/java/common/src/main/java/org/apache/qpid/util/concurrent/BatchSynchQueue.java
+++ /dev/null
@@ -1,122 +0,0 @@
-package org.apache.qpid.util.concurrent;
-/*
- *
- * 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 java.util.Collection;
-import java.util.concurrent.BlockingQueue;
-
-/**
- * BatchSynchQueue is an abstraction of the classic producer/consumer buffer pattern for thread interaction. In this
- * pattern threads can deposit data onto a buffer whilst other threads take data from the buffer and perform usefull
- * work with it. A BatchSynchQueue adds to this the possibility that producers can be blocked until their data is
- * consumed or until a consumer chooses to release the producer some time after consuming the data from the queue.
- *
- * <p>There are a number of possible advantages to using this technique when compared with having the producers
- * processing their own data:
- *
- * <ul>
- * <li>Data may be deposited asynchronously in the buffer allowing the producers to continue running.</li>
- * <li>Data may be deposited synchronously in the buffer so that producers wait until their data has been processed
- * before being allowed to continue.</li>
- * <li>Variable rates of production/consumption can be smoothed over by the buffer as it provides space in memory to
- * hold data between production and consumption.</li>
- * <li>Consumers may be able to batch data as they consume it leading to more efficient consumption over
- * individual data item consumption where latency associated with the consume operation can be ammortized.
- * For example, it may be possibly to ammortize the cost of a disk seek over many producers.</li>
- * <li>Data from seperate threads can be combined together in the buffer, providing a convenient way of spreading work
- * amongst many workers and gathering the results together again.</li>
- * <li>Different types of queue can be used to hold the buffer, resulting in different processing orders. For example,
- * lifo, fifo, priority heap, etc.</li>
- * </ul>
- *
- * <p/>The asynchronous type of producer/consumer buffers is already well supported by the java.util.concurrent package
- * (in Java 5) and there is also a synchronous queue implementation available there too. This interface extends the
- * blocking queue with some more methods for controlling a synchronous blocking queue. In particular it adds additional
- * take methods that can be used to take data from a queue without releasing producers, so that consumers have an
- * opportunity to confirm correct processing of the data before producers are released. It also adds a put method with
- * exceptions so that consumers can signal exception cases back to producers where there are errors in the data.
- *
- * <p/>This type of queue is usefull in situations where consumers can obtain an efficiency gain by batching data
- * from many threads but where synchronous handling of that data is neccessary because producers need to know that
- * their data has been processed before they continue. For example, sending a bundle of messages together, or writing
- * many records to disk at once, may result in improved performance but the originators of the messages or disk records
- * need confirmation that their data has really been sent or saved to disk.
- *
- * <p/>The consumer can put an element back onto the queue or send an error message to the elements producer using the
- * {@link SynchRecord} interface.
- *
- * <p/>The {@link #take()}, {@link #drainTo(java.util.Collection<? super E>)} and
- * {@link #drainTo(java.util.Collection<? super E>, int)} methods from {@link BlockingQueue} should behave as if they
- * have been called with unblock set to false. That is they take elements from the queue but leave the producers
- * blocked. These methods do not return collections of {@link SynchRecord}s so they do not supply an interface through
- * which errors or re-queuings can be applied. If these methods are used then the consumer must succesfully process
- * all the records it takes.
- *
- * <p/>The {@link #put} method should silently swallow any exceptions that consumers attempt to return to the caller.
- * In order to handle exceptions the {@link #tryPut} method must be used.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Handle synchronous puts, with possible exceptions.
- * <tr><td> Allow consumers to take many records from a queue in a batch.
- * <tr><td> Allow consumers to decide when to unblock synchronous producers.
- * </table>
- */
-public interface BatchSynchQueue<E> extends BlockingQueue<E>
-{
- /**
- * Tries a synchronous put into the queue. If a consumer encounters an exception condition whilst processing the
- * data that is put, then this is returned to the caller wrapped inside a {@link SynchException}.
- *
- * @param e The data element to put into the queue.
- *
- * @throws InterruptedException If the thread is interrupted whilst waiting to write to the queue or whilst waiting
- * on its entry in the queue being consumed.
- * @throws SynchException If a consumer encounters an error whilst processing the data element.
- */
- public void tryPut(E e) throws InterruptedException, SynchException;
-
- /**
- * Takes all available data items from the queue or blocks until some become available. The returned items
- * are wrapped in a {@link SynchRecord} which provides an interface to requeue them or send errors to their
- * producers, where the producers are still blocked.
- *
- * @param c The collection to drain the data items into.
- * @param unblock If set to <tt>true</tt> the producers for the taken items will be immediately unblocked.
- *
- * @return A count of the number of elements that were drained from the queue.
- */
- public SynchRef drainTo(Collection<SynchRecord<E>> c, boolean unblock);
-
- /**
- * Takes up to maxElements available data items from the queue or blocks until some become available. The returned
- * items are wrapped in a {@link SynchRecord} which provides an interface to requeue them or send errors to their
- * producers, where the producers are still blocked.
- *
- * @param c The collection to drain the data items into.
- * @param maxElements The maximum number of elements to drain.
- * @param unblock If set to <tt>true</tt> the producers for the taken items will be immediately unblocked.
- *
- * @return A count of the number of elements that were drained from the queue.
- */
- public SynchRef drainTo(Collection<SynchRecord<E>> c, int maxElements, boolean unblock);
-}
diff --git a/java/common/src/main/java/org/apache/qpid/util/concurrent/BatchSynchQueueBase.java b/java/common/src/main/java/org/apache/qpid/util/concurrent/BatchSynchQueueBase.java
deleted file mode 100644
index 4564b1d686..0000000000
--- a/java/common/src/main/java/org/apache/qpid/util/concurrent/BatchSynchQueueBase.java
+++ /dev/null
@@ -1,834 +0,0 @@
-package org.apache.qpid.util.concurrent;
-/*
- *
- * 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 java.util.*;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.locks.Condition;
-import java.util.concurrent.locks.ReentrantLock;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-
-/**
- * Synchronous/Asynchronous puts. Asynchronous is easiest, just wait till can write to queue and deposit data.
- * Synchronous is harder. Deposit data, but then must wait until deposited element/elements are taken before being
- * allowed to unblock and continue. Consumer needs some options here too. Can just get the data from the buffer and
- * allow any producers unblocked as a result to continue, or can get data but continue blocking while the data is
- * processed before sending a message to do the unblocking. Synch/Asynch mode to be controlled by a switch.
- * Unblocking/not unblocking during consumer processing to be controlled by the consumers calls.
- *
- * <p/>Implementing sub-classes only need to supply an implementation of a queue to produce a valid concrete
- * implementation of this. This queue is only accessed through the methods {@link #insert}, {@link #extract},
- * {@link #getBufferCapacity()}, {@link #peekAtBufferHead()}. An implementation can override these methods to implement
- * the buffer other than by a queue, for example, by using an array.
- *
- * <p/>Normal queue methods to work asynchronously.
- * <p/>Put, take and drain methods from the BlockingQueue interface work synchronously but unblock producers immediately
- * when their data is taken.
- * <p/>The additional put, take and drain methods from the BatchSynchQueue interface work synchronously and provide the
- * option to keep producers blocked until the consumer decides to release them.
- *
- * <p/>Removed take method that keeps producers blocked as it is pointless. Essentially it reduces this class to
- * synchronous processing of individual data items, which negates the point of the hand-off design. The efficiency
- * gain of the hand off design comes in being able to batch consume requests, ammortizing latency (such as caused by io)
- * accross many producers. The only advantage of the single blocking take method is that it did take advantage of the
- * queue ordering, which ma be usefull, for example to apply a priority ordering amongst producers. This is also an
- * advantage over the java.util.concurrent.SynchronousQueue which doesn't have a backing queue which can be used to
- * apply orderings. If a single item take is really needed can just use the drainTo method with a maximum of one item.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * </table>
- */
-public abstract class BatchSynchQueueBase<E> extends AbstractQueue<E> implements BatchSynchQueue<E>
-{
- /** Used for logging. */
- private static final Logger log = LoggerFactory.getLogger(BatchSynchQueueBase.class);
-
- /** Holds a reference to the queue implementation that holds the buffer. */
- Queue<SynchRecordImpl<E>> buffer;
-
- /** Holds the number of items in the queue */
- private int count;
-
- /** Main lock guarding all access */
- private ReentrantLock lock;
-
- /** Condition for waiting takes */
- private Condition notEmpty;
-
- /** Condition for waiting puts */
- private Condition notFull;
-
- /**
- * Creates a batch synch queue without fair thread scheduling.
- */
- public BatchSynchQueueBase()
- {
- this(false);
- }
-
- /**
- * Ensures that the underlying buffer implementation is created.
- *
- * @param fair <tt>true</tt> if fairness is to be applied to threads waiting to access the buffer.
- */
- public BatchSynchQueueBase(boolean fair)
- {
- buffer = this.createQueue();
-
- // Create the buffer lock with the fairness flag set accordingly.
- lock = new ReentrantLock(fair);
-
- // Create the non-empty and non-full condition monitors on the buffer lock.
- notEmpty = lock.newCondition();
- notFull = lock.newCondition();
- }
-
- /**
- * Returns an iterator over the elements contained in this collection.
- *
- * @return An iterator over the elements contained in this collection.
- */
- public Iterator<E> iterator()
- {
- throw new RuntimeException("Not implemented.");
- }
-
- /**
- * Returns the number of elements in this collection. If the collection contains more than
- * <tt>Integer.MAX_VALUE</tt> elements, returns <tt>Integer.MAX_VALUE</tt>.
- *
- * @return The number of elements in this collection.
- */
- public int size()
- {
- final ReentrantLock lock = this.lock;
- lock.lock();
-
- try
- {
- return count;
- }
- finally
- {
- lock.unlock();
- }
- }
-
- /**
- * Inserts the specified element into this queue, if possible. When using queues that may impose insertion
- * restrictions (for example capacity bounds), method <tt>offer</tt> is generally preferable to method
- * {@link java.util.Collection#add}, which can fail to insert an element only by throwing an exception.
- *
- * @param e The element to insert.
- *
- * @return <tt>true</tt> if it was possible to add the element to this queue, else <tt>false</tt>
- */
- public boolean offer(E e)
- {
- if (e == null)
- {
- throw new NullPointerException();
- }
-
- final ReentrantLock lock = this.lock;
- lock.lock();
-
- try
- {
- return insert(e, false);
- }
- finally
- {
- lock.unlock();
- }
- }
-
- /**
- * Inserts the specified element into this queue, waiting if necessary up to the specified wait time for space to
- * become available.
- *
- * @param e The element to add.
- * @param timeout How long to wait before giving up, in units of <tt>unit</tt>
- * @param unit A <tt>TimeUnit</tt> determining how to interpret the <tt>timeout</tt> parameter.
- *
- * @return <tt>true</tt> if successful, or <tt>false</tt> if the specified waiting time elapses before space is
- * available.
- *
- * @throws InterruptedException If interrupted while waiting.
- * @throws NullPointerException If the specified element is <tt>null</tt>.
- */
- public boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException
- {
- if (e == null)
- {
- throw new NullPointerException();
- }
-
- final ReentrantLock lock = this.lock;
- lock.lockInterruptibly();
-
- long nanos = unit.toNanos(timeout);
-
- try
- {
- do
- {
- if (insert(e, false))
- {
- return true;
- }
-
- try
- {
- nanos = notFull.awaitNanos(nanos);
- }
- catch (InterruptedException ie)
- {
- notFull.signal(); // propagate to non-interrupted thread
- throw ie;
- }
- }
- while (nanos > 0);
-
- return false;
- }
- finally
- {
- lock.unlock();
- }
- }
-
- /**
- * Retrieves and removes the head of this queue, or <tt>null</tt> if this queue is empty.
- *
- * @return The head of this queue, or <tt>null</tt> if this queue is empty.
- */
- public E poll()
- {
- final ReentrantLock lock = this.lock;
-
- lock.lock();
- try
- {
- if (count == 0)
- {
- return null;
- }
-
- E x = extract(true, true).getElement();
-
- return x;
- }
- finally
- {
- lock.unlock();
- }
- }
-
- /**
- * Retrieves and removes the head of this queue, waiting if necessary up to the specified wait time if no elements
- * are present on this queue.
- *
- * @param timeout How long to wait before giving up, in units of <tt>unit</tt>.
- * @param unit A <tt>TimeUnit</tt> determining how to interpret the <tt>timeout</tt> parameter.
- *
- * @return The head of this queue, or <tt>null</tt> if the specified waiting time elapses before an element is present.
- *
- * @throws InterruptedException If interrupted while waiting.
- */
- public E poll(long timeout, TimeUnit unit) throws InterruptedException
- {
- final ReentrantLock lock = this.lock;
- lock.lockInterruptibly();
- try
- {
- long nanos = unit.toNanos(timeout);
-
- do
- {
- if (count != 0)
- {
- E x = extract(true, true).getElement();
-
- return x;
- }
-
- try
- {
- nanos = notEmpty.awaitNanos(nanos);
- }
- catch (InterruptedException ie)
- {
- notEmpty.signal(); // propagate to non-interrupted thread
- throw ie;
- }
- }
- while (nanos > 0);
-
- return null;
- }
- finally
- {
- lock.unlock();
- }
- }
-
- /**
- * Retrieves, but does not remove, the head of this queue, returning <tt>null</tt> if this queue is empty.
- *
- * @return The head of this queue, or <tt>null</tt> if this queue is empty.
- */
- public E peek()
- {
- final ReentrantLock lock = this.lock;
- lock.lock();
-
- try
- {
- return peekAtBufferHead();
- }
- finally
- {
- lock.unlock();
- }
- }
-
- /**
- * Returns the number of elements that this queue can ideally (in the absence of memory or resource constraints)
- * accept without blocking, or <tt>Integer.MAX_VALUE</tt> if there is no intrinsic limit.
- *
- * <p>Note that you <em>cannot</em> always tell if an attempt to <tt>add</tt> an element will succeed by
- * inspecting <tt>remainingCapacity</tt> because it may be the case that another thread is about to <tt>put</tt>
- * or <tt>take</tt> an element.
- *
- * @return The remaining capacity.
- */
- public int remainingCapacity()
- {
- final ReentrantLock lock = this.lock;
- lock.lock();
-
- try
- {
- return getBufferCapacity() - count;
- }
- finally
- {
- lock.unlock();
- }
- }
-
- /**
- * Adds the specified element to this queue, waiting if necessary for space to become available.
- *
- * <p/>This method delegated to {@link #tryPut} which can raise {@link SynchException}s. If any are raised
- * this method silently ignores them. Use the {@link #tryPut} method directly if you want to catch these
- * exceptions.
- *
- * @param e The element to add.
- *
- * @throws InterruptedException If interrupted while waiting.
- */
- public void put(E e) throws InterruptedException
- {
- try
- {
- tryPut(e);
- }
- catch (SynchException ex)
- {
- // This exception is deliberately ignored. See the method comment for information about this.
- }
- }
-
- /**
- * Tries a synchronous put into the queue. If a consumer encounters an exception condition whilst processing the
- * data that is put, then this is returned to the caller wrapped inside a {@link SynchException}.
- *
- * @param e The data element to put into the queue. Cannot be null.
- *
- * @throws InterruptedException If the thread is interrupted whilst waiting to write to the queue or whilst waiting
- * on its entry in the queue being consumed.
- * @throws SynchException If a consumer encounters an error whilst processing the data element.
- */
- public void tryPut(E e) throws InterruptedException, SynchException
- {
- if (e == null)
- {
- throw new NullPointerException();
- }
-
- // final Queue<E> items = this.buffer;
- final ReentrantLock lock = this.lock;
- lock.lockInterruptibly();
-
- try
- {
- while (count == getBufferCapacity())
- {
- // Release the lock and wait until the queue is not full.
- notFull.await();
- }
- }
- catch (InterruptedException ie)
- {
- notFull.signal(); // propagate to non-interrupted thread
- throw ie;
- }
-
- // There is room in the queue so insert must succeed. Insert into the queu, release the lock and block
- // the producer until its data is taken.
- insert(e, true);
- }
-
- /**
- * Retrieves and removes the head of this queue, waiting if no elements are present on this queue.
- * Any producer that has its data element taken by this call will be immediately unblocked. To keep the
- * producer blocked whilst taking just a single item, use the
- * {@link #drainTo(java.util.Collection<org.apache.qpid.util.concurrent.SynchRecord<E>>, int, boolean)}
- * method. There is no take method to do that because there is not usually any advantage in a synchronous hand
- * off design that consumes data one item at a time. It is normal to consume data in chunks to ammortize consumption
- * latencies accross many producers where possible.
- *
- * @return The head of this queue.
- *
- * @throws InterruptedException if interrupted while waiting.
- */
- public E take() throws InterruptedException
- {
- final ReentrantLock lock = this.lock;
- lock.lockInterruptibly();
-
- try
- {
- try
- {
- while (count == 0)
- {
- // Release the lock and wait until the queue becomes non-empty.
- notEmpty.await();
- }
- }
- catch (InterruptedException ie)
- {
- notEmpty.signal(); // propagate to non-interrupted thread
- throw ie;
- }
-
- // There is data in the queue so extraction must succeed. Notify any waiting threads that the queue is
- // not full, and unblock the producer that owns the data item that is taken.
- E x = extract(true, true).getElement();
-
- return x;
- }
- finally
- {
- lock.unlock();
- }
- }
-
- /**
- * Removes all available elements from this queue and adds them into the given collection. This operation may be
- * more efficient than repeatedly polling this queue. A failure encountered while attempting to <tt>add</tt> elements
- * to collection <tt>c</tt> may result in elements being in neither, either or both collections when the associated
- * exception is thrown. Attempts to drain a queue to itself result in <tt>IllegalArgumentException</tt>. Further,
- * the behavior of this operation is undefined if the specified collection is modified while the operation is in
- * progress.
- *
- * @param objects The collection to transfer elements into.
- *
- * @return The number of elements transferred.
- *
- * @throws NullPointerException If objects is null.
- * @throws IllegalArgumentException If objects is this queue.
- */
- public int drainTo(Collection<? super E> objects)
- {
- return drainTo(objects, -1);
- }
-
- /**
- * Removes at most the given number of available elements from this queue and adds them into the given collection.
- * A failure encountered while attempting to <tt>add</tt> elements to collection <tt>c</tt> may result in elements
- * being in neither, either or both collections when the associated exception is thrown. Attempts to drain a queue
- * to itself result in <tt>IllegalArgumentException</tt>. Further, the behavior of this operation is undefined if
- * the specified collection is modified while the operation is in progress.
- *
- * @param objects The collection to transfer elements into.
- * @param maxElements The maximum number of elements to transfer. If this is -1 then that is interpreted as meaning
- * all elements.
- *
- * @return The number of elements transferred.
- *
- * @throws NullPointerException If c is null.
- * @throws IllegalArgumentException If c is this queue.
- */
- public int drainTo(Collection<? super E> objects, int maxElements)
- {
- if (objects == null)
- {
- throw new NullPointerException();
- }
-
- if (objects == this)
- {
- throw new IllegalArgumentException();
- }
-
- // final Queue<E> items = this.buffer;
- final ReentrantLock lock = this.lock;
- lock.lock();
-
- try
- {
- int n = 0;
-
- for (int max = ((maxElements >= count) || (maxElements < 0)) ? count : maxElements; n < max; n++)
- {
- // Take items from the queue, do unblock the producers, but don't send not full signals yet.
- objects.add(extract(true, false).getElement());
- }
-
- if (n > 0)
- {
- // count -= n;
- notFull.signalAll();
- }
-
- return n;
- }
- finally
- {
- lock.unlock();
- }
- }
-
- /**
- * Takes all available data items from the queue or blocks until some become available. The returned items
- * are wrapped in a {@link SynchRecord} which provides an interface to requeue them or send errors to their
- * producers, where the producers are still blocked.
- *
- * @param c The collection to drain the data items into.
- * @param unblock If set to <tt>true</tt> the producers for the taken items will be immediately unblocked.
- *
- * @return A count of the number of elements that were drained from the queue.
- */
- public SynchRef drainTo(Collection<SynchRecord<E>> c, boolean unblock)
- {
- return drainTo(c, -1, unblock);
- }
-
- /**
- * Takes up to maxElements available data items from the queue or blocks until some become available. The returned
- * items are wrapped in a {@link SynchRecord} which provides an interface to requeue them or send errors to their
- * producers, where the producers are still blocked.
- *
- * @param coll The collection to drain the data items into.
- * @param maxElements The maximum number of elements to drain.
- * @param unblock If set to <tt>true</tt> the producers for the taken items will be immediately unblocked.
- *
- * @return A count of the number of elements that were drained from the queue.
- */
- public SynchRef drainTo(Collection<SynchRecord<E>> coll, int maxElements, boolean unblock)
- {
- if (coll == null)
- {
- throw new NullPointerException();
- }
-
- // final Queue<E> items = this.buffer;
- final ReentrantLock lock = this.lock;
- lock.lock();
-
- try
- {
- int n = 0;
-
- for (int max = ((maxElements >= count) || (maxElements < 0)) ? count : maxElements; n < max; n++)
- {
- // Extract the next record from the queue, don't signall the not full condition yet and release
- // producers depending on whether the caller wants to or not.
- coll.add(extract(false, unblock));
- }
-
- if (n > 0)
- {
- // count -= n;
- notFull.signalAll();
- }
-
- return new SynchRefImpl(n, coll);
- }
- finally
- {
- lock.unlock();
- }
- }
-
- /**
- * This abstract method should be overriden to return an empty queue. Different implementations of producer
- * consumer buffers can control the order in which data is accessed using different queue implementations.
- * This method allows the type of queue to be abstracted out of this class and to be supplied by concrete
- * implementations.
- *
- * @return An empty queue.
- */
- protected abstract <T> Queue<T> createQueue();
-
- /**
- * Insert element into the queue, then possibly signal that the queue is not empty and block the producer
- * on the element until permission to procede is given.
- *
- * <p/>If the producer is to be blocked then the lock must be released first, otherwise no other process
- * will be able to get access to the queue. Hence, unlock and block are always set together.
- *
- * <p/>Call only when holding the global lock.
- *
- * @param unlockAndBlock <tt>true</tt>If the global queue lock should be released and the producer should be blocked.
- *
- * @return <tt>true</tt> if the operation succeeded, <tt>false</tt> otherwise. If the result is <tt>true</tt> this
- * method may not return straight away, but only after the producer is unblocked by having its data
- * consumed if the unlockAndBlock flag is set. In the false case the method will return straight away, no
- * matter what value the unlockAndBlock flag has, leaving the global lock on.
- */
- protected boolean insert(E x, boolean unlockAndBlock)
- {
- // Create a new record for the data item.
- SynchRecordImpl<E> record = new SynchRecordImpl<E>(x);
-
- boolean result = buffer.offer(record);
-
- if (result)
- {
- count++;
-
- // Tell any waiting consumers that the queue is not empty.
- notEmpty.signal();
-
- if (unlockAndBlock)
- {
- // Allow other threads to read/write the queue.
- lock.unlock();
-
- // Wait until a consumer takes this data item.
- record.waitForConsumer();
- }
-
- return true;
- }
- else
- {
- return false;
- }
- }
-
- /**
- * Extract element at current take position, advance, and signal.
- *
- * <p/>Call only when holding lock.
- */
- protected SynchRecordImpl<E> extract(boolean unblock, boolean signal)
- {
- SynchRecordImpl<E> result = buffer.remove();
- count--;
-
- if (signal)
- {
- notFull.signal();
- }
-
- if (unblock)
- {
- result.releaseImmediately();
- }
-
- return result;
- }
-
- /**
- * Get the capacity of the buffer. If the buffer has no maximum capacity then Integer.MAX_VALUE is returned.
- *
- * <p/>Call only when holding lock.
- *
- * @return The maximum capacity of the buffer.
- */
- protected int getBufferCapacity()
- {
- if (buffer instanceof Capacity)
- {
- return ((Capacity) buffer).getCapacity();
- }
- else
- {
- return Integer.MAX_VALUE;
- }
- }
-
- /**
- * Return the head element from the buffer.
- *
- * <p/>Call only when holding lock.
- *
- * @return The head element from the buffer.
- */
- protected E peekAtBufferHead()
- {
- return buffer.peek().getElement();
- }
-
- public class SynchRefImpl implements SynchRef
- {
- /** Holds the number of synch records associated with this reference. */
- int numRecords;
-
- /** Holds a reference to the collection of synch records managed by this. */
- Collection<SynchRecord<E>> records;
-
- public SynchRefImpl(int n, Collection<SynchRecord<E>> records)
- {
- this.numRecords = n;
- this.records = records;
- }
-
- public int getNumRecords()
- {
- return numRecords;
- }
-
- /**
- * Any producers that have had their data elements taken from the queue but have not been unblocked are unblocked
- * when this method is called. The exception to this is producers that have had their data put back onto the queue
- * by a consumer. Producers that have had exceptions for their data items registered by consumers will be unblocked
- * but will not return from their put call normally, but with an exception instead.
- */
- public void unblockProducers()
- {
- log.debug("public void unblockProducers(): called");
-
- if (records != null)
- {
- for (SynchRecord<E> record : records)
- {
- // This call takes account of items that have already been released, are to be requeued or are in
- // error.
- record.releaseImmediately();
- }
- }
-
- records = null;
- }
- }
-
- /**
- * A SynchRecordImpl is used by a {@link BatchSynchQueue} to pair together a producer with its data. This allows
- * the producer of data to be identified so that it can be unblocked when its data is consumed or sent errors when
- * its data cannot be consumed.
- */
- public class SynchRecordImpl<E> implements SynchRecord<E>
- {
- /** A boolean latch that determines when the producer for this data item will be allowed to continue. */
- BooleanLatch latch = new BooleanLatch();
-
- /** The data element associated with this item. */
- E element;
-
- /**
- * Create a new synch record.
- *
- * @param e The data element that the record encapsulates.
- */
- public SynchRecordImpl(E e)
- {
- // Keep the data element.
- element = e;
- }
-
- /**
- * Waits until the producer is given permission to proceded by a consumer.
- */
- public void waitForConsumer()
- {
- latch.await();
- }
-
- /**
- * Gets the data element contained by this record.
- *
- * @return The data element contained by this record.
- */
- public E getElement()
- {
- return element;
- }
-
- /**
- * Immediately releases the producer of this data record. Consumers can bring the synchronization time of
- * producers to a minimum by using this method to release them at the earliest possible moment when batch
- * consuming records from sychronized producers.
- */
- public void releaseImmediately()
- {
- // Check that the record has not already been released, is in error or is to be requeued.
- latch.signal();
-
- // Propagate errors to the producer.
-
- // Requeue items to be requeued.
- }
-
- /**
- * Tells the synch queue to put this element back onto the queue instead of releasing its producer.
- * The element is not requeued immediately but upon calling the {@link SynchRef#unblockProducers()} method or
- * the {@link #releaseImmediately()} method.
- *
- * <p/>This method will raise a runtime exception {@link AlreadyUnblockedException} if the producer for this
- * element has already been unblocked.
- */
- public void reQueue()
- {
- throw new RuntimeException("Not implemented.");
- }
-
- /**
- * Tells the synch queue to raise an exception with this elements producer. The exception is not raised
- * immediately but upon calling the {@link SynchRef#unblockProducers()} method or the
- * {@link #releaseImmediately()} method. The exception will be wrapped in a {@link SynchException} before it is
- * raised on the producer.
- *
- * <p/>This method is unusual in that it accepts an exception as an argument. This is non-standard but is used
- * because the exception is to be passed onto a different thread.
- *
- * <p/>This method will raise a runtime exception {@link AlreadyUnblockedException} if the producer for this
- * element has already been unblocked.
- *
- * @param e The exception to raise on the producer.
- */
- public void inError(Exception e)
- {
- throw new RuntimeException("Not implemented.");
- }
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/util/concurrent/BooleanLatch.java b/java/common/src/main/java/org/apache/qpid/util/concurrent/BooleanLatch.java
deleted file mode 100644
index 0e4a07594f..0000000000
--- a/java/common/src/main/java/org/apache/qpid/util/concurrent/BooleanLatch.java
+++ /dev/null
@@ -1,128 +0,0 @@
-package org.apache.qpid.util.concurrent;
-/*
- *
- * 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 java.util.concurrent.locks.AbstractQueuedSynchronizer;
-
-/**
- * A BooleanLatch is like a set of traffic lights, where threads can wait at a red light until another thread gives
- * the green light. When threads arrive at the latch it is initially red. They queue up until the green signal is
- * given, at which point they can all acquire the latch in shared mode and continue to run concurrently. Once the latch
- * is signalled it cannot be reset to red again.
- *
- * <p/> The latch uses a {@link java.util.concurrent.locks.AbstractQueuedSynchronizer} to implement its synchronization.
- * This has two internal states, 0 which means that the latch is blocked, and 1 which means that the latch is open.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Block threads until a go signal is given.
- * </table>
- *
- * @todo Might be better to use a countdown latch to count down from 1. Its await method can throw interrupted
- * exception which makes the possibility of interruption more explicit, and provides a reminder to recheck the
- * latch condition before continuing.
- */
-public class BooleanLatch
-{
- /** Holds the synchronizer that provides the thread queueing synchronization. */
- private final Sync sync = new Sync();
-
- /**
- * Tests whether or not the latch has been signalled, that is to say that, the light is green.
- *
- * <p/>This method is non-blocking.
- *
- * @return <tt>true</tt> if the latch may be acquired; the light is green.
- */
- public boolean isSignalled()
- {
- return sync.isSignalled();
- }
-
- /**
- * Waits on the latch until the signal is given and the light is green. If the light is already green then the
- * latch will be acquired and the thread will not have to wait.
- *
- * <p/>This method will block until the go signal is given or the thread is otherwise interrupted. Before carrying
- * out any processing threads that return from this method should confirm that the go signal has really been given
- * on this latch by calling the {@link #isSignalled()} method.
- */
- public void await()
- {
- sync.acquireShared(1);
- }
-
- /**
- * Releases any threads currently waiting on the latch. This flips the light to green allowing any threads that
- * were waiting for this condition to now run.
- *
- * <p/>This method is non-blocking.
- */
- public void signal()
- {
- sync.releaseShared(1);
- }
-
- /**
- * Implements a thread queued synchronizer. The internal state 0 means that the queue is blocked and the internl
- * state 1 means that the queue is released and that all waiting threads can acquire the synchronizer in shared
- * mode.
- */
- private static class Sync extends AbstractQueuedSynchronizer
- {
- /**
- * Attempts to acquire this synchronizer in shared mode. It may be acquired once it has been released.
- *
- * @param ignore This parameter is ignored.
- *
- * @return 1 if the shared acquisition succeeds and -1 if it fails.
- */
- protected int tryAcquireShared(int ignore)
- {
- return isSignalled() ? 1 : -1;
- }
-
- /**
- * Releases the synchronizer, setting its internal state to 1.
- *
- * @param ignore This parameter is ignored.
- *
- * @return <tt>true</tt> always.
- */
- protected boolean tryReleaseShared(int ignore)
- {
- setState(1);
-
- return true;
- }
-
- /**
- * Tests if the synchronizer is signalled. It is signalled when its internal state it 1.
- *
- * @return <tt>true</tt> if the internal state is 1, <tt>false</tt> otherwise.
- */
- boolean isSignalled()
- {
- return getState() != 0;
- }
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/util/concurrent/Capacity.java b/java/common/src/main/java/org/apache/qpid/util/concurrent/Capacity.java
deleted file mode 100644
index a97ce0e172..0000000000
--- a/java/common/src/main/java/org/apache/qpid/util/concurrent/Capacity.java
+++ /dev/null
@@ -1,35 +0,0 @@
-package org.apache.qpid.util.concurrent;
-/*
- *
- * 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.
- *
- */
-
-
-/**
- * An interface exposed by data structures that have a maximum capacity.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Report the maximum capacity.
- * </table>
- */
-public interface Capacity
-{
- public int getCapacity();
-}
diff --git a/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchBuffer.java b/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchBuffer.java
deleted file mode 100644
index bc63eb0353..0000000000
--- a/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchBuffer.java
+++ /dev/null
@@ -1,50 +0,0 @@
-package org.apache.qpid.util.concurrent;
-/*
- *
- * 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 java.util.Queue;
-
-/**
- * SynchBuffer completes the {@link BatchSynchQueueBase} abstract class by providing an implementation of the underlying
- * queue as an array. This uses FIFO ordering for the queue but restricts the maximum size of the queue to a fixed
- * amount. It also has the advantage that, as the buffer does not grow and shrink dynamically, memory for the buffer
- * is allocated up front and does not create garbage during the operation of the queue.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Provide array based FIFO queue to create a batch synched queue around.
- * </table>
- *
- * @todo Write an array based buffer implementation that implements Queue.
- */
-public class SynchBuffer<E> extends BatchSynchQueueBase<E>
-{
- /**
- * Returns an empty queue, implemented as an array.
- *
- * @return An empty queue, implemented as an array.
- */
- protected <T> Queue<T> createQueue()
- {
- throw new RuntimeException("Not implemented.");
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchException.java b/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchException.java
deleted file mode 100644
index 99a83f96cd..0000000000
--- a/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchException.java
+++ /dev/null
@@ -1,52 +0,0 @@
-package org.apache.qpid.util.concurrent;
-/*
- *
- * 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.
- *
- */
-
-
-/**
- * SynchException is used to encapsulate exceptions with the data elements that caused them in order to send exceptions
- * back from the consumers of a {@link BatchSynchQueue} to producers. The underlying exception should be retrieved from
- * the {@link #getCause} method.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Encapsulate a data element and exception.
- * </table>
- */
-public class SynchException extends Exception
-{
- /** Holds the data element that is in error. */
- Object element;
-
- /**
- * Creates a new BaseApplicationException object.
- *
- * @param message The exception message.
- * @param cause The underlying throwable cause. This may be null.
- */
- public SynchException(String message, Throwable cause, Object element)
- {
- super(message, cause);
-
- // Keep the data element that was in error.
- this.element = element;
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchQueue.java b/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchQueue.java
deleted file mode 100644
index 95833f398a..0000000000
--- a/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchQueue.java
+++ /dev/null
@@ -1,48 +0,0 @@
-package org.apache.qpid.util.concurrent;
-/*
- *
- * 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 java.util.LinkedList;
-import java.util.Queue;
-
-/**
- * SynchQueue completes the {@link BatchSynchQueueBase} abstract class by providing an implementation of the underlying
- * queue as a linked list. This uses FIFO ordering for the queue and allows the queue to grow to accomodate more
- * elements as needed.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Provide linked list FIFO queue to create a batch synched queue around.
- * </table>
- */
-public class SynchQueue<E> extends BatchSynchQueueBase<E>
-{
- /**
- * Returns an empty queue, implemented as a linked list.
- *
- * @return An empty queue, implemented as a linked list.
- */
- protected <T> Queue<T> createQueue()
- {
- return new LinkedList<T>();
- }
-}
diff --git a/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchRecord.java b/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchRecord.java
deleted file mode 100644
index fd740c20cd..0000000000
--- a/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchRecord.java
+++ /dev/null
@@ -1,74 +0,0 @@
-package org.apache.qpid.util.concurrent;
-/*
- *
- * 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.
- *
- */
-
-
-/**
- * SynchRecord associates a data item from a {@link BatchSynchQueue} with its producer. This enables the data item data
- * item to be put back on the queue without unblocking its producer, or to send exceptions to the producer.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Get the underlying data element.
- * <tr><td> Put the data element back on the queue without unblocking its producer.
- * <tr><td> Send and exception to the data elements producer.
- * </table>
- */
-public interface SynchRecord<E>
-{
- /**
- * Gets the data element contained by this record.
- *
- * @return The data element contained by this record.
- */
- public E getElement();
-
- /**
- * Tells the synch queue to put this element back onto the queue instead of releasing its producer.
- * The element is not requeued immediately but upon calling the {@link SynchRef#unblockProducers()} method.
- *
- * <p/>This method will raise a runtime exception {@link AlreadyUnblockedException} if the producer for this element
- * has already been unblocked.
- */
- public void reQueue();
-
- /**
- * Immediately releases the producer of this data record. Consumers can bring the synchronization time of
- * producers to a minimum by using this method to release them at the earliest possible moment when batch
- * consuming records from sychronized producers.
- */
- public void releaseImmediately();
-
- /**
- * Tells the synch queue to raise an exception with this elements producer. The exception is not raised immediately
- * but upon calling the {@link SynchRef#unblockProducers()} method. The exception will be wrapped in a
- * {@link SynchException} before it is raised on the producer.
- *
- * <p/>This method is unusual in that it accepts an exception as an argument. This is non-standard but is used
- * because the exception is to be passed onto a different thread.
- *
- * <p/>This method will raise a runtime exception {@link AlreadyUnblockedException} if the producer for this element
- * has already been unblocked.
- *
- * @param e The exception to raise on the producer.
- */
- public void inError(Exception e);
-}
diff --git a/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchRef.java b/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchRef.java
deleted file mode 100644
index efe2344c06..0000000000
--- a/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchRef.java
+++ /dev/null
@@ -1,51 +0,0 @@
-package org.apache.qpid.util.concurrent;
-/*
- *
- * 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.
- *
- */
-
-
-/**
- * A SynchRef is an interface which is returned from the synchronous take and drain methods of {@link BatchSynchQueue},
- * allowing call-backs to be made against the synchronizing strucutre. It allows the consumer to communicate when it
- * wants producers that have their data taken to be unblocked.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities
- * <tr><td> Report number of records returned by a taking operation.
- * <tr><td> Provide call-back to release producers of taken records.
- * </table>
- */
-public interface SynchRef
-{
- /**
- * Reports the number of records taken by the take or drain operation.
- *
- * @return The number of records taken by the take or drain operation.
- */
- public int getNumRecords();
-
- /**
- * Any producers that have had their data elements taken from the queue but have not been unblocked are
- * unblocked when this method is called. The exception to this is producers that have had their data put back
- * onto the queue by a consumer. Producers that have had exceptions for their data items registered by consumers
- * will be unblocked but will not return from their put call normally, but with an exception instead.
- */
- public void unblockProducers();
-}
diff --git a/java/common/src/test/java/org/apache/mina/SocketIOTest/IOWriterClient.java b/java/common/src/test/java/org/apache/mina/SocketIOTest/IOWriterClient.java
deleted file mode 100644
index b93dc46741..0000000000
--- a/java/common/src/test/java/org/apache/mina/SocketIOTest/IOWriterClient.java
+++ /dev/null
@@ -1,396 +0,0 @@
-/*
- *
- * Copyright (c) 2006 The Apache Software Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-package org.apache.mina.SocketIOTest;
-
-import org.apache.mina.common.ByteBuffer;
-import org.apache.mina.common.CloseFuture;
-import org.apache.mina.common.ConnectFuture;
-import org.apache.mina.common.IoConnector;
-import org.apache.mina.common.IoFilterChain;
-import org.apache.mina.common.IoHandlerAdapter;
-import org.apache.mina.common.IoSession;
-import org.apache.mina.common.SimpleByteBufferAllocator;
-import org.apache.mina.filter.ReadThrottleFilterBuilder;
-import org.apache.mina.filter.WriteBufferLimitFilterBuilder;
-import org.apache.mina.transport.socket.nio.SocketSessionConfig;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.io.IOException;
-import java.net.InetSocketAddress;
-import java.util.concurrent.CountDownLatch;
-
-public class IOWriterClient implements Runnable
-{
- private static final Logger _logger = LoggerFactory.getLogger(IOWriterClient.class);
-
- public static int DEFAULT_TEST_SIZE = 2;
-
- private IoSession _session;
-
- private long _startTime;
-
- private long[] _chunkTimes;
-
- public int _chunkCount = 200000;
-
- private int _chunkSize = 1024;
-
- private CountDownLatch _notifier;
-
- private int _maximumWriteQueueLength;
-
- static public int _PORT = IOWriterServer._PORT;
-
- public void run()
- {
- _logger.info("Starting to send " + _chunkCount + " buffers of " + _chunkSize + "B");
- _startTime = System.currentTimeMillis();
- _notifier = new CountDownLatch(1);
-
- for (int i = 0; i < _chunkCount; i++)
- {
- ByteBuffer buf = ByteBuffer.allocate(_chunkSize, false);
- byte check = (byte) (i % 128);
- buf.put(check);
- buf.fill((byte) 88, buf.remaining());
- buf.flip();
-
- _session.write(buf);
- }
-
- long _sentall = System.currentTimeMillis();
- long _receivedall = _sentall;
- try
- {
- _logger.info("All buffers sent; waiting for receipt from server");
- _notifier.await();
- _receivedall = System.currentTimeMillis();
- }
- catch (InterruptedException e)
- {
- //Ignore
- }
- _logger.info("Completed");
- _logger.info("Total time waiting for server after last write: " + (_receivedall - _sentall));
-
- long totalTime = System.currentTimeMillis() - _startTime;
-
- _logger.info("Total time: " + totalTime);
- _logger.info("MB per second: " + (int) ((1.0 * _chunkSize * _chunkCount) / totalTime));
- long lastChunkTime = _startTime;
- double average = 0;
- for (int i = 0; i < _chunkTimes.length; i++)
- {
- if (i == 0)
- {
- average = _chunkTimes[i] - _startTime;
- }
- else
- {
- long delta = _chunkTimes[i] - lastChunkTime;
- if (delta != 0)
- {
- average = (average + delta) / 2;
- }
- }
- lastChunkTime = _chunkTimes[i];
- }
- _logger.info("Average chunk time: " + average + "ms");
- _logger.info("Maximum WriteRequestQueue size: " + _maximumWriteQueueLength);
-
- CloseFuture cf = _session.close();
- _logger.info("Closing session");
- cf.join();
- }
-
- private class WriterHandler extends IoHandlerAdapter
- {
- private int _chunksReceived = 0;
-
- private int _partialBytesRead = 0;
-
- private byte _partialCheckNumber;
-
- private int _totalBytesReceived = 0;
-
- private int _receivedCount = 0;
- private int _sentCount = 0;
- private static final String DEFAULT_READ_BUFFER = "262144";
- private static final String DEFAULT_WRITE_BUFFER = "262144";
-
- public void sessionCreated(IoSession session) throws Exception
- {
- IoFilterChain chain = session.getFilterChain();
-
- ReadThrottleFilterBuilder readfilter = new ReadThrottleFilterBuilder();
- readfilter.setMaximumConnectionBufferSize(Integer.parseInt(System.getProperty("qpid.read.buffer.limit", DEFAULT_READ_BUFFER)));
- readfilter.attach(chain);
-
- WriteBufferLimitFilterBuilder writefilter = new WriteBufferLimitFilterBuilder();
-
- writefilter.setMaximumConnectionBufferSize(Integer.parseInt(System.getProperty("qpid.write.buffer.limit", DEFAULT_WRITE_BUFFER)));
-
- writefilter.attach(chain);
- }
-
- public void messageSent(IoSession session, Object message) throws Exception
- {
- _maximumWriteQueueLength = Math.max(session.getScheduledWriteRequests(), _maximumWriteQueueLength);
-
- if (_logger.isDebugEnabled())
- {
- ++_sentCount;
- if (_sentCount % 1000 == 0)
- {
- _logger.debug("Sent count " + _sentCount + ":WQueue" + session.getScheduledWriteRequests());
-
- }
- }
- }
-
- public void messageReceived(IoSession session, Object message) throws Exception
- {
- if (_logger.isDebugEnabled())
- {
- ++_receivedCount;
-
- if (_receivedCount % 1000 == 0)
- {
- _logger.debug("Receieved count " + _receivedCount);
- }
- }
-
- ByteBuffer result = (ByteBuffer) message;
- _totalBytesReceived += result.remaining();
- int size = result.remaining();
- long now = System.currentTimeMillis();
- if (_partialBytesRead > 0)
- {
- int offset = _chunkSize - _partialBytesRead;
- if (size >= offset)
- {
- _chunkTimes[_chunksReceived++] = now;
- result.position(offset);
- }
- else
- {
- // have not read even one chunk, including the previous partial bytes
- _partialBytesRead += size;
- return;
- }
- }
-
-
- int chunkCount = result.remaining() / _chunkSize;
-
- for (int i = 0; i < chunkCount; i++)
- {
- _chunkTimes[_chunksReceived++] = now;
- byte check = result.get();
- _logger.debug("Check number " + check + " read");
- if (check != (byte) ((_chunksReceived - 1) % 128))
- {
- _logger.error("Check number " + check + " read when expected " + (_chunksReceived % 128));
- }
- _logger.debug("Chunk times recorded");
-
- try
- {
- result.skip(_chunkSize - 1);
- }
- catch (IllegalArgumentException e)
- {
- _logger.error("Position was: " + result.position());
- _logger.error("Tried to skip to: " + (_chunkSize * i));
- _logger.error("limit was; " + result.limit());
- }
- }
- _logger.debug("Chunks received now " + _chunksReceived);
- _logger.debug("Bytes received: " + _totalBytesReceived);
- _partialBytesRead = result.remaining();
-
- if (_partialBytesRead > 0)
- {
- _partialCheckNumber = result.get();
- }
-
-
- if (_chunksReceived >= _chunkCount)
- {
- _notifier.countDown();
- }
-
- }
-
- public void exceptionCaught(IoSession session, Throwable cause) throws Exception
- {
- _logger.error("Error: " + cause, cause);
- }
- }
-
- public void startWriter() throws IOException, InterruptedException
- {
-
- _maximumWriteQueueLength = 0;
-
- IoConnector ioConnector = null;
-
- if (Boolean.getBoolean("multinio"))
- {
- _logger.warn("Using MultiThread NIO");
- ioConnector = new org.apache.mina.transport.socket.nio.MultiThreadSocketConnector();
- }
- else
- {
- _logger.warn("Using MINA NIO");
- ioConnector = new org.apache.mina.transport.socket.nio.SocketConnector();
- }
-
- SocketSessionConfig scfg = (SocketSessionConfig) ioConnector.getDefaultConfig().getSessionConfig();
- scfg.setTcpNoDelay(true);
- scfg.setSendBufferSize(32768);
- scfg.setReceiveBufferSize(32768);
-
- ByteBuffer.setAllocator(new SimpleByteBufferAllocator());
-
-
- final InetSocketAddress address = new InetSocketAddress("localhost", _PORT);
- _logger.info("Attempting connection to " + address);
-
- //Old mina style
-// ioConnector.setHandler(new WriterHandler());
-// ConnectFuture future = ioConnector.connect(address);
- ConnectFuture future = ioConnector.connect(address, new WriterHandler());
- // wait for connection to complete
- future.join();
- _logger.info("Connection completed");
- // we call getSession which throws an IOException if there has been an error connecting
- _session = future.getSession();
-
- _chunkTimes = new long[_chunkCount];
- Thread t = new Thread(this);
- t.start();
- t.join();
- _logger.info("Test Complete");
- }
-
-
- public void test1k() throws IOException, InterruptedException
- {
- _logger.info("Starting 1k test");
- _chunkSize = 1024;
- startWriter();
- }
-
-
- public void test2k() throws IOException, InterruptedException
- {
- _logger.info("Starting 2k test");
- _chunkSize = 2048;
- startWriter();
- }
-
-
- public void test4k() throws IOException, InterruptedException
- {
- _logger.info("Starting 4k test");
- _chunkSize = 4096;
- startWriter();
- }
-
-
- public void test8k() throws IOException, InterruptedException
- {
- _logger.info("Starting 8k test");
- _chunkSize = 8192;
- startWriter();
- }
-
-
- public void test16k() throws IOException, InterruptedException
- {
- _logger.info("Starting 16k test");
- _chunkSize = 16384;
- startWriter();
- }
-
-
- public void test32k() throws IOException, InterruptedException
- {
- _logger.info("Starting 32k test");
- _chunkSize = 32768;
- startWriter();
- }
-
-
- public static int getIntArg(String[] args, int index, int defaultValue)
- {
- if (args.length > index)
- {
- try
- {
- return Integer.parseInt(args[index]);
- }
- catch (NumberFormatException e)
- {
- //Do nothing
- }
- }
- return defaultValue;
- }
-
- public static void main(String[] args) throws IOException, InterruptedException
- {
- _PORT = getIntArg(args, 0, _PORT);
-
- int test = getIntArg(args, 1, DEFAULT_TEST_SIZE);
-
- IOWriterClient w = new IOWriterClient();
- w._chunkCount = getIntArg(args, 2, w._chunkCount);
- switch (test)
- {
- case 0:
- w.test1k();
- w.test2k();
- w.test4k();
- w.test8k();
- w.test16k();
- w.test32k();
- break;
- case 1:
- w.test1k();
- break;
- case 2:
- w.test2k();
- break;
- case 4:
- w.test4k();
- break;
- case 8:
- w.test8k();
- break;
- case 16:
- w.test16k();
- break;
- case 32:
- w.test32k();
- break;
- }
- }
-}
diff --git a/java/common/src/test/java/org/apache/mina/SocketIOTest/IOWriterServer.java b/java/common/src/test/java/org/apache/mina/SocketIOTest/IOWriterServer.java
deleted file mode 100644
index 423e98c67b..0000000000
--- a/java/common/src/test/java/org/apache/mina/SocketIOTest/IOWriterServer.java
+++ /dev/null
@@ -1,157 +0,0 @@
-/*
- *
- * Copyright (c) 2006 The Apache Software Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-package org.apache.mina.SocketIOTest;
-
-import org.apache.mina.common.ByteBuffer;
-import org.apache.mina.common.IoAcceptor;
-import org.apache.mina.common.IoFilterChain;
-import org.apache.mina.common.IoHandlerAdapter;
-import org.apache.mina.common.IoSession;
-import org.apache.mina.common.SimpleByteBufferAllocator;
-import org.apache.mina.filter.ReadThrottleFilterBuilder;
-import org.apache.mina.filter.WriteBufferLimitFilterBuilder;
-import org.apache.mina.transport.socket.nio.SocketSessionConfig;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.io.IOException;
-import java.net.InetSocketAddress;
-
-/** Tests MINA socket performance. This acceptor simply reads data from the network and writes it back again. */
-public class IOWriterServer
-{
- private static final Logger _logger = LoggerFactory.getLogger(IOWriterServer.class);
-
- static public int _PORT = 9999;
-
- private static final String DEFAULT_READ_BUFFER = "262144";
- private static final String DEFAULT_WRITE_BUFFER = "262144";
-
-
- private static class TestHandler extends IoHandlerAdapter
- {
- private int _sentCount = 0;
-
- private int _bytesSent = 0;
-
- private int _receivedCount = 0;
-
- public void sessionCreated(IoSession ioSession) throws java.lang.Exception
- {
- IoFilterChain chain = ioSession.getFilterChain();
-
- ReadThrottleFilterBuilder readfilter = new ReadThrottleFilterBuilder();
- readfilter.setMaximumConnectionBufferSize(Integer.parseInt(System.getProperty("qpid.read.buffer.limit", DEFAULT_READ_BUFFER)));
- readfilter.attach(chain);
-
- WriteBufferLimitFilterBuilder writefilter = new WriteBufferLimitFilterBuilder();
-
- writefilter.setMaximumConnectionBufferSize(Integer.parseInt(System.getProperty("qpid.write.buffer.limit", DEFAULT_WRITE_BUFFER)));
-
- writefilter.attach(chain);
-
- }
-
- public void messageReceived(IoSession session, Object message) throws Exception
- {
- ((ByteBuffer) message).acquire();
- session.write(message);
-
- if (_logger.isDebugEnabled())
- {
- _bytesSent += ((ByteBuffer) message).remaining();
-
- _sentCount++;
-
- if (_sentCount % 1000 == 0)
- {
- _logger.debug("Bytes sent: " + _bytesSent);
- }
- }
- }
-
- public void messageSent(IoSession session, Object message) throws Exception
- {
- if (_logger.isDebugEnabled())
- {
- ++_receivedCount;
-
- if (_receivedCount % 1000 == 0)
- {
- _logger.debug("Receieved count " + _receivedCount);
- }
- }
- }
-
- public void exceptionCaught(IoSession session, Throwable cause) throws Exception
- {
- _logger.error("Error: " + cause, cause);
- }
- }
-
- public void startAcceptor() throws IOException
- {
- IoAcceptor acceptor;
- if (Boolean.getBoolean("multinio"))
- {
- _logger.warn("Using MultiThread NIO");
- acceptor = new org.apache.mina.transport.socket.nio.MultiThreadSocketAcceptor();
- }
- else
- {
- _logger.warn("Using MINA NIO");
- acceptor = new org.apache.mina.transport.socket.nio.SocketAcceptor();
- }
-
-
- SocketSessionConfig sc = (SocketSessionConfig) acceptor.getDefaultConfig().getSessionConfig();
- sc.setTcpNoDelay(true);
- sc.setSendBufferSize(32768);
- sc.setReceiveBufferSize(32768);
-
- ByteBuffer.setAllocator(new SimpleByteBufferAllocator());
-
- //The old mina style
-// acceptor.setLocalAddress(new InetSocketAddress(_PORT));
-// acceptor.setHandler(new TestHandler());
-// acceptor.bind();
- acceptor.bind(new InetSocketAddress(_PORT), new TestHandler());
-
- _logger.info("Bound on port " + _PORT + ":" + _logger.isDebugEnabled());
- _logger.debug("debug on");
- }
-
- public static void main(String[] args) throws IOException
- {
-
- if (args.length > 0)
- {
- try
- {
- _PORT = Integer.parseInt(args[0]);
- }
- catch (NumberFormatException e)
- {
- //IGNORE so use default port 9999;
- }
- }
-
- IOWriterServer a = new IOWriterServer();
- a.startAcceptor();
- }
-}
diff --git a/java/common/src/test/java/org/apache/qpid/AMQExceptionTest.java b/java/common/src/test/java/org/apache/qpid/AMQExceptionTest.java
deleted file mode 100644
index ef6cd41492..0000000000
--- a/java/common/src/test/java/org/apache/qpid/AMQExceptionTest.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;
-
-import junit.framework.TestCase;
-import org.apache.qpid.protocol.AMQConstant;
-import org.apache.qpid.framing.AMQFrameDecodingException;
-
-/**
- * This test is to ensure that when an AMQException is rethrown that the specified exception is correctly wrapped up.
- *
- * There are three cases:
- * Re-throwing an AMQException
- * Re-throwing a Subclass of AMQException
- * Re-throwing a Subclass of AMQException that does not have the default AMQException constructor which will force the
- * creation of an AMQException.
- */
-public class AMQExceptionTest extends TestCase
-{
- /**
- * Test that an AMQException will be correctly created and rethrown.
- */
- public void testRethrowGeneric()
- {
- AMQException test = new AMQException(AMQConstant.ACCESS_REFUSED, "refused", new RuntimeException());
-
- AMQException e = reThrowException(test);
-
- assertEquals("Exception not of correct class", AMQException.class, e.getClass());
-
- }
-
- /**
- * Test that a subclass of AMQException that has the default constructor will be correctly created and rethrown.
- */
- public void testRethrowAMQESubclass()
- {
- AMQFrameDecodingException test = new AMQFrameDecodingException(AMQConstant.INTERNAL_ERROR,
- "Error",
- new Exception());
- AMQException e = reThrowException(test);
-
- assertEquals("Exception not of correct class", AMQFrameDecodingException.class, e.getClass());
- }
-
- /**
- * Test that a subclass of AMQException that doesnot have the default constructor will be correctly rethrown as an
- * AMQException
- */
- public void testRethrowAMQESubclassNoConstructor()
- {
- AMQExceptionSubclass test = new AMQExceptionSubclass("Invalid Argument Exception");
-
- AMQException e = reThrowException(test);
-
- assertEquals("Exception not of correct class", AMQException.class, e.getClass());
- }
-
- /**
- * Private method to rethrown and validate the basic values of the rethrown
- * @param test Exception to rethrow
- * @throws AMQException the rethrown exception
- */
- private AMQException reThrowException(AMQException test)
- {
- AMQException amqe = test.cloneForCurrentThread();
-
- assertEquals("Error code does not match.", test.getErrorCode(), amqe.getErrorCode());
- assertTrue("Exception message does not start as expected.", amqe.getMessage().startsWith(test.getMessage()));
- assertEquals("Test Exception is not set as the cause", test, amqe.getCause());
- assertEquals("Cause is not correct", test.getCause(), amqe.getCause().getCause());
-
- return amqe;
- }
-
- /**
- * Private class that extends AMQException but does not have a default exception.
- */
- private class AMQExceptionSubclass extends AMQException
- {
-
- public AMQExceptionSubclass(String msg)
- {
- super(null, msg, null);
- }
- }
-}
-
diff --git a/java/common/src/test/java/org/apache/qpid/codec/AMQDecoderTest.java b/java/common/src/test/java/org/apache/qpid/codec/AMQDecoderTest.java
deleted file mode 100644
index 62e25e7d79..0000000000
--- a/java/common/src/test/java/org/apache/qpid/codec/AMQDecoderTest.java
+++ /dev/null
@@ -1,151 +0,0 @@
-package org.apache.qpid.codec;
-/*
- *
- * 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 java.nio.ByteBuffer;
-import java.util.ArrayList;
-
-import junit.framework.TestCase;
-
-import org.apache.qpid.framing.AMQDataBlock;
-import org.apache.qpid.framing.AMQFrame;
-import org.apache.qpid.framing.AMQFrameDecodingException;
-import org.apache.qpid.framing.AMQProtocolVersionException;
-import org.apache.qpid.framing.HeartbeatBody;
-
-public class AMQDecoderTest extends TestCase
-{
-
- private AMQCodecFactory _factory;
- private AMQDecoder _decoder;
-
-
- public void setUp()
- {
- _factory = new AMQCodecFactory(false, null);
- _decoder = _factory.getDecoder();
- }
-
-
- public void testSingleFrameDecode() throws AMQProtocolVersionException, AMQFrameDecodingException
- {
- ByteBuffer msg = HeartbeatBody.FRAME.toNioByteBuffer();
- ArrayList<AMQDataBlock> frames = _decoder.decodeBuffer(msg);
- if (frames.get(0) instanceof AMQFrame)
- {
- assertEquals(HeartbeatBody.FRAME.getBodyFrame().getFrameType(), ((AMQFrame) frames.get(0)).getBodyFrame().getFrameType());
- }
- else
- {
- fail("decode was not a frame");
- }
- }
-
- public void testPartialFrameDecode() throws AMQProtocolVersionException, AMQFrameDecodingException
- {
- ByteBuffer msg = HeartbeatBody.FRAME.toNioByteBuffer();
- ByteBuffer msgA = msg.slice();
- int msgbPos = msg.remaining() / 2;
- int msgaLimit = msg.remaining() - msgbPos;
- msgA.limit(msgaLimit);
- msg.position(msgbPos);
- ByteBuffer msgB = msg.slice();
- ArrayList<AMQDataBlock> frames = _decoder.decodeBuffer(msgA);
- assertEquals(0, frames.size());
- frames = _decoder.decodeBuffer(msgB);
- assertEquals(1, frames.size());
- if (frames.get(0) instanceof AMQFrame)
- {
- assertEquals(HeartbeatBody.FRAME.getBodyFrame().getFrameType(), ((AMQFrame) frames.get(0)).getBodyFrame().getFrameType());
- }
- else
- {
- fail("decode was not a frame");
- }
- }
-
- public void testMultipleFrameDecode() throws AMQProtocolVersionException, AMQFrameDecodingException
- {
- ByteBuffer msgA = HeartbeatBody.FRAME.toNioByteBuffer();
- ByteBuffer msgB = HeartbeatBody.FRAME.toNioByteBuffer();
- ByteBuffer msg = ByteBuffer.allocate(msgA.remaining() + msgB.remaining());
- msg.put(msgA);
- msg.put(msgB);
- msg.flip();
- ArrayList<AMQDataBlock> frames = _decoder.decodeBuffer(msg);
- assertEquals(2, frames.size());
- for (AMQDataBlock frame : frames)
- {
- if (frame instanceof AMQFrame)
- {
- assertEquals(HeartbeatBody.FRAME.getBodyFrame().getFrameType(), ((AMQFrame) frame).getBodyFrame().getFrameType());
- }
- else
- {
- fail("decode was not a frame");
- }
- }
- }
-
- public void testMultiplePartialFrameDecode() throws AMQProtocolVersionException, AMQFrameDecodingException
- {
- ByteBuffer msgA = HeartbeatBody.FRAME.toNioByteBuffer();
- ByteBuffer msgB = HeartbeatBody.FRAME.toNioByteBuffer();
- ByteBuffer msgC = HeartbeatBody.FRAME.toNioByteBuffer();
-
- ByteBuffer sliceA = ByteBuffer.allocate(msgA.remaining() + msgB.remaining() / 2);
- sliceA.put(msgA);
- int limit = msgB.limit();
- int pos = msgB.remaining() / 2;
- msgB.limit(pos);
- sliceA.put(msgB);
- sliceA.flip();
- msgB.limit(limit);
- msgB.position(pos);
-
- ByteBuffer sliceB = ByteBuffer.allocate(msgB.remaining() + pos);
- sliceB.put(msgB);
- msgC.limit(pos);
- sliceB.put(msgC);
- sliceB.flip();
- msgC.limit(limit);
-
- ArrayList<AMQDataBlock> frames = _decoder.decodeBuffer(sliceA);
- assertEquals(1, frames.size());
- frames = _decoder.decodeBuffer(sliceB);
- assertEquals(1, frames.size());
- frames = _decoder.decodeBuffer(msgC);
- assertEquals(1, frames.size());
- for (AMQDataBlock frame : frames)
- {
- if (frame instanceof AMQFrame)
- {
- assertEquals(HeartbeatBody.FRAME.getBodyFrame().getFrameType(), ((AMQFrame) frame).getBodyFrame().getFrameType());
- }
- else
- {
- fail("decode was not a frame");
- }
- }
- }
-
-}
diff --git a/java/common/src/test/java/org/apache/qpid/codec/MockAMQVersionAwareProtocolSession.java b/java/common/src/test/java/org/apache/qpid/codec/MockAMQVersionAwareProtocolSession.java
deleted file mode 100644
index 401848c21d..0000000000
--- a/java/common/src/test/java/org/apache/qpid/codec/MockAMQVersionAwareProtocolSession.java
+++ /dev/null
@@ -1,105 +0,0 @@
-package org.apache.qpid.codec;
-/*
- *
- * 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 java.nio.ByteBuffer;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.AMQDataBlock;
-import org.apache.qpid.framing.AMQMethodBody;
-import org.apache.qpid.framing.ContentBody;
-import org.apache.qpid.framing.ContentHeaderBody;
-import org.apache.qpid.framing.HeartbeatBody;
-import org.apache.qpid.framing.MethodRegistry;
-import org.apache.qpid.framing.ProtocolVersion;
-import org.apache.qpid.protocol.AMQVersionAwareProtocolSession;
-import org.apache.qpid.transport.Sender;
-
-public class MockAMQVersionAwareProtocolSession implements AMQVersionAwareProtocolSession
-{
-
- public void contentBodyReceived(int channelId, ContentBody body) throws AMQException
- {
- // TODO Auto-generated method stub
-
- }
-
- public void contentHeaderReceived(int channelId, ContentHeaderBody body) throws AMQException
- {
- // TODO Auto-generated method stub
-
- }
-
- public MethodRegistry getMethodRegistry()
- {
- return MethodRegistry.getMethodRegistry(ProtocolVersion.v0_9);
- }
-
- public void heartbeatBodyReceived(int channelId, HeartbeatBody body) throws AMQException
- {
- // TODO Auto-generated method stub
-
- }
-
- public void init()
- {
- // TODO Auto-generated method stub
-
- }
-
- public void methodFrameReceived(int channelId, AMQMethodBody body) throws AMQException
- {
- // TODO Auto-generated method stub
-
- }
-
- public void setSender(Sender<ByteBuffer> sender)
- {
- // TODO Auto-generated method stub
-
- }
-
- public void writeFrame(AMQDataBlock frame)
- {
- // TODO Auto-generated method stub
-
- }
-
- public byte getProtocolMajorVersion()
- {
- // TODO Auto-generated method stub
- return 0;
- }
-
- public byte getProtocolMinorVersion()
- {
- // TODO Auto-generated method stub
- return 0;
- }
-
- public ProtocolVersion getProtocolVersion()
- {
- // TODO Auto-generated method stub
- return null;
- }
-
-}
diff --git a/java/common/src/test/java/org/apache/qpid/framing/AMQShortStringTest.java b/java/common/src/test/java/org/apache/qpid/framing/AMQShortStringTest.java
deleted file mode 100644
index 92e7ce0a80..0000000000
--- a/java/common/src/test/java/org/apache/qpid/framing/AMQShortStringTest.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.qpid.framing;
-
-import junit.framework.TestCase;
-public class AMQShortStringTest extends TestCase
-{
-
- public static final AMQShortString HELLO = new AMQShortString("Hello");
- public static final AMQShortString HELL = new AMQShortString("Hell");
- public static final AMQShortString GOODBYE = new AMQShortString("Goodbye");
- public static final AMQShortString GOOD = new AMQShortString("Good");
- public static final AMQShortString BYE = new AMQShortString("BYE");
-
- public void testStartsWith()
- {
- assertTrue(HELLO.startsWith(HELL));
-
- assertFalse(HELL.startsWith(HELLO));
-
- assertTrue(GOODBYE.startsWith(GOOD));
-
- assertFalse(GOOD.startsWith(GOODBYE));
- }
-
- public void testEndWith()
- {
- assertFalse(HELL.endsWith(HELLO));
-
- assertTrue(GOODBYE.endsWith(new AMQShortString("bye")));
-
- assertFalse(GOODBYE.endsWith(BYE));
- }
-
-
- public void testTokenize()
- {
- AMQShortString dotSeparatedWords = new AMQShortString("this.is.a.test.with.1.2.3.-numbers-and-then--dashes-");
- AMQShortStringTokenizer dotTokenizer = dotSeparatedWords.tokenize((byte) '.');
-
- assertTrue(dotTokenizer.hasMoreTokens());
- assertEquals(new AMQShortString("this"),(dotTokenizer.nextToken()));
- assertTrue(dotTokenizer.hasMoreTokens());
- assertEquals(new AMQShortString("is"),(dotTokenizer.nextToken()));
- assertTrue(dotTokenizer.hasMoreTokens());
- assertEquals(new AMQShortString("a"),(dotTokenizer.nextToken()));
- assertTrue(dotTokenizer.hasMoreTokens());
- assertEquals(new AMQShortString("test"),(dotTokenizer.nextToken()));
- assertTrue(dotTokenizer.hasMoreTokens());
- assertEquals(new AMQShortString("with"),(dotTokenizer.nextToken()));
- assertTrue(dotTokenizer.hasMoreTokens());
- assertEquals(dotTokenizer.nextToken().toIntValue() , 1);
- assertTrue(dotTokenizer.hasMoreTokens());
- assertEquals(dotTokenizer.nextToken().toIntValue() , 2);
- assertTrue(dotTokenizer.hasMoreTokens());
- assertEquals(dotTokenizer.nextToken().toIntValue() , 3);
- assertTrue(dotTokenizer.hasMoreTokens());
- AMQShortString dashString = dotTokenizer.nextToken();
- assertEquals(new AMQShortString("-numbers-and-then--dashes-"),(dashString));
-
- AMQShortStringTokenizer dashTokenizer = dashString.tokenize((byte)'-');
- assertEquals(dashTokenizer.countTokens(), 7);
-
- AMQShortString[] expectedResults = new AMQShortString[]
- { AMQShortString.EMPTY_STRING,
- new AMQShortString("numbers"),
- new AMQShortString("and"),
- new AMQShortString("then"),
- AMQShortString.EMPTY_STRING,
- new AMQShortString("dashes"),
- AMQShortString.EMPTY_STRING };
-
- for(int i = 0; i < 7; i++)
- {
- assertTrue(dashTokenizer.hasMoreTokens());
- assertEquals(dashTokenizer.nextToken(), expectedResults[i]);
- }
-
- assertFalse(dotTokenizer.hasMoreTokens());
- }
-
-
- public void testEquals()
- {
- assertEquals(GOODBYE, new AMQShortString("Goodbye"));
- assertEquals(new AMQShortString("A"), new AMQShortString("A"));
- assertFalse(new AMQShortString("A").equals(new AMQShortString("a")));
- }
-
-
-}
diff --git a/java/common/src/test/java/org/apache/qpid/framing/BasicContentHeaderPropertiesTest.java b/java/common/src/test/java/org/apache/qpid/framing/BasicContentHeaderPropertiesTest.java
deleted file mode 100644
index 4fd1f60d69..0000000000
--- a/java/common/src/test/java/org/apache/qpid/framing/BasicContentHeaderPropertiesTest.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.framing;
-
-import org.apache.mina.common.ByteBuffer;
-
-import junit.framework.TestCase;
-
-
-public class BasicContentHeaderPropertiesTest extends TestCase
-{
-
- BasicContentHeaderProperties _testProperties;
- FieldTable _testTable;
- String _testString = "This is a test string";
- int _testint = 666;
-
- /**
- * Currently only test setting/getting String, int and boolean props
- */
- public BasicContentHeaderPropertiesTest()
- {
- _testProperties = new BasicContentHeaderProperties();
- }
-
- public void setUp()
- {
- _testTable = new FieldTable();
- _testTable.setString("TestString", _testString);
- _testTable.setInteger("Testint", _testint);
- _testProperties = new BasicContentHeaderProperties();
- _testProperties.setHeaders(_testTable);
- }
-
- public void testGetPropertyListSize()
- {
- //needs a better test but at least we're exercising the code !
- // FT length is encoded in an int
- int expectedSize = EncodingUtils.encodedIntegerLength();
-
- expectedSize += EncodingUtils.encodedShortStringLength("TestInt");
- // 1 is for the Encoding Letter. here an 'i'
- expectedSize += 1 + EncodingUtils.encodedIntegerLength();
-
- expectedSize += EncodingUtils.encodedShortStringLength("TestString");
- // 1 is for the Encoding Letter. here an 'S'
- expectedSize += 1 + EncodingUtils.encodedLongStringLength(_testString);
-
-
- int size = _testProperties.getPropertyListSize();
-
- assertEquals(expectedSize, size);
- }
-
- public void testGetSetPropertyFlags()
- {
- _testProperties.setPropertyFlags(99);
- assertEquals(99, _testProperties.getPropertyFlags());
- }
-
- public void testWritePropertyListPayload()
- {
- ByteBuffer buf = ByteBuffer.allocate(300);
- _testProperties.writePropertyListPayload(buf);
- }
-
- public void testPopulatePropertiesFromBuffer() throws Exception
- {
- ByteBuffer buf = ByteBuffer.allocate(300);
- _testProperties.populatePropertiesFromBuffer(buf, 99, 99);
- }
-
- public void testSetGetContentType()
- {
- String contentType = "contentType";
- _testProperties.setContentType(contentType);
- assertEquals(contentType, _testProperties.getContentTypeAsString());
- }
-
- public void testSetGetEncoding()
- {
- String encoding = "encoding";
- _testProperties.setEncoding(encoding);
- assertEquals(encoding, _testProperties.getEncodingAsString());
- }
-
- public void testSetGetHeaders()
- {
- _testProperties.setHeaders(_testTable);
- assertEquals(_testTable, _testProperties.getHeaders());
- }
-
- public void testSetGetDeliveryMode()
- {
- byte deliveryMode = 1;
- _testProperties.setDeliveryMode(deliveryMode);
- assertEquals(deliveryMode, _testProperties.getDeliveryMode());
- }
-
- public void testSetGetPriority()
- {
- byte priority = 1;
- _testProperties.setPriority(priority);
- assertEquals(priority, _testProperties.getPriority());
- }
-
- public void testSetGetCorrelationId()
- {
- String correlationId = "correlationId";
- _testProperties.setCorrelationId(correlationId);
- assertEquals(correlationId, _testProperties.getCorrelationIdAsString());
- }
-
- public void testSetGetReplyTo()
- {
- String replyTo = "replyTo";
- _testProperties.setReplyTo(replyTo);
- assertEquals(replyTo, _testProperties.getReplyToAsString());
- }
-
- public void testSetGetExpiration()
- {
- long expiration = 999999999;
- _testProperties.setExpiration(expiration);
- assertEquals(expiration, _testProperties.getExpiration());
- }
-
- public void testSetGetMessageId()
- {
- String messageId = "messageId";
- _testProperties.setMessageId(messageId);
- assertEquals(messageId, _testProperties.getMessageIdAsString());
- }
-
- public void testSetGetTimestamp()
- {
- long timestamp = System.currentTimeMillis();
- _testProperties.setTimestamp(timestamp);
- assertEquals(timestamp, _testProperties.getTimestamp());
- }
-
- public void testSetGetType()
- {
- String type = "type";
- _testProperties.setType(type);
- assertEquals(type, _testProperties.getTypeAsString());
- }
-
- public void testSetGetUserId()
- {
- String userId = "userId";
- _testProperties.setUserId(userId);
- assertEquals(userId, _testProperties.getUserIdAsString());
- }
-
- public void testSetGetAppId()
- {
- String appId = "appId";
- _testProperties.setAppId(appId);
- assertEquals(appId, _testProperties.getAppIdAsString());
- }
-
- public void testSetGetClusterId()
- {
- String clusterId = "clusterId";
- _testProperties.setClusterId(clusterId);
- assertEquals(clusterId, _testProperties.getClusterIdAsString());
- }
-
-}
diff --git a/java/common/src/test/java/org/apache/qpid/framing/PropertyFieldTableTest.java b/java/common/src/test/java/org/apache/qpid/framing/PropertyFieldTableTest.java
deleted file mode 100644
index d4691ba097..0000000000
--- a/java/common/src/test/java/org/apache/qpid/framing/PropertyFieldTableTest.java
+++ /dev/null
@@ -1,974 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.framing;
-
-import junit.framework.Assert;
-import junit.framework.TestCase;
-
-import org.apache.mina.common.ByteBuffer;
-
-import org.apache.qpid.AMQInvalidArgumentException;
-import org.apache.qpid.AMQPInvalidClassException;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class PropertyFieldTableTest extends TestCase
-{
- private static final Logger _logger = LoggerFactory.getLogger(PropertyFieldTableTest.class);
-
- /**
- * Test that setting a similar named value replaces any previous value set on that name
- */
- public void testReplacement()
- {
- FieldTable table1 = new FieldTable();
- // Set a boolean value
- table1.setBoolean("value", true);
- // Check length of table is correct (<Value length> + <type> + <Boolean length>)
- int size = EncodingUtils.encodedShortStringLength("value") + 1 + EncodingUtils.encodedBooleanLength();
- Assert.assertEquals(size, table1.getEncodedSize());
-
- // reset value to an integer
- table1.setInteger("value", Integer.MAX_VALUE);
-
- // Check the length has changed accordingly (<Value length> + <type> + <Integer length>)
- size = EncodingUtils.encodedShortStringLength("value") + 1 + EncodingUtils.encodedIntegerLength();
- Assert.assertEquals(size, table1.getEncodedSize());
-
- // Check boolean value is null
- Assert.assertEquals(null, table1.getBoolean("value"));
- // ... and integer value is good
- Assert.assertEquals((Integer) Integer.MAX_VALUE, table1.getInteger("value"));
- }
-
- /**
- * Set a boolean and check that we can only get it back as a boolean and a string
- * Check that attempting to lookup a non existent value returns null
- */
- public void testBoolean()
- {
- FieldTable table1 = new FieldTable();
- table1.setBoolean("value", true);
- Assert.assertTrue(table1.propertyExists("value"));
-
- // Test Getting right value back
- Assert.assertEquals((Boolean) true, table1.getBoolean("value"));
-
- // Check we don't get anything back for other gets
- Assert.assertEquals(null, table1.getByte("value"));
- Assert.assertEquals(null, table1.getByte("value"));
- Assert.assertEquals(null, table1.getShort("value"));
- Assert.assertEquals(null, table1.getCharacter("value"));
- Assert.assertEquals(null, table1.getDouble("value"));
- Assert.assertEquals(null, table1.getFloat("value"));
- Assert.assertEquals(null, table1.getInteger("value"));
- Assert.assertEquals(null, table1.getLong("value"));
- Assert.assertEquals(null, table1.getBytes("value"));
-
- // except value as a string
- Assert.assertEquals("true", table1.getString("value"));
-
- table1.remove("value");
-
- // Table should now have zero length for encoding
- checkEmpty(table1);
-
- // Looking up an invalid value returns null
- Assert.assertEquals(null, table1.getBoolean("Rubbish"));
- }
-
- /**
- * Set a byte and check that we can only get it back as a byte and a string
- * Check that attempting to lookup a non existent value returns null
- */
- public void testByte()
- {
- FieldTable table1 = new FieldTable();
- table1.setByte("value", Byte.MAX_VALUE);
- Assert.assertTrue(table1.propertyExists("value"));
-
- // Tets lookups we shouldn't get anything back for other gets
- // we should get right value back for this type ....
- Assert.assertEquals(null, table1.getBoolean("value"));
- Assert.assertEquals(Byte.MAX_VALUE, (byte) table1.getByte("value"));
- Assert.assertEquals(null, table1.getShort("value"));
- Assert.assertEquals(null, table1.getCharacter("value"));
- Assert.assertEquals(null, table1.getDouble("value"));
- Assert.assertEquals(null, table1.getFloat("value"));
- Assert.assertEquals(null, table1.getInteger("value"));
- Assert.assertEquals(null, table1.getLong("value"));
- Assert.assertEquals(null, table1.getBytes("value"));
-
- // ... and a the string value of it.
- Assert.assertEquals("" + Byte.MAX_VALUE, table1.getString("value"));
-
- table1.remove("value");
- // Table should now have zero length for encoding
- checkEmpty(table1);
-
- // Looking up an invalid value returns null
- Assert.assertEquals(null, table1.getByte("Rubbish"));
- }
-
- /**
- * Set a short and check that we can only get it back as a short and a string
- * Check that attempting to lookup a non existent value returns null
- */
- public void testShort()
- {
- FieldTable table1 = new FieldTable();
- table1.setShort("value", Short.MAX_VALUE);
- Assert.assertTrue(table1.propertyExists("value"));
-
- // Tets lookups we shouldn't get anything back for other gets
- // we should get right value back for this type ....
- Assert.assertEquals(null, table1.getBoolean("value"));
- Assert.assertEquals(null, table1.getByte("value"));
- Assert.assertEquals(Short.MAX_VALUE, (short) table1.getShort("value"));
- Assert.assertEquals(null, table1.getCharacter("value"));
- Assert.assertEquals(null, table1.getDouble("value"));
- Assert.assertEquals(null, table1.getFloat("value"));
- Assert.assertEquals(null, table1.getInteger("value"));
- Assert.assertEquals(null, table1.getLong("value"));
- Assert.assertEquals(null, table1.getBytes("value"));
-
- // ... and a the string value of it.
- Assert.assertEquals("" + Short.MAX_VALUE, table1.getString("value"));
-
- table1.remove("value");
- // Table should now have zero length for encoding
- checkEmpty(table1);
-
- // Looking up an invalid value returns null
- Assert.assertEquals(null, table1.getShort("Rubbish"));
- }
-
- /**
- * Set a char and check that we can only get it back as a char
- * Check that attempting to lookup a non existent value returns null
- */
- public void testChar()
- {
- FieldTable table1 = new FieldTable();
- table1.setChar("value", 'c');
- Assert.assertTrue(table1.propertyExists("value"));
-
- // Tets lookups we shouldn't get anything back for other gets
- // we should get right value back for this type ....
- Assert.assertEquals(null, table1.getBoolean("value"));
- Assert.assertEquals(null, table1.getByte("value"));
- Assert.assertEquals(null, table1.getShort("value"));
- Assert.assertEquals('c', (char) table1.getCharacter("value"));
- Assert.assertEquals(null, table1.getDouble("value"));
- Assert.assertEquals(null, table1.getFloat("value"));
- Assert.assertEquals(null, table1.getInteger("value"));
- Assert.assertEquals(null, table1.getLong("value"));
- Assert.assertEquals(null, table1.getBytes("value"));
-
- // ... and a the string value of it.
- Assert.assertEquals("c", table1.getString("value"));
-
- table1.remove("value");
-
- // Table should now have zero length for encoding
- checkEmpty(table1);
-
- // Looking up an invalid value returns null
- Assert.assertEquals(null, table1.getCharacter("Rubbish"));
- }
-
- /**
- * Set a double and check that we can only get it back as a double
- * Check that attempting to lookup a non existent value returns null
- */
- public void testDouble()
- {
- FieldTable table1 = new FieldTable();
- table1.setDouble("value", Double.MAX_VALUE);
- Assert.assertTrue(table1.propertyExists("value"));
-
- // Tets lookups we shouldn't get anything back for other gets
- // we should get right value back for this type ....
- Assert.assertEquals(null, table1.getBoolean("value"));
- Assert.assertEquals(null, table1.getByte("value"));
- Assert.assertEquals(null, table1.getShort("value"));
- Assert.assertEquals(null, table1.getCharacter("value"));
- Assert.assertEquals(Double.MAX_VALUE, (double) table1.getDouble("value"));
- Assert.assertEquals(null, table1.getFloat("value"));
- Assert.assertEquals(null, table1.getInteger("value"));
- Assert.assertEquals(null, table1.getLong("value"));
- Assert.assertEquals(null, table1.getBytes("value"));
-
- // ... and a the string value of it.
- Assert.assertEquals("" + Double.MAX_VALUE, table1.getString("value"));
- table1.remove("value");
- // but after a removeKey it doesn't
- Assert.assertFalse(table1.containsKey("value"));
-
- // Table should now have zero length for encoding
- checkEmpty(table1);
-
- // Looking up an invalid value returns null
- Assert.assertEquals(null, table1.getDouble("Rubbish"));
- }
-
- /**
- * Set a float and check that we can only get it back as a float
- * Check that attempting to lookup a non existent value returns null
- */
- public void testFloat()
- {
- FieldTable table1 = new FieldTable();
- table1.setFloat("value", Float.MAX_VALUE);
- Assert.assertTrue(table1.propertyExists("value"));
-
- // Tets lookups we shouldn't get anything back for other gets
- // we should get right value back for this type ....
- Assert.assertEquals(null, table1.getBoolean("value"));
- Assert.assertEquals(null, table1.getByte("value"));
- Assert.assertEquals(null, table1.getShort("value"));
- Assert.assertEquals(null, table1.getCharacter("value"));
- Assert.assertEquals(null, table1.getDouble("value"));
- Assert.assertEquals(Float.MAX_VALUE, (float) table1.getFloat("value"));
- Assert.assertEquals(null, table1.getInteger("value"));
- Assert.assertEquals(null, table1.getLong("value"));
- Assert.assertEquals(null, table1.getBytes("value"));
-
- // ... and a the string value of it.
- Assert.assertEquals("" + Float.MAX_VALUE, table1.getString("value"));
-
- table1.remove("value");
- // but after a removeKey it doesn't
- Assert.assertFalse(table1.containsKey("value"));
-
- // Table should now have zero length for encoding
- checkEmpty(table1);
-
- // Looking up an invalid value returns null
- Assert.assertEquals(null, table1.getFloat("Rubbish"));
- }
-
- /**
- * Set an int and check that we can only get it back as an int
- * Check that attempting to lookup a non existent value returns null
- */
- public void testInt()
- {
- FieldTable table1 = new FieldTable();
- table1.setInteger("value", Integer.MAX_VALUE);
- Assert.assertTrue(table1.propertyExists("value"));
-
- // Tets lookups we shouldn't get anything back for other gets
- // we should get right value back for this type ....
- Assert.assertEquals(null, table1.getBoolean("value"));
- Assert.assertEquals(null, table1.getByte("value"));
- Assert.assertEquals(null, table1.getShort("value"));
- Assert.assertEquals(null, table1.getCharacter("value"));
- Assert.assertEquals(null, table1.getDouble("value"));
- Assert.assertEquals(null, table1.getFloat("value"));
- Assert.assertEquals(Integer.MAX_VALUE, (int) table1.getInteger("value"));
- Assert.assertEquals(null, table1.getLong("value"));
- Assert.assertEquals(null, table1.getBytes("value"));
-
- // ... and a the string value of it.
- Assert.assertEquals("" + Integer.MAX_VALUE, table1.getString("value"));
-
- table1.remove("value");
- // but after a removeKey it doesn't
- Assert.assertFalse(table1.containsKey("value"));
-
- // Table should now have zero length for encoding
- checkEmpty(table1);
-
- // Looking up an invalid value returns null
- Assert.assertEquals(null, table1.getInteger("Rubbish"));
- }
-
- /**
- * Set a long and check that we can only get it back as a long
- * Check that attempting to lookup a non existent value returns null
- */
- public void testLong()
- {
- FieldTable table1 = new FieldTable();
- table1.setLong("value", Long.MAX_VALUE);
- Assert.assertTrue(table1.propertyExists("value"));
-
- // Tets lookups we shouldn't get anything back for other gets
- // we should get right value back for this type ....
- Assert.assertEquals(null, table1.getBoolean("value"));
- Assert.assertEquals(null, table1.getByte("value"));
- Assert.assertEquals(null, table1.getShort("value"));
- Assert.assertEquals(null, table1.getCharacter("value"));
- Assert.assertEquals(null, table1.getDouble("value"));
- Assert.assertEquals(null, table1.getFloat("value"));
- Assert.assertEquals(null, table1.getInteger("value"));
- Assert.assertEquals(Long.MAX_VALUE, (long) table1.getLong("value"));
- Assert.assertEquals(null, table1.getBytes("value"));
-
- // ... and a the string value of it.
- Assert.assertEquals("" + Long.MAX_VALUE, table1.getString("value"));
-
- table1.remove("value");
- // but after a removeKey it doesn't
- Assert.assertFalse(table1.containsKey("value"));
-
- // Table should now have zero length for encoding
- checkEmpty(table1);
-
- // Looking up an invalid value returns null
- Assert.assertEquals(null, table1.getLong("Rubbish"));
- }
-
- /**
- * Set a double and check that we can only get it back as a double
- * Check that attempting to lookup a non existent value returns null
- */
- public void testBytes()
- {
- byte[] bytes = { 99, 98, 97, 96, 95 };
-
- FieldTable table1 = new FieldTable();
- table1.setBytes("value", bytes);
- Assert.assertTrue(table1.propertyExists("value"));
-
- // Tets lookups we shouldn't get anything back for other gets
- // we should get right value back for this type ....
- Assert.assertEquals(null, table1.getBoolean("value"));
- Assert.assertEquals(null, table1.getByte("value"));
- Assert.assertEquals(null, table1.getShort("value"));
- Assert.assertEquals(null, table1.getCharacter("value"));
- Assert.assertEquals(null, table1.getDouble("value"));
- Assert.assertEquals(null, table1.getFloat("value"));
- Assert.assertEquals(null, table1.getInteger("value"));
- Assert.assertEquals(null, table1.getLong("value"));
- assertBytesEqual(bytes, table1.getBytes("value"));
-
- // ... and a the string value of it is null
- Assert.assertEquals(null, table1.getString("value"));
-
- table1.remove("value");
- // but after a removeKey it doesn't
- Assert.assertFalse(table1.containsKey("value"));
-
- // Table should now have zero length for encoding
- checkEmpty(table1);
-
- // Looking up an invalid value returns null
- Assert.assertEquals(null, table1.getBytes("Rubbish"));
- }
-
- /**
- * Calls all methods that can be used to check the table is empty
- * - getEncodedSize
- * - isEmpty
- * - length
- *
- * @param table to check is empty
- */
- private void checkEmpty(FieldTable table)
- {
- Assert.assertEquals(0, table.getEncodedSize());
- Assert.assertTrue(table.isEmpty());
- Assert.assertEquals(0, table.size());
-
- Assert.assertEquals(0, table.keySet().size());
- }
-
- /**
- * Set a String and check that we can only get it back as a String
- * Check that attempting to lookup a non existent value returns null
- */
- public void testString()
- {
- FieldTable table1 = new FieldTable();
- table1.setString("value", "Hello");
- Assert.assertTrue(table1.propertyExists("value"));
-
- // Tets lookups we shouldn't get anything back for other gets
- // we should get right value back for this type ....
- Assert.assertEquals(null, table1.getBoolean("value"));
- Assert.assertEquals(null, table1.getByte("value"));
- Assert.assertEquals(null, table1.getShort("value"));
- Assert.assertEquals(null, table1.getCharacter("value"));
- Assert.assertEquals(null, table1.getDouble("value"));
- Assert.assertEquals(null, table1.getFloat("value"));
- Assert.assertEquals(null, table1.getInteger("value"));
- Assert.assertEquals(null, table1.getLong("value"));
- Assert.assertEquals(null, table1.getBytes("value"));
- Assert.assertEquals("Hello", table1.getString("value"));
-
- // Try setting a null value and read it back
- table1.setString("value", null);
-
- Assert.assertEquals(null, table1.getString("value"));
-
- // but still contains the value
- Assert.assertTrue(table1.containsKey("value"));
-
- table1.remove("value");
- // but after a removeKey it doesn't
- Assert.assertFalse(table1.containsKey("value"));
-
- checkEmpty(table1);
-
- // Looking up an invalid value returns null
- Assert.assertEquals(null, table1.getString("Rubbish"));
-
- // Additional Test that haven't been covered for string
- table1.setObject("value", "Hello");
- // Check that it was set correctly
- Assert.assertEquals("Hello", table1.getString("value"));
- }
-
- /** Check that a nested field table parameter correctly encodes and decodes to a byte buffer. */
- public void testNestedFieldTable()
- {
- byte[] testBytes = new byte[] { 0, 1, 2, 3, 4, 5 };
-
- FieldTable outerTable = new FieldTable();
- FieldTable innerTable = new FieldTable();
-
- // Put some stuff in the inner table.
- innerTable.setBoolean("bool", true);
- innerTable.setByte("byte", Byte.MAX_VALUE);
- innerTable.setBytes("bytes", testBytes);
- innerTable.setChar("char", 'c');
- innerTable.setDouble("double", Double.MAX_VALUE);
- innerTable.setFloat("float", Float.MAX_VALUE);
- innerTable.setInteger("int", Integer.MAX_VALUE);
- innerTable.setLong("long", Long.MAX_VALUE);
- innerTable.setShort("short", Short.MAX_VALUE);
- innerTable.setString("string", "hello");
- innerTable.setString("null-string", null);
-
- // Put the inner table in the outer one.
- outerTable.setFieldTable("innerTable", innerTable);
-
- // Write the outer table into the buffer.
- final ByteBuffer buffer = ByteBuffer.allocate((int) outerTable.getEncodedSize() + 4);
- outerTable.writeToBuffer(buffer);
- buffer.flip();
-
- // Extract the table back from the buffer again.
- try
- {
- FieldTable extractedOuterTable = EncodingUtils.readFieldTable(buffer);
-
- FieldTable extractedTable = extractedOuterTable.getFieldTable("innerTable");
-
- Assert.assertEquals((Boolean) true, extractedTable.getBoolean("bool"));
- Assert.assertEquals((Byte) Byte.MAX_VALUE, extractedTable.getByte("byte"));
- assertBytesEqual(testBytes, extractedTable.getBytes("bytes"));
- Assert.assertEquals((Character) 'c', extractedTable.getCharacter("char"));
- Assert.assertEquals(Double.MAX_VALUE, extractedTable.getDouble("double"));
- Assert.assertEquals(Float.MAX_VALUE, extractedTable.getFloat("float"));
- Assert.assertEquals((Integer) Integer.MAX_VALUE, extractedTable.getInteger("int"));
- Assert.assertEquals((Long) Long.MAX_VALUE, extractedTable.getLong("long"));
- Assert.assertEquals((Short) Short.MAX_VALUE, extractedTable.getShort("short"));
- Assert.assertEquals("hello", extractedTable.getString("string"));
- Assert.assertEquals(null, extractedTable.getString("null-string"));
- }
- catch (AMQFrameDecodingException e)
- {
- fail("Failed to decode field table with nested inner table.");
- }
- }
-
- public void testValues()
- {
- FieldTable table = new FieldTable();
- table.setBoolean("bool", true);
- table.setByte("byte", Byte.MAX_VALUE);
- byte[] bytes = { 99, 98, 97, 96, 95 };
- table.setBytes("bytes", bytes);
- table.setChar("char", 'c');
- table.setDouble("double", Double.MAX_VALUE);
- table.setFloat("float", Float.MAX_VALUE);
- table.setInteger("int", Integer.MAX_VALUE);
- table.setLong("long", Long.MAX_VALUE);
- table.setShort("short", Short.MAX_VALUE);
- table.setString("string", "Hello");
- table.setString("null-string", null);
-
- table.setObject("object-bool", true);
- table.setObject("object-byte", Byte.MAX_VALUE);
- table.setObject("object-bytes", bytes);
- table.setObject("object-char", 'c');
- table.setObject("object-double", Double.MAX_VALUE);
- table.setObject("object-float", Float.MAX_VALUE);
- table.setObject("object-int", Integer.MAX_VALUE);
- table.setObject("object-long", Long.MAX_VALUE);
- table.setObject("object-short", Short.MAX_VALUE);
- table.setObject("object-string", "Hello");
-
- try
- {
- table.setObject("Null-object", null);
- fail("null values are not allowed");
- }
- catch (AMQPInvalidClassException aice)
- {
- assertEquals("Null values are not allowed to be set",
- AMQPInvalidClassException.INVALID_OBJECT_MSG + "null", aice.getMessage());
- }
-
- try
- {
- table.setObject("Unsupported-object", new Exception());
- fail("Non primitive values are not allowed");
- }
- catch (AMQPInvalidClassException aice)
- {
- assertEquals("Non primitive values are not allowed to be set",
- AMQPInvalidClassException.INVALID_OBJECT_MSG + Exception.class, aice.getMessage());
- }
-
- Assert.assertEquals((Boolean) true, table.getBoolean("bool"));
- Assert.assertEquals((Byte) Byte.MAX_VALUE, table.getByte("byte"));
- assertBytesEqual(bytes, table.getBytes("bytes"));
- Assert.assertEquals((Character) 'c', table.getCharacter("char"));
- Assert.assertEquals(Double.MAX_VALUE, table.getDouble("double"));
- Assert.assertEquals(Float.MAX_VALUE, table.getFloat("float"));
- Assert.assertEquals((Integer) Integer.MAX_VALUE, table.getInteger("int"));
- Assert.assertEquals((Long) Long.MAX_VALUE, table.getLong("long"));
- Assert.assertEquals((Short) Short.MAX_VALUE, table.getShort("short"));
- Assert.assertEquals("Hello", table.getString("string"));
- Assert.assertEquals(null, table.getString("null-string"));
-
- Assert.assertEquals(true, table.getObject("object-bool"));
- Assert.assertEquals(Byte.MAX_VALUE, table.getObject("object-byte"));
- assertBytesEqual(bytes, (byte[]) table.getObject("object-bytes"));
- Assert.assertEquals('c', table.getObject("object-char"));
- Assert.assertEquals(Double.MAX_VALUE, table.getObject("object-double"));
- Assert.assertEquals(Float.MAX_VALUE, table.getObject("object-float"));
- Assert.assertEquals(Integer.MAX_VALUE, table.getObject("object-int"));
- Assert.assertEquals(Long.MAX_VALUE, table.getObject("object-long"));
- Assert.assertEquals(Short.MAX_VALUE, table.getObject("object-short"));
- Assert.assertEquals("Hello", table.getObject("object-string"));
- }
-
- public void testwriteBuffer()
- {
- byte[] bytes = { 99, 98, 97, 96, 95 };
-
- FieldTable table = new FieldTable();
- table.setBoolean("bool", true);
- table.setByte("byte", Byte.MAX_VALUE);
-
- table.setBytes("bytes", bytes);
- table.setChar("char", 'c');
- table.setDouble("double", Double.MAX_VALUE);
- table.setFloat("float", Float.MAX_VALUE);
- table.setInteger("int", Integer.MAX_VALUE);
- table.setLong("long", Long.MAX_VALUE);
- table.setShort("short", Short.MAX_VALUE);
- table.setString("string", "hello");
- table.setString("null-string", null);
-
- final ByteBuffer buffer = ByteBuffer.allocate((int) table.getEncodedSize() + 4); // FIXME XXX: Is cast a problem?
-
- table.writeToBuffer(buffer);
-
- buffer.flip();
-
- long length = buffer.getUnsignedInt();
-
- FieldTable table2 = new FieldTable(buffer, length);
-
- Assert.assertEquals((Boolean) true, table2.getBoolean("bool"));
- Assert.assertEquals((Byte) Byte.MAX_VALUE, table2.getByte("byte"));
- assertBytesEqual(bytes, table2.getBytes("bytes"));
- Assert.assertEquals((Character) 'c', table2.getCharacter("char"));
- Assert.assertEquals(Double.MAX_VALUE, table2.getDouble("double"));
- Assert.assertEquals(Float.MAX_VALUE, table2.getFloat("float"));
- Assert.assertEquals((Integer) Integer.MAX_VALUE, table2.getInteger("int"));
- Assert.assertEquals((Long) Long.MAX_VALUE, table2.getLong("long"));
- Assert.assertEquals((Short) Short.MAX_VALUE, table2.getShort("short"));
- Assert.assertEquals("hello", table2.getString("string"));
- Assert.assertEquals(null, table2.getString("null-string"));
- }
-
- public void testEncodingSize()
- {
- FieldTable result = new FieldTable();
- int size = 0;
-
- result.setBoolean("boolean", true);
- size += 1 + EncodingUtils.encodedShortStringLength("boolean") + EncodingUtils.encodedBooleanLength();
- Assert.assertEquals(size, result.getEncodedSize());
-
- result.setByte("byte", (byte) Byte.MAX_VALUE);
- size += 1 + EncodingUtils.encodedShortStringLength("byte") + EncodingUtils.encodedByteLength();
- Assert.assertEquals(size, result.getEncodedSize());
-
- byte[] _bytes = { 99, 98, 97, 96, 95 };
-
- result.setBytes("bytes", _bytes);
- size += 1 + EncodingUtils.encodedShortStringLength("bytes") + 4 + _bytes.length;
- Assert.assertEquals(size, result.getEncodedSize());
-
- result.setChar("char", (char) 'c');
- size += 1 + EncodingUtils.encodedShortStringLength("char") + EncodingUtils.encodedCharLength();
- Assert.assertEquals(size, result.getEncodedSize());
-
- result.setDouble("double", (double) Double.MAX_VALUE);
- size += 1 + EncodingUtils.encodedShortStringLength("double") + EncodingUtils.encodedDoubleLength();
- Assert.assertEquals(size, result.getEncodedSize());
-
- result.setFloat("float", (float) Float.MAX_VALUE);
- size += 1 + EncodingUtils.encodedShortStringLength("float") + EncodingUtils.encodedFloatLength();
- Assert.assertEquals(size, result.getEncodedSize());
-
- result.setInteger("int", (int) Integer.MAX_VALUE);
- size += 1 + EncodingUtils.encodedShortStringLength("int") + EncodingUtils.encodedIntegerLength();
- Assert.assertEquals(size, result.getEncodedSize());
-
- result.setLong("long", (long) Long.MAX_VALUE);
- size += 1 + EncodingUtils.encodedShortStringLength("long") + EncodingUtils.encodedLongLength();
- Assert.assertEquals(size, result.getEncodedSize());
-
- result.setShort("short", (short) Short.MAX_VALUE);
- size += 1 + EncodingUtils.encodedShortStringLength("short") + EncodingUtils.encodedShortLength();
- Assert.assertEquals(size, result.getEncodedSize());
-
- result.setString("result", "Hello");
- size += 1 + EncodingUtils.encodedShortStringLength("result") + EncodingUtils.encodedLongStringLength("Hello");
- Assert.assertEquals(size, result.getEncodedSize());
-
- result.setObject("object-bool", true);
- size += 1 + EncodingUtils.encodedShortStringLength("object-bool") + EncodingUtils.encodedBooleanLength();
- Assert.assertEquals(size, result.getEncodedSize());
-
- result.setObject("object-byte", Byte.MAX_VALUE);
- size += 1 + EncodingUtils.encodedShortStringLength("object-byte") + EncodingUtils.encodedByteLength();
- Assert.assertEquals(size, result.getEncodedSize());
-
- result.setObject("object-bytes", _bytes);
- size += 1 + EncodingUtils.encodedShortStringLength("object-bytes") + 4 + _bytes.length;
- Assert.assertEquals(size, result.getEncodedSize());
-
- result.setObject("object-char", 'c');
- size += 1 + EncodingUtils.encodedShortStringLength("object-char") + EncodingUtils.encodedCharLength();
- Assert.assertEquals(size, result.getEncodedSize());
-
- result.setObject("object-double", Double.MAX_VALUE);
- size += 1 + EncodingUtils.encodedShortStringLength("object-double") + EncodingUtils.encodedDoubleLength();
- Assert.assertEquals(size, result.getEncodedSize());
-
- result.setObject("object-float", Float.MAX_VALUE);
- size += 1 + EncodingUtils.encodedShortStringLength("object-float") + EncodingUtils.encodedFloatLength();
- Assert.assertEquals(size, result.getEncodedSize());
-
- result.setObject("object-int", Integer.MAX_VALUE);
- size += 1 + EncodingUtils.encodedShortStringLength("object-int") + EncodingUtils.encodedIntegerLength();
- Assert.assertEquals(size, result.getEncodedSize());
-
- result.setObject("object-long", Long.MAX_VALUE);
- size += 1 + EncodingUtils.encodedShortStringLength("object-long") + EncodingUtils.encodedLongLength();
- Assert.assertEquals(size, result.getEncodedSize());
-
- result.setObject("object-short", Short.MAX_VALUE);
- size += 1 + EncodingUtils.encodedShortStringLength("object-short") + EncodingUtils.encodedShortLength();
- Assert.assertEquals(size, result.getEncodedSize());
-
- }
-
- // public void testEncodingSize1()
- // {
- // PropertyFieldTable table = new PropertyFieldTable();
- // int length = 0;
- // result.put("one", 1L);
- // length = EncodingUtils.encodedShortStringLength("one");
- // length += 1 + EncodingUtils.encodedLongLength();
- // assertEquals(length, result.getEncodedSize());
- //
- // result.put("two", 2L);
- // length += EncodingUtils.encodedShortStringLength("two");
- // length += 1 + EncodingUtils.encodedLongLength();
- // assertEquals(length, result.getEncodedSize());
- //
- // result.put("three", 3L);
- // length += EncodingUtils.encodedShortStringLength("three");
- // length += 1 + EncodingUtils.encodedLongLength();
- // assertEquals(length, result.getEncodedSize());
- //
- // result.put("four", 4L);
- // length += EncodingUtils.encodedShortStringLength("four");
- // length += 1 + EncodingUtils.encodedLongLength();
- // assertEquals(length, result.getEncodedSize());
- //
- // result.put("five", 5L);
- // length += EncodingUtils.encodedShortStringLength("five");
- // length += 1 + EncodingUtils.encodedLongLength();
- // assertEquals(length, result.getEncodedSize());
- //
- // //fixme should perhaps be expanded to incorporate all types.
- //
- // final ByteBuffer buffer = ByteBuffer.allocate((int) result.getEncodedSize()); // FIXME XXX: Is cast a problem?
- //
- // result.writeToBuffer(buffer);
- //
- // buffer.flip();
- //
- // long length = buffer.getUnsignedInt();
- //
- // try
- // {
- // PropertyFieldTable table2 = new PropertyFieldTable(buffer, length);
- //
- // Assert.assertEquals((Long) 1L, table2.getLong("one"));
- // Assert.assertEquals((Long) 2L, table2.getLong("two"));
- // Assert.assertEquals((Long) 3L, table2.getLong("three"));
- // Assert.assertEquals((Long) 4L, table2.getLong("four"));
- // Assert.assertEquals((Long) 5L, table2.getLong("five"));
- // }
- // catch (AMQFrameDecodingException e)
- // {
- // e.printStackTrace();
- // fail("PFT should be instantiated from bytes." + e.getCause());
- // }
- //
- // }
-
- /**
- * Additional test for setObject
- */
- public void testSetObject()
- {
- FieldTable table = new FieldTable();
-
- // Try setting a non primative object
-
- try
- {
- table.setObject("value", this);
- fail("Only primative values allowed in setObject");
- }
- catch (AMQPInvalidClassException iae)
- {
- // normal path
- }
- // so length should be zero
- Assert.assertEquals(0, table.getEncodedSize());
- }
-
- /**
- * Additional test checkPropertyName doesn't accept Null
- */
- public void testCheckPropertyNameasNull()
- {
- FieldTable table = new FieldTable();
-
- try
- {
- table.setObject((String) null, "String");
- fail("Null property name is not allowed");
- }
- catch (IllegalArgumentException iae)
- {
- // normal path
- }
- // so length should be zero
- Assert.assertEquals(0, table.getEncodedSize());
- }
-
- /**
- * Additional test checkPropertyName doesn't accept an empty String
- */
- public void testCheckPropertyNameasEmptyString()
- {
- FieldTable table = new FieldTable();
-
- try
- {
- table.setObject("", "String");
- fail("empty property name is not allowed");
- }
- catch (IllegalArgumentException iae)
- {
- // normal path
- }
- // so length should be zero
- Assert.assertEquals(0, table.getEncodedSize());
- }
-
- /**
- * Additional test checkPropertyName doesn't accept an empty String
- */
- public void testCheckPropertyNamehasMaxLength()
- {
- String oldVal = System.getProperty("STRICT_AMQP");
- System.setProperty("STRICT_AMQP", "true");
- FieldTable table = new FieldTable();
-
- StringBuffer longPropertyName = new StringBuffer(129);
-
- for (int i = 0; i < 129; i++)
- {
- longPropertyName.append("x");
- }
-
- try
- {
- table.setObject(longPropertyName.toString(), "String");
- fail("property name must be < 128 characters");
- }
- catch (IllegalArgumentException iae)
- {
- // normal path
- }
- // so length should be zero
- Assert.assertEquals(0, table.getEncodedSize());
- if (oldVal != null)
- {
- System.setProperty("STRICT_AMQP", oldVal);
- }
- else
- {
- System.clearProperty("STRICT_AMQP");
- }
- }
-
- /**
- * Additional test checkPropertyName starts with a letter
- */
- public void testCheckPropertyNameStartCharacterIsLetter()
- {
- String oldVal = System.getProperty("STRICT_AMQP");
- System.setProperty("STRICT_AMQP", "true");
- FieldTable table = new FieldTable();
-
- // Try a name that starts with a number
- try
- {
- table.setObject("1", "String");
- fail("property name must start with a letter");
- }
- catch (IllegalArgumentException iae)
- {
- // normal path
- }
- // so length should be zero
- Assert.assertEquals(0, table.getEncodedSize());
- if (oldVal != null)
- {
- System.setProperty("STRICT_AMQP", oldVal);
- }
- else
- {
- System.clearProperty("STRICT_AMQP");
- }
- }
-
- /**
- * Additional test checkPropertyName starts with a hash or a dollar
- */
- public void testCheckPropertyNameStartCharacterIsHashorDollar()
- {
- String oldVal = System.getProperty("STRICT_AMQP");
- System.setProperty("STRICT_AMQP", "true");
- FieldTable table = new FieldTable();
-
- // Try a name that starts with a number
- try
- {
- table.setObject("#", "String");
- table.setObject("$", "String");
- }
- catch (IllegalArgumentException iae)
- {
- fail("property name are allowed to start with # and $s");
- }
-
- if (oldVal != null)
- {
- System.setProperty("STRICT_AMQP", oldVal);
- }
- else
- {
- System.clearProperty("STRICT_AMQP");
- }
- }
-
- /**
- * Additional test to test the contents of the table
- */
- public void testContents()
- {
- FieldTable table = new FieldTable();
-
- table.setObject("StringProperty", "String");
-
- Assert.assertEquals("String", table.getString("StringProperty"));
-
- // Test Clear
-
- table.clear();
-
- checkEmpty(table);
- }
-
- /**
- * Test the contents of the sets
- */
- public void testSets()
- {
-
- FieldTable table = new FieldTable();
-
- table.setObject("n1", "1");
- table.setObject("n2", "2");
- table.setObject("n3", "3");
-
- Assert.assertEquals("1", table.getObject("n1"));
- Assert.assertEquals("2", table.getObject("n2"));
- Assert.assertEquals("3", table.getObject("n3"));
-
- }
-
- private void assertBytesEqual(byte[] expected, byte[] actual)
- {
- Assert.assertEquals(expected.length, actual.length);
-
- for (int index = 0; index < expected.length; index++)
- {
- Assert.assertEquals(expected[index], actual[index]);
- }
- }
-
- private void assertBytesNotEqual(byte[] expected, byte[] actual)
- {
- Assert.assertEquals(expected.length, actual.length);
-
- for (int index = 0; index < expected.length; index++)
- {
- Assert.assertFalse(expected[index] == actual[index]);
- }
- }
-
- public static junit.framework.Test suite()
- {
- return new junit.framework.TestSuite(PropertyFieldTableTest.class);
- }
-
-}
diff --git a/java/common/src/test/java/org/apache/qpid/framing/abstraction/MessagePublishInfoImplTest.java b/java/common/src/test/java/org/apache/qpid/framing/abstraction/MessagePublishInfoImplTest.java
deleted file mode 100644
index 3243136287..0000000000
--- a/java/common/src/test/java/org/apache/qpid/framing/abstraction/MessagePublishInfoImplTest.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.framing.abstraction;
-
-import junit.framework.TestCase;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.abstraction.MessagePublishInfoImpl;
-
-public class MessagePublishInfoImplTest extends TestCase
-{
- MessagePublishInfoImpl _mpi;
- final AMQShortString _exchange = new AMQShortString("exchange");
- final AMQShortString _routingKey = new AMQShortString("routingKey");
-
- public void setUp()
- {
- _mpi = new MessagePublishInfoImpl(_exchange, true, true, _routingKey);
- }
-
- /** Test that we can update the exchange value. */
- public void testExchange()
- {
- assertEquals(_exchange, _mpi.getExchange());
- AMQShortString newExchange = new AMQShortString("newExchange");
- //Check we can update the exchange
- _mpi.setExchange(newExchange);
- assertEquals(newExchange, _mpi.getExchange());
- //Ensure that the new exchange doesn't equal the old one
- assertFalse(_exchange.equals(_mpi.getExchange()));
- }
-
- /**
- * Check that the immedate value is set correctly and defaulted correctly
- */
- public void testIsImmediate()
- {
- //Check that the set value is correct
- assertTrue("Set value for immediate not as expected", _mpi.isImmediate());
-
- MessagePublishInfoImpl mpi = new MessagePublishInfoImpl();
-
- assertFalse("Default value for immediate should be false", mpi.isImmediate());
-
- mpi.setImmediate(true);
-
- assertTrue("Updated value for immediate not as expected", mpi.isImmediate());
-
- }
-
- /**
- * Check that the mandatory value is set correctly and defaulted correctly
- */
- public void testIsMandatory()
- {
- assertTrue("Set value for mandatory not as expected", _mpi.isMandatory());
-
- MessagePublishInfoImpl mpi = new MessagePublishInfoImpl();
-
- assertFalse("Default value for mandatory should be false", mpi.isMandatory());
-
- mpi.setMandatory(true);
-
- assertTrue("Updated value for mandatory not as expected", mpi.isMandatory());
- }
-
- /**
- * Check that the routingKey value is perserved
- */
- public void testRoutingKey()
- {
- assertEquals(_routingKey, _mpi.getRoutingKey());
- AMQShortString newRoutingKey = new AMQShortString("newRoutingKey");
-
- //Check we can update the routingKey
- _mpi.setRoutingKey(newRoutingKey);
- assertEquals(newRoutingKey, _mpi.getRoutingKey());
- //Ensure that the new routingKey doesn't equal the old one
- assertFalse(_routingKey.equals(_mpi.getRoutingKey()));
-
- }
-}
diff --git a/java/common/src/test/java/org/apache/qpid/pool/ReferenceCountingExecutorServiceTest.java b/java/common/src/test/java/org/apache/qpid/pool/ReferenceCountingExecutorServiceTest.java
deleted file mode 100644
index 35998de3a1..0000000000
--- a/java/common/src/test/java/org/apache/qpid/pool/ReferenceCountingExecutorServiceTest.java
+++ /dev/null
@@ -1,159 +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.pool;
-
-import java.util.HashSet;
-import java.util.Set;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.ThreadFactory;
-import java.util.concurrent.TimeUnit;
-
-import junit.framework.TestCase;
-
-
-public class ReferenceCountingExecutorServiceTest extends TestCase
-{
-
-
- private ReferenceCountingExecutorService _executorService = ReferenceCountingExecutorService.getInstance(); // Class under test
- private ThreadFactory _beforeExecutorThreadFactory;
-
-
- @Override
- protected void setUp() throws Exception
- {
- super.setUp();
- _beforeExecutorThreadFactory = _executorService.getThreadFactory();
- }
-
- @Override
- protected void tearDown() throws Exception
- {
- super.tearDown();
- _executorService.setThreadFactory(_beforeExecutorThreadFactory);
- }
-
-
-
- /**
- * Tests that the ReferenceCountingExecutorService correctly manages the reference count.
- */
- public void testReferenceCounting() throws Exception
- {
- final int countBefore = _executorService.getReferenceCount();
-
- try
- {
- _executorService.acquireExecutorService();
- _executorService.acquireExecutorService();
-
- assertEquals("Reference count should now be +2", countBefore + 2, _executorService.getReferenceCount());
- }
- finally
- {
- _executorService.releaseExecutorService();
- _executorService.releaseExecutorService();
- }
- assertEquals("Reference count should have returned to the initial value", countBefore, _executorService.getReferenceCount());
- }
-
- /**
- * Tests that the executor creates and executes a task using the default thread pool.
- */
- public void testExecuteCommandWithDefaultExecutorThreadFactory() throws Exception
- {
- final CountDownLatch latch = new CountDownLatch(1);
- final Set<ThreadGroup> threadGroups = new HashSet<ThreadGroup>();
-
- _executorService.acquireExecutorService();
-
- try
- {
- _executorService.getPool().execute(createRunnable(latch, threadGroups));
-
- latch.await(3, TimeUnit.SECONDS);
-
- assertTrue("Expect that executor created a thread using default thread factory",
- threadGroups.contains(Thread.currentThread().getThreadGroup()));
- }
- finally
- {
- _executorService.releaseExecutorService();
- }
- }
-
- /**
- * Tests that the executor creates and executes a task using an overridden thread pool.
- */
- public void testExecuteCommandWithOverriddenExecutorThreadFactory() throws Exception
- {
- final CountDownLatch latch = new CountDownLatch(1);
- final ThreadGroup expectedThreadGroup = new ThreadGroup("junit");
- _executorService.setThreadFactory(new ThreadGroupChangingThreadFactory(expectedThreadGroup));
- _executorService.acquireExecutorService();
-
- final Set<ThreadGroup> threadGroups = new HashSet<ThreadGroup>();
-
- try
- {
- _executorService.getPool().execute(createRunnable(latch, threadGroups));
-
- latch.await(3, TimeUnit.SECONDS);
-
- assertTrue("Expect that executor created a thread using overridden thread factory",
- threadGroups.contains(expectedThreadGroup));
- }
- finally
- {
- _executorService.releaseExecutorService();
- }
- }
-
- private Runnable createRunnable(final CountDownLatch latch, final Set<ThreadGroup> threadGroups)
- {
- return new Runnable()
- {
-
- public void run()
- {
- threadGroups.add(Thread.currentThread().getThreadGroup());
- latch.countDown();
- }
-
- };
- }
-
- private final class ThreadGroupChangingThreadFactory implements ThreadFactory
- {
- private final ThreadGroup _newGroup;
-
- private ThreadGroupChangingThreadFactory(final ThreadGroup newGroup)
- {
- this._newGroup = newGroup;
- }
-
- public Thread newThread(Runnable r)
- {
- return new Thread(_newGroup, r);
- }
- }
-
-}
diff --git a/java/common/src/test/java/org/apache/qpid/session/TestSession.java b/java/common/src/test/java/org/apache/qpid/session/TestSession.java
deleted file mode 100644
index aafc91b03b..0000000000
--- a/java/common/src/test/java/org/apache/qpid/session/TestSession.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.session;
-
-import org.apache.mina.common.*;
-
-import java.net.SocketAddress;
-import java.util.Set;
-import java.util.concurrent.ConcurrentMap;
-import java.util.concurrent.ConcurrentHashMap;
-
-public class TestSession implements IoSession
-{
- private final ConcurrentMap attributes = new ConcurrentHashMap();
-
- public TestSession()
- {
- }
-
- public IoService getService()
- {
- return null; //TODO
- }
-
- public IoServiceConfig getServiceConfig()
- {
- return null; //TODO
- }
-
- public IoHandler getHandler()
- {
- return null; //TODO
- }
-
- public IoSessionConfig getConfig()
- {
- return null; //TODO
- }
-
- public IoFilterChain getFilterChain()
- {
- return null; //TODO
- }
-
- public WriteFuture write(Object message)
- {
- return null; //TODO
- }
-
- public CloseFuture close()
- {
- return null; //TODO
- }
-
- public Object getAttachment()
- {
- return getAttribute("");
- }
-
- public Object setAttachment(Object attachment)
- {
- return setAttribute("",attachment);
- }
-
- public Object getAttribute(String key)
- {
- return attributes.get(key);
- }
-
- public Object setAttribute(String key, Object value)
- {
- return attributes.put(key,value);
- }
-
- public Object setAttribute(String key)
- {
- return attributes.put(key, Boolean.TRUE);
- }
-
- public Object removeAttribute(String key)
- {
- return attributes.remove(key);
- }
-
- public boolean containsAttribute(String key)
- {
- return attributes.containsKey(key);
- }
-
- public Set getAttributeKeys()
- {
- return attributes.keySet();
- }
-
- public TransportType getTransportType()
- {
- return null; //TODO
- }
-
- public boolean isConnected()
- {
- return false; //TODO
- }
-
- public boolean isClosing()
- {
- return false; //TODO
- }
-
- public CloseFuture getCloseFuture()
- {
- return null; //TODO
- }
-
- public SocketAddress getRemoteAddress()
- {
- return null; //TODO
- }
-
- public SocketAddress getLocalAddress()
- {
- return null; //TODO
- }
-
- public SocketAddress getServiceAddress()
- {
- return null; //TODO
- }
-
- public int getIdleTime(IdleStatus status)
- {
- return 0; //TODO
- }
-
- public long getIdleTimeInMillis(IdleStatus status)
- {
- return 0; //TODO
- }
-
- public void setIdleTime(IdleStatus status, int idleTime)
- {
- //TODO
- }
-
- public int getWriteTimeout()
- {
- return 0; //TODO
- }
-
- public long getWriteTimeoutInMillis()
- {
- return 0; //TODO
- }
-
- public void setWriteTimeout(int writeTimeout)
- {
- //TODO
- }
-
- public TrafficMask getTrafficMask()
- {
- return null; //TODO
- }
-
- public void setTrafficMask(TrafficMask trafficMask)
- {
- //TODO
- }
-
- public void suspendRead()
- {
- //TODO
- }
-
- public void suspendWrite()
- {
- //TODO
- }
-
- public void resumeRead()
- {
- //TODO
- }
-
- public void resumeWrite()
- {
- //TODO
- }
-
- public long getReadBytes()
- {
- return 0; //TODO
- }
-
- public long getWrittenBytes()
- {
- return 0; //TODO
- }
-
- public long getReadMessages()
- {
- return 0;
- }
-
- public long getWrittenMessages()
- {
- return 0;
- }
-
- public long getWrittenWriteRequests()
- {
- return 0; //TODO
- }
-
- public int getScheduledWriteRequests()
- {
- return 0; //TODO
- }
-
- public int getScheduledWriteBytes()
- {
- return 0; //TODO
- }
-
- public long getCreationTime()
- {
- return 0; //TODO
- }
-
- public long getLastIoTime()
- {
- return 0; //TODO
- }
-
- public long getLastReadTime()
- {
- return 0; //TODO
- }
-
- public long getLastWriteTime()
- {
- return 0; //TODO
- }
-
- public boolean isIdle(IdleStatus status)
- {
- return false; //TODO
- }
-
- public int getIdleCount(IdleStatus status)
- {
- return 0; //TODO
- }
-
- public long getLastIdleTime(IdleStatus status)
- {
- return 0; //TODO
- }
-}
diff --git a/java/common/src/test/java/org/apache/qpid/test/utils/QpidTestCase.java b/java/common/src/test/java/org/apache/qpid/test/utils/QpidTestCase.java
deleted file mode 100644
index 8b470d555e..0000000000
--- a/java/common/src/test/java/org/apache/qpid/test/utils/QpidTestCase.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.test.utils;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileReader;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-
-import junit.framework.TestCase;
-import junit.framework.TestResult;
-
-import org.apache.log4j.Logger;
-
-public class QpidTestCase extends TestCase
-{
- protected static final Logger _logger = Logger.getLogger(QpidTestCase.class);
-
- /**
- * Some tests are excluded when the property test.excludes is set to true.
- * An exclusion list is either a file (prop test.excludesfile) which contains one test name
- * to be excluded per line or a String (prop test.excludeslist) where tests to be excluded are
- * separated by " ". Excluded tests are specified following the format:
- * className#testName where className is the class of the test to be
- * excluded and testName is the name of the test to be excluded.
- * className#* excludes all the tests of the specified class.
- */
- static
- {
- if (Boolean.getBoolean("test.exclude"))
- {
- _logger.info("Some tests should be excluded, building the exclude list");
- String exclusionListURIs = System.getProperties().getProperty("test.excludefiles", "");
- String exclusionListString = System.getProperties().getProperty("test.excludelist", "");
- List<String> exclusionList = new ArrayList<String>();
-
- for (String uri : exclusionListURIs.split("\\s+"))
- {
- File file = new File(uri);
- if (file.exists())
- {
- _logger.info("Using exclude file: " + uri);
- try
- {
- BufferedReader in = new BufferedReader(new FileReader(file));
- String excludedTest = in.readLine();
- do
- {
- exclusionList.add(excludedTest);
- excludedTest = in.readLine();
- }
- while (excludedTest != null);
- }
- catch (IOException e)
- {
- _logger.warn("Exception when reading exclusion list", e);
- }
- }
- }
-
- if (!exclusionListString.equals(""))
- {
- _logger.info("Using excludeslist: " + exclusionListString);
- for (String test : exclusionListString.split("\\s+"))
- {
- exclusionList.add(test);
- }
- }
-
- _exclusionList = exclusionList;
- }
- }
-
- protected static final String MS_CLASS_NAME_KEY = "messagestore.class.name";
- protected static final String MEMORY_STORE_CLASS_NAME = "org.apache.qpid.server.store.MemoryMessageStore";
-
- private static List<String> _exclusionList;
-
- public QpidTestCase()
- {
- this("QpidTestCase");
- }
-
- public QpidTestCase(String name)
- {
- super(name);
- }
-
- public void run(TestResult testResult)
- {
- if (_exclusionList != null && (_exclusionList.contains(getClass().getPackage().getName() + ".*") ||
- _exclusionList.contains(getClass().getName() + "#*") ||
- _exclusionList.contains(getClass().getName() + "#" + getName())))
- {
- _logger.info("Test: " + getName() + " is excluded");
- testResult.endTest(this);
- }
- else
- {
- super.run(testResult);
- }
- }
-
- public String getTestProfileMessageStoreClassName()
- {
- String storeClass = System.getProperty(MS_CLASS_NAME_KEY);
-
- return storeClass != null ? storeClass : MEMORY_STORE_CLASS_NAME ;
- }
-}
diff --git a/java/common/src/test/java/org/apache/qpid/thread/ThreadFactoryTest.java b/java/common/src/test/java/org/apache/qpid/thread/ThreadFactoryTest.java
deleted file mode 100644
index 7b0f93700a..0000000000
--- a/java/common/src/test/java/org/apache/qpid/thread/ThreadFactoryTest.java
+++ /dev/null
@@ -1,104 +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.thread;
-
-import junit.framework.TestCase;
-
-/**
- * Tests the ThreadFactory.
- */
-public class ThreadFactoryTest extends TestCase
-{
- public void testThreadFactory()
- {
- Class<? extends ThreadFactory> threadFactoryClass = null;
- try
- {
- threadFactoryClass = Class.forName(System.getProperty("qpid.thread_factory",
- "org.apache.qpid.thread.DefaultThreadFactory")).asSubclass(ThreadFactory.class);
- }
- // If the thread factory class was wrong it will flagged way before it gets here.
- catch(Exception e)
- {
- fail("Invalid thread factory class");
- }
-
- assertEquals(threadFactoryClass, Threading.getThreadFactory().getClass());
- }
-
- /**
- * Tests creating a thread without a priority. Also verifies that the factory sets the
- * uncaught exception handler so uncaught exceptions are logged to SLF4J.
- */
- public void testCreateThreadWithDefaultPriority()
- {
- Runnable r = createRunnable();
-
- Thread t = null;
- try
- {
- t = Threading.getThreadFactory().createThread(r);
- }
- catch(Exception e)
- {
- fail("Error creating thread using Qpid thread factory");
- }
-
- assertNotNull(t);
- assertEquals(Thread.NORM_PRIORITY, t.getPriority());
- assertTrue(t.getUncaughtExceptionHandler() instanceof LoggingUncaughtExceptionHandler);
- }
-
- /**
- * Tests creating thread with a priority. Also verifies that the factory sets the
- * uncaught exception handler so uncaught exceptions are logged to SLF4J.
- */
- public void testCreateThreadWithSpecifiedPriority()
- {
- Runnable r = createRunnable();
-
- Thread t = null;
- try
- {
- t = Threading.getThreadFactory().createThread(r, 4);
- }
- catch(Exception e)
- {
- fail("Error creating thread using Qpid thread factory");
- }
-
- assertNotNull(t);
- assertEquals(4, t.getPriority());
- assertTrue(t.getUncaughtExceptionHandler() instanceof LoggingUncaughtExceptionHandler);
- }
-
- private Runnable createRunnable()
- {
- Runnable r = new Runnable(){
-
- public void run(){
-
- }
- };
- return r;
- }
-}
diff --git a/java/common/src/test/java/org/apache/qpid/transport/ConnectionTest.java b/java/common/src/test/java/org/apache/qpid/transport/ConnectionTest.java
deleted file mode 100644
index 375a326654..0000000000
--- a/java/common/src/test/java/org/apache/qpid/transport/ConnectionTest.java
+++ /dev/null
@@ -1,446 +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.transport;
-
-import org.apache.mina.util.AvailablePortFinder;
-
-import org.apache.qpid.test.utils.QpidTestCase;
-import org.apache.qpid.transport.network.ConnectionBinding;
-import org.apache.qpid.transport.network.io.IoAcceptor;
-import org.apache.qpid.transport.util.Logger;
-import org.apache.qpid.transport.util.Waiter;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Collections;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-import java.io.IOException;
-
-import static org.apache.qpid.transport.Option.*;
-
-/**
- * ConnectionTest
- */
-
-public class ConnectionTest extends QpidTestCase implements SessionListener
-{
-
- private static final Logger log = Logger.get(ConnectionTest.class);
-
- private int port;
- private volatile boolean queue = false;
- private List<MessageTransfer> messages = new ArrayList<MessageTransfer>();
- private List<MessageTransfer> incoming = new ArrayList<MessageTransfer>();
-
- private IoAcceptor _ioa = null;
-
-
- protected void setUp() throws Exception
- {
- super.setUp();
-
- port = AvailablePortFinder.getNextAvailable(12000);
- }
-
- protected void tearDown() throws Exception
- {
- if (_ioa != null)
- {
- _ioa.close();
- }
-
- super.tearDown();
- }
-
- public void opened(Session ssn) {}
-
- public void resumed(Session ssn) {}
-
- public void message(final Session ssn, MessageTransfer xfr)
- {
- if (queue)
- {
- messages.add(xfr);
- ssn.processed(xfr);
- return;
- }
-
- String body = xfr.getBodyString();
-
- if (body.startsWith("CLOSE"))
- {
- ssn.getConnection().close();
- }
- else if (body.startsWith("DELAYED_CLOSE"))
- {
- ssn.processed(xfr);
- new Thread()
- {
- public void run()
- {
- try
- {
- sleep(3000);
- }
- catch (InterruptedException e)
- {
- throw new RuntimeException(e);
- }
- ssn.getConnection().close();
- }
- }.start();
- }
- else if (body.startsWith("ECHO"))
- {
- int id = xfr.getId();
- ssn.invoke(xfr);
- ssn.processed(id);
- }
- else if (body.startsWith("SINK"))
- {
- ssn.processed(xfr);
- }
- else if (body.startsWith("DROP"))
- {
- // do nothing
- }
- else if (body.startsWith("EXCP"))
- {
- ExecutionException exc = new ExecutionException();
- exc.setDescription("intentional exception for testing");
- ssn.invoke(exc);
- ssn.close();
- }
- else
- {
- throw new IllegalArgumentException
- ("unrecognized message: " + body);
- }
- }
-
- public void exception(Session ssn, SessionException exc)
- {
- throw exc;
- }
-
- public void closed(Session ssn) {}
-
- private void send(Session ssn, String msg)
- {
- send(ssn, msg, false);
- }
-
- private void send(Session ssn, String msg, boolean sync)
- {
- ssn.messageTransfer
- ("xxx", MessageAcceptMode.NONE, MessageAcquireMode.PRE_ACQUIRED,
- null, msg, sync ? SYNC : NONE);
- }
-
- private Connection connect(final CountDownLatch closed)
- {
- Connection conn = new Connection();
- conn.addConnectionListener(new ConnectionListener()
- {
- public void opened(Connection conn) {}
- public void exception(Connection conn, ConnectionException exc)
- {
- exc.printStackTrace();
- }
- public void closed(Connection conn)
- {
- if (closed != null)
- {
- closed.countDown();
- }
- }
- });
- conn.connect("localhost", port, null, "guest", "guest", false);
- return conn;
- }
-
- public void testProtocolNegotiationExceptionOverridesCloseException() throws Exception
- {
- // Force os.name to be windows to exercise code in IoReceiver
- // that looks for the value of os.name
- System.setProperty("os.name","windows");
-
- // Start server as 0-9 to froce a ProtocolVersionException
- startServer(new ProtocolHeader(1, 0, 9));
-
- CountDownLatch closed = new CountDownLatch(1);
-
- try
- {
- connect(closed);
- fail("ProtocolVersionException expected");
- }
- catch (ProtocolVersionException pve)
- {
- //Expected code path
- }
- catch (Exception e)
- {
- fail("ProtocolVersionException expected. Got:" + e.getMessage());
- }
- }
-
- private void startServer()
- {
- startServer(new ProtocolHeader(1, 0, 10));
- }
-
- private void startServer(final ProtocolHeader protocolHeader)
- {
- ConnectionDelegate server = new ServerDelegate()
- {
- @Override
- public void init(Connection conn, ProtocolHeader hdr)
- {
- conn.send(protocolHeader);
- List<Object> utf8 = new ArrayList<Object>();
- utf8.add("utf8");
- conn.connectionStart(null, Collections.EMPTY_LIST, utf8);
- }
-
- @Override
- public Session getSession(Connection conn, SessionAttach atc)
- {
- Session ssn = super.getSession(conn, atc);
- ssn.setSessionListener(ConnectionTest.this);
- return ssn;
- }
- };
-
- try
- {
- _ioa = new IoAcceptor("localhost", port, ConnectionBinding.get(server));
- }
- catch (IOException e)
- {
- e.printStackTrace();
- fail("Unable to start Server for test due to:" + e.getMessage());
- }
-
- _ioa.start();
- }
-
- public void testClosedNotificationAndWriteToClosed() throws Exception
- {
- startServer();
-
- CountDownLatch closed = new CountDownLatch(1);
- Connection conn = connect(closed);
-
- Session ssn = conn.createSession(1);
- send(ssn, "CLOSE");
-
- if (!closed.await(3, TimeUnit.SECONDS))
- {
- fail("never got notified of connection close");
- }
-
- try
- {
- conn.connectionCloseOk();
- fail("writing to a closed socket succeeded");
- }
- catch (TransportException e)
- {
- // expected
- }
- }
-
- class FailoverConnectionListener implements ConnectionListener
- {
- public void opened(Connection conn) {}
-
- public void exception(Connection conn, ConnectionException e)
- {
- throw e;
- }
-
- public void closed(Connection conn)
- {
- queue = true;
- conn.connect("localhost", port, null, "guest", "guest");
- conn.resume();
- }
- }
-
- class TestSessionListener implements SessionListener
- {
- public void opened(Session s) {}
- public void resumed(Session s) {}
- public void exception(Session s, SessionException e) {}
- public void message(Session s, MessageTransfer xfr)
- {
- synchronized (incoming)
- {
- incoming.add(xfr);
- incoming.notifyAll();
- }
-
- s.processed(xfr);
- }
- public void closed(Session s) {}
- }
-
- public void testResumeNonemptyReplayBuffer() throws Exception
- {
- startServer();
-
- Connection conn = new Connection();
- conn.addConnectionListener(new FailoverConnectionListener());
- conn.connect("localhost", port, null, "guest", "guest");
- Session ssn = conn.createSession(1);
- ssn.setSessionListener(new TestSessionListener());
-
- send(ssn, "SINK 0");
- send(ssn, "ECHO 1");
- send(ssn, "ECHO 2");
-
- ssn.sync();
-
- String[] msgs = { "DROP 3", "DROP 4", "DROP 5", "CLOSE 6", "SINK 7" };
- for (String m : msgs)
- {
- send(ssn, m);
- }
-
- ssn.sync();
-
- assertEquals(msgs.length, messages.size());
- for (int i = 0; i < msgs.length; i++)
- {
- assertEquals(msgs[i], messages.get(i).getBodyString());
- }
-
- queue = false;
-
- send(ssn, "ECHO 8");
- send(ssn, "ECHO 9");
-
- synchronized (incoming)
- {
- Waiter w = new Waiter(incoming, 30000);
- while (w.hasTime() && incoming.size() < 4)
- {
- w.await();
- }
-
- assertEquals(4, incoming.size());
- assertEquals("ECHO 1", incoming.get(0).getBodyString());
- assertEquals(0, incoming.get(0).getId());
- assertEquals("ECHO 2", incoming.get(1).getBodyString());
- assertEquals(1, incoming.get(1).getId());
- assertEquals("ECHO 8", incoming.get(2).getBodyString());
- assertEquals(0, incoming.get(0).getId());
- assertEquals("ECHO 9", incoming.get(3).getBodyString());
- assertEquals(1, incoming.get(1).getId());
- }
- }
-
- public void testResumeEmptyReplayBuffer() throws InterruptedException
- {
- startServer();
-
- Connection conn = new Connection();
- conn.addConnectionListener(new FailoverConnectionListener());
- conn.connect("localhost", port, null, "guest", "guest");
- Session ssn = conn.createSession(1);
- ssn.setSessionListener(new TestSessionListener());
-
- send(ssn, "SINK 0");
- send(ssn, "SINK 1");
- send(ssn, "DELAYED_CLOSE 2");
- ssn.sync();
- Thread.sleep(6000);
- send(ssn, "SINK 3");
- ssn.sync();
- System.out.println(messages);
- assertEquals(1, messages.size());
- assertEquals("SINK 3", messages.get(0).getBodyString());
- }
-
- public void testFlushExpected() throws InterruptedException
- {
- startServer();
-
- Connection conn = new Connection();
- conn.connect("localhost", port, null, "guest", "guest");
- Session ssn = conn.createSession();
- ssn.sessionFlush(EXPECTED);
- send(ssn, "SINK 0");
- ssn.sessionFlush(EXPECTED);
- send(ssn, "SINK 1");
- ssn.sync();
- }
-
- public void testHeartbeat()
- {
- startServer();
- Connection conn = new Connection();
- conn.connect("localhost", port, null, "guest", "guest");
- conn.connectionHeartbeat();
- conn.close();
- }
-
- public void testExecutionExceptionInvoke() throws Exception
- {
- startServer();
-
- Connection conn = new Connection();
- conn.connect("localhost", port, null, "guest", "guest");
- Session ssn = conn.createSession();
- send(ssn, "EXCP 0");
- Thread.sleep(3000);
- try
- {
- send(ssn, "SINK 1");
- }
- catch (SessionException exc)
- {
- assertNotNull(exc.getException());
- }
- }
-
- public void testExecutionExceptionSync() throws Exception
- {
- startServer();
-
- Connection conn = new Connection();
- conn.connect("localhost", port, null, "guest", "guest");
- Session ssn = conn.createSession();
- send(ssn, "EXCP 0", true);
- try
- {
- ssn.sync();
- fail("this should have failed");
- }
- catch (SessionException exc)
- {
- assertNotNull(exc.getException());
- }
- }
-
-}
diff --git a/java/common/src/test/java/org/apache/qpid/transport/GenTest.java b/java/common/src/test/java/org/apache/qpid/transport/GenTest.java
deleted file mode 100644
index 512a0a29a6..0000000000
--- a/java/common/src/test/java/org/apache/qpid/transport/GenTest.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.transport;
-
-import junit.framework.TestCase;
-
-/**
- * GenTest
- *
- */
-
-public class GenTest extends TestCase
-{
-
- public void testBooleans()
- {
- QueueDeclare qd = new QueueDeclare().queue("test-queue").durable(false);
- assertEquals(qd.getQueue(), "test-queue");
- assertFalse("durable should be false", qd.getDurable());
- qd.setDurable(true);
- assertTrue("durable should be true", qd.getDurable());
- qd.setDurable(false);
- assertFalse("durable should be false again", qd.getDurable());
- }
-
-}
diff --git a/java/common/src/test/java/org/apache/qpid/transport/RangeSetTest.java b/java/common/src/test/java/org/apache/qpid/transport/RangeSetTest.java
deleted file mode 100644
index ad45d00e46..0000000000
--- a/java/common/src/test/java/org/apache/qpid/transport/RangeSetTest.java
+++ /dev/null
@@ -1,238 +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.transport;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-import junit.framework.TestCase;
-
-import static org.apache.qpid.util.Serial.*;
-
-/**
- * RangeSetTest
- *
- */
-
-public class RangeSetTest extends TestCase
-{
-
- private void check(RangeSet ranges)
- {
- List<Integer> posts = new ArrayList<Integer>();
- for (Range range : ranges)
- {
- posts.add(range.getLower());
- posts.add(range.getUpper());
- }
-
- List<Integer> sorted = new ArrayList<Integer>(posts);
- Collections.sort(sorted, COMPARATOR);
-
- assertEquals(posts, sorted);
-
- int idx = 1;
- while (idx + 1 < posts.size())
- {
- assertTrue(!eq(posts.get(idx) + 1, posts.get(idx+1)));
- idx += 2;
- }
- }
-
- public void test1()
- {
- RangeSet ranges = new RangeSet();
- ranges.add(5, 10);
- check(ranges);
- ranges.add(15, 20);
- check(ranges);
- ranges.add(23, 25);
- check(ranges);
- ranges.add(12, 14);
- check(ranges);
- ranges.add(0, 1);
- check(ranges);
- ranges.add(3, 11);
- check(ranges);
- }
-
- public void test2()
- {
- RangeSet rs = new RangeSet();
- check(rs);
-
- rs.add(1);
- assertTrue(rs.includes(1));
- assertTrue(!rs.includes(2));
- assertTrue(!rs.includes(0));
- check(rs);
-
- rs.add(2);
- assertTrue(!rs.includes(0));
- assertTrue(rs.includes(1));
- assertTrue(rs.includes(2));
- assertTrue(!rs.includes(3));
- check(rs);
-
- rs.add(0);
-
- assertTrue(!rs.includes(-1));
- assertTrue(rs.includes(0));
- assertTrue(rs.includes(1));
- assertTrue(rs.includes(2));
- assertTrue(!rs.includes(3));
- check(rs);
-
- rs.add(37);
-
- assertTrue(!rs.includes(-1));
- assertTrue(rs.includes(0));
- assertTrue(rs.includes(1));
- assertTrue(rs.includes(2));
- assertTrue(!rs.includes(3));
- assertTrue(!rs.includes(36));
- assertTrue(rs.includes(37));
- assertTrue(!rs.includes(38));
- check(rs);
-
- rs.add(-1);
- check(rs);
-
- rs.add(-3);
- check(rs);
-
- rs.add(1, 20);
- assertTrue(!rs.includes(21));
- assertTrue(rs.includes(20));
- check(rs);
- }
-
- public void testAddSelf()
- {
- RangeSet a = new RangeSet();
- a.add(0, 8);
- check(a);
- a.add(0, 8);
- check(a);
- assertEquals(a.size(), 1);
- Range range = a.iterator().next();
- assertEquals(range.getLower(), 0);
- assertEquals(range.getUpper(), 8);
- }
-
- public void testIntersect1()
- {
- Range a = new Range(0, 10);
- Range b = new Range(9, 20);
- Range i1 = a.intersect(b);
- Range i2 = b.intersect(a);
- assertEquals(i1.getUpper(), 10);
- assertEquals(i2.getUpper(), 10);
- assertEquals(i1.getLower(), 9);
- assertEquals(i2.getLower(), 9);
- }
-
- public void testIntersect2()
- {
- Range a = new Range(0, 10);
- Range b = new Range(11, 20);
- assertNull(a.intersect(b));
- assertNull(b.intersect(a));
- }
-
- public void testIntersect3()
- {
- Range a = new Range(0, 10);
- Range b = new Range(3, 5);
- Range i1 = a.intersect(b);
- Range i2 = b.intersect(a);
- assertEquals(i1.getUpper(), 5);
- assertEquals(i2.getUpper(), 5);
- assertEquals(i1.getLower(), 3);
- assertEquals(i2.getLower(), 3);
- }
-
- public void testSubtract1()
- {
- Range a = new Range(0, 10);
- assertTrue(a.subtract(a).isEmpty());
- }
-
- public void testSubtract2()
- {
- Range a = new Range(0, 10);
- Range b = new Range(20, 30);
- List<Range> ranges = a.subtract(b);
- assertEquals(ranges.size(), 1);
- Range d = ranges.get(0);
- assertEquals(d.getLower(), a.getLower());
- assertEquals(d.getUpper(), a.getUpper());
- }
-
- public void testSubtract3()
- {
- Range a = new Range(20, 30);
- Range b = new Range(0, 10);
- List<Range> ranges = a.subtract(b);
- assertEquals(ranges.size(), 1);
- Range d = ranges.get(0);
- assertEquals(d.getLower(), a.getLower());
- assertEquals(d.getUpper(), a.getUpper());
- }
-
- public void testSubtract4()
- {
- Range a = new Range(0, 10);
- Range b = new Range(3, 5);
- List<Range> ranges = a.subtract(b);
- assertEquals(ranges.size(), 2);
- Range low = ranges.get(0);
- Range high = ranges.get(1);
- assertEquals(low.getLower(), 0);
- assertEquals(low.getUpper(), 2);
- assertEquals(high.getLower(), 6);
- assertEquals(high.getUpper(), 10);
- }
-
- public void testSubtract5()
- {
- Range a = new Range(0, 10);
- Range b = new Range(3, 20);
- List<Range> ranges = a.subtract(b);
- assertEquals(ranges.size(), 1);
- Range d = ranges.get(0);
- assertEquals(d.getLower(), 0);
- assertEquals(d.getUpper(), 2);
- }
-
- public void testSubtract6()
- {
- Range a = new Range(0, 10);
- Range b = new Range(-10, 5);
- List<Range> ranges = a.subtract(b);
- assertEquals(ranges.size(), 1);
- Range d = ranges.get(0);
- assertEquals(d.getLower(), 6);
- assertEquals(d.getUpper(), 10);
- }
-
-}
diff --git a/java/common/src/test/java/org/apache/qpid/transport/TestNetworkDriver.java b/java/common/src/test/java/org/apache/qpid/transport/TestNetworkDriver.java
deleted file mode 100644
index 957a7190ee..0000000000
--- a/java/common/src/test/java/org/apache/qpid/transport/TestNetworkDriver.java
+++ /dev/null
@@ -1,133 +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.transport;
-
-import java.net.BindException;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.SocketAddress;
-import java.nio.ByteBuffer;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-
-import org.apache.qpid.protocol.ProtocolEngine;
-import org.apache.qpid.protocol.ProtocolEngineFactory;
-import org.apache.qpid.ssl.SSLContextFactory;
-
-/**
- * Test implementation of IoSession, which is required for some tests. Methods not being used are not implemented,
- * so if this class is being used and some methods are to be used, then please update those.
- */
-public class TestNetworkDriver implements NetworkDriver
-{
- private final ConcurrentMap attributes = new ConcurrentHashMap();
- private String _remoteHost = "127.0.0.1";
- private String _localHost = "127.0.0.1";
- private int _port = 1;
- private SocketAddress _localAddress = null;
- private SocketAddress _remoteAddress = null;
-
- public TestNetworkDriver()
- {
- }
-
- public void bind(int port, InetAddress[] addresses, ProtocolEngineFactory protocolFactory,
- NetworkDriverConfiguration config, SSLContextFactory sslFactory) throws BindException
- {
-
- }
-
- public SocketAddress getLocalAddress()
- {
- return (_localAddress != null) ? _localAddress : new InetSocketAddress(_localHost, _port);
- }
-
- public SocketAddress getRemoteAddress()
- {
- return (_remoteAddress != null) ? _remoteAddress : new InetSocketAddress(_remoteHost, _port);
- }
-
- public void open(int port, InetAddress destination, ProtocolEngine engine, NetworkDriverConfiguration config,
- SSLContextFactory sslFactory) throws OpenException
- {
-
- }
-
- public void setMaxReadIdle(int idleTime)
- {
-
- }
-
- public void setMaxWriteIdle(int idleTime)
- {
-
- }
-
- public void close()
- {
-
- }
-
- public void flush()
- {
-
- }
-
- public void send(ByteBuffer msg)
- {
-
- }
-
- public void setIdleTimeout(int i)
- {
-
- }
-
- public void setPort(int port)
- {
- _port = port;
- }
-
- public int getPort()
- {
- return _port;
- }
-
- public void setLocalHost(String host)
- {
- _localHost = host;
- }
-
- public void setRemoteHost(String host)
- {
- _remoteHost = host;
- }
-
- public void setLocalAddress(SocketAddress address)
- {
- _localAddress = address;
- }
-
- public void setRemoteAddress(SocketAddress address)
- {
- _remoteAddress = address;
- }
-}
diff --git a/java/common/src/test/java/org/apache/qpid/transport/codec/BBEncoderTest.java b/java/common/src/test/java/org/apache/qpid/transport/codec/BBEncoderTest.java
deleted file mode 100644
index 79bf184fe2..0000000000
--- a/java/common/src/test/java/org/apache/qpid/transport/codec/BBEncoderTest.java
+++ /dev/null
@@ -1,47 +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.transport.codec;
-
-import junit.framework.TestCase;
-
-import java.nio.ByteBuffer;
-
-/**
- * BBEncoderTest
- *
- */
-
-public class BBEncoderTest extends TestCase
-{
-
- public void testGrow()
- {
- BBEncoder enc = new BBEncoder(4);
- enc.writeInt32(0xDEADBEEF);
- ByteBuffer buf = enc.buffer();
- assertEquals(0xDEADBEEF, buf.getInt(0));
- enc.writeInt32(0xBEEFDEAD);
- buf = enc.buffer();
- assertEquals(0xDEADBEEF, buf.getInt(0));
- assertEquals(0xBEEFDEAD, buf.getInt(4));
- }
-
-}
diff --git a/java/common/src/test/java/org/apache/qpid/transport/network/mina/MINANetworkDriverTest.java b/java/common/src/test/java/org/apache/qpid/transport/network/mina/MINANetworkDriverTest.java
deleted file mode 100644
index fc8e689ca4..0000000000
--- a/java/common/src/test/java/org/apache/qpid/transport/network/mina/MINANetworkDriverTest.java
+++ /dev/null
@@ -1,494 +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.transport.network.mina;
-
-import java.net.BindException;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.SocketAddress;
-import java.net.UnknownHostException;
-import java.nio.ByteBuffer;
-import java.util.ArrayList;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-import junit.framework.TestCase;
-
-import org.apache.qpid.framing.AMQDataBlock;
-import org.apache.qpid.protocol.ProtocolEngine;
-import org.apache.qpid.protocol.ProtocolEngineFactory;
-import org.apache.qpid.transport.NetworkDriver;
-import org.apache.qpid.transport.OpenException;
-
-public class MINANetworkDriverTest extends TestCase
-{
-
- private static final String TEST_DATA = "YHALOTHAR";
- private static int TEST_PORT = 2323;
- private NetworkDriver _server;
- private NetworkDriver _client;
- private CountingProtocolEngine _countingEngine; // Keeps a count of how many bytes it's read
- private Exception _thrownEx;
-
- @Override
- public void setUp()
- {
- _server = new MINANetworkDriver();
- _client = new MINANetworkDriver();
- _thrownEx = null;
- _countingEngine = new CountingProtocolEngine();
- // increment the port to prevent tests clashing with each other when
- // the port is in TIMED_WAIT state.
- TEST_PORT++;
- }
-
- @Override
- public void tearDown()
- {
- if (_server != null)
- {
- _server.close();
- }
-
- if (_client != null)
- {
- _client.close();
- }
- }
-
- /**
- * Tests that a socket can't be opened if a driver hasn't been bound
- * to the port and can be opened if a driver has been bound.
- * @throws BindException
- * @throws UnknownHostException
- * @throws OpenException
- */
- public void testBindOpen() throws BindException, UnknownHostException, OpenException
- {
- try
- {
- _client.open(TEST_PORT, InetAddress.getLocalHost(), _countingEngine, null, null);
- }
- catch (OpenException e)
- {
- _thrownEx = e;
- }
-
- assertNotNull("Open should have failed since no engine bound", _thrownEx);
-
- _server.bind(TEST_PORT, null, new EchoProtocolEngineSingletonFactory(), null, null);
-
- _client.open(TEST_PORT, InetAddress.getLocalHost(), _countingEngine, null, null);
- }
-
- /**
- * Tests that a socket can't be opened after a bound NetworkDriver has been closed
- * @throws BindException
- * @throws UnknownHostException
- * @throws OpenException
- */
- public void testBindOpenCloseOpen() throws BindException, UnknownHostException, OpenException
- {
- _server.bind(TEST_PORT, null, new EchoProtocolEngineSingletonFactory(), null, null);
- _client.open(TEST_PORT, InetAddress.getLocalHost(), _countingEngine, null, null);
- _client.close();
- _server.close();
-
- try
- {
- _client.open(TEST_PORT, InetAddress.getLocalHost(), _countingEngine, null, null);
- }
- catch (OpenException e)
- {
- _thrownEx = e;
- }
- assertNotNull("Open should have failed", _thrownEx);
- }
-
- /**
- * Checks that the right exception is thrown when binding a NetworkDriver to an already
- * existing socket.
- */
- public void testBindPortInUse()
- {
- try
- {
- _server.bind(TEST_PORT, null, new EchoProtocolEngineSingletonFactory(), null, null);
- }
- catch (BindException e)
- {
- fail("First bind should not fail");
- }
-
- try
- {
- _client.bind(TEST_PORT, null, new EchoProtocolEngineSingletonFactory(), null, null);
- }
- catch (BindException e)
- {
- _thrownEx = e;
- }
- assertNotNull("Second bind should throw BindException", _thrownEx);
- }
-
- /**
- * tests that bytes sent on a network driver are received at the other end
- *
- * @throws UnknownHostException
- * @throws OpenException
- * @throws InterruptedException
- * @throws BindException
- */
- public void testSend() throws UnknownHostException, OpenException, InterruptedException, BindException
- {
- // Open a connection from a counting engine to an echo engine
- _server.bind(TEST_PORT, null, new EchoProtocolEngineSingletonFactory(), null, null);
- _client.open(TEST_PORT, InetAddress.getLocalHost(), _countingEngine, null, null);
-
- // Tell the counting engine how much data we're sending
- _countingEngine.setNewLatch(TEST_DATA.getBytes().length);
-
- // Send the data and wait for up to 2 seconds to get it back
- _client.send(ByteBuffer.wrap(TEST_DATA.getBytes()));
- _countingEngine.getLatch().await(2, TimeUnit.SECONDS);
-
- // Check what we got
- assertEquals("Wrong amount of data recieved", TEST_DATA.getBytes().length, _countingEngine.getReadBytes());
- }
-
- /**
- * Opens a connection with a low read idle and check that it gets triggered
- * @throws BindException
- * @throws OpenException
- * @throws UnknownHostException
- *
- */
- public void testSetReadIdle() throws BindException, UnknownHostException, OpenException
- {
- // Open a connection from a counting engine to an echo engine
- _server.bind(TEST_PORT, null, new EchoProtocolEngineSingletonFactory(), null, null);
- _client.open(TEST_PORT, InetAddress.getLocalHost(), _countingEngine, null, null);
- assertFalse("Reader should not have been idle", _countingEngine.getReaderHasBeenIdle());
- _client.setMaxReadIdle(1);
- sleepForAtLeast(1500);
- assertTrue("Reader should have been idle", _countingEngine.getReaderHasBeenIdle());
- }
-
- /**
- * Opens a connection with a low write idle and check that it gets triggered
- * @throws BindException
- * @throws OpenException
- * @throws UnknownHostException
- *
- */
- public void testSetWriteIdle() throws BindException, UnknownHostException, OpenException
- {
- // Open a connection from a counting engine to an echo engine
- _server.bind(TEST_PORT, null, new EchoProtocolEngineSingletonFactory(), null, null);
- _client.open(TEST_PORT, InetAddress.getLocalHost(), _countingEngine, null, null);
- assertFalse("Reader should not have been idle", _countingEngine.getWriterHasBeenIdle());
- _client.setMaxWriteIdle(1);
- sleepForAtLeast(1500);
- assertTrue("Reader should have been idle", _countingEngine.getWriterHasBeenIdle());
- }
-
-
- /**
- * Creates and then closes a connection from client to server and checks that the server
- * has its closed() method called. Then creates a new client and closes the server to check
- * that the client has its closed() method called.
- * @throws BindException
- * @throws UnknownHostException
- * @throws OpenException
- */
- public void testClosed() throws BindException, UnknownHostException, OpenException
- {
- // Open a connection from a counting engine to an echo engine
- EchoProtocolEngineSingletonFactory factory = new EchoProtocolEngineSingletonFactory();
- _server.bind(TEST_PORT, null, factory, null, null);
- _client.open(TEST_PORT, InetAddress.getLocalHost(), _countingEngine, null, null);
- EchoProtocolEngine serverEngine = null;
- while (serverEngine == null)
- {
- serverEngine = factory.getEngine();
- if (serverEngine == null)
- {
- try
- {
- Thread.sleep(10);
- }
- catch (InterruptedException e)
- {
- }
- }
- }
- assertFalse("Server should not have been closed", serverEngine.getClosed());
- serverEngine.setNewLatch(1);
- _client.close();
- try
- {
- serverEngine.getLatch().await(2, TimeUnit.SECONDS);
- }
- catch (InterruptedException e)
- {
- }
- assertTrue("Server should have been closed", serverEngine.getClosed());
-
- _client.open(TEST_PORT, InetAddress.getLocalHost(), _countingEngine, null, null);
- _countingEngine.setClosed(false);
- assertFalse("Client should not have been closed", _countingEngine.getClosed());
- _countingEngine.setNewLatch(1);
- _server.close();
- try
- {
- _countingEngine.getLatch().await(2, TimeUnit.SECONDS);
- }
- catch (InterruptedException e)
- {
- }
- assertTrue("Client should have been closed", _countingEngine.getClosed());
- }
-
- /**
- * Create a connection and instruct the client to throw an exception when it gets some data
- * and that the latch gets counted down.
- * @throws BindException
- * @throws UnknownHostException
- * @throws OpenException
- * @throws InterruptedException
- */
- public void testExceptionCaught() throws BindException, UnknownHostException, OpenException, InterruptedException
- {
- _server.bind(TEST_PORT, null, new EchoProtocolEngineSingletonFactory(), null, null);
- _client.open(TEST_PORT, InetAddress.getLocalHost(), _countingEngine, null, null);
-
-
- assertEquals("Exception should not have been thrown", 1,
- _countingEngine.getExceptionLatch().getCount());
- _countingEngine.setErrorOnNextRead(true);
- _countingEngine.setNewLatch(TEST_DATA.getBytes().length);
- _client.send(ByteBuffer.wrap(TEST_DATA.getBytes()));
- _countingEngine.getExceptionLatch().await(2, TimeUnit.SECONDS);
- assertEquals("Exception should have been thrown", 0,
- _countingEngine.getExceptionLatch().getCount());
- }
-
- /**
- * Opens a connection and checks that the remote address is the one that was asked for
- * @throws BindException
- * @throws UnknownHostException
- * @throws OpenException
- */
- public void testGetRemoteAddress() throws BindException, UnknownHostException, OpenException
- {
- _server.bind(TEST_PORT, null, new EchoProtocolEngineSingletonFactory(), null, null);
- _client.open(TEST_PORT, InetAddress.getLocalHost(), _countingEngine, null, null);
- assertEquals(new InetSocketAddress(InetAddress.getLocalHost(), TEST_PORT),
- _client.getRemoteAddress());
- }
-
- private class EchoProtocolEngineSingletonFactory implements ProtocolEngineFactory
- {
- EchoProtocolEngine _engine = null;
-
- public ProtocolEngine newProtocolEngine(NetworkDriver driver)
- {
- if (_engine == null)
- {
- _engine = new EchoProtocolEngine();
- _engine.setNetworkDriver(driver);
- }
- return getEngine();
- }
-
- public EchoProtocolEngine getEngine()
- {
- return _engine;
- }
- }
-
- public class CountingProtocolEngine implements ProtocolEngine
- {
-
- protected NetworkDriver _driver;
- public ArrayList<ByteBuffer> _receivedBytes = new ArrayList<ByteBuffer>();
- private int _readBytes;
- private CountDownLatch _latch = new CountDownLatch(0);
- private boolean _readerHasBeenIdle;
- private boolean _writerHasBeenIdle;
- private boolean _closed = false;
- private boolean _nextReadErrors = false;
- private CountDownLatch _exceptionLatch = new CountDownLatch(1);
-
- public void closed()
- {
- setClosed(true);
- _latch.countDown();
- }
-
- public void setErrorOnNextRead(boolean b)
- {
- _nextReadErrors = b;
- }
-
- public void setNewLatch(int length)
- {
- _latch = new CountDownLatch(length);
- }
-
- public long getReadBytes()
- {
- return _readBytes;
- }
-
- public SocketAddress getRemoteAddress()
- {
- if (_driver != null)
- {
- return _driver.getRemoteAddress();
- }
- else
- {
- return null;
- }
- }
-
- public SocketAddress getLocalAddress()
- {
- if (_driver != null)
- {
- return _driver.getLocalAddress();
- }
- else
- {
- return null;
- }
- }
-
- public long getWrittenBytes()
- {
- return 0;
- }
-
- public void readerIdle()
- {
- _readerHasBeenIdle = true;
- }
-
- public void setNetworkDriver(NetworkDriver driver)
- {
- _driver = driver;
- }
-
- public void writeFrame(AMQDataBlock frame)
- {
-
- }
-
- public void writerIdle()
- {
- _writerHasBeenIdle = true;
- }
-
- public void exception(Throwable t)
- {
- _exceptionLatch.countDown();
- }
-
- public CountDownLatch getExceptionLatch()
- {
- return _exceptionLatch;
- }
-
- public void received(ByteBuffer msg)
- {
- // increment read bytes and count down the latch for that many
- int bytes = msg.remaining();
- _readBytes += bytes;
- for (int i = 0; i < bytes; i++)
- {
- _latch.countDown();
- }
-
- // Throw an error if we've been asked too, but we can still count
- if (_nextReadErrors)
- {
- throw new RuntimeException("Was asked to error");
- }
- }
-
- public CountDownLatch getLatch()
- {
- return _latch;
- }
-
- public boolean getWriterHasBeenIdle()
- {
- return _writerHasBeenIdle;
- }
-
- public boolean getReaderHasBeenIdle()
- {
- return _readerHasBeenIdle;
- }
-
- public void setClosed(boolean _closed)
- {
- this._closed = _closed;
- }
-
- public boolean getClosed()
- {
- return _closed;
- }
-
- }
-
- private class EchoProtocolEngine extends CountingProtocolEngine
- {
-
- public void received(ByteBuffer msg)
- {
- super.received(msg);
- msg.rewind();
- _driver.send(msg);
- }
- }
-
- public static void sleepForAtLeast(long period)
- {
- long start = System.currentTimeMillis();
- long timeLeft = period;
- while (timeLeft > 0)
- {
- try
- {
- Thread.sleep(timeLeft);
- }
- catch (InterruptedException e)
- {
- // Ignore it
- }
- timeLeft = period - (System.currentTimeMillis() - start);
- }
- }
-} \ No newline at end of file
diff --git a/java/common/src/test/java/org/apache/qpid/util/CommandLineParserTest.java b/java/common/src/test/java/org/apache/qpid/util/CommandLineParserTest.java
deleted file mode 100644
index 942901f1c0..0000000000
--- a/java/common/src/test/java/org/apache/qpid/util/CommandLineParserTest.java
+++ /dev/null
@@ -1,554 +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.util;
-
-import junit.framework.*;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.Properties;
-
-/**
- * Unit tests the {@link CommandLineParser} class.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Check that parsing a single flag works ok.
- * <tr><td> Check that parsing multiple flags condensed together works ok.
- * <tr><td> Check that parsing an option with a space between it and its argument works ok.
- * <tr><td> Check that parsing an option with no space between it and its argument works ok.
- * <tr><td> Check that parsing an option with specific argument format works ok.
- * <tr><td> Check that parsing an option with specific argument format fails on bad argument.
- * <tr><td> Check that parsing a flag condensed together with an option fails.
- * <tr><td> Check that parsing a free argument works ok.
- * <tr><td> Check that parsing a free argument with specific format works ok.
- * <tr><td> Check that parsing a free argument with specific format fails on bad argument.
- * <tr><td> Check that parsing a mandatory option works ok.
- * <tr><td> Check that parsing a mandatory free argument works ok.
- * <tr><td> Check that parsing a mandatory option fails when no option is set.
- * <tr><td> Check that parsing a mandatory free argument fails when no argument is specified.
- * <tr><td> Check that parsing an unknown option works when unknowns not errors.
- * <tr><td> Check that parsing an unknown flag fails when unknowns are to be reported as errors.
- * <tr><td> Check that parsing an unknown option fails when unknowns are to be reported as errors.
- * <tr><td> Check that get errors returns a string on errors.
- * <tr><td> Check that get errors returns an empty string on no errors.
- * <tr><td> Check that get usage returns a string.
- * <tr><td> Check that get options in force returns an empty string before parsing.
- * <tr><td> Check that get options in force return a non-empty string after parsing.
- * </table>
- */
-public class CommandLineParserTest extends TestCase
-{
- private static final Logger log = LoggerFactory.getLogger(CommandLineParserTest.class);
-
- public CommandLineParserTest(String name)
- {
- super(name);
- }
-
- /**
- * Compile all the tests for the default test implementation of a traversable state into a test suite.
- */
- public static Test suite()
- {
- // Build a new test suite
- TestSuite suite = new TestSuite("CommandLineParser Tests");
-
- // Add all the tests defined in this class (using the default constructor)
- suite.addTestSuite(CommandLineParserTest.class);
-
- return suite;
- }
-
- /** Check that get errors returns an empty string on no errors. */
- public void testGetErrorsReturnsEmptyStringOnNoErrors() throws Exception
- {
- // Create a command line parser for some flags and options.
- CommandLineParser parser =
- new CommandLineParser(
- new String[][]
- {
- { "t1", "Test Flag 1." },
- { "t2", "Test Option 2.", "test" },
- { "t3", "Test Option 3.", "test", "true" },
- { "t4", "Test Option 4.", "test", null, "^test$" }
- });
-
- // Do some legal parsing.
- parser.parseCommandLine(new String[] { "-t1", "-t2test", "-t3test", "-t4test" });
-
- // Check that the get errors message returns an empty string.
- assertTrue("The errors method did not return an empty string.", "".equals(parser.getErrors()));
- }
-
- /** Check that get errors returns a string on errors. */
- public void testGetErrorsReturnsStringOnErrors() throws Exception
- {
- // Create a command line parser for some flags and options.
- CommandLineParser parser =
- new CommandLineParser(
- new String[][]
- {
- { "t1", "Test Flag 1." },
- { "t2", "Test Option 2.", "test" },
- { "t3", "Test Option 3.", "test", "true" },
- { "t4", "Test Option 4.", "test", null, "^test$" }
- });
-
- try
- {
- // Do some illegal parsing.
- parser.parseCommandLine(new String[] { "-t1", "-t1t2test", "-t4fail" });
- }
- catch (IllegalArgumentException e)
- { }
-
- // Check that the get errors message returns a string.
- assertTrue("The errors method returned an empty string.",
- !((parser.getErrors() == null) || "".equals(parser.getErrors())));
-
- }
-
- /** Check that get options in force returns an empty string before parsing. */
- public void testGetOptionsInForceReturnsEmptyStringBeforeParsing() throws Exception
- {
- // Create a command line parser for some flags and options.
- CommandLineParser parser =
- new CommandLineParser(
- new String[][]
- {
- { "t1", "Test Flag 1." },
- { "t2", "Test Option 2.", "test" },
- { "t3", "Test Option 3.", "test", "true" },
- { "t4", "Test Option 4.", "test", null, "^test$" }
- });
-
- // Check that the options in force method returns an empty string.
- assertTrue("The options in force method did not return an empty string.", "".equals(parser.getOptionsInForce()));
- }
-
- /** Check that get options in force return a non-empty string after parsing. */
- public void testGetOptionsInForceReturnsNonEmptyStringAfterParsing() throws Exception
- {
- // Create a command line parser for some flags and options.
- CommandLineParser parser =
- new CommandLineParser(
- new String[][]
- {
- { "t1", "Test Flag 1." },
- { "t2", "Test Option 2.", "test" },
- { "t3", "Test Option 3.", "test", "true" },
- { "t4", "Test Option 4.", "test", null, "^test$" }
- });
-
- // Do some parsing.
- parser.parseCommandLine(new String[] { "-t1", "-t2test", "-t3test", "-t4test" });
-
- // Check that the options in force method returns a string.
- assertTrue("The options in force method did not return a non empty string.",
- !((parser.getOptionsInForce() == null) || "".equals(parser.getOptionsInForce())));
- }
-
- /** Check that get usage returns a string. */
- public void testGetUsageReturnsString() throws Exception
- {
- // Create a command line parser for some flags and options.
- CommandLineParser parser =
- new CommandLineParser(
- new String[][]
- {
- { "t1", "Test Flag 1." },
- { "t2", "Test Option 2.", "test" },
- { "t3", "Test Option 3.", "test", "true" },
- { "t4", "Test Option 4.", "test", null, "^test$" }
- });
-
- // Check that the usage method returns a string.
- assertTrue("The usage method did not return a non empty string.",
- !((parser.getUsage() == null) || "".equals(parser.getUsage())));
- }
-
- /** Check that parsing multiple flags condensed together works ok. */
- public void testParseCondensedFlagsOk() throws Exception
- {
- // Create a command line parser for multiple flags.
- CommandLineParser parser =
- new CommandLineParser(
- new String[][]
- {
- { "t1", "Test Flag 1." },
- { "t2", "Test Flag 2." },
- { "t3", "Test Flag 3." }
- });
-
- // Parse a command line with the flags set and condensed together.
- Properties testProps = parser.parseCommandLine(new String[] { "-t1t2t3" });
-
- // Check that the flags were set in the parsed properties.
- assertTrue("The t1 flag was not \"true\", it was: " + testProps.get("t1"), "true".equals(testProps.get("t1")));
- assertTrue("The t2 flag was not \"true\", it was: " + testProps.get("t2"), "true".equals(testProps.get("t2")));
- assertTrue("The t3 flag was not \"true\", it was: " + testProps.get("t3"), "true".equals(testProps.get("t3")));
- }
-
- /** Check that parsing a flag condensed together with an option fails. */
- public void testParseFlagCondensedWithOptionFails() throws Exception
- {
- // Create a command line parser for a flag and an option.
- CommandLineParser parser =
- new CommandLineParser(new String[][]
- {
- { "t1", "Test Flag 1." },
- { "t2", "Test Option 2.", "test" }
- });
-
- // Check that the parser reports an error.
- boolean testPassed = false;
-
- try
- {
- // Parse a command line with the flag and option condensed together.
- Properties testProps = parser.parseCommandLine(new String[] { "-t1t2" });
- }
- catch (IllegalArgumentException e)
- {
- testPassed = true;
- }
-
- assertTrue("IllegalArgumentException not thrown when a flag and option are condensed together.", testPassed);
- }
-
- /** Check that parsing a free argument with specific format fails on bad argument. */
- public void testParseFormattedFreeArgumentFailsBadArgument() throws Exception
- {
- // Create a command line parser for a formatted free argument.
- CommandLineParser parser =
- new CommandLineParser(new String[][]
- {
- { "1", "Test Free Argument.", "test", null, "^test$" }
- });
-
- // Check that the parser signals an error for a badly formatted argument.
- boolean testPassed = false;
-
- try
- {
- // Parse a command line with this option set incorrectly.
- Properties testProps = parser.parseCommandLine(new String[] { "fail" });
- }
- catch (IllegalArgumentException e)
- {
- testPassed = true;
- }
-
- assertTrue("IllegalArgumentException not thrown when a badly formatted argument was set.", testPassed);
- }
-
- /** Check that parsing a free argument with specific format works ok. */
- public void testParseFormattedFreeArgumentOk() throws Exception
- {
- // Create a command line parser for a formatted free argument.
- CommandLineParser parser =
- new CommandLineParser(new String[][]
- {
- { "1", "Test Free Argument.", "test", null, "^test$" }
- });
-
- // Parse a command line with this argument set correctly.
- Properties testProps = parser.parseCommandLine(new String[] { "test" });
-
- // Check that the resultant properties contains the correctly parsed option.
- assertTrue("The first free argument was not equal to \"test\" but was: " + testProps.get("1"),
- "test".equals(testProps.get("1")));
- }
-
- /** Check that parsing an option with specific argument format fails on bad argument. */
- public void testParseFormattedOptionArgumentFailsBadArgument() throws Exception
- {
- // Create a command line parser for a formatted option.
- CommandLineParser parser = new CommandLineParser(new String[][]
- {
- { "t", "Test Option.", "test", null, "^test$" }
- });
-
- // Check that the parser signals an error for a badly formatted argument.
- boolean testPassed = false;
-
- try
- {
- // Parse a command line with this option set incorrectly.
- Properties testProps = parser.parseCommandLine(new String[] { "-t", "fail" });
- }
- catch (IllegalArgumentException e)
- {
- testPassed = true;
- }
-
- assertTrue("IllegalArgumentException not thrown when a badly formatted argument was set.", testPassed);
- }
-
- /** Check that parsing an option with specific argument format works ok. */
- public void testParseFormattedOptionArgumentOk() throws Exception
- {
- // Create a command line parser for a formatted option.
- CommandLineParser parser = new CommandLineParser(new String[][]
- {
- { "t", "Test Option.", "test", null, "^test$" }
- });
-
- // Parse a command line with this option set correctly.
- Properties testProps = parser.parseCommandLine(new String[] { "-t", "test" });
-
- // Check that the resultant properties contains the correctly parsed option.
- assertTrue("The test option was not equal to \"test\" but was: " + testProps.get("t"),
- "test".equals(testProps.get("t")));
- }
-
- /** Check that parsing a free argument works ok. */
- public void testParseFreeArgumentOk() throws Exception
- {
- // Create a command line parser for a free argument.
- CommandLineParser parser = new CommandLineParser(new String[][]
- {
- { "1", "Test Free Argument.", "test" }
- });
-
- // Parse a command line with this argument set.
- Properties testProps = parser.parseCommandLine(new String[] { "test" });
-
- // Check that the resultant properties contains the correctly parsed option.
- assertTrue("The first free argument was not equal to \"test\" but was: " + testProps.get("1"),
- "test".equals(testProps.get("1")));
- }
-
- /** Check that parsing a mandatory option works ok. */
- public void testParseMandatoryOptionOk() throws Exception
- {
- // Create a command line parser for a mandatory option.
- CommandLineParser parser = new CommandLineParser(new String[][]
- {
- { "t", "Test Option.", "test", "true" }
- });
-
- // Parse a command line with this option set correctly.
- Properties testProps = parser.parseCommandLine(new String[] { "-t", "test" });
-
- // Check that the resultant properties contains the correctly parsed option.
- assertTrue("The test option was not equal to \"test\" but was: " + testProps.get("t"),
- "test".equals(testProps.get("t")));
- }
-
- /** Check that parsing a mandatory free argument works ok. */
- public void testParseMandatoryFreeArgumentOk() throws Exception
- {
- // Create a command line parser for a mandatory free argument.
- CommandLineParser parser = new CommandLineParser(new String[][]
- {
- { "1", "Test Option.", "test", "true" }
- });
-
- // Parse a command line with this argument set.
- Properties testProps = parser.parseCommandLine(new String[] { "test" });
-
- // Check that the resultant properties contains the correctly parsed option.
- assertTrue("The first free argument was not equal to \"test\" but was: " + testProps.get("1"),
- "test".equals(testProps.get("1")));
- }
-
- /** Check that parsing a mandatory free argument fails when no argument is specified. */
- public void testParseManadatoryFreeArgumentFailsNoArgument() throws Exception
- {
- // Create a command line parser for a mandatory free argument.
- CommandLineParser parser = new CommandLineParser(new String[][]
- {
- { "1", "Test Option.", "test", "true" }
- });
-
- // Check that parsing fails when this mandatory free argument is missing.
- boolean testPassed = false;
-
- try
- {
- // Parse a command line with this free argument not set.
- Properties testProps = parser.parseCommandLine(new String[] {});
- }
- catch (IllegalArgumentException e)
- {
- testPassed = true;
- }
-
- // Check that the resultant properties contains the correctly parsed option.
- assertTrue("IllegalArgumentException not thrown for a missing mandatory option.", testPassed);
- }
-
- /** Check that parsing a mandatory option fails when no option is set. */
- public void testParseMandatoryFailsNoOption() throws Exception
- {
- // Create a command line parser for a mandatory option.
- CommandLineParser parser = new CommandLineParser(new String[][]
- {
- { "t", "Test Option.", "test", "true" }
- });
-
- // Check that parsing fails when this mandatory option is missing.
- boolean testPassed = false;
-
- try
- {
- // Parse a command line with this option not set.
- Properties testProps = parser.parseCommandLine(new String[] {});
- }
- catch (IllegalArgumentException e)
- {
- testPassed = true;
- }
-
- // Check that the resultant properties contains the correctly parsed option.
- assertTrue("IllegalArgumentException not thrown for a missing mandatory option.", testPassed);
- }
-
- /** Check that parsing an option with no space between it and its argument works ok. */
- public void testParseOptionWithNoSpaceOk() throws Exception
- {
- // Create a command line parser for an option.
- CommandLineParser parser = new CommandLineParser(new String[][]
- {
- { "t", "Test Option.", "test" }
- });
-
- // Parse a command line with this option set with no space.
- Properties testProps = parser.parseCommandLine(new String[] { "-ttest" });
-
- // Check that the resultant properties contains the correctly parsed option.
- assertTrue("The test option was not equal to \"test\" but was: " + testProps.get("t"),
- "test".equals(testProps.get("t")));
- }
-
- /** Check that parsing an option with a space between it and its argument works ok. */
- public void testParseOptionWithSpaceOk() throws Exception
- {
- // Create a command line parser for an option.
- CommandLineParser parser = new CommandLineParser(new String[][]
- {
- { "t", "Test Option.", "test" }
- });
-
- // Parse a command line with this option set with a space.
- Properties testProps = parser.parseCommandLine(new String[] { "-t", "test" });
-
- // Check that the resultant properties contains the correctly parsed option.
- assertTrue("The test option was not equal to \"test\" but was: " + testProps.get("t"),
- "test".equals(testProps.get("t")));
- }
-
- /** Check that parsing a single flag works ok. */
- public void testParseSingleFlagOk() throws Exception
- {
- // Create a command line parser for a single flag.
- CommandLineParser parser = new CommandLineParser(new String[][]
- {
- { "t", "Test Flag." }
- });
-
- // Parse a command line with the single flag set.
- Properties testProps = parser.parseCommandLine(new String[] { "-t" });
-
- // Check that the flag is set in the parsed properties.
- assertTrue("The t flag was not \"true\", it was: " + testProps.get("t"), "true".equals(testProps.get("t")));
-
- // Reset the parser.
- parser.reset();
-
- // Parse a command line with the single flag not set.
- testProps = parser.parseCommandLine(new String[] {});
-
- // Check that the flag is cleared in the parsed properties.
- assertTrue("The t flag was not \"false\", it was: " + testProps.get("t"), "false".equals(testProps.get("t")));
- }
-
- /** Check that parsing an unknown option works when unknowns not errors. */
- public void testParseUnknownOptionOk() throws Exception
- {
- // Create a command line parser for no flags or options
- CommandLineParser parser = new CommandLineParser(new String[][] {});
-
- // Check that parsing does not fail on an unknown flag.
- try
- {
- parser.parseCommandLine(new String[] { "-t" });
- }
- catch (IllegalArgumentException e)
- {
- fail("The parser threw an IllegalArgumentException on an unknown flag when errors on unkowns is off.");
- }
- }
-
- /** Check that parsing an unknown flag fails when unknowns are to be reported as errors. */
- public void testParseUnknownFlagFailsWhenUnknownsAreErrors() throws Exception
- {
- // Create a command line parser for no flags or options
- CommandLineParser parser = new CommandLineParser(new String[][] {});
-
- // Turn on fail on unknowns mode.
- parser.setErrorsOnUnknowns(true);
-
- // Check that parsing fails on an unknown flag.
- boolean testPassed = false;
-
- try
- {
- parser.parseCommandLine(new String[] { "-t" });
- }
- catch (IllegalArgumentException e)
- {
- testPassed = true;
- }
-
- assertTrue("IllegalArgumentException not thrown for an unknown flag when errors on unknowns mode is on.",
- testPassed);
- }
-
- /** Check that parsing an unknown option fails when unknowns are to be reported as errors. */
- public void testParseUnknownOptionFailsWhenUnknownsAreErrors() throws Exception
- {
- // Create a command line parser for no flags or options
- CommandLineParser parser = new CommandLineParser(new String[][] {});
-
- // Turn on fail on unknowns mode.
- parser.setErrorsOnUnknowns(true);
-
- // Check that parsing fails on an unknown flag.
- boolean testPassed = false;
-
- try
- {
- parser.parseCommandLine(new String[] { "-t", "test" });
- }
- catch (IllegalArgumentException e)
- {
- testPassed = true;
- }
-
- assertTrue("IllegalArgumentException not thrown for an unknown option when errors on unknowns mode is on.",
- testPassed);
- }
-}
diff --git a/java/common/src/test/java/org/apache/qpid/util/FileUtilsTest.java b/java/common/src/test/java/org/apache/qpid/util/FileUtilsTest.java
deleted file mode 100644
index 7eba5f092e..0000000000
--- a/java/common/src/test/java/org/apache/qpid/util/FileUtilsTest.java
+++ /dev/null
@@ -1,612 +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.util;
-
-import junit.framework.TestCase;
-
-import java.io.BufferedWriter;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.util.List;
-
-public class FileUtilsTest extends TestCase
-{
- private static final String COPY = "-Copy";
- private static final String SUB = "-Sub";
-
- /**
- * Additional test for the copy method.
- * Ensures that the directory count did increase by more than 1 after the copy.
- */
- public void testCopyFile()
- {
- final String TEST_DATA = "FileUtilsTest-testCopy-TestDataTestDataTestDataTestDataTestDataTestData";
- String fileName = "FileUtilsTest-testCopy";
- String fileNameCopy = fileName + COPY;
-
- File[] beforeCopyFileList = null;
-
- //Create initial file
- File test = createTestFile(fileName, TEST_DATA);
-
- try
- {
- //Check number of files before copy
- beforeCopyFileList = test.getAbsoluteFile().getParentFile().listFiles();
- int beforeCopy = beforeCopyFileList.length;
-
- //Perform Copy
- File destination = new File(fileNameCopy);
- FileUtils.copy(test, destination);
- //Ensure the JVM cleans up if cleanup failues
- destination.deleteOnExit();
-
- //Retrieve counts after copy
- int afterCopy = test.getAbsoluteFile().getParentFile().listFiles().length;
-
- int afterCopyFromCopy = new File(fileNameCopy).getAbsoluteFile().getParentFile().listFiles().length;
-
- // Validate the copy counts
- assertEquals("The file listing from the original and the copy differ in length.", afterCopy, afterCopyFromCopy);
- assertEquals("The number of files did not increase.", beforeCopy + 1, afterCopy);
- assertEquals("The number of files did not increase.", beforeCopy + 1, afterCopyFromCopy);
-
- //Validate copy
- // Load content
- String copiedFileContent = FileUtils.readFileAsString(fileNameCopy);
- assertEquals(TEST_DATA, copiedFileContent);
- }
- finally // Ensure clean
- {
- //Clean up
- assertTrue("Unable to cleanup", FileUtils.deleteFile(fileNameCopy));
-
- //Check file list after cleanup
- File[] afterCleanup = new File(test.getAbsoluteFile().getParent()).listFiles();
- checkFileLists(beforeCopyFileList, afterCleanup);
-
- //Remove original file
- assertTrue("Unable to cleanup", test.delete());
- }
- }
-
- /**
- * Create and Copy the following structure:
- *
- * testDirectory --+
- * +-- testSubDirectory --+
- * +-- testSubFile
- * +-- File
- *
- * to testDirectory-Copy
- *
- * Validate that the file count in the copy is correct and contents of the copied files is correct.
- */
- public void testCopyRecursive()
- {
- final String TEST_DATA = "FileUtilsTest-testDirectoryCopy-TestDataTestDataTestDataTestDataTestDataTestData";
- String fileName = "FileUtilsTest-testCopy";
- String TEST_DIR = "testDirectoryCopy";
-
- //Create Initial Structure
- File testDir = new File(TEST_DIR);
-
- //Check number of files before copy
- File[] beforeCopyFileList = testDir.getAbsoluteFile().getParentFile().listFiles();
-
- try
- {
- //Create Directories
- assertTrue("Test directory already exists cannot test.", !testDir.exists());
-
- if (!testDir.mkdir())
- {
- fail("Unable to make test Directory");
- }
-
- File testSubDir = new File(TEST_DIR + File.separator + TEST_DIR + SUB);
- if (!testSubDir.mkdir())
- {
- fail("Unable to make test sub Directory");
- }
-
- //Create Files
- createTestFile(testDir.toString() + File.separator + fileName, TEST_DATA);
- createTestFile(testSubDir.toString() + File.separator + fileName + SUB, TEST_DATA);
-
- //Ensure the JVM cleans up if cleanup failues
- testSubDir.deleteOnExit();
- testDir.deleteOnExit();
-
- //Perform Copy
- File copyDir = new File(testDir.toString() + COPY);
- try
- {
- FileUtils.copyRecursive(testDir, copyDir);
- }
- catch (FileNotFoundException e)
- {
- fail(e.getMessage());
- }
- catch (FileUtils.UnableToCopyException e)
- {
- fail(e.getMessage());
- }
-
- //Validate Copy
- assertEquals("Copied directory should only have one file and one directory in it.", 2, copyDir.listFiles().length);
-
- //Validate Copy File Contents
- String copiedFileContent = FileUtils.readFileAsString(copyDir.toString() + File.separator + fileName);
- assertEquals(TEST_DATA, copiedFileContent);
-
- //Validate Name of Sub Directory
- assertTrue("Expected subdirectory is not a directory", new File(copyDir.toString() + File.separator + TEST_DIR + SUB).isDirectory());
-
- //Assert that it contains only one item
- assertEquals("Copied sub directory should only have one directory in it.", 1, new File(copyDir.toString() + File.separator + TEST_DIR + SUB).listFiles().length);
-
- //Validate content of Sub file
- copiedFileContent = FileUtils.readFileAsString(copyDir.toString() + File.separator + TEST_DIR + SUB + File.separator + fileName + SUB);
- assertEquals(TEST_DATA, copiedFileContent);
- }
- finally
- {
- //Clean up source and copy directory.
- assertTrue("Unable to cleanup", FileUtils.delete(testDir, true));
- assertTrue("Unable to cleanup", FileUtils.delete(new File(TEST_DIR + COPY), true));
-
- //Check file list after cleanup
- File[] afterCleanup = testDir.getAbsoluteFile().getParentFile().listFiles();
- checkFileLists(beforeCopyFileList, afterCleanup);
- }
- }
-
- /**
- * Helper method to create a test file with a string content
- *
- * @param fileName The fileName to use in the creation
- * @param test_data The data to store in the file
- *
- * @return The File reference
- */
- private File createTestFile(String fileName, String test_data)
- {
- File test = new File(fileName);
-
- try
- {
- test.createNewFile();
- //Ensure the JVM cleans up if cleanup failues
- test.deleteOnExit();
- }
- catch (IOException e)
- {
- fail(e.getMessage());
- }
-
- BufferedWriter writer = null;
- try
- {
- writer = new BufferedWriter(new FileWriter(test));
- try
- {
- writer.write(test_data);
- }
- catch (IOException e)
- {
- fail(e.getMessage());
- }
- }
- catch (IOException e)
- {
- fail(e.getMessage());
- }
- finally
- {
- try
- {
- if (writer != null)
- {
- writer.close();
- }
- }
- catch (IOException e)
- {
- fail(e.getMessage());
- }
- }
-
- return test;
- }
-
- /** Test that deleteFile only deletes the specified file */
- public void testDeleteFile()
- {
- File test = new File("FileUtilsTest-testDelete");
- //Record file count in parent directory to check it is not changed by delete
- String path = test.getAbsolutePath();
- File[] filesBefore = new File(path.substring(0, path.lastIndexOf(File.separator))).listFiles();
- int fileCountBefore = filesBefore.length;
-
- try
- {
- test.createNewFile();
- //Ensure the JVM cleans up if cleanup failues
- test.deleteOnExit();
- }
- catch (IOException e)
- {
- fail(e.getMessage());
- }
-
- assertTrue("File does not exists", test.exists());
- assertTrue("File is not a file", test.isFile());
-
- //Check that file creation can be seen on disk
- int fileCountCreated = new File(path.substring(0, path.lastIndexOf(File.separator))).listFiles().length;
- assertEquals("File creation was no registered", fileCountBefore + 1, fileCountCreated);
-
- //Perform Delete
- assertTrue("Unable to cleanup", FileUtils.deleteFile("FileUtilsTest-testDelete"));
-
- assertTrue("File exists after delete", !test.exists());
-
- //Check that after deletion the file count is now accurate
- File[] filesAfter = new File(path.substring(0, path.lastIndexOf(File.separator))).listFiles();
- int fileCountAfter = filesAfter.length;
- assertEquals("File creation was no registered", fileCountBefore, fileCountAfter);
-
- checkFileLists(filesBefore, filesAfter);
- }
-
- public void testDeleteNonExistentFile()
- {
- File test = new File("FileUtilsTest-testDelete-" + System.currentTimeMillis());
-
- assertTrue("File exists", !test.exists());
- assertFalse("File is a directory", test.isDirectory());
-
- assertTrue("Delete Succeeded ", !FileUtils.delete(test, true));
- }
-
- public void testDeleteNull()
- {
- try
- {
- FileUtils.delete(null, true);
- fail("Delete with null value should throw NPE.");
- }
- catch (NullPointerException npe)
- {
- // expected path
- }
- }
-
- /**
- * Given two lists of File arrays ensure they are the same length and all entries in Before are in After
- *
- * @param filesBefore File[]
- * @param filesAfter File[]
- */
- private void checkFileLists(File[] filesBefore, File[] filesAfter)
- {
- assertNotNull("Before file list cannot be null", filesBefore);
- assertNotNull("After file list cannot be null", filesAfter);
-
- assertEquals("File lists are unequal", filesBefore.length, filesAfter.length);
-
- for (File fileBefore : filesBefore)
- {
- boolean found = false;
-
- for (File fileAfter : filesAfter)
- {
- if (fileBefore.getAbsolutePath().equals(fileAfter.getAbsolutePath()))
- {
- found = true;
- break;
- }
- }
-
- assertTrue("File'" + fileBefore.getName() + "' was not in directory afterwards", found);
- }
- }
-
- public void testNonRecursiveNonEmptyDirectoryDeleteFails()
- {
- String directoryName = "FileUtilsTest-testRecursiveDelete";
- File test = new File(directoryName);
-
- //Record file count in parent directory to check it is not changed by delete
- String path = test.getAbsolutePath();
- File[] filesBefore = new File(path.substring(0, path.lastIndexOf(File.separator))).listFiles();
- int fileCountBefore = filesBefore.length;
-
- assertTrue("Directory exists", !test.exists());
-
- test.mkdir();
-
- //Create a file in the directory
- String fileName = test.getAbsolutePath() + File.separatorChar + "testFile";
- File subFile = new File(fileName);
- try
- {
- subFile.createNewFile();
- //Ensure the JVM cleans up if cleanup failues
- subFile.deleteOnExit();
- }
- catch (IOException e)
- {
- fail(e.getMessage());
- }
- //Ensure the JVM cleans up if cleanup failues
- // This must be after the subFile as the directory must be empty before
- // the delete is performed
- test.deleteOnExit();
-
- //Try and delete the non-empty directory
- assertFalse("Non Empty Directory was successfully deleted.", FileUtils.deleteDirectory(directoryName));
-
- //Check directory is still there
- assertTrue("Directory was deleted.", test.exists());
-
- // Clean up
- assertTrue("Unable to cleanup", FileUtils.delete(test, true));
-
- //Check that after deletion the file count is now accurate
- File[] filesAfter = new File(path.substring(0, path.lastIndexOf(File.separator))).listFiles();
- int fileCountAfter = filesAfter.length;
- assertEquals("File creation was no registered", fileCountBefore, fileCountAfter);
-
- checkFileLists(filesBefore, filesAfter);
- }
-
- /** Test that an empty directory can be deleted with deleteDirectory */
- public void testEmptyDirectoryDelete()
- {
- String directoryName = "FileUtilsTest-testRecursiveDelete";
- File test = new File(directoryName);
-
- //Record file count in parent directory to check it is not changed by delete
- String path = test.getAbsolutePath();
- File[] filesBefore = new File(path.substring(0, path.lastIndexOf(File.separator))).listFiles();
- int fileCountBefore = filesBefore.length;
-
- assertTrue("Directory exists", !test.exists());
-
- test.mkdir();
- //Ensure the JVM cleans up if cleanup failues
- test.deleteOnExit();
-
- //Try and delete the empty directory
- assertTrue("Non Empty Directory was successfully deleted.", FileUtils.deleteDirectory(directoryName));
-
- //Check directory is still there
- assertTrue("Directory was deleted.", !test.exists());
-
- //Check that after deletion the file count is now accurate
- File[] filesAfter = new File(path.substring(0, path.lastIndexOf(File.separator))).listFiles();
- int fileCountAfter = filesAfter.length;
- assertEquals("File creation was no registered", fileCountBefore, fileCountAfter);
-
- checkFileLists(filesBefore, filesAfter);
-
- }
-
- /** Test that deleteDirectory on a non empty directory to complete */
- public void testNonEmptyDirectoryDelete()
- {
- String directoryName = "FileUtilsTest-testRecursiveDelete";
- File test = new File(directoryName);
-
- assertTrue("Directory exists", !test.exists());
-
- //Record file count in parent directory to check it is not changed by delete
- String path = test.getAbsolutePath();
- File[] filesBefore = new File(path.substring(0, path.lastIndexOf(File.separator))).listFiles();
- int fileCountBefore = filesBefore.length;
-
- test.mkdir();
-
- //Create a file in the directory
- String fileName = test.getAbsolutePath() + File.separatorChar + "testFile";
- File subFile = new File(fileName);
- try
- {
- subFile.createNewFile();
- //Ensure the JVM cleans up if cleanup failues
- subFile.deleteOnExit();
- }
- catch (IOException e)
- {
- fail(e.getMessage());
- }
-
- // Ensure the JVM cleans up if cleanup failues
- // This must be after the subFile as the directory must be empty before
- // the delete is performed
- test.deleteOnExit();
-
- //Try and delete the non-empty directory non-recursively
- assertFalse("Non Empty Directory was successfully deleted.", FileUtils.delete(test, false));
-
- //Check directory is still there
- assertTrue("Directory was deleted.", test.exists());
-
- // Clean up
- assertTrue("Unable to cleanup", FileUtils.delete(test, true));
-
- //Check that after deletion the file count is now accurate
- File[] filesAfter = new File(path.substring(0, path.lastIndexOf(File.separator))).listFiles();
- int fileCountAfter = filesAfter.length;
- assertEquals("File creation was no registered", fileCountBefore, fileCountAfter);
-
- checkFileLists(filesBefore, filesAfter);
-
- }
-
- /** Test that a recursive delete successeds */
- public void testRecursiveDelete()
- {
- String directoryName = "FileUtilsTest-testRecursiveDelete";
- File test = new File(directoryName);
-
- assertTrue("Directory exists", !test.exists());
-
- //Record file count in parent directory to check it is not changed by delete
- String path = test.getAbsolutePath();
- File[] filesBefore = new File(path.substring(0, path.lastIndexOf(File.separator))).listFiles();
- int fileCountBefore = filesBefore.length;
-
- test.mkdir();
-
- createSubDir(directoryName, 2, 4);
-
- //Ensure the JVM cleans up if cleanup failues
- // This must be after the sub dir creation as the delete order is
- // recorded and the directory must be empty to be deleted.
- test.deleteOnExit();
-
- assertFalse("Non recursive delete was able to directory", FileUtils.delete(test, false));
-
- assertTrue("File does not exist after non recursive delete", test.exists());
-
- assertTrue("Unable to cleanup", FileUtils.delete(test, true));
-
- assertTrue("File exist after recursive delete", !test.exists());
-
- //Check that after deletion the file count is now accurate
- File[] filesAfter = new File(path.substring(0, path.lastIndexOf(File.separator))).listFiles();
- int fileCountAfter = filesAfter.length;
- assertEquals("File creation was no registered", fileCountBefore, fileCountAfter);
-
- checkFileLists(filesBefore, filesAfter);
-
- }
-
- private void createSubDir(String path, int directories, int files)
- {
- File directory = new File(path);
-
- assertTrue("Directory" + path + " does not exists", directory.exists());
-
- for (int dir = 0; dir < directories; dir++)
- {
- String subDirName = path + File.separatorChar + "sub" + dir;
- File subDir = new File(subDirName);
-
- subDir.mkdir();
-
- createSubDir(subDirName, directories - 1, files);
- //Ensure the JVM cleans up if cleanup failues
- // This must be after the sub dir creation as the delete order is
- // recorded and the directory must be empty to be deleted.
- subDir.deleteOnExit();
- }
-
- for (int file = 0; file < files; file++)
- {
- String subDirName = path + File.separatorChar + "file" + file;
- File subFile = new File(subDirName);
- try
- {
- subFile.createNewFile();
- //Ensure the JVM cleans up if cleanup failues
- subFile.deleteOnExit();
- }
- catch (IOException e)
- {
- fail(e.getMessage());
- }
- }
- }
-
- public static final String SEARCH_STRING = "testSearch";
-
- /**
- * Test searchFile(File file, String search) will find a match when it
- * exists.
- *
- * @throws java.io.IOException if unable to perform test setup
- */
- public void testSearchSucceed() throws IOException
- {
- File _logfile = File.createTempFile("FileUtilsTest-testSearchSucceed", ".out");
-
- prepareFileForSearchTest(_logfile);
-
- List<String> results = FileUtils.searchFile(_logfile, SEARCH_STRING);
-
- assertNotNull("Null result set returned", results);
-
- assertEquals("Results do not contain expected count", 1, results.size());
- }
-
- /**
- * Test searchFile(File file, String search) will not find a match when the
- * test string does not exist.
- *
- * @throws java.io.IOException if unable to perform test setup
- */
- public void testSearchFail() throws IOException
- {
- File _logfile = File.createTempFile("FileUtilsTest-testSearchFail", ".out");
-
- prepareFileForSearchTest(_logfile);
-
- List<String> results = FileUtils.searchFile(_logfile, "Hello");
-
- assertNotNull("Null result set returned", results);
-
- //Validate we only got one message
- if (results.size() > 0)
- {
- System.err.println("Unexpected messages");
-
- for (String msg : results)
- {
- System.err.println(msg);
- }
- }
-
- assertEquals("Results contains data when it was not expected",
- 0, results.size());
- }
-
- /**
- * Write the SEARCH_STRING in to the given file.
- *
- * @param logfile The file to write the SEARCH_STRING into
- *
- * @throws IOException if an error occurs
- */
- private void prepareFileForSearchTest(File logfile) throws IOException
- {
- BufferedWriter writer = new BufferedWriter(new FileWriter(logfile));
- writer.append(SEARCH_STRING);
- writer.flush();
- writer.close();
- }
-
-}
diff --git a/java/common/src/test/java/org/apache/qpid/util/PropertyUtilsTest.java b/java/common/src/test/java/org/apache/qpid/util/PropertyUtilsTest.java
deleted file mode 100644
index 9fd18d461a..0000000000
--- a/java/common/src/test/java/org/apache/qpid/util/PropertyUtilsTest.java
+++ /dev/null
@@ -1,48 +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.util;
-
-import org.apache.qpid.configuration.PropertyException;
-import org.apache.qpid.configuration.PropertyUtils;
-import org.apache.qpid.test.utils.QpidTestCase;
-
-public class PropertyUtilsTest extends QpidTestCase
-{
- public void testSimpleExpansion() throws PropertyException
- {
- System.setProperty("banana", "fruity");
- String expandedProperty = PropertyUtils.replaceProperties("${banana}");
- assertEquals(expandedProperty, "fruity");
- }
-
- public void testDualExpansion() throws PropertyException
- {
- System.setProperty("banana", "fruity");
- System.setProperty("concrete", "horrible");
- String expandedProperty = PropertyUtils.replaceProperties("${banana}xyz${concrete}");
- assertEquals(expandedProperty, "fruityxyzhorrible");
- }
-
- public static junit.framework.Test suite()
- {
- return new junit.framework.TestSuite(PropertyUtilsTest.class);
- }
-}
diff --git a/java/common/src/test/java/org/apache/qpid/util/SerialTest.java b/java/common/src/test/java/org/apache/qpid/util/SerialTest.java
deleted file mode 100644
index b2578563e0..0000000000
--- a/java/common/src/test/java/org/apache/qpid/util/SerialTest.java
+++ /dev/null
@@ -1,82 +0,0 @@
-package org.apache.qpid.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.
- *
- */
-
-
-import junit.framework.TestCase;
-
-import java.util.Random;
-
-import org.apache.qpid.SerialException;
-
-/**
- *Junit tests for the Serial class
- */
-public class SerialTest extends TestCase
-{
-
- /**
- * Test the key boundaries where wraparound occurs.
- */
- public void testBoundaries()
- {
- assertTrue(Serial.gt(1, 0));
- assertTrue(Serial.lt(0, 1));
-
- assertTrue(Serial.gt(Integer.MAX_VALUE+1, Integer.MAX_VALUE));
- assertTrue(Serial.lt(Integer.MAX_VALUE, Integer.MAX_VALUE+1));
-
- assertTrue(Serial.gt(0xFFFFFFFF + 1, 0xFFFFFFFF));
- assertTrue(Serial.lt(0xFFFFFFFF, 0xFFFFFFFF + 1));
- }
-
- /**
- * Test the first Corollary of RFC 1982
- * For any sequence number s and any integer n such that addition of n
- * to s is well defined, (s + n) >= s. Further (s + n) == s only when
- * n == 0, in all other defined cases, (s + n) > s.
- */
- public void testCorollary1()
- {
- int wrapcount = 0;
-
- int s = 0;
-
- for (int i = 0; i < 67108664; i++)
- {
- for (int n = 1; n < 4096; n += 512)
- {
- assertTrue(Serial.gt(s+n, s));
- assertTrue(Serial.lt(s, s+n));
- }
-
- s += 1024;
-
- if (s == 0)
- {
- wrapcount += 1;
- }
- }
-
- assertTrue(wrapcount > 0);
- }
-
-}
diff --git a/java/common/templates/method/MethodBodyInterface.vm b/java/common/templates/method/MethodBodyInterface.vm
deleted file mode 100644
index d5feba12de..0000000000
--- a/java/common/templates/method/MethodBodyInterface.vm
+++ /dev/null
@@ -1,62 +0,0 @@
-#macro( UpperCamel $name )
-#set( $name = "${name.substring(0,1).toUpperCase()}${name.substring(1)}" )
-#end
-#macro( toUpperCamel $name )${name.substring(0,1).toUpperCase()}${name.substring(1)}#end
-
-
-
-#set( $amqp_ClassName = $amqpClass.Name)
-#UpperCamel( $amqp_ClassName )
-#set( $amqp_MethodName = $amqpMethod.Name )
-#UpperCamel( $amqp_MethodName )
-#set( $javaClassName = "${amqp_ClassName}${amqp_MethodName}Body" )
-
-
-#set( $filename = "${javaClassName}.java")
-/*
- *
- * 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 ${generator} - do not modify.
- * Supported AMQP version:
- #foreach( $supportedVersion in $model.VersionSet )
- * $supportedVersion.getMajor()-$supportedVersion.getMinor()
- #end
- */
-
-
-package org.apache.qpid.framing;
-
-
-public interface ${javaClassName} extends EncodableAMQDataBlock, AMQMethodBody
-{
-
-
-#foreach( $field in $amqpMethod.Fields )
-
-#if( $amqpMethod.isCommon( $field ) )
- public $field.ConsistentNativeType get#toUpperCamel( ${field.Name} )();
-#end
-#end
-
-
-
-}
diff --git a/java/common/templates/method/version/MethodBodyClass.vm b/java/common/templates/method/version/MethodBodyClass.vm
deleted file mode 100644
index a739110d70..0000000000
--- a/java/common/templates/method/version/MethodBodyClass.vm
+++ /dev/null
@@ -1,213 +0,0 @@
-#macro( UpperCamel $name )
-#set( $name = "${name.substring(0,1).toUpperCase()}${name.substring(1)}" )
-#end
-#macro( toUpperCamel $name )${name.substring(0,1).toUpperCase()}${name.substring(1)}#end
-
-
-
-#set( $amqp_ClassName = $amqpClass.Name)
-#UpperCamel( $amqp_ClassName )
-#set( $amqp_MethodName = $amqpMethod.Name )
-#UpperCamel( $amqp_MethodName )
-#set( $javaClassName = "${amqp_ClassName}${amqp_MethodName}BodyImpl" )
-#set( $interfaceName = "${amqp_ClassName}${amqp_MethodName}Body" )
-#set( $amqpPackageName = "amqp_$version.getMajor()_$version.getMinor()" )
-
-#set( $filename = "${amqpPackageName}/${javaClassName}.java")
-/*
- *
- * 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 ${generator} - do not modify.
- * Supported AMQP version:
- * $version.getMajor()-$version.getMinor()
- */
-
-#set( $clazz = $amqpClass.asSingleVersionClass( $version ) )
-#set( $method = $amqpMethod.asSingleVersionMethod( $version ) )
-
-package org.apache.qpid.framing.amqp_$version.getMajor()_$version.getMinor();
-
-import java.util.HashMap;
-
-import org.apache.mina.common.ByteBuffer;
-import org.apache.qpid.framing.*;
-import org.apache.qpid.AMQException;
-
-public class ${javaClassName} extends AMQMethodBody_$version.getMajor()_$version.getMinor() implements $interfaceName
-{
- private static final AMQMethodBodyInstanceFactory FACTORY_INSTANCE = new AMQMethodBodyInstanceFactory()
- {
- public AMQMethodBody newInstance(ByteBuffer in, long size) throws AMQFrameDecodingException
- {
- return new ${javaClassName}(in);
- }
-
-
- };
-
-
- public static AMQMethodBodyInstanceFactory getFactory()
- {
- return FACTORY_INSTANCE;
- }
-
- public static final int CLASS_ID = $clazz.ClassId;
-
- public static final int METHOD_ID = $method.MethodId;
-
-
-
- // Fields declared in specification
-#foreach( $field in $method.ConsolidatedFields )
- private final $field.NativeType _$field.getName(); // $field.UnderlyingFields
-#end
-
-
- // Constructor
-
- public ${javaClassName}(ByteBuffer buffer) throws AMQFrameDecodingException
- {
-#foreach( $field in $method.ConsolidatedFields )
- _$field.Name = read$field.getEncodingType()( buffer );
-#end
- }
-
- public ${javaClassName}(
-#foreach( $field in $method.FieldList )
-#if( $velocityCount == $method.getFieldList().size() )
- $field.NativeType $field.Name
-#else
- $field.NativeType $field.Name,
-#end
-#end
- )
- {
-#set( $consolidatedFieldName = "" )
-#foreach( $field in $method.FieldList )
-#if( $method.isConsolidated( $field.Name ) )
-#if( !$method.getConsolidatedFieldName( $field.Name ).equals( $consolidatedFieldName ) )
-#if( !$consolidatedFieldName.equals("") )
- _$consolidatedFieldName = $consolidatedFieldName; // 1
-#end
-#set( $consolidatedFieldName = $method.getConsolidatedFieldName( $field.Name ) )
- byte $consolidatedFieldName = (byte)0;
-#end
- if( $field.Name )
- {
- $consolidatedFieldName = (byte) (((int) $consolidatedFieldName) | (1 << $method.getPositionInBitField( $field.Name )));
- }
-#if( $velocityCount == $method.getFieldList().size())
- _$consolidatedFieldName = $consolidatedFieldName;
-#else
-
-#end
-#else
-#if( !$consolidatedFieldName.equals("") )
- _$consolidatedFieldName = $consolidatedFieldName;
-#end
-#set( $consolidatedFieldName = "" )
- _$field.Name = $field.Name;
-#end
-#end
- }
-
- public int getClazz()
- {
- return CLASS_ID;
- }
-
- public int getMethod()
- {
- return METHOD_ID;
- }
-
-
-#foreach( $field in $method.FieldList )
- public final $field.NativeType get#toUpperCamel( ${field.Name} )()
- {
-#if( $method.isConsolidated( $field.Name ) )
- return (((int)(_$method.getConsolidatedFieldName( $field.Name ))) & ( 1 << $method.getPositionInBitField( $field.Name ))) != 0;
-#else
- return _$field.Name;
-#end
- }
-#end
-
- protected int getBodySize()
- {
-#set( $fixedSize = 0 )
-#foreach( $field in $method.ConsolidatedFields )
-#if( $field.isFixedSize() )
-#set( $fixedSize = $fixedSize + $field.Size )
-#end
-#end
- int size = $fixedSize;
-#foreach( $field in $method.ConsolidatedFields )
-#if( ! $field.isFixedSize() )
- size += getSizeOf( _$field.Name );
-#end
-#end
- return size;
- }
-
- public void writeMethodPayload(ByteBuffer buffer)
- {
-#foreach( $field in $method.ConsolidatedFields )
- write$field.getEncodingType()( buffer, _$field.Name );
-#end
- }
-
- public boolean execute(MethodDispatcher dispatcher, int channelId) throws AMQException
- {
-#set( $amqpMethodNameFirstChar = $amqpMethod.getName().substring(0,1) )
-#set( $amqpMethodNameFirstCharU = $amqpMethodNameFirstChar.toUpperCase() )
-#set( $amqpMethodNameUpperCamel = "$amqpMethodNameFirstCharU$amqpMethod.getName().substring(1)" )
-#if( $amqpMethod.inAllVersions() )
- return dispatcher.dispatch${amqpClassNameUpperCamel}${amqpMethodNameUpperCamel}(this, channelId);
-#else
- return ((MethodDispatcher_$version.getMajor()_$version.getMinor())dispatcher).dispatch${amqp_ClassName}${amqpMethodNameUpperCamel}(this, channelId);
-
-#end
-
- }
-
-
- public String toString()
- {
- StringBuilder buf = new StringBuilder("[$javaClassName: ");
-#foreach( $field in $method.FieldList )
- buf.append( "$field.Name=" );
-#if( $field.NativeType == "byte[]" )
- buf.append( get#toUpperCamel( $field.Name )() == null ? "null" : java.util.Arrays.toString( get#toUpperCamel( $field.Name )() ) );
-#else
- buf.append( get#toUpperCamel( $field.Name )() );
-#end
-#if( $velocityCount != $method.FieldList.size() )
- buf.append( ", " );
-#end
-#end
- buf.append("]");
- return buf.toString();
- }
-
-
-}
diff --git a/java/common/templates/model/ClientMethodDispatcherInterface.vm b/java/common/templates/model/ClientMethodDispatcherInterface.vm
deleted file mode 100644
index 9e4aee7dee..0000000000
--- a/java/common/templates/model/ClientMethodDispatcherInterface.vm
+++ /dev/null
@@ -1,56 +0,0 @@
-#set( $filename = "ClientMethodDispatcher.java")
-/*
- *
- * 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 $generator - do not modify.
- * Supported AMQP version:
- #foreach( $supportedVersion in $model.VersionSet )
- * $supportedVersion.getMajor()-$supportedVersion.getMinor()
- #end
- */
-
-package org.apache.qpid.framing;
-
-import org.apache.qpid.AMQException;
-
-
-public interface ClientMethodDispatcher
-{
-
-#foreach( $amqpClass in $model.getClasses() )
-#set( $amqpClassNameFirstChar = $amqpClass.getName().substring(0,1) )
-#set( $amqpClassNameFirstCharU = $amqpClassNameFirstChar.toUpperCase() )
-#set( $amqpClassNameUpperCamel = "$amqpClassNameFirstCharU$amqpClass.getName().substring(1)" )
-#foreach( $amqpMethodVersions in $amqpClass.getMethods() )
-#if( $amqpMethodVersions.inAllVersions() )
-#set( $amqpMethod = $amqpMethodVersions.asSingleVersionMethod($amqpMethodVersions.getVersionSet().first()) )
-#if( $amqpMethod.isClientMethod() )
-#set( $amqpMethodNameFirstChar = $amqpMethod.getName().substring(0,1) )
-#set( $amqpMethodNameFirstCharU = $amqpMethodNameFirstChar.toUpperCase() )
-#set( $amqpMethodNameUpperCamel = "$amqpMethodNameFirstCharU$amqpMethod.getName().substring(1)" )
- public boolean dispatch${amqpClassNameUpperCamel}${amqpMethodNameUpperCamel}(${amqpClassNameUpperCamel}${amqpMethodNameUpperCamel}Body body, int channelId) throws AMQException;
-#end
-#end
-#end
-#end
-
-} \ No newline at end of file
diff --git a/java/common/templates/model/MethodDispatcherInterface.vm b/java/common/templates/model/MethodDispatcherInterface.vm
deleted file mode 100644
index ff14715fef..0000000000
--- a/java/common/templates/model/MethodDispatcherInterface.vm
+++ /dev/null
@@ -1,39 +0,0 @@
-#set( $filename = "MethodDispatcher.java")
-/*
- *
- * 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 $generator - do not modify.
- * Supported AMQP version:
- #foreach( $supportedVersion in $model.VersionSet )
- * $supportedVersion.getMajor()-$supportedVersion.getMinor()
- #end
- */
-
-package org.apache.qpid.framing;
-
-import org.apache.qpid.AMQException;
-
-
-public interface MethodDispatcher extends
- ClientMethodDispatcher, ServerMethodDispatcher
-{
-} \ No newline at end of file
diff --git a/java/common/templates/model/MethodRegistryClass.vm b/java/common/templates/model/MethodRegistryClass.vm
deleted file mode 100644
index 759e5e4a42..0000000000
--- a/java/common/templates/model/MethodRegistryClass.vm
+++ /dev/null
@@ -1,104 +0,0 @@
-#set( $filename = "MethodRegistry.java")
-/*
- *
- * 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 $generator - do not modify.
- * Supported AMQP version:
- #foreach( $supportedVersion in $model.VersionSet )
- * $supportedVersion.getMajor()-$supportedVersion.getMinor()
- #end
- */
-
-package org.apache.qpid.framing;
-
-import org.apache.mina.common.ByteBuffer;
-
-import org.apache.qpid.framing.abstraction.ProtocolVersionMethodConverter;
-
-import java.util.Map;
-import java.util.HashMap;
-
-
-public abstract class MethodRegistry
-{
- private static final Map<ProtocolVersion, MethodRegistry> _registries =
- new HashMap<ProtocolVersion, MethodRegistry>();
-
-#foreach( $supportedVersion in $model.VersionSet )
-
-#set( $verName = "_$supportedVersion.getMajor()_$supportedVersion.getMinor()" )
-#set( $regPackage = "org.apache.qpid.framing.amqp$verName" )
- public static final MethodRegistry registry_$supportedVersion.getMajor()_$supportedVersion.getMinor() =
- new ${regPackage}.MethodRegistry${verName}();
-
-#end
-
-
- public abstract AMQMethodBody convertToBody(ByteBuffer in, long size)
- throws AMQFrameDecodingException;
-
- public abstract int getMaxClassId();
-
- public abstract int getMaxMethodId(int classId);
-
-
- protected MethodRegistry(ProtocolVersion pv)
- {
- _registries.put(pv, this);
- }
-
- public static MethodRegistry getMethodRegistry(ProtocolVersion pv)
- {
- return _registries.get(pv);
- }
-
-#foreach( $amqpClass in $model.getClasses() )
-#set( $amqpClassNameFirstChar = $amqpClass.getName().substring(0,1) )
-#set( $amqpClassNameFirstCharU = $amqpClassNameFirstChar.toUpperCase() )
-#set( $amqpClassNameUpperCamel = "$amqpClassNameFirstCharU$amqpClass.getName().substring(1)" )
-
-#foreach( $amqpMethodVersions in $amqpClass.getMethods() )
-#if( $amqpMethodVersions.isVersionInterfaceConsistent() )
-#set( $amqpMethod = $amqpMethodVersions.asSingleVersionMethod($amqpMethodVersions.getVersionSet().first()) )
-
-#set( $amqpMethodNameFirstChar = $amqpMethod.getName().substring(0,1) )
-#set( $amqpMethodNameFirstCharU = $amqpMethodNameFirstChar.toUpperCase() )
-#set( $amqpMethodNameUpperCamel = "$amqpMethodNameFirstCharU$amqpMethod.getName().substring(1)" )
- public abstract ${amqpClassNameUpperCamel}${amqpMethodNameUpperCamel}Body create${amqpClassNameUpperCamel}${amqpMethodNameUpperCamel}Body(
-#foreach( $field in $amqpMethod.FieldList )
-#if( $velocityCount == $amqpMethod.getFieldList().size() )
- final $field.NativeType $field.Name
-#else
- final $field.NativeType $field.Name,
-#end
-#end
- );
-
-
-#end
-#end
-#end
-
-
- public abstract ProtocolVersionMethodConverter getProtocolVersionMethodConverter();
-
-} \ No newline at end of file
diff --git a/java/common/templates/model/ProtocolVersionListClass.vm b/java/common/templates/model/ProtocolVersionListClass.vm
deleted file mode 100644
index 78605c70ff..0000000000
--- a/java/common/templates/model/ProtocolVersionListClass.vm
+++ /dev/null
@@ -1,201 +0,0 @@
-#set( $filename = "ProtocolVersion.java" )
-/*
-*
-* 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 $generator - do not modify.
-* Supported AMQP versions:
-#foreach( $version in $model.getVersionSet() )
-* $version.getMajor()-$version.getMinor()
-#end
-*/
-
-package org.apache.qpid.framing;
-
-import java.util.SortedSet;
-import java.util.Collections;
-import java.util.TreeSet;
-import java.util.Map;
-import java.util.HashMap;
-
-
-public class ProtocolVersion implements Comparable
-{
- private final byte _majorVersion;
- private final byte _minorVersion;
- private final String _stringFormat;
-
-
- public ProtocolVersion(byte majorVersion, byte minorVersion)
- {
- _majorVersion = majorVersion;
- _minorVersion = minorVersion;
- _stringFormat = _majorVersion+"-"+_minorVersion;
- }
-
- public byte getMajorVersion()
- {
- return _majorVersion;
- }
-
- public byte getMinorVersion()
- {
- return _minorVersion;
- }
-
- public byte getActualMinorVersion()
- {
- return _minorVersion > 90 ? (byte) (_minorVersion / 10) : _minorVersion;
- }
-
-
- public byte getRevisionVersion()
- {
- return _minorVersion > 90 ? (byte) (_minorVersion % 10) : (byte) 0;
- }
-
- public String toString()
- {
- return _stringFormat;
- }
-
-
- public int compareTo(Object o)
- {
- ProtocolVersion pv = (ProtocolVersion) o;
-
- /*
- * 0-8 has it's major and minor numbers the wrong way round (it's actually 8-0)...
- * so we need to deal with that case specially
- */
-
- if((_majorVersion == (byte) 8) && (_minorVersion == (byte) 0))
- {
- ProtocolVersion fixedThis = new ProtocolVersion(_minorVersion, _majorVersion);
- return fixedThis.compareTo(pv);
- }
-
- if((pv.getMajorVersion() == (byte) 8) && (pv.getMinorVersion() == (byte) 0))
- {
- ProtocolVersion fixedOther = new ProtocolVersion(pv.getMinorVersion(), pv.getMajorVersion());
- return this.compareTo(fixedOther);
- }
-
- if(_majorVersion > pv.getMajorVersion())
- {
- return 1;
- }
- else if(_majorVersion < pv.getMajorVersion())
- {
- return -1;
- }
- else if(_minorVersion > pv.getMinorVersion())
- {
- return 1;
- }
- else if(getMinorVersion() < pv.getMinorVersion())
- {
- return -1;
- }
- else
- {
- return 0;
- }
-
- }
-
- public boolean equals(Object o)
- {
- return o != null && (o == this || (compareTo(o) == 0));
- }
-
- public int hashCode()
- {
- return (0xFF & (int)_minorVersion) | ((0xFF & (int)_majorVersion) << 8);
- }
-
-
- public boolean isSupported()
- {
- return _supportedVersions.contains(this);
- }
-
- public static ProtocolVersion getLatestSupportedVersion()
- {
- return _supportedVersions.last();
- }
-
- private static final SortedSet<ProtocolVersion> _supportedVersions;
- private static final Map<String, ProtocolVersion> _nameToVersionMap =
- new HashMap<String, ProtocolVersion>();
- private static final ProtocolVersion _defaultVersion;
-
-
- public static final ProtocolVersion v0_10 = new ProtocolVersion((byte)0,(byte)10);
-
-#foreach( $version in $model.getVersionSet() )
-#set( $versionId = "v$version.getMajor()_$version.getMinor()" )
- public static final ProtocolVersion $versionId = new ProtocolVersion((byte)$version.getMajor(),(byte)$version.getMinor());
-#end
-
-
- static
- {
- SortedSet<ProtocolVersion> versions = new TreeSet<ProtocolVersion>();
-
- versions.add(v0_10);
- _nameToVersionMap.put("0-10", v0_10);
-#foreach( $version in $model.getVersionSet() )
-#set( $versionId = "v$version.getMajor()_$version.getMinor()" )
- versions.add($versionId);
- _nameToVersionMap.put("${version.getMajor()}-${version.getMinor()}", $versionId);
-#end
- _supportedVersions = Collections.unmodifiableSortedSet(versions);
-
-
- ProtocolVersion systemDefinedVersion =
- _nameToVersionMap.get(System.getProperty("org.apache.qpid.amqp_version"));
-
- _defaultVersion = (systemDefinedVersion == null)
- ? getLatestSupportedVersion()
- : systemDefinedVersion;
- }
-
-
- public static SortedSet<ProtocolVersion> getSupportedProtocolVersions()
- {
- return _supportedVersions;
- }
-
-
-
- public static ProtocolVersion parse(String name)
- {
- return _nameToVersionMap.get(name);
- }
-
- public static ProtocolVersion defaultProtocolVersion()
- {
- return _defaultVersion;
- }
-
-
-}
diff --git a/java/common/templates/model/ServerMethodDispatcherInterface.vm b/java/common/templates/model/ServerMethodDispatcherInterface.vm
deleted file mode 100644
index b80d6027b7..0000000000
--- a/java/common/templates/model/ServerMethodDispatcherInterface.vm
+++ /dev/null
@@ -1,56 +0,0 @@
-#set( $filename = "ServerMethodDispatcher.java")
-/*
- *
- * 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 $generator - do not modify.
- * Supported AMQP version:
- #foreach( $supportedVersion in $model.VersionSet )
- * $supportedVersion.getMajor()-$supportedVersion.getMinor()
- #end
- */
-
-package org.apache.qpid.framing;
-
-import org.apache.qpid.AMQException;
-
-
-public interface ServerMethodDispatcher
-{
-
-#foreach( $amqpClass in $model.getClasses() )
-#set( $amqpClassNameFirstChar = $amqpClass.getName().substring(0,1) )
-#set( $amqpClassNameFirstCharU = $amqpClassNameFirstChar.toUpperCase() )
-#set( $amqpClassNameUpperCamel = "$amqpClassNameFirstCharU$amqpClass.getName().substring(1)" )
-#foreach( $amqpMethodVersions in $amqpClass.getMethods() )
-#if( $amqpMethodVersions.inAllVersions() )
-#set( $amqpMethod = $amqpMethodVersions.asSingleVersionMethod($amqpMethodVersions.getVersionSet().first()) )
-#if( $amqpMethod.isServerMethod() )
-#set( $amqpMethodNameFirstChar = $amqpMethod.getName().substring(0,1) )
-#set( $amqpMethodNameFirstCharU = $amqpMethodNameFirstChar.toUpperCase() )
-#set( $amqpMethodNameUpperCamel = "$amqpMethodNameFirstCharU$amqpMethod.getName().substring(1)" )
- public boolean dispatch${amqpClassNameUpperCamel}${amqpMethodNameUpperCamel}(${amqpClassNameUpperCamel}${amqpMethodNameUpperCamel}Body body, int channelId) throws AMQException;
-#end
-#end
-#end
-#end
-
-} \ No newline at end of file
diff --git a/java/common/templates/model/version/AmqpConstantsClass.vm b/java/common/templates/model/version/AmqpConstantsClass.vm
deleted file mode 100644
index 8d459f2977..0000000000
--- a/java/common/templates/model/version/AmqpConstantsClass.vm
+++ /dev/null
@@ -1,37 +0,0 @@
-&{AmqpConstants.java}
-/*
- *
- * 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 ${GENERATOR} - do not modify.
- * Supported AMQP versions:
-%{VLIST} * ${major}-${minor}
- */
-
-package org.apache.qpid.framing;
-
-class AmqpConstants
-{
- // Constant getValue methods
-
-%{TLIST} ${const_get_method}
-
-}
diff --git a/java/common/templates/model/version/ClientMethodDispatcherInterface.vm b/java/common/templates/model/version/ClientMethodDispatcherInterface.vm
deleted file mode 100644
index 80705c1a39..0000000000
--- a/java/common/templates/model/version/ClientMethodDispatcherInterface.vm
+++ /dev/null
@@ -1,55 +0,0 @@
-#set( $filename = "amqp_$version.getMajor()_$version.getMinor()/ClientMethodDispatcher_${version.getMajor()}_${version.getMinor()}.java")
-/*
- *
- * 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 $generator - do not modify.
- * Supported AMQP version:
- #foreach( $supportedVersion in $model.VersionSet )
- * $supportedVersion.getMajor()-$supportedVersion.getMinor()
- #end
- */
-
-package org.apache.qpid.framing.amqp_$version.getMajor()_$version.getMinor();
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.*;
-
-
-public interface ClientMethodDispatcher_${version.getMajor()}_${version.getMinor()} extends ClientMethodDispatcher
-{
-
-#foreach( $amqpClass in $model.getClasses() )
-#set( $amqpClassNameFirstChar = $amqpClass.getName().substring(0,1) )
-#set( $amqpClassNameFirstCharU = $amqpClassNameFirstChar.toUpperCase() )
-#set( $amqpClassNameUpperCamel = "$amqpClassNameFirstCharU$amqpClass.getName().substring(1)" )
-#foreach( $amqpMethodVersions in $amqpClass.getMethods() )
-#set( $amqpMethod = $amqpMethodVersions.asSingleVersionMethod($amqpMethodVersions.getVersionSet().first()) )
-#if( $amqpMethod.isClientMethod() )
-#set( $amqpMethodNameFirstChar = $amqpMethod.getName().substring(0,1) )
-#set( $amqpMethodNameFirstCharU = $amqpMethodNameFirstChar.toUpperCase() )
-#set( $amqpMethodNameUpperCamel = "$amqpMethodNameFirstCharU$amqpMethod.getName().substring(1)" )
- public boolean dispatch${amqpClassNameUpperCamel}${amqpMethodNameUpperCamel}(${amqpClassNameUpperCamel}${amqpMethodNameUpperCamel}Body body, int channelId) throws AMQException;
-#end
-#end
-#end
-
-} \ No newline at end of file
diff --git a/java/common/templates/model/version/MethodDispatcherInterface.vm b/java/common/templates/model/version/MethodDispatcherInterface.vm
deleted file mode 100644
index 8a7b667a91..0000000000
--- a/java/common/templates/model/version/MethodDispatcherInterface.vm
+++ /dev/null
@@ -1,43 +0,0 @@
-#set( $filename = "amqp_$version.getMajor()_$version.getMinor()/MethodDispatcher_${version.getMajor()}_${version.getMinor()}.java")
-/*
- *
- * 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 $generator - do not modify.
- * Supported AMQP version:
- #foreach( $supportedVersion in $model.VersionSet )
- * $supportedVersion.getMajor()-$supportedVersion.getMinor()
- #end
- */
-
-package org.apache.qpid.framing.amqp_$version.getMajor()_$version.getMinor();
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.*;
-
-
-public interface MethodDispatcher_${version.getMajor()}_${version.getMinor()}
- extends MethodDispatcher,
- ServerMethodDispatcher_${version.getMajor()}_${version.getMinor()},
- ClientMethodDispatcher_${version.getMajor()}_${version.getMinor()}
-{
-
-} \ No newline at end of file
diff --git a/java/common/templates/model/version/MethodRegistryClass.vm b/java/common/templates/model/version/MethodRegistryClass.vm
deleted file mode 100644
index 277605e34b..0000000000
--- a/java/common/templates/model/version/MethodRegistryClass.vm
+++ /dev/null
@@ -1,193 +0,0 @@
-#set( $filename = "amqp_$version.getMajor()_$version.getMinor()/MethodRegistry_${version.getMajor()}_${version.getMinor()}.java")
-/*
- *
- * 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 $generator - do not modify.
- * Supported AMQP version:
- * $version.getMajor()-$version.getMinor()
- */
-
-package org.apache.qpid.framing.amqp_${version.getMajor()}_${version.getMinor()};
-
-import org.apache.qpid.framing.*;
-import org.apache.qpid.protocol.AMQConstant;
-
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import org.apache.mina.common.ByteBuffer;
-
-import org.apache.qpid.framing.abstraction.ProtocolVersionMethodConverter;
-
-
-public class MethodRegistry_$version.getMajor()_$version.getMinor() extends MethodRegistry
-{
-
- private static final Logger _log = LoggerFactory.getLogger(MethodRegistry.class);
-
- private ProtocolVersionMethodConverter _protocolVersionConverter = new MethodConverter_$version.getMajor()_$version.getMinor()();
-
-#set( $specificModel = $model.asSingleVersionModel() )
-
-
-#set( $maxClassId = $specificModel.getMaximumClassId()+1 )
- private final AMQMethodBodyInstanceFactory[][] _factories = new AMQMethodBodyInstanceFactory[$maxClassId][];
-
- public MethodRegistry_$version.getMajor()_$version.getMinor()()
- {
- this(new ProtocolVersion((byte)$version.getMajor(),(byte)$version.getMinor()));
- }
-
- public MethodRegistry_$version.getMajor()_$version.getMinor()(ProtocolVersion pv)
- {
- super(pv);
-#foreach( $amqpClass in $specificModel.getClassList() )
-#set( $amqpClassNameFirstChar = $amqpClass.getName().substring(0,1) )
-#set( $amqpClassNameFirstCharU = $amqpClassNameFirstChar.toUpperCase() )
-#set( $amqpClassNameUpperCamel = "$amqpClassNameFirstCharU$amqpClass.getName().substring(1)" )
-
-
-
- // Register method body instance factories for the $amqpClassNameUpperCamel class.
-
-#set( $maxMethodId = $amqpClass.getMaximumMethodId()+1 )
- _factories[$amqpClass.getClassId()] = new AMQMethodBodyInstanceFactory[$maxMethodId];
-
-#foreach( $amqpMethod in $amqpClass.getMethodList() )
-#set( $amqpMethodNameFirstChar = $amqpMethod.getName().substring(0,1) )
-#set( $amqpMethodNameFirstCharU = $amqpMethodNameFirstChar.toUpperCase() )
-#set( $amqpMethodNameUpperCamel = "$amqpMethodNameFirstCharU$amqpMethod.getName().substring(1)" )
- _factories[$amqpClass.getClassId()][$amqpMethod.getMethodId()] = ${amqpClassNameUpperCamel}${amqpMethodNameUpperCamel}BodyImpl.getFactory();
-#end
-
-#end
-
-
- }
-
-
- public AMQMethodBody convertToBody(ByteBuffer in, long size)
- throws AMQFrameDecodingException
- {
- int classId = in.getUnsignedShort();
- int methodId = in.getUnsignedShort();
-
- AMQMethodBodyInstanceFactory bodyFactory;
- try
- {
- bodyFactory = _factories[classId][methodId];
- }
- catch(NullPointerException e)
- {
- throw new AMQFrameDecodingException(AMQConstant.COMMAND_INVALID,
- "Class " + classId + " unknown in AMQP version $version.getMajor()-$version.getMinor()"
- + " (while trying to decode class " + classId + " method " + methodId + ".");
- }
- catch(IndexOutOfBoundsException e)
- {
- if(classId >= _factories.length)
- {
- throw new AMQFrameDecodingException(AMQConstant.COMMAND_INVALID,
- "Class " + classId + " unknown in AMQP version $version.getMajor()-$version.getMinor()"
- + " (while trying to decode class " + classId + " method " + methodId + ".");
-
- }
- else
- {
- throw new AMQFrameDecodingException(AMQConstant.COMMAND_INVALID,
- "Method " + methodId + " unknown in AMQP version $version.getMajor()-$version.getMinor()"
- + " (while trying to decode class " + classId + " method " + methodId + ".");
-
- }
- }
-
-
- if (bodyFactory == null)
- {
- throw new AMQFrameDecodingException(AMQConstant.COMMAND_INVALID,
- "Method " + methodId + " unknown in AMQP version $version.getMajor()-$version.getMinor()"
- + " (while trying to decode class " + classId + " method " + methodId + ".");
- }
-
-
- return bodyFactory.newInstance(in, size);
-
-
- }
-
-
- public int getMaxClassId()
- {
- return $specificModel.getMaximumClassId();
- }
-
- public int getMaxMethodId(int classId)
- {
- return _factories[classId].length - 1;
- }
-
-
-
-#foreach( $amqpClass in $specificModel.getClassList() )
-#set( $amqpClassNameFirstChar = $amqpClass.getName().substring(0,1) )
-#set( $amqpClassNameFirstCharU = $amqpClassNameFirstChar.toUpperCase() )
-#set( $amqpClassNameUpperCamel = "$amqpClassNameFirstCharU$amqpClass.getName().substring(1)" )
-
-
-#foreach( $amqpMethod in $amqpClass.getMethodList() )
-#set( $amqpMethodNameFirstChar = $amqpMethod.getName().substring(0,1) )
-#set( $amqpMethodNameFirstCharU = $amqpMethodNameFirstChar.toUpperCase() )
-#set( $amqpMethodNameUpperCamel = "$amqpMethodNameFirstCharU$amqpMethod.getName().substring(1)" )
- public ${amqpClassNameUpperCamel}${amqpMethodNameUpperCamel}Body create${amqpClassNameUpperCamel}${amqpMethodNameUpperCamel}Body(
-#foreach( $field in $amqpMethod.FieldList )
-#if( $velocityCount == $amqpMethod.getFieldList().size() )
- final $field.NativeType $field.Name
-#else
- final $field.NativeType $field.Name,
-#end
-#end
- )
- {
- return new ${amqpClassNameUpperCamel}${amqpMethodNameUpperCamel}BodyImpl(
-#foreach( $field in $amqpMethod.FieldList )
-#if( $velocityCount == $amqpMethod.getFieldList().size() )
- $field.Name
-#else
- $field.Name,
-#end
-#end
- );
- }
-
-#end
-
-#end
-
-
- public ProtocolVersionMethodConverter getProtocolVersionMethodConverter()
- {
- return _protocolVersionConverter;
- }
-
-
-}
diff --git a/java/common/templates/model/version/ServerMethodDispatcherInterface.vm b/java/common/templates/model/version/ServerMethodDispatcherInterface.vm
deleted file mode 100644
index db388fcc65..0000000000
--- a/java/common/templates/model/version/ServerMethodDispatcherInterface.vm
+++ /dev/null
@@ -1,55 +0,0 @@
-#set( $filename = "amqp_$version.getMajor()_$version.getMinor()/ServerMethodDispatcher_${version.getMajor()}_${version.getMinor()}.java")
-/*
- *
- * 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 $generator - do not modify.
- * Supported AMQP version:
- #foreach( $supportedVersion in $model.VersionSet )
- * $supportedVersion.getMajor()-$supportedVersion.getMinor()
- #end
- */
-
-package org.apache.qpid.framing.amqp_$version.getMajor()_$version.getMinor();
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.*;
-
-
-public interface ServerMethodDispatcher_${version.getMajor()}_${version.getMinor()} extends ServerMethodDispatcher
-{
-
-#foreach( $amqpClass in $model.getClasses() )
-#set( $amqpClassNameFirstChar = $amqpClass.getName().substring(0,1) )
-#set( $amqpClassNameFirstCharU = $amqpClassNameFirstChar.toUpperCase() )
-#set( $amqpClassNameUpperCamel = "$amqpClassNameFirstCharU$amqpClass.getName().substring(1)" )
-#foreach( $amqpMethodVersions in $amqpClass.getMethods() )
-#set( $amqpMethod = $amqpMethodVersions.asSingleVersionMethod($amqpMethodVersions.getVersionSet().first()) )
-#if( $amqpMethod.isServerMethod() )
-#set( $amqpMethodNameFirstChar = $amqpMethod.getName().substring(0,1) )
-#set( $amqpMethodNameFirstCharU = $amqpMethodNameFirstChar.toUpperCase() )
-#set( $amqpMethodNameUpperCamel = "$amqpMethodNameFirstCharU$amqpMethod.getName().substring(1)" )
- public boolean dispatch${amqpClassNameUpperCamel}${amqpMethodNameUpperCamel}(${amqpClassNameUpperCamel}${amqpMethodNameUpperCamel}Body body, int channelId) throws AMQException;
-#end
-#end
-#end
-
-} \ No newline at end of file
diff --git a/java/common/templating.py b/java/common/templating.py
deleted file mode 100644
index 732e96fa60..0000000000
--- a/java/common/templating.py
+++ /dev/null
@@ -1,119 +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.
-#
-
-class Parser:
-
- def __init__(self, **kwargs):
- self.output = ""
- self.environ = {"out": self.parse}
- for k, v in kwargs.items():
- self.environ[k] = v
- self.text = ""
- self.level = 0
- self.line = None
-
- def action(self, actor):
- text = self.text
- self.text = ""
- actor(text)
-
- def out(self, text):
- self.output += text
-
- def prefix_lines(self, text):
- return "%s%s" % ("\n"*(self.line - 1 - text.count("\n")), text)
-
- def evaluate(self, text):
- self.out(str(eval(self.prefix_lines(text), self.environ, self.environ)))
-
- def execute(self, text):
- exec self.prefix_lines(text) in self.environ, self.environ
-
- def parse(self, input):
- old_line = self.line
- try:
- state = self.start
- self.line = 1
- for ch in input:
- state = state(ch)
- if ch == "\n":
- self.line += 1
- if state == self.start:
- self.action(self.out)
- elif state == self.alnum:
- self.action(self.evaluate)
- else:
- raise ParseError()
- finally:
- self.line = old_line
-
- def start(self, ch):
- if ch == "$":
- return self.dollar
- else:
- self.text += ch
- return self.start
-
- def dollar(self, ch):
- if ch == "$":
- self.text += "$"
- return self.start
- elif ch == "(":
- self.action(self.out)
- return self.expression
- elif ch == "{":
- self.action(self.out)
- return self.block
- else:
- self.action(self.out)
- self.text += ch
- return self.alnum
-
- def alnum(self, ch):
- if ch.isalnum():
- self.text += ch
- return self.alnum
- else:
- self.action(self.evaluate)
- self.text += ch
- return self.start
-
- def match(self, ch, start, end):
- if ch == start:
- self.level += 1
- if ch == end:
- self.level -= 1
-
- def block(self, ch):
- if not self.level and ch == "}":
- self.action(self.execute)
- return self.start
- else:
- self.match(ch, "{", "}")
- self.text += ch
- return self.block
-
- def expression(self, ch):
- if not self.level and ch == ")":
- self.action(self.evaluate)
- return self.start
- else:
- self.match(ch, "(", ")")
- self.text += ch
- return self.expression
diff --git a/java/doc/AMQBlazeDetailedDesign.vsd b/java/doc/AMQBlazeDetailedDesign.vsd
deleted file mode 100644
index 90577c69cf..0000000000
--- a/java/doc/AMQBlazeDetailedDesign.vsd
+++ /dev/null
Binary files differ
diff --git a/java/doc/FramingClassDiagram.vsd b/java/doc/FramingClassDiagram.vsd
deleted file mode 100644
index 8db65255ea..0000000000
--- a/java/doc/FramingClassDiagram.vsd
+++ /dev/null
Binary files differ
diff --git a/java/doc/Qpid-architecture.dia b/java/doc/Qpid-architecture.dia
deleted file mode 100644
index 4bdfd2ee93..0000000000
--- a/java/doc/Qpid-architecture.dia
+++ /dev/null
Binary files differ
diff --git a/java/doc/broker-0.5-network.dia b/java/doc/broker-0.5-network.dia
deleted file mode 100644
index f30decde4b..0000000000
--- a/java/doc/broker-0.5-network.dia
+++ /dev/null
Binary files differ
diff --git a/java/doc/broker-0.N-network-phase-1.dia b/java/doc/broker-0.N-network-phase-1.dia
deleted file mode 100644
index 4ac8213b23..0000000000
--- a/java/doc/broker-0.N-network-phase-1.dia
+++ /dev/null
Binary files differ
diff --git a/java/doc/broker-0.N-state.dia b/java/doc/broker-0.N-state.dia
deleted file mode 100644
index 5ef83a871b..0000000000
--- a/java/doc/broker-0.N-state.dia
+++ /dev/null
Binary files differ
diff --git a/java/doc/broker-overview.dia b/java/doc/broker-overview.dia
deleted file mode 100644
index 2d943beadf..0000000000
--- a/java/doc/broker-overview.dia
+++ /dev/null
Binary files differ
diff --git a/java/doc/broker-priority-queue-subscription.dia b/java/doc/broker-priority-queue-subscription.dia
deleted file mode 100644
index 2289899435..0000000000
--- a/java/doc/broker-priority-queue-subscription.dia
+++ /dev/null
Binary files differ
diff --git a/java/doc/broker-queue-subscription.dia b/java/doc/broker-queue-subscription.dia
deleted file mode 100644
index d146ad136d..0000000000
--- a/java/doc/broker-queue-subscription.dia
+++ /dev/null
Binary files differ
diff --git a/java/doc/client-0.5-connection-creation.dia b/java/doc/client-0.5-connection-creation.dia
deleted file mode 100644
index b7c6d185a1..0000000000
--- a/java/doc/client-0.5-connection-creation.dia
+++ /dev/null
Binary files differ
diff --git a/java/doc/client-0.5-network-processing.dia b/java/doc/client-0.5-network-processing.dia
deleted file mode 100644
index acacc4f462..0000000000
--- a/java/doc/client-0.5-network-processing.dia
+++ /dev/null
Binary files differ
diff --git a/java/doc/client-0.N-network-processing.dia b/java/doc/client-0.N-network-processing.dia
deleted file mode 100644
index ed2c340969..0000000000
--- a/java/doc/client-0.N-network-processing.dia
+++ /dev/null
Binary files differ
diff --git a/java/doc/common-0.N-network.dia b/java/doc/common-0.N-network.dia
deleted file mode 100644
index 826ac32e5b..0000000000
--- a/java/doc/common-0.N-network.dia
+++ /dev/null
Binary files differ
diff --git a/java/doc/network-driver-protocol-engine-sequence.dia b/java/doc/network-driver-protocol-engine-sequence.dia
deleted file mode 100644
index 16cdc7e1dc..0000000000
--- a/java/doc/network-driver-protocol-engine-sequence.dia
+++ /dev/null
Binary files differ
diff --git a/java/doc/noddy-network-blocks.dia b/java/doc/noddy-network-blocks.dia
deleted file mode 100644
index 06abc109b1..0000000000
--- a/java/doc/noddy-network-blocks.dia
+++ /dev/null
Binary files differ
diff --git a/java/etc/code-style.xml b/java/etc/code-style.xml
deleted file mode 100644
index 298275fd58..0000000000
--- a/java/etc/code-style.xml
+++ /dev/null
@@ -1,272 +0,0 @@
-<?xml version="1.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.
-
--->
-
-<profiles version="10">
- <profile name="mine" version="10">
- <setting id="org.eclipse.jdt.core.formatter.align_type_members_on_columns" value="false"/>
- <setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression" value="16"/>
- <setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant" value="16"/>
- <setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call" value="16"/>
- <setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation" value="16"/>
- <setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression" value="16"/>
- <setting id="org.eclipse.jdt.core.formatter.alignment_for_assignment" value="0"/>
- <setting id="org.eclipse.jdt.core.formatter.alignment_for_binary_expression" value="16"/>
- <setting id="org.eclipse.jdt.core.formatter.alignment_for_compact_if" value="16"/>
- <setting id="org.eclipse.jdt.core.formatter.alignment_for_conditional_expression" value="80"/>
- <setting id="org.eclipse.jdt.core.formatter.alignment_for_enum_constants" value="0"/>
- <setting id="org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer" value="16"/>
- <setting id="org.eclipse.jdt.core.formatter.alignment_for_multiple_fields" value="16"/>
- <setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration" value="16"/>
- <setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration" value="16"/>
- <setting id="org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation" value="16"/>
- <setting id="org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration" value="16"/>
- <setting id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration" value="16"/>
- <setting id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration" value="16"/>
- <setting id="org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration" value="16"/>
- <setting id="org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration" value="16"/>
- <setting id="org.eclipse.jdt.core.formatter.blank_lines_after_imports" value="1"/>
- <setting id="org.eclipse.jdt.core.formatter.blank_lines_after_package" value="1"/>
- <setting id="org.eclipse.jdt.core.formatter.blank_lines_before_field" value="1"/>
- <setting id="org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration" value="0"/>
- <setting id="org.eclipse.jdt.core.formatter.blank_lines_before_imports" value="1"/>
- <setting id="org.eclipse.jdt.core.formatter.blank_lines_before_member_type" value="1"/>
- <setting id="org.eclipse.jdt.core.formatter.blank_lines_before_method" value="1"/>
- <setting id="org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk" value="1"/>
- <setting id="org.eclipse.jdt.core.formatter.blank_lines_before_package" value="0"/>
- <setting id="org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations" value="1"/>
- <setting id="org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration" value="next_line"/>
- <setting id="org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration" value="next_line"/>
- <setting id="org.eclipse.jdt.core.formatter.brace_position_for_array_initializer" value="end_of_line"/>
- <setting id="org.eclipse.jdt.core.formatter.brace_position_for_block" value="next_line"/>
- <setting id="org.eclipse.jdt.core.formatter.brace_position_for_block_in_case" value="next_line"/>
- <setting id="org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration" value="next_line"/>
- <setting id="org.eclipse.jdt.core.formatter.brace_position_for_enum_constant" value="next_line"/>
- <setting id="org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration" value="next_line"/>
- <setting id="org.eclipse.jdt.core.formatter.brace_position_for_method_declaration" value="next_line"/>
- <setting id="org.eclipse.jdt.core.formatter.brace_position_for_switch" value="next_line"/>
- <setting id="org.eclipse.jdt.core.formatter.brace_position_for_type_declaration" value="next_line"/>
- <setting id="org.eclipse.jdt.core.formatter.comment.clear_blank_lines" value="false"/>
- <setting id="org.eclipse.jdt.core.formatter.comment.format_comments" value="true"/>
- <setting id="org.eclipse.jdt.core.formatter.comment.format_header" value="false"/>
- <setting id="org.eclipse.jdt.core.formatter.comment.format_html" value="true"/>
- <setting id="org.eclipse.jdt.core.formatter.comment.format_source_code" value="true"/>
- <setting id="org.eclipse.jdt.core.formatter.comment.indent_parameter_description" value="true"/>
- <setting id="org.eclipse.jdt.core.formatter.comment.indent_root_tags" value="true"/>
- <setting id="org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.comment.line_length" value="80"/>
- <setting id="org.eclipse.jdt.core.formatter.compact_else_if" value="true"/>
- <setting id="org.eclipse.jdt.core.formatter.continuation_indentation" value="2"/>
- <setting id="org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer" value="2"/>
- <setting id="org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line" value="false"/>
- <setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header" value="true"/>
- <setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header" value="true"/>
- <setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header" value="true"/>
- <setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header" value="true"/>
- <setting id="org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases" value="true"/>
- <setting id="org.eclipse.jdt.core.formatter.indent_empty_lines" value="false"/>
- <setting id="org.eclipse.jdt.core.formatter.indent_statements_compare_to_block" value="true"/>
- <setting id="org.eclipse.jdt.core.formatter.indent_statements_compare_to_body" value="true"/>
- <setting id="org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases" value="true"/>
- <setting id="org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch" value="false"/>
- <setting id="org.eclipse.jdt.core.formatter.indentation.size" value="4"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_binary_operator" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_ellipsis" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_after_unary_operator" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_binary_operator" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_ellipsis" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional" value="insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_before_unary_operator" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation" value="do not insert"/>
- <setting id="org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line" value="false"/>
- <setting id="org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line" value="false"/>
- <setting id="org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line" value="false"/>
- <setting id="org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line" value="false"/>
- <setting id="org.eclipse.jdt.core.formatter.lineSplit" value="80"/>
- <setting id="org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body" value="0"/>
- <setting id="org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve" value="1"/>
- <setting id="org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line" value="true"/>
- <setting id="org.eclipse.jdt.core.formatter.tabulation.char" value="space"/>
- <setting id="org.eclipse.jdt.core.formatter.tabulation.size" value="4"/>
- <setting id="org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations" value="false"/>
- </profile>
-</profiles>
diff --git a/java/etc/coding_standards.xml b/java/etc/coding_standards.xml
deleted file mode 100644
index fdb42c1b9c..0000000000
--- a/java/etc/coding_standards.xml
+++ /dev/null
@@ -1,138 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
-
--->
-
-<!DOCTYPE module PUBLIC "-//Puppy Crawl//DTD Check Configuration 1.1//EN" "http://www.puppycrawl.com/dtds/configuration_1_1.dtd">
-<module name="Checker">
- <!-- Checks package.html defined for all packages. -->
- <module name="PackageHtml"/>
-
- <module name="TreeWalker">
-
- <!-- Whitespace conventions. -->
- <module name="TabCharacter"/>
-
- <!-- License conventions. Checks that the license is included in every file. -->
- <module name="Header">
- <property name="headerFile" value="${checkstyle.header.file}"/>
- </module>
-
- <!-- Coding style conventions. -->
- <module name="com.puppycrawl.tools.checkstyle.checks.coding.PackageDeclarationCheck">
- <property name="severity" value="error"/>
- </module>
-
- <!-- These rules ensure that everything is javadoc'ed. -->
- <!--
- <module name="RequiredRegexp">
- <property name="format" value="&lt;table id=&quot;crc&quot;&gt;&lt;caption&gt;CRC Card&lt;/caption&gt;"/>
- </module>
- -->
-
- <module name="com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocTypeCheck">
- <property name="excludeScope" value="nothing"/>
- <property name="scope" value="private"/>
- <property name="severity" value="error"/>
- <property name="tokens" value="CLASS_DEF, INTERFACE_DEF"/>
- <property name="allowMissingParamTags" value="true"/>
- </module>
-
- <module name="com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocVariableCheck">
- <property name="excludeScope" value="nothing"/>
- <property name="scope" value="private"/>
- <property name="severity" value="error"/>
- </module>
-
- <module name="com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocMethodCheck">
- <property name="allowMissingParamTags" value="false"/>
- <property name="allowMissingReturnTag" value="false"/>
- <property name="allowMissingThrowsTags" value="false"/>
- <property name="allowThrowsTagsForSubclasses" value="false"/>
- <property name="allowUndeclaredRTE" value="true"/>
- <property name="allowMissingJavadoc" value="false"/>
- <property name="allowMissingPropertyJavadoc" value="true"/>
- <property name="excludeScope" value="nothing"/>
- <property name="scope" value="private"/>
- <property name="severity" value="error"/>
- <property name="tokens" value="METHOD_DEF, CTOR_DEF"/>
- </module>
-
- <module name="JavadocStyle">
- <property name="scope" value="private"/>
- <property name="checkHtml" value="false"/>
- <property name="checkFirstSentence" value="true"/>
- <property name="checkEmptyJavadoc" value="true"/>
- </module>
-
- <!-- These rules enforce the conventions for the naming of variables. -->
- <!--
- <module name="com.puppycrawl.tools.checkstyle.checks.naming.ConstantNameCheck">
- <property name="format" value="^log$|^[A-Z](_?[A-Z0-9]+)*$"/>
- <property name="severity" value="error"/>
- </module>
-
- <module name="com.puppycrawl.tools.checkstyle.checks.naming.LocalFinalVariableNameCheck">
- <property name="format" value="^[a-z][a-zA-Z0-9_]*$"/>
- <property name="severity" value="error"/>
- </module>
-
- <module name="com.puppycrawl.tools.checkstyle.checks.naming.LocalVariableNameCheck">
- <property name="format" value="^[a-z][a-zA-Z0-9_]*$"/>
- <property name="severity" value="error"/>
- </module>
-
- <module name="com.puppycrawl.tools.checkstyle.checks.naming.MemberNameCheck">
- <property name="applyToPackage" value="true"/>
- <property name="applyToPrivate" value="true"/>
- <property name="applyToProtected" value="true"/>
- <property name="applyToPublic" value="true"/>
- <property name="format" value="^[a-z][a-zA-Z0-9_]*$"/>
- <property name="severity" value="error"/>
- </module>
-
- <module name="com.puppycrawl.tools.checkstyle.checks.naming.MethodNameCheck">
- <property name="format" value="^[a-z][a-zA-Z0-9_]*$"/>
- <property name="severity" value="error"/>
- </module>
-
- <module name="com.puppycrawl.tools.checkstyle.checks.naming.PackageNameCheck">
- <property name="format" value="^[a-z]+(\.[a-zA-Z_][a-zA-Z0-9_]*)*$"/>
- <property name="severity" value="error"/>
- </module>
-
- <module name="com.puppycrawl.tools.checkstyle.checks.naming.ParameterNameCheck">
- <property name="format" value="^[a-z][a-zA-Z0-9_]*$"/>
- <property name="severity" value="error"/>
- </module>
-
- <module name="com.puppycrawl.tools.checkstyle.checks.naming.StaticVariableNameCheck">
- <property name="format" value="^[a-z][a-zA-Z0-9_]*$"/>
- <property name="severity" value="error"/>
- </module>
-
- <module name="com.puppycrawl.tools.checkstyle.checks.naming.TypeNameCheck">
- <property name="format" value="^[A-Z][a-zA-Z0-9_]*$"/>
- <property name="severity" value="error"/>
- <property name="tokens" value="CLASS_DEF, INTERFACE_DEF"/>
- </module>
- -->
- </module>
-</module>
diff --git a/java/etc/license_header.txt b/java/etc/license_header.txt
deleted file mode 100644
index 02ee6e8f98..0000000000
--- a/java/etc/license_header.txt
+++ /dev/null
@@ -1,20 +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.
- *
- */ \ No newline at end of file
diff --git a/java/etc/log4j.xml b/java/etc/log4j.xml
deleted file mode 100644
index 266c466a3a..0000000000
--- a/java/etc/log4j.xml
+++ /dev/null
@@ -1,61 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
--->
-<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
-
-<!-- ===================================================================== -->
-<!-- -->
-<!-- Log4j Configuration -->
-<!-- -->
-<!-- ===================================================================== -->
-
-<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">
-
- <!-- ============================== -->
- <!-- Append messages to the console -->
- <!-- ============================== -->
-
- <appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
- <param name="Target" value="System.out"/>
- <param name="Threshold" value="ALL"/>
-
- <layout class="org.apache.log4j.PatternLayout">
- <!-- The default pattern: Date Priority [Category] Message\n -->
- <param name="ConversionPattern" value="%m%n"/>
- </layout>
-
- </appender>
-
- <!-- ================ -->
- <!-- Limit categories -->
- <!-- ================ -->
-
- <category name="org.apache.qpid">
- <priority value="${amqj.logging.level}" logger="CONSOLE"/>
- </category>
-
- <!-- ======================= -->
- <!-- Setup the Root category -->
- <!-- ======================= -->
-
- <root level="${root.logging.level}">
- <appender-ref ref="CONSOLE"/>
- </root>
-
-</log4j:configuration>
diff --git a/java/genpom b/java/genpom
deleted file mode 100755
index 39eccd4c3e..0000000000
--- a/java/genpom
+++ /dev/null
@@ -1,177 +0,0 @@
-#!/usr/bin/python
-#
-# 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 sys, re, os, mllib, optparse
-
-def die(msg):
- print >> sys.stderr, msg
- sys.exit(1)
-
-parser = optparse.OptionParser(usage="usage: %prog [options] JARs ...",
- description="Generates a pom.")
-parser.add_option("-n", "--name")
-parser.add_option("-g", "--group")
-parser.add_option("-a", "--artifact")
-parser.add_option("-v", "--version")
-parser.add_option("-d", "--description", default="")
-parser.add_option("-u", "--url", default="")
-parser.add_option("-m", "--modules", help="modules dependencies")
-parser.add_option("-p", "--prefix", help="prefix of the project's artifacts names")
-parser.add_option("-i", "--ignore", action="store_true", help="ignore missing deps")
-parser.add_option("-s", "--search-path", action="append",
- help="the path to search for deps")
-parser.add_option("-S", "--scope", metavar="ARTIFACT=SCOPE", action="append",
- default=[],
- help="specify scope for an artifact")
-parser.add_option("-o", "--output")
-
-opts, jars = parser.parse_args()
-
-if opts.search_path is None:
- path=["%s/.m2" % os.environ["HOME"]]
-else:
- path = []
- for p in opts.search_path:
- path.extend(p.split(os.pathsep))
-
-expanded_path = []
-for p in path:
- os.path.walk(p, lambda a, d, fs: expanded_path.append(d), None)
-
-if opts.group is None:
- die("the group option is required")
-
-if opts.version is None:
- die("the version option is required")
-
-if opts.name is None and opts.artifact is None:
- die("one of name or artifact must be supplied")
-
-if opts.prefix is not None:
- opts.artifact = opts.prefix + "-" + opts.artifact
-
-if opts.name is None:
- opts.name = opts.artifact
-
-if opts.artifact is None:
- opts.artifact = opts.name
-
-def lookup(dep, attr):
- nd = dep["dep"][attr]
- if nd is None:
- if nd is None:
- return None
- return nd.text()
-
-def search(path, file):
- for d in path:
- f = os.path.join(d, file)
- if os.path.exists(f):
- return mllib.xml_parse(f)
-
-scopes = {}
-for s in opts.scope:
- m = re.match(r"(.*)=(.*)", s)
- if not m:
- die("bad scope specifier: %s" % s)
- scopes[m.group(1)] = m.group(2)
-
-deps = []
-module_depends = []
-if opts.modules is not None:
- module_depends = opts.modules.replace("/", "-").split();
-
-for module in module_depends:
- if opts.prefix is None:
- artifactId = module
- else:
- artifactId = opts.prefix + "-" + module
-
- deps.append("""
- <dependency>
- <groupId>%s</groupId>
- <artifactId>%s</artifactId>
- <version>%s</version>
- </dependency>
-""" % (opts.group, artifactId, opts.version))
-
-for jar in jars:
- base, ext = os.path.splitext(os.path.basename(jar))
- dep = search(expanded_path, "%s.xml" % base)
- if dep is None:
- if opts.ignore:
- continue
- else:
- die("unable to locate xml for %s" % jar)
- group = lookup(dep, "groupId")
- artifactId = lookup(dep, "artifactId")
- version = lookup(dep, "version")
- deps.append("""
- <dependency>
- <groupId>%s</groupId>
- <artifactId>%s</artifactId>
- <version>%s</version>
- <scope>%s</scope>
- </dependency>
-""" % (group, artifactId, version,
- scopes.get(artifactId, "compile")))
-
-TEMPLATE = """<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd ">
- <modelVersion>4.0.0</modelVersion>
- <groupId>%(group)s</groupId>
- <artifactId>%(artifact)s</artifactId>
- <version>%(version)s</version>
-
- <name>%(name)s</name>
- <url>%(url)s</url>
- <description>%(description)s</description>
-
- <organization>
- <name>The Apache Software Foundation</name>
- <url>http://www.apache.org</url>
- </organization>
-
- <licenses>
- <license>
- <name>The Apache Software License, Version 2.0</name>
- <url>http://www.apache.org/licenses/LICENSE-2.0.html</url>
- </license>
- </licenses>
-
- <dependencies>
- %(dependencies)s
- </dependencies>
-
-</project>
-"""
-
-vars = {}
-vars.update(opts.__dict__)
-vars["dependencies"] = "".join(deps)
-
-if opts.output is None:
- out = sys.stdout
-else:
- out = open(opts.output, "w")
-out.write(TEMPLATE % vars)
-out.close()
diff --git a/java/integrationtests/README.txt b/java/integrationtests/README.txt
deleted file mode 100644
index 00a21883a9..0000000000
--- a/java/integrationtests/README.txt
+++ /dev/null
@@ -1,13 +0,0 @@
-This module contains integration tests, for testing a java client againt *any* broker
-implementation or against other clients. These tests must not rely on starting the
-Java broker in-vm but must depend on a broker being started independantly before running
-the tests in this module. By default tests in this module will expect the broker to be
-started on localhost on the default port, but this can be overridden by passing in a
-sys property to maven. Interop tests are in this module. Java broker specific tests that
-use an in-vm broker should go in the systests module.
-
-Don't set the tests in this module to run by default as part of the maven build, until
-there is a script to start and stop the broker; needed to fully automate these tests.
-Interop tests will always be run using a seperate script (not from maven) but it might
-be worthwile to script into the maven build starting of the Java broker, and running
-these tests against it. \ No newline at end of file
diff --git a/java/integrationtests/bin/interoptests.py b/java/integrationtests/bin/interoptests.py
deleted file mode 100755
index a883a22a5f..0000000000
--- a/java/integrationtests/bin/interoptests.py
+++ /dev/null
@@ -1,180 +0,0 @@
-#!/usr/bin/env python
-#
-#
-# 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 glob, os, subprocess
-from subprocess import Popen
-from optparse import OptionParser
-
-interop_cases = ["InteropTestCase1DummyRun", "InteropTestCase2BasicP2P", "InteropTestCase3BasicPubSub", "InteropTestCase4P2PMessageSize", "InteropTestCase5PubSubMessageSize"]
-
-interop_command = "java -cp %s org.apache.qpid.test.framework.distributedtesting.Coordinator --xml -e interop -o . -n interop org.apache.qpid.interop.testcases.%s"
-
-# TODO: read this from the ant properties file
-clientlibs = ["qpid-integrationtests-M4.jar",
- "qpid-junit-toolkit-M4.jar",
- "junit-3.8.1.jar",
- "qpid-systests-M4.jar",
- "qpid-junit-toolkit-M4.jar",
- "geronimo-jms_1.1_spec-1.0.jar",
- "log4j-1.2.12.jar"]
-
-def main():
- parser = OptionParser()
- parser.add_option("-t", "--testlib", dest="testlib", action="store",
- type="string",
- help="The directory containing the test classes to run")
- parser.add_option("-b", "--brokers", dest="brokers", action="store",
- type="string",
- help="The directory containing the unpacked brokers to test")
- parser.add_option("-j", "--java", dest="java", action="store",
- type="string",
- help="The directory containing the java client to test")
- parser.add_option("-d", "--dotnet", dest="dotnet", action="store",
- type="string",
- help="The directory containing the .Net client to test")
- parser.add_option("-c", "--cpp", dest="cpp", action="store",
- type="string",
- help="The directory containing the C++ client to test")
- (options, args) = parser.parse_args()
-
- # check available brokers
- if (options.brokers == None or
- not os.path.exists(options.brokers) or
- not os.path.isdir(options.brokers)):
- parser.error("Broker directory must be specified and must exist")
-
- # check available clients
- if (options.java == None or
- not os.path.exists(options.java) or
- not os.path.isdir(options.java)):
- parser.error("Java client directory must be specified and must exist")
-
- # check available tests
- if (options.testlib == None or
- not os.path.exists(options.testlib) or
- not os.path.isdir(options.testlib)):
- parser.error("Test directory must be specified and must exist")
-
- # check dotnet test client
- if (options.dotnet == None or
- not os.path.exists(options.dotnet) or
- not os.path.exists(options.dotnet+"/TestClient.exe")):
- parser.error(".Net test directory must be specified and must contain TestClient.exe")
-
- # check cpp test client
- if (options.cpp == None or
- not os.path.exists(options.cpp) or
- not os.path.exists(options.cpp+"/src/tests/interop_runner")):
- parser.error("C++ test directory must be specified and must contain test client")
-
- # Get list of available broker and client versions
- brokers = glob.glob(options.brokers+"/qpid-[0-9].[0-9].[0-9].[0-9]")
- java_clients = glob.glob(options.java+"/qpid-[0-9].[0-9].[0-9].[0-9]*")
-
- if (not len(brokers) > 0):
- parser.error("Broker directory did not contain any brokers!")
-
- if (not len(java_clients) > 0):
- parser.error("Broker directory did not contain any brokers!")
-
- for broker in brokers:
- for client in java_clients:
- test(options.testlib, broker, client, options.dotnet,
- options.cpp)
-
-def start_dotnet(dotnetpath):
- return Popen(["%s/TestClient.exe" % os.path.abspath(dotnetpath),
- "-bamqp://guest:guest@clientid/?brokerlist=\'tcp://localhost:5672\'"],
- stdin=subprocess.PIPE, stdout=subprocess.PIPE,
- stderr=subprocess.STDOUT)
-
-def start_java(javapath):
- # Setup classpath
- classpath = ""
- for lib in clientlibs:
- classpath = classpath + testlibdir+"/"+lib+";"
-
- classpath = classpath + javapath+"/lib/qpid-all.jar"
-
- # Add qpid common since the tests need that, classpath hatefulness
- classpath = classpath + ";"+testlibdir+"/qpid-common-M4.jar"
-
- return Popen(["java", "-cp","\""+classpath+"\"",
- "org.apache.qpid.test.framework.distributedtesting.TestClient"],
- stdin=subprocess.PIPE, stdout=subprocess.PIPE,
- stderr=subprocess.STDOUT)
-
-def start_cpp(cpppath):
- return Popen([cpppath+"tests/interop_runner"],
- stdin=subprocess.PIPE, stdout=subprocess.PIPE,
- stderr=subprocess.STDOUT)
-
-def run_tests():
- for testcase in interop_cases:
- cmd = " ".join(["java", "-cp","\""+classpath+"\"", "org.apache.qpid.test.framework.distributedtesting.Coordinator",
- "--xml", "-e", "interop", "-o", ".", "-n", "interop", ("org.apache.qpid.interop.testcases.%s" % testcase)])
- fd = os.popen(cmd, "r")
- output = fd.read()
- fd.close()
-
-def test(testlibdir, brokerpath, javapath, dotnetpath, cpppath):
- print ("Testing broker in %s\nclient in %s" % (brokerpath, javapath))
- print ("Logging too %s" % ("/tmp/qpid-interop-tests/%s-%s" %
- (os.path.basename(brokerpath), os.path.basename(javapath))))
- os.environ["QPID_HOME"] = brokerpath
- os.environ["QPID_WORK"] = ("/tmp/qpid-interop-tests/%s-%s" %
- (os.path.basename(brokerpath), os.path.basename(javapath)))
-
- brokerp, javacp, dotnetp, cppp, coordinatorp = (None, None, None, None, None)
-
- try:
- # Start broker
- brokerp = Popen(brokerpath+"/bin/qpid-server",
- stdin=subprocess.PIPE, stdout=subprocess.PIPE,
- stderr=subprocess.STDOUT)
- print ("Started broker, pid %s" % brokerp.pid)
-
- cppp = start_cpp(cpppath)
- print ("Started C++ client, pid %s" % cppp.pid)
-
- dotnetp = start_dotnet(dotnetpath)
- print ("Started .Net client, pid %s" % dotnetp.pid)
-
- javacp = start_java(javapath)
- print ("Started client, pid %s" % javacp.pid)
-
- run_tests()
-
- finally:
- # Shutdown broker and clients
- if javacp != None:
- os.kill(javacp.pid, 9)
- if dotnetp != None:
- os.kill(dotnetp.pid, 9)
- if coordinatorp != None:
- os.kill(coordinatorp.pid, 9)
- if brokerp != None:
- os.kill(brokerp.pid, 9)
-
- # Start coordinator
-
-
-if __name__ == "__main__":
- main()
diff --git a/java/integrationtests/build.xml b/java/integrationtests/build.xml
deleted file mode 100644
index ae870c5675..0000000000
--- a/java/integrationtests/build.xml
+++ /dev/null
@@ -1,28 +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.
- -
- -->
-<project name="Integration Tests" default="build">
-
- <property name="module.depends" value="systests client common common/test junit-toolkit"/>
- <property name="module.dist" value="false"/>
-
- <import file="../module.xml"/>
-
-</project>
diff --git a/java/integrationtests/docs/RunningSustainedTests.txt b/java/integrationtests/docs/RunningSustainedTests.txt
deleted file mode 100644
index db4405a32d..0000000000
--- a/java/integrationtests/docs/RunningSustainedTests.txt
+++ /dev/null
@@ -1,17 +0,0 @@
-In addition to the integration tests the framework provided by this package also allows for
-sustained tests to be run. Currently avaible tests:
-- org.apache.qpid.sustained.SustainedClientTestCase : Pub Sub test to determine steady state throughput.
-
-
-Running Tests.
-
-Run the tests as per the integration tests.
-- Start a broker
-- Start at least one test client [java org.apache.qpid.interop.TestClient], ensuring unique naming.
-
-- Start the test coordinator with the 'fanout' engine, on the sustained test case [java org.apache.qpid.test.framework.distributedtesting.Coordinator]
-
-- Additional Test clients can be started and joined into the running test: [java org.apache.qpid.interop.TestClient -j]
-
-
-
diff --git a/java/integrationtests/jar-with-dependencies.xml b/java/integrationtests/jar-with-dependencies.xml
deleted file mode 100644
index 3e95e7ab22..0000000000
--- a/java/integrationtests/jar-with-dependencies.xml
+++ /dev/null
@@ -1,47 +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 is an assembly descriptor that produces a jar file that contains all the
- dependencies, fully expanded into a single jar, required to run the tests of
- a maven project.
- -->
-<assembly>
- <id>all-test-deps</id>
- <formats>
- <format>jar</format>
- </formats>
- <includeBaseDirectory>false</includeBaseDirectory>
- <dependencySets>
- <dependencySet>
- <outputDirectory></outputDirectory>
- <outputFileNameMapping></outputFileNameMapping>
- <unpack>true</unpack>
- <scope>test</scope>
- </dependencySet>
- </dependencySets>
- <fileSets>
- <fileSet>
- <directory>target/classes</directory>
- <outputDirectory></outputDirectory>
- </fileSet>
- <fileSet>
- <directory>target/test-classes</directory>
- <outputDirectory></outputDirectory>
- </fileSet>
- </fileSets>
-</assembly>
diff --git a/java/integrationtests/src/main/java/org/apache/qpid/interop/clienttestcases/TestCase1DummyRun.java b/java/integrationtests/src/main/java/org/apache/qpid/interop/clienttestcases/TestCase1DummyRun.java
deleted file mode 100644
index db17c7aacc..0000000000
--- a/java/integrationtests/src/main/java/org/apache/qpid/interop/clienttestcases/TestCase1DummyRun.java
+++ /dev/null
@@ -1,135 +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.interop.clienttestcases;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.test.framework.distributedtesting.TestClientControlledTest;
-
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.Session;
-
-/**
- * Implements tet case 1, dummy run. This test case sends no test messages, it exists to confirm that the test harness
- * is interacting with the coordinator correctly.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Supply the name of the test case that this implements.
- * <tr><td> Accept/Reject invites based on test parameters.
- * <tr><td> Adapt to assigned roles.
- * <tr><td> Perform test case actions.
- * <tr><td> Generate test reports.
- * </table>
- */
-public class TestCase1DummyRun implements TestClientControlledTest
-{
- /** Used for debugging. */
- private static final Logger log = Logger.getLogger(TestCase1DummyRun.class);
-
- /**
- * Should provide the name of the test case that this class implements. The exact names are defined in the
- * interop testing spec.
- *
- * @return The name of the test case that this implements.
- */
- public String getName()
- {
- log.debug("public String getName(): called");
-
- return "TC1_DummyRun";
- }
-
- /**
- * Determines whether the test invite that matched this test case is acceptable.
- *
- * @param inviteMessage The invitation to accept or reject.
- *
- * @return <tt>true</tt> to accept the invitation, <tt>false</tt> to reject it.
- *
- * @throws JMSException Any JMSException resulting from reading the message are allowed to fall through.
- */
- public boolean acceptInvite(Message inviteMessage) throws JMSException
- {
- log.debug("public boolean acceptInvite(Message inviteMessage): called");
-
- // Test parameters don't matter, accept all invites.
- return true;
- }
-
- /**
- * Assigns the role to be played by this test case. The test parameters are fully specified in the
- * assignment message. When this method return the test case will be ready to execute.
- *
- * @param role The role to be played; sender or receivers.
- * @param assignRoleMessage The role assingment message, contains the full test parameters.
- *
- * @throws JMSException Any JMSException resulting from reading the message are allowed to fall through.
- */
- public void assignRole(Roles role, Message assignRoleMessage) throws JMSException
- {
- log.debug("public void assignRole(Roles role, Message assignRoleMessage): called");
-
- // Do nothing, both roles are the same.
- }
-
- /**
- * Performs the test case actions. Returning from here, indicates that the sending role has completed its test.
- *
- * @param numMessages The number of test messages to send.
- */
- public void start(int numMessages)
- {
- log.debug("public void start(): called");
-
- // Do nothing.
- }
-
- /**
- * Gets a report on the actions performed by the test case in its assigned role.
- *
- * @param session The controlSession to create the report message in.
- *
- * @return The report message.
- *
- * @throws JMSException Any JMSExceptions resulting from creating the report are allowed to fall through.
- */
- public Message getReport(Session session) throws JMSException
- {
- log.debug("public Message getReport(Session controlSession): called");
-
- // Generate a dummy report, the coordinator expects a report but doesn't care what it is.
- return session.createTextMessage("Dummy Run, Ok.");
- }
-
- /**
- * Handles incoming test messages. Does nothing.
- *
- * @param message The incoming test message.
- */
- public void onMessage(Message message)
- {
- log.debug("public void onMessage(Message message = " + message + "): called");
-
- // Ignore any messages.
- }
-}
diff --git a/java/integrationtests/src/main/java/org/apache/qpid/interop/clienttestcases/TestCase2BasicP2P.java b/java/integrationtests/src/main/java/org/apache/qpid/interop/clienttestcases/TestCase2BasicP2P.java
deleted file mode 100644
index 36d3cce7f7..0000000000
--- a/java/integrationtests/src/main/java/org/apache/qpid/interop/clienttestcases/TestCase2BasicP2P.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.interop.clienttestcases;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.test.framework.TestUtils;
-import org.apache.qpid.test.framework.distributedtesting.TestClient;
-import org.apache.qpid.test.framework.distributedtesting.TestClientControlledTest;
-
-import javax.jms.*;
-
-/**
- * Implements test case 2, basic P2P. Sends/received a specified number of messages to a specified route on the
- * default direct exchange. Produces reports on the actual number of messages sent/received.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Supply the name of the test case that this implements.
- * <tr><td> Accept/Reject invites based on test parameters.
- * <tr><td> Adapt to assigned roles.
- * <tr><td> Send required number of test messages.
- * <tr><td> Generate test reports.
- * </table>
- */
-public class TestCase2BasicP2P implements TestClientControlledTest, MessageListener
-{
- /** Used for debugging. */
- private static final Logger log = Logger.getLogger(TestCase2BasicP2P.class);
-
- /** Holds the count of test messages received. */
- private int messageCount;
-
- /** The role to be played by the test. */
- private Roles role;
-
- /** The number of test messages to send. */
- private int numMessages;
-
- /** The connection to send the test messages on. */
- private Connection connection;
-
- /** The controlSession to send the test messages on. */
- private Session session;
-
- /** The producer to send the test messages with. */
- MessageProducer producer;
-
- /**
- * Should provide the name of the test case that this class implements. The exact names are defined in the
- * interop testing spec.
- *
- * @return The name of the test case that this implements.
- */
- public String getName()
- {
- log.debug("public String getName(): called");
-
- return "TC2_BasicP2P";
- }
-
- /**
- * Determines whether the test invite that matched this test case is acceptable.
- *
- * @param inviteMessage The invitation to accept or reject.
- *
- * @return <tt>true</tt> to accept the invitation, <tt>false</tt> to reject it.
- *
- * @throws JMSException Any JMSException resulting from reading the message are allowed to fall through.
- */
- public boolean acceptInvite(Message inviteMessage) throws JMSException
- {
- log.debug("public boolean acceptInvite(Message inviteMessage = " + inviteMessage + "): called");
-
- // All invites are acceptable.
- return true;
- }
-
- /**
- * Assigns the role to be played by this test case. The test parameters are fully specified in the
- * assignment message. When this method return the test case will be ready to execute.
- *
- * @param role The role to be played; sender or receivers.
- *
- * @param assignRoleMessage The role assingment message, contains the full test parameters.
- *
- * @throws JMSException Any JMSException resulting from reading the message are allowed to fall through.
- */
- public void assignRole(Roles role, Message assignRoleMessage) throws JMSException
- {
- log.debug("public void assignRole(Roles role = " + role + ", Message assignRoleMessage = " + assignRoleMessage
- + "): called");
-
- // Reset the message count for a new test.
- messageCount = 0;
-
- // Take note of the role to be played.
- this.role = role;
-
- // Create a new connection to pass the test messages on.
- connection = TestUtils.createConnection(TestClient.testContextProperties);
- session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- // Extract and retain the test parameters.
- numMessages = assignRoleMessage.getIntProperty("P2P_NUM_MESSAGES");
- Destination sendDestination = session.createQueue(assignRoleMessage.getStringProperty("P2P_QUEUE_AND_KEY_NAME"));
-
- log.debug("numMessages = " + numMessages);
- log.debug("sendDestination = " + sendDestination);
- log.debug("role = " + role);
-
- switch (role)
- {
- // Check if the sender role is being assigned, and set up a message producer if so.
- case SENDER:
- producer = session.createProducer(sendDestination);
- break;
-
- // Otherwise the receivers role is being assigned, so set this up to listen for messages.
- case RECEIVER:
- MessageConsumer consumer = session.createConsumer(sendDestination);
- consumer.setMessageListener(this);
- break;
- }
-
- connection.start();
- }
-
- /**
- * Performs the test case actions. Returning from here, indicates that the sending role has completed its test.
- *
- * @param numMessages The number of test messages to send.
- *
- * @throws JMSException Any JMSException resulting from reading the message are allowed to fall through.
- */
- public void start(int numMessages) throws JMSException
- {
- log.debug("public void start(): called");
-
- // Check that the sender role is being performed.
- if (role.equals(Roles.SENDER))
- {
- Message testMessage = session.createTextMessage("test");
-
- for (int i = 0; i < this.numMessages; i++)
- {
- producer.send(testMessage);
-
- // Increment the message count.
- messageCount++;
- }
- }
- }
-
- /**
- * Gets a report on the actions performed by the test case in its assigned role.
- *
- * @param session The controlSession to create the report message in.
- *
- * @return The report message.
- *
- * @throws JMSException Any JMSExceptions resulting from creating the report are allowed to fall through.
- */
- public Message getReport(Session session) throws JMSException
- {
- log.debug("public Message getReport(Session controlSession): called");
-
- // Close the test connection.
- connection.close();
-
- // Generate a report message containing the count of the number of messages passed.
- Message report = session.createMessage();
- report.setStringProperty("CONTROL_TYPE", "REPORT");
- report.setIntProperty("MESSAGE_COUNT", messageCount);
-
- return report;
- }
-
- /**
- * Counts incoming test messages.
- *
- * @param message The incoming test message.
- */
- public void onMessage(Message message)
- {
- log.debug("public void onMessage(Message message = " + message + "): called");
-
- // Increment the message count.
- messageCount++;
- }
-}
diff --git a/java/integrationtests/src/main/java/org/apache/qpid/interop/clienttestcases/TestCase3BasicPubSub.java b/java/integrationtests/src/main/java/org/apache/qpid/interop/clienttestcases/TestCase3BasicPubSub.java
deleted file mode 100644
index 205472716b..0000000000
--- a/java/integrationtests/src/main/java/org/apache/qpid/interop/clienttestcases/TestCase3BasicPubSub.java
+++ /dev/null
@@ -1,239 +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.interop.clienttestcases;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.test.framework.TestUtils;
-import org.apache.qpid.test.framework.distributedtesting.TestClient;
-import org.apache.qpid.test.framework.distributedtesting.TestClientControlledTest;
-
-import javax.jms.*;
-
-/**
- * Implements test case 3, basic pub/sub. Sends/received a specified number of messages to a specified route on the
- * default topic exchange, using the specified number of receivers connections. Produces reports on the actual number of
- * messages sent/received.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Supply the name of the test case that this implements.
- * <tr><td> Accept/Reject invites based on test parameters.
- * <tr><td> Adapt to assigned roles.
- * <tr><td> Send required number of test messages using pub/sub.
- * <tr><td> Generate test reports.
- * </table>
- */
-public class TestCase3BasicPubSub implements TestClientControlledTest, MessageListener
-{
- /** Used for debugging. */
- private static final Logger log = Logger.getLogger(TestCase3BasicPubSub.class);
-
- /** Holds the count of test messages received. */
- private int messageCount;
-
- /** The role to be played by the test. */
- private Roles role;
-
- /** The number of test messages to send. */
- private int numMessages;
-
- /** The connections to send/receive the test messages on. */
- private Connection[] connection;
-
- /** The sessions to send/receive the test messages on. */
- private Session[] session;
-
- /** The producer to send the test messages with. */
- MessageProducer producer;
-
- /**
- * Should provide the name of the test case that this class implements. The exact names are defined in the
- * interop testing spec.
- *
- * @return The name of the test case that this implements.
- */
- public String getName()
- {
- log.debug("public String getName(): called");
-
- return "TC3_BasicPubSub";
- }
-
- /**
- * Determines whether the test invite that matched this test case is acceptable.
- *
- * @param inviteMessage The invitation to accept or reject.
- *
- * @return <tt>true</tt> to accept the invitation, <tt>false</tt> to reject it.
- *
- * @throws javax.jms.JMSException Any JMSException resulting from reading the message are allowed to fall through.
- */
- public boolean acceptInvite(Message inviteMessage) throws JMSException
- {
- log.debug("public boolean acceptInvite(Message inviteMessage = " + inviteMessage + "): called");
-
- // All invites are acceptable.
- return true;
- }
-
- /**
- * Assigns the role to be played by this test case. The test parameters are fully specified in the
- * assignment message. When this method return the test case will be ready to execute.
- *
- * @param role The role to be played; sender or receivers.
- *
- * @param assignRoleMessage The role assingment message, contains the full test parameters.
- *
- * @throws JMSException Any JMSException resulting from reading the message are allowed to fall through.
- */
- public void assignRole(Roles role, Message assignRoleMessage) throws JMSException
- {
- log.debug("public void assignRole(Roles role = " + role + ", Message assignRoleMessage = " + assignRoleMessage
- + "): called");
-
- // Reset the message count for a new test.
- messageCount = 0;
-
- // Take note of the role to be played.
- this.role = role;
-
- // Extract and retain the test parameters.
- numMessages = assignRoleMessage.getIntProperty("PUBSUB_NUM_MESSAGES");
- int numReceivers = assignRoleMessage.getIntProperty("PUBSUB_NUM_RECEIVERS");
- String sendKey = assignRoleMessage.getStringProperty("PUBSUB_KEY");
-
- log.debug("numMessages = " + numMessages);
- log.debug("numReceivers = " + numReceivers);
- log.debug("sendKey = " + sendKey);
- log.debug("role = " + role);
-
- switch (role)
- {
- // Check if the sender role is being assigned, and set up a single message producer if so.
- case SENDER:
- // Create a new connection to pass the test messages on.
- connection = new Connection[1];
- session = new Session[1];
-
- connection[0] = TestUtils.createConnection(TestClient.testContextProperties);
- session[0] = connection[0].createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- // Extract and retain the test parameters.
- Destination sendDestination = session[0].createTopic(sendKey);
-
- producer = session[0].createProducer(sendDestination);
- break;
-
- // Otherwise the receivers role is being assigned, so set this up to listen for messages on the required number
- // of receivers connections.
- case RECEIVER:
- // Create the required number of receivers connections.
- connection = new Connection[numReceivers];
- session = new Session[numReceivers];
-
- for (int i = 0; i < numReceivers; i++)
- {
- connection[i] = TestUtils.createConnection(TestClient.testContextProperties);
- session[i] = connection[i].createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- sendDestination = session[i].createTopic(sendKey);
-
- MessageConsumer consumer = session[i].createConsumer(sendDestination);
- consumer.setMessageListener(this);
- }
-
- break;
- }
-
- // Start all the connection dispatcher threads running.
- for (Connection conn : connection)
- {
- conn.start();
- }
- }
-
- /**
- * Performs the test case actions. Returning from here, indicates that the sending role has completed its test.
- *
- * @param numMessages The number of test messages to send.
- *
- * @throws JMSException Any JMSException resulting from reading the message are allowed to fall through.
- */
- public void start(int numMessages) throws JMSException
- {
- log.debug("public void start(): called");
-
- // Check that the sender role is being performed.
- if (role.equals(Roles.SENDER))
- {
- Message testMessage = session[0].createTextMessage("test");
-
- for (int i = 0; i < this.numMessages; i++)
- {
- producer.send(testMessage);
-
- // Increment the message count.
- messageCount++;
- }
- }
- }
-
- /**
- * Gets a report on the actions performed by the test case in its assigned role.
- *
- * @param session The controlSession to create the report message in.
- *
- * @return The report message.
- *
- * @throws JMSException Any JMSExceptions resulting from creating the report are allowed to fall through.
- */
- public Message getReport(Session session) throws JMSException
- {
- log.debug("public Message getReport(Session controlSession): called");
-
- // Close the test connections.
- for (Connection conn : connection)
- {
- conn.close();
- }
-
- // Generate a report message containing the count of the number of messages passed.
- Message report = session.createMessage();
- report.setStringProperty("CONTROL_TYPE", "REPORT");
- report.setIntProperty("MESSAGE_COUNT", messageCount);
-
- return report;
- }
-
- /**
- * Counts incoming test messages.
- *
- * @param message The incoming test message.
- */
- public void onMessage(Message message)
- {
- log.debug("public void onMessage(Message message = " + message + "): called");
-
- // Increment the message count.
- messageCount++;
- }
-}
diff --git a/java/integrationtests/src/main/java/org/apache/qpid/interop/clienttestcases/TestCase4P2PMessageSize.java b/java/integrationtests/src/main/java/org/apache/qpid/interop/clienttestcases/TestCase4P2PMessageSize.java
deleted file mode 100644
index 3730233264..0000000000
--- a/java/integrationtests/src/main/java/org/apache/qpid/interop/clienttestcases/TestCase4P2PMessageSize.java
+++ /dev/null
@@ -1,214 +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.interop.clienttestcases;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.test.framework.TestUtils;
-import org.apache.qpid.test.framework.distributedtesting.TestClient;
-import org.apache.qpid.test.framework.distributedtesting.TestClientControlledTest;
-
-import javax.jms.*;
-
-/**
- * Implements test case 4, P2P messages with message size. Sends/received a specified number of messages to a specified
- * route on the default direct exchange, of a specified size. Produces reports on the actual number of messages
- * sent/received.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Supply the name of the test case that this implements.
- * <tr><td> Accept/Reject invites based on test parameters.
- * <tr><td> Adapt to assigned roles.
- * <tr><td> Send required number of test messages.
- * <tr><td> Generate test reports.
- * </table>
- */
-public class TestCase4P2PMessageSize implements TestClientControlledTest, MessageListener
-{
- /** Used for debugging. */
- private static final Logger log = Logger.getLogger(TestCase4P2PMessageSize.class);
-
- /** Holds the count of test messages received. */
- private int messageCount;
-
- /** The role to be played by the test. */
- private Roles role;
-
- /** The number of test messages to send. */
- private int numMessages;
-
- /** The size of the test messages to send. */
- private int messageSize;
-
- /** The connection to send the test messages on. */
- private Connection connection;
-
- /** The controlSession to send the test messages on. */
- private Session session;
-
- /** The producer to send the test messages with. */
- MessageProducer producer;
-
- /**
- * Should provide the name of the test case that this class implements. The exact names are defined in the
- * interop testing spec.
- *
- * @return The name of the test case that this implements.
- */
- public String getName()
- {
- log.debug("public String getName(): called");
-
- return "TC4_P2PMessageSize";
- }
-
- /**
- * Determines whether the test invite that matched this test case is acceptable.
- *
- * @param inviteMessage The invitation to accept or reject.
- *
- * @return <tt>true</tt> to accept the invitation, <tt>false</tt> to reject it.
- *
- * @throws JMSException Any JMSException resulting from reading the message are allowed to fall through.
- */
- public boolean acceptInvite(Message inviteMessage) throws JMSException
- {
- log.debug("public boolean acceptInvite(Message inviteMessage = " + inviteMessage + "): called");
-
- // All invites are acceptable.
- return true;
- }
-
- /**
- * Assigns the role to be played by this test case. The test parameters are fully specified in the
- * assignment message. When this method return the test case will be ready to execute.
- *
- * @param role The role to be played; sender or receivers.
- *
- * @param assignRoleMessage The role assingment message, contains the full test parameters.
- *
- * @throws JMSException Any JMSException resulting from reading the message are allowed to fall through.
- */
- public void assignRole(Roles role, Message assignRoleMessage) throws JMSException
- {
- log.debug("public void assignRole(Roles role = " + role + ", Message assignRoleMessage = " + assignRoleMessage
- + "): called");
-
- // Reset the message count for a new test.
- messageCount = 0;
-
- // Take note of the role to be played.
- this.role = role;
-
- // Create a new connection to pass the test messages on.
- connection = TestUtils.createConnection(TestClient.testContextProperties);
- session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- // Extract and retain the test parameters.
- numMessages = assignRoleMessage.getIntProperty("P2P_NUM_MESSAGES");
- messageSize = assignRoleMessage.getIntProperty("messageSize");
- Destination sendDestination = session.createQueue(assignRoleMessage.getStringProperty("P2P_QUEUE_AND_KEY_NAME"));
-
- log.debug("numMessages = " + numMessages);
- log.debug("sendDestination = " + sendDestination);
- log.debug("role = " + role);
-
- switch (role)
- {
- // Check if the sender role is being assigned, and set up a message producer if so.
- case SENDER:
- producer = session.createProducer(sendDestination);
- break;
-
- // Otherwise the receivers role is being assigned, so set this up to listen for messages.
- case RECEIVER:
- MessageConsumer consumer = session.createConsumer(sendDestination);
- consumer.setMessageListener(this);
- break;
- }
-
- connection.start();
- }
-
- /**
- * Performs the test case actions. Returning from here, indicates that the sending role has completed its test.
- *
- * @param numMessages The number of test messages to send.
- *
- * @throws JMSException Any JMSException resulting from reading the message are allowed to fall through.
- */
- public void start(int numMessages) throws JMSException
- {
- log.debug("public void start(): called");
-
- // Check that the sender role is being performed.
- if (role.equals(Roles.SENDER))
- {
- Message testMessage = TestUtils.createTestMessageOfSize(session, messageSize);
-
- for (int i = 0; i < this.numMessages; i++)
- {
- producer.send(testMessage);
-
- // Increment the message count.
- messageCount++;
- }
- }
- }
-
- /**
- * Gets a report on the actions performed by the test case in its assigned role.
- *
- * @param session The controlSession to create the report message in.
- *
- * @return The report message.
- *
- * @throws JMSException Any JMSExceptions resulting from creating the report are allowed to fall through.
- */
- public Message getReport(Session session) throws JMSException
- {
- log.debug("public Message getReport(Session controlSession): called");
-
- // Close the test connection.
- connection.close();
-
- // Generate a report message containing the count of the number of messages passed.
- Message report = session.createMessage();
- report.setStringProperty("CONTROL_TYPE", "REPORT");
- report.setIntProperty("MESSAGE_COUNT", messageCount);
-
- return report;
- }
-
- /**
- * Counts incoming test messages.
- *
- * @param message The incoming test message.
- */
- public void onMessage(Message message)
- {
- log.debug("public void onMessage(Message message = " + message + "): called");
-
- // Increment the message count.
- messageCount++;
- }
-}
diff --git a/java/integrationtests/src/main/java/org/apache/qpid/interop/clienttestcases/TestCase5PubSubMessageSize.java b/java/integrationtests/src/main/java/org/apache/qpid/interop/clienttestcases/TestCase5PubSubMessageSize.java
deleted file mode 100644
index f601712bc9..0000000000
--- a/java/integrationtests/src/main/java/org/apache/qpid/interop/clienttestcases/TestCase5PubSubMessageSize.java
+++ /dev/null
@@ -1,243 +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.interop.clienttestcases;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.test.framework.TestUtils;
-import org.apache.qpid.test.framework.distributedtesting.TestClient;
-import org.apache.qpid.test.framework.distributedtesting.TestClientControlledTest;
-
-import javax.jms.*;
-
-/**
- * Implements test case 5, pub/sub with message size. Sends/received a specified number of messages to a specified route
- * on the default topic exchange, using the specified number of receivers connections, and the specified message size.
- * Produces reports on the actual number of messages sent/received.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Supply the name of the test case that this implements.
- * <tr><td> Accept/Reject invites based on test parameters.
- * <tr><td> Adapt to assigned roles.
- * <tr><td> Send required number of test messages using pub/sub.
- * <tr><td> Generate test reports.
- * </table>
- */
-public class TestCase5PubSubMessageSize implements TestClientControlledTest, MessageListener
-{
- /** Used for debugging. */
- private static final Logger log = Logger.getLogger(TestCase5PubSubMessageSize.class);
-
- /** Holds the count of test messages received. */
- private int messageCount;
-
- /** The role to be played by the test. */
- private Roles role;
-
- /** The number of test messages to send. */
- private int numMessages;
-
- /** The size of the test messages to send. */
- private int messageSize;
-
- /** The connections to send/receive the test messages on. */
- private Connection[] connection;
-
- /** The sessions to send/receive the test messages on. */
- private Session[] session;
-
- /** The producer to send the test messages with. */
- MessageProducer producer;
-
- /**
- * Should provide the name of the test case that this class implements. The exact names are defined in the
- * interop testing spec.
- *
- * @return The name of the test case that this implements.
- */
- public String getName()
- {
- log.debug("public String getName(): called");
-
- return "TC5_PubSubMessageSize";
- }
-
- /**
- * Determines whether the test invite that matched this test case is acceptable.
- *
- * @param inviteMessage The invitation to accept or reject.
- *
- * @return <tt>true</tt> to accept the invitation, <tt>false</tt> to reject it.
- *
- * @throws javax.jms.JMSException Any JMSException resulting from reading the message are allowed to fall through.
- */
- public boolean acceptInvite(Message inviteMessage) throws JMSException
- {
- log.debug("public boolean acceptInvite(Message inviteMessage = " + inviteMessage + "): called");
-
- // All invites are acceptable.
- return true;
- }
-
- /**
- * Assigns the role to be played by this test case. The test parameters are fully specified in the
- * assignment message. When this method return the test case will be ready to execute.
- *
- * @param role The role to be played; sender or receivers.
- *
- * @param assignRoleMessage The role assingment message, contains the full test parameters.
- *
- * @throws javax.jms.JMSException Any JMSException resulting from reading the message are allowed to fall through.
- */
- public void assignRole(Roles role, Message assignRoleMessage) throws JMSException
- {
- log.debug("public void assignRole(Roles role = " + role + ", Message assignRoleMessage = " + assignRoleMessage
- + "): called");
-
- // Reset the message count for a new test.
- messageCount = 0;
-
- // Take note of the role to be played.
- this.role = role;
-
- // Extract and retain the test parameters.
- numMessages = assignRoleMessage.getIntProperty("PUBSUB_NUM_MESSAGES");
- messageSize = assignRoleMessage.getIntProperty("messageSize");
- int numReceivers = assignRoleMessage.getIntProperty("PUBSUB_NUM_RECEIVERS");
- String sendKey = assignRoleMessage.getStringProperty("PUBSUB_KEY");
-
- log.debug("numMessages = " + numMessages);
- log.debug("numReceivers = " + numReceivers);
- log.debug("sendKey = " + sendKey);
- log.debug("role = " + role);
-
- switch (role)
- {
- // Check if the sender role is being assigned, and set up a single message producer if so.
- case SENDER:
- // Create a new connection to pass the test messages on.
- connection = new Connection[1];
- session = new Session[1];
-
- connection[0] = TestUtils.createConnection(TestClient.testContextProperties);
- session[0] = connection[0].createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- // Extract and retain the test parameters.
- Destination sendDestination = session[0].createTopic(sendKey);
-
- producer = session[0].createProducer(sendDestination);
- break;
-
- // Otherwise the receivers role is being assigned, so set this up to listen for messages on the required number
- // of receivers connections.
- case RECEIVER:
- // Create the required number of receivers connections.
- connection = new Connection[numReceivers];
- session = new Session[numReceivers];
-
- for (int i = 0; i < numReceivers; i++)
- {
- connection[i] = TestUtils.createConnection(TestClient.testContextProperties);
- session[i] = connection[i].createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- sendDestination = session[i].createTopic(sendKey);
-
- MessageConsumer consumer = session[i].createConsumer(sendDestination);
- consumer.setMessageListener(this);
- }
-
- break;
- }
-
- // Start all the connection dispatcher threads running.
- for (Connection conn : connection)
- {
- conn.start();
- }
- }
-
- /**
- * Performs the test case actions. Returning from here, indicates that the sending role has completed its test.
- *
- * @param numMessages The number of test messages to send.
- *
- * @throws JMSException Any JMSException resulting from reading the message are allowed to fall through.
- */
- public void start(int numMessages) throws JMSException
- {
- log.debug("public void start(): called");
-
- // Check that the sender role is being performed.
- if (role.equals(Roles.SENDER))
- {
- Message testMessage = TestUtils.createTestMessageOfSize(session[0], messageSize);
-
- for (int i = 0; i < this.numMessages; i++)
- {
- producer.send(testMessage);
-
- // Increment the message count.
- messageCount++;
- }
- }
- }
-
- /**
- * Gets a report on the actions performed by the test case in its assigned role.
- *
- * @param session The controlSession to create the report message in.
- *
- * @return The report message.
- *
- * @throws javax.jms.JMSException Any JMSExceptions resulting from creating the report are allowed to fall through.
- */
- public Message getReport(Session session) throws JMSException
- {
- log.debug("public Message getReport(Session controlSession): called");
-
- // Close the test connections.
- for (Connection conn : connection)
- {
- conn.close();
- }
-
- // Generate a report message containing the count of the number of messages passed.
- Message report = session.createMessage();
- report.setStringProperty("CONTROL_TYPE", "REPORT");
- report.setIntProperty("MESSAGE_COUNT", messageCount);
-
- return report;
- }
-
- /**
- * Counts incoming test messages.
- *
- * @param message The incoming test message.
- */
- public void onMessage(Message message)
- {
- log.debug("public void onMessage(Message message = " + message + "): called");
-
- // Increment the message count.
- messageCount++;
- }
-}
diff --git a/java/integrationtests/src/main/java/org/apache/qpid/interop/testcases/InteropTestCase1DummyRun.java b/java/integrationtests/src/main/java/org/apache/qpid/interop/testcases/InteropTestCase1DummyRun.java
deleted file mode 100644
index a2e4a00aa6..0000000000
--- a/java/integrationtests/src/main/java/org/apache/qpid/interop/testcases/InteropTestCase1DummyRun.java
+++ /dev/null
@@ -1,84 +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.interop.testcases;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.test.framework.FrameworkBaseCase;
-
-import java.util.Properties;
-
-/**
- * Coordinates test case 1, from the interop test specification. This test connects up the sender and receivers roles,
- * and gets some dummy test reports from them, in order to check that the test framework itself is operational.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Exercises the interop testing framework without actually sending any test messages.
- * <td> {@link FrameworkBaseCase}
- * </table>
- */
-public class InteropTestCase1DummyRun extends FrameworkBaseCase
-{
- /** Used for debugging. */
- private static final Logger log = Logger.getLogger(InteropTestCase1DummyRun.class);
-
- /**
- * Creates a new coordinating test case with the specified name.
- *
- * @param name The test case name.
- */
- public InteropTestCase1DummyRun(String name)
- {
- super(name);
- }
-
- /**
- * Performs the basic P2P test case, "Test Case 2" in the specification.
- *
- * @throws Exception Any exceptions are allowed to fall through and fail the test.
- */
- public void testDummyRun() throws Exception
- {
- log.debug("public void testDummyRun(): called");
-
- Properties testConfig = new Properties();
- testConfig.put("TEST_NAME", "TC1_DummyRun");
-
- /*Message[] reports =*/ getCircuitFactory().sequenceTest(null, null, testConfig);
-
- // Compare sender and receivers reports.
- // Assert.assertEquals("Expected to get 2 dummy reports.", 2, reports.length);
- }
-
- /**
- * Should provide a translation from the junit method name of a test to its test case name as defined in the
- * interop testing specification. For example the method "testP2P" might map onto the interop test case name
- * "TC2_BasicP2P".
- *
- * @param methodName The name of the JUnit test method.
- * @return The name of the corresponding interop test case.
- */
- public String getTestCaseNameForTestMethod(String methodName)
- {
- return "TC1_DummyRun";
- }
-}
diff --git a/java/integrationtests/src/main/java/org/apache/qpid/interop/testcases/InteropTestCase2BasicP2P.java b/java/integrationtests/src/main/java/org/apache/qpid/interop/testcases/InteropTestCase2BasicP2P.java
deleted file mode 100644
index 6d6515f1fd..0000000000
--- a/java/integrationtests/src/main/java/org/apache/qpid/interop/testcases/InteropTestCase2BasicP2P.java
+++ /dev/null
@@ -1,90 +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.interop.testcases;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.test.framework.FrameworkBaseCase;
-
-import java.util.Properties;
-
-/**
- * Implements test case 2, from the interop test specification. This test sets up the TC2_BasicP2P test for 50
- * messages. It checks that the sender and receivers reports both indicate that all the test messages were transmitted
- * successfully.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Setup p2p test parameters and compare with test output. <td> {@link FrameworkBaseCase}
- * </table>
- */
-public class InteropTestCase2BasicP2P extends FrameworkBaseCase
-{
- /** Used for debugging. */
- private static final Logger log = Logger.getLogger(InteropTestCase2BasicP2P.class);
-
- /**
- * Creates a new coordinating test case with the specified name.
- *
- * @param name The test case name.
- */
- public InteropTestCase2BasicP2P(String name)
- {
- super(name);
- }
-
- /**
- * Performs the basic P2P test case, "Test Case 2" in the specification.
- *
- * @throws Exception Any exceptions are allowed to fall through and fail the test.
- */
- public void testBasicP2P() throws Exception
- {
- log.debug("public void testBasicP2P(): called");
-
- Properties testConfig = new Properties();
- testConfig.setProperty("TEST_NAME", "TC2_BasicP2P");
- testConfig.setProperty("P2P_QUEUE_AND_KEY_NAME", "tc2queue");
- testConfig.put("P2P_NUM_MESSAGES", 50);
-
- /*Message[] reports =*/ getCircuitFactory().sequenceTest(null, null, testConfig);
-
- // Compare sender and receivers reports.
- /*int messagesSent = reports[0].getIntProperty("MESSAGE_COUNT");
- int messagesReceived = reports[1].getIntProperty("MESSAGE_COUNT");
-
- Assert.assertEquals("The requested number of messages were not sent.", 50, messagesSent);
- Assert.assertEquals("Sender and receivers messages sent did not match up.", messagesSent, messagesReceived);*/
- }
-
- /**
- * Should provide a translation from the junit method name of a test to its test case name as defined in the
- * interop testing specification. For example the method "testP2P" might map onto the interop test case name
- * "TC2_BasicP2P".
- *
- * @param methodName The name of the JUnit test method.
- * @return The name of the corresponding interop test case.
- */
- public String getTestCaseNameForTestMethod(String methodName)
- {
- return "TC2_BasicP2P";
- }
-}
diff --git a/java/integrationtests/src/main/java/org/apache/qpid/interop/testcases/InteropTestCase3BasicPubSub.java b/java/integrationtests/src/main/java/org/apache/qpid/interop/testcases/InteropTestCase3BasicPubSub.java
deleted file mode 100644
index 2faca91e73..0000000000
--- a/java/integrationtests/src/main/java/org/apache/qpid/interop/testcases/InteropTestCase3BasicPubSub.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.interop.testcases;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.test.framework.FrameworkBaseCase;
-
-import java.util.Properties;
-
-/**
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Setup pub/sub test parameters and compare with test output. <td> {@link FrameworkBaseCase}
- * </table>
- */
-public class InteropTestCase3BasicPubSub extends FrameworkBaseCase
-{
- /** Used for debugging. */
- private static final Logger log = Logger.getLogger(InteropTestCase3BasicPubSub.class);
-
- /**
- * Creates a new coordinating test case with the specified name.
- *
- * @param name The test case name.
- */
- public InteropTestCase3BasicPubSub(String name)
- {
- super(name);
- }
-
- /**
- * Performs the basic P2P test case, "Test Case 2" in the specification.
- *
- * @throws Exception Any exceptions are allowed to fall through and fail the test.
- */
- public void testBasicPubSub() throws Exception
- {
- log.debug("public void testBasicPubSub(): called");
-
- Properties testConfig = new Properties();
- testConfig.put("TEST_NAME", "TC3_BasicPubSub");
- testConfig.put("PUBSUB_KEY", "tc3route");
- testConfig.put("PUBSUB_NUM_MESSAGES", 10);
- testConfig.put("PUBSUB_NUM_RECEIVERS", 5);
-
- /*Message[] reports =*/ getCircuitFactory().sequenceTest(null, null, testConfig);
-
- // Compare sender and receivers reports.
- /*int messagesSent = reports[0].getIntProperty("MESSAGE_COUNT");
- int messagesReceived = reports[1].getIntProperty("MESSAGE_COUNT");
-
- Assert.assertEquals("The requested number of messages were not sent.", 10, messagesSent);
- Assert.assertEquals("Received messages did not match up to num sent * num receivers.", messagesSent * 5,
- messagesReceived);*/
- }
-
- /**
- * Should provide a translation from the junit method name of a test to its test case name as defined in the
- * interop testing specification. For example the method "testP2P" might map onto the interop test case name
- * "TC2_BasicP2P".
- *
- * @param methodName The name of the JUnit test method.
- * @return The name of the corresponding interop test case.
- */
- public String getTestCaseNameForTestMethod(String methodName)
- {
- return "TC3_BasicPubSub";
- }
-}
diff --git a/java/integrationtests/src/main/java/org/apache/qpid/interop/testcases/InteropTestCase4P2PMessageSize.java b/java/integrationtests/src/main/java/org/apache/qpid/interop/testcases/InteropTestCase4P2PMessageSize.java
deleted file mode 100644
index 2d64f2b805..0000000000
--- a/java/integrationtests/src/main/java/org/apache/qpid/interop/testcases/InteropTestCase4P2PMessageSize.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.interop.testcases;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.test.framework.FrameworkBaseCase;
-
-import java.util.Properties;
-
-/**
- * Implements test case 4, from the interop test specification. This test sets up the TC2_P2PMessageSize test for 50
- * messages, and a variety of message sizes. It checks that the sender and receivers reports both indicate that all
- * the test messages were transmitted successfully.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Setup p2p test parameters and compare with test output. <td> {@link FrameworkBaseCase}
- * </table>
- */
-public class InteropTestCase4P2PMessageSize extends FrameworkBaseCase
-{
- /** Used for debugging. */
- private static final Logger log = Logger.getLogger(InteropTestCase4P2PMessageSize.class);
-
- /**
- * Creates a new coordinating test case with the specified name.
- *
- * @param name The test case name.
- */
- public InteropTestCase4P2PMessageSize(String name)
- {
- super(name);
- }
-
- /**
- * Performs the P2P message test case, "Test Case 4" in the specification, for messages 0K in size.
- *
- * @throws Exception Any exceptions are allowed to fall through and fail the test.
- */
- public void testP2PMessageSize0K() throws Exception
- {
- runTestForMessagesOfSize(0);
- }
-
- /**
- * Performs the P2P message test case, "Test Case 4" in the specification, for messages 63K in size.
- *
- * @throws Exception Any exceptions are allowed to fall through and fail the test.
- */
- public void testP2PMessageSize63K() throws Exception
- {
- runTestForMessagesOfSize(63 * 1024);
- }
-
- /**
- * Performs the P2P message test case, "Test Case 4" in the specification, for messages 64K in size.
- *
- * @throws Exception Any exceptions are allowed to fall through and fail the test.
- */
- public void testP2PMessageSize64K() throws Exception
- {
- runTestForMessagesOfSize(64 * 1024);
- }
-
- /**
- * Performs the P2P message test case, "Test Case 4" in the specification, for messages 65K in size.
- *
- * @throws Exception Any exceptions are allowed to fall through and fail the test.
- */
- public void testP2PMessageSize65K() throws Exception
- {
- runTestForMessagesOfSize(65 * 1024);
- }
-
- /**
- * Performs the P2P message test case, "Test Case 4" in the specification, for messages 127K in size.
- *
- * @throws Exception Any exceptions are allowed to fall through and fail the test.
- */
- public void testP2PMessageSize127K() throws Exception
- {
- runTestForMessagesOfSize(127 * 1024);
- }
-
- /**
- * Performs the P2P message test case, "Test Case 4" in the specification, for messages 128K in size.
- *
- * @throws Exception Any exceptions are allowed to fall through and fail the test.
- */
- public void testP2PMessageSize128K() throws Exception
- {
- runTestForMessagesOfSize(128 * 1024);
- }
-
- /**
- * Performs the P2P message test case, "Test Case 4" in the specification, for messages 129K in size.
- *
- * @throws Exception Any exceptions are allowed to fall through and fail the test.
- */
- public void testP2PMessageSize129K() throws Exception
- {
- runTestForMessagesOfSize(129 * 1024);
- }
-
- /**
- * Performs the P2P message test case, "Test Case 4" in the specification, for messages 255K in size.
- *
- * @throws Exception Any exceptions are allowed to fall through and fail the test.
- */
- public void testP2PMessageSize255K() throws Exception
- {
- runTestForMessagesOfSize(255 * 1024);
- }
-
- /**
- * Performs the P2P message test case, "Test Case 4" in the specification, for messages 256K in size.
- *
- * @throws Exception Any exceptions are allowed to fall through and fail the test.
- */
- public void testP2PMessageSize256K() throws Exception
- {
- runTestForMessagesOfSize(256 * 1024);
- }
-
- /**
- * Performs the P2P message test case, "Test Case 4" in the specification, for messages 257K in size.
- *
- * @throws Exception Any exceptions are allowed to fall through and fail the test.
- */
- public void testP2PMessageSize257K() throws Exception
- {
- runTestForMessagesOfSize(257 * 1024);
- }
-
- /**
- * Sends 50 test messages of the specified size, and asserts that all were received.
- *
- * @param size The size of the messages to send in bytes.
- */
- private void runTestForMessagesOfSize(int size)
- {
- Properties testConfig = new Properties();
- testConfig.setProperty("TEST_NAME", "TC4_P2PMessageSize");
- testConfig.setProperty("P2P_QUEUE_AND_KEY_NAME", "tc2queue");
- testConfig.put("P2P_NUM_MESSAGES", 50);
- testConfig.put("messageSize", size);
-
- /*Message[] reports =*/
- getCircuitFactory().sequenceTest(null, null, testConfig);
-
- // Compare sender and receivers reports.
- /*
- int messagesSent = reports[0].getIntProperty("MESSAGE_COUNT");
- int messagesReceived = reports[1].getIntProperty("MESSAGE_COUNT");
-
- Assert.assertEquals("The requested number of messages were not sent.", 50, messagesSent);
- Assert.assertEquals("Sender and receivers messages sent did not match up.", messagesSent, messagesReceived);
- */
- }
-
- /**
- * Should provide a translation from the junit method name of a test to its test case name as defined in the
- * interop testing specification. For example the method "testP2P" might map onto the interop test case name
- * "TC2_BasicP2P".
- *
- * @param methodName The name of the JUnit test method.
- *
- * @return The name of the corresponding interop test case.
- */
- public String getTestCaseNameForTestMethod(String methodName)
- {
- return "TC4_P2PMessageSize";
- }
-}
diff --git a/java/integrationtests/src/main/java/org/apache/qpid/interop/testcases/InteropTestCase5PubSubMessageSize.java b/java/integrationtests/src/main/java/org/apache/qpid/interop/testcases/InteropTestCase5PubSubMessageSize.java
deleted file mode 100644
index 23d33fc115..0000000000
--- a/java/integrationtests/src/main/java/org/apache/qpid/interop/testcases/InteropTestCase5PubSubMessageSize.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.interop.testcases;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.test.framework.FrameworkBaseCase;
-
-import java.util.Properties;
-
-/**
- * Implements test case 5, from the interop test specification. This test sets up the TC2_PubSubMessageSize test for 10
- * messages, sent to 5 consumers, and a variety of message sizes. It checks that the sender and receivers reports both
- * indicate that all the test messages were transmitted successfully.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Setup pub/sub test parameters and compare with test output. <td> {@link FrameworkBaseCase}
- * </table>
- */
-public class InteropTestCase5PubSubMessageSize extends FrameworkBaseCase
-{
- /** Used for debugging. */
- private static final Logger log = Logger.getLogger(InteropTestCase5PubSubMessageSize.class);
-
- /**
- * Creates a new coordinating test case with the specified name.
- *
- * @param name The test case name.
- */
- public InteropTestCase5PubSubMessageSize(String name)
- {
- super(name);
- }
-
- /**
- * Performs the P2P message test case, "Test Case 4" in the specification, for messages 0K in size.
- *
- * @throws Exception Any exceptions are allowed to fall through and fail the test.
- */
- public void testPubSubMessageSize0K() throws Exception
- {
- runTestForMessagesOfSize(0);
- }
-
- /**
- * Performs the P2P message test case, "Test Case 4" in the specification, for messages 63K in size.
- *
- * @throws Exception Any exceptions are allowed to fall through and fail the test.
- */
- public void testPubSubMessageSize63K() throws Exception
- {
- runTestForMessagesOfSize(63 * 1024);
- }
-
- /**
- * Performs the P2P message test case, "Test Case 4" in the specification, for messages 64K in size.
- *
- * @throws Exception Any exceptions are allowed to fall through and fail the test.
- */
- public void testPubSubMessageSize64K() throws Exception
- {
- runTestForMessagesOfSize(64 * 1024);
- }
-
- /**
- * Performs the P2P message test case, "Test Case 4" in the specification, for messages 65K in size.
- *
- * @throws Exception Any exceptions are allowed to fall through and fail the test.
- */
- public void testPubSubMessageSize65K() throws Exception
- {
- runTestForMessagesOfSize(65 * 1024);
- }
-
- /**
- * Performs the P2P message test case, "Test Case 4" in the specification, for messages 127K in size.
- *
- * @throws Exception Any exceptions are allowed to fall through and fail the test.
- */
- public void testPubSubMessageSize127K() throws Exception
- {
- runTestForMessagesOfSize(127 * 1024);
- }
-
- /**
- * Performs the P2P message test case, "Test Case 4" in the specification, for messages 128K in size.
- *
- * @throws Exception Any exceptions are allowed to fall through and fail the test.
- */
- public void testPubSubMessageSize128K() throws Exception
- {
- runTestForMessagesOfSize(128 * 1024);
- }
-
- /**
- * Performs the P2P message test case, "Test Case 4" in the specification, for messages 129K in size.
- *
- * @throws Exception Any exceptions are allowed to fall through and fail the test.
- */
- public void testPubSubMessageSize129K() throws Exception
- {
- runTestForMessagesOfSize(129 * 1024);
- }
-
- /**
- * Performs the P2P message test case, "Test Case 4" in the specification, for messages 255K in size.
- *
- * @throws Exception Any exceptions are allowed to fall through and fail the test.
- */
- public void testPubSubMessageSize255K() throws Exception
- {
- runTestForMessagesOfSize(255 * 1024);
- }
-
- /**
- * Performs the P2P message test case, "Test Case 4" in the specification, for messages 256K in size.
- *
- * @throws Exception Any exceptions are allowed to fall through and fail the test.
- */
- public void testPubSubMessageSize256K() throws Exception
- {
- runTestForMessagesOfSize(256 * 1024);
- }
-
- /**
- * Performs the P2P message test case, "Test Case 4" in the specification, for messages 257K in size.
- *
- * @throws Exception Any exceptions are allowed to fall through and fail the test.
- */
- public void testPubSubMessageSize257K() throws Exception
- {
- runTestForMessagesOfSize(257 * 1024);
- }
-
- /**
- * Sends 50 test messages of the specified size, and asserts that all were received.
- *
- * @param size The size of the messages to send in bytes.
- */
- private void runTestForMessagesOfSize(int size)
- {
- Properties testConfig = new Properties();
- testConfig.put("TEST_NAME", "TC5_PubSubMessageSize");
- testConfig.put("PUBSUB_KEY", "tc3route");
- testConfig.put("PUBSUB_NUM_MESSAGES", 10);
- testConfig.put("PUBSUB_NUM_RECEIVERS", 5);
- testConfig.put("messageSize", size);
-
- /*Message[] reports =*/
- getCircuitFactory().sequenceTest(null, null, testConfig);
-
- // Compare sender and receivers reports.
- /*
- int messagesSent = reports[0].getIntProperty("MESSAGE_COUNT");
- int messagesReceived = reports[1].getIntProperty("MESSAGE_COUNT");
-
- Assert.assertEquals("The requested number of messages were not sent.", 50, messagesSent);
- Assert.assertEquals("Sender and receivers messages sent did not match up.", messagesSent, messagesReceived);
- */
- }
-
- /**
- * Should provide a translation from the junit method name of a test to its test case name as defined in the
- * interop testing specification. For example the method "testP2P" might map onto the interop test case name
- * "TC2_BasicP2P".
- *
- * @param methodName The name of the JUnit test method.
- * @return The name of the corresponding interop test case.
- */
- public String getTestCaseNameForTestMethod(String methodName)
- {
- return "TC5_PubSubMessageSize";
- }
-}
diff --git a/java/integrationtests/src/main/java/org/apache/qpid/sustained/SustainedClientTestCase.java b/java/integrationtests/src/main/java/org/apache/qpid/sustained/SustainedClientTestCase.java
deleted file mode 100644
index 63e2c75509..0000000000
--- a/java/integrationtests/src/main/java/org/apache/qpid/sustained/SustainedClientTestCase.java
+++ /dev/null
@@ -1,906 +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.sustained;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.client.AMQNoConsumersException;
-import org.apache.qpid.client.AMQNoRouteException;
-import org.apache.qpid.test.framework.distributedtesting.TestClient;
-import org.apache.qpid.interop.clienttestcases.TestCase3BasicPubSub;
-import org.apache.qpid.test.framework.TestUtils;
-
-import javax.jms.Connection;
-import javax.jms.Destination;
-import javax.jms.ExceptionListener;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageListener;
-import javax.jms.MessageProducer;
-import javax.jms.Session;
-import javax.jms.TextMessage;
-
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.concurrent.CountDownLatch;
-
-/**
- * Implements test case 3, basic pub/sub. Sends/received a specified number of messages to a specified route on the
- * default topic exchange, using the specified number of receivers connections. Produces reports on the actual number of
- * messages sent/received.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Supply the name of the test case that this implements.
- * <tr><td> Accept/Reject invites based on test parameters.
- * <tr><td> Adapt to assigned roles.
- * <tr><td> Send required number of test messages using pub/sub. <tr><td> Generate test reports.
- * </table>
- */
-public class SustainedClientTestCase extends TestCase3BasicPubSub implements ExceptionListener, MessageListener
-{
- /** Used for debugging. */
- private static final Logger log = Logger.getLogger(SustainedClientTestCase.class);
-
- /** Used to log to the console. */
- private static final Logger console = Logger.getLogger("SustainedTest");
-
- /** The role to be played by the test. */
- private Roles role;
-
- /** The number of receivers connection to use. */
- private int numReceivers;
-
- /** The routing key to send them to on the default direct exchange. */
- private Destination sendDestination;
-
- /** The routing key to send updates to on the default direct exchange. */
- private Destination sendUpdateDestination;
-
- /** The connections to send/receive the test messages on. */
- private Connection[] connection;
-
- /** The sessions to send/receive the test messages on. */
- private Session[] session;
-
- /** The producer to send the test messages with. */
- MessageProducer producer;
-
- /** Adapter that adjusts the send rate based on the updates from clients. */
- SustainedRateAdapter _rateAdapter;
-
- /** */
- int _batchSize;
-
- private static final long TEN_MILLI_SEC = 10000000;
- private static final int DEBUG_LOG_UPATE_INTERVAL = 10;
- private static final int LOG_UPATE_INTERVAL = 10;
- private static final boolean SLEEP_PER_MESSAGE = Boolean.getBoolean("sleepPerMessage");
-
- /**
- * Should provide the name of the test case that this class implements. The exact names are defined in the interop
- * testing spec.
- *
- * @return The name of the test case that this implements.
- */
- public String getName()
- {
- log.debug("public String getName(): called");
-
- return "Perf_SustainedPubSub";
- }
-
- /**
- * Assigns the role to be played by this test case. The test parameters are fully specified in the assignment
- * message. When this method return the test case will be ready to execute.
- *
- * @param role The role to be played; sender or receivers.
- * @param assignRoleMessage The role assingment message, contains the full test parameters.
- *
- * @throws JMSException Any JMSException resulting from reading the message are allowed to fall through.
- */
- public void assignRole(Roles role, Message assignRoleMessage) throws JMSException
- {
- log.debug("public void assignRole(Roles role = " + role + ", Message assignRoleMessage = " + assignRoleMessage
- + "): called");
-
- // Take note of the role to be played.
- this.role = role;
-
- // Extract and retain the test parameters.
- numReceivers = assignRoleMessage.getIntProperty("SUSTAINED_NUM_RECEIVERS");
- _batchSize = assignRoleMessage.getIntProperty("SUSTAINED_UPDATE_INTERVAL");
- String sendKey = assignRoleMessage.getStringProperty("SUSTAINED_KEY");
- String sendUpdateKey = assignRoleMessage.getStringProperty("SUSTAINED_UPDATE_KEY");
- int ackMode = assignRoleMessage.getIntProperty("ACKNOWLEDGE_MODE");
- String clientName = assignRoleMessage.getStringProperty("CLIENT_NAME");
-
- if (log.isDebugEnabled())
- {
- log.debug("numReceivers = " + numReceivers);
- log.debug("_batchSize = " + _batchSize);
- log.debug("ackMode = " + ackMode);
- log.debug("sendKey = " + sendKey);
- log.debug("sendUpdateKey = " + sendUpdateKey);
- log.debug("role = " + role);
- }
-
- switch (role)
- {
- // Check if the sender role is being assigned, and set up a single message producer if so.
- case SENDER:
- console.info("Creating Sender");
- // Create a new connection to pass the test messages on.
- connection = new Connection[1];
- session = new Session[1];
-
- connection[0] = TestUtils.createConnection(TestClient.testContextProperties);
- session[0] = connection[0].createSession(false, ackMode);
-
- // Extract and retain the test parameters.
- sendDestination = session[0].createTopic(sendKey);
-
- connection[0].setExceptionListener(this);
-
- producer = session[0].createProducer(sendDestination);
-
- sendUpdateDestination = session[0].createTopic(sendUpdateKey);
- MessageConsumer updateConsumer = session[0].createConsumer(sendUpdateDestination);
-
- _rateAdapter = new SustainedRateAdapter(this);
- updateConsumer.setMessageListener(_rateAdapter);
-
- break;
-
- // Otherwise the receivers role is being assigned, so set this up to listen for messages on the required number
- // of receivers connections.
- case RECEIVER:
- console.info("Creating Receiver");
- // Create the required number of receivers connections.
- connection = new Connection[numReceivers];
- session = new Session[numReceivers];
-
- for (int i = 0; i < numReceivers; i++)
- {
- connection[i] = TestUtils.createConnection(TestClient.testContextProperties);
- session[i] = connection[i].createSession(false, ackMode);
-
- sendDestination = session[i].createTopic(sendKey);
-
- sendUpdateDestination = session[i].createTopic(sendUpdateKey);
-
- MessageConsumer consumer = session[i].createConsumer(sendDestination);
-
- consumer.setMessageListener(new SustainedListener(clientName + "-" + i, _batchSize, session[i],
- sendUpdateDestination));
- }
-
- break;
- }
-
- // Start all the connection dispatcher threads running.
- for (int i = 0; i < connection.length; i++)
- {
- connection[i].start();
- }
- }
-
- /** Performs the test case actions.
- * @param numMessages*/
- public void start(int numMessages) throws JMSException
- {
- log.debug("public void start(): called");
-
- // Check that the sender role is being performed.
- switch (role)
- {
- // Check if the sender role is being assigned, and set up a single message producer if so.
- case SENDER:
- _rateAdapter.run();
- break;
- case RECEIVER:
-
- }
-
- // return from here when you have finished the test.. this will signal the controller and
- }
-
- public void terminate() throws JMSException, InterruptedException
- {
- if (_rateAdapter != null)
- {
- _rateAdapter.stop();
- }
- }
-
- /**
- * Gets a report on the actions performed by the test case in its assigned role.
- *
- * @param session The controlSession to create the report message in.
- *
- * @return The report message.
- *
- * @throws JMSException Any JMSExceptions resulting from creating the report are allowed to fall through.
- */
- public Message getReport(Session session) throws JMSException
- {
- log.debug("public Message getReport(Session controlSession): called");
-
- // Close the test connections.
- for (int i = 0; i < connection.length; i++)
- {
- connection[i].close();
- }
-
- Message report = session.createMessage();
- report.setStringProperty("CONTROL_TYPE", "REPORT");
-
- return report;
- }
-
- public void onException(JMSException jmsException)
- {
- Exception linked = jmsException.getLinkedException();
-
- if (linked != null)
- {
- if (log.isDebugEnabled())
- {
- log.debug("Linked Exception:" + linked);
- }
-
- if ((linked instanceof AMQNoRouteException) || (linked instanceof AMQNoConsumersException))
- {
- if (log.isDebugEnabled())
- {
- if (linked instanceof AMQNoConsumersException)
- {
- log.warn("No clients currently available for message:"
- + ((AMQNoConsumersException) linked).getUndeliveredMessage());
- }
- else
- {
- log.warn("No route for message");
- }
- }
-
- // Tell the rate adapter that there are no clients ready yet
- _rateAdapter.NO_CLIENTS = true;
- }
- }
- else
- {
- log.warn("Exception:" + linked);
- }
- }
-
- /**
- * Inner class that listens for messages and sends a report for the time taken between receiving the 'start' and
- * 'end' messages.
- */
- class SustainedListener implements MessageListener
- {
- /** Number of messages received */
- private long _received = 0;
- /** The number of messages in the batch */
- private int _batchSize = 0;
- /** Record of the when the 'start' messagse was sen */
- private Long _startTime;
- /** Message producer to use to send reports */
- MessageProducer _updater;
- /** Session to create the report message on */
- Session _session;
- /** Record of the client ID used for this SustainedListnener */
- String _client;
-
- /**
- * Main Constructor
- *
- * @param clientname The _client id used to identify this connection.
- * @param batchSize The number of messages that are to be sent per batch. Note: This is not used to
- * control the interval between sending reports.
- * @param session The controlSession used for communication.
- * @param sendDestination The destination that update reports should be sent to.
- *
- * @throws JMSException My occur if creatingthe Producer fails
- */
- public SustainedListener(String clientname, int batchSize, Session session, Destination sendDestination)
- throws JMSException
- {
- _batchSize = batchSize;
- _client = clientname;
- _session = session;
- _updater = session.createProducer(sendDestination);
- }
-
- public void onMessage(Message message)
- {
- if (log.isDebugEnabled())
- {
- log.debug("Message " + _received + "received in listener");
- }
-
- if (message instanceof TextMessage)
- {
- try
- {
- _received++;
- if (((TextMessage) message).getText().equals("start"))
- {
- log.debug("Starting Batch");
- _startTime = System.nanoTime();
- }
- else if (((TextMessage) message).getText().equals("end"))
- {
- if (_startTime != null)
- {
- long currentTime = System.nanoTime();
- sendStatus(currentTime - _startTime, _received, message.getIntProperty("BATCH"));
- log.debug("End Batch");
- }
- }
- }
- catch (JMSException e)
- {
- // ignore error
- }
- }
-
- }
-
- /**
- * sendStatus creates and sends the report back to the publisher
- *
- * @param time taken for the the last batch
- * @param received Total number of messages received.
- * @param batchNumber the batch number
- * @throws JMSException if an error occurs during the send
- */
- private void sendStatus(long time, long received, int batchNumber) throws JMSException
- {
- Message updateMessage = _session.createTextMessage("update");
- updateMessage.setStringProperty("CLIENT_ID", ":" + _client);
- updateMessage.setStringProperty("CONTROL_TYPE", "UPDATE");
- updateMessage.setLongProperty("RECEIVED", received);
- updateMessage.setIntProperty("BATCH", batchNumber);
- updateMessage.setLongProperty("DURATION", time);
-
- if (log.isInfoEnabled())
- {
- log.info("**** SENDING [" + batchNumber + "]**** " + "CLIENT_ID:" + _client + " RECEIVED:" + received
- + " BATCH:" + batchNumber + " DURATION:" + time);
- }
-
- // Output on the main console.info the details of this batch
- if ((batchNumber % 10) == 0)
- {
- console.info("Sending Report [" + batchNumber + "] " + "CLIENT_ID:" + _client + " RECEIVED:" + received
- + " BATCH:" + batchNumber + " DURATION:" + time);
- }
-
- _updater.send(updateMessage);
- }
- }
-
- /**
- * This class is used here to adjust the _delay value which in turn is used to control the number of messages/second
- * that are sent through the test system.
- *
- * By keeping a record of the messages recevied and the average time taken to process the batch size can be
- * calculated and so the delay can be adjusted to maintain that rate.
- *
- * Given that delays of < 10ms can be rounded up the delay is only used between messages if the _delay > 10ms * no
- * messages in the batch. Otherwise the delay is used at the end of the batch.
- */
- class SustainedRateAdapter implements MessageListener, Runnable
- {
- private SustainedClientTestCase _client;
- private long _batchVariance = Integer.getInteger("batchVariance", 3); // no. batches to allow drifting
- private long _timeVariance = TEN_MILLI_SEC * 5; // no. nanos between send and report delay (10ms)
- private volatile long _delay; // in nanos
- private long _sent;
- private Map<String, Long> _slowClients = new HashMap<String, Long>();
- private static final long PAUSE_SLEEP = TEN_MILLI_SEC / 1000; // 10 ms
- private static final long NO_CLIENT_SLEEP = 1000; // 1s
- private volatile boolean NO_CLIENTS = true;
- private int _delayShifting;
- private final int REPORTS_WITHOUT_CHANGE = Integer.getInteger("stableReportCount", 5);
- private boolean _warmedup = false;
- private static final long EXPECTED_TIME_PER_BATCH = 100000L;
- private int _warmUpBatches = Integer.getInteger("warmUpBatches", 10);
-
- SustainedRateAdapter(SustainedClientTestCase client)
- {
- _client = client;
- }
-
- public void onMessage(Message message)
- {
- if (log.isDebugEnabled())
- {
- log.debug("SustainedRateAdapter onMessage(Message message = " + message + "): called");
- }
-
- try
- {
- String controlType = message.getStringProperty("CONTROL_TYPE");
-
- // Check if the message is a test invite.
- if ("UPDATE".equals(controlType))
- {
- NO_CLIENTS = false;
- long duration = message.getLongProperty("DURATION");
- long totalReceived = message.getLongProperty("RECEIVED");
- String client = message.getStringProperty("CLIENT_ID");
- int batchNumber = message.getIntProperty("BATCH");
-
- if (log.isInfoEnabled() && ((batchNumber % DEBUG_LOG_UPATE_INTERVAL) == 0))
- {
- log.info("Update Report: CLIENT_ID:" + client + " RECEIVED:" + totalReceived + " Recevied BATCH:"
- + batchNumber + " DURATION:" + duration);
- }
-
- recordSlow(client, totalReceived, batchNumber);
-
- adjustDelay(client, batchNumber, duration);
-
- // Warm up completes when:
- // we haven't warmed up
- // and the number of batches sent to each client is at least half of the required warmup batches
- if (!_warmedup && (batchNumber >= _warmUpBatches))
- {
- _warmedup = true;
- _warmup.countDown();
-
- }
- }
- }
- catch (JMSException e)
- {
- //
- }
- }
-
- CountDownLatch _warmup = new CountDownLatch(1);
-
- int _numBatches = 10000;
-
- // long[] _timings = new long[_numBatches];
- private boolean _running = true;
-
- public void run()
- {
- console.info("Warming up");
-
- doBatch(_warmUpBatches);
-
- try
- {
- // wait for warmup to complete.
- _warmup.await();
-
- // set delay to the average length of the batches
- _delay = _totalDuration / _warmUpBatches / delays.size();
-
- console.info("Warmup complete delay set : " + _delay + " based on _totalDuration: " + _totalDuration
- + " over no. batches: " + _warmUpBatches + " with client count: " + delays.size());
-
- _totalDuration = 0L;
- _totalReceived = 0L;
- _sent = 0L;
- }
- catch (InterruptedException e)
- {
- //
- }
-
- doBatch(_numBatches);
-
- }
-
- private void doBatch(int batchSize) // long[] timings,
- {
- TextMessage testMessage = null;
- try
- {
- testMessage = _client.session[0].createTextMessage("start");
-
- for (int batch = 0; batch <= batchSize; batch++)
- // while (_running)
- {
- long start = System.nanoTime();
-
- testMessage.setText("start");
- testMessage.setIntProperty("BATCH", batch);
-
- _client.producer.send(testMessage);
- _rateAdapter.sentMessage();
-
- testMessage.setText("test");
- // start at 2 so start and end count as part of batch
- for (int m = 2; m < _batchSize; m++)
- {
- _client.producer.send(testMessage);
- _rateAdapter.sentMessage();
- }
-
- testMessage.setText("end");
- _client.producer.send(testMessage);
- _rateAdapter.sentMessage();
-
- long end = System.nanoTime();
-
- long sendtime = end - start;
-
- if (log.isDebugEnabled())
- {
- log.info("Sent batch[" + batch + "](" + _batchSize + ") in " + sendtime); // timings[batch]);
- }
-
- if ((batch % LOG_UPATE_INTERVAL) == 0)
- {
- console.info("Sent Batch[" + batch + "](" + _batchSize + ")" + status());
- }
-
- _rateAdapter.sleepBatch();
-
- }
- }
- catch (JMSException e)
- {
- console.error("Runner ended");
- }
- }
-
- private String status()
- {
- return " TotalDuration: " + _totalDuration + " for " + delays.size() + " consumers" + " Delay is " + _delay
- + " resulting in "
- + ((_delay > (TEN_MILLI_SEC * _batchSize)) ? ((_delay / _batchSize) + "/msg") : (_delay + "/batch"));
- }
-
- private void sleepBatch()
- {
- if (checkForSlowClients())
- { // if there werwe slow clients we have already slept so don't sleep anymore again.
- return;
- }
-
- if (!SLEEP_PER_MESSAGE)
- {
- // per batch sleep.. if sleep is to small to spread over the batch.
- if (_delay <= (TEN_MILLI_SEC * _batchSize))
- {
- sleepLong(_delay);
- }
- else
- {
- log.info("Not sleeping _delay > ten*batch is:" + _delay);
- }
- }
- }
-
- public void stop()
- {
- _running = false;
- }
-
- Map<String, Long> delays = new HashMap<String, Long>();
- Long _totalReceived = 0L;
- Long _totalDuration = 0L;
- int _skipUpdate = 0;
-
- /**
- * Adjust the delay for sending messages based on this update from the client
- *
- * @param client The client that send this update
- * @param duration The time taken for the last batch of messagse
- * @param batchNumber The reported batchnumber from the client
- */
- private void adjustDelay(String client, int batchNumber, long duration)
- {
- // Retrieve the current total time taken for this client.
- Long currentTime = delays.get(client);
-
- // Add the new duration time to this client
- if (currentTime == null)
- {
- currentTime = duration;
- }
- else
- {
- currentTime += duration;
- }
-
- delays.put(client, currentTime);
-
- long batchesSent = _sent / _batchSize;
-
- // ensure we don't divide by zero
- if (batchesSent == 0)
- {
- batchesSent = 1L;
- }
-
- _totalReceived += _batchSize;
- _totalDuration += duration;
-
- // calculate average duration accross clients per batch
- long averageDuration = _totalDuration / delays.size() / batchesSent;
-
- // calculate the difference between current send delay and average report delay
- long diff = (duration) - averageDuration;
-
- if (log.isInfoEnabled() && ((batchNumber % DEBUG_LOG_UPATE_INTERVAL) == 0))
- {
- log.info("TotalDuration:" + _totalDuration + " for " + delays.size() + " consumers." + " on batch: "
- + batchesSent + " received batch: " + batchNumber + " Batch Duration: " + duration + " Average: "
- + averageDuration + " so diff: " + diff + " for : " + client + " Delay is " + _delay + " resulting in "
- + ((_delay > (TEN_MILLI_SEC * _batchSize)) ? ((_delay / _batchSize) + "/msg") : (_delay + "/batch")));
- }
-
- // if the averageDuration differs from the current by more than the specified variane then adjust delay.
- if (Math.abs(diff) > _timeVariance)
- {
-
- // if the the _delay is larger than the required duration to send report
- // speed up
- if (diff > TEN_MILLI_SEC)
- {
- _delay -= TEN_MILLI_SEC;
-
- if (_delay < 0)
- {
- _delay = 0;
- log.info("Reset _delay to 0");
- delayStable();
- }
- else
- {
- delayChanged();
- }
-
- }
- else if (diff < 0) // diff < 0 diff cannot be 0 as it is > _timeVariance
- {
- // the report took longer
- _delay += TEN_MILLI_SEC;
- delayChanged();
- }
- }
- else
- {
- delayStable();
- }
-
- // If we have a consumer that is behind with the batches.
- if ((batchesSent - batchNumber) > _batchVariance)
- {
- log.debug("Increasing _delay as sending more than receiving");
-
- _delay += 2 * TEN_MILLI_SEC;
- delayChanged();
- }
-
- }
-
- /** Reset the number of iterations before we say the delay has stabilised. */
- private void delayChanged()
- {
- _delayShifting = REPORTS_WITHOUT_CHANGE;
- }
-
- /**
- * Record the fact that delay has stabilised If delay has stablised for REPORTS_WITHOUT_CHANGE then it will
- * output Delay stabilised
- */
- private void delayStable()
- {
- _delayShifting--;
-
- if (_delayShifting < 0)
- {
- _delayShifting = 0;
- console.debug("Delay stabilised:" + _delay);
- }
- }
-
- /**
- * Checks that the client has received enough messages. If the client has fallen behind then they are put in the
- * _slowClients lists which will increase the delay.
- *
- * @param client The client identifier to check
- * @param received the number of messages received by that client
- * @param batchNumber
- */
- private void recordSlow(String client, long received, int batchNumber)
- {
- if (Math.abs(batchNumber - (_sent / _batchSize)) > _batchVariance)
- {
- _slowClients.put(client, received);
- }
- else
- {
- _slowClients.remove(client);
- }
- }
-
- /** Incrment the number of sent messages and then sleep, if required. */
- public void sentMessage()
- {
-
- _sent++;
-
- if (_delay > (TEN_MILLI_SEC * _batchSize))
- {
- long batchDelay = _delay / _batchSize;
- // less than 10ms sleep doesn't always work.
- // _delay is in nano seconds
- // if (batchDelay < (TEN_MILLI_SEC))
- // {
- // sleep(0, (int) batchDelay);
- // }
- // else
- {
- // if (batchDelay < 30000000000L)
- {
- sleepLong(batchDelay);
- }
- }
- }
- else
- {
- if (SLEEP_PER_MESSAGE && (_delay > 0))
- {
- sleepLong(_delay / _batchSize);
- }
- }
- }
-
- /**
- * Check at the end of each batch and pause sending messages to allow slow clients to catch up.
- *
- * @return true if there were slow clients that caught up.
- */
- private boolean checkForSlowClients()
- {
- // This will allways be true as we are running this at the end of each batchSize
- // if (_sent % _batchSize == 0)
- {
- // Cause test to pause when we have slow
- if (!_slowClients.isEmpty() || NO_CLIENTS)
- {
-
- while (!_slowClients.isEmpty())
- {
- if (log.isInfoEnabled() && ((_sent / _batchSize % DEBUG_LOG_UPATE_INTERVAL) == 0))
- {
- String clients = "";
- Iterator it = _slowClients.keySet().iterator();
- while (it.hasNext())
- {
- clients += it.next();
- if (it.hasNext())
- {
- clients += ", ";
- }
- }
-
- log.info("Pausing for slow clients:" + clients);
- }
-
- if (console.isDebugEnabled() && ((_sent / _batchSize % LOG_UPATE_INTERVAL) == 0))
- {
- console.debug(_slowClients.size() + " slow clients.");
- }
-
- sleep(PAUSE_SLEEP);
- }
-
- if (NO_CLIENTS)
- {
- sleep(NO_CLIENT_SLEEP);
- }
-
- log.debug("Continuing");
-
- return true;
- }
- else
- {
- if ((_sent / _batchSize % LOG_UPATE_INTERVAL) == 0)
- {
- console.info("Total Delay :" + _delay + " "
- + ((_delayShifting == 0) ? "Stablised" : ("Not Stablised(" + _delayShifting + ")")));
- }
- }
-
- }
-
- return false;
- }
-
- /**
- * Sleep normally takes micro-seconds this allows the use of a nano-second value.
- *
- * @param delay nanoseconds to sleep for.
- */
- private void sleepLong(long delay)
- {
- sleep(delay / 1000000, (int) (delay % 1000000));
- }
-
- /**
- * Sleep for the specified micro-seconds.
- * @param sleep microseconds to sleep for.
- */
- private void sleep(long sleep)
- {
- sleep(sleep, 0);
- }
-
- /**
- * Perform the sleep , swallowing any InteruptException.
- *
- * NOTE: If a sleep request is > 10s then reset only sleep for 5s
- *
- * @param milli to sleep for
- * @param nano sub miliseconds to sleep for
- */
- private void sleep(long milli, int nano)
- {
- try
- {
- log.debug("Sleep:" + milli + ":" + nano);
- if (milli > 10000)
- {
-
- if (_delay == milli)
- {
- _totalDuration = _totalReceived / _batchSize * EXPECTED_TIME_PER_BATCH;
- log.error("Sleeping for more than 10 seconds adjusted to 5s!:" + (milli / 1000)
- + "s. Reset _totalDuration:" + _totalDuration);
- }
- else
- {
- log.error("Sleeping for more than 10 seconds adjusted to 5s!:" + (milli / 1000) + "s");
- }
-
- milli = 5000;
- }
-
- Thread.sleep(milli, nano);
- }
- catch (InterruptedException e)
- {
- //
- }
- }
-
- public void setClient(SustainedClientTestCase client)
- {
- _client = client;
- }
- }
-
-}
diff --git a/java/integrationtests/src/main/java/org/apache/qpid/sustained/SustainedTestCase.java b/java/integrationtests/src/main/java/org/apache/qpid/sustained/SustainedTestCase.java
deleted file mode 100644
index 0077b4727a..0000000000
--- a/java/integrationtests/src/main/java/org/apache/qpid/sustained/SustainedTestCase.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.sustained;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.test.framework.DropInTest;
-import org.apache.qpid.test.framework.FrameworkBaseCase;
-
-import javax.jms.JMSException;
-import javax.jms.Message;
-
-import java.util.Properties;
-
-/**
- * SustainedTestCase is a {@link FrameworkBaseCase} that runs the "Perf_SustainedPubSub" test case. This consists of one
- * test client sending, and several receiving, and attempts to find the highest rate at which messages can be broadcast
- * to the receivers. It is also a {@link DropInTest} to which more test clients may be added during a test run.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td>
- * </table>
- */
-public class SustainedTestCase extends FrameworkBaseCase implements DropInTest
-{
- /** Used for debugging. */
- Logger log = Logger.getLogger(SustainedTestCase.class);
-
- /** Holds the root name of the topic on which to send the test messages. */
- private static final String SUSTAINED_KEY = "Perf_SustainedPubSub";
-
- /**
- * Creates a new coordinating test case with the specified name.
- *
- * @param name The test case name.
- */
- public SustainedTestCase(String name)
- {
- super(name);
- }
-
- /**
- * Performs a single test run of the sustained test.
- *
- * @throws Exception Any exceptions are allowed to fall through and fail the test.
- */
- public void testBasicPubSub() throws Exception
- {
- log.debug("public void testSinglePubSubCycle(): called");
-
- Properties testConfig = new Properties();
- testConfig.put("TEST_NAME", "Perf_SustainedPubSub");
- testConfig.put("SUSTAINED_KEY", SUSTAINED_KEY);
- testConfig.put("SUSTAINED_NUM_RECEIVERS", Integer.getInteger("numReceives", 2));
- testConfig.put("SUSTAINED_UPDATE_INTERVAL", Integer.getInteger("batchSize", 1000));
- testConfig.put("SUSTAINED_UPDATE_KEY", SUSTAINED_KEY + ".UPDATE");
- testConfig.put("ACKNOWLEDGE_MODE", Integer.getInteger("ackMode", AMQSession.AUTO_ACKNOWLEDGE));
-
- log.info("Created Config: " + testConfig.entrySet().toArray());
-
- getCircuitFactory().sequenceTest(null, null, testConfig);
- }
-
- /**
- * Accepts a late joining client into this test case. The client will be enlisted with a control message
- * with the 'CONTROL_TYPE' field set to the value 'LATEJOIN'. It should also provide values for the fields:
- *
- * <p/><table>
- * <tr><td> CLIENT_NAME <td> A unique name for the new client.
- * <tr><td> CLIENT_PRIVATE_CONTROL_KEY <td> The key for the route on which the client receives its control messages.
- * </table>
- *
- * @param message The late joiners join message.
- *
- * @throws JMSException Any JMS Exception are allowed to fall through, indicating that the join failed.
- */
- public void lateJoin(Message message) throws JMSException
- {
- throw new RuntimeException("Not implemented.");
- /*
- // Extract the joining clients details from its join request message.
- TestClientDetails clientDetails = new TestClientDetails();
- clientDetails.clientName = message.getStringProperty("CLIENT_NAME");
- clientDetails.privateControlKey = message.getStringProperty("CLIENT_PRIVATE_CONTROL_KEY");
-
- // Register the joining client, but do block for confirmation as cannot do a synchronous receivers during this
- // method call, as it may have been called from an 'onMessage' method.
- assignReceiverRole(clientDetails, new Properties(), false);
- */
- }
-
- /**
- * Should provide a translation from the junit method name of a test to its test case name as known to the test
- * clients that will run the test. The purpose of this is to convert the JUnit method name into the correct test
- * case name to place into the test invite. For example the method "testP2P" might map onto the interop test case
- * name "TC2_BasicP2P".
- *
- * @param methodName The name of the JUnit test method.
- *
- * @return The name of the corresponding interop test case.
- */
- public String getTestCaseNameForTestMethod(String methodName)
- {
- return "Perf_SustainedPubSub";
- }
-}
diff --git a/java/integrationtests/src/resources/sustained-log4j.xml b/java/integrationtests/src/resources/sustained-log4j.xml
deleted file mode 100644
index c5ab3137bf..0000000000
--- a/java/integrationtests/src/resources/sustained-log4j.xml
+++ /dev/null
@@ -1,69 +0,0 @@
-<?xml version="1.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.
- -
- -->
-<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
-<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
-
-
- <appender name="FileAppender" class="org.apache.log4j.FileAppender">
- <param name="File" value="${QPID_WORK}/log/${logprefix}qpid${logsuffix}.log"/>
- <param name="Append" value="false"/>
-
- <layout class="org.apache.log4j.PatternLayout">
- <param name="ConversionPattern" value="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/>
- </layout>
- </appender>
-
- <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
-
- <layout class="org.apache.log4j.PatternLayout">
- <param name="ConversionPattern" value="%d %-5p (%F:%L) - %m%n"/>
- <!--param name="ConversionPattern" value="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/-->
- </layout>
- </appender>
-
- <category name="SustainedTest">
- <priority value="${sustained.level}"/>
- </category>
-
- <category name="org.apache">
- <priority value="warn"/>
- </category>
-
- <category name="org.apache.qpid.interop">
- <priority value="${interop.logging.level}"/>
- </category>
-
-
- <category name="org.apache.qpid.sustained">
- <priority value="${amqj.logging.level}"/>
- </category>
-
- <!--category name="org.apache.qpid.server.txn">
- <priority value="debug"/>
- </category>-->
-
- <root>
- <priority value="all"/>
- <appender-ref ref="STDOUT"/>
- <!--appender-ref ref="ArchivingFileAppender"/-->
- </root>
-</log4j:configuration>
diff --git a/java/ivy.xml b/java/ivy.xml
deleted file mode 100644
index cdffcff458..0000000000
--- a/java/ivy.xml
+++ /dev/null
@@ -1,39 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-<ivy-module version="2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:noNamespaceSchemaLocation="http://ant.apache.org/ivy/schemas/ivy.xsd">
-
- <info organisation="org/apache" module="qpid" revision="0.10"/>
-
- <publications xmlns:e="urn:ant.apache.org:ivy-extras">
- <artifact name="qpid-client" type="pom" ext="pom"/>
- <artifact name="qpid-client" type="pom.asc" ext="pom.asc"/>
- <artifact name="qpid-client" type="jar" ext="jar"/>
- <artifact name="qpid-client" type="jar.asc" ext="jar.asc"/>
- <artifact name="qpid-client" type="source" ext="jar" e:classifier="sources"/>
- <artifact name="qpid-client" type="source.asc" ext="jar.asc" e:classifier="sources"/>
- <artifact name="qpid-common" type="pom" ext="pom"/>
- <artifact name="qpid-common" type="pom.asc" ext="pom.asc"/>
- <artifact name="qpid-common" type="jar" ext="jar"/>
- <artifact name="qpid-common" type="jar.asc" ext="jar.asc"/>
- <artifact name="qpid-common" type="source" ext="jar" e:classifier="sources"/>
- <artifact name="qpid-common" type="source.asc" ext="jar.asc" e:classifier="sources"/>
- </publications>
-
- <dependencies/>
-</ivy-module>
diff --git a/java/ivysettings-nexus.xml b/java/ivysettings-nexus.xml
deleted file mode 100644
index 1d9c393e23..0000000000
--- a/java/ivysettings-nexus.xml
+++ /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.
--->
-<ivysettings>
- <credentials host="${nexus.host}" realm="Sonatype Nexus Repository Manager" username="${nexus.user}" passwd="${nexus.password}"/>
- <caches defaultCacheDir="${user.home}/.ivy2/cache"/>
- <resolvers>
- <ibiblio name="public" m2compatible="true"/>
- <url name="nexus">
- <artifact pattern="${nexus.upload.url}/[organisation]/[module]/[artifact]/[revision]/[artifact]-[revision](-[classifier]).[ext]" />
- </url>
- </resolvers>
- <modules>
- <module organisation="${nexus.organisation}" name="qpid" resolver="nexus"/>
- </modules>
- <settings defaultResolver="public"/>
-</ivysettings>
diff --git a/java/junit-toolkit/build.xml b/java/junit-toolkit/build.xml
deleted file mode 100644
index a2f352c4b7..0000000000
--- a/java/junit-toolkit/build.xml
+++ /dev/null
@@ -1,26 +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.
- -
- -->
-<project name="Junit Toolkit" default="build">
- <property name="module.src" value="src/main"/>
-
- <import file="../module.xml"/>
-
-</project>
diff --git a/java/junit-toolkit/src/main/org/apache/qpid/junit/concurrency/DefaultThreadFactory.java b/java/junit-toolkit/src/main/org/apache/qpid/junit/concurrency/DefaultThreadFactory.java
deleted file mode 100644
index 8fb0a6a90e..0000000000
--- a/java/junit-toolkit/src/main/org/apache/qpid/junit/concurrency/DefaultThreadFactory.java
+++ /dev/null
@@ -1,48 +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.junit.concurrency;
-
-import java.util.concurrent.ThreadFactory;
-
-/**
- * Implements a default thread factory.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Create default threads with no specialization.
- * </table>
- *
- * @author Rupert Smith
- */
-public class DefaultThreadFactory implements ThreadFactory
-{
- /**
- * Constructs a new <tt>Thread</tt>.
- *
- * @param r A runnable to be executed by new thread instance.
- *
- * @return The constructed thread.
- */
- public Thread newThread(Runnable r)
- {
- return new Thread(r);
- }
-}
diff --git a/java/junit-toolkit/src/main/org/apache/qpid/junit/concurrency/PossibleDeadlockException.java b/java/junit-toolkit/src/main/org/apache/qpid/junit/concurrency/PossibleDeadlockException.java
deleted file mode 100644
index 3bbfc2d502..0000000000
--- a/java/junit-toolkit/src/main/org/apache/qpid/junit/concurrency/PossibleDeadlockException.java
+++ /dev/null
@@ -1,46 +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.junit.concurrency;
-
-/**
- * PossibleDeadlockException is used to signal that two test threads being executed by a {@link ThreadTestCoordinator}
- * may be in a state of deadlock because they are mutually blocking each other or one is waiting on the other and the
- * other has been blocked elsewhere for longer than a specified timeout.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Signal a possible state of deadlock between coordinated test threads.
- * </table>
- *
- * @author Rupert Smith
- */
-public class PossibleDeadlockException extends RuntimeException
-{
- /**
- * Create a new possible deadlock execption.
- *
- * @param message The exception message.
- */
- public PossibleDeadlockException(String message)
- {
- super(message);
- }
-}
diff --git a/java/junit-toolkit/src/main/org/apache/qpid/junit/concurrency/TestRunnable.java b/java/junit-toolkit/src/main/org/apache/qpid/junit/concurrency/TestRunnable.java
deleted file mode 100644
index 02e776a4ea..0000000000
--- a/java/junit-toolkit/src/main/org/apache/qpid/junit/concurrency/TestRunnable.java
+++ /dev/null
@@ -1,239 +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.junit.concurrency;
-
-/**
- * TestRunnable is an extension of java.util.Runnable that adds some features to make it easier to coordinate the
- * activities of threads in such a way as to expose bugs in multi threaded code.
- *
- * <p/>Sometimes several threads will run in a particular order so that a bug is not revealed. Other times the ordering
- * of the threads will expose a bug. Such bugs can be hard to replicate as the exact execution ordering of threads is not
- * usually controlled. This class adds some methods that allow threads to synchronize other threads, either allowing them
- * to run, or waiting for them to allow this thread to run. It also provides convenience methods to gather error messages
- * and exceptions from threads, which will often be reported in unit testing code.
- *
- * <p/>Coordination between threads is handled by the {@link ThreadTestCoordinator}. It is called through the convenience
- * methods {@link #allow} and {@link #waitFor}. Threads to be coordinated must be set up with the coordinator and assigned
- * integer ids. It is then possible to call the coordinator with an array of thread ids requesting that those threads
- * be allowed to continue, or to wait until one of them allows this thread to continue. The otherwise non-deterministic
- * execution order of threads can be controlled into a carefully determined sequence using these methods in order
- * to reproduce race conditions, dead locks, live locks, dirty reads, phantom reads, non repeatable reads and so on.
- *
- * <p/>When waiting for another thread to give a signal to continue it is sometimes the case that the other thread has
- * become blocked by the code under test. For example in testing for a dirty read (for example in database code),
- * thread 1 lets thread 2 perform a write but not commit it, then thread 2 lets thread 1 run and attempt to perform a
- * dirty read on its uncommitted write. Transaction synchronization code being tested against the possibility of a dirty
- * write may make use of snapshots in which case both threads should be able to read and write without blocking. It may
- * make use of explicit keys in which case thread 2 may become blocked on its write attempt because thread 1 holds a
- * read lock and it must wait until thread 1 completes its transaction before it can acquire this lock. The
- * {@link #waitFor} method accepts a boolean parameter to indicate that threads being blocked (other than on the
- * coordinator) can be interpreted the same as if the thread explicitly allows the thread calling waitFor to continue.
- * Using this technique a dirty read test could be written that works against either the snapshot or the locking
- * implementation, allowing both approaches to pass the test yet arranging for multiple threads to run against the
- * implementation in such a way that a potential dirty read bug is exposed.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Wait for another thread to allow this one to continue.
- * <tr><td> Allow another thread to continue.
- * <tr><td> Accumulate error messages.
- * <tr><td> Record exceptions from thread run.
- * <tr><td> Maintain link to thread coordinator.
- * <tr><td> Explicitly mark a thread with an integer id.
- * <tr><td> Maintian a flag to indicate whether or not this thread is waiting on the coordinator.
- * </table>
- *
- * @todo The allow then waitFor operations are very often used as a pair. So create a method allowAndWait that combines
- * them into a single method call.
- *
- * @author Rupert Smith
- */
-public abstract class TestRunnable implements Runnable
-{
- /** Holds a reference to the thread coordinator. */
- private ThreadTestCoordinator coordinator;
-
- /** Holds the explicit integer id of this thread. */
- private int id;
-
- /** Used to indicate that this thread is waiting on the coordinator and not elsewhere. */
- private boolean waitingOnCoordinator = false;
-
- /** Used to accumulate error messsages. */
- private String errorMessage = "";
-
- /** Holds the Java thread object that this is running under. */
- private Thread thisThread;
-
- /** Used to hold any exceptions resulting from the run method. */
- private Exception runException = null;
-
- /**
- * Implementations override this to perform coordinated thread sequencing.
- *
- * @throws Exception Any exception raised by the implementation will be caught by the default {@link #run()}
- * implementation for later querying by the {@link #getException()} method.
- */
- public abstract void runWithExceptions() throws Exception;
-
- /**
- * Provides a default implementation of the run method that allows exceptions to be thrown and keeps a record
- * of those exceptions. Defers to the {@link #runWithExceptions()} method to provide the thread body implementation
- * and catches any exceptions thrown by it.
- */
- public void run()
- {
- try
- {
- runWithExceptions();
- }
- catch (Exception e)
- {
- this.runException = e;
- }
- }
-
- /**
- * Attempt to consume an allow event from one of the specified threads and blocks until such an event occurrs.
- *
- * @param threads The set of threads that can allow this one to continue.
- * @param otherWaitIsAllow If set to <tt>true</tt> if the threads being waited on are blocked other than on
- * the coordinator itself then this is to be interpreted as allowing this thread to
- * continue.
- *
- * @return If the <tt>otherWaitIsAllow</tt> flag is set, then <tt>true</tt> is returned when the thread being waited on is found
- * to be blocked outside of the thread test coordinator. <tt>false</tt> under all other conditions.
- */
- protected boolean waitFor(int[] threads, boolean otherWaitIsAllow)
- {
- return coordinator.consumeAllowEvent(threads, otherWaitIsAllow, id, this);
- }
-
- /**
- * Produces allow events on each of the specified threads.
- *
- * @param threads The set of threads that are to be allowed to continue.
- */
- protected void allow(int[] threads)
- {
- coordinator.produceAllowEvents(threads, id, this);
- }
-
- /**
- * Keeps the error message for later reporting by the coordinator.
- *
- * @param message The error message to keep.
- */
- protected void addErrorMessage(String message)
- {
- errorMessage += message;
- }
-
- /**
- * Sets the coordinator for this thread.
- *
- * @param coordinator The coordinator for this thread.
- */
- void setCoordinator(ThreadTestCoordinator coordinator)
- {
- this.coordinator = coordinator;
- }
-
- /**
- * Reports whether or not this thread is waiting on the coordinator.
- *
- * @return <tt>If this thread is waiting on the coordinator.
- */
- boolean isWaitingOnCoordinator()
- {
- return waitingOnCoordinator;
- }
-
- /**
- * Sets the value of the waiting on coordinator flag.
- *
- * @param waiting The value of the waiting on coordinator flag.
- */
- void setWaitingOnCoordinator(boolean waiting)
- {
- waitingOnCoordinator = waiting;
- }
-
- /**
- * Sets up the explicit int id for this thread.
- *
- * @param id The integer id.
- */
- void setId(int id)
- {
- this.id = id;
- }
-
- /**
- * Reports any accumulated error messages.
- *
- * @return Any accumulated error messages.
- */
- String getErrorMessage()
- {
- return errorMessage;
- }
-
- /**
- * Reports any exception thrown by the {@link #runWithExceptions} method.
- *
- * @return Any exception thrown by the {@link #runWithExceptions} method.
- */
- Exception getException()
- {
- return runException;
- }
-
- /**
- * Sets the Java thread under which this runs.
- *
- * @param thread The Java thread under which this runs.
- */
- void setThread(Thread thread)
- {
- thisThread = thread;
- }
-
- /**
- * Gets the Java thread under which this runs.
- *
- * @return The Java thread under which this runs.
- */
- Thread getThread()
- {
- return thisThread;
- }
-
- /**
- * Provides a string summary of this test threads status.
- *
- * @return Summarizes this threads status.
- */
- public String toString()
- {
- return "id = " + id + ", waitingOnCoordinator = " + waitingOnCoordinator;
- }
-}
diff --git a/java/junit-toolkit/src/main/org/apache/qpid/junit/concurrency/ThreadTestCoordinator.java b/java/junit-toolkit/src/main/org/apache/qpid/junit/concurrency/ThreadTestCoordinator.java
deleted file mode 100644
index 3cf8543656..0000000000
--- a/java/junit-toolkit/src/main/org/apache/qpid/junit/concurrency/ThreadTestCoordinator.java
+++ /dev/null
@@ -1,486 +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.junit.concurrency;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.concurrent.ThreadFactory;
-
-/**
- * ThreadTestCoordinator provides an array of binary latches that allows threads to wait for other threads or to send
- * them a signal that allows them to continue running or to wait for another thread to signal them. The binary latch
- * array is always a square array, allowing one latch from and to every thread. Upon accepting an allow signal from one
- * sender the latches for all senders for a are cleared. This class is always used in conjunction with
- * {@link TestRunnable} for writing concurrent test code that coordinates multi-threaded activity in order to reproduce
- * concurrency bugs.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Accept test threads to coordinate.
- * <tr><td> Allow test threads to send 'allow to continue' signals.
- * <tr><td> Allow test threads to wait on this coordinator for 'allow to continue' signals.
- * <tr><td> Report error messages from test threads.
- * <tr><td> Report exceptions from test threads.
- * <tr><td> Provide method to wait until all test threads have completed.
- * </table>
- *
- * @todo This code was hacked together as a bit of an experiment, because I wasn't sure if this idea would work. It has
- * proved extremely usefull. Some documentation for this needs to be written to explain it better.
- *
- * @todo Consider how deadlock detection will be handled. If all threads are blocking on the coordinator, waiting for
- * each other, they are deadlocked and there is something wrong with the test code that put them in that
- * situation. If they are all blocked elsewhere, they may be deadlocked, or could just be waiting on some
- * external event. A timeout should be used. Timeout is already implemented, just need to sanity check how
- * this is working and document it.
- *
- * @todo Consider how livelock detection could be implemented? LockFree data structures might cause live locks. I
- * guess a longish timeout is the only thing that can be done for that.
- *
- * @todo Only course grained synchronous at the method class level can be obtained. This is because test code can
- * only insert synchronization points between method calls it makes. So this code will not be usefull for
- * checking sequences of events within methods, unless the code under test is explicitly instrumented for it.
- * It might be possible to instrument code by using labels, and then use the debugger/profiler interface to
- * put breakpoints on the labels and use them as synchronization points. Not perfect, but at the unused labels
- * can be left in the code, without altering its behaviour.
- *
- * @author Rupert Smith
- */
-public class ThreadTestCoordinator
-{
- /** Used for logging. */
- private static final Logger log = LoggerFactory.getLogger(ThreadTestCoordinator.class);
-
- /** Keeps track of the test threads by their ids. */
- private TestRunnable[] testThreads; // = new TestRunnable[2];
-
- /** An explicit thread monitor for the coordinator. Threads wait on the coordinator whilst waiting for events. */
- private final Object coordinatorLock = new Object();
-
- /** A set of monitors for each test thread. */
- private Object[] locks;
-
- /** The binary latch array, this is always a square array allowing one event from and to every thread. */
- private boolean[][] allowEvents;
-
- /** Keeps track of the number of threads being coordinated. */
- private int threadCount = 0;
-
- /** Accumulates any exceptions resulting from the threads run methods. */
- private Collection<Exception> exceptions = new ArrayList<Exception>();
-
- /**
- * Holds the deadlock timeout after which threads are given a runtime exception to signal that a potential
- * deadlock may be happening.
- */
- private long deadlockTimeout = 1000 * 1000000;
-
- /** Holds the factory to create test thread with. */
- private ThreadFactory threadFactory;
-
- /**
- * Creates a new test thread coordinator. The number of threads to run must be specified here.
- *
- * @param numThreads The number of threads to run.
- */
- public ThreadTestCoordinator(int numThreads)
- {
- this.threadCount = numThreads;
-
- // Create an array big enough to hold all the test threads.
- testThreads = new TestRunnable[threadCount];
-
- // Use the default thread factory, as none specified.
- threadFactory = new DefaultThreadFactory();
- }
-
- /**
- * Creates a new test thread coordinator with a specific thread factory. The number of threads to run must be
- * specified here.
- *
- * @param numThreads The number of threads to run.
- * @param threadFactory The factory to use to create the test threads.
- */
- public ThreadTestCoordinator(int numThreads, ThreadFactory threadFactory)
- {
- this.threadCount = numThreads;
-
- // Create an array big enough to hold all the test threads.
- testThreads = new TestRunnable[threadCount];
-
- // Use the specified thread factory.
- this.threadFactory = threadFactory;
- }
-
- /**
- * Adds a thread to this coordinator and assigns an id to it. The ids must be numbered sequentially from 0 and
- * it is up to the caller to do this.
- *
- * @param runnable The test thread.
- * @param id The explicit id to assign to the test thread.
- */
- public void addTestThread(TestRunnable runnable, int id)
- {
- testThreads[id] = runnable;
- runnable.setCoordinator(this);
- runnable.setId(id);
- }
-
- /**
- * Starts all the coordinated threads running.
- */
- public void run()
- {
- // Create the monitors for each thread.
- locks = new Object[threadCount];
-
- // Create an appropriately sized event queue to allow one event from and to each thread.
- allowEvents = new boolean[threadCount][threadCount];
-
- // Initialize the monitors and clear the event queues.
- for (int i = 0; i < locks.length; i++)
- {
- locks[i] = new Object();
-
- for (int j = 0; j < locks.length; j++)
- {
- allowEvents[i][j] = false;
- }
- }
-
- // Start all the threads running.
- for (TestRunnable nextRunnable : testThreads)
- {
- // Create a Java thread for the test thread.
- Thread newThread = threadFactory.newThread(nextRunnable);
- nextRunnable.setThread(newThread);
-
- // Start it running.
- newThread.start();
- }
- }
-
- /**
- * Waits until all the test threads have completed and returns any accumulated error messages from them. Any
- * exceptions thrown by their run methods are also kept at this point.
- *
- * @return The accumulated error messages from all the threads concatenated together.
- */
- public String joinAndRetrieveMessages()
- {
- // Create an empty error message.
- String errorMessage = "";
-
- // Join all the test threads.
- for (TestRunnable r : testThreads)
- {
- Thread t = r.getThread();
-
- try
- {
- t.join();
- }
- catch (InterruptedException e)
- { }
-
- // Add any accumulated error messages to the return value.
- errorMessage += r.getErrorMessage();
-
- // Keep any exceptions resulting from the threads run method.
- Exception e = r.getException();
-
- if (e != null)
- {
- exceptions.add(e);
- }
- }
-
- return errorMessage;
- }
-
- /**
- * Reports any accumulated exceptions from the test threads run methods. This method must be called after
- * {@link #joinAndRetrieveMessages}.
- *
- * @return Any accumulated exceptions from the test threads run methods. This method must be called after
- */
- public Collection<Exception> getExceptions()
- {
- return exceptions;
- }
-
- /**
- * Sets a timeout to break out of potential deadlocks. If all threads are waiting for other threads to send
- * them continue events for longer than this timeout then the threads are all terminated.
- *
- * @param millis The minimum time to allow to pass before breaking out of any potential deadlocks.
- *
- * @todo This has not been implemented yet. If a potential deadlock happens then the joinAndRetrieveMessages
- * method should throw a PotentialDeadlockException.
- */
- public void setDeadlockTimeout(long millis)
- {
- deadlockTimeout = millis * 1000000;
- }
-
- /**
- * Creates a set of 'allow to continue' events on the event queues of the specified threads.
- *
- * @param threads The set of threads to allow to continue.
- * @param callerId The explicit id of the calling test thread.
- * @param caller The calling test thread.
- */
- void produceAllowEvents(int[] threads, int callerId, TestRunnable caller)
- {
- // Generate some debugging messages. Very usefull to know how thread synchronization is progressing.
- String message = "Thread " + callerId + " is allowing threads [ ";
-
- for (int j = 0; j < threads.length; j++)
- {
- message += threads[j] + ((j < (threads.length - 1)) ? ", " : "");
- }
-
- message += " ] to continue.";
- log.debug(message);
-
- // For each allow event, synchronize on the threads lock then set the event flag to true.
- for (int id : threads)
- {
- // Set the waiting on coordinator flag to true in case the coordinator tries to test this thread for
- // being blocked at this time.
- caller.setWaitingOnCoordinator(true);
-
- synchronized (locks[id])
- {
- // Release the wating on coordinator flag now that this thread is running again.
- caller.setWaitingOnCoordinator(false);
-
- // Send the allow to continue event to the receiving thread.
- allowEvents[id][callerId] = true;
- }
- }
-
- // Wake up any threads waiting on the coordinator lock to recheck their event queues.
- // Set the waiting on coordinator flag to true in case the coordinator tries to test this thread for
- // being blocked at this time.
- caller.setWaitingOnCoordinator(true);
-
- synchronized (coordinatorLock)
- {
- // Release the wating on coordinator flag now that this thread is running again.
- caller.setWaitingOnCoordinator(false);
- coordinatorLock.notifyAll();
- }
- }
-
- /**
- * Consumes an 'allow to continue' from one of the specified threads or waits until one is available or in some
- * cases if one of the specified threads is blocked elsewhere to accept that as an 'allow to continue' event.
- *
- * @param threads The set of threads to accept an allow to continue event from.
- * @param otherWaitIsAllow Whether or not to accept threads being blocked elsewhere as permission to continue.
- * @param callerId The explicit id of the calling test thread.
- * @param caller The calling test thread.
- *
- * @return If the <tt>otherWaitIsAllow</tt> flag is set, then <tt>true</tt> is returned when the thread being waited on is found
- * to be blocked outside of the thread test coordinator. <tt>false</tt> under all other conditions.
- */
- boolean consumeAllowEvent(int[] threads, boolean otherWaitIsAllow, int callerId, TestRunnable caller)
- {
- // Generate some debugging messages. Very usefull to know how thread synchronization is progressing.
- String message = "Thread " + callerId + " is requesting threads [ ";
-
- // Record the time at which this method was called. Will be used for breaking out of potential deadlocks.
- long startTime = System.nanoTime();
-
- for (int j = 0; j < threads.length; j++)
- {
- message += threads[j] + ((j < (threads.length - 1)) ? ", " : "");
- }
-
- message += " ] to allow it to continue.";
- log.debug(message);
-
- // Loop until an allow to continue event is received.
- while (true)
- {
- // Look at all the allowing thread to see if one has created an event for consumption.
- for (int allowerId : threads)
- {
- // Get the threads lock for the event to consume.
- // Set the waiting on coordinator flag to true in case the coordinator tries to test this thread for
- // being blocked at this time.
- caller.setWaitingOnCoordinator(true);
-
- synchronized (locks[callerId])
- {
- // Release the wating on coordinator flag now that this thread is running again.
- caller.setWaitingOnCoordinator(false);
-
- // Check if there is an event on the queue from the allowing thread to this one.
- if (allowEvents[callerId][allowerId])
- {
- log.debug("Found an allow event, thread " + allowerId + ", is allowing thread " + callerId
- + ", to continue.");
-
- // Consume all the allow events for this thread.
- /*for (int i = 0; i < allowEvents[callerId].length; i++)
- {
- allowEvents[callerId][i] = false;
- }*/
-
- // Consume just the event from the allower to the consumer, leaving other pending allow events alone.
- allowEvents[callerId][allowerId] = false;
-
- return false;
- }
- }
- }
-
- // If waiting elsewhere is to be interpreted as an 'allow to continue' event, then look at the thread status
- // for the threads being waited on to see if any are blocked on other resources.
- if (otherWaitIsAllow)
- {
- log.debug("Other wait is to be interpreted as an allow event.");
-
- // Look at all the potential allower threads.
- for (int allowerId : threads)
- {
- // Get the Java thread state for the allowing thread.
- Thread threadToTest = testThreads[allowerId].getThread();
- Thread.State state = threadToTest.getState();
-
- // Check if the thread is blocked and so a potential candidate for releasing this one.
- if ((state == Thread.State.BLOCKED) || (state == Thread.State.WAITING)
- || (state == Thread.State.TIMED_WAITING))
- {
- log.debug("Found an allower thread, id = " + allowerId + ", that is blocked or wating.");
-
- // Check that the allower thread is not waiting on the coordinator lock or any of the
- // individual thread locks. It must be waiting or blocked on another monitor.
- TestRunnable allowingRunnable = testThreads[allowerId];
- boolean isWaitingOnCoordinator = allowingRunnable.isWaitingOnCoordinator();
-
- if (!isWaitingOnCoordinator)
- {
- log.debug("The allower thread, id = " + allowerId
- + ", is blocked or waiting other than on the coordinator.");
-
- // Get the threads lock for the event to consume.
- caller.setWaitingOnCoordinator(true);
-
- synchronized (locks[callerId])
- {
- caller.setWaitingOnCoordinator(false);
-
- // Consume all the allow events for this thread.
- for (int i = 0; i < allowEvents[callerId].length; i++)
- {
- allowEvents[callerId][i] = false;
- }
-
- return true;
- }
- }
- else
- {
- log.debug("The waiting allower thread, " + allowerId
- + ", is waiting on the coordinator so does not allow thread " + callerId + " to continue.");
- }
- }
- }
- }
-
- // Keep waiting until an 'allow to continue' event can be consumed.
- try
- {
- // Set the waiting on coordinator flag to true in case the coordinator tries to test this thread for
- // being blocked at this time.
- caller.setWaitingOnCoordinator(true);
-
- synchronized (coordinatorLock)
- {
- // Release the wating on coordinator flag now that this thread is running again.
- caller.setWaitingOnCoordinator(false);
-
- log.debug("Thread " + callerId + " is waiting on coordinator lock for more allow events.");
-
- // Set the waiting on coordinator flag to true in case the coordinator tries to test this thread for
- // being blocked at this time.
- caller.setWaitingOnCoordinator(true);
- coordinatorLock.wait(10);
- }
- }
- catch (InterruptedException e)
- { }
-
- // Release the waiting on coordinator flag now that this thread is running again.
- caller.setWaitingOnCoordinator(false);
-
- // Check if this thread has been waiting for longer than the deadlock timeout and raise a possible
- // deadlock exception if so.
- long waitTime = System.nanoTime() - startTime;
- log.debug("Thread " + callerId + " has been waiting for " + (waitTime / 1000000) + " milliseconds.");
-
- if (waitTime > deadlockTimeout)
- {
- // Throw a possible deadlock exception.
- throw new PossibleDeadlockException("Possible deadlock due to timeout with state:\n" + this);
- }
-
- log.debug("Thread " + callerId + " has woken up, was waiting for more allow events to become available.");
- }
- }
-
- /**
- * Pretty prints the state of the thread test coordinator, for debugging purposes.
- *
- * @return Pretty printed state of the thread test coordinator.
- */
- public String toString()
- {
- String result = "[";
-
- for (int i = 0; i < allowEvents.length; i++)
- {
- for (int j = 0; j < allowEvents[i].length; j++)
- {
- result += allowEvents[i][j];
-
- result += (j < (allowEvents[i].length - 1)) ? ", " : "";
- }
-
- result += (i < (allowEvents.length - 1)) ? ",\n " : "";
- }
-
- result += "]";
-
- for (int i = 0; i < testThreads.length; i++)
- {
- result += "thread[" + i + "] = " + testThreads[i].toString();
- }
-
- return result;
- }
-
-}
diff --git a/java/junit-toolkit/src/main/org/apache/qpid/junit/concurrency/ThreadTestExample.java b/java/junit-toolkit/src/main/org/apache/qpid/junit/concurrency/ThreadTestExample.java
deleted file mode 100644
index b9865f2e22..0000000000
--- a/java/junit-toolkit/src/main/org/apache/qpid/junit/concurrency/ThreadTestExample.java
+++ /dev/null
@@ -1,145 +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.junit.concurrency;
-
-import org.apache.log4j.Logger;
-
-/**
- * An example to illustrate the use of the {@link ThreadTestCoordinator} and {@link TestRunnable}s.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Demo multi-threaded testing.
- * </table>
- *
- * @author Rupert Smith
- */
-public class ThreadTestExample
-{
- /** Used for logging. */
- private static final Logger log = Logger.getLogger(ThreadTestExample.class);
-
- /** Test thread 1. */
- TestRunnable testThread1 =
- new TestRunnable()
- {
- public void runWithExceptions() throws Exception
- {
- log.debug("public void run(): called");
- log.info("in testThread0, block 1");
-
- // Wait for t2 to allow t1 to continue.
- allow(new int[] { 1 });
- waitFor(new int[] { 1 }, false);
-
- log.info("in testThread0, block 2");
-
- // Wait for t2 to allow t1 to continue. T2 is allowed to be blocked elsewhere than giving explicit
- // permission to allow t1 to continue.
- allow(new int[] { 1 });
- waitFor(new int[] { 1 }, true);
-
- log.info("in testThread0, block 3");
-
- // Release thread 2 from waiting on the shared lock.
- synchronized (sharedLock)
- {
- sharedLock.notifyAll();
- }
-
- allow(new int[] { 1 });
- }
- };
-
- /** A shared lock between the test threads. */
- final Object sharedLock = new Object();
-
- /** Test thread 2. */
- TestRunnable testThread2 =
- new TestRunnable()
- {
- public void runWithExceptions() throws Exception
- {
- log.debug("public void run(): called");
- log.info("in testThread1, block 1");
-
- // Wait for t1 to allow t2 to continue.
- allow(new int[] { 0 });
- waitFor(new int[] { 0 }, false);
-
- log.info("in testThread1, block 2");
-
- // Wait on another resource. T1 should accept this as permission to continue.
- try
- {
- synchronized (sharedLock)
- {
- log.debug("in testThread1, waiting on shared lock.");
- sharedLock.wait();
- }
- }
- catch (InterruptedException e)
- {
- // Bail-out with a runtime if this happens.
- throw new RuntimeException("Interrupted whilst waiting for shared lock.", e);
- }
-
- log.info("in testThread1, finished waiting on shared lock.");
-
- // allow(new int[] { 0 });
-
- // Wait for t1 to allow t2 to continue.
- waitFor(new int[] { 0 }, false);
-
- log.info("in testThread1, block 3");
-
- allow(new int[] { 0 });
- }
- };
-
- /**
- * Executes the test threads with coordination.
- *
- * @param args Ignored.
- */
- public void main(String[] args)
- {
- ThreadTestCoordinator tt = new ThreadTestCoordinator(2);
-
- tt.addTestThread(testThread1, 0);
- tt.addTestThread(testThread2, 1);
- tt.setDeadlockTimeout(500);
- tt.run();
-
- String errorMessage = tt.joinAndRetrieveMessages();
-
- // Print any error messages or exceptions.
- log.info(errorMessage);
-
- if (!tt.getExceptions().isEmpty())
- {
- for (Exception e : tt.getExceptions())
- {
- log.warn("Exception thrown during test thread: ", e);
- }
- }
- }
-}
diff --git a/java/junit-toolkit/src/main/org/apache/qpid/junit/concurrency/package.html b/java/junit-toolkit/src/main/org/apache/qpid/junit/concurrency/package.html
deleted file mode 100644
index 904fd0fd05..0000000000
--- a/java/junit-toolkit/src/main/org/apache/qpid/junit/concurrency/package.html
+++ /dev/null
@@ -1,28 +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.
-
--->
-
-<html>
-<body>
-Contains code to assist in testing concurrency issues using coordinated threads to present code under test with
-oportunities to expose concurrency bugs. Some example concurrency bugs that may be tested using these techniques are
-race conditions, dead locks, live locks, dirty reads, phantom reads, non repeatable reads and so on.
-</body>
-</html>
diff --git a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/AsymptoticTestCase.java b/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/AsymptoticTestCase.java
deleted file mode 100644
index 58a7f60f3c..0000000000
--- a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/AsymptoticTestCase.java
+++ /dev/null
@@ -1,303 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.junit.extensions;
-
-import junit.framework.TestCase;
-
-import org.apache.log4j.Logger;
-
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.lang.reflect.Modifier;
-
-/**
- * AsymptoticTestCase is an extension of TestCase for writing unit tests to analyze asymptotic time and space behaviour.
- *
- * <p>ParameterizedTestCases allow tests to be defined which have test methods that take a single int argument. Normal
- * JUnit test methods do not take any arguments. This int argument can be interpreted in any way by the test but it is
- * intended to denote the 'size' of the test to be run. For example, when testing the performance of a data structure
- * for different numbers of data elements held in the data structure the int parameter should be interpreted as the
- * number of elements. Test timings for different numbers of elements can then be captured and the asymptotic behaviour
- * of the data structure with respect to time analyzed. Any non-parameterized tests defined in extensions of this class
- * will also be run.
- *
- * <p>TestCases derived from this class may also define tear down methods to clean up their memory usage. This is
- * intended to be used in conjunction with memory listeners that report the amount of memory a test uses. The idea is
- * to write a test that allocates memory in the main test method in such a way that it leaves that memory still
- * allocated at the end of the test. The amount of memory used can then be measured before calling the tear down method
- * to clean it up. In the data structure example above, a test will allocate as many elements as are requested by the
- * int parameter and deallocate them in the tear down method. In this way memory readings for different numbers of
- * elements can be captured and the asymptotic behaviour of the data structure with respect to space analyzed.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Store the current int parameter value. <td> {@link TKTestResult} and see {@link AsymptoticTestDecorator} too.
- * <tr><td> Invoke parameterized test methods.
- * </table>
- *
- * @todo If possible try to move the code that invokes the test and setup/teardown methods into {@link TKTestResult} or
- * {@link AsymptoticTestDecorator} rather than this class. This would mean that tests don't have to extend this
- * class to do time and space performance analysis, these methods could be added to any JUnit TestCase class
- * instead. This would be an improvement because existing unit tests wouldn't have to extend a different class to
- * work with this extension, and also tests that extend other junit extension classes could have parameterized
- * and tear down methods too.
- *
- * @author Rupert Smith
- */
-public class AsymptoticTestCase extends TestCase implements InstrumentedTest
-{
- /** Used for logging. */
- private static final Logger log = Logger.getLogger(AsymptoticTestCase.class);
-
- /** The name of the test case. */
- private String testCaseName;
-
- /** Thread local for holding measurements on a per thread basis. */
- ThreadLocal<TestMeasurements> threadLocalMeasurement =
- new ThreadLocal<TestMeasurements>()
- {
- /**
- * Sets up a default set test measurements (zeroed, apart from the size param which defaults to 1).
- *
- * @return A set of default test measurements.
- */
- protected synchronized TestMeasurements initialValue()
- {
- return new TestMeasurements();
- }
- };
-
- /**
- * Constructs a test case with the given name.
- *
- * @param name The name of the test.
- */
- public AsymptoticTestCase(String name)
- {
- super(name);
-
- log.debug("public AsymptoticTestCase(String " + name + "): called");
- testCaseName = name;
- }
-
- /**
- * Gets the current value of the integer parameter to be passed to the parameterized test.
- *
- * @return The current value of the integer parameter.
- */
- public int getN()
- {
- log.debug("public int getN(): called");
- int n = threadLocalMeasurement.get().n;
-
- log.debug("return: " + n);
-
- return n;
- }
-
- /**
- * Sets the current value of the integer parameter to be passed to the parameterized test.
- *
- * @param n The new current value of the integer parameter.
- */
- public void setN(int n)
- {
- log.debug("public void setN(int " + n + "): called");
- threadLocalMeasurement.get().n = n;
- }
-
- /**
- * Reports how long the test took to run.
- *
- * @return The time in milliseconds that the test took to run.
- */
- public long getTestTime()
- {
- log.debug("public long getTestTime(): called");
- long startTime = threadLocalMeasurement.get().startTime;
- long endTime = threadLocalMeasurement.get().endTime;
- long testTime = endTime - startTime;
-
- log.debug("return: " + testTime);
-
- return testTime;
- }
-
- /**
- * Reports the memory usage at the start of the test.
- *
- * @return The memory usage at the start of the test.
- */
- public long getTestStartMemory()
- {
- // log.debug("public long getTestStartMemory(): called");
- long startMem = threadLocalMeasurement.get().startMem;
-
- // log.debug("return: " + startMem);
-
- return startMem;
- }
-
- /**
- * Reports the memory usage at the end of the test.
- *
- * @return The memory usage at the end of the test.
- */
- public long getTestEndMemory()
- {
- // log.debug("public long getTestEndMemory(): called");
- long endMem = threadLocalMeasurement.get().endMem;
-
- // log.debug("return: " + endMem);
- return endMem;
- }
-
- /**
- * Resets the instrumentation values to zero, and nulls any references to held measurements so that the memory
- * can be reclaimed.
- */
- public void reset()
- {
- log.debug("public void reset(): called");
- threadLocalMeasurement.remove();
- }
-
- /**
- * Runs the test method for this test case.
- *
- * @throws Throwable Any Throwables from the test methods invoked are allowed to fall through.
- */
- protected void runTest() throws Throwable
- {
- log.debug("protected void runTest(): called");
-
- // Check that a test name has been set. This is used to define which method to run.
- assertNotNull(testCaseName);
- log.debug("testCaseName = " + testCaseName);
-
- // Try to get the method with matching name.
- Method runMethod = null;
- boolean isParameterized = false;
-
- // Check if a parameterized test method is available.
- try
- {
- // Use getMethod to get all public inherited methods. getDeclaredMethods returns all
- // methods of this class but excludes the inherited ones.
- runMethod = getClass().getMethod(testCaseName, int.class);
- isParameterized = true;
- }
- catch (NoSuchMethodException e)
- {
- // log.debug("Parameterized method \"" + testCaseName + "\" not found.");
- // Set run method to null (it already will be but...) to indicate that no parameterized method
- // version could be found.
- runMethod = null;
- }
-
- // If no parameterized method is available, try and get the unparameterized method.
- if (runMethod == null)
- {
- try
- {
- runMethod = getClass().getMethod(testCaseName);
- isParameterized = false;
-
- }
- catch (NoSuchMethodException e)
- {
- fail("Method \"" + testCaseName + "\" not found.");
- }
- }
-
- // Check that the method is publicly accessable.
- if (!Modifier.isPublic(runMethod.getModifiers()))
- {
- fail("Method \"" + testCaseName + "\" should be public.");
- }
-
- // Try to execute the method, passing it the current int parameter value. Allow any invocation exceptions or
- // resulting exceptions from the method to fall through.
- try
- {
- Integer paramN = getN();
- log.debug("paramN = " + paramN);
-
- // Calculate parameters for parameterized tests so new does not get called during memory measurement.
- Object[] params = new Object[] { paramN };
-
- // Take the test start memory and start time.
- threadLocalMeasurement.get().startMem = 0; // SizeOf.getUsedMemory();
-
- threadLocalMeasurement.get().startTime = System.nanoTime();
-
- if (isParameterized)
- {
- runMethod.invoke(this, params);
- }
- else
- {
- runMethod.invoke(this);
- }
- }
- catch (InvocationTargetException e)
- {
- e.fillInStackTrace();
- throw e.getTargetException();
- }
- catch (IllegalAccessException e)
- {
- e.fillInStackTrace();
- throw e;
- }
- finally
- {
- // Take the test end memory and end time and calculate how long it took to run.
- long endTime = System.nanoTime();
- threadLocalMeasurement.get().endTime = endTime;
- log.debug("startTime = " + threadLocalMeasurement.get().startTime + ", endTime = " + endTime + ", testTime = "
- + getTestTime());
-
- threadLocalMeasurement.get().endMem = 0; // SizeOf.getUsedMemory();
- }
- }
-
- /**
- * The test parameters, encapsulated as a unit for attaching on a per thread basis.
- */
- private static class TestMeasurements
- {
- /** Holds the current value of the integer parameter to run tests on. */
- public int n = 1;
-
- /** Holds the test start memory. */
- public long startTime = 0;
-
- /** Holds the test end memory. */
- public long endTime = 0;
-
- /** Holds the test start memory. */
- public long startMem = 0;
-
- /** Holds the test end memory. */
- public long endMem = 0;
- }
-}
diff --git a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/AsymptoticTestDecorator.java b/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/AsymptoticTestDecorator.java
deleted file mode 100644
index 8869d25be3..0000000000
--- a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/AsymptoticTestDecorator.java
+++ /dev/null
@@ -1,173 +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.junit.extensions;
-
-import junit.framework.TestResult;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.junit.extensions.util.MathUtils;
-
-/**
- * A Decorator that runs a test repeatedly on an increasing int parameter, or for a fixed number of repeats. If both
- * a set of integer parameters and a repeat count are specified, then each test is run for the repeat count at each
- * integer parameter.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Repeat a test for each of a set of integer parameters. <td> {@link TKTestResult}
- * <tr><td> Repeat a test multiple times.
- * <tr><td>
- * </table>
- *
- * @author Rupert Smith
- */
-public class AsymptoticTestDecorator extends WrappedSuiteTestDecorator
-{
- /** Used for logging. */
- private static final Logger log = Logger.getLogger(AsymptoticTestDecorator.class);
-
- /** The int size parameters to run the test with. */
- private int[] params;
-
- /** The number of times the whole test should be repeated. */
- private int repeat;
-
- /**
- * Creates an asymptotic test decorator that wraps a test with repeats and a set of integer 'size' paramters
- * to call the test with.
- *
- * @param test The test to wrap.
- * @param params The integer 'size' parameters.
- * @param repeat The number of times to repeat the test.
- */
- public AsymptoticTestDecorator(WrappedSuiteTestDecorator test, int[] params, int repeat)
- {
- super(test);
-
- log.debug("public AsymptoticTestDecorator(Test \"" + test + "\", int[] "
- + ((params == null) ? null : MathUtils.printArray(params)) + ", int " + repeat + "): called");
-
- this.params = params;
- this.repeat = repeat;
- }
-
- /**
- * Creates a new AsymptoticTestDecorator object.
- *
- * @param test The test to decorate.
- * @param start The starting asymptotic integer parameter value.
- * @param end The ending asymptotic integer parameter value.
- * @param step The increment size to move from the start to end values by.
- * @param repeat The number of times to repeat the test at each step of the cycle.
- */
- public AsymptoticTestDecorator(WrappedSuiteTestDecorator test, int start, int end, int step, int repeat)
- {
- super(test);
-
- if (start < 0)
- {
- throw new IllegalArgumentException("Start must be >= 0");
- }
-
- if (end < start)
- {
- throw new IllegalArgumentException("End must be >= start");
- }
-
- if (step < 1)
- {
- throw new IllegalArgumentException("Step must be >= 1");
- }
-
- if (repeat < 1)
- {
- throw new IllegalArgumentException("Repeat must be >= 1");
- }
-
- // Generate the sequence.
- params = new int[((end - start) / step) + 1];
- int i = 0;
- for (int n = start; n <= end; n += step)
- {
- params[i++] = n;
- }
-
- this.repeat = repeat;
- }
-
- /**
- * Runs the test repeatedly for each value of the int parameter specified and for the correct number of test
- * repeats.
- *
- * @param result The test result object that the tests will indicate their results to. This is also used
- * to pass the int parameter from this class to the decorated test class.
- */
- public void run(TestResult result)
- {
- log.debug("public void run(TestResult result): called");
-
- if (!(result instanceof TKTestResult))
- {
- throw new IllegalArgumentException("AsymptoticTestDecorator only works with TKTestResult");
- }
-
- // Cast the test result into a TKTestResult to place the current parameter into.
- TKTestResult tkResult = (TKTestResult) result;
-
- log.debug("params = " + ((params == null) ? null : MathUtils.printArray(params)));
- log.debug("repeat = " + repeat);
-
- if(params != null)
- {
- for (int n : params)
- {
- for (int j = 0; j < repeat; j++)
- {
- log.debug("n = " + n);
-
- // Set the integer parameter in the TKTestResult to be passed to the tests.
- tkResult.setN(n);
-
- if (tkResult.shouldStop())
- {
- log.debug("tkResult.shouldStop = " + true);
-
- break;
- }
-
- log.debug("Calling super#run");
- super.run(tkResult);
- }
- }
- }
- }
-
- /**
- * Prints out the name of this test with the string "(parameterized)" appended onto it for debugging purposes.
- *
- * @return The name of this test with the string "(parameterized)" appended onto it.
- */
- public String toString()
- {
- return super.toString() + "(parameterized)";
- }
-}
diff --git a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/BaseThrottle.java b/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/BaseThrottle.java
deleted file mode 100644
index 61d5746421..0000000000
--- a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/BaseThrottle.java
+++ /dev/null
@@ -1,98 +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.junit.extensions;
-
-/**
- * Provides a base implementation of the non-waiting throttle checking method, using the system nano timer.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Check against a throttle speed without waiting.
- * </table>
- *
- * @author Rupert Smith
- */
-public abstract class BaseThrottle implements Throttle
-{
- /** Holds the length of a single cycle in nano seconds. */
- protected long cycleTimeNanos;
-
- /** Holds the time of the last succesfull call to the check method. */
- private long lastCheckTimeNanos;
-
- /** Flag used to detect the first call to the {@link #checkThrottle()} method. */
- boolean firstCheckCall = true;
-
- /**
- * Flag used to detect the first call to the {@link #throttle()} method. Zero or negative start time cannot be
- * relied on to detect this as System.nanoTime can return zero or negative values.
- */
- boolean firstCall = true;
-
- /**
- * Specifies the throttling rate in operations per second. This must be called with with a value, the inverse
- * of which is a measurement in nano seconds, such that the number of nano seconds do not overflow a long integer.
- * The value must also be larger than zero.
- *
- * @param hertz The throttling rate in cycles per second.
- */
- public void setRate(float hertz)
- {
- // Check that the argument is above zero.
- if (hertz <= 0.0f)
- {
- throw new IllegalArgumentException("The throttle rate must be above zero.");
- }
-
- // Calculate the cycle time.
- cycleTimeNanos = (long) (1000000000f / hertz);
-
- // Reset the first pass flag.
- firstCall = false;
- firstCheckCall = false;
- }
-
- /**
- * Checks but does not enforce the throttle rate. When this method is called, it checks if a length of time greater
- * than that equal to the inverse of the throttling rate has passed since it was last called and returned <tt>true</tt>
- *
- * @return <tt>true</tt> if a length of time greater than that equal to the inverse of the throttling rate has
- * passed since this method was last called and returned <tt>true</tt>, <tt>false</tt> otherwise. The very
- * first time this method is called on a throttle, it returns <tt>true</tt> as the base case to the above
- * self-referential definition.
- */
- public boolean checkThrottle()
- {
- long now = System.nanoTime();
-
- if ((now > (cycleTimeNanos + lastCheckTimeNanos)) || firstCheckCall)
- {
- firstCheckCall = false;
- lastCheckTimeNanos = now;
-
- return true;
- }
- else
- {
- return false;
- }
- }
-}
diff --git a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/BatchedThrottle.java b/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/BatchedThrottle.java
deleted file mode 100644
index 241e7aa2b7..0000000000
--- a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/BatchedThrottle.java
+++ /dev/null
@@ -1,94 +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.junit.extensions;
-
-/**
- * BatchedThrottle is a {@link SleepThrottle} that uses batching to achieve much higher throttling rates than a sleep
- * throttle can. Sleep throttle has difficulties once the rate gets above a few hundred hertz, because the JVM cannot
- * generate timed pauses that are that short. BatchedThrottle gets around this by only inserting pauses once every so
- * many calls to the {@link #throttle()} method, and using a sleep throttle run at a lower rate. The rate for the sleep
- * throttle is chosen so that it remains under 100hz. The final throttling rate of this throttle is equal to the batch
- * size times the rate of the underlying sleep throttle.
- *
- * <p/>The batching calculation involves taking the log to the base 100 of the desired rate and rounding this to
- * an integer. The batch size is always an exact power of 100 because of the rounding. The rate for an underlying
- * sleep throttle is then chosen appropriately.
- *
- * <p/>In practice, the accuracy of a BacthedThrottle skews off but can sometimes even be reasonable up to ten thousand
- * hertz compared with 100 Hz for a {@link SleepThrottle}.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Accept throttling rate in operations per second.
- * <tr><td> Inject short pauses, occasionaly, to fill out processing cycles to a specified rate.
- * <tr><td> Check against a throttle speed without waiting.
- * </table>
- *
- * @todo Should always round the log base 100 down to the nearest integer?
- *
- * @author Rupert Smith
- */
-public class BatchedThrottle extends BaseThrottle
-{
- /** Holds the batch size. */
- int batchSize;
-
- /** The call count within the current batch. */
- long callCount;
-
- /** Holds a sleep throttle configured to run at the batched rate. */
- private Throttle batchRateThrottle = new SleepThrottle();
-
- /**
- * Specifies the throttling rate in operations per second.
- *
- * @param hertz The throttling rate in cycles per second.
- */
- public void setRate(float hertz)
- {
- // Pass the rate unaltered down to the base implementation, for the check method.
- super.setRate(hertz);
-
- // Log base 10 over 2 is used here to get a feel for what power of 100 the total rate is.
- // As the total rate goes up the powers of 100 the batch size goes up by powers of 100 to keep the
- // throttle rate in the range 1 to 100.
- int x = (int) (Math.log10(hertz) / 2);
- batchSize = (int) Math.pow(100, x);
- float throttleRate = hertz / batchSize;
-
- // Reset the call count.
- callCount = 0;
-
- // Set the sleep throttle wrapped implementation at a rate within its abilities.
- batchRateThrottle.setRate(throttleRate);
- }
-
- /**
- * Throttle calls to this method to the rate specified by the {@link #setRate(float)} method.
- */
- public void throttle()
- {
- if ((callCount++ % batchSize) == 0)
- {
- batchRateThrottle.throttle();
- }
- }
-}
diff --git a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/DurationTestDecorator.java b/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/DurationTestDecorator.java
deleted file mode 100644
index e99fcce752..0000000000
--- a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/DurationTestDecorator.java
+++ /dev/null
@@ -1,205 +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.junit.extensions;
-
-import junit.framework.Test;
-import junit.framework.TestResult;
-
-import org.apache.log4j.Logger;
-
-import java.util.Timer;
-import java.util.TimerTask;
-
-/**
- * A test decorator that runs a test repeatedly until a specified length of time has passed.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Repeatedly run a test for a fixed length of time.
- * </table>
- *
- * @todo The count of the number of tests run is an important number to keep. Also num passed/error/failed is also
- * important to record. What to do with these numbers? They are already logged to the test listeners.
- *
- * @todo The duration test runner wraps on top of size, repeat or thread wrappers, need a way for it to tell
- * TKTestResult when the duration is up, so that it can terminate any repeats in progress. It should end
- * as soon as possible once the test method exits.
- *
- * @author Rupert Smith
- */
-public class DurationTestDecorator extends WrappedSuiteTestDecorator implements ShutdownHookable
-{
- /** Used for logging. */
- private static final Logger log = Logger.getLogger(DurationTestDecorator.class);
-
- /** The test to run. */
- private Test test;
-
- /** The length of time to run the test for. */
- private long duration;
-
- /** Flag set by the shutdown hook. This decorator will not start any new tests when this is set. */
- private boolean shutdown = false;
-
- /**
- * Creates an active test with default multiplier (1).
- *
- * @param test The target test.
- */
- public DurationTestDecorator(WrappedSuiteTestDecorator test)
- {
- super(test);
- this.test = test;
- }
-
- /**
- * Creates active test with default multiplier (1).
- *
- * @param test The target test.
- * @param duration The duration in milliseconds.
- */
- public DurationTestDecorator(WrappedSuiteTestDecorator test, long duration)
- {
- super(test);
-
- // log.debug("public DurationTestDecorator(Test \"" + test + "\", long " + duration + "): called");
-
- this.test = test;
- this.duration = duration;
- }
-
- /**
- * Runs the test repeatedly for the fixed duration.
- *
- * @param testResult The the results object to monitor the test results with.
- */
- public void run(TestResult testResult)
- {
- log.debug("public void run(TestResult testResult): called");
-
-// Removing the durationTimer as this addition prevents this TestDecorator being wrapped with a Scaled Test Decorator.
- // This change will cause the tests to run for at least the specified duration
- // If we need the test to stop much closer to the specified duration then we need to
- // ensure that the solution doesn't prevent this Decorator being wrapped with other Decorators.
-
-// // Cast the test result to expose it as a TKTestResult if the test is running under the TKTestRunner.
-// TKTestResult tkTestResult = null;
-//
-// if (testResult instanceof TKTestResult)
-// {
-// tkTestResult = (TKTestResult) testResult;
-// }
-//
-// // If running under the TKTestRunner, set up a timer to notify the test framework when the test reaches its
-// // completion time.
-// Timer durationTimer = null;
-//
-// if (tkTestResult != null)
-// {
-// log.debug("Creating duration timer.");
-//
-// durationTimer = new Timer();
-// durationTimer.schedule(new DurationTimerTask((TKTestResult) testResult), duration);
-// }
-
-
- // Work out when the test should end.
- long now = System.nanoTime();
- long end = (duration * 1000000) + now;
-
- // Run the test until the duration times out or the shutdown flag is set. The test method may not exit until
- // interrupted in some cases, in which case the timer will do the interrupting.
- while ((now < end) && !shutdown)
- {
- test.run(testResult);
-
- now = System.nanoTime();
- }
-
-// // Clean up any timer that was used.
-// if (durationTimer != null)
-// {
-// log.debug("Cancelling duration timer.");
-//
-// durationTimer.cancel();
-// }
- }
-
- /**
- * Supplies the shutdown hook. This shutdown hook does not call {@link TKTestResult#shutdownNow()} because the
- * {@link ScaledTestDecorator} already takes care of that.
- *
- * @return The shut down hook.
- */
- public Thread getShutdownHook()
- {
- return new Thread(new Runnable()
- {
- public void run()
- {
- // log.debug("DurationTestDecorator::ShutdownHook: called");
-
- // Set the shutdown flag so that no new tests are started.
- shutdown = true;
- }
- });
- }
-
-// /**
-// * DurationTimerTask is a timer task that is configured, upon expiry of its timer, to invoke
-// * {@link TKTestResult#shutdownNow()}, for the test result object on which it is set. It also sets
-// * the {@link DurationTestDecorator#shutdown} flag to indicate that no new tests should be run.
-// *
-// * <p/>The test loop implemented by DurationTestDecorator checks that the duration has not expired, on each
-// * test case that it runs. However, it is possible to write test cases that never return until explicitly
-// * interrupted by the test framework. This timer task exists to notify the test framework
-// */
-// private class DurationTimerTask extends TimerTask
-// {
-// /** Used for debugging purposes. */
-// private final Logger log = Logger.getLogger(DurationTimerTask.class);
-//
-// /** Holds the test result for the test to which a duration limit is being applied. */
-// TKTestResult testResult;
-//
-// /**
-// * Creates a duration limit timer which will notify the specified test result when the duration has
-// * expired.
-// *
-// * @param testResult The test result to notify upon expiry of the test duration.
-// */
-// public DurationTimerTask(TKTestResult testResult)
-// {
-// this.testResult = testResult;
-// }
-//
-// /**
-// * The action to be performed by this timer task.
-// */
-// public void run()
-// {
-// log.debug("public void run(): called");
-//
-// shutdown = true;
-// testResult.shutdownNow();
-// }
-// }
-}
diff --git a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/InstrumentedTest.java b/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/InstrumentedTest.java
deleted file mode 100644
index 0804757dce..0000000000
--- a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/InstrumentedTest.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.
- *
- */
-package org.apache.qpid.junit.extensions;
-
-import junit.framework.Test;
-
-/**
- * An InstrumentedTest is one which can supply some additional instrumentation on top of the pass/fail/error behaviour
- * of normal junit tests. Tests implementing this interface must additionally supply information about how long they
- * took to run and how much memory they used.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities
- * <tr><td> Report test run time.
- * <tr><td> Report test memory usage.
- * </table>
- *
- * @author Rupert Smith
- */
-public interface InstrumentedTest extends Test
-{
- /**
- * Reports how long the test took to run.
- *
- * @return The time in milliseconds that the test took to run.
- */
- public long getTestTime();
-
- /**
- * Reports the memory usage at the start of the test.
- *
- * @return The memory usage at the start of the test.
- */
- public long getTestStartMemory();
-
- /**
- * Reports the memory usage at the end of the test.
- *
- * @return The memory usage at the end of the test.
- */
- public long getTestEndMemory();
-
- /**
- * Resets the instrumentation values to zero, and nulls any references to held measurements so that the memory
- * can be reclaimed.
- */
- public void reset();
-}
diff --git a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/NullResultPrinter.java b/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/NullResultPrinter.java
deleted file mode 100644
index 6727f6f152..0000000000
--- a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/NullResultPrinter.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.junit.extensions;
-
-import junit.framework.AssertionFailedError;
-import junit.framework.Test;
-
-import junit.textui.ResultPrinter;
-
-import java.io.PrintStream;
-
-/**
- * A ResultPrinter that prints nothing. This exists, in order to provide a replacement to JUnit's ResultPrinter, which
- * is refered to directly by JUnit code, rather that as an abstracted TestListener. JUnit's text ui TestRunner must
- * have a ResultPrinter. This provides an implementation of it that prints nothing, so that a better mechanism can
- * be used for providing feedback to the console instead.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td>
- * </table>
- *
- * @todo See todo in TKTestRunner about completely replacing the test ui runner. Doing things like this in order to
- * extend JUnit is not nice, and there needs to be a better way to do it. Delete this class and use a listener
- * instead.
- *
- * @author Rupert Smith
- */
-public class NullResultPrinter extends ResultPrinter
-{
- /**
- * Builds a fake ResultPrinter that prints nothing.
- *
- * @param writer The writer to send output to.
- */
- public NullResultPrinter(PrintStream writer)
- {
- super(writer);
- }
-
- /**
- * Does nothing.
- *
- * @param test Ignored.
- * @param t Ignored.
- */
- public void addError(Test test, Throwable t)
- { }
-
- /**
- * Does nothing.
- *
- * @param test Ignored.
- * @param t Ignored.
- */
- public void addFailure(Test test, AssertionFailedError t)
- { }
-
- /**
- * Does nothing.
- *
- * @param test Ignored.
- */
- public void endTest(Test test)
- { }
-
- /**
- * Does nothing.
- *
- * @param test Ignored.
- */
- public void startTest(Test test)
- { }
-}
diff --git a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/ParameterVariationTestDecorator.java b/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/ParameterVariationTestDecorator.java
deleted file mode 100644
index 7da4667928..0000000000
--- a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/ParameterVariationTestDecorator.java
+++ /dev/null
@@ -1,175 +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.junit.extensions;
-
-import junit.framework.TestResult;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.junit.extensions.util.MathUtils;
-
-/**
- * ParameterVariationTestDecorator is a test decorator that runs a test repeatedly under all permutations of its
- * test parameters.
- *
- * a set of integer parameters and a repeat count are specified, then each test is run for the repeat count at each
- * integer parameter.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Repeat a test for each of a set of integer parameters. <td> {@link org.apache.qpid.junit.extensions.TKTestResult}
- * <tr><td> Repeat a test multiple times.
- * <tr><td>
- * </table>
- *
- * @author Rupert Smith
- */
-public class ParameterVariationTestDecorator extends WrappedSuiteTestDecorator
-{
- /** Used for logging. */
- private static final Logger log = Logger.getLogger(ParameterVariationTestDecorator.class);
-
- /** The int size parameters to run the test with. */
- private int[] params;
-
- /** The number of times the whole test should be repeated. */
- private int repeat;
-
- /**
- * Creates an asymptotic test decorator that wraps a test with repeats and a set of integer 'size' paramters
- * to call the test with.
- *
- * @param test The test to wrap.
- * @param params The integer 'size' parameters.
- * @param repeat The number of times to repeat the test.
- */
- public ParameterVariationTestDecorator(WrappedSuiteTestDecorator test, int[] params, int repeat)
- {
- super(test);
-
- log.debug("public AsymptoticTestDecorator(Test \"" + test + "\", int[] "
- + ((params == null) ? null : MathUtils.printArray(params)) + ", int " + repeat + "): called");
-
- this.params = params;
- this.repeat = repeat;
- }
-
- /**
- * Creates a new AsymptoticTestDecorator object.
- *
- * @param test The test to decorate.
- * @param start The starting asymptotic integer parameter value.
- * @param end The ending asymptotic integer parameter value.
- * @param step The increment size to move from the start to end values by.
- * @param repeat The number of times to repeat the test at each step of the cycle.
- */
- public ParameterVariationTestDecorator(WrappedSuiteTestDecorator test, int start, int end, int step, int repeat)
- {
- super(test);
-
- if (start < 0)
- {
- throw new IllegalArgumentException("Start must be >= 0");
- }
-
- if (end < start)
- {
- throw new IllegalArgumentException("End must be >= start");
- }
-
- if (step < 1)
- {
- throw new IllegalArgumentException("Step must be >= 1");
- }
-
- if (repeat < 1)
- {
- throw new IllegalArgumentException("Repeat must be >= 1");
- }
-
- // Generate the sequence.
- params = new int[((end - start) / step) + 1];
- int i = 0;
- for (int n = start; n <= end; n += step)
- {
- params[i++] = n;
- }
-
- this.repeat = repeat;
- }
-
- /**
- * Runs the test repeatedly for each value of the int parameter specified and for the correct number of test
- * repeats.
- *
- * @param result The test result object that the tests will indicate their results to. This is also used
- * to pass the int parameter from this class to the decorated test class.
- */
- public void run(TestResult result)
- {
- log.debug("public void run(TestResult result): called");
-
- if (!(result instanceof TKTestResult))
- {
- throw new IllegalArgumentException("AsymptoticTestDecorator only works with TKTestResult");
- }
-
- // Cast the test result into a TKTestResult to place the current parameter into.
- TKTestResult tkResult = (TKTestResult) result;
-
- log.debug("params = " + ((params == null) ? null : MathUtils.printArray(params)));
- log.debug("repeat = " + repeat);
-
- if(params != null)
- {
- for (int n : params)
- {
- for (int j = 0; j < repeat; j++)
- {
- log.debug("n = " + n);
-
- // Set the integer parameter in the TKTestResult to be passed to the tests.
- tkResult.setN(n);
-
- if (tkResult.shouldStop())
- {
- log.debug("tkResult.shouldStop = " + true);
-
- break;
- }
-
- log.debug("Calling super#run");
- super.run(tkResult);
- }
- }
- }
- }
-
- /**
- * Prints out the name of this test with the string "(parameterized)" appended onto it for debugging purposes.
- *
- * @return The name of this test with the string "(parameterized)" appended onto it.
- */
- public String toString()
- {
- return super.toString() + "(parameterized)";
- }
-}
diff --git a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/ScaledTestDecorator.java b/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/ScaledTestDecorator.java
deleted file mode 100644
index 93e2a3c855..0000000000
--- a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/ScaledTestDecorator.java
+++ /dev/null
@@ -1,391 +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.junit.extensions;
-
-import junit.framework.Test;
-import junit.framework.TestResult;
-
-import java.util.concurrent.BrokenBarrierException;
-import java.util.concurrent.CyclicBarrier;
-
-/**
- * A test decorator that runs a test many times simultaneously in many threads.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Clone a test run into many threads and run them simultaneously.
- * <tr><td> Inform the test results of the start and end of each concurrent test batch. <td> {@link TKTestResult}
- * <tr><td> Inform the test results of the concurrency level. <td> {@link TKTestResult}
- * </table>
- *
- * @author Rupert Smith
- */
-public class ScaledTestDecorator extends WrappedSuiteTestDecorator implements ShutdownHookable // TestDecorator
-{
- /** Used for logging. */
- // private static final Logger log = Logger.getLogger(ScaledTestDecorator.class);
-
- /** Determines how long to wait for tests to cleanly exit on shutdown. */
- private static final long SHUTDOWN_PAUSE = 3000;
-
- /**
- * The stress levels or numbers of simultaneous threads to run the test in. The test is repeated at each of
- * the concurrency levels specified here. Defaults to 1 thread.
- */
- private int[] threads = new int[] { 1 };
-
- /** Used to hold the number of tests currently being run in parallel. */
- private int concurrencyLevel;
-
- /** The test to run. */
- private WrappedSuiteTestDecorator test;
-
- /**
- * Used to hold the current {@link TKTestResult} for the tests currently being run. This is made available so that
- * the shutdown hook can ask it to cleanly end the current tests in the event of a shutdown.
- */
- private TKTestResult currentTestResult;
-
- /** Flag set by the shutdown hook. This decorator will not start any new tests when this is set. */
- private boolean shutdown = false;
-
- /**
- * Creates an active test with default multiplier (1).
- *
- * @param test The target test.
- */
- public ScaledTestDecorator(WrappedSuiteTestDecorator test)
- {
- super(test);
- this.test = test;
- }
-
- /**
- * Creates a concurrently scaled test with the specified number of threads.
- *
- * @param test The target test.
- * @param numThreads The stress level.
- */
- public ScaledTestDecorator(WrappedSuiteTestDecorator test, int numThreads)
- {
- this(test, new int[] { numThreads });
- }
-
- /**
- * Creates a concurrently scaled test with the specified thread levels, the test is repeated at each level.
- *
- * @param test The target test.
- * @param threads The concurrency levels.
- */
- public ScaledTestDecorator(WrappedSuiteTestDecorator test, int[] threads)
- {
- super(test);
-
- /*log.debug("public ScaledTestDecorator(WrappedSuiteTestDecorator test = \"" + test + "\", int[] threads = "
- + MathUtils.printArray(threads) + "): called");*/
-
- this.test = test;
- this.threads = threads;
- }
-
- /**
- * Runs the test simultaneously in at the specified concurrency levels.
- *
- * @param testResult The results object to monitor the test results with.
- */
- public void run(TestResult testResult)
- {
- // log.debug("public void run(TestResult testResult = " + testResult + "): called");
-
- // Loop through all of the specified concurrent levels for the test, provided shutdown has not been called.
- for (int i = 0; (i < threads.length) && !shutdown; i++)
- {
- // Get the number of threads for this run.
- int numThreads = threads[i];
-
- // Create test thread handlers for all the threads.
- TestThreadHandler[] threadHandlers = new TestThreadHandler[numThreads];
-
- // Create a cyclic barrier for the test threads to synch their setups and teardowns on.
- CyclicBarrier barrier = new CyclicBarrier(numThreads);
-
- // Set up the test thread handlers to output results to the same test results object.
- for (int j = 0; j < numThreads; j++)
- {
- threadHandlers[j] = new TestThreadHandler(testResult, test, barrier);
- }
-
- // Ensure the concurrency level statistic is set up correctly.
- concurrencyLevel = numThreads;
-
- // Begin batch.
- if (testResult instanceof TKTestResult)
- {
- TKTestResult tkResult = (TKTestResult) testResult;
- // tkResult.notifyStartBatch();
- tkResult.setConcurrencyLevel(numThreads);
-
- // Set the test result for the currently running tests, so that the shutdown hook can call it if necessary.
- currentTestResult = tkResult;
- }
-
- // Run all the tests and wait for them all to finish.
- executeAndWaitForRunnables(threadHandlers);
-
- // Clear the test result for the currently running tests.
- currentTestResult = null;
-
- // End batch.
- if (testResult instanceof TKTestResult)
- {
- TKTestResult tkResult = (TKTestResult) testResult;
- tkResult.notifyEndBatch();
- }
-
- // Clear up all the test threads, they hold references to their associated TestResult object and Test object,
- // which may prevent them from being garbage collected as the TestResult and Test objects are long lived.
- for (int j = 0; j < numThreads; j++)
- {
- threadHandlers[j].testResult = null;
- threadHandlers[j].test = null;
- threadHandlers[j] = null;
- }
- }
- }
-
- /**
- * Reports the number of tests that the scaled decorator is currently running concurrently.
- *
- * @return The number of tests that the scaled decorator is currently running concurrently.
- */
- public int getConcurrencyLevel()
- {
- return concurrencyLevel;
- }
-
- /**
- * Executes all of the specifed runnable using the thread pool and waits for them all to complete.
- *
- * @param runnables The set of runnables to execute concurrently.
- */
- private void executeAndWaitForRunnables(Runnable[] runnables)
- {
- int numThreads = runnables.length;
-
- // Used to keep track of the test threads in order to know when they have all completed.
- Thread[] threads = new Thread[numThreads];
-
- // Create all the test threads.
- for (int j = 0; j < numThreads; j++)
- {
- threads[j] = new Thread(runnables[j]);
- }
-
- // Start all the test threads.
- for (int j = 0; j < numThreads; j++)
- {
- threads[j].start();
- }
-
- // Wait for all the test threads to complete.
- for (int j = 0; j < numThreads; j++)
- {
- try
- {
- threads[j].join();
- }
- catch (InterruptedException e)
- {
- // Restore the interrupted state of the thread.
- Thread.currentThread().interrupt();
- }
- }
- }
-
- /**
- * Supplies the shut-down hook.
- *
- * @return The shut-down hook.
- */
- public Thread getShutdownHook()
- {
- return new Thread(new Runnable()
- {
- public void run()
- {
- // log.debug("ScaledTestDecorator::ShutdownHook: called");
-
- // Set the shutdown flag so that no new tests are started.
- shutdown = true;
-
- // Check if tests are currently running, and ask them to complete as soon as possible. Allow
- // a short pause for this to happen.
- TKTestResult testResult = currentTestResult;
-
- if (testResult != null)
- {
- // log.debug("There is a test result currently running tests, asking it to terminate ASAP.");
- testResult.shutdownNow();
-
- try
- {
- Thread.sleep(SHUTDOWN_PAUSE);
- }
- catch (InterruptedException e)
- {
- // Restore the interrupted state of the thread.
- Thread.currentThread().interrupt();
- }
- }
- }
- });
- }
-
- /**
- * Prints a string summarizing this test decorator, mainly for debugging purposes.
- *
- * @return String representation for debugging purposes.
- */
- public String toString()
- {
- return "ScaledTestDecorator: [ test = " + test + ", concurrencyLevel = " + concurrencyLevel + " ]";
- }
-
- /**
- * TestThreadHandler is a runnable used to execute a test in. This is static to avoid implicit 'this' reference to
- * the longer lived ScaledTestDecorator class. The scaled test decorator may execute many repeats but creates fresh
- * handlers for each one. It re-uses the threads in a pool but does not re-use these handlers.
- */
- private static class TestThreadHandler implements Runnable
- {
- /** The test result object for the test to be run with. */
- TestResult testResult;
-
- /** The test to run. */
- WrappedSuiteTestDecorator test;
-
- /** Holds the cyclic barrier to synchronize on the end of the setups and before the tear downs. */
- CyclicBarrier barrier;
-
- /**
- * Creates a new TestThreadHandler object.
- *
- * @param testResult The test result object for the test to be run with.
- * @param test The test to run in a sperate thread.
- * @param barrier The barrier implementation to use to synchronize per-thread setup completion and test
- * completion before moving on through the setup, test, teardown phases. The barrier should
- * be configured for the number of test threads.
- */
- TestThreadHandler(TestResult testResult, WrappedSuiteTestDecorator test, CyclicBarrier barrier)
- {
- this.testResult = testResult;
- this.test = test;
- this.barrier = barrier;
- }
-
- /**
- * Runs the test associated with this pool.
- */
- public void run()
- {
- try
- {
- // Call setup on all underlying tests in the suite that are thread aware.
- for (Test childTest : test.getAllUnderlyingTests())
- {
- // Check that the test is concurrency aware, so provides a setup method to call.
- if (childTest instanceof TestThreadAware)
- {
- // Call the tests per thread setup.
- TestThreadAware setupTest = (TestThreadAware) childTest;
- setupTest.threadSetUp();
- }
- }
-
- // Wait until all test threads have completed their setups.
- barrier.await();
-
-
- // Call setup on all underlying tests in the suite that are thread aware.
- for (Test childTest : test.getAllUnderlyingTests())
- {
- // Check that the test is concurrency aware, so provides a setup method to call.
- if (childTest instanceof TestThreadAware)
- {
- // Call the tests post thread setup.
- TestThreadAware setupTest = (TestThreadAware) childTest;
- setupTest.postThreadSetUp();
- }
- }
-
- // Wait until all test threads have completed their prefill.
- barrier.await();
-
- // Start timing the test batch, only after thread setups have completed.
- if (testResult instanceof TKTestResult)
- {
- ((TKTestResult) testResult).notifyStartBatch();
- }
-
- // Run the tests.
- test.run(testResult);
-
- // Wait unitl all test threads have completed their tests.
- barrier.await();
-
- // Call tear down on all underlying tests in the suite that are thread aware.
- for (Test childTest : test.getAllUnderlyingTests())
- {
- // Check that the test is concurrency aware, so provides a teardown method to call.
- if (childTest instanceof TestThreadAware)
- {
- // Call the tests per thread tear down.
- TestThreadAware setupTest = (TestThreadAware) childTest;
- setupTest.threadTearDown();
- }
- }
- }
- catch (InterruptedException e)
- {
- // Restore the interrupted state of the thread.
- Thread.currentThread().interrupt();
- }
- catch (BrokenBarrierException e)
- {
- // Set the interrupted state on the thread. The BrokenBarrierException may be caused where one thread
- // waiting for the barrier is interrupted, causing the remaining threads correctly waiting on the
- // barrier to fail. This condition is expected during test interruptions, and the response to it is to
- // interrupt all the other threads running in the same scaled test.
- Thread.currentThread().interrupt();
- }
- }
-
- /**
- * Prints the name of the test for debugging purposes.
- *
- * @return The name of the test.
- */
- public String toString()
- {
- return "ScaledTestDecorator: [test = \"" + test + "\"]";
- }
- }
-}
diff --git a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/SetupTaskAware.java b/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/SetupTaskAware.java
deleted file mode 100644
index e462145d7d..0000000000
--- a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/SetupTaskAware.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.junit.extensions;
-
-/**
- * SetupTaskAware is an interface that tests that can accept injectable setup tasks may implement. Typically this
- * is used by configurable decorator stack to inject setup tasks into tests. It is then up to the test case to run
- * the tasks in the setup or threadSetup methods as it chooses.
- *
- * <p/>Set up tasks should be chained so that they are executed in the order that they are applied. Tear down tasks
- * should be chained so that they are executed in the reverse order to which they are applied. That way the set up and
- * tear down tasks act as a 'task' stack, with nested setups and tear downs.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities.
- * <tr><td> Handle injection of set up tasks.
- * <tr><td> Handle injection of tear down tasks.
- * </table>
- *
- * @author Rupert Smith
- */
-public interface SetupTaskAware
-{
- /**
- * Adds the specified task to the tests setup.
- *
- * @param task The task to add to the tests setup.
- */
- public void chainSetupTask(Runnable task);
-
- /**
- * Adds the specified task to the tests tear down.
- *
- * @param task The task to add to the tests tear down.
- */
- public void chainTearDownTask(Runnable task);
-}
diff --git a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/SetupTaskHandler.java b/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/SetupTaskHandler.java
deleted file mode 100644
index b91ce41ad3..0000000000
--- a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/SetupTaskHandler.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.junit.extensions;
-
-import org.apache.qpid.junit.extensions.util.StackQueue;
-
-import java.util.LinkedList;
-import java.util.Queue;
-
-/**
- * SetupTaskHandler implements a task stack. It can be used, by delegation, as a base implementation for tests that want
- * to have configurable setup/teardown task stacks. Typically it is up to the test implementation to decide whether the
- * stack is executed in the setup/teardown methods or in the threadSetup/threadTeaddown methods.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Handle injection of set up tasks.
- * <tr><td> Handle injection of tear down tasks.
- * <tr><td> Run set up tasks in chain order.
- * <tr><td> Run tear down tasks in reverse chain order.
- * </table>
- *
- * @author Rupert Smith
- */
-public class SetupTaskHandler implements SetupTaskAware
-{
- /** Holds the set up tasks. */
- Queue<Runnable> setups = new LinkedList<Runnable>();
-
- /** Holds the tear down tasks. */
- Queue<Runnable> teardowns = new StackQueue<Runnable>();
-
- /**
- * Adds the specified task to the tests setup.
- *
- * @param task The task to add to the tests setup.
- */
- public void chainSetupTask(Runnable task)
- {
- setups.offer(task);
- }
-
- /**
- * Adds the specified task to the tests tear down.
- *
- * @param task The task to add to the tests tear down.
- */
- public void chainTearDownTask(Runnable task)
- {
- teardowns.offer(task);
- }
-
- /**
- * Runs the set up tasks in the order that they way chained.
- */
- public void runSetupTasks()
- {
- while (!setups.isEmpty())
- {
- setups.remove().run();
- }
- }
-
- /**
- * Runs the tear down tasks in the reverse of the order in which they were chained.
- */
- public void runTearDownTasks()
- {
- while (!teardowns.isEmpty())
- {
- teardowns.remove().run();
- }
- }
-}
diff --git a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/ShutdownHookable.java b/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/ShutdownHookable.java
deleted file mode 100644
index dc6aa3c291..0000000000
--- a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/ShutdownHookable.java
+++ /dev/null
@@ -1,42 +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.junit.extensions;
-
-/**
- * Defines an interface that classes which supply shutdown hooks implement. Code that creates these classes can check
- * if they supply a shutdown hook and register these hooks when the obejct are created.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities
- * <tr><td> Supply a shutdown hook.
- * </table>
- *
- * @author Rupert Smith
- */
-public interface ShutdownHookable
-{
- /**
- * Supplies the shutdown hook.
- *
- * @return The shut down hook.
- */
- public Thread getShutdownHook();
-}
diff --git a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/SleepThrottle.java b/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/SleepThrottle.java
deleted file mode 100644
index 2dc4c0e272..0000000000
--- a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/SleepThrottle.java
+++ /dev/null
@@ -1,81 +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.junit.extensions;
-
-/**
- * SleepThrottle is a Throttle implementation that generates short pauses using the thread sleep methods. As the pauses
- * get shorter, this technique gets more innacurate. In practice, around 100 Hz is the cap rate for accuracy.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Accept throttling rate in operations per second.
- * <tr><td> Inject short pauses to fill out processing cycles to a specified rate.
- * <tr><td> Check against a throttle speed without waiting.
- * </table>
- *
- * @author Rupert Smith
- */
-public class SleepThrottle extends BaseThrottle implements Throttle
-{
- /** Holds the time of the last call to the throttle method in nano seconds. */
- private long lastTimeNanos;
-
- /**
- * This method can only be called at the rate set by the {@link #setRate} method, if it is called faster than this
- * it will inject short pauses to restrict the call rate to that rate.
- */
- public void throttle()
- {
- // Get the current time in nanos.
- long currentTimeNanos = System.nanoTime();
-
- // Don't introduce any pause on the first call.
- if (!firstCall)
- {
- // Check if there is any time left in the cycle since the last call to this method and introduce a short pause
- // to fill that time if there is.
- long remainingTimeNanos = cycleTimeNanos - (currentTimeNanos - lastTimeNanos);
-
- if (remainingTimeNanos > 0)
- {
- long milliPause = remainingTimeNanos / 1000000;
- int nanoPause = (int) (remainingTimeNanos % 1000000);
-
- try
- {
- Thread.sleep(milliPause, nanoPause);
- }
- catch (InterruptedException e)
- {
- // Restore the interrupted thread, in-case the caller is checking for it.
- Thread.currentThread().interrupt();
- }
- }
- }
- else
- {
- firstCall = false;
- }
-
- // Update the last time stamp.
- lastTimeNanos = System.nanoTime();
- }
-}
diff --git a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/TKTestResult.java b/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/TKTestResult.java
deleted file mode 100644
index 5ce56a690e..0000000000
--- a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/TKTestResult.java
+++ /dev/null
@@ -1,654 +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.junit.extensions;
-
-import junit.framework.Test;
-import junit.framework.TestCase;
-import junit.framework.TestResult;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.junit.extensions.listeners.TKTestListener;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Properties;
-
-/**
- * TKTestResult extends TestResult in order to calculate test timings, to pass the variable integer parameter for
- * parameterized test cases to those test cases and to introduce an optional delay before test starts. Interested
- * {@link TKTestListener}s may be attached to this and will be informed of all relevant test statistics.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Calculate test timings.
- * <tr><td> Inform timing listeners of timings.
- * <tr><td> Inform memory listeners of memory readings.
- * <tr><td> Inform parameters listeners of parameters.
- * <tr><td> Pass the integer parameter to parameterized test cases.
- * <tr><td> Provide verbose test information on test start and end.
- * </table>
- *
- * @todo Move the verbose test information on test start/end into a test listener instead. It confuses the intention
- * of this class. Could also move the delay into a listener but that seems less appropriate as it would be a
- * side-effecting listener. Delay and timing calculation are fundamental enough to this class.
- *
- * @todo The need for this class to act as a place-holder for the integer parameter for parameterized test cases is
- * because this behaviour has been factored out into a test decorator class, see {@link AsymptoticTestDecorator}.
- * The {@link AsymptoticTestDecorator#run} method takes a TestResult as an argument and cannot easily get to the
- * {@link AsymptoticTestCase} class other than through this class. The option of using this class as a place hold
- * for this value was chosen. Alternatively this class could provide a method for decorators to access the
- * underlying test case through and then leave the setting of this parameter to the decorator which is a more
- * natural home for this behaviour. It would also provide a more general framework for decorators.
- *
- * @todo The memory usage may need to be moved in closer to the test method invocation so that as little code as possible
- * exists between it and the test or the results may be obscured. In fact it certainly does as the teardown method
- * is getting called first. Wouldn't be a bad idea to move the timing code in closer too.
- *
- * @todo Get rid of the delay logic. Will be replaced by throttle control.
- *
- * @author Rupert Smith
- */
-public class TKTestResult extends TestResult
-{
- /** Used for logging. */
- private static final Logger log = Logger.getLogger(TKTestResult.class);
-
- /** The delay between two tests. */
- private int delay = 0;
-
- /**
- * This flag indicates that the #completeTest method of the timing controller has been called. Once this has
- * been called once, the end test event for the whole test method should be ignored because tests have taken
- * charge of outputing their own timings.
- */
- private boolean completeTestUsed = false;
-
- /**
- * Thread locals to hold test start time for non-instrumented tests. (Instrumented tests hold their own
- * measurement data).
- */
- // private Hashtable threadStartTimeMap = new Hashtable();
- private ThreadLocal<ThreadLocalSettings> threadLocals = new ThreadLocal<ThreadLocalSettings>();
-
- /** Used to hold the current integer parameter to pass to parameterized tests. This defaults to 1. */
- private int n = 1;
-
- /** The timing listeners. */
- private Collection<TKTestListener> tkListeners;
-
- /** The test case name. */
- private String testCaseName;
-
- /** Used to hold the current concurrency level, set by the {@link ScaledTestDecorator}. */
- private int concurrencyLevel = 1;
-
- /** Flag used to indicate that this test result should attempt to complete its current tests as soon as possible. */
- private boolean shutdownNow = false;
-
- /** Holds the parametes that the test is run with. */
- private Properties testParameters;
-
- /**
- * Creates a new TKTestResult object.
- *
- * @param delay A delay in milliseconds to introduce before every test start.
- * @param testCaseName The name of the test case that this is the TestResult object for.
- */
- public TKTestResult(int delay, String testCaseName)
- {
- super();
-
- /*log.debug("public TKTestResult(PrintStream writer, int " + delay + ", boolean " + verbose + ", String "
- + testCaseName + "): called");*/
-
- // Keep all the parameters that this is created with.
- this.delay = delay;
- this.testCaseName = testCaseName;
- }
-
- /**
- * Callback method use to inform this test result that a test will be started. Waits for the configured delay time
- * if one has been set, starts the timer, then delegates to the super class implementation.
- *
- * @param test The test to be started.
- */
- public void startTest(Test test)
- {
- // log.debug("public void startTest(Test test): called");
-
- // If a delay time has been specified then wait for that length of time.
- if (this.delay > 0)
- {
- try
- {
- Thread.sleep(delay);
- }
- catch (InterruptedException e)
- {
- // Ignore, but restore the interrupted flag.
- Thread.currentThread().interrupt();
- }
- }
-
- // Create the thread local settings for the test.
- ThreadLocalSettings threadLocalSettings = new ThreadLocalSettings();
- threadLocals.set(threadLocalSettings);
-
- // Record the test start time against this thread for calculating the test timing. (Consider using ThreadLocal
- // instead?)
- Long startTime = System.nanoTime();
- threadLocalSettings.startTime = startTime;
- // log.debug("startTime = " + startTime);
-
- // Check if the test is timing controller aware, in which case set up a new timing controller and hold it
- // in the thread local settings.
- if (test instanceof TimingControllerAware)
- {
- TimingControllerAware controllerAware = (TimingControllerAware) test;
- TimingControllerImpl controller =
- new TimingControllerImpl(this, test, startTime, Thread.currentThread().getId());
- controllerAware.setTimingController(controller);
-
- threadLocalSettings.timingController = controller;
- }
-
- // Delegate to the super method to notify test event listeners.
- super.startTest(test);
- }
-
- /**
- * Callback method use to inform this result that a test was completed. This calculates how long the test took
- * to run, then delegates to the super class implementation.
- *
- * @param test The test that has ended.
- */
- public void endTest(Test test)
- {
- // log.debug("public void endTest(Test test): called");
-
- long runTime = 0;
-
- // Recover the thread local settings.
- ThreadLocalSettings threadLocalSettings = threadLocals.get();
-
- // Check if the test is an instrumented test and get the timing information from the instrumentation as this
- // will be more accurate.
- if (test instanceof InstrumentedTest)
- {
- InstrumentedTest iTest = (InstrumentedTest) test;
-
- // Calculate the test run time.
- runTime = iTest.getTestTime();
- // log.debug("runTime = " + runTime);
-
- // Calculate the test memory usage.
- long startMem = iTest.getTestStartMemory();
- long endMem = iTest.getTestEndMemory();
-
- // log.debug("startMem = " + startMem);
- // log.debug("endMem = " + endMem);
-
- // Inform any memory listeners of the test memory.
- if (tkListeners != null)
- {
- for (TKTestListener memoryListener : tkListeners)
- {
- memoryListener.memoryUsed(test, startMem, endMem, null);
- }
- }
- }
- else
- {
- // Calculate the test run time.
- long endTime = System.nanoTime();
- Long startTime = threadLocalSettings.startTime;
- runTime = endTime - startTime;
- // log.debug("runTime = " + runTime);
-
- threadLocals.remove();
- }
-
- // Output end test stats. This is only done when the tests have not used the timing controller to output
- // mutiple timings.
- if (!completeTestUsed)
- {
- // Check if the test is an asymptotic test case and get its int parameter if so.
- if (test instanceof AsymptoticTestCase)
- {
- AsymptoticTestCase pTest = (AsymptoticTestCase) test;
-
- // Set the parameter.
- int paramValue = pTest.getN();
-
- // Inform any parameter listeners of the test parameter.
- if (tkListeners != null)
- {
- for (TKTestListener parameterListener : tkListeners)
- {
- parameterListener.parameterValue(test, paramValue, null);
- }
- }
- }
-
- // Inform any timing listeners of the test timing and concurrency level.
- if (tkListeners != null)
- {
- for (TKTestListener tkListener : tkListeners)
- {
- TKTestListener next = tkListener;
-
- next.timing(test, runTime, null);
- next.concurrencyLevel(test, concurrencyLevel, null);
- }
- }
-
- // Call the super method to notify test event listeners of the end event.
- super.endTest(test);
- }
- }
-
- /**
- * Gets the integer parameter to pass to parameterized test cases.
- *
- * @return The value of the integer parameter.
- */
- public int getN()
- {
- return n;
- }
-
- /**
- * Sets the integer parameter to pass to parameterized test cases.
- *
- * @param n The new value of the integer parameter.
- */
- public void setN(int n)
- {
- // log.debug("public void setN(int " + n + "): called");
-
- this.n = n;
- }
-
- /**
- * Adds a timing listener to pass all timing events to.
- *
- * @param listener The timing listener to register.
- */
- public void addTKTestListener(TKTestListener listener)
- {
- // Create the collection to hold the timing listeners if it does not already exist.
- if (tkListeners == null)
- {
- tkListeners = new ArrayList<TKTestListener>();
- }
-
- // Keep the new timing listener.
- tkListeners.add(listener);
- }
-
- /**
- * Called by the test runner to notify this that a new test batch is being begun. This method forwards this
- * notification to all batch listeners.
- */
- public void notifyStartBatch()
- {
- if (tkListeners != null)
- {
- for (TKTestListener batchListener : tkListeners)
- {
- batchListener.startBatch();
- }
- }
- }
-
- /**
- * Called by the test runner to notify this that the current test batch has been ended. This method forwards this
- * notification to all batch listener.
- */
- public void notifyEndBatch()
- {
- // log.debug("public void notifyEndBatch(): called");
-
- if (tkListeners != null)
- {
- for (TKTestListener batchListener : tkListeners)
- {
- batchListener.endBatch(testParameters);
- }
- }
- }
-
- /**
- * Called by the test runner to notify this of the properties that the test is using.
- *
- * @param properties The tests set/read properties.
- */
- public void notifyTestProperties(Properties properties)
- {
- // log.debug("public void notifyTestProperties(Properties properties): called");
-
- this.testParameters = properties;
-
- /*
- if (tkListeners != null)
- {
- for (TKTestListener batchListener : tkListeners)
- {
- batchListener.properties(properties);
- }
- }
- */
- }
-
- /**
- * Intercepts the execution of a test case to pass the variable integer parameter to a test if it is a parameterized
- * test case.
- *
- * @param test The test to run.
- */
- protected void run(final TestCase test)
- {
- // log.debug("protected void run(final TestCase test): called");
-
- // Check if the test case is a parameterized test and set its integer parameter if so.
- if (test instanceof AsymptoticTestCase)
- {
- AsymptoticTestCase pTest = (AsymptoticTestCase) test;
-
- // Set up the integer parameter.
- pTest.setN(n);
- }
-
- // Delegate to the super method to run the test.
- super.run(test);
- }
-
- /**
- * Helper method that generats a String of verbose information about a test. This includes the thread name, test
- * class name and test method name.
- *
- * @param test The test to generate the info string for.
- *
- * @return Returns a string with the thread name, test class name and test method name.
- */
- protected String getTestInfo(Test test)
- {
- // log.debug("protected String getTestInfo(Test test): called");
-
- return "[" + Thread.currentThread().getName() + "@" + test.getClass().getName() + "."
- + ((test instanceof TestCase) ? ((TestCase) test).getName() : "") + "]";
- }
-
- /**
- * Sets the concurrency level to pass into the test result.
- *
- * @param concurrencyLevel The concurrency level the tests are running out.
- */
- public void setConcurrencyLevel(int concurrencyLevel)
- {
- this.concurrencyLevel = concurrencyLevel;
- }
-
- /**
- * Tells this test result that it should stop running tests. Once this method has been called this test result
- * will not start any new tests, and any tests that use the timing controller will be passed interrupted exceptions,
- * to indicate that they should end immediately. Usually the caller of this method will introduce a short wait
- * to allow an opporunity for running tests to complete, before forcing the shutdown of the JVM.
- */
- public void shutdownNow()
- {
- log.debug("public void shutdownNow(): called on " + this);
-
- shutdownNow = true;
- }
-
- /**
- * Prints a string summary of this class, mainly for debugging purposes.
- *
- * @return A string summary of this class, mainly for debugging purposes.
- */
- public String toString()
- {
- return "TKTestResult@" + Integer.toString(hashCode(), 16) + ": [ testCaseName = " + testCaseName + ", n = " + n
- + ", tkListeners = " + tkListeners + " ]";
- }
-
- /**
- * Holds things that need to be kept on a per thread basis for each test invocation, such as the test start
- * time and its timing controller.
- */
- private static class ThreadLocalSettings
- {
- /** Holds the test start time. */
- Long startTime;
-
- /** Holds the test threads timing controller. */
- TimingController timingController;
- }
-
- /**
- * Provides an implementation of the {@link TimingController} interface that timing aware tests can use to call
- * back to reset timers, and register additional test timings.
- */
- private static class TimingControllerImpl implements TimingController
- {
- /** Holds an explicit reference to the test TKTestResult that created this. */
- TKTestResult testResult;
-
- /** Holds a reference to the test that this is the timing controller for. */
- Test test;
-
- /** Holds the start time for this timing controller. This gets reset to now on each completed test. */
- long startTime;
-
- /**
- * Holds the thread id of the thread that started the test, so that this controller may be called from other
- * threads but still identify itself correctly to {@link TKTestListener}s as being associated with the
- * thread that called the test method.
- */
- long threadId;
-
- /**
- * Creates a timing controller on a specified TKTestResult and a test.
- *
- * @param testResult The TKTestResult that this controller interacts with.
- * @param test The test that this is the timing controller for.
- * @param startTime The test start time in nanoseconds.
- * @param threadId The thread id of the thread that is calling the test method.
- */
- public TimingControllerImpl(TKTestResult testResult, Test test, long startTime, long threadId)
- {
- this.testResult = testResult;
- this.test = test;
- this.startTime = startTime;
- this.threadId = threadId;
- }
-
- /**
- * Gets the timing controller associated with the current test thread. Tests that use timing controller should
- * always get the timing controller from this method in the same thread that called the setUp, tearDown or test
- * method. The controller returned by this method may be called from any thread because it remembers the thread
- * id of the original test thread.
- *
- * @return The timing controller associated with the current test thread.
- */
- public TimingController getControllerForCurrentThread()
- {
- // Recover the thread local settings and extract the timing controller from them.
- ThreadLocalSettings threadLocalSettings = testResult.threadLocals.get();
-
- return threadLocalSettings.timingController;
- }
-
- /**
- * Not implemented yet.
- *
- * @return Nothing.
- */
- public long suspend()
- {
- throw new RuntimeException("Method not implemented.");
- }
-
- /**
- * Not implemented yet.
- *
- * @return Nothing.
- */
- public long resume()
- {
- throw new RuntimeException("Method not implemented.");
- }
-
- /**
- * Resets the timer start time to now.
- *
- * @return The new value of the start time.
- */
- public long restart()
- {
- startTime = System.nanoTime();
-
- return startTime;
- }
-
- /**
- * Register an additional pass/fail for the current test. The test result is assumed to apply to a test of
- * 'size' parmeter 1. Use the {@link #completeTest(boolean, int)} method to register timings with parameters.
- *
- * @param testPassed Whether or not this timing is for a test pass or fail.
- *
- * @throws InterruptedException If the test runner decides that testing should stop it throws this exception to
- * indicate to the test method that it should stop immediately.
- */
- public void completeTest(boolean testPassed) throws InterruptedException
- {
- completeTest(testPassed, 1);
- }
-
- /**
- * Register an additional pass/fail for the current test. The test result is applies to a test of the specified
- * 'size' parmeter.
- *
- * @param testPassed Whether or not this timing is for a test pass or fail.
- * @param param The test parameter size for parameterized tests.
- *
- * @throws InterruptedException If the test runner decides that testing should stop it throws this exception to
- * indicate to the test method that it should stop immediately.
- */
- public void completeTest(boolean testPassed, int param) throws InterruptedException
- {
- completeTest(testPassed, param, null, null);
- }
-
- /**
- * Register an additional pass/fail for the current test. The test result is applies to a test of the specified
- * 'size' parmeter and allows the caller to sepecify the timing to log.
- *
- * @param testPassed Whether or not this timing is for a test pass or fail.
- * @param param The test parameter size for parameterized tests.
- * @param timeNanos The time in nano-seconds to log the test result with.
- *
- * A null value for timeNanos is a request to this method that it should
- * calculate the time for the given test run.
- *
- * @throws InterruptedException If the test runner decides that testing should stop it throws this exception to
- * indicate to the test method that it should stop immediately.
- */
- public void completeTest(boolean testPassed, int param, Long timeNanos) throws InterruptedException
- {
- completeTest(testPassed, param, timeNanos, null);
- }
-
- /**
- * Register an additional pass/fail for the current test. The test result is applies to a test of the specified
- * 'size' parmeter and allows the caller to sepecify the timing to log.
- *
- * @param testPassed Whether or not this timing is for a test pass or fail.
- * @param param The test parameter size for parameterized tests.
- * @param timeNanos The time in nano seconds to log the test result with.
- *
- * A null value for timeNanos is a request to this method that it should
- * calculate the time for the given test run.
- * A null value for timeNanos2 means this test does not provide a second
- * timing value so a '-' is printed in the log.
- *
- *
- * @throws InterruptedException If the test runner decides that testing should stop it throws this exception to
- * indicate to the test method that it should stop immediately.
- */
- public void completeTest(boolean testPassed, int param, Long timeNanos, Long time2Nanos) throws InterruptedException
- {
- log.debug("public void completeTest(boolean testPassed, int param, long timeNanos): called");
- log.debug("testResult = " + testResult);
-
- /*log.debug("public long completeTest(boolean testPassed = " + testPassed + ", int param = " + param
- + "): called");*/
-
- // Calculate the test run time.
- long endTime = System.nanoTime();
- long runTime = endTime - startTime;
- startTime = endTime;
-
- //
- if (timeNanos != null)
- {
- runTime = timeNanos;
- }
-
- // Tell the test result that completeTest has been used, so to not register end test events for the whole
- // test method.
- testResult.completeTestUsed = true;
-
- // Inform any timing listeners of the test timings and parameters and send an end test notification using
- // the thread id of the thread that started the test.
- if (testResult.tkListeners != null)
- {
- for (TKTestListener listener : testResult.tkListeners)
- {
- listener.reset(test, threadId);
- listener.timing(test, runTime, threadId);
- listener.timing2(test, time2Nanos, threadId);
- listener.parameterValue(test, param, threadId);
- listener.concurrencyLevel(test, testResult.concurrencyLevel, threadId);
-
- if (!testPassed)
- {
- listener.addFailure(test, null, threadId);
- }
-
- listener.endTest(test, threadId);
- }
- }
-
- // log.debug("testResult.shutdownNow = " + testResult.shutdownNow);
-
- // Check if the test runner has been asked to shutdown and raise an interuppted exception if so.
- if (testResult.shutdownNow)
- {
- // log.debug("The shutdown flag is set.");
-
- throw new InterruptedException("Attempting clean shutdown by suspending current test.");
- }
- }
- }
-}
diff --git a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/TKTestRunner.java b/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/TKTestRunner.java
deleted file mode 100644
index 671d33feed..0000000000
--- a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/TKTestRunner.java
+++ /dev/null
@@ -1,694 +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.junit.extensions;
-
-import junit.framework.Test;
-import junit.framework.TestResult;
-import junit.framework.TestSuite;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.junit.extensions.listeners.CSVTestListener;
-import org.apache.qpid.junit.extensions.listeners.ConsoleTestListener;
-import org.apache.qpid.junit.extensions.listeners.XMLTestListener;
-import org.apache.qpid.junit.extensions.util.CommandLineParser;
-import org.apache.qpid.junit.extensions.util.MathUtils;
-import org.apache.qpid.junit.extensions.util.ParsedProperties;
-import org.apache.qpid.junit.extensions.util.TestContextProperties;
-
-import java.io.*;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.LinkedList;
-import java.util.List;
-
-/**
- * TKTestRunner extends {@link junit.textui.TestRunner} with the ability to run tests multiple times, to execute a test
- * simultaneously using many threads, to put a delay between test runs and adds support for tests that take integer
- * parameters that can be 'stepped' through on multiple test runs. These features can be accessed by using this class
- * as an entry point and passing command line arguments to specify which features to use:
- *
- * <pre>
- * -w ms The number of milliseconds between invocations of test cases.
- * -c pattern The number of tests to run concurrently.
- * -r num The number of times to repeat each test.
- * -d duration The length of time to run the tests for.
- * -t name The name of the test case to execute.
- * -s pattern The size parameter to run tests with.
- * -o dir The name of the directory to output test timings to.
- * --csv Output test results in CSV format.
- * --xml Output test results in XML format.
- * </pre>
- *
- * <p/>This command line may also have trailing 'name=value' parameters added to it. All of these values are added
- * to the test context properties and passed to the test, which can access them by name.
- *
- * <p/>The pattern arguments are of the form [lowest(: ...)(: highest)](:sample=s)(:exp), where round brackets
- * enclose optional values. Using this pattern form it is possible to specify a single value, a range of values divided
- * into s samples, a range of values divided into s samples but distributed exponentially, or a fixed set of samples.
- *
- * <p/>The duration arguments are of the form (dD)(hH)(mM)(sS), where round brackets enclose optional values. At least
- * one of the optional values must be present.
- *
- * <p/>When specifying optional test parameters on the command line, in 'name=value' format, it is also possible to use
- * the format 'name=[value1:value2:value3:...]', to specify multiple values for a parameter. All permutations of all
- * parameters with multiple values will be created and tested. If the values are numerical, it is also possible to use
- * the sequence generation patterns instead of fully specifying all of the values.
- *
- * <p/>Here are some examples:
- *
- * <p/><table>
- * <tr><td><pre> -c [10:20:30:40:50] </pre><td> Runs the test with 10,20,...,50 threads.
- * <tr><td><pre> -s [1:100]:samples=10 </pre>
- * <td> Runs the test with ten different size parameters evenly spaced between 1 and 100.
- * <tr><td><pre> -s [1:1000000]:samples=10:exp </pre>
- * <td> Runs the test with ten different size parameters exponentially spaced between 1 and 1000000.
- * <tr><td><pre> -r 10 </pre><td> Runs each test ten times.
- * <tr><td><pre> -d 10H </pre><td> Runs the test repeatedly for 10 hours.
- * <tr><td><pre> -d 1M, -r 10 </pre>
- * <td> Runs the test repeatedly for 1 minute but only takes a timing sample every 10 test runs.
- * <tr><td><pre> -r 10, -c [1:5:10:50], -s [100:1000:10000] </pre>
- * <td> Runs 12 test cycles (4 concurrency samples * 3 size sample), with 10 repeats each. In total the test
- * will be run 199 times (3 + 15 + 30 + 150)
- * <tr><td><pre> cache=true </pre><td> Passes the 'cache' parameter with value 'true' to the test.
- * <tr><td><pre> cache=[true:false] </pre><td> Runs the test with the 'cache' parameter set to 'true' and 'false'.
- * <tr><td><pre> cacheSize=[1000:1000000],samples=4,exp </pre>
- * <td> Runs the test with the 'cache' parameter set to a series of exponentially increasing sizes.
- * </table>
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Create the test configuration specified by the command line parameters.
- * </table>
- *
- * @todo Verify that the output directory exists or can be created.
- *
- * @todo Verify that the specific named test case to execute exists.
- *
- * @todo Drop the delay parameter as it is being replaced by throttling.
- *
- * @todo Completely replace the test ui test runner, instead of having TKTestRunner inherit from it, its just not
- * good code to extend.
- *
- * @author Rupert Smith
- */
-public class TKTestRunner extends TestRunnerImprovedErrorHandling
-{
- /** Used for debugging. */
- private static final Logger log = Logger.getLogger(TKTestRunner.class);
-
- /** Used for displaying information on the console. */
- // private static final Logger console = Logger.getLogger("CONSOLE." + TKTestRunner.class.getName());
-
- /** Used for generating the timestamp when naming output files. */
- protected static final DateFormat TIME_STAMP_FORMAT = new SimpleDateFormat("yyyy-MM-dd-HH.mm.ss");
-
- /** Number of times to rerun the test. */
- protected Integer repetitions = 1;
-
- /** The length of time to run the tests for. */
- protected Long duration;
-
- /** Number of threads running the tests. */
- protected int[] threads;
-
- /** Delay in ms to wait between two test cases. */
- protected int delay = 0;
-
- /** The parameter values to pass to parameterized tests. */
- protected int[] params;
-
- /** Name of the single test case to execute. */
- protected String testCaseName = null;
-
- /** Name of the test class. */
- protected String testClassName = null;
-
- /** Name of the test run. */
- protected String testRunName = null;
-
- /** Directory to output XML reports into, if specified. */
- protected String reportDir = null;
-
- /** Flag that indicates the CSV results listener should be used to output results. */
- protected boolean csvResults;
-
- /** Flag that indiciates the XML results listener should be used to output results. */
- protected boolean xmlResults;
-
- /**
- * Holds the name of the class of the test currently being run. Ideally passed into the {@link #createTestResult}
- * method, but as the signature is already fixed for this, the current value gets pushed here as a member variable.
- */
- protected String currentTestClassName;
-
- /** Holds the test results object, which is reponsible for instrumenting tests/threads to record results. */
- protected TKTestResult result;
-
- /** Holds a list of factories for instantiating optional user specified test decorators. */
- protected List<TestDecoratorFactory> decoratorFactories;
-
- /**
- * Constructs a TKTestRunner using System.out for all the output.
- *
- * @param repetitions The number of times to repeat the test, or test batch size.
- * @param duration The length of time to run the tests for. -1 means no duration has been set.
- * @param threads The concurrency levels to ramp up to.
- * @param delay A delay in milliseconds between test runs.
- * @param params The sets of 'size' parameters to pass to test.
- * @param testCaseName The name of the test case to run.
- * @param reportDir The directory to output the test results to.
- * @param runName The name of the test run; used to name the output file.
- * @param csvResults <tt>true</tt> if the CSV results listener should be attached.
- * @param xmlResults <tt>true</tt> if the XML results listener should be attached.
- * @param decoratorFactories List of factories for user specified decorators.
- */
- public TKTestRunner(Integer repetitions, Long duration, int[] threads, int delay, int[] params, String testCaseName,
- String reportDir, String runName, boolean csvResults, boolean xmlResults,
- List<TestDecoratorFactory> decoratorFactories)
- {
- super(new NullResultPrinter(System.out));
-
- log.debug("public TKTestRunner(): called");
-
- // Keep all the test parameters.
- this.repetitions = repetitions;
- this.duration = duration;
- this.threads = threads;
- this.delay = delay;
- this.params = params;
- this.testCaseName = testCaseName;
- this.reportDir = reportDir;
- this.testRunName = runName;
- this.csvResults = csvResults;
- this.xmlResults = xmlResults;
- this.decoratorFactories = decoratorFactories;
- }
-
- /**
- * The entry point for the toolkit test runner.
- *
- * @param args The command line arguments.
- */
- public static void main(String[] args)
- {
- // Use the command line parser to evaluate the command line.
- CommandLineParser commandLine =
- new CommandLineParser(
- new String[][]
- {
- { "w", "The number of milliseconds between invocations of test cases.", "ms", "false" },
- { "c", "The number of tests to run concurrently.", "num", "false", MathUtils.SEQUENCE_REGEXP },
- { "r", "The number of times to repeat each test.", "num", "false" },
- { "d", "The length of time to run the tests for.", "duration", "false", MathUtils.DURATION_REGEXP },
- { "f", "The maximum rate to call the tests at.", "frequency", "false", "^([1-9][0-9]*)/([1-9][0-9]*)$" },
- { "s", "The size parameter to run tests with.", "size", "false", MathUtils.SEQUENCE_REGEXP },
- { "t", "The name of the test case to execute.", "name", "false" },
- { "o", "The name of the directory to output test timings to.", "dir", "false" },
- { "n", "A name for this test run, used to name the output file.", "name", "true" },
- {
- "X:decorators", "A list of additional test decorators to wrap the tests in.",
- "\"class.name[:class.name]*\"", "false"
- },
- { "1", "Test class.", "class", "true" },
- { "-csv", "Output test results in CSV format.", null, "false" },
- { "-xml", "Output test results in XML format.", null, "false" }
- });
-
- // Capture the command line arguments or display errors and correct usage and then exit.
- ParsedProperties options = null;
-
- try
- {
- options = new ParsedProperties(commandLine.parseCommandLine(args));
- }
- catch (IllegalArgumentException e)
- {
- System.out.println(commandLine.getErrors());
- System.out.println(commandLine.getUsage());
- System.exit(FAILURE_EXIT);
- }
-
- // Extract the command line options.
- Integer delay = options.getPropertyAsInteger("w");
- String threadsString = options.getProperty("c");
- Integer repetitions = options.getPropertyAsInteger("r");
- String durationString = options.getProperty("d");
- String paramsString = options.getProperty("s");
- String testCaseName = options.getProperty("t");
- String reportDir = options.getProperty("o");
- String testRunName = options.getProperty("n");
- String decorators = options.getProperty("X:decorators");
- String testClassName = options.getProperty("1");
- boolean csvResults = options.getPropertyAsBoolean("-csv");
- boolean xmlResults = options.getPropertyAsBoolean("-xml");
-
- int[] threads = (threadsString == null) ? null : MathUtils.parseSequence(threadsString);
- int[] params = (paramsString == null) ? null : MathUtils.parseSequence(paramsString);
- Long duration = (durationString == null) ? null : MathUtils.parseDuration(durationString);
-
- // The test run name defaults to the test class name unless a value was specified for it.
- testRunName = (testRunName == null) ? testClassName : testRunName;
-
- // Add all the command line options and trailing settings to test context properties. Tests may pick up
- // overridden values from there, and these values will be logged in the test results, for analysis and
- // to make tests repeatable.
- commandLine.addTrailingPairsToProperties(TestContextProperties.getInstance());
- commandLine.addOptionsToProperties(TestContextProperties.getInstance());
-
- // Create and start the test runner.
- try
- {
- // Create a list of test decorator factories for use specified decorators to be applied.
- List<TestDecoratorFactory> decoratorFactories = parseDecorators(decorators);
-
- TKTestRunner testRunner =
- new TKTestRunner(repetitions, duration, threads, (delay == null) ? 0 : delay, params, testCaseName,
- reportDir, testRunName, csvResults, xmlResults, decoratorFactories);
-
- TestResult testResult = testRunner.start(testClassName);
-
- if (!testResult.wasSuccessful())
- {
- System.exit(FAILURE_EXIT);
- }
- }
- catch (Exception e)
- {
- System.err.println(e.getMessage());
- e.printStackTrace(new PrintStream(System.err));
- System.exit(EXCEPTION_EXIT);
- }
- }
-
- /**
- * Parses a list of test decorators, in the form "class.name[:class.name]*", and creates factories for those
- * TestDecorator classes , and returns a list of the factories. This list of factories will be in the same
- * order as specified in the string. The factories can be used to succesively wrap tests in layers of
- * decorators, as decorators themselves implement the 'Test' interface.
- *
- * <p/>If the string fails to parse, or if any of the decorators specified in it are cannot be loaded, or are not
- * TestDecorators, a runtime exception with a suitable error message will be thrown. The factories themselves
- * throw runtimes if the constructor method calls on the decorators fail.
- *
- * @param decorators The decorators list to be parsed.
- *
- * @return A list of instantiated decorators.
- */
- protected static List<TestDecoratorFactory> parseDecorators(String decorators)
- {
- List<TestDecoratorFactory> result = new LinkedList<TestDecoratorFactory>();
- String toParse = decorators;
-
- // Check that the decorators string is not null or empty, returning an empty list of decorator factories it
- // it is.
- if ((decorators == null) || "".equals(decorators))
- {
- return result;
- }
-
- // Strip any leading and trailing quotes from the string.
- if (toParse.charAt(0) == '\"')
- {
- toParse = toParse.substring(1, toParse.length() - 1);
- }
-
- if (toParse.charAt(toParse.length() - 1) == '\"')
- {
- toParse = toParse.substring(0, toParse.length() - 2);
- }
-
- // Instantiate all decorators.
- for (String decoratorClassName : toParse.split(":"))
- {
- try
- {
- Class decoratorClass = Class.forName(decoratorClassName);
- final Constructor decoratorConstructor = decoratorClass.getConstructor(WrappedSuiteTestDecorator.class);
-
- // Check that the decorator is an instance of WrappedSuiteTestDecorator.
- if (!WrappedSuiteTestDecorator.class.isAssignableFrom(decoratorClass))
- {
- throw new RuntimeException("The decorator class " + decoratorClassName
- + " is not a sub-class of WrappedSuiteTestDecorator, which it needs to be.");
- }
-
- result.add(new TestDecoratorFactory()
- {
- public WrappedSuiteTestDecorator decorateTest(Test test)
- {
- try
- {
- return (WrappedSuiteTestDecorator) decoratorConstructor.newInstance(test);
- }
- catch (InstantiationException e)
- {
- throw new RuntimeException(
- "The decorator class " + decoratorConstructor.getDeclaringClass().getName()
- + " cannot be instantiated.", e);
- }
- catch (IllegalAccessException e)
- {
- throw new RuntimeException(
- "The decorator class " + decoratorConstructor.getDeclaringClass().getName()
- + " does not have a publicly accessable constructor.", e);
- }
- catch (InvocationTargetException e)
- {
- throw new RuntimeException(
- "The decorator class " + decoratorConstructor.getDeclaringClass().getName()
- + " cannot be invoked.", e);
- }
- }
- });
- }
- catch (ClassNotFoundException e)
- {
- throw new RuntimeException("The decorator class " + decoratorClassName + " could not be found.", e);
- }
- catch (NoSuchMethodException e)
- {
- throw new RuntimeException("The decorator class " + decoratorClassName
- + " does not have a constructor that accepts a single 'WrappedSuiteTestDecorator' argument.", e);
- }
- }
-
- return result;
- }
-
- /**
- * TestDecoratorFactory is a factory for creating test decorators from tests.
- */
- protected interface TestDecoratorFactory
- {
- /**
- * Decorates the specified test with a new decorator.
- *
- * @param test The test to decorate.
- *
- * @return The decorated test.
- */
- public WrappedSuiteTestDecorator decorateTest(Test test);
- }
-
- /**
- * Runs a test or suite of tests, using the super class implemenation. This method wraps the test to be run
- * in any test decorators needed to add in the configured toolkits enhanced junit functionality.
- *
- * @param test The test to run.
- * @param wait Undocumented. Nothing in the JUnit javadocs to say what this is for.
- *
- * @return The results of the test run.
- */
- public TestResult doRun(Test test, boolean wait)
- {
- log.debug("public TestResult doRun(Test \"" + test + "\", boolean " + wait + "): called");
-
- // Wrap the tests in decorators for duration, scaling, repetition, parameterization etc.
- WrappedSuiteTestDecorator targetTest = decorateTests(test);
-
- // Delegate to the super method to run the decorated tests.
- log.debug("About to call super.doRun");
-
- TestResult result = super.doRun(targetTest, wait);
- log.debug("super.doRun returned.");
-
- /*if (result instanceof TKTestResult)
- {
- TKTestResult tkResult = (TKTestResult) result;
-
- tkResult.notifyEndBatch();
- }*/
-
- return result;
- }
-
- /**
- * Applies test decorators to the tests for parameterization, duration, scaling and repetition.
- *
- * @param test The test to decorat.
- *
- * @return The decorated test.
- */
- protected WrappedSuiteTestDecorator decorateTests(Test test)
- {
- log.debug("params = " + ((params == null) ? null : MathUtils.printArray(params)));
- log.debug("repetitions = " + repetitions);
- log.debug("threads = " + ((threads == null) ? null : MathUtils.printArray(threads)));
- log.debug("duration = " + duration);
-
- // Wrap all tests in the test suite with WrappedSuiteTestDecorators. This is quite ugly and a bit baffling,
- // but the reason it is done is because the JUnit implementation of TestDecorator has some bugs in it.
- WrappedSuiteTestDecorator targetTest = null;
-
- if (test instanceof TestSuite)
- {
- log.debug("targetTest is a TestSuite");
-
- TestSuite suite = (TestSuite) test;
-
- int numTests = suite.countTestCases();
- log.debug("There are " + numTests + " in the suite.");
-
- for (int i = 0; i < numTests; i++)
- {
- Test nextTest = suite.testAt(i);
- log.debug("suite.testAt(" + i + ") = " + nextTest);
-
- if (nextTest instanceof TimingControllerAware)
- {
- log.debug("nextTest is TimingControllerAware");
- }
-
- if (nextTest instanceof TestThreadAware)
- {
- log.debug("nextTest is TestThreadAware");
- }
- }
-
- targetTest = new WrappedSuiteTestDecorator(suite);
- log.debug("Wrapped with a WrappedSuiteTestDecorator.");
- }
- // If the test has already been wrapped, no need to do it again.
- else if (test instanceof WrappedSuiteTestDecorator)
- {
- targetTest = (WrappedSuiteTestDecorator) test;
- }
-
- // If size parameter values have been set, then wrap the test in an asymptotic test decorator.
- if (params != null)
- {
- targetTest = new AsymptoticTestDecorator(targetTest, params, (repetitions == null) ? 1 : repetitions);
- log.debug("Wrapped with asymptotic test decorator.");
- log.debug("targetTest = " + targetTest);
- }
-
- // If no size parameters are set but the repitions parameter is, then wrap the test in an asymptotic test decorator.
- else if ((repetitions != null) && (repetitions > 1))
- {
- targetTest = new AsymptoticTestDecorator(targetTest, new int[] { 1 }, repetitions);
- log.debug("Wrapped with asymptotic test decorator.");
- log.debug("targetTest = " + targetTest);
- }
-
- // Apply any optional user specified decorators.
- targetTest = applyOptionalUserDecorators(targetTest);
-
- // If a test run duration has been set then wrap the test in a duration test decorator. This will wrap on
- // top of size, repeat or concurrency wrappings already applied.
- if (duration != null)
- {
- DurationTestDecorator durationTest = new DurationTestDecorator(targetTest, duration);
- targetTest = durationTest;
-
- log.debug("Wrapped with duration test decorator.");
- log.debug("targetTest = " + targetTest);
-
- registerShutdownHook(durationTest);
- }
-
- // ParameterVariationTestDecorator...
-
- // If a test thread concurrency level is set then wrap the test in a scaled test decorator. This will wrap on
- // top of size scaling or repetition wrappings.
- ScaledTestDecorator scaledDecorator;
-
- if ((threads != null) && ((threads.length > 1) || (MathUtils.maxInArray(threads) > 1)))
- {
- scaledDecorator = new ScaledTestDecorator(targetTest, threads);
- targetTest = scaledDecorator;
- log.debug("Wrapped with scaled test decorator.");
- log.debug("targetTest = " + targetTest);
- }
- else
- {
- scaledDecorator = new ScaledTestDecorator(targetTest, new int[] { 1 });
- targetTest = scaledDecorator;
- log.debug("Wrapped with scaled test decorator with default of 1 thread.");
- log.debug("targetTest = " + targetTest);
- }
-
- // Register the scaled test decorators shutdown hook.
- registerShutdownHook(scaledDecorator);
-
- return targetTest;
- }
-
- /**
- * If there were any user specified test decorators on the command line, this method instantiates them and wraps
- * the test in them, from inner-most to outer-most in the order in which the decorators were supplied on the
- * command line.
- *
- * @param targetTest The test to wrap.
- *
- * @return A wrapped test.
- */
- protected WrappedSuiteTestDecorator applyOptionalUserDecorators(WrappedSuiteTestDecorator targetTest)
- {
- // If there are user defined test decorators apply them in order now.
- for (TestDecoratorFactory factory : decoratorFactories)
- {
- targetTest = factory.decorateTest(targetTest);
- }
-
- return targetTest;
- }
-
- /**
- * Creates the TestResult object to be used for test runs. See {@link TKTestResult} for more information and the
- * enhanced test result class that this uses.
- *
- * @return An instance of the enhanced test result object, {@link TKTestResult}.
- */
- protected TestResult createTestResult()
- {
- log.debug("protected TestResult createTestResult(): called");
-
- TKTestResult result = new TKTestResult(delay, testCaseName);
-
- // Check if a directory to output reports to has been specified and attach test listeners if so.
- if (reportDir != null)
- {
- // Create the report directory if it does not already exist.
- File reportDirFile = new File(reportDir);
-
- if (!reportDirFile.exists())
- {
- reportDirFile.mkdir();
- }
-
- // Create the results file (make the name of this configurable as a command line parameter).
- Writer timingsWriter;
-
- // Always set up a console feedback listener.
- ConsoleTestListener feedbackListener = new ConsoleTestListener();
- result.addListener(feedbackListener);
- result.addTKTestListener(feedbackListener);
-
- // Set up an XML results listener to output the timings to the results file, if requested on the command line.
- if (xmlResults)
- {
- try
- {
- File timingsFile = new File(reportDirFile, "TEST-" + currentTestClassName + ".xml");
- timingsWriter = new BufferedWriter(new FileWriter(timingsFile), 20000);
- }
- catch (IOException e)
- {
- throw new RuntimeException("Unable to create the log file to write test results to: " + e, e);
- }
-
- XMLTestListener listener = new XMLTestListener(timingsWriter, currentTestClassName);
- result.addListener(listener);
- result.addTKTestListener(listener);
-
- registerShutdownHook(listener);
- }
-
- // Set up an CSV results listener to output the timings to the results file, if requested on the command line.
- if (csvResults)
- {
- try
- {
- File timingsFile =
- new File(reportDirFile, testRunName + "-" + TIME_STAMP_FORMAT.format(new Date()) + "-timings.csv");
- timingsWriter = new BufferedWriter(new FileWriter(timingsFile), 20000);
- }
- catch (IOException e)
- {
- throw new RuntimeException("Unable to create the log file to write test results to: " + e, e);
- }
-
- CSVTestListener listener = new CSVTestListener(timingsWriter);
- result.addListener(listener);
- result.addTKTestListener(listener);
-
- // Register the results listeners shutdown hook to flush its data if the test framework is shutdown
- // prematurely.
- registerShutdownHook(listener);
- }
-
- // Register the results listeners shutdown hook to flush its data if the test framework is shutdown
- // prematurely.
- // registerShutdownHook(listener);
-
- // Record the start time of the batch.
- // result.notifyStartBatch();
-
- // At this point in time the test class has been instantiated, giving it an opportunity to read its parameters.
- // Inform any test listers of the test properties.
- result.notifyTestProperties(TestContextProperties.getAccessedProps());
- }
-
- return result;
- }
-
- /**
- * Registers the shutdown hook of a {@link ShutdownHookable}.
- *
- * @param hookable The hookable to register.
- */
- protected void registerShutdownHook(ShutdownHookable hookable)
- {
- Runtime.getRuntime().addShutdownHook(hookable.getShutdownHook());
- }
-
- /**
- * Initializes the test runner with the provided command line arguments and and starts the test run.
- *
- * @param testClassName The fully qualified name of the test class to run.
- *
- * @return The test results.
- *
- * @throws Exception Any exceptions from running the tests are allowed to fall through.
- */
- protected TestResult start(String testClassName) throws Exception
- {
- // Record the current test class, so that the test results can be output to a file incorporating this name.
- this.currentTestClassName = testClassName;
-
- // Delegate to the super method to run the tests.
- return super.start(new String[] { testClassName });
- }
-}
diff --git a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/TestRunnerImprovedErrorHandling.java b/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/TestRunnerImprovedErrorHandling.java
deleted file mode 100644
index c68405bd06..0000000000
--- a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/TestRunnerImprovedErrorHandling.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.junit.extensions;
-
-import junit.framework.Test;
-import junit.framework.TestResult;
-
-import junit.runner.Version;
-
-import junit.textui.ResultPrinter;
-import junit.textui.TestRunner;
-
-import org.apache.log4j.Logger;
-
-import java.io.PrintStream;
-
-/**
- * The {@link junit.textui.TestRunner} does not provide very good error handling. It does not wrap exceptions and
- * does not print out stack traces, losing valuable error tracing information. This class overrides methods in it
- * in order to improve their error handling. The {@link TKTestRunner} is then built on top of this.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * </table>
- *
- * @author Rupert Smith
- */
-public class TestRunnerImprovedErrorHandling extends TestRunner
-{
- /** Used for logging. */
- Logger log = Logger.getLogger(TestRunnerImprovedErrorHandling.class);
-
- /**
- * Delegates to the super constructor.
- */
- public TestRunnerImprovedErrorHandling()
- {
- super();
- }
-
- /**
- * Delegates to the super constructor.
- *
- * @param printStream The location to write test results to.
- */
- public TestRunnerImprovedErrorHandling(PrintStream printStream)
- {
- super(printStream);
- }
-
- /**
- * Delegates to the super constructor.
- *
- * @param resultPrinter The location to write test results to.
- */
- public TestRunnerImprovedErrorHandling(ResultPrinter resultPrinter)
- {
- super(resultPrinter);
- }
-
- /**
- * Starts a test run. Analyzes the command line arguments
- * and runs the given test suite.
- *
- * @param args The command line arguments.
- *
- * @return The test results.
- *
- * @throws Exception Any exceptions falling through the tests are wrapped in Exception and rethrown.
- */
- public TestResult start(String[] args) throws Exception
- {
- String testCase = "";
- boolean wait = false;
-
- for (int i = 0; i < args.length; i++)
- {
- if (args[i].equals("-wait"))
- {
- wait = true;
- }
- else if (args[i].equals("-c"))
- {
- testCase = extractClassName(args[++i]);
- }
- else if (args[i].equals("-v"))
- {
- System.err.println("JUnit " + Version.id() + " by Kent Beck and Erich Gamma");
- }
- else
- {
- testCase = args[i];
- }
- }
-
- if (testCase.equals(""))
- {
- throw new Exception("Usage: TestRunner [-wait] testCaseName, where name is the name of the TestCase class");
- }
-
- try
- {
- Test suite = getTest(testCase);
-
- return doRun(suite, wait);
- }
- catch (Exception e)
- {
- log.warn("Got exception whilst creating and running test suite.", e);
- throw new Exception("Could not create and run the test suite.", e);
- }
- }
-}
diff --git a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/TestThreadAware.java b/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/TestThreadAware.java
deleted file mode 100644
index 94dcf5499b..0000000000
--- a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/TestThreadAware.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.junit.extensions;
-
-/**
- * This interface can be implemented by tests that want to know if they are being run concurrently. It provides
- * lifecycle notification events to tell the test implementation when test threads are being created and destroyed.
- * This can assist tests in creating and destroying resources that exist over the life of a test thread. A single
- * test thread can excute the same test many times, and often it is convenient to keep resources, for example network
- * connections, open over many test calls.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities
- * <tr><td> Set up per thread test fixtures.
- * <tr><td> Clean up per thread test fixtures.
- * </table>
- *
- * @author Rupert Smith
- */
-public interface TestThreadAware
-{
- /**
- * Called when a test thread is created.
- */
- public void threadSetUp();
-
- /**
- * Called after all threads have completed their setup.
- */
- public void postThreadSetUp();
-
- /**
- * Called when a test thread is destroyed.
- */
- public void threadTearDown();
-}
diff --git a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/Throttle.java b/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/Throttle.java
deleted file mode 100644
index 1ea8e8e2be..0000000000
--- a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/Throttle.java
+++ /dev/null
@@ -1,73 +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.junit.extensions;
-
-/**
- * Throttle is an interface that supplies a {@link #throttle} method, that can only be called at the rate specified
- * in a call to the {@link #setRate} method. This can be used to restict processing to run at a certain number
- * of operations per second.
- *
- * <p/>Throttle also supplies a method to check the throttle rate, without waiting. This could be used to update a user
- * interface every time an event occurs, but only up to a maximum rate. For example, as elements are added to a list,
- * a count of elements is updated for the user to see, but only up to a maximum rate of ten updates a second, as updating
- * faster than that slows the processing of element-by-element additions to the list unnecessarily.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities
- * <tr><td> Accept throttling rate in operations per second.
- * <tr><td> Inject short pauses to fill-out processing cycles to a specified rate.
- * <tr><td> Check against a throttle speed without waiting.
- * </table>
- *
- * @author Rupert Smith
- */
-public interface Throttle
-{
- /**
- * Specifies the throttling rate in operations per second. This must be called with with a value, the inverse
- * of which is a measurement in nano seconds, such that the number of nano seconds do not overflow a long integer.
- * The value must also be larger than zero.
- *
- * @param hertz The throttling rate in cycles per second.
- */
- public void setRate(float hertz);
-
- /**
- * This method can only be called at the rate set by the {@link #setRate} method, if it is called faster than this
- * it will inject short pauses to restrict the call rate to that rate.
- *
- * <p/>If the thread executing this method is interrupted, it must ensure that the threads interrupt thread
- * remains set upon exit from the method. This method does not expose InterruptedException, to indicate interruption
- * of the throttle during a timed wait. It may be changed so that it does.
- */
- public void throttle();
-
- /**
- * Checks but does not enforce the throttle rate. When this method is called, it checks if a length of time greater
- * than that equal to the inverse of the throttling rate has passed since it was last called and returned <tt>true</tt>
- *
- * @return <tt>true</tt> if a length of time greater than that equal to the inverse of the throttling rate has
- * passed since this method was last called and returned <tt>true</tt>, <tt>false</tt> otherwise. The very
- * first time this method is called on a throttle, it returns <tt>true</tt> as the base case to the above
- * self-referential definition.
- */
- public boolean checkThrottle();
-}
diff --git a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/TimingController.java b/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/TimingController.java
deleted file mode 100644
index 27e43a10a4..0000000000
--- a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/TimingController.java
+++ /dev/null
@@ -1,198 +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.junit.extensions;
-
-/**
- * A TimingController is a interface that a test that is aware of the fact that it is being timed can use to manage
- * the timer. Using this interface tests can suspend and resume test timers. This is usefull if you want to exclude
- * some expensive preparation from being timed as part of a test. In general when timing tests to measure the
- * performance of code, you should try to set up data in the #setUp where possible, or as static members in the test
- * class. This is not always convenient, this interface gives you a way to suspend and resume, or event completely
- * restart test timers, to get accurate measurements.
- *
- * <p/>The interface can also be used to register multiple test pass/fails and timings from a single test method.
- * In some cases it is easier to write tests in this way. For example a concurrent and asynchronous test may make
- * many asynchronous requests and then wait for replies to all its requests. Writing such a test with one send/reply
- * per test method and trying to scale up using many threads will quickly run into limitations if more than about
- * 100 asynchronous calls need to be made at once. A better way to write such a test is as a single method that sends
- * many (perhaps thousands or millions) and waits for replies in two threads, one for send, one for replies. It can
- * then log pass/fails and timings on each individual reply as they come back in, even though the test has been written
- * to send thousands of requests per test method in order to do volume testing.
- *
- * <p/>If when the {@link #completeTest(boolean)} is called, the test runner decides that testing should stop (perhaps
- * because a duration test has expired), it throws an InterruptedException to indicate that the test method should stop
- * immediately. The test method can do this by allowing this exception to fall through, if no other clean-up handling
- * is necessary, or it can simply return as soon as it possibly can. The test runner will still call the tearDown
- * method in the usual way when this happens.
- *
- * <p/>Below are some examples of how this can be used. Not how checking that the timing controller is really available
- * rather than assuming it is, means that the test can run as an ordinary JUnit test under the default test runners. In
- * general code should be written to take advantage of the extended capabilities of junit toolkit, without assuming they
- * are going to be run under its test runner.
- *
- * <pre>
- * public class MyTest extends TestCase implements TimingControllerAware {
- * ...
- *
- * timingUtils = this.getTimingController();
- *
- * // Do expensive data preparation here...
- *
- * if (timingUtils != null)
- * timingUtils.restart();
- * </pre>
- *
- * <pre>
- * public class MyTest extends TestCase implements TimingControllerAware {
- * ...
- *
- * public void myVolumeTest(int size) {
- *
- * timingUtils = this.getTimingController();
- *
- * boolean stopNow = false;
- *
- * // In Sender thread.
- * for(int i = 0; !stopNow && i < size; i++)
- * // Send request i.
- * ...
- *
- * // In Receiver thread.
- * onReceive(Object o) {
- * try {
- * // Check o is as expected.
- * if (....)
- * {
- * if (timingUtils != null)
- * timingUtils.completeTest(true);
- * }
- * else
- * {
- * if (timingUtils != null)
- * timingUtils.completeTest(false);
- * }
- * } catch (InterruptedException e) {
- * stopNow = true;
- * return;
- * }
- * }
- * </pre>
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities
- * <tr><td> Allow test timers to be suspended, restarted or reset.
- * <tr><td> Allow tests to register multiple pass/fails and timings.
- * </table>
- *
- * @author Rupert Smith
- */
-public interface TimingController
-{
- /**
- * Gets the timing controller associated with the current test thread. Tests that use timing controller should
- * always get the timing controller from this method in the same thread that called the setUp, tearDown or test
- * method. The controller returned by this method may be called from any thread because it remembers the thread
- * id of the original test thread.
- *
- * @return The timing controller associated with the current test thread.
- */
- public TimingController getControllerForCurrentThread();
-
- /**
- * Suspends the test timer.
- *
- * @return The current time in nanoseconds.
- */
- public long suspend();
-
- /**
- * Allows the test timer to continue running after a suspend.
- *
- * @return The current time in nanoseconds.
- */
- public long resume();
-
- /**
- * Completely restarts the test timer from zero.
- *
- * @return The current time in nanoseconds.
- */
- public long restart();
-
- /**
- * Register an additional pass/fail for the current test. The test result is assumed to apply to a test of
- * 'size' parmeter 1. Use the {@link #completeTest(boolean, int)} method to register timings with parameters.
- *
- * @param testPassed Whether or not this timing is for a test pass or fail.
- *
- * @throws InterruptedException If the test runner decides that testing should stop it throws this exception to
- * indicate to the test method that it should stop immediately.
- */
- public void completeTest(boolean testPassed) throws InterruptedException;
-
- /**
- * Register an additional pass/fail for the current test. The test result is applies to a test of the specified
- * 'size' parmeter.
- *
- * @param testPassed Whether or not this timing is for a test pass or fail.
- * @param param The test parameter size for parameterized tests.
- *
- * @throws InterruptedException If the test runner decides that testing should stop it throws this exception to
- * indicate to the test method that it should stop immediately.
- */
- public void completeTest(boolean testPassed, int param) throws InterruptedException;
-
- /**
- * Register an additional pass/fail for the current test. The test result is applies to a test of the specified
- * 'size' parmeter and allows the caller to sepecify the timing to log.
- *
- * @param testPassed Whether or not this timing is for a test pass or fail.
- * @param param The test parameter size for parameterized tests.
- * @param timeNanos The time in nano seconds to log the test result with.
- *
- * A null value for timeNanos is a request to this method that it should
- * calculate the time for the given test run.
- *
- *
- * @throws InterruptedException If the test runner decides that testing should stop it throws this exception to
- * indicate to the test method that it should stop immediately.
- */
- public void completeTest(boolean testPassed, int param, Long timeNanos) throws InterruptedException;
-
- /**
- * Register an additional pass/fail for the current test. The test result is applies to a test of the specified
- * 'size' parmeter and allows the caller to sepecify the timing to log.
- *
- * @param testPassed Whether or not this timing is for a test pass or fail.
- * @param param The test parameter size for parameterized tests.
- * @param timeNanos The time in nano seconds to log the test result with.
- *
- * A null value for timeNanos is a request to this method that it should
- * calculate the time for the given test run.
- * A null value for timeNanos2 means this test does not provide a second
- * timing value so a '-' is printed in the log.
- *
- *
- * @throws InterruptedException If the test runner decides that testing should stop it throws this exception to
- * indicate to the test method that it should stop immediately.
- */
- public void completeTest(boolean testPassed, int param, Long timeNanos, Long time2Nanos) throws InterruptedException;
-}
diff --git a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/TimingControllerAware.java b/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/TimingControllerAware.java
deleted file mode 100644
index 11db87e073..0000000000
--- a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/TimingControllerAware.java
+++ /dev/null
@@ -1,43 +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.junit.extensions;
-
-/**
- * TimingControllerAware is an interface that tests that manipulate the timing controller should implement. It enables
- * the TK test runner to set the test up with a handle on the timing controller which the test can use to call back
- * to the test runner to manage the timers.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities
- * <tr><td> Provide timing controller insertion point for tests.
- * </table>
- *
- * @author Rupert Smith
- */
-public interface TimingControllerAware
-{
- /**
- * Used by test runners that can supply a {@link TimingController} to set the controller on an aware test.
- *
- * @param controller The timing controller.
- */
- public void setTimingController(TimingController controller);
-}
diff --git a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/WrappedSuiteTestDecorator.java b/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/WrappedSuiteTestDecorator.java
deleted file mode 100644
index d5690fc24a..0000000000
--- a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/WrappedSuiteTestDecorator.java
+++ /dev/null
@@ -1,134 +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.junit.extensions;
-
-import junit.extensions.TestDecorator;
-
-import junit.framework.Test;
-import junit.framework.TestSuite;
-
-import org.apache.log4j.Logger;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-/**
- * WrappedSuiteTestDecorator is a test decorator that wraps a test suite, or another wrapped suite, but provides the
- * same functionality for the {@link junit.extensions.TestDecorator#countTestCases()} and {@link TestSuite#testAt(int)}
- * methods as the underlying suite. It returns the values that these methods provide, to enable classes using decorated
- * tests to drill down to the underlying tests in the suite. That is to say that it indexes and reports the number of
- * distinct tests in the suite, not the number of test runs that would result from, for example, wrapping the suite in a
- * repeating decorator.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities
- * <tr><td> Provide access to the underlying tests in a suite.
- * </table>
- *
- * @author Rupert Smith
- */
-public class WrappedSuiteTestDecorator extends TestDecorator
-{
- /** Used for logging. */
- private static Logger log = Logger.getLogger(WrappedSuiteTestDecorator.class);
-
- /** Holds the test suite that this supplies access to. */
- protected Test suite;
-
- /**
- * Creates a wrappred suite test decorator from a test suite.
- *
- * @param suite The test suite.
- */
- public WrappedSuiteTestDecorator(TestSuite suite)
- {
- super(suite);
- this.suite = suite;
- }
-
- /**
- * Creates a wrapped suite test decorator from another one.
- *
- * @param suite The test suite.
- */
- public WrappedSuiteTestDecorator(WrappedSuiteTestDecorator suite)
- {
- super(suite);
- this.suite = suite;
- }
-
- /**
- * Returns the test count of the wrapped suite.
- *
- * @return The test count of the wrapped suite.
- */
- public int countTestCases()
- {
- return suite.countTestCases();
- }
-
- /**
- * Gets the ith test from the test suite.
- *
- * @param i The index of the test within the suite to get.
- *
- * @return The test with the specified index.
- */
- public Test testAt(int i)
- {
- log.debug("public Test testAt(int i = " + i + "): called");
-
- if (suite instanceof WrappedSuiteTestDecorator)
- {
- return ((WrappedSuiteTestDecorator) suite).testAt(i);
- }
- else if (suite instanceof TestSuite)
- {
- return ((TestSuite) suite).testAt(i);
- }
-
- // This should never happen.
- return null;
- }
-
- /**
- * Gets all the tests from the underlying test suite.
- *
- * @return All the tests from the underlying test suite.
- */
- public Collection<Test> getAllUnderlyingTests()
- {
- log.debug("public Collection<Test> getAllUnderlyingTests(): called");
-
- List<Test> tests = new ArrayList<Test>();
-
- int numTests = countTestCases();
- log.debug("numTests = " + numTests);
-
- for (int i = 0; i < numTests; i++)
- {
- tests.add(testAt(i));
- }
-
- return tests;
- }
-}
diff --git a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/listeners/CSVTestListener.java b/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/listeners/CSVTestListener.java
deleted file mode 100644
index 40841189a3..0000000000
--- a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/listeners/CSVTestListener.java
+++ /dev/null
@@ -1,572 +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.junit.extensions.listeners;
-
-import junit.framework.AssertionFailedError;
-import junit.framework.Test;
-import junit.framework.TestCase;
-import junit.framework.TestListener;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.junit.extensions.ShutdownHookable;
-import org.apache.qpid.junit.extensions.util.TestContextProperties;
-
-import java.io.IOException;
-import java.io.Writer;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Properties;
-import java.util.Set;
-import java.util.TreeSet;
-
-/**
- * CSVTestListener is both a test listener, a timings listener, a memory listener and a parameter listener. It listens for test completion events and
- * then writes out all the data that it has listened to into a '.csv' (comma seperated values) file.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Listen to test events; start, end, fail, error.
- * <tr><td> Listen to test timings.
- * <tr><td> Listen to test memory usage.
- * <tr><td> Listen to parameterized test parameters.
- * <tr><td> Output all test data to a CSV file.
- * </table>
- *
- * @author Rupert Smith
- *
- * @todo Write an XML output class. Write a transform to convert it into an HTML page with timings as graphs.
- */
-public class CSVTestListener implements TestListener, TKTestListener, ShutdownHookable
-{
- /** Used for logging. */
- private static final Logger log = Logger.getLogger(CSVTestListener.class);
-
- /** The timings file writer. */
- private Writer timingsWriter;
-
- /**
- * Map for holding results on a per thread basis as they come in. A ThreadLocal is not used as sometimes an
- * explicit thread id must be used, where notifications come from different threads than the ones that called
- * the test method.
- */
- Map<Long, TestResult> threadLocalResults = Collections.synchronizedMap(new HashMap<Long, TestResult>());
-
- /** Used to record the start time of a complete test run, for outputing statistics at the end of the test run. */
- private long batchStartTime;
-
- /** Used to record the number of errors accross a complete test run. */
- private int numError;
-
- /** Used to record the number of failures accross a complete test run. */
- private int numFailed;
-
- /** Used to record the number of passes accross a complete test run. */
- private int numPassed;
-
- /** Used to record the total tests run accross a complete test run. Always equal to passes + errors + fails. */
- private int totalTests;
-
- /** Used to recrod the current concurrency level for the test batch. */
- private int concurrencyLevel;
-
- /**
- * Used to record the total 'size' of the tests run, this is the number run times the average value of the test
- * size parameters.
- */
- private int totalSize;
-
- /**
- * Used to record the summation of all of the individual test timings. Note that total time and summed time
- * are unlikely to be in agreement, exception for a single threaded test (with no setup time). Total time is
- * the time taken to run all the tests, summed time is the added up time that each individual test took. So if
- * two tests run in parallel and take one second each, total time will be one seconds, summed time will be two
- * seconds.
- */
- private long summedTime;
-
- /**
- * Used to record the summation of all of the second test timing information.
- * One use of the second timing would be to provide latency as well as test timing.
- */
- private long summedTime2;
-
- /** Flag to indicate when batch has been started but not ended to ensure end batch stats are output only once. */
- private boolean batchStarted = false;
-
- /**
- * Creates a new CSVTestListener object.
- *
- * @param writer A writer where this CSV listener should write out its output to.
- */
- public CSVTestListener(Writer writer)
- {
- // log.debug("public CSVTestListener(Writer writer): called");
-
- // Keep the writer.
- this.timingsWriter = writer;
- }
-
- /**
- * Resets the test results to the default state of time zero, memory usage zero, test passed.
- *
- * @param test The test to resest any results for.
- * @param threadId Optional thread id if not calling from thread that started the test method. May be null.
- */
- public void reset(Test test, Long threadId)
- {
- // log.debug("public void reset(Test test = \"" + test + "\", Long threadId = " + threadId + "): called");
-
- TestResult r =
- (threadId == null) ? threadLocalResults.get(Thread.currentThread().getId()) : threadLocalResults.get(threadId);
-
- r.testTime = 0L;
- r.testTime2 = null;
- r.testStartMem = 0L;
- r.testEndMem = 0L;
- r.testState = "Pass";
- r.testParam = 0;
- }
-
- /**
- * Called when a test results in an error.
- *
- * @param test The test which is in error.
- * @param t Any Throwable raised by the test in error.
- */
- public void addError(Test test, Throwable t)
- {
- // log.debug("public void addError(Test test, Throwable t): called");
-
- TestResult r = threadLocalResults.get(Thread.currentThread().getId());
- r.testState = "Error";
- }
-
- /**
- * Called when a test results in a failure.
- *
- * @param test The test which failed.
- * @param t The AssertionFailedError that encapsulates the test failure.
- */
- public void addFailure(Test test, AssertionFailedError t)
- {
- // log.debug("public void addFailure(Test \"" + test + "\", AssertionFailedError t): called");
-
- TestResult r = threadLocalResults.get(Thread.currentThread().getId());
- r.testState = "Failure";
- }
-
- /**
- * Called when a test completes to mark it as a test fail. This method should be used when registering a
- * failure from a different thread than the one that started the test.
- *
- * @param test The test which failed.
- * @param e The assertion that failed the test.
- * @param threadId Optional thread id if not calling from thread that started the test method. May be null.
- */
- public void addFailure(Test test, AssertionFailedError e, Long threadId)
- {
- // log.debug("public void addFailure(Test test = \"" + test + "\", AssertionFailedError e, Long threadId = " + threadId
- // + "): called");
-
- TestResult r =
- (threadId == null) ? threadLocalResults.get(Thread.currentThread().getId()) : threadLocalResults.get(threadId);
-
- r.testState = "Failure";
- }
-
- /**
- * Called when a test completes. Success, failure and errors.
- *
- * @param test The test which completed.
- */
- public void endTest(Test test)
- {
- // log.debug("public void endTest(Test \"" + test + "\"): called");
-
- TestResult r = threadLocalResults.get(Thread.currentThread().getId());
-
- writeTestResults(r, test);
-
- // Clear all the test results for the thread.
- threadLocalResults.remove(Thread.currentThread().getId());
- }
-
- /**
- * Called when a test starts.
- *
- * @param test The test wich has started.
- */
- public void startTest(Test test)
- {
- // log.debug("public void startTest(Test \"" + test + "\"): called");
-
- // Initialize the thread local test results.
- threadLocalResults.put(Thread.currentThread().getId(), new TestResult());
- }
-
- /**
- * Should be called every time a test completes with the run time of that test.
- *
- * @param test The name of the test.
- * @param nanos The run time of the test in nanoseconds.
- * @param threadId Optional thread id if not calling from thread that started the test method. May be null.
- */
- public void timing(Test test, long nanos, Long threadId)
- {
- // log.debug("public void timing(String \"" + test + "\", long " + nanos + "): called");
-
- TestResult r =
- (threadId == null) ? threadLocalResults.get(Thread.currentThread().getId()) : threadLocalResults.get(threadId);
-
- r.testTime = nanos;
- summedTime += nanos;
- }
-
- /**
- * Optionally called every time a test completes with the second timing test.
- *
- * @param test The name of the test.
- * @param nanos The second timing information of the test in nanoseconds.
- * @param threadId Optional thread id if not calling from thread that started the test method. May be null.
- */
- public void timing2(Test test, Long nanos, Long threadId)
- {
- TestResult r =
- (threadId == null) ? threadLocalResults.get(Thread.currentThread().getId()) : threadLocalResults.get(threadId);
-
-
- if (nanos != null)
- {
- r.testTime2 = nanos;
- summedTime2 += nanos;
- }
- }
-
- /**
- * Should be called every time a test completed with the amount of memory used before and after the test was run.
- *
- * @param test The test which memory was measured for.
- * @param memStart The total JVM memory used before the test was run.
- * @param memEnd The total JVM memory used after the test was run.
- * @param threadId Optional thread id if not calling from thread that started the test method. May be null.
- */
- public void memoryUsed(Test test, long memStart, long memEnd, Long threadId)
- {
- // log.debug("public void memoryUsed(Test \"" + test + "\", long " + memStart + ", long " + memEnd + ", Long "
- // + threadId + "): called");
-
- TestResult r =
- (threadId == null) ? threadLocalResults.get(Thread.currentThread().getId()) : threadLocalResults.get(threadId);
-
- r.testStartMem = memStart;
- r.testEndMem = memEnd;
- }
-
- /**
- * Should be called every time a parameterized test completed with the int value of its test parameter.
- *
- * @param test The test which memory was measured for.
- * @param parameter The int parameter value.
- * @param threadId Optional thread id if not calling from thread that started the test method. May be null.
- */
- public void parameterValue(Test test, int parameter, Long threadId)
- {
- // log.debug("public void parameterValue(Test test = \"" + test + "\", int parameter = " + parameter + "): called");
-
- TestResult r =
- (threadId == null) ? threadLocalResults.get(Thread.currentThread().getId()) : threadLocalResults.get(threadId);
-
- r.testParam = parameter;
- totalSize += parameter;
- }
-
- /**
- * Should be called every time a test completes with the current number of test threads running. This should not
- * change within a test batch, therefore it is safe to take this as a batch level property value too.
- *
- * @param test The test for which the measurement is being generated.
- * @param threads The number of tests being run concurrently.
- * @param threadId Optional thread id if not calling from thread that started the test method. May be null.
- */
- public void concurrencyLevel(Test test, int threads, Long threadId)
- {
- // log.debug("public void concurrencyLevel(Test test = \"" + test + "\", int threads = " + threads + "): called");
-
- TestResult r =
- (threadId == null) ? threadLocalResults.get(Thread.currentThread().getId()) : threadLocalResults.get(threadId);
-
- r.testConcurrency = threads;
- concurrencyLevel = threads;
-
- }
-
- /**
- * Called when a test completes. Success, failure and errors. This method should be used when registering an
- * end test from a different thread than the one that started the test.
- *
- * @param test The test which completed.
- * @param threadId Optional thread id if not calling from thread that started the test method. May be null.
- */
- public void endTest(Test test, Long threadId)
- {
- // log.debug("public void endTest(Test test = \"" + test + "\", Long threadId " + threadId + "): called");
-
- TestResult r =
- (threadId == null) ? threadLocalResults.get(Thread.currentThread().getId()) : threadLocalResults.get(threadId);
-
- writeTestResults(r, test);
- }
-
- /**
- * Takes a time stamp for the beginning of the batch and resets stats counted for the batch.
- */
- public synchronized void startBatch()
- {
- numError = 0;
- numFailed = 0;
- numPassed = 0;
- totalTests = 0;
- totalSize = 0;
- batchStartTime = System.nanoTime();
- summedTime = 0;
- summedTime2 = 0;
- batchStarted = true;
-
- // Write out the column headers for the batch.
- writeColumnHeaders();
- }
-
- /**
- * Takes a time stamp for the end of the batch to calculate the total run time.
- * Write this and other stats out to the tail of the csv file.
- *
- * @param parameters The optional test parameters, may be null.
- */
- public synchronized void endBatch(Properties parameters)
- {
- boolean noParams = (parameters == null) || (parameters.size() == 0);
-
- // Check that a batch has been started but not ended.
- if (batchStarted)
- {
- long batchEndTime = System.nanoTime();
- float totalTimeMillis = ((float) (batchEndTime - batchStartTime)) / 1000000f;
- float summedTimeMillis = ((float) summedTime) / 1000000f;
- float summedTime2Millis = ((float) summedTime2) / 1000000f;
-
-
- // Write the stats for the batch out.
- try
- {
- synchronized (this.getClass())
- {
- timingsWriter.write("Total Tests:, " + totalTests + ", ");
- timingsWriter.write("Total Passed:, " + numPassed + ", ");
- timingsWriter.write("Total Failed:, " + numFailed + ", ");
- timingsWriter.write("Total Error:, " + numError + ", ");
- timingsWriter.write("Total Size:, " + totalSize + ", ");
- timingsWriter.write("Summed Time:, " + summedTimeMillis + ", ");
- timingsWriter.write("Summed Custom Time:, " + summedTime2Millis + ", ");
- timingsWriter.write("Concurrency Level:, " + concurrencyLevel + ", ");
- timingsWriter.write("Total Time:, " + totalTimeMillis + ", ");
- timingsWriter.write("Average Custom Time:, " + ((summedTime2Millis/ (float) totalTests)) + ", ");
- timingsWriter.write("Test Throughput:, " + (((float) totalTests) / totalTimeMillis) + ", ");
- timingsWriter.write("Test * Size Throughput:, " + (((float) totalSize) / totalTimeMillis)
- + (noParams ? "\n\n" : ", "));
-
- // Write out the test parameters if there are any specified.
- if (!noParams)
- {
- properties(parameters);
- }
-
- timingsWriter.flush();
- }
- }
- catch (IOException e)
- {
- throw new RuntimeException("Unable to write out end batch statistics: " + e, e);
- }
- }
-
- // Reset the batch started flag to ensure stats are only output once.
- batchStarted = false;
- }
-
- /**
- * Notifies listeners of the tests read/set properties.
- *
- * @param properties The tests read/set properties.
- */
- public void properties(Properties properties)
- {
- // log.debug("public void properties(Properties properties): called");
-
- // Write the properties out to the results file.
- try
- {
- synchronized (this.getClass())
- {
- Set keySet = new TreeSet(properties.keySet());
-
- // timingsWriter.write("\n");
-
- for (Object key : keySet)
- {
- timingsWriter.write(key + " = , " + properties.getProperty((String) key) + ", ");
- }
-
- timingsWriter.write("\n\n");
- // timingsWriter.flush();
- }
- }
- catch (IOException e)
- {
- throw new RuntimeException("Unable to write out test parameters: " + e, e);
- }
-
- // Write out the column headers after the properties.
- // writeColumnHeaders();
- }
-
- /**
- * Writes out and flushes the column headers for raw test data.
- */
- private void writeColumnHeaders()
- {
- // Write the column headers for the CSV file. Any IO exceptions are ignored.
- try
- {
- timingsWriter.write("Class, ");
- timingsWriter.write("Method, ");
- timingsWriter.write("Thread, ");
- timingsWriter.write("Test Outcome, ");
- timingsWriter.write("Time (milliseconds), ");
- timingsWriter.write("Custom Time (milliseconds), ");
- timingsWriter.write("Memory Used (bytes), ");
- timingsWriter.write("Concurrency level, ");
- timingsWriter.write("Test Size\n");
-
- timingsWriter.flush();
- }
- catch (IOException e)
- {
- throw new RuntimeException("Unable to write out column headers: " + e, e);
- }
- }
-
- /**
- * Writes out the test results for the specified test. This outputs a single line of results to the csv file.
- *
- * @param r The test results to write out.
- * @param test The test to write them out for.
- */
- private void writeTestResults(TestResult r, Test test)
- {
- // Update the running stats for this batch.
- if ("Error".equals(r.testState))
- {
- numError++;
- }
- else if ("Failure".equals(r.testState))
- {
- numFailed++;
- }
- else if ("Pass".equals(r.testState))
- {
- numPassed++;
- }
-
- totalTests++;
-
- // Write the test name and thread information plus all instrumenation a line of the CSV ouput. Any IO
- // exceptions are ignored.
- try
- {
- synchronized (this.getClass())
- {
- timingsWriter.write(test.getClass().getName() + ", ");
- timingsWriter.write(((test instanceof TestCase) ? ((TestCase) test).getName() : "") + ", ");
- timingsWriter.write(Thread.currentThread().getName() + ", ");
- timingsWriter.write(r.testState + ", ");
- timingsWriter.write((((float) r.testTime) / 1000000f) + ", ");
-
- timingsWriter.write(r.testTime2 == null ? "- , " :
- (((float) r.testTime2) / 1000000f) + ", ");
- timingsWriter.write((r.testEndMem - r.testStartMem) + ", ");
- timingsWriter.write(r.testConcurrency + ", ");
- timingsWriter.write(r.testParam + "\n");
- }
- }
- catch (IOException e)
- {
- throw new RuntimeException("Unable to write out test results: " + e, e);
- }
- }
-
- /**
- * Supplies the shutdown hook. This attempts to flush the results in the event of the test runner being prematurely
- * suspended before the end of the current test batch.
- *
- * @return The shut down hook.
- */
- public Thread getShutdownHook()
- {
- return new Thread(new Runnable()
- {
- public void run()
- {
- log.debug("CSVTestListener::ShutdownHook: called");
-
- // Complete the current test batch stats.
- endBatch(TestContextProperties.getInstance());
- }
- });
- }
-
- /** Captures test results packaged into a single object, so that it can be set up as a thread local. */
- private static class TestResult
- {
- /** Used to hold the test timing. */
- public long testTime;
-
- /** Use to hold the second timing information. */
- public Long testTime2;
-
- /** Used to hold the test start memory usage. */
- public long testStartMem;
-
- /** Used to hold the test end memory usage. */
- public long testEndMem;
-
- /** Used to hold the test pass/fail/error state. */
- public String testState = "Pass";
-
- /** Used to hold the test parameter value. */
- public int testParam;
-
- /** Used to hold the concurrency level under which the test was run. */
- public int testConcurrency;
-
- }
-}
diff --git a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/listeners/ConsoleTestListener.java b/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/listeners/ConsoleTestListener.java
deleted file mode 100644
index 276fec328e..0000000000
--- a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/listeners/ConsoleTestListener.java
+++ /dev/null
@@ -1,274 +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.junit.extensions.listeners;
-
-import junit.framework.AssertionFailedError;
-import junit.framework.Test;
-import junit.framework.TestListener;
-
-import org.apache.qpid.junit.extensions.SleepThrottle;
-import org.apache.qpid.junit.extensions.Throttle;
-
-import java.util.Properties;
-
-/**
- * ConsoleTestListener provides feedback to the console, as test timings are taken, by drawing a '.', or an 'E', or an
- * 'F', for each test that passes, is in error or fails. It does this for every test result registered with the framework,
- * not just on the completion of each test method as the JUnit one does. It also uses a throttle to cap the rate of
- * dot drawing, as exessively high rates can degrade test performance without providing much usefull feedback to the user.
- * Unlike the JUnit dot drawing feedback, this one will correctly wrap lines when tests are run concurrently (the
- * rate capping ensures that this does not become a hot-spot for thread contention).
- *
- * <p/>Where rate capping causes the conflation of multiple requested dots into a single dot, the dot that is actually
- * drawn will be the worst result within the conflation period, that is, error is worse than fail which is worse than pass.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Draw dots as each test result completes, at a capped rate.
- * </table>
- *
- * @author Rupert Smith
- */
-public class ConsoleTestListener implements TestListener, TKTestListener
-{
- /** Used to indicate a test pass. */
- private static final int PASS = 1;
-
- /** Used to indicate a test failure. */
- private static final int FAIL = 2;
-
- /** Used to indicate a test error. */
- private static final int ERROR = 3;
-
- /** Defines the maximum number of columns of dots to print. */
- private static final int MAX_COLUMNS = 80;
-
- /** Used to throttle the dot writing rate. */
- Throttle throttle;
-
- /** Tracks the worst test result so far, when the throttled print method must conflate results due to throttling. */
- private int conflatedResult = 0;
-
- /** Tracks the column count as dots are printed, so that newlines can be inserted at the right margin. */
- private int columnCount = 0;
-
- /** Used as a monitor on the print method criticial section, to ensure that line ends always happen in the right place. */
- private final Object printMonitor = new Object();
-
- /**
- * Creates a dot drawing feedback test listener, set by default to 80 columns at 80 dots per second capped rate.
- */
- public ConsoleTestListener()
- {
- throttle = new SleepThrottle();
- throttle.setRate(80f);
- }
-
- /**
- * Prints dots at a capped rate, conflating the requested type of dot to draw if this method is called at a rate
- * higher than the capped rate. The conflation works by always printing the worst result that occurs within the
- * conflation period, that is, error is worse than fail which is worse than a pass.
- *
- * @param result The type of dot to draw, {@link #PASS}, {@link #FAIL} or {@link #ERROR}.
- */
- private void throttledPrint(int result)
- {
- conflatedResult = (result > conflatedResult) ? result : conflatedResult;
-
- if (throttle.checkThrottle())
- {
- synchronized (printMonitor)
- {
- switch (conflatedResult)
- {
- default:
- case PASS:
- System.out.print('.');
- break;
-
- case FAIL:
- System.out.print('F');
- break;
-
- case ERROR:
- System.out.print('E');
- break;
- }
-
- columnCount = (columnCount >= MAX_COLUMNS) ? 0 : (columnCount + 1);
-
- if (columnCount == 0)
- {
- System.out.print('\n');
- }
-
- conflatedResult = 0;
- }
- }
- }
-
- /**
- * An error occurred.
- *
- * @param test The test in error. Ignored.
- * @param t The error that the test threw. Ignored.
- */
- public void addError(Test test, Throwable t)
- {
- throttledPrint(ERROR);
- }
-
- /**
- * A failure occurred.
- *
- * @param test The test that failed. Ignored.
- * @param t The assertion failure that the test threw. Ignored.
- */
- public void addFailure(Test test, AssertionFailedError t)
- {
- throttledPrint(FAIL);
- }
-
- /**
- * A test ended.
- *
- * @param test The test that ended. Ignored.
- */
- public void endTest(Test test)
- {
- throttledPrint(PASS);
- }
-
- /**
- * A test started.
- *
- * @param test The test that started. Ignored.
- */
- public void startTest(Test test)
- { }
-
- /**
- * Resets the test results to the default state of time zero, memory usage zero, parameter zero, test passed.
- *
- * @param test The test to resest any results for.
- * @param threadId Optional thread id if not calling from thread that started the test method. May be null.
- */
- public void reset(Test test, Long threadId)
- { }
-
- /**
- * Should be called every time a test completes with the run time of that test.
- *
- * @param test The name of the test.
- * @param nanos The run time of the test in nanoseconds.
- * @param threadId Optional thread id if not calling from thread that started the test method. May be null.
- */
- public void timing(Test test, long nanos, Long threadId)
- { }
-
- /**
- * Optionally called every time a test completes with the second timing test.
- *
- * @param test The name of the test.
- * @param nanos The second timing information of the test in nanoseconds.
- * @param threadId Optional thread id if not calling from thread that started the test method. May be null.
- */
- public void timing2(Test test, Long nanos, Long threadId)
- { }
-
- /**
- * Should be called every time a test completed with the amount of memory used before and after the test was run.
- *
- * @param test The test which memory was measured for.
- * @param memStart The total JVM memory used before the test was run.
- * @param memEnd The total JVM memory used after the test was run.
- * @param threadId Optional thread id if not calling from thread that started the test method. May be null.
- */
- public void memoryUsed(Test test, long memStart, long memEnd, Long threadId)
- { }
-
- /**
- * Should be called every time a parameterized test completed with the int value of its test parameter.
- *
- * @param test The test which memory was measured for.
- * @param parameter The int parameter value.
- * @param threadId Optional thread id if not calling from thread that started the test method. May be null.
- */
- public void parameterValue(Test test, int parameter, Long threadId)
- { }
-
- /**
- * Should be called every time a test completes with the current number of test threads running.
- *
- * @param test The test for which the measurement is being generated.
- * @param threads The number of tests being run concurrently.
- * @param threadId Optional thread id if not calling from thread that started the test method. May be null.
- */
- public void concurrencyLevel(Test test, int threads, Long threadId)
- { }
-
- /**
- * Called when a test completes. Success, failure and errors. This method should be used when registering an
- * end test from a different thread than the one that started the test.
- *
- * @param test The test which completed.
- * @param threadId Optional thread id if not calling from thread that started the test method. May be null.
- */
- public void endTest(Test test, Long threadId)
- {
- throttledPrint(PASS);
- }
-
- /**
- * Called when a test completes to mark it as a test fail. This method should be used when registering a
- * failure from a different thread than the one that started the test.
- *
- * @param test The test which failed.
- * @param e The assertion that failed the test.
- * @param threadId Optional thread id if not calling from thread that started the test method. May be null.
- */
- public void addFailure(Test test, AssertionFailedError e, Long threadId)
- {
- throttledPrint(FAIL);
- }
-
- /**
- * Notifies listeners of the start of a complete run of tests.
- */
- public void startBatch()
- { }
-
- /**
- * Notifies listeners of the end of a complete run of tests.
- *
- * @param parameters The optional test parameters to log out with the batch results.
- */
- public void endBatch(Properties parameters)
- { }
-
- /**
- * Notifies listeners of the tests read/set properties.
- *
- * @param properties The tests read/set properties.
- */
- public void properties(Properties properties)
- { }
-}
diff --git a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/listeners/TKTestListener.java b/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/listeners/TKTestListener.java
deleted file mode 100644
index 63b042db10..0000000000
--- a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/listeners/TKTestListener.java
+++ /dev/null
@@ -1,142 +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.junit.extensions.listeners;
-
-import junit.framework.AssertionFailedError;
-import junit.framework.Test;
-import junit.framework.TestListener;
-
-import java.util.Properties;
-
-/**
- * TKTestListener is a listener interface for listeners that want to be informed of the run times of tests, the memory
- * usage of tests, the 'size' parameters of parameterized tests and the begin and end events of complete test runs.
- * {@link org.apache.qpid.junit.extensions.TKTestResult} is an example of a test result class that listeners
- * interested in these events can be attached to.
- *
- * The {@link #timing(junit.framework.Test, long, Long)}, {@link #memoryUsed(junit.framework.Test, long, long, Long)},
- * {@link #parameterValue(junit.framework.Test, int, Long)} and {@link #endTest(junit.framework.Test, Long)} methods
- * all accept on optional thread id parameter.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities
- * <tr><td> Listen to test timings.
- * <tr><td> Listen to test memory usages.
- * <tr><td> Listen to parameterized test parameters.
- * </table>
- *
- * @author Rupert Smith
- */
-public interface TKTestListener extends TestListener
-{
- /**
- * Resets the test results to the default state of time zero, memory usage zero, parameter zero, test passed.
- *
- * @param test The test to resest any results for.
- * @param threadId Optional thread id if not calling from thread that started the test method. May be null.
- */
- public void reset(Test test, Long threadId);
-
- /**
- * Should be called every time a test completes with the run time of that test.
- *
- * @param test The name of the test.
- * @param nanos The run time of the test in nanoseconds.
- * @param threadId Optional thread id if not calling from thread that started the test method. May be null.
- */
- public void timing(Test test, long nanos, Long threadId);
-
-
- /**
- * Optionally called every time a test completes with the second timing test.
- *
- * @param test The name of the test.
- * @param nanos The second timing information of the test in nanoseconds.
- * @param threadId Optional thread id if not calling from thread that started the test method. May be null.
- */
- public void timing2(Test test, Long nanos, Long threadId);
-
- /**
- * Should be called every time a test completed with the amount of memory used before and after the test was run.
- *
- * @param test The test which memory was measured for.
- * @param memStart The total JVM memory used before the test was run.
- * @param memEnd The total JVM memory used after the test was run.
- * @param threadId Optional thread id if not calling from thread that started the test method. May be null.
- */
- public void memoryUsed(Test test, long memStart, long memEnd, Long threadId);
-
- /**
- * Should be called every time a parameterized test completed with the int value of its test parameter.
- *
- * @param test The test which memory was measured for.
- * @param parameter The int parameter value.
- * @param threadId Optional thread id if not calling from thread that started the test method. May be null.
- */
- public void parameterValue(Test test, int parameter, Long threadId);
-
- /**
- * Should be called every time a test completes with the current number of test threads running.
- *
- * @param test The test for which the measurement is being generated.
- * @param threads The number of tests being run concurrently.
- * @param threadId Optional thread id if not calling from thread that started the test method. May be null.
- */
- public void concurrencyLevel(Test test, int threads, Long threadId);
-
- /**
- * Called when a test completes. Success, failure and errors. This method should be used when registering an
- * end test from a different thread than the one that started the test.
- *
- * @param test The test which completed.
- * @param threadId Optional thread id if not calling from thread that started the test method. May be null.
- */
- public void endTest(Test test, Long threadId);
-
- /**
- * Called when a test completes to mark it as a test fail. This method should be used when registering a
- * failure from a different thread than the one that started the test.
- *
- * @param test The test which failed.
- * @param e The assertion that failed the test.
- * @param threadId Optional thread id if not calling from thread that started the test method. May be null.
- */
- public void addFailure(Test test, AssertionFailedError e, Long threadId);
-
- /**
- * Notifies listeners of the start of a complete run of tests.
- */
- public void startBatch();
-
- /**
- * Notifies listeners of the end of a complete run of tests.
- *
- * @param parameters The optional test parameters to log out with the batch results.
- */
- public void endBatch(Properties parameters);
-
- /**
- * Notifies listeners of the tests read/set properties.
- *
- * @param properties The tests read/set properties.
- */
- public void properties(Properties properties);
-}
diff --git a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/listeners/XMLTestListener.java b/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/listeners/XMLTestListener.java
deleted file mode 100644
index ac875f89cf..0000000000
--- a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/listeners/XMLTestListener.java
+++ /dev/null
@@ -1,410 +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.junit.extensions.listeners;
-
-import junit.framework.AssertionFailedError;
-import junit.framework.Test;
-import junit.framework.TestCase;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.junit.extensions.ShutdownHookable;
-
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.io.Writer;
-import java.util.*;
-
-/**
- * Listens for test results for a named test and outputs these in the standard JUnit XML format to the specified
- * writer.
- *
- * <p/>The API for this listener accepts notifications about different aspects of a tests results through different
- * methods, so some assumption needs to be made as to which test result a notification refers to. For example
- * {@link #startTest} will be called, then possibly {@link #timing} will be called, even though the test instance is
- * passed in both cases, it is not enough to distinguish a particular run of the test, as the test case instance may
- * be being shared between multiple threads, or being run a repeated number of times, and can therfore be re-used
- * between calls. The listeners make the assumption that, for every test, a unique thread will call {@link #startTest}
- * and {@link #endTest} to delimit each test. All calls to set test parameters, timings, state and so on, will occur
- * between the start and end and will be given with the same thread id as the start and end, so the thread id provides
- * a unqiue value to identify a particular test run against.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Listen to test lifecycle notifications.
- * <tr><td> Listen to test errors and failures.
- * <tr><td> Listen to test timings.
- * <tr><td> Listen to test memory usages.
- * <tr><td> Listen to parameterized test parameters.
- * <tr><th> Responsibilities
- * </table>
- *
- * @todo Merge this class with CSV test listener, making the collection of results common to both, and only factoring
- * out the results printing code into sub-classes. Provide a simple XML results formatter with the same format as
- * the ant XML formatter, and a more structured one for outputing results with timings and summaries from
- * performance tests.
- *
- * @author Rupert Smith
- */
-public class XMLTestListener implements TKTestListener, ShutdownHookable
-{
- /** Used for debugging. */
- private static final Logger log = Logger.getLogger(XMLTestListener.class);
-
- /** The results file writer. */
- protected Writer writer;
-
- /** Holds the results for individual tests. */
- // protected Map<Result, Result> results = new LinkedHashMap<Result, Result>();
- // protected List<Result> results = new ArrayList<Result>();
-
- /**
- * Map for holding results on a per thread basis as they come in. A ThreadLocal is not used as sometimes an
- * explicit thread id must be used, where notifications come from different threads than the ones that called
- * the test method.
- */
- Map<Long, Result> threadLocalResults = Collections.synchronizedMap(new LinkedHashMap<Long, Result>());
-
- /**
- * Holds results for tests that have ended. Transferring these results here from the per-thread results map, means
- * that the thread id is freed for the thread to generate more results.
- */
- List<Result> results = new ArrayList<Result>();
-
- /** Holds the overall error count. */
- protected int errors = 0;
-
- /** Holds the overall failure count. */
- protected int failures = 0;
-
- /** Holds the overall tests run count. */
- protected int runs = 0;
-
- /** Holds the name of the class that tests are being run for. */
- String testClassName;
-
- /**
- * Creates a new XML results output listener that writes to the specified location.
- *
- * @param writer The location to write results to.
- * @param testClassName The name of the test class to include in the test results.
- */
- public XMLTestListener(Writer writer, String testClassName)
- {
- log.debug("public XMLTestListener(Writer writer, String testClassName = " + testClassName + "): called");
-
- this.writer = writer;
- this.testClassName = testClassName;
- }
-
- /**
- * Resets the test results to the default state of time zero, memory usage zero, parameter zero, test passed.
- *
- * @param test The test to resest any results for.
- * @param threadId Optional thread id if not calling from thread that started the test method. May be null.
- */
- public void reset(Test test, Long threadId)
- {
- log.debug("public void reset(Test test = " + test + ", Long threadId = " + threadId + "): called");
-
- XMLTestListener.Result r =
- (threadId == null) ? threadLocalResults.get(Thread.currentThread().getId()) : threadLocalResults.get(threadId);
-
- r.error = null;
- r.failure = null;
-
- }
-
- /**
- * Notification that a test started.
- *
- * @param test The test that started.
- */
- public void startTest(Test test)
- {
- log.debug("public void startTest(Test test = " + test + "): called");
-
- Result newResult = new Result(test.getClass().getName(), ((TestCase) test).getName());
-
- // Initialize the thread local test results.
- threadLocalResults.put(Thread.currentThread().getId(), newResult);
- runs++;
- }
-
- /**
- * Should be called every time a test completes with the run time of that test.
- *
- * @param test The name of the test.
- * @param nanos The run time of the test in nanoseconds.
- * @param threadId Optional thread id if not calling from thread that started the test method. May be null.
- */
- public void timing(Test test, long nanos, Long threadId)
- { }
-
- /**
- * Optionally called every time a test completes with the second timing test.
- *
- * @param test The name of the test.
- * @param nanos The second timing information of the test in nanoseconds.
- * @param threadId Optional thread id if not calling from thread that started the test method. May be null.
- */
- public void timing2(Test test, Long nanos, Long threadId)
- { }
-
- /**
- * Should be called every time a test completed with the amount of memory used before and after the test was run.
- *
- * @param test The test which memory was measured for.
- * @param memStart The total JVM memory used before the test was run.
- * @param memEnd The total JVM memory used after the test was run.
- * @param threadId Optional thread id if not calling from thread that started the test method. May be null.
- */
- public void memoryUsed(Test test, long memStart, long memEnd, Long threadId)
- { }
-
- /**
- * Should be called every time a parameterized test completed with the int value of its test parameter.
- *
- * @param test The test which memory was measured for.
- * @param parameter The int parameter value.
- * @param threadId Optional thread id if not calling from thread that started the test method. May be null.
- */
- public void parameterValue(Test test, int parameter, Long threadId)
- { }
-
- /**
- * Should be called every time a test completes with the current number of test threads running.
- *
- * @param test The test for which the measurement is being generated.
- * @param threads The number of tests being run concurrently.
- * @param threadId Optional thread id if not calling from thread that started the test method. May be null.
- */
- public void concurrencyLevel(Test test, int threads, Long threadId)
- { }
-
- /**
- * Notifies listeners of the tests read/set properties.
- *
- * @param properties The tests read/set properties.
- */
- public void properties(Properties properties)
- { }
-
- /**
- * Notification that a test ended.
- *
- * @param test The test that ended.
- */
- public void endTest(Test test)
- {
- log.debug("public void endTest(Test test = " + test + "): called");
-
- // Move complete test results into the completed tests list.
- Result r = threadLocalResults.get(Thread.currentThread().getId());
- results.add(r);
-
- // Clear all the test results for the thread.
- threadLocalResults.remove(Thread.currentThread().getId());
- }
-
- /**
- * Called when a test completes. Success, failure and errors. This method should be used when registering an
- * end test from a different thread than the one that started the test.
- *
- * @param test The test which completed.
- * @param threadId Optional thread id if not calling from thread that started the test method. May be null.
- */
- public void endTest(Test test, Long threadId)
- {
- log.debug("public void endTest(Test test = " + test + ", Long threadId = " + threadId + "): called");
-
- // Move complete test results into the completed tests list.
- Result r =
- (threadId == null) ? threadLocalResults.get(Thread.currentThread().getId()) : threadLocalResults.get(threadId);
- results.add(r);
-
- // Clear all the test results for the thread.
- threadLocalResults.remove(Thread.currentThread().getId());
- }
-
- /**
- * An error occurred.
- *
- * @param test The test in which the error occurred.
- * @param t The throwable that resulted from the error.
- */
- public void addError(Test test, Throwable t)
- {
- log.debug("public void addError(Test test = " + test + ", Throwable t = " + t + "): called");
-
- Result r = threadLocalResults.get(Thread.currentThread().getId());
- r.error = t;
- errors++;
- }
-
- /**
- * A failure occurred.
- *
- * @param test The test in which the failure occurred.
- * @param t The JUnit assertions that led to the failure.
- */
- public void addFailure(Test test, AssertionFailedError t)
- {
- log.debug("public void addFailure(Test test = " + test + ", AssertionFailedError t = " + t + "): called");
-
- Result r = threadLocalResults.get(Thread.currentThread().getId());
- r.failure = t;
- failures++;
- }
-
- /**
- * Called when a test completes to mark it as a test fail. This method should be used when registering a
- * failure from a different thread than the one that started the test.
- *
- * @param test The test which failed.
- * @param e The assertion that failed the test.
- * @param threadId Optional thread id if not calling from thread that started the test method. May be null.
- */
- public void addFailure(Test test, AssertionFailedError e, Long threadId)
- {
- log.debug("public void addFailure(Test test, AssertionFailedError e, Long threadId): called");
-
- Result r =
- (threadId == null) ? threadLocalResults.get(Thread.currentThread().getId()) : threadLocalResults.get(threadId);
- r.failure = e;
- failures++;
- }
-
- /**
- * Notifies listeners of the start of a complete run of tests.
- */
- public void startBatch()
- {
- log.debug("public void startBatch(): called");
-
- // Reset all results counts.
- threadLocalResults = Collections.synchronizedMap(new HashMap<Long, Result>());
- errors = 0;
- failures = 0;
- runs = 0;
-
- // Write out the file header.
- try
- {
- writer.write("<?xml version=\"1.0\" ?>\n");
- }
- catch (IOException e)
- {
- throw new RuntimeException("Unable to write the test results.", e);
- }
- }
-
- /**
- * Notifies listeners of the end of a complete run of tests.
- *
- * @param parameters The optional test parameters to log out with the batch results.
- */
- public void endBatch(Properties parameters)
- {
- log.debug("public void endBatch(Properties parameters = " + parameters + "): called");
-
- // Write out the results.
- try
- {
- // writer.write("<?xml version=\"1.0\" ?>\n");
- writer.write("<testsuite errors=\"" + errors + "\" failures=\"" + failures + "\" tests=\"" + runs + "\" name=\""
- + testClassName + "\">\n");
-
- for (Result result : results)
- {
- writer.write(" <testcase classname=\"" + result.testClass + "\" name=\"" + result.testName + "\">\n");
-
- if (result.error != null)
- {
- writer.write(" <error type=\"" + result.error.getClass() + "\">");
- result.error.printStackTrace(new PrintWriter(writer));
- writer.write(" </error>");
- }
- else if (result.failure != null)
- {
- writer.write(" <failure type=\"" + result.failure.getClass() + "\">");
- result.failure.printStackTrace(new PrintWriter(writer));
- writer.write(" </failure>");
- }
-
- writer.write(" </testcase>\n");
- }
-
- writer.write("</testsuite>\n");
- writer.flush();
- }
- catch (IOException e)
- {
- throw new RuntimeException("Unable to write the test results.", e);
- }
- }
-
- /**
- * Supplies the shutdown hook.
- *
- * @return The shut down hook.
- */
- public Thread getShutdownHook()
- {
- return new Thread(new Runnable()
- {
- public void run()
- {
- log.debug("XMLTestListener::ShutdownHook: called");
- }
- });
- }
-
- /**
- * Used to capture the results of a particular test run.
- */
- protected static class Result
- {
- /** Holds the name of the test class. */
- public String testClass;
-
- /** Holds the name of the test method. */
- public String testName;
-
- /** Holds the exception that caused error in this test. */
- public Throwable error;
-
- /** Holds the assertion exception that caused failure in this test. */
- public AssertionFailedError failure;
-
- /**
- * Creates a placeholder for the results of a test.
- *
- * @param testClass The test class.
- * @param testName The name of the test that was run.
- */
- public Result(String testClass, String testName)
- {
- this.testClass = testClass;
- this.testName = testName;
- }
- }
-}
diff --git a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/listeners/package.html b/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/listeners/package.html
deleted file mode 100644
index 15acc02ab1..0000000000
--- a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/listeners/package.html
+++ /dev/null
@@ -1,27 +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.
-
--->
-
-<html>
-<body>
-Listners for test statistics are defined in this package. At the moment there is only one listener which writes all test
-statistics out to a CSV (comma seperated values) file which can be loaded by most spread sheets.
-</body>
-</html>
diff --git a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/package.html b/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/package.html
deleted file mode 100644
index 4cab8d936a..0000000000
--- a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/package.html
+++ /dev/null
@@ -1,33 +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.
-
--->
-
-<html>
-<body>
-Basic JUnit is enahanced with test runners to run tests repeatedly, simultaneously in many threads and with increasing
-test sizes for asymptotic performance measurements. There are features to measure the time and amount of memory that
-tests use as well as to record the asymptotic test size parameters. There are some utilities to write these test
-statistics to various file formats too and these can be found in the listeners package.
-
-</p>The main test runner class is TKTestRunner which can be called with command line parameters to specify how tests
-should be run.
-
-</body>
-</html>
diff --git a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/util/CommandLineParser.java b/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/util/CommandLineParser.java
deleted file mode 100644
index f158090e96..0000000000
--- a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/util/CommandLineParser.java
+++ /dev/null
@@ -1,787 +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.junit.extensions.util;
-
-import java.text.CharacterIterator;
-import java.text.StringCharacterIterator;
-import java.util.*;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-/**
- * CommandLineParser provides a utility for specifying the format of a command line and parsing command lines to ensure
- * that they fit their specified format. A command line is made up of flags and options, both may be refered to as
- * options. A flag is an option that does not take an argument (specifying it means it has the value 'true' and not
- * specifying it means it has the value 'false'). Options must take arguments but they can be set up with defaults so
- * that they take a default value when not set. Options may be mandatory in wich case it is an error not to specify
- * them on the command line. Flags are never mandatory because they are implicitly set to false when not specified.
- *
- * <p/>Some examples command line are:
- *
- * <ul>
- * <li>This one has two options that expect arguments:
- * <pre>
- * cruisecontrol -configfile cruisecontrol.xml -port 9000
- * </pre>
- * <li>This has one no-arg flag and two 'free' arguments:
- * <pre>
- * zip -r project.zip project/*
- * </pre>
- * <li>This one concatenates multiple flags into a single block with only one '-':
- * <pre>
- * jar -tvf mytar.tar
- * </pre>
- *
- * <p/>The parsing rules are:
- *
- * <ol>
- * <li>Flags may be combined after a single '-' because they never take arguments. Normally such flags are single letter
- * flags but this is only a convention and not enforced. Flags of more than one letter are usually specified on their own.
- * <li>Options expecting arguments must always be on their own.
- * <li>The argument to an option may be seperated from it by whitespace or appended directly onto the option.
- * <li>The argument to an option may never begin with a '-' character.
- * <li>All other arguments not beginning with a '-' character are free arguments that do not belong to any option.
- * <li>The second or later of a set of duplicate or repeated flags override earlier ones.
- * <li>Options are matched up to the shortest matching option. This is because of the possibility of having no space
- * between an option and its argument. This rules out the possibility of using two options where one is an opening
- * substring of the other. For example, the options "foo" and "foobar" cannot be used on the same command line because
- * it is not possible to distinguish the argument "-foobar" from being the "foobar" option or the "foo" option with
- * the "bar" argument.
- * </ol>
- *
- * <p/>By default, unknown options are simply ignored if specified on the command line. This behaviour may be changed
- * so that the parser reports all unknowns as errors by using the {@link #setErrorsOnUnknowns} method.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Accept a command line specification.
- * <tr><td> Parse a command line into properties, validating it against its specification.
- * <tr><td> Report all errors between a command line and its specification.
- * <tr><td> Provide a formatted usage string for a command line.
- * <tr><td> Provide a formatted options in force string for a command line.
- * <tr><td> Allow errors on unknowns behaviour to be turned on or off.
- * </table>
- *
- * @author Rupert Smith
- */
-public class CommandLineParser
-{
- /**
- * Holds a mapping from command line option names to detailed information about those options.
- * Use of a tree map ensures that the options are easy to print in alphabetical order as a usage string.
- * An alternative might be to use a LinkedHashMap to print them in the order they are specified.
- */
- private Map<String, CommandLineOption> optionMap = new TreeMap<String, CommandLineOption>();
-
- /** Holds a list of parsing errors. */
- private List<String> parsingErrors = new ArrayList<String>();
-
- /** Holds the regular head matcher to match command line options with. */
- private Matcher optionMatcher = null;
-
- /** Holds the parsed command line properties after parsing. */
- private Properties parsedProperties = null;
-
- /** Holds any trailing name=value pairs specified in the free arguments. */
- private Properties trailingProperties = null;
-
- /** Flag used to indicate that errors should be created for unknown options. False by default. */
- private boolean errorsOnUnknowns = false;
-
- /**
- * Creates a command line options parser from a command line specification. This is passed to this constructor
- * as an array of arrays of strings. Each array of strings specifies the command line for a single option. A static
- * array may therefore easily be used to configure the command line parser in a single method call with an easily
- * readable format.
- *
- * <p/>Each array of strings must be 2, 3, 4 or 5 elements long. If any of the last three elements are missing they
- * are assumed to be null. The elements specify the following parameters:
- * <ol>
- * <li>The name of the option without the leading '-'. For example, "file". To specify the format of the 'free'
- * arguments use the option names "1", "2", ... and so on.
- * <li>The option comment. A line of text describing the usage of the option. For example, "The file to be processed."
- * <li>The options argument. This is a very short description of the argument to the option, often a single word
- * or a reminder as to the arguments format. When this element is null the option is a flag and does not
- * accept any arguments. For example, "filename" or "(unix | windows)" or null. The actual text specified
- * is only used to print in the usage message to remind the user of the usage of the option.
- * <li>The mandatory flag. When set to "true" an option must always be specified. Any other value, including null,
- * means that the option is mandatory. Flags are always mandatory (see class javadoc for explanation of why) so
- * this is ignored for flags.
- * <li>A regular head describing the format that the argument must take. Ignored if null.
- * </ol>
- * <p/>An example call to this constructor is:
- *
- * <pre>
- * CommandLineParser commandLine = new CommandLineParser(
- * new String[][] {{"file", "The file to be processed. ", "filename", "true"},
- * {"dir", "Directory to store results in. Current dir used if not set.", "out dir"},
- * {"os", "Operating system EOL format to use.", "(windows | unix)", null, "windows\|unix"},
- * {"v", "Verbose mode. Prints information about the processing as it goes."},
- * {"1", "The processing command to run.", "command", "true", "add\|remove\|list"}});
- * </pre>
- *
- * @param config The configuration as an array of arrays of strings.
- */
- public CommandLineParser(String[][] config)
- {
- // Loop through all the command line option specifications creating details for each in the options map.
- for (String[] nextOptionSpec : config)
- {
- addOption(nextOptionSpec[0], nextOptionSpec[1], (nextOptionSpec.length > 2) ? nextOptionSpec[2] : null,
- (nextOptionSpec.length > 3) && ("true".equals(nextOptionSpec[3])),
- (nextOptionSpec.length > 4) ? nextOptionSpec[4] : null);
- }
- }
-
- /**
- * Extracts all name=value pairs from the command line, sets them all as system properties and also returns
- * a map of properties containing them.
- *
- * @param args The command line.
- * @param commandLine The command line parser.
- * @param properties The properties object to inject all parsed properties into (optional may be <tt>null</tt>).
- *
- * @return A set of properties containing all name=value pairs from the command line.
- */
- public static Properties processCommandLine(String[] args, CommandLineParser commandLine, Properties properties)
- {
- // Capture the command line arguments or display errors and correct usage and then exit.
- Properties options = null;
-
- try
- {
- options = commandLine.parseCommandLine(args);
-
- // Add all the command line options and trailing settings to properties if the optional properties object
- // to copy them into has been set.
- if (properties != null)
- {
- commandLine.addTrailingPairsToProperties(properties);
- commandLine.addOptionsToProperties(properties);
- }
- }
- catch (IllegalArgumentException e)
- {
- System.out.println(commandLine.getErrors());
- System.out.println(commandLine.getUsage());
- System.exit(1);
- }
-
- return options;
- }
-
- /**
- * Lists all the parsing errors from the most recent parsing in a string.
- *
- * @return All the parsing errors from the most recent parsing.
- */
- public String getErrors()
- {
- // Return the empty string if there are no errors.
- if (parsingErrors.isEmpty())
- {
- return "";
- }
-
- // Concatenate all the parsing errors together.
- String result = "";
-
- for (String s : parsingErrors)
- {
- result += s;
- }
-
- return result;
- }
-
- /**
- * Lists the properties set from the most recent parsing or an empty string if no parsing has been done yet.
- *
- * @return The properties set from the most recent parsing or an empty string if no parsing has been done yet.
- */
- public String getOptionsInForce()
- {
- // Check if there are no properties to report and return and empty string if so.
- if (parsedProperties == null)
- {
- return "";
- }
-
- // List all the properties.
- String result = "Options in force:\n";
-
- for (Map.Entry<Object, Object> property : parsedProperties.entrySet())
- {
- result += property.getKey() + " = " + property.getValue() + "\n";
- }
-
- return result;
- }
-
- /**
- * Generates a usage string consisting of the name of each option and each options argument description and
- * comment.
- *
- * @return A usage string for all the options.
- */
- public String getUsage()
- {
- String result = "Options:\n";
-
- int optionWidth = 0;
- int argumentWidth = 0;
-
- // Calculate the column widths required for aligned layout.
- for (CommandLineOption optionInfo : optionMap.values())
- {
- int oWidth = optionInfo.option.length();
- int aWidth = (optionInfo.argument != null) ? (optionInfo.argument.length()) : 0;
-
- optionWidth = (oWidth > optionWidth) ? oWidth : optionWidth;
- argumentWidth = (aWidth > argumentWidth) ? aWidth : argumentWidth;
- }
-
- // Print usage on each of the command line options.
- for (CommandLineOption optionInfo : optionMap.values())
- {
- String argString = ((optionInfo.argument != null) ? (optionInfo.argument) : "");
- String optionString = optionInfo.option;
-
- argString = rightPad(argString, " ", argumentWidth);
- optionString = rightPad(optionString, " ", optionWidth);
-
- result += "-" + optionString + " " + argString + " " + optionInfo.comment + "\n";
- }
-
- return result;
- }
-
- /**
- * Right pads a string with a given string to a given size. This method will repeat the padder string as many
- * times as is necessary until the exact specified size is reached. If the specified size is less than the size
- * of the original string then the original string is returned unchanged.
- *
- * <pre>
- * Example1 - original string "cat", padder string "white", size 8 gives "catwhite".
- * Example2 - original string "cat", padder string "white", size 15 gives "catwhitewhitewh".
- * Example3 - original string "cat", padder string "white", size 2 gives "cat".
- * </pre>
- *
- * @param stringToPad The original string.
- * @param padder The string to pad onto the original string.
- * @param size The required size of the new string.
- *
- * @return The newly padded string.
- */
- public static String rightPad(String stringToPad, String padder, int size)
- {
- if (padder.length() == 0)
- {
- return stringToPad;
- }
-
- StringBuffer strb = new StringBuffer(stringToPad);
- StringCharacterIterator sci = new StringCharacterIterator(padder);
-
- while (strb.length() < size)
- {
- for (char ch = sci.first(); ch != CharacterIterator.DONE; ch = sci.next())
- {
- if (strb.length() < size)
- {
- strb.append(String.valueOf(ch));
- }
- }
- }
-
- return strb.toString();
- }
-
- /**
- * Control the behaviour of the errors on unkowns reporting. When turned on this reports all unkowns options
- * as errors. When turned off, all unknowns are simply ignored.
- *
- * @param errors The setting of the errors on unkown flag. True to turn it on.
- */
- public void setErrorsOnUnknowns(boolean errors)
- {
- errorsOnUnknowns = errors;
- }
-
- /**
- * Parses a set of command line arguments into a set of properties, keyed by the argument flag. The free arguments
- * are keyed by integers as strings starting at "1" and then "2", ... and so on.
- *
- * <p/>See the class level comment for a description of the parsing rules.
- *
- * @param args The command line arguments.
- *
- * @return The arguments as a set of properties.
- *
- * @throws IllegalArgumentException If the command line cannot be parsed against its specification. If this exception
- * is thrown a call to {@link #getErrors} will provide a diagnostic of the command
- * line errors.
- */
- public Properties parseCommandLine(String[] args) throws IllegalArgumentException
- {
- Properties options = new Properties();
-
- // Used to keep count of the current 'free' argument.
- int free = 1;
-
- // Used to indicate that the most recently parsed option is expecting arguments.
- boolean expectingArgs = false;
-
- // The option that is expecting arguments from the next element of the command line.
- String optionExpectingArgs = null;
-
- // Used to indicate that the most recently parsed option is a duplicate and should be ignored.
- // boolean ignore = false;
-
- // Create the regular head matcher for the command line options.
- String regexp = "^(";
- int optionsAdded = 0;
-
- for (Iterator<String> i = optionMap.keySet().iterator(); i.hasNext();)
- {
- String nextOption = i.next();
-
- // Check that the option is not a free argument definition.
- boolean notFree = false;
-
- try
- {
- Integer.parseInt(nextOption);
- }
- catch (NumberFormatException e)
- {
- notFree = true;
- }
-
- // Add the option to the regular head matcher if it is not a free argument definition.
- if (notFree)
- {
- regexp += nextOption + (i.hasNext() ? "|" : "");
- optionsAdded++;
- }
- }
-
- // There has to be more that one option in the regular head or else the compiler complains that the close
- // cannot be nullable if the '?' token is used to make the matched option string optional.
- regexp += ")" + ((optionsAdded > 0) ? "?" : "") + "(.*)";
- Pattern pattern = Pattern.compile(regexp);
-
- // Loop through all the command line arguments.
- for (String arg1 : args)
- {
- // Check if the next command line argument begins with a '-' character and is therefore the start of
- // an option.
- if (arg1.startsWith("-"))
- {
- // Extract the value of the option without the leading '-'.
- String arg = arg1.substring(1);
-
- // Match up to the longest matching option.
- optionMatcher = pattern.matcher(arg);
- optionMatcher.matches();
-
- String matchedOption = optionMatcher.group(1);
-
- // Match any argument directly appended onto the longest matching option.
- String matchedArg = optionMatcher.group(2);
-
- // Check that a known option was matched.
- if ((matchedOption != null) && !"".equals(matchedOption))
- {
- // Get the command line option information for the matched option.
- CommandLineOption optionInfo = optionMap.get(matchedOption);
-
- // Check if this option is expecting arguments.
- if (optionInfo.expectsArgs)
- {
- // The option is expecting arguments so swallow the next command line argument as an
- // argument to this option.
- expectingArgs = true;
- optionExpectingArgs = matchedOption;
-
- // In the mean time set this options argument to the empty string in case no argument is ever
- // supplied.
- // options.put(matchedOption, "");
- }
-
- // Check if the option was matched on its own and is a flag in which case set that flag.
- if ("".equals(matchedArg) && !optionInfo.expectsArgs)
- {
- options.put(matchedOption, "true");
- }
- // The option was matched as a substring with its argument appended to it or is a flag that is
- // condensed together with other flags.
- else if (!"".equals(matchedArg))
- {
- // Check if the option is a flag and therefore is allowed to be condensed together
- // with other flags.
- if (!optionInfo.expectsArgs)
- {
- // Set the first matched flag.
- options.put(matchedOption, "true");
-
- // Repeat the longest matching process on the remainder but ensure that the remainder
- // consists only of flags as only flags may be condensed together in this fashion.
- do
- {
- // Match the remainder against the options.
- optionMatcher = pattern.matcher(matchedArg);
- optionMatcher.matches();
-
- matchedOption = optionMatcher.group(1);
- matchedArg = optionMatcher.group(2);
-
- // Check that an option was matched.
- if (matchedOption != null)
- {
- // Get the command line option information for the next matched option.
- optionInfo = optionMap.get(matchedOption);
-
- // Ensure that the next option is a flag or raise an error if not.
- if (optionInfo.expectsArgs)
- {
- parsingErrors.add("Option " + matchedOption + " cannot be combined with flags.\n");
- }
-
- options.put(matchedOption, "true");
- }
- // The remainder could not be matched against a flag it is either an unknown flag
- // or an illegal argument to a flag.
- else
- {
- parsingErrors.add("Illegal argument to a flag in the option " + arg + "\n");
-
- break;
- }
- }
- // Continue until the remainder of the argument has all been matched with flags.
- while (!"".equals(matchedArg));
- }
- // The option is expecting an argument, so store the unmatched portion against it
- // as its argument.
- else
- {
- // Check the arguments format is correct against any specified format.
- checkArgumentFormat(optionInfo, matchedArg);
-
- // Store the argument against its option (regardless of its format).
- options.put(matchedOption, matchedArg);
-
- // The argument to this flag has already been supplied to it. Do not swallow the
- // next command line argument as an argument to this flag.
- expectingArgs = false;
- }
- }
- }
- else // No matching option was found.
- {
- // Add this to the list of parsing errors if errors on unkowns is being used.
- if (errorsOnUnknowns)
- {
- parsingErrors.add("Option " + matchedOption + " is not a recognized option.\n");
- }
- }
- }
- // The command line argument did not being with a '-' so it is an argument to the previous flag or it
- // is a free argument.
- else
- {
- // Check if a previous flag is expecting to swallow this next argument as its argument.
- if (expectingArgs)
- {
- // Get the option info for the option waiting for arguments.
- CommandLineOption optionInfo = optionMap.get(optionExpectingArgs);
-
- // Check the arguments format is correct against any specified format.
- checkArgumentFormat(optionInfo, arg1);
-
- // Store the argument against its option (regardless of its format).
- options.put(optionExpectingArgs, arg1);
-
- // Clear the expecting args flag now that the argument has been swallowed.
- expectingArgs = false;
- optionExpectingArgs = null;
- }
- // This command line option is not an argument to any option. Add it to the set of 'free' options.
- else
- {
- // Get the option info for the free option, if there is any.
- CommandLineOption optionInfo = optionMap.get(Integer.toString(free));
-
- if (optionInfo != null)
- {
- // Check the arguments format is correct against any specified format.
- checkArgumentFormat(optionInfo, arg1);
- }
-
- // Add to the list of free options.
- options.put(Integer.toString(free), arg1);
-
- // Move on to the next free argument.
- free++;
- }
- }
- }
-
- // Scan through all the specified options to check that all mandatory options have been set and that all flags
- // that were not set are set to false in the set of properties.
- for (CommandLineOption optionInfo : optionMap.values())
- {
- // Check if this is a flag.
- if (!optionInfo.expectsArgs)
- {
- // Check if the flag is not set in the properties and set it to false if so.
- if (!options.containsKey(optionInfo.option))
- {
- options.put(optionInfo.option, "false");
- }
- }
- // Check if this is a mandatory option and was not set.
- else if (optionInfo.mandatory && !options.containsKey(optionInfo.option))
- {
- // Create an error for the missing option.
- parsingErrors.add("Option " + optionInfo.option + " is mandatory but not was not specified.\n");
- }
- }
-
- // Check if there were any errors.
- if (!parsingErrors.isEmpty())
- {
- // Throw an illegal argument exception to signify that there were parsing errors.
- throw new IllegalArgumentException();
- }
-
- // Convert any name/value pairs in the free arguments into properties in the parsed options.
- trailingProperties = takeFreeArgsAsProperties(options, 1);
-
- parsedProperties = options;
-
- return options;
- }
-
- /**
- * If a command line has been parsed, calling this method sets all of its free arguments that were name=value pairs
- * on the specified properties.
- *
- * @param properties The property set to add the name=value pairs to.
- */
- public void addTrailingPairsToProperties(Properties properties)
- {
- if (trailingProperties != null)
- {
- for (Object propKey : trailingProperties.keySet())
- {
- String name = (String) propKey;
- String value = trailingProperties.getProperty(name);
-
- properties.setProperty(name, value);
- }
- }
- }
-
- /**
- * If a command line has been parsed, calling this method sets all of its options that were set to the specified
- * properties.
- *
- * @param properties The property set to the options to.
- */
- public void addOptionsToProperties(Properties properties)
- {
- if (parsedProperties != null)
- {
- for (Object propKey : parsedProperties.keySet())
- {
- String name = (String) propKey;
- String value = parsedProperties.getProperty(name);
-
- // This filters out all trailing items.
- if (!name.matches("^[0-9]+$"))
- {
- properties.setProperty(name, value);
- }
- }
- }
- }
-
- /**
- * Resets this command line parser after it has been used to parse a command line. This method will only need
- * to be called to use this parser a second time which is not likely seeing as a command line is usually only
- * specified once. However, it is exposed as a public method for the rare case where this may be done.
- *
- * <p/>Cleans the internal state of this parser, removing all stored errors and information about the options in
- * force.
- */
- public void reset()
- {
- parsingErrors = new ArrayList<String>();
- parsedProperties = null;
- }
-
- /**
- * Adds the option to list of available command line options.
- *
- * @param option The option to add as an available command line option.
- * @param comment A comment for the option.
- * @param argument The text that appears after the option in the usage string.
- * @param mandatory When true, indicates that this option is mandatory.
- * @param formatRegexp The format that the argument must take, defined as a regular head.
- */
- protected void addOption(String option, String comment, String argument, boolean mandatory, String formatRegexp)
- {
- // Check if usage text has been set in which case this option is expecting arguments.
- boolean expectsArgs = (!((argument == null) || argument.equals("")));
-
- // Add the option to the map of command line options.
- CommandLineOption opt = new CommandLineOption(option, expectsArgs, comment, argument, mandatory, formatRegexp);
- optionMap.put(option, opt);
- }
-
- /**
- * Converts the free arguments into property declarations. After parsing the command line the free arguments
- * are numbered from 1, such that the parsed properties contain values for the keys "1", "2", ... This method
- * converts any free arguments declared using the 'name=value' syntax into properties with key 'name', value
- * 'value'.
- *
- * <p/>For example the comand line:
- * <pre>
- * ... debug=true
- * </pre>
- *
- * <p/>After parsing has properties:
- * <pre>[[1, debug=true]]</pre>
- *
- * <p/>After applying this method the properties are:
- * <pre>[[1, debug=true], [debug, true]]</pre>
- *
- * @param properties The parsed command line properties.
- * @param from The free argument index to convert to properties from.
- *
- * @return The parsed command line properties, with free argument name value pairs too.
- */
- private Properties takeFreeArgsAsProperties(Properties properties, int from)
- {
- Properties result = new Properties();
-
- for (int i = from; true; i++)
- {
- String nextFreeArg = properties.getProperty(Integer.toString(i));
-
- // Terminate the loop once all free arguments have been consumed.
- if (nextFreeArg == null)
- {
- break;
- }
-
- // Split it on the =, strip any whitespace and set it as a system property.
- String[] nameValuePair = nextFreeArg.split("=");
-
- if (nameValuePair.length == 2)
- {
- result.setProperty(nameValuePair[0], nameValuePair[1]);
- }
- }
-
- return result;
- }
-
- /**
- * Checks the format of an argument to an option against its specified regular head format if one has
- * been set. Any errors are added to the list of parsing errors.
- *
- * @param optionInfo The command line option information for the option which is havings its argument checked.
- * @param matchedArg The string argument to the option.
- */
- private void checkArgumentFormat(CommandLineOption optionInfo, String matchedArg)
- {
- // Check if this option enforces a format for its argument.
- if (optionInfo.argumentFormatRegexp != null)
- {
- Pattern pattern = Pattern.compile(optionInfo.argumentFormatRegexp);
- Matcher argumentMatcher = pattern.matcher(matchedArg);
-
- // Check if the argument does not meet its required format.
- if (!argumentMatcher.matches())
- {
- // Create an error for this badly formed argument.
- parsingErrors.add("The argument to option " + optionInfo.option + " does not meet its required format.\n");
- }
- }
- }
-
- /**
- * Holds information about a command line options. This includes what its name is, whether or not it is a flag,
- * whether or not it is mandatory, what its user comment is, what its argument reminder text is and what its
- * regular head format is.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Hold details of a command line option.
- * </table>
- *
- * @author Rupert Smith
- */
- protected class CommandLineOption
- {
- /** Holds the text for the flag to match this argument with. */
- public String option = null;
-
- /** Holds a string describing how to use this command line argument. */
- public String argument = null;
-
- /** Flag that determines whether or not this command line argument can take arguments. */
- public boolean expectsArgs = false;
-
- /** Holds a short comment describing what this command line argument is for. */
- public String comment = null;
-
- /** Flag that determines whether or not this is an mandatory command line argument. */
- public boolean mandatory = false;
-
- /** A regular head describing what format the argument to this option muist have. */
- public String argumentFormatRegexp = null;
-
- /**
- * Create a command line option object that holds specific information about a command line option.
- *
- * @param option The text that matches the option.
- * @param expectsArgs Whether or not the option expects arguments. It is a flag if this is false.
- * @param comment A comment explaining how to use this option.
- * @param argument A short reminder of the format of the argument to this option/
- * @param mandatory Set to true if this option is mandatory.
- * @param formatRegexp The regular head that the argument to this option must meet to be valid.
- */
- public CommandLineOption(String option, boolean expectsArgs, String comment, String argument, boolean mandatory,
- String formatRegexp)
- {
- this.option = option;
- this.expectsArgs = expectsArgs;
- this.comment = comment;
- this.argument = argument;
- this.mandatory = mandatory;
- this.argumentFormatRegexp = formatRegexp;
- }
- }
-}
diff --git a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/util/ContextualProperties.java b/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/util/ContextualProperties.java
deleted file mode 100644
index 14de96d165..0000000000
--- a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/util/ContextualProperties.java
+++ /dev/null
@@ -1,494 +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.junit.extensions.util;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Properties;
-
-/**
- * ContextualProperties is an extension of {@link java.util.Properties} that automatically selects properties based on an
- * environment parameter (defined by the system property {@link #ENV_SYS_PROPERTY}), the name of a class, plus a modifier
- * (which can be used to name a method of a class) and a property key. It also supports the definition of arrays of
- * property values using indexes. The properties are searched in the following order until a match is found:
- *
- * <ol>
- * <li>environment + class name with package name + modifier + key
- * <li>environment + class name with package name + key
- * <li>environment + key
- * <li>class name with package name + modifier + key
- * <li>class name with package name + key
- * <li>key
- * </ol>
- *
- * <p>To create arrays of property values add index numbers onto the end of the property keys. An array of string values
- * will be created with the elements of the array set to the value of the property at the matching index. Ideally the
- * index values will be contiguous, starting at 0. This does not need to be the case however. If an array definition
- * begins at index n, and ends at index m, Then an array big enough to hold m + 1 elements will be created and populated
- * with values from n to m. Values before n and any missing values between n and m will be null in the array.
- *
- * <p>To give an example, suppose you have two different environments 'DEVELOPMENT' and 'PRODUCTION' and they each need
- * the same properties but set to different values for each environment and some properties the same in both, you could
- * create a properties file like:
- *
- * <p><code>
- * # Project configuration properties file.<br/>
- * <br/>
- * # These properties are environment specific.<br/>
- * DEVELOPMENT.debug=true<br/>
- * PRODUCTION.debug=false<br/>
- * <br/>
- * # Always debug MyClass in all environments but not the myMethod method.<br/>
- * MyClass.debug=true<br/>
- * MyClass.myMethod.debug=false<br/>
- * <br/>
- * # Set up an array of my ten favourite animals. Leave elements 3 to 8 as null as I haven't decided on them yet.<br/>
- * animals.0=cat<br/>
- * animals.1=dog<br/>
- * animals.2=elephant<br/>
- * animals.9=lion<br/>
- * <br/>
- * # This is a default value that will be used when the environment is not known.<br/>
- * debug=false<br/>
- * </code>
- *
- * <p>The most specific definition of a property is searched for first moving out to the most general. This allows
- * general property defaults to be set and then overiden for specific uses by some classes and modifiers.
- *
- * <p>A ContextualProperties object can be loaded in the same way as a java.utils.Properties. A recommended way to do
- * this that does not assume that the properties file is a file (it could be in a jar) is to load the properties from the
- * url for the resource lookup up on the classpath:
- *
- * <p><code>
- * Properties configProperties = new ContextualProperties();<br/>
- * configProperties.load(this.getClass().getClassLoader().getResourceAsStream("config.properties"));<br/>
- * </code>
- *
- * <p>EnvironmentProperties will load the 'DEVELOPMENT.debug' property or 'PROUCTION.debug' property based on the setting
- * of the system environment property. If a matching property for the environment cannot be found then the simple property
- * name without the environment pre-pended onto it will be used instead. This 'use of default environments' behaviour is
- * turned on initially but it can be disabled by calling the {@link #useDefaultEnvironments} method.
- *
- * <p>When a property matching a key cannot be found then the property accessor methods will always return null. If a
- * default value for a property exists but the 'use of default environments' behavious prevents it being used then the
- * accessor methods will return null.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Automatically select properties dependant on environment, class name and modifier as well as property key.
- * <tr><td> Convert indexed properties into arrays.
- * </table>
- *
- * @author Rupert Smith
- */
-public class ContextualProperties extends ParsedProperties
-{
- /** The name of the system property that is used to define the environment. */
- public static final String ENV_SYS_PROPERTY = "environment";
-
- /**
- * <p>Holds the iteration count down order.
- *
- * <p>If e = 4, b = 2, m = 1 then the iteration order or i is 7,6,4 and then if using environment defaults 3,2,0
- * where the accessor key is:
- * (i & e != 0 ? environment : "") + (i & b != 0 ? base : "") + (1 + m != 0 ? modifier : "") + key
- *
- * <p>In other words the presence or otherwise of the three least significant bits when counting down from 7
- * specifies which of the environment, base and modifier are to be included in the key where the environment, base
- * and modifier stand for the bits in positions 2, 1 and 0. The numbers 5 and 1 are missed out of the count because
- * they stand for the case where the modifier is used without the base which is not done.
- */
- private static final int[] ORDER = new int[] { 7, 6, 4, 3, 2, 0 };
-
- /**
- * Defines the point in the iteration count order below which the 'use environment defaults' feature is being used.
- */
- private static final int ENVIRONMENT_DEFAULTS_CUTOFF = 4;
-
- /** Defines the bit representation for the environment in the key ordering. See {@link #ORDER}. */
- private static final int E = 4;
-
- /** Defines the bit representation for the base in the key ordering. See {@link #ORDER}. */
- private static final int B = 2;
-
- /** Defines the bit representation for the modifier in the key ordering. See {@link #ORDER}. */
- private static final int M = 1;
-
- /** Used to hold the value of the environment system property. */
- private String environment;
-
- /** Used to indicate that the 'use of defaults' behaviour should be used. */
- private boolean useDefaults = true;
-
- /** Used to hold all the array properties. This is a mapping from property names to ArrayLists of Strings. */
- protected Map arrayProperties = new HashMap();
-
- /**
- * Default constructor that builds a ContextualProperties that uses environment defaults.
- */
- public ContextualProperties()
- {
- super();
-
- // Keep the value of the system environment property.
- environment = System.getProperty(ENV_SYS_PROPERTY);
- }
-
- /**
- * Creates a ContextualProperties that uses environment defaults and is initialized with the specified properties.
- *
- * @param props The properties to initialize this with.
- */
- public ContextualProperties(Properties props)
- {
- super(props);
-
- // Keep the value of the system environment property.
- environment = System.getProperty(ENV_SYS_PROPERTY);
-
- // Extract any array properties as arrays.
- createArrayProperties();
- }
-
- /**
- * Parses an input stream as properties.
- *
- * @param inStream The input stream to read the properties from.
- *
- * @exception IOException If there is an IO error during reading from the input stream.
- */
- public void load(InputStream inStream) throws IOException
- {
- super.load(inStream);
-
- // Extract any array properties as arrays.
- createArrayProperties();
- }
-
- /**
- * Tells this environment aware properties object whether it should use default environment properties without a
- * pre-pended environment when a property for the current environment cannot be found.
- *
- * @param flag True to use defaults, false to not use defaults.
- */
- public void useDefaultEnvironments(boolean flag)
- {
- useDefaults = flag;
- }
-
- /**
- * Looks up a property value relative to the environment, callers class and method. The default environment will be
- * checked for a matching property if defaults are being used. In order to work out the callers class and method this
- * method throws an exception and then searches one level up its stack frames.
- *
- * @param key The property key.
- *
- * @return The value of this property searching from the most specific definition (environment, class, method, key)
- * to the most general (key only), unless use of default environments is turned off in which case the most general
- * proeprty searched is (environment, key).
- */
- public String getProperty(String key)
- {
- // Try to get the callers class name and method name by examing the stack.
- String className = null;
- String methodName = null;
-
- // Java 1.4 onwards only.
- /*try
- {
- throw new Exception();
- }
- catch (Exception e)
- {
- StackTraceElement[] stack = e.getStackTrace();
-
- // Check that the stack trace contains at least two elements, one for this method and one for the caller.
- if (stack.length >= 2)
- {
- className = stack[1].getClassName();
- methodName = stack[1].getMethodName();
- }
- }*/
-
- // Java 1.5 onwards only.
- StackTraceElement[] stack = Thread.currentThread().getStackTrace();
-
- // Check that the stack trace contains at least two elements, one for this method and one for the caller.
- if (stack.length >= 2)
- {
- className = stack[1].getClassName();
- methodName = stack[1].getMethodName();
- }
-
- // Java 1.3 and before? Not sure, some horrible thing that parses the text spat out by printStackTrace?
-
- return getProperty(className, methodName, key);
- }
-
- /**
- * Looks up a property value relative to the environment, base class and modifier. The default environment will be
- * checked for a matching property if defaults are being used.
- *
- * @param base An object of the class to retrieve properties relative to.
- * @param modifier The modifier (which may stand for a method of the class).
- * @param key The property key.
- *
- * @return The value of this property searching from the most specific definition (environment, class, modifier, key)
- * to the most general (key only), unless use of default environments is turned off in which case the most general
- * property searched is (environment, key).
- */
- public String getProperty(Object base, String modifier, String key)
- {
- return getProperty(base.getClass().getName(), modifier, key);
- }
-
- /**
- * Looks up a property value relative to the environment, base class and modifier. The default environment will be
- * checked for a matching property if defaults are being used.
- *
- * @param base The name of the class to retrieve properties relative to.
- * @param modifier The modifier (which may stand for a method of the class).
- * @param key The property key.
- *
- * @return The value of this property searching from the most specific definition (environment, class, modifier, key)
- * to the most general (key only), unless use of default environments is turned off in which case the most general
- * property searched is (environment, key).
- */
- public String getProperty(String base, String modifier, String key)
- {
- String result = null;
-
- // Loop over the key orderings, from the most specific to the most general, until a matching value is found.
- for (Iterator i = getKeyIterator(base, modifier, key); i.hasNext();)
- {
- String nextKey = (String) i.next();
-
- result = super.getProperty(nextKey);
-
- if (result != null)
- {
- break;
- }
- }
-
- return result;
- }
-
- /**
- * Looks up an array property value relative to the environment, callers class and method. The default environment
- * will be checked for a matching array property if defaults are being used. In order to work out the callers class
- * and method this method throws an exception and then searches one level up its stack frames.
- *
- * @param key The property key.
- *
- * @return The array value of this indexed property searching from the most specific definition (environment, class,
- * method, key) to the most general (key only), unless use of default environments is turned off in which
- * case the most general proeprty searched is (environment, key).
- */
- public String[] getProperties(String key)
- {
- // Try to get the callers class name and method name by throwing an exception an searching the stack frames.
- String className = null;
- String methodName = null;
-
- /* Java 1.4 onwards only.
- try {
- throw new Exception();
- } catch (Exception e) {
- StackTraceElement[] stack = e.getStackTrace();
- // Check that the stack trace contains at least two elements, one for this method and one for the caller.
- if (stack.length >= 2) {
- className = stack[1].getClassName();
- methodName = stack[1].getMethodName();
- }
- }*/
- return getProperties(className, methodName, key);
- }
-
- /**
- * Looks up an array property value relative to the environment, base class and modifier. The default environment will
- * be checked for a matching array property if defaults are being used.
- *
- * @param base An object of the class to retrieve properties relative to.
- * @param modifier The modifier (which may stand for a method of the class).
- * @param key The property key.
- *
- * @return The array value of this indexed property searching from the most specific definition (environment, class,
- * modifier, key) to the most general (key only), unless use of default environments is turned off in which
- * case the most general proeprty searched is (environment, key).
- */
- public String[] getProperties(Object base, String modifier, String key)
- {
- return getProperties(base.getClass().getName(), modifier, key);
- }
-
- /**
- * Looks up an array property value relative to the environment, base class and modifier. The default environment will
- * be checked for a matching array property if defaults are being used.
- *
- * @param base The name of the class to retrieve properties relative to.
- * @param modifier The modifier (which may stand for a method of the class).
- * @param key The property key.
- *
- * @return The array value of this indexed property searching from the most specific definition (environment, class,
- * modifier, key) to the most general (key only), unless use of default environments is turned off in which
- * case the most general property searched is (environment, key).
- */
- public String[] getProperties(String base, String modifier, String key)
- {
- String[] result = null;
-
- // Loop over the key orderings, from the most specific to the most general, until a matching value is found.
- for (Iterator i = getKeyIterator(base, modifier, key); i.hasNext();)
- {
- String nextKey = (String) i.next();
- ArrayList arrayList = (ArrayList) arrayProperties.get(nextKey);
-
- if (arrayList != null)
- {
- result = (String[]) arrayList.toArray(new String[] {});
-
- break;
- }
- }
-
- return result;
- }
-
- /**
- * For a given environment, base, modifier and key and setting of the use of default environments feature this
- * generates an iterator that walks over the order in which to try and access properties.
- *
- * <p>See the {@link #ORDER} constant for an explanation of how the key ordering is generated.
- *
- * @param base The name of the class to retrieve properties relative to.
- * @param modifier The modifier (which may stand for a method of the class).
- * @param key The property key.
- *
- * @return An Iterator over String keys defining the order in which properties should be accessed.
- */
- protected Iterator getKeyIterator(final String base, final String modifier, final String key)
- {
- return new Iterator()
- {
- // The key ordering count always begins at the start of the ORDER array.
- private int i = 0;
-
- public boolean hasNext()
- {
- return (useDefaults ? ((i < ORDER.length) && (ORDER[i] > ENVIRONMENT_DEFAULTS_CUTOFF))
- : (i < ORDER.length));
- }
-
- public Object next()
- {
- // Check that there is a next element and return null if not.
- if (!hasNext())
- {
- return null;
- }
-
- // Get the next ordering count.
- int o = ORDER[i];
-
- // Do bit matching on the count to choose which elements to include in the key.
- String result =
- (((o & E) != 0) ? (environment + ".") : "") + (((o & B) != 0) ? (base + ".") : "")
- + (((o & M) != 0) ? (modifier + ".") : "") + key;
-
- // Increment the iterator to get the next key on the next call.
- i++;
-
- return result;
- }
-
- public void remove()
- {
- // This method is not supported.
- throw new UnsupportedOperationException("remove() is not supported on this key order iterator as "
- + "the ordering cannot be changed");
- }
- };
- }
-
- /**
- * Scans all the properties in the parent Properties object and creates arrays for any array property definitions.
- *
- * <p>Array properties are defined with indexes. For example:
- *
- * <p><code>
- * property.1=one<br/>
- * property.2=two<br/>
- * property.3=three<br/>
- * </code>
- *
- * <p>Note that these properties will be stored as the 'empty string' or "" property array.
- *
- * <p><code>
- * .1=one<br/>
- * 2=two<br/>
- * </code>
- */
- protected void createArrayProperties()
- {
- // Scan through all defined properties.
- for (Object o : keySet())
- {
- String key = (String) o;
- String value = super.getProperty(key);
-
- // Split the property key into everything before the last '.' and after it.
- int lastDotIndex = key.lastIndexOf('.');
- String keyEnding = key.substring(lastDotIndex + 1, key.length());
- String keyStart = key.substring(0, (lastDotIndex == -1) ? 0 : lastDotIndex);
-
- // Check if the property key ends in an integer, in which case it is an array property.
- int index = 0;
-
- try
- {
- index = Integer.parseInt(keyEnding);
- }
- // The ending is not an integer so its not an array.
- catch (NumberFormatException e)
- {
- // Scan the next property.
- continue;
- }
-
- // Check if an array property already exists for this base name and create one if not.
- ArrayList propArray = (ArrayList) arrayProperties.get(keyStart);
-
- if (propArray == null)
- {
- propArray = new ArrayList();
- arrayProperties.put(keyStart, propArray);
- }
-
- // Add the new property value to the array property for the index.
- propArray.set(index, value);
- }
- }
-}
diff --git a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/util/MathUtils.java b/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/util/MathUtils.java
deleted file mode 100644
index 7c803294f4..0000000000
--- a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/util/MathUtils.java
+++ /dev/null
@@ -1,428 +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.junit.extensions.util;
-
-import java.util.ArrayList;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-/**
- * Mathematical support methods for the toolkit. Caculating averages, variances, min/max for test latencies and
- * generating linear/exponential sequences for test size/concurrency ramping up.
- *
- * <p/>The sequence specifications are of the form [lowest(, ...)(, highest)](,sample=s)(,exp), where round brackets
- * enclose optional values. Using this pattern form it is possible to specify a single value, a range of values divided
- * into s samples, a range of values divided into s samples but distributed exponentially, or a fixed set of samples.
- *
- * <p/>The duration arguments are of the form (dD)(hH)(mM)(sS), where round brackets enclose optional values. At least
- * one of the optional values must be present.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Generate a sequene of integers from a sequence specification.
- * <tr><td> Parse an encoded duration into milliseconds.
- * </table>
- *
- * @author Rupert Smith
- */
-public class MathUtils
-{
- /** Used for debugging. */
- // private static final Logger log = Logger.getLogger(MathUtils.class);
-
- /** The sequence defintion matching regular expression. */
- public static final String SEQUENCE_REGEXP = "^(\\[[0-9:]+\\])(:samples=[0-9]+)?(:exp)?$";
-
- /** The regular expression that matches sequence definitions. */
- private static final Pattern SEQUENCE_PATTERN = Pattern.compile(SEQUENCE_REGEXP);
-
- /** The duration definition matching regular expression. */
- public static final String DURATION_REGEXP = "^(\\d+D)?(\\d+H)?(\\d+M)?(\\d+S)?$";
-
- /** The regular expression that matches the duration expression. */
- public static final Pattern DURATION_PATTERN = Pattern.compile(DURATION_REGEXP);
-
- /** For matching name=value pairs. */
- public static final String NAME_VALUE_REGEXP = "^\\w+=\\w+$";
-
- /** For matching name=[value1: value2: ...] variations. */
- public static final String NAME_VALUE_VARIATION_REGEXP = "^\\w+=\\[[\\w:]+\\]$";
-
- /** For matching name=[n: ... :m](:sample=s)(:exp) sequences. */
- public static final String NAME_VALUE_SEQUENCE_REGEXP = "^\\w+=(\\[[0-9:]+\\])(:samples=[0-9]+)?(:exp)?$";
-
- /** The regular expression that matches name=value pairs and variations. */
- public static final Pattern NAME_VALUE_PATTERN =
- Pattern.compile("(" + NAME_VALUE_REGEXP + ")|(" + NAME_VALUE_VARIATION_REGEXP + ")|(" + NAME_VALUE_SEQUENCE_REGEXP
- + ")");
-
- /**
- * Runs a quick test of the sequence generation methods to confirm that they work as expected.
- *
- * @param args The command line parameters.
- */
- public static void main(String[] args)
- {
- // Use the command line parser to evaluate the command line.
- CommandLineParser commandLine =
- new CommandLineParser(
- new String[][]
- {
- { "s", "The sequence definition.", "[m:...:n](:sample=s)(:exp)", "true", MathUtils.SEQUENCE_REGEXP },
- { "d", "The duration definition.", "dDhHmMsS", "false", MathUtils.DURATION_REGEXP }
- });
-
- // Capture the command line arguments or display errors and correct usage and then exit.
- ParsedProperties options = null;
-
- try
- {
- options = new ParsedProperties(commandLine.parseCommandLine(args));
- }
- catch (IllegalArgumentException e)
- {
- System.out.println(commandLine.getErrors());
- System.out.println(commandLine.getUsage());
- System.exit(-1);
- }
-
- // Extract the command line options.
- String sequence = options.getProperty("s");
- String durationString = options.getProperty("d");
-
- System.out.println("Sequence is: " + printArray(parseSequence(sequence)));
-
- if (durationString != null)
- {
- System.out.println("Duration is: " + parseDuration(durationString));
- }
- }
-
- /**
- * Given a start and end and a number of steps this method generates a sequence of evenly spaced integer
- * values, starting at the start (inclusive) and finishing at the end (inclusive) with the specified number
- * of values in the sequence. The sequence returned may contain less than the specified number where the integer
- * range between start and end is too small to contain that many.
- *
- * <p/>As the results are integers, they will not be perfectly evenly spaced but a best-fit.
- *
- * @param start The sequence start.
- * @param end The sequence end.
- * @param steps The number of steps.
- *
- * @return The sequence.
- */
- public static int[] generateSequence(int start, int end, int steps)
- {
- // Check that there are at least two steps.
- if (steps < 2)
- {
- throw new IllegalArgumentException("There must be at least 2 steps.");
- }
-
- ArrayList<Integer> result = new ArrayList<Integer>();
-
- // Calculate the sequence using floating point, then round into the results.
- double fStart = start;
- double fEnd = end;
- double fCurrent = start;
-
- for (int i = 0; i < steps; i++)
- {
- fCurrent = (((fEnd - fStart) / (steps - 1)) * i) + fStart;
-
- roundAndAdd(result, fCurrent);
- }
-
- // Return the results after converting to a primitive array.
- return intListToPrimitiveArray(result);
- }
-
- /**
- * Given a start and end and a number of steps this method generates a sequence of expontentially spaced integer
- * values, starting at the start (inclusive) and finishing at the end (inclusive) with the specified number
- * of values in the sequence. An exponentially spaced sequence is one where the ratio between any two consecutive
- * numbers in the sequence remains constant. The sequence returned may contain less than the specified number where
- * the difference between two consecutive values is too small (this is more likely at the start of the sequence,
- * where the values are closer together).
- *
- * <p/>As the results are integers, they will not be perfectly exponentially spaced but a best-fit.
- *
- * @param start The sequence start.
- * @param end The sequence end.
- * @param steps The number of steps.
- *
- * @return The sequence.
- */
- public static int[] generateExpSequence(int start, int end, int steps)
- {
- // Check that there are at least two steps.
- if (steps < 2)
- {
- throw new IllegalArgumentException("There must be at least 2 steps.");
- }
-
- ArrayList<Integer> result = new ArrayList<Integer>();
-
- // Calculate the sequence using floating point, then round into the results.
- double fStart = start;
- double fEnd = end;
- // float fCurrent = start;
- double diff = fEnd - fStart;
- double factor = java.lang.Math.pow(diff, (1.0f / (steps - 1)));
-
- for (int i = 0; i < steps; i++)
- {
- // This is a cheat to get the end exactly on and lose the accumulated rounding error.
- if (i == (steps - 1))
- {
- result.add(end);
- }
- else
- {
- roundAndAdd(result, fStart - 1.0f + java.lang.Math.pow(factor, i));
- }
- }
-
- // Return the results after converting to a primitive array.
- return intListToPrimitiveArray(result);
- }
-
- /**
- * Parses a string defintion of a sequence into an int array containing the sequence. The definition will conform
- * to the regular expression: "^(\[[0-9,]+\])(,samples=[0-9]+)?(,exp)?$". This splits it into three parts,
- * an array of integers, the optional sample count and the optional exponential flag.
- *
- * @param sequenceDef The sequence definition.
- *
- * @return The sequence as a fully expanded int array.
- */
- public static int[] parseSequence(String sequenceDef)
- {
- // Match the sequence definition against the regular expression for sequences.
- Matcher matcher = SEQUENCE_PATTERN.matcher(sequenceDef);
-
- // Check that the argument is of the right format accepted by this method.
- if (!matcher.matches())
- {
- throw new IllegalArgumentException("The sequence definition is not in the correct format.");
- }
-
- // Get the total number of matching groups to see if either of the optional samples or exponential flag
- // goups were set.
- int numGroups = matcher.groupCount();
-
- // Split the array of integers on commas.
- String intArrayString = matcher.group(1);
-
- String[] intSplits = intArrayString.split("[:\\[\\]]");
-
- int[] sequence = new int[intSplits.length - 1];
-
- for (int i = 1; i < intSplits.length; i++)
- {
- sequence[i - 1] = Integer.parseInt(intSplits[i]);
- }
-
- // Check for the optional samples count.
- int samples = 0;
-
- if ((numGroups > 1) && (matcher.group(2) != null))
- {
- String samplesGroup = matcher.group(2);
-
- String samplesString = samplesGroup.substring(",samples=".length());
- samples = Integer.parseInt(samplesString);
- }
-
- // Check for the optional exponential flag.
- boolean expFlag = false;
-
- if ((numGroups > 2) && (matcher.group(3) != null))
- {
- expFlag = true;
- }
-
- // If there is a sample count and 2 or more sequence values defined, then generate the sequence from the first
- // and last sequence values.
- if ((samples != 0) && (sequence.length >= 2))
- {
- int start = sequence[0];
- int end = sequence[sequence.length - 1];
-
- if (!expFlag)
- {
- sequence = generateSequence(start, end, samples);
- }
- else
- {
- sequence = generateExpSequence(start, end, samples);
- }
- }
-
- return sequence;
- }
-
- /**
- * Parses a duration defined as a string, giving a duration in days, hours, minutes and seconds into a number
- * of milliseconds equal to that duration.
- *
- * @param duration The duration definition string.
- *
- * @return The duration in millliseconds.
- */
- public static long parseDuration(String duration)
- {
- // Match the duration against the regular expression.
- Matcher matcher = DURATION_PATTERN.matcher(duration);
-
- // Check that the argument is of the right format accepted by this method.
- if (!matcher.matches())
- {
- throw new IllegalArgumentException("The duration definition is not in the correct format.");
- }
-
- // This accumulates the duration.
- long result = 0;
-
- int numGroups = matcher.groupCount();
-
- // Extract the days.
- if (numGroups >= 1)
- {
- String daysString = matcher.group(1);
- result +=
- (daysString == null)
- ? 0 : (Long.parseLong(daysString.substring(0, daysString.length() - 1)) * 24 * 60 * 60 * 1000);
- }
-
- // Extract the hours.
- if (numGroups >= 2)
- {
- String hoursString = matcher.group(2);
- result +=
- (hoursString == null) ? 0
- : (Long.parseLong(hoursString.substring(0, hoursString.length() - 1)) * 60 * 60 * 1000);
- }
-
- // Extract the minutes.
- if (numGroups >= 3)
- {
- String minutesString = matcher.group(3);
- result +=
- (minutesString == null)
- ? 0 : (Long.parseLong(minutesString.substring(0, minutesString.length() - 1)) * 60 * 1000);
- }
-
- // Extract the seconds.
- if (numGroups >= 4)
- {
- String secondsString = matcher.group(4);
- result +=
- (secondsString == null) ? 0 : (Long.parseLong(secondsString.substring(0, secondsString.length() - 1)) * 1000);
- }
-
- return result;
- }
-
- /**
- * Pretty prints an array of ints as a string.
- *
- * @param array The array to pretty print.
- *
- * @return The pretty printed string.
- */
- public static String printArray(int[] array)
- {
- String result = "[";
- for (int i = 0; i < array.length; i++)
- {
- result += array[i];
- result += (i < (array.length - 1)) ? ", " : "";
- }
-
- result += "]";
-
- return result;
- }
-
- /**
- * Returns the maximum value in an array of integers.
- *
- * @param values The array to find the amx in.
- *
- * @return The max value.
- */
- public static int maxInArray(int[] values)
- {
- if ((values == null) || (values.length == 0))
- {
- throw new IllegalArgumentException("Cannot find the max of a null or empty array.");
- }
-
- int max = values[0];
-
- for (int value : values)
- {
- max = (max < value) ? value : max;
- }
-
- return max;
- }
-
- /**
- * The #toArray methods of collections cannot be used with primitive arrays. This loops over and array list
- * of Integers and outputs and array of int.
- *
- * @param result The array of Integers to convert.
- *
- * @return An array of int.
- */
- private static int[] intListToPrimitiveArray(ArrayList<Integer> result)
- {
- int[] resultArray = new int[result.size()];
- int index = 0;
- for (int r : result)
- {
- resultArray[index] = result.get(index);
- index++;
- }
-
- return resultArray;
- }
-
- /**
- * Rounds the specified floating point value to the nearest integer and adds it to the specified list of
- * integers, provided it is not already in the list.
- *
- * @param result The list of integers to add to.
- * @param value The new candidate to round and add to the list.
- */
- private static void roundAndAdd(ArrayList<Integer> result, double value)
- {
- int roundedValue = (int) Math.round(value);
-
- if (!result.contains(roundedValue))
- {
- result.add(roundedValue);
- }
- }
-}
diff --git a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/util/ParsedProperties.java b/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/util/ParsedProperties.java
deleted file mode 100644
index 1cc6757675..0000000000
--- a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/util/ParsedProperties.java
+++ /dev/null
@@ -1,390 +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.junit.extensions.util;
-
-import java.util.Properties;
-
-/**
- * ParsedProperties extends the basic Properties class with methods to extract properties, not as strings but as strings
- * parsed into basic types.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * </table>
- *
- * @author Rupert Smith
- */
-public class ParsedProperties extends Properties
-{
- /**
- * Creates an empty ParsedProperties.
- */
- public ParsedProperties()
- {
- super();
- }
-
- /**
- * Creates a ParsedProperties initialized with the specified properties.
- *
- * @param props The properties to initialize this with.
- */
- public ParsedProperties(Properties props)
- {
- super(props);
- }
-
- /**
- * Helper method for setting system properties to defaults when they are not already set.
- *
- * @param propname The name of the system property to set.
- * @param value The value to set it to.
- *
- * @return The value of the property after this method call.
- */
- public static boolean setSysPropertyIfNull(String propname, boolean value)
- {
- return Boolean.parseBoolean(setSysPropertyIfNull(propname, Boolean.toString(value)));
- }
-
- /**
- * Helper method for setting system properties to defaults when they are not already set.
- *
- * @param propname The name of the system property to set.
- * @param value The value to set it to.
- *
- * @return The value of the property after this method call.
- */
- public static short setSysPropertyIfNull(String propname, short value)
- {
- return Short.parseShort(setSysPropertyIfNull(propname, Short.toString(value)));
- }
-
- /**
- * Helper method for setting system properties to defaults when they are not already set.
- *
- * @param propname The name of the system property to set.
- * @param value The value to set it to.
- *
- * @return The value of the property after this method call.
- */
- public static int setSysPropertyIfNull(String propname, int value)
- {
- return Integer.parseInt(setSysPropertyIfNull(propname, Integer.toString(value)));
- }
-
- /**
- * Helper method for setting system properties to defaults when they are not already set.
- *
- * @param propname The name of the system property to set.
- * @param value The value to set it to.
- *
- * @return The value of the property after this method call.
- */
- public static long setSysPropertyIfNull(String propname, long value)
- {
- return Long.parseLong(setSysPropertyIfNull(propname, Long.toString(value)));
- }
-
- /**
- * Helper method for setting system properties to defaults when they are not already set.
- *
- * @param propname The name of the system property to set.
- * @param value The value to set it to.
- *
- * @return The value of the property after this method call.
- */
- public static float setSysPropertyIfNull(String propname, float value)
- {
- return Float.parseFloat(setSysPropertyIfNull(propname, Float.toString(value)));
- }
-
- /**
- * Helper method for setting system properties to defaults when they are not already set.
- *
- * @param propname The name of the system property to set.
- * @param value The value to set it to.
- *
- * @return The value of the property after this method call.
- */
- public static double setSysPropertyIfNull(String propname, double value)
- {
- return Double.parseDouble(setSysPropertyIfNull(propname, Double.toString(value)));
- }
-
- /**
- * Helper method for setting system properties to defaults when they are not already set.
- *
- * @param propname The name of the system property to set.
- * @param value The value to set it to.
- *
- * @return The value of the system property after this method call.
- */
- public static String setSysPropertyIfNull(String propname, String value)
- {
- String property = System.getProperty(propname);
-
- if (property == null)
- {
- System.setProperty(propname, value);
-
- return value;
- }
- else
- {
- return property;
- }
- }
-
- /**
- * Helper method for setting properties to defaults when they are not already set.
- *
- * @param propname The name of the system property to set.
- * @param value The value to set it to.
- *
- * @return The value of the property after this method call.
- */
- public boolean setPropertyIfNull(String propname, boolean value)
- {
- return Boolean.parseBoolean(setPropertyIfNull(propname, Boolean.toString(value)));
- }
-
- /**
- * Helper method for setting properties to defaults when they are not already set.
- *
- * @param propname The name of the system property to set.
- * @param value The value to set it to.
- *
- * @return The value of the property after this method call.
- */
- public short setPropertyIfNull(String propname, short value)
- {
- return Short.parseShort(setPropertyIfNull(propname, Short.toString(value)));
- }
-
- /**
- * Helper method for setting properties to defaults when they are not already set.
- *
- * @param propname The name of the system property to set.
- * @param value The value to set it to.
- *
- * @return The value of the property after this method call.
- */
- public int setPropertyIfNull(String propname, int value)
- {
- return Integer.parseInt(setPropertyIfNull(propname, Integer.toString(value)));
- }
-
- /**
- * Helper method for setting properties to defaults when they are not already set.
- *
- * @param propname The name of the system property to set.
- * @param value The value to set it to.
- *
- * @return The value of the property after this method call.
- */
- public long setPropertyIfNull(String propname, long value)
- {
- return Long.parseLong(setPropertyIfNull(propname, Long.toString(value)));
- }
-
- /**
- * Helper method for setting properties to defaults when they are not already set.
- *
- * @param propname The name of the system property to set.
- * @param value The value to set it to.
- *
- * @return The value of the property after this method call.
- */
- public float setPropertyIfNull(String propname, float value)
- {
- return Float.parseFloat(setPropertyIfNull(propname, Float.toString(value)));
- }
-
- /**
- * Helper method for setting properties to defaults when they are not already set.
- *
- * @param propname The name of the system property to set.
- * @param value The value to set it to.
- *
- * @return The value of the property after this method call.
- */
- public double setPropertyIfNull(String propname, double value)
- {
- return Double.parseDouble(setPropertyIfNull(propname, Double.toString(value)));
- }
-
- /**
- * Helper method for setting properties to defaults when they are not already set.
- *
- * @param propname The name of the system property to set.
- * @param value The value to set it to.
- *
- * @return The value of the property after this method call.
- */
- public String setPropertyIfNull(String propname, String value)
- {
- String property = super.getProperty(propname);
-
- if (property == null)
- {
- super.setProperty(propname, value);
-
- return value;
- }
- else
- {
- return property;
- }
- }
-
- /**
- * Helper method for setting properties.
- *
- * @param propname The name of the system property to set.
- * @param value The value to set it to.
- *
- * @return The value of the property after this method call.
- */
- public boolean setProperty(String propname, boolean value)
- {
- setProperty(propname, Boolean.toString(value));
-
- return value;
- }
-
- /**
- * Helper method for setting properties.
- *
- * @param propname The name of the system property to set.
- * @param value The value to set it to.
- *
- * @return The value of the property after this method call.
- */
- public short setProperty(String propname, short value)
- {
- setProperty(propname, Short.toString(value));
-
- return value;
- }
-
- /**
- * Helper method for setting properties.
- *
- * @param propname The name of the system property to set.
- * @param value The value to set it to.
- *
- * @return The value of the property after this method call.
- */
- public int setProperty(String propname, int value)
- {
- setProperty(propname, Integer.toString(value));
-
- return value;
- }
-
- /**
- * Helper method for setting properties.
- *
- * @param propname The name of the system property to set.
- * @param value The value to set it to.
- *
- * @return The value of the property after this method call.
- */
- public long setProperty(String propname, long value)
- {
- setProperty(propname, Long.toString(value));
-
- return value;
- }
-
- /**
- * Helper method for setting properties.
- *
- * @param propname The name of the system property to set.
- * @param value The value to set it to.
- *
- * @return The value of the property after this method call.
- */
- public float setProperty(String propname, float value)
- {
- setProperty(propname, Float.toString(value));
-
- return value;
- }
-
- /**
- * Helper method for setting properties.
- *
- * @param propname The name of the system property to set.
- * @param value The value to set it to.
- *
- * @return The value of the property after this method call.
- */
- public double setProperty(String propname, double value)
- {
- setProperty(propname, Double.toString(value));
-
- return value;
- }
-
- /**
- * Parses a property as a boolean.
- *
- * @param propName The property.
- *
- * @return The property as a boolean, or false if it does not exist.
- */
- public boolean getPropertyAsBoolean(String propName)
- {
- String prop = getProperty(propName);
-
- return (prop != null) && Boolean.parseBoolean(prop);
- }
-
- /**
- * Parses a property as an integer.
- *
- * @param propName The property.
- *
- * @return The property as a integer, or null if it does not exist.
- */
- public Integer getPropertyAsInteger(String propName)
- {
- String prop = getProperty(propName);
-
- return (prop != null) ? new Integer(prop) : null;
- }
-
- /**
- * Parses a property as a long.
- *
- * @param propName The property.
- *
- * @return The property as a long, or null if it does not exist.
- */
- public Long getPropertyAsLong(String propName)
- {
- String prop = getProperty(propName);
-
- return (prop != null) ? new Long(prop) : null;
- }
-}
diff --git a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/util/SizeOf.java b/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/util/SizeOf.java
deleted file mode 100644
index ecc08770a9..0000000000
--- a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/util/SizeOf.java
+++ /dev/null
@@ -1,94 +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.junit.extensions.util;
-
-/**
- * SizeOf provides a static method that does its best to return an accurate measure of the total amount of memory used by
- * the virtual machine. This is calculated as the total memory available to the VM minus the actual amount used by it.
- * Before this measurement is taken the garbage collector is run many times until the used memory calculation stabilizes.
- * Generally, this trick works quite well to provide an accurate reading, however, it cannot be relied upon to be totally
- * accurate. It is also quite slow.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Calculate total memory used.
- * </table>
- *
- * @author Rupert Smith
- */
-public class SizeOf
-{
- /** Holds a reference to the runtime object. */
- private static final Runtime RUNTIME = Runtime.getRuntime();
-
- /**
- * Makes 4 calls the {@link #runGCTillStable} method.
- */
- public static void runGCTillStableSeveralTimes()
- {
- // It helps to call Runtime.gc() using several method calls.
- for (int r = 0; r < 4; ++r)
- {
- runGCTillStable();
- }
- }
-
- /**
- * Runs the garbage collector until the used memory reading stabilizes. It may run the garbage collector up
- * to 500 times.
- */
- public static void runGCTillStable()
- {
- long usedMem1 = usedMemory(), usedMem2 = Long.MAX_VALUE;
-
- for (int i = 0; (usedMem1 < usedMem2) && (i < 500); ++i)
- {
- RUNTIME.runFinalization();
- RUNTIME.gc();
- Thread.currentThread().yield();
-
- usedMem2 = usedMem1;
- usedMem1 = usedMemory();
- }
- }
-
- /**
- * Runs the garbage collector until the used memory stabilizes and then measures it.
- *
- * @return The amount of memory used by the virtual machine.
- */
- public static long getUsedMemory()
- {
- runGCTillStableSeveralTimes();
-
- return usedMemory();
- }
-
- /**
- * Returns the amount of memory used by subtracting the free memory from the total available memory.
- *
- * @return The amount of memory used.
- */
- private static long usedMemory()
- {
- return RUNTIME.totalMemory() - RUNTIME.freeMemory();
- }
-}
diff --git a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/util/StackQueue.java b/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/util/StackQueue.java
deleted file mode 100644
index acc1e2c218..0000000000
--- a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/util/StackQueue.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.junit.extensions.util;
-
-import java.util.EmptyStackException;
-import java.util.NoSuchElementException;
-import java.util.Queue;
-import java.util.Stack;
-
-/**
- * The Stack class in java.util (most unhelpfully) does not implement the Queue interface. This is an adaption of that
- * class as a queue.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Turn a stack into a queue.
- * </table>
- *
- * @todo Need to override the add method, and iterator and consider other methods too. They work like LIFO but
- * really wany FIFO behaviour accross the whole data structure.
- *
- * @author Rupert Smith
- */
-public class StackQueue<E> extends Stack<E> implements Queue<E>
-{
- /**
- * Retrieves, but does not remove, the head of this queue.
- *
- * @return The element at the top of the stack.
- */
- public E element()
- {
- try
- {
- return super.peek();
- }
- catch (EmptyStackException e)
- {
- NoSuchElementException t = new NoSuchElementException();
- t.initCause(e);
- throw t;
- }
- }
-
- /**
- * Inserts the specified element into this queue, if possible.
- *
- * @param o The data element to push onto the stack.
- *
- * @return True if it was added to the stack, false otherwise (this implementation always returns true).
- */
- public boolean offer(E o)
- {
- push(o);
-
- return true;
- }
-
- /**
- * Retrieves, but does not remove, the head of this queue, returning null if this queue is empty.
- *
- * @return The top element from the stack, or null if the stack is empty.
- */
- public E peek()
- {
- try
- {
- return super.peek();
- }
- catch (EmptyStackException e)
- {
- return null;
- }
- }
-
- /**
- * Retrieves and removes the head of this queue, or null if this queue is empty.
- *
- * @return The top element from the stack, or null if the stack is empty.
- */
- public E poll()
- {
- try
- {
- return super.pop();
- }
- catch (EmptyStackException e)
- {
- return null;
- }
- }
-
- /**
- * Retrieves and removes the head of this queue.
- *
- * @return The top element from the stack, or null if the stack is empty.
- *
- * @throws NoSuchElementException If the stack is empty so no element can be removed from it.
- */
- public E remove()
- {
- try
- {
- return super.pop();
- }
- catch (EmptyStackException e)
- {
- NoSuchElementException t = new NoSuchElementException();
- t.initCause(e);
- throw t;
- }
- }
-}
diff --git a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/util/TestContextProperties.java b/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/util/TestContextProperties.java
deleted file mode 100644
index d402077963..0000000000
--- a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/util/TestContextProperties.java
+++ /dev/null
@@ -1,202 +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.junit.extensions.util;
-
-import java.util.Properties;
-
-/**
- * TestContextProperties is an extension of {@link ParsedProperties} that keeps track of property key/value pairs
- * that are used by tests being run under the {@link org.apache.qpid.junit.extensions.TKTestRunner}. To keep the
- * test runner notified of configurable test parameters, tests should establish their required property values by
- * initiliazing fields or statics or in the constructor, through this class. The tk test runner automatically places
- * any additional properties specified on the command line into the this class, and these are held statically.
- *
- * <p/>Here is an example:
- *
- * <pre>
- * public class MyTestClass extends TestCase {
- * ParsedProperties testProps = TestContextProperties.getInstance();
- * private int testParam = testProps.setPropertyIfNull("testParam", 1);
- * ...
- * </pre>
- *
- * <p/>This has the effect of setting up the field testParam with the default value of 1, unless it is overridden
- * by values passed to the tk test runner. It also notifies the tk test runner of the name and value of the test
- * parameter actually used for the test, so that this can be logged in the test output file.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Log all name/value pairs read or written.
- * </table>
- *
- * @author Rupert Smith
- */
-public class TestContextProperties extends ParsedProperties
-{
- /** Used for debugging. */
- // Logger log = Logger.getLogger(TestContextProperties.class);
-
- /** Holds all properties set or read through this property extension class. */
- private Properties accessedProps = new Properties();
-
- /** The singleton instance of the test context properties. */
- private static TestContextProperties singleton = null;
-
- /**
- * Default constructor that builds a ContextualProperties that uses environment defaults.
- */
- private TestContextProperties()
- {
- super();
- }
-
- /**
- * Gets the singleton instance of the test context properties.
- *
- * @return The singleton instance of the test context properties.
- */
- public static synchronized ParsedProperties getInstance()
- {
- if (singleton == null)
- {
- singleton = new TestContextProperties();
- }
-
- return singleton;
- }
-
- /**
- * Gets the singleton instance of the test context properties, applying a specified set of default properties to
- * it, if they are not already set.
- *
- * @param defaults The defaults to apply for properties not already set.
- *
- * @return The singleton instance of the test context properties.
- */
- public static synchronized ParsedProperties getInstance(Properties defaults)
- {
- ParsedProperties props = getInstance();
-
- for (Object key : defaults.keySet())
- {
- String stringKey = (String) key;
- String value = defaults.getProperty(stringKey);
-
- props.setPropertyIfNull(stringKey, value);
- }
-
- return props;
- }
-
- /*
- * Creates a ContextualProperties that uses environment defaults and is initialized with the specified properties.
- *
- * @param props The properties to initialize this with.
- */
- /*public TestContextProperties(Properties props)
- {
- super();
- }*/
-
- /**
- * Gets all of the properties (with their most recent values) that have been set or read through this class.
- *
- * @return All of the properties accessed through this class.
- */
- public static Properties getAccessedProps()
- {
- return (singleton == null) ? new Properties() : singleton;
- // return accessedProps;
- }
-
- /**
- * Looks up a property value relative to the environment, callers class and method. The default environment will be
- * checked for a matching property if defaults are being used. The property key/value pair is remembered and made
- * available to {@link org.apache.qpid.junit.extensions.TKTestRunner}.
- *
- * @param key The property key.
- *
- * @return The value of this property searching from the most specific definition (environment, class, method, key)
- * to the most general (key only), unless use of default environments is turned off in which case the most general
- * proeprty searched is (environment, key).
- */
- public String getProperty(String key)
- {
- // log.debug("public String getProperty(String key = " + key + "): called");
-
- String value = super.getProperty(key);
-
- if (value != null)
- {
- accessedProps.setProperty(key, value);
- }
-
- // log.debug("value = " + value);
-
- return value;
- }
-
- /**
- * Calls the <tt>Hashtable</tt> method <code>put</code>. Provided for parallelism with the <tt>getProperty</tt>
- * method. Enforces use of strings for property keys and values. The value returned is the result of the
- * <tt>Hashtable</tt> call to <code>put</code>. The property key/value pair is remembered and made
- * available to {@link org.apache.qpid.junit.extensions.TKTestRunner}.
- *
- * @param key The key to be placed into this property list.
- * @param value The value corresponding to <tt>key</tt>.
- *
- * @return The previous value of the specified key in this property list, or <code>null</code> if it did not have one.
- */
- public synchronized Object setProperty(String key, String value)
- {
- // log.debug("public synchronized Object setProperty(String key = " + key + ", String value = " + value + "): called");
-
- Object result = super.setProperty(key, value);
- accessedProps.setProperty(key, value);
-
- return result;
- }
-
- /**
- * Helper method for setting properties to defaults when they are not already set. The property key/value pair is
- * remembered and made available to {@link org.apache.qpid.junit.extensions.TKTestRunner}.
- *
- * @param key The name of the system property to set.
- * @param value The value to set it to.
- *
- * @return The value of the property, which will be the value passed in if it was null, or the existing value otherwise.
- */
- public String setPropertyIfNull(String key, String value)
- {
- // log.debug("public String setPropertyIfNull(String key = " + key + ", String value = " + value + "): called");
-
- String result = super.setPropertyIfNull(key, value);
-
- if (value != null)
- {
- accessedProps.setProperty(key, result);
- }
-
- // log.debug("result = " + result);
-
- return result;
- }
-}
diff --git a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/util/TestUtils.java b/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/util/TestUtils.java
deleted file mode 100644
index 553a41ecae..0000000000
--- a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/util/TestUtils.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.junit.extensions.util;
-
-/**
- * Provides commonly used functions that aid testing.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Provide a short pause.
- * </table>
- *
- * @author Rupert Smith
- */
-public class TestUtils
-{
- /**
- * Injects a short pause. The pause may not complete its full length, if the thread is interrupted when waiting.
- * In most cases, this will not happen and this method is a vry adequate pause implementation, without the
- * need to handle interrupted exceptions.
- *
- * @param millis The length of the pause in milliseconds.
- */
- public static void pause(long millis)
- {
- try
- {
- Thread.sleep(millis);
- }
- catch (InterruptedException e)
- {
- // Clear the flag and ignore.
- Thread.interrupted();
- }
- }
-}
diff --git a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/util/package.html b/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/util/package.html
deleted file mode 100644
index f39b892e2d..0000000000
--- a/java/junit-toolkit/src/main/org/apache/qpid/junit/extensions/util/package.html
+++ /dev/null
@@ -1,27 +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.
-
--->
-
-<html>
-<body>
-Provides some helper classes. ContextualProperties allows a hierarchy of properties to be used in properties file with
-default overrides. SizeOf takes memeory measurements by stabilizing the garbage collector.
-</body>
-</html>
diff --git a/java/lib/backport-util-concurrent-2.2.jar b/java/lib/backport-util-concurrent-2.2.jar
deleted file mode 100644
index 20a16877bd..0000000000
--- a/java/lib/backport-util-concurrent-2.2.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/bnd-0.0.384.jar b/java/lib/bnd-0.0.384.jar
deleted file mode 100644
index fa5e5263f7..0000000000
--- a/java/lib/bnd-0.0.384.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/cobertura/README.txt b/java/lib/cobertura/README.txt
deleted file mode 100644
index 8e4cc09a80..0000000000
--- a/java/lib/cobertura/README.txt
+++ /dev/null
@@ -1,10 +0,0 @@
-Download the cobertura binary from the following location:
-
-http://cobertura.sourceforge.net/download.html
-
-
-Unpack it into the cobertura (this) directory with tar --strip-path 1 -xf.
-This should leave you with cobertura.jar in qpid/java/lib/cobertura.
-
-Run "ant cover-test coverage-report" to generate coverage report.
-
diff --git a/java/lib/com.ibm.icu_3.8.1.v20080530.jar b/java/lib/com.ibm.icu_3.8.1.v20080530.jar
deleted file mode 100644
index 1d8a0a0997..0000000000
--- a/java/lib/com.ibm.icu_3.8.1.v20080530.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/commons-beanutils-core-1.8.0.jar b/java/lib/commons-beanutils-core-1.8.0.jar
deleted file mode 100644
index 87c15f4565..0000000000
--- a/java/lib/commons-beanutils-core-1.8.0.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/commons-cli-1.0.jar b/java/lib/commons-cli-1.0.jar
deleted file mode 100644
index 22a004e14e..0000000000
--- a/java/lib/commons-cli-1.0.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/commons-codec-1.3.jar b/java/lib/commons-codec-1.3.jar
deleted file mode 100644
index 957b6752af..0000000000
--- a/java/lib/commons-codec-1.3.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/commons-collections-3.2.jar b/java/lib/commons-collections-3.2.jar
deleted file mode 100644
index 75580be255..0000000000
--- a/java/lib/commons-collections-3.2.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/commons-configuration-1.6.jar b/java/lib/commons-configuration-1.6.jar
deleted file mode 100644
index 2d4689a1b8..0000000000
--- a/java/lib/commons-configuration-1.6.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/commons-digester-1.8.1.jar b/java/lib/commons-digester-1.8.1.jar
deleted file mode 100644
index 7abda9696a..0000000000
--- a/java/lib/commons-digester-1.8.1.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/commons-lang-2.2.jar b/java/lib/commons-lang-2.2.jar
deleted file mode 100644
index b9105611f3..0000000000
--- a/java/lib/commons-lang-2.2.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/commons-logging-1.0.4.jar b/java/lib/commons-logging-1.0.4.jar
deleted file mode 100644
index b73a80fab6..0000000000
--- a/java/lib/commons-logging-1.0.4.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/derby-10.6.1.0.jar b/java/lib/derby-10.6.1.0.jar
deleted file mode 100644
index 33a84e9dc5..0000000000
--- a/java/lib/derby-10.6.1.0.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/findbugs/README.txt b/java/lib/findbugs/README.txt
deleted file mode 100644
index 56343d7e63..0000000000
--- a/java/lib/findbugs/README.txt
+++ /dev/null
@@ -1,30 +0,0 @@
-Download the FindBugs archive from the following location:
-http://findbugs.sourceforge.net/downloads.html
-
-Unpack the contents of the 'findbugs-<version>/lib' folder within the archive
-to the 'qpid/java/lib/findbugs' (i.e. this) directory. This should leave you
-with contents of 'qpid/java/lib/findbugs' similar to:
-
-annotations.jar
-ant.jar
-asm-3.1.jar
-asm-analysis-3.1.jar
-asm-commons-3.1.jar
-asm-tree-3.1.jar
-asm-util-3.1.jar
-asm-xml-3.1.jar
-bcel.jar
-buggy.icns
-commons-lang-2.4.jar
-dom4j-1.6.1.jar
-findbugs-ant.jar
-findbugs.jar
-jFormatString.jar
-jaxen-1.1.1.jar
-jdepend-2.9.jar
-jsr305.jar
-mysql-connector-java-5.1.7-bin.jar
-
-
-Now simply run "ant findbugs" in qpid/java to generate the report.
-
diff --git a/java/lib/geronimo-jms_1.1_spec-1.0.jar b/java/lib/geronimo-jms_1.1_spec-1.0.jar
deleted file mode 100644
index 42bf403e28..0000000000
--- a/java/lib/geronimo-jms_1.1_spec-1.0.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/ivy/README.txt b/java/lib/ivy/README.txt
deleted file mode 100644
index f8a01f39b4..0000000000
--- a/java/lib/ivy/README.txt
+++ /dev/null
@@ -1,11 +0,0 @@
-Folder used to store Ivy libs for use in publishing Maven artifacts.
-
-Ivy must be downloaded and extracted into this directory if it is not available in the Ant lib dir.
-
-File may be downloaded in 2 ways:
-1. By running the following command from the qpid/java dir:
- ant -buildfile upload.xml download-ivy
-2. Manually download and extract via http://ant.apache.org/ivy.
-
-Note for method 1 you may also have to set proxy server settings in advance, eg:
-export ANT_OPTS="-Dhttp.proxyHost=<hostname> -Dhttp.proxyPort=<port>"
diff --git a/java/lib/javacc.jar b/java/lib/javacc.jar
deleted file mode 100644
index 5506008402..0000000000
--- a/java/lib/javacc.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/jetty-6.1.14.jar b/java/lib/jetty-6.1.14.jar
deleted file mode 100644
index 3e67d1e19e..0000000000
--- a/java/lib/jetty-6.1.14.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/jetty-servlet-tester-6.1.14.jar b/java/lib/jetty-servlet-tester-6.1.14.jar
deleted file mode 100644
index c6d7c66f4a..0000000000
--- a/java/lib/jetty-servlet-tester-6.1.14.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/jetty-util-6.1.14.jar b/java/lib/jetty-util-6.1.14.jar
deleted file mode 100644
index 7acc988655..0000000000
--- a/java/lib/jetty-util-6.1.14.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/junit-3.8.1.jar b/java/lib/junit-3.8.1.jar
deleted file mode 100644
index 674d71e89e..0000000000
--- a/java/lib/junit-3.8.1.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/jython-2.5.0.jar b/java/lib/jython-2.5.0.jar
deleted file mode 100644
index f8fc553ae7..0000000000
--- a/java/lib/jython-2.5.0.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/log4j-1.2.12.jar b/java/lib/log4j-1.2.12.jar
deleted file mode 100644
index 9b5a720088..0000000000
--- a/java/lib/log4j-1.2.12.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/maven-ant-tasks-2.1.1.jar b/java/lib/maven-ant-tasks-2.1.1.jar
deleted file mode 100644
index 7810a541b8..0000000000
--- a/java/lib/maven-ant-tasks-2.1.1.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/mina-core-1.0.1.jar b/java/lib/mina-core-1.0.1.jar
deleted file mode 100755
index f12067aa90..0000000000
--- a/java/lib/mina-core-1.0.1.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/mina-filter-ssl-1.0.1.jar b/java/lib/mina-filter-ssl-1.0.1.jar
deleted file mode 100755
index 53738e6498..0000000000
--- a/java/lib/mina-filter-ssl-1.0.1.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/org.apache.commons.codec_1.3.0.v20080530-1600.jar b/java/lib/org.apache.commons.codec_1.3.0.v20080530-1600.jar
deleted file mode 100644
index d9b4c8ea1f..0000000000
--- a/java/lib/org.apache.commons.codec_1.3.0.v20080530-1600.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/org.apache.felix.framework-2.0.5.jar b/java/lib/org.apache.felix.framework-2.0.5.jar
deleted file mode 100644
index 71e5a84231..0000000000
--- a/java/lib/org.apache.felix.framework-2.0.5.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/org.eclipse.core.commands_3.4.0.I20080509-2000.jar b/java/lib/org.eclipse.core.commands_3.4.0.I20080509-2000.jar
deleted file mode 100644
index 6467d78d66..0000000000
--- a/java/lib/org.eclipse.core.commands_3.4.0.I20080509-2000.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/org.eclipse.core.contenttype_3.3.0.v20080604-1400.jar b/java/lib/org.eclipse.core.contenttype_3.3.0.v20080604-1400.jar
deleted file mode 100644
index 0b6163cf1b..0000000000
--- a/java/lib/org.eclipse.core.contenttype_3.3.0.v20080604-1400.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/org.eclipse.core.databinding_1.1.1.M20080827-0800b.jar b/java/lib/org.eclipse.core.databinding_1.1.1.M20080827-0800b.jar
deleted file mode 100644
index 7f9d1b637e..0000000000
--- a/java/lib/org.eclipse.core.databinding_1.1.1.M20080827-0800b.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/org.eclipse.core.expressions_3.4.0.v20080603-2000.jar b/java/lib/org.eclipse.core.expressions_3.4.0.v20080603-2000.jar
deleted file mode 100644
index 671e92aa4b..0000000000
--- a/java/lib/org.eclipse.core.expressions_3.4.0.v20080603-2000.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/org.eclipse.core.jobs_3.4.0.v20080512.jar b/java/lib/org.eclipse.core.jobs_3.4.0.v20080512.jar
deleted file mode 100644
index 7bdbc00313..0000000000
--- a/java/lib/org.eclipse.core.jobs_3.4.0.v20080512.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/org.eclipse.core.runtime.compatibility.registry_3.2.200.v20080610/META-INF/ECLIPSE.RSA b/java/lib/org.eclipse.core.runtime.compatibility.registry_3.2.200.v20080610/META-INF/ECLIPSE.RSA
deleted file mode 100644
index d694a14d7f..0000000000
--- a/java/lib/org.eclipse.core.runtime.compatibility.registry_3.2.200.v20080610/META-INF/ECLIPSE.RSA
+++ /dev/null
Binary files differ
diff --git a/java/lib/org.eclipse.core.runtime.compatibility.registry_3.2.200.v20080610/META-INF/ECLIPSE.SF b/java/lib/org.eclipse.core.runtime.compatibility.registry_3.2.200.v20080610/META-INF/ECLIPSE.SF
deleted file mode 100644
index 6bf4f8d81a..0000000000
--- a/java/lib/org.eclipse.core.runtime.compatibility.registry_3.2.200.v20080610/META-INF/ECLIPSE.SF
+++ /dev/null
@@ -1,17 +0,0 @@
-Signature-Version: 1.0
-SHA1-Digest-Manifest: lM34M2cYUookZFTsw+CIRRJzG/o=
-Created-By: 1.5.0 (IBM Corporation)
-SHA1-Digest-Manifest-Main-Attributes: XjH6FbEjs0cznPMbHs9K2V7KmP4=
-
-Name: runtime_registry_compatibility.jar
-SHA1-Digest: 3ZA+TQU6TxgVia+krDcqMAAYdpU=
-
-Name: about.html
-SHA1-Digest: M+fykt9heyWoEv1LNiIEeBhi/2Q=
-
-Name: META-INF/eclipse.inf
-SHA1-Digest: SAqY+5ITAL0mkdYeijlSRhyIaZk=
-
-Name: fragment.properties
-SHA1-Digest: Gi/SEQV8Vl9A/8928AtuhnVkrKQ=
-
diff --git a/java/lib/org.eclipse.core.runtime.compatibility.registry_3.2.200.v20080610/META-INF/MANIFEST.MF b/java/lib/org.eclipse.core.runtime.compatibility.registry_3.2.200.v20080610/META-INF/MANIFEST.MF
deleted file mode 100644
index d9a497e8f4..0000000000
--- a/java/lib/org.eclipse.core.runtime.compatibility.registry_3.2.200.v20080610/META-INF/MANIFEST.MF
+++ /dev/null
@@ -1,25 +0,0 @@
-Manifest-Version: 1.0
-Bundle-RequiredExecutionEnvironment: CDC-1.0/Foundation-1.0,J2SE-1.3
-Bundle-SymbolicName: org.eclipse.core.runtime.compatibility.registry
-Bundle-ManifestVersion: 2
-Bundle-Localization: fragment
-Bundle-Name: %fragmentName
-Bundle-Version: 3.2.200.v20080610
-Bundle-ClassPath: runtime_registry_compatibility.jar
-Fragment-Host: org.eclipse.equinox.registry;bundle-version="[3.3.0,3.5
- .0)"
-Eclipse-PatchFragment: true
-Bundle-Vendor: %providerName
-
-Name: runtime_registry_compatibility.jar
-SHA1-Digest: Oxij1RUWY4Q3SjHVBqQuVSFgLxs=
-
-Name: about.html
-SHA1-Digest: ejOZra0kypGLQQ2bJtGTX+LI8tU=
-
-Name: META-INF/eclipse.inf
-SHA1-Digest: KyT9FF7C7t86NoBoa2kZT3ZJBfw=
-
-Name: fragment.properties
-SHA1-Digest: 4yjHkU5Z/6ej6ZFYT+PE9sMOJPY=
-
diff --git a/java/lib/org.eclipse.core.runtime.compatibility.registry_3.2.200.v20080610/META-INF/eclipse.inf b/java/lib/org.eclipse.core.runtime.compatibility.registry_3.2.200.v20080610/META-INF/eclipse.inf
deleted file mode 100644
index 7864d3c4c3..0000000000
--- a/java/lib/org.eclipse.core.runtime.compatibility.registry_3.2.200.v20080610/META-INF/eclipse.inf
+++ /dev/null
@@ -1,3 +0,0 @@
-#Processed using Jarprocessor
-pack200.args = -E4
-pack200.conditioned = true
diff --git a/java/lib/org.eclipse.core.runtime.compatibility.registry_3.2.200.v20080610/about.html b/java/lib/org.eclipse.core.runtime.compatibility.registry_3.2.200.v20080610/about.html
deleted file mode 100644
index 460233046e..0000000000
--- a/java/lib/org.eclipse.core.runtime.compatibility.registry_3.2.200.v20080610/about.html
+++ /dev/null
@@ -1,28 +0,0 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml">
-<head>
-<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
-<title>About</title>
-</head>
-<body lang="EN-US">
-<h2>About This Content</h2>
-
-<p>June 2, 2006</p>
-<h3>License</h3>
-
-<p>The Eclipse Foundation makes available all content in this plug-in (&quot;Content&quot;). Unless otherwise
-indicated below, the Content is provided to you under the terms and conditions of the
-Eclipse Public License Version 1.0 (&quot;EPL&quot;). A copy of the EPL is available
-at <a href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a>.
-For purposes of the EPL, &quot;Program&quot; will mean the Content.</p>
-
-<p>If you did not receive this Content directly from the Eclipse Foundation, the Content is
-being redistributed by another party (&quot;Redistributor&quot;) and different terms and conditions may
-apply to your use of any object code in the Content. Check the Redistributor's license that was
-provided with the Content. If no such license exists, contact the Redistributor. Unless otherwise
-indicated below, the terms and conditions of the EPL still apply to any source code in the Content
-and such source code may be obtained at <a href="http://www.eclipse.org">http://www.eclipse.org</a>.</p>
-
-</body>
-</html> \ No newline at end of file
diff --git a/java/lib/org.eclipse.core.runtime.compatibility.registry_3.2.200.v20080610/fragment.properties b/java/lib/org.eclipse.core.runtime.compatibility.registry_3.2.200.v20080610/fragment.properties
deleted file mode 100644
index e60dbf5c67..0000000000
--- a/java/lib/org.eclipse.core.runtime.compatibility.registry_3.2.200.v20080610/fragment.properties
+++ /dev/null
@@ -1,12 +0,0 @@
-###############################################################################
-# Copyright (c) 2006 IBM Corporation and others.
-# All rights reserved. This program and the accompanying materials
-# are made available under the terms of the Eclipse Public License v1.0
-# which accompanies this distribution, and is available at
-# http://www.eclipse.org/legal/epl-v10.html
-#
-# Contributors:
-# IBM Corporation - initial API and implementation
-###############################################################################
-providerName=Eclipse.org
-fragmentName=Eclipse Registry Compatibility Fragment
diff --git a/java/lib/org.eclipse.core.runtime.compatibility.registry_3.2.200.v20080610/runtime_registry_compatibility.jar b/java/lib/org.eclipse.core.runtime.compatibility.registry_3.2.200.v20080610/runtime_registry_compatibility.jar
deleted file mode 100644
index 3103fb0ce7..0000000000
--- a/java/lib/org.eclipse.core.runtime.compatibility.registry_3.2.200.v20080610/runtime_registry_compatibility.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/org.eclipse.core.runtime_3.4.0.v20080512.jar b/java/lib/org.eclipse.core.runtime_3.4.0.v20080512.jar
deleted file mode 100644
index 366be26fe3..0000000000
--- a/java/lib/org.eclipse.core.runtime_3.4.0.v20080512.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/org.eclipse.equinox.app_1.1.0.v20080421-2006.jar b/java/lib/org.eclipse.equinox.app_1.1.0.v20080421-2006.jar
deleted file mode 100644
index e46c099fe4..0000000000
--- a/java/lib/org.eclipse.equinox.app_1.1.0.v20080421-2006.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/org.eclipse.equinox.common_3.4.0.v20080421-2006.jar b/java/lib/org.eclipse.equinox.common_3.4.0.v20080421-2006.jar
deleted file mode 100644
index c73223995b..0000000000
--- a/java/lib/org.eclipse.equinox.common_3.4.0.v20080421-2006.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/org.eclipse.equinox.launcher.carbon.macosx_1.0.101.R34x_v20080731/META-INF/ECLIPSE.RSA b/java/lib/org.eclipse.equinox.launcher.carbon.macosx_1.0.101.R34x_v20080731/META-INF/ECLIPSE.RSA
deleted file mode 100644
index 29e6f3e7a0..0000000000
--- a/java/lib/org.eclipse.equinox.launcher.carbon.macosx_1.0.101.R34x_v20080731/META-INF/ECLIPSE.RSA
+++ /dev/null
Binary files differ
diff --git a/java/lib/org.eclipse.equinox.launcher.carbon.macosx_1.0.101.R34x_v20080731/META-INF/ECLIPSE.SF b/java/lib/org.eclipse.equinox.launcher.carbon.macosx_1.0.101.R34x_v20080731/META-INF/ECLIPSE.SF
deleted file mode 100644
index 1d2eece149..0000000000
--- a/java/lib/org.eclipse.equinox.launcher.carbon.macosx_1.0.101.R34x_v20080731/META-INF/ECLIPSE.SF
+++ /dev/null
@@ -1,17 +0,0 @@
-Signature-Version: 1.0
-SHA1-Digest-Manifest: FheFhPCFIe9e17dtN19PvFpfHzs=
-Created-By: 1.5.0 (IBM Corporation)
-SHA1-Digest-Manifest-Main-Attributes: X4gDjCpbD8vwxPcCNeLjJjIHBoU=
-
-Name: about.html
-SHA1-Digest: xGcp/Hbq/ywyvVWkPzD/2vkIzdY=
-
-Name: eclipse_1115.so
-SHA1-Digest: ItFKEUKn9bCxLiWwFj8ubKbopDg=
-
-Name: META-INF/eclipse.inf
-SHA1-Digest: SAqY+5ITAL0mkdYeijlSRhyIaZk=
-
-Name: launcher.carbon.macosx.properties
-SHA1-Digest: iJiwtqN46CqxjQPiFqskiJDS2hk=
-
diff --git a/java/lib/org.eclipse.equinox.launcher.carbon.macosx_1.0.101.R34x_v20080731/META-INF/MANIFEST.MF b/java/lib/org.eclipse.equinox.launcher.carbon.macosx_1.0.101.R34x_v20080731/META-INF/MANIFEST.MF
deleted file mode 100644
index f9ef43c43a..0000000000
--- a/java/lib/org.eclipse.equinox.launcher.carbon.macosx_1.0.101.R34x_v20080731/META-INF/MANIFEST.MF
+++ /dev/null
@@ -1,25 +0,0 @@
-Manifest-Version: 1.0
-Bundle-SymbolicName: org.eclipse.equinox.launcher.carbon.macosx;single
- ton:=true
-Bundle-ManifestVersion: 2
-Bundle-Localization: launcher.carbon.macosx
-Bundle-Name: %pluginName
-Eclipse-PlatformFilter: (& (osgi.ws=carbon) (osgi.os=macosx) (|(osgi.a
- rch=x86)(osgi.arch=ppc)) )
-Bundle-Version: 1.0.101.R34x_v20080731
-Fragment-Host: org.eclipse.equinox.launcher;bundle-version="[1.0.0,1.1
- .0)"
-Bundle-Vendor: %providerName
-
-Name: eclipse_1115.so
-SHA1-Digest: RRLhb5Prci79GCZFsylKadyPBvM=
-
-Name: about.html
-SHA1-Digest: a9lDHrGuLPkvHBUhsqWU+V2mhPw=
-
-Name: META-INF/eclipse.inf
-SHA1-Digest: KyT9FF7C7t86NoBoa2kZT3ZJBfw=
-
-Name: launcher.carbon.macosx.properties
-SHA1-Digest: L4VSSU2M0KAWyhCp8QBLMsnC6Jk=
-
diff --git a/java/lib/org.eclipse.equinox.launcher.carbon.macosx_1.0.101.R34x_v20080731/META-INF/eclipse.inf b/java/lib/org.eclipse.equinox.launcher.carbon.macosx_1.0.101.R34x_v20080731/META-INF/eclipse.inf
deleted file mode 100644
index 7864d3c4c3..0000000000
--- a/java/lib/org.eclipse.equinox.launcher.carbon.macosx_1.0.101.R34x_v20080731/META-INF/eclipse.inf
+++ /dev/null
@@ -1,3 +0,0 @@
-#Processed using Jarprocessor
-pack200.args = -E4
-pack200.conditioned = true
diff --git a/java/lib/org.eclipse.equinox.launcher.carbon.macosx_1.0.101.R34x_v20080731/about.html b/java/lib/org.eclipse.equinox.launcher.carbon.macosx_1.0.101.R34x_v20080731/about.html
deleted file mode 100644
index 395df3ba90..0000000000
--- a/java/lib/org.eclipse.equinox.launcher.carbon.macosx_1.0.101.R34x_v20080731/about.html
+++ /dev/null
@@ -1,28 +0,0 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml">
-<head>
-<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
-<title>About</title>
-</head>
-<body lang="EN-US">
-<h2>About This Content</h2>
-
-<p>June 5, 2006</p>
-<h3>License</h3>
-
-<p>The Eclipse Foundation makes available all content in this plug-in (&quot;Content&quot;).
-Unless otherwise indicated below, the Content is provided to you under the terms and conditions of the
-Eclipse Public License Version 1.0 (&quot;EPL&quot;). A copy of the EPL is available
-at <a href="http://www.eclipse.org/org/documents/epl-v10.php">http://www.eclipse.org/legal/epl-v10.html</a>.
-For purposes of the EPL, &quot;Program&quot; will mean the Content.</p>
-
-<p>If you did not receive this Content directly from the Eclipse Foundation, the Content is
-being redistributed by another party (&quot;Redistributor&quot;) and different terms and conditions may
-apply to your use of any object code in the Content. Check the Redistributor&rsquo;s license
-that was provided with the Content. If no such license exists, contact the Redistributor. Unless otherwise
-indicated below, the terms and conditions of the EPL still apply to any source code in the Content
-and such source code may be obtained at <a href="http://www.eclipse.org/">http://www.eclipse.org</a>.</p>
-
-</body>
-</html> \ No newline at end of file
diff --git a/java/lib/org.eclipse.equinox.launcher.carbon.macosx_1.0.101.R34x_v20080731/eclipse_1115.so b/java/lib/org.eclipse.equinox.launcher.carbon.macosx_1.0.101.R34x_v20080731/eclipse_1115.so
deleted file mode 100644
index 17e8230b19..0000000000
--- a/java/lib/org.eclipse.equinox.launcher.carbon.macosx_1.0.101.R34x_v20080731/eclipse_1115.so
+++ /dev/null
Binary files differ
diff --git a/java/lib/org.eclipse.equinox.launcher.carbon.macosx_1.0.101.R34x_v20080731/launcher.carbon.macosx.properties b/java/lib/org.eclipse.equinox.launcher.carbon.macosx_1.0.101.R34x_v20080731/launcher.carbon.macosx.properties
deleted file mode 100644
index 4373d35790..0000000000
--- a/java/lib/org.eclipse.equinox.launcher.carbon.macosx_1.0.101.R34x_v20080731/launcher.carbon.macosx.properties
+++ /dev/null
@@ -1,12 +0,0 @@
-###############################################################################
-# Copyright (c) 2007 IBM Corporation and others.
-# All rights reserved. This program and the accompanying materials
-# are made available under the terms of the Eclipse Public License v1.0
-# which accompanies this distribution, and is available at
-# http://www.eclipse.org/legal/epl-v10.html
-#
-# Contributors:
-# IBM Corporation - initial API and implementation
-###############################################################################
-pluginName = Equinox Launcher MacOSX Fragment
-providerName = Eclipse.org
diff --git a/java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_1.0.101.R34x_v20080805/META-INF/ECLIPSE.RSA b/java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_1.0.101.R34x_v20080805/META-INF/ECLIPSE.RSA
deleted file mode 100644
index 566c0abd11..0000000000
--- a/java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_1.0.101.R34x_v20080805/META-INF/ECLIPSE.RSA
+++ /dev/null
Binary files differ
diff --git a/java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_1.0.101.R34x_v20080805/META-INF/ECLIPSE.SF b/java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_1.0.101.R34x_v20080805/META-INF/ECLIPSE.SF
deleted file mode 100644
index 4122b4ea8f..0000000000
--- a/java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_1.0.101.R34x_v20080805/META-INF/ECLIPSE.SF
+++ /dev/null
@@ -1,17 +0,0 @@
-Signature-Version: 1.0
-SHA1-Digest-Manifest: tswsDz0e+s2SPhfY7LybTLEXoI4=
-Created-By: 1.5.0 (IBM Corporation)
-SHA1-Digest-Manifest-Main-Attributes: Ymnpf9HjgpR8t0MrPx1wLH4tJFQ=
-
-Name: launcher.gtk.linux.x86.properties
-SHA1-Digest: +CJXeQUkWFS+xYpRY6jNNT065mI=
-
-Name: about.html
-SHA1-Digest: xGcp/Hbq/ywyvVWkPzD/2vkIzdY=
-
-Name: eclipse_1115.so
-SHA1-Digest: gvha3rnYpdA1SDXsMMxPKyEB/Xg=
-
-Name: META-INF/eclipse.inf
-SHA1-Digest: SAqY+5ITAL0mkdYeijlSRhyIaZk=
-
diff --git a/java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_1.0.101.R34x_v20080805/META-INF/MANIFEST.MF b/java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_1.0.101.R34x_v20080805/META-INF/MANIFEST.MF
deleted file mode 100644
index d699938858..0000000000
--- a/java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_1.0.101.R34x_v20080805/META-INF/MANIFEST.MF
+++ /dev/null
@@ -1,25 +0,0 @@
-Manifest-Version: 1.0
-Bundle-SymbolicName: org.eclipse.equinox.launcher.gtk.linux.x86;single
- ton:=true
-Bundle-ManifestVersion: 2
-Bundle-Localization: launcher.gtk.linux.x86
-Bundle-Name: %pluginName
-Eclipse-PlatformFilter: (& (osgi.ws=gtk) (osgi.os=linux) (osgi.arch=x8
- 6))
-Bundle-Version: 1.0.101.R34x_v20080805
-Fragment-Host: org.eclipse.equinox.launcher;bundle-version="[1.0.0,1.1
- .0)"
-Bundle-Vendor: %providerName
-
-Name: launcher.gtk.linux.x86.properties
-SHA1-Digest: BSbhScorws9R/DVRUdKNmymMSIU=
-
-Name: eclipse_1115.so
-SHA1-Digest: n3UyHV1KgJ0YuFIDUxPBXj2dxw0=
-
-Name: about.html
-SHA1-Digest: a9lDHrGuLPkvHBUhsqWU+V2mhPw=
-
-Name: META-INF/eclipse.inf
-SHA1-Digest: KyT9FF7C7t86NoBoa2kZT3ZJBfw=
-
diff --git a/java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_1.0.101.R34x_v20080805/META-INF/eclipse.inf b/java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_1.0.101.R34x_v20080805/META-INF/eclipse.inf
deleted file mode 100644
index 7864d3c4c3..0000000000
--- a/java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_1.0.101.R34x_v20080805/META-INF/eclipse.inf
+++ /dev/null
@@ -1,3 +0,0 @@
-#Processed using Jarprocessor
-pack200.args = -E4
-pack200.conditioned = true
diff --git a/java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_1.0.101.R34x_v20080805/about.html b/java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_1.0.101.R34x_v20080805/about.html
deleted file mode 100644
index 395df3ba90..0000000000
--- a/java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_1.0.101.R34x_v20080805/about.html
+++ /dev/null
@@ -1,28 +0,0 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml">
-<head>
-<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
-<title>About</title>
-</head>
-<body lang="EN-US">
-<h2>About This Content</h2>
-
-<p>June 5, 2006</p>
-<h3>License</h3>
-
-<p>The Eclipse Foundation makes available all content in this plug-in (&quot;Content&quot;).
-Unless otherwise indicated below, the Content is provided to you under the terms and conditions of the
-Eclipse Public License Version 1.0 (&quot;EPL&quot;). A copy of the EPL is available
-at <a href="http://www.eclipse.org/org/documents/epl-v10.php">http://www.eclipse.org/legal/epl-v10.html</a>.
-For purposes of the EPL, &quot;Program&quot; will mean the Content.</p>
-
-<p>If you did not receive this Content directly from the Eclipse Foundation, the Content is
-being redistributed by another party (&quot;Redistributor&quot;) and different terms and conditions may
-apply to your use of any object code in the Content. Check the Redistributor&rsquo;s license
-that was provided with the Content. If no such license exists, contact the Redistributor. Unless otherwise
-indicated below, the terms and conditions of the EPL still apply to any source code in the Content
-and such source code may be obtained at <a href="http://www.eclipse.org/">http://www.eclipse.org</a>.</p>
-
-</body>
-</html> \ No newline at end of file
diff --git a/java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_1.0.101.R34x_v20080805/eclipse_1115.so b/java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_1.0.101.R34x_v20080805/eclipse_1115.so
deleted file mode 100644
index 3ec14a5e88..0000000000
--- a/java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_1.0.101.R34x_v20080805/eclipse_1115.so
+++ /dev/null
Binary files differ
diff --git a/java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_1.0.101.R34x_v20080805/launcher.gtk.linux.x86.properties b/java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_1.0.101.R34x_v20080805/launcher.gtk.linux.x86.properties
deleted file mode 100644
index 792485112e..0000000000
--- a/java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_1.0.101.R34x_v20080805/launcher.gtk.linux.x86.properties
+++ /dev/null
@@ -1,12 +0,0 @@
-###############################################################################
-# Copyright (c) 2007 IBM Corporation and others.
-# All rights reserved. This program and the accompanying materials
-# are made available under the terms of the Eclipse Public License v1.0
-# which accompanies this distribution, and is available at
-# http://www.eclipse.org/legal/epl-v10.html
-#
-# Contributors:
-# IBM Corporation - initial API and implementation
-###############################################################################
-pluginName = Equinox Launcher Linux X86 Fragment
-providerName = Eclipse.org
diff --git a/java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.0.101.R34x_v20080731/META-INF/ECLIPSE.RSA b/java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.0.101.R34x_v20080731/META-INF/ECLIPSE.RSA
deleted file mode 100644
index df6b24ad57..0000000000
--- a/java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.0.101.R34x_v20080731/META-INF/ECLIPSE.RSA
+++ /dev/null
Binary files differ
diff --git a/java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.0.101.R34x_v20080731/META-INF/ECLIPSE.SF b/java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.0.101.R34x_v20080731/META-INF/ECLIPSE.SF
deleted file mode 100644
index 4193e97338..0000000000
--- a/java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.0.101.R34x_v20080731/META-INF/ECLIPSE.SF
+++ /dev/null
@@ -1,17 +0,0 @@
-Signature-Version: 1.0
-SHA1-Digest-Manifest: gnfArgp6eM77c1JxQF9X3q9/Hd8=
-Created-By: 1.5.0 (IBM Corporation)
-SHA1-Digest-Manifest-Main-Attributes: hR6QNnvCGlzBxiyTmh4DMZ03Yyg=
-
-Name: about.html
-SHA1-Digest: xGcp/Hbq/ywyvVWkPzD/2vkIzdY=
-
-Name: eclipse_1115.so
-SHA1-Digest: 33jSy/p2jY6bvgg4W0xBlxjxMWA=
-
-Name: META-INF/eclipse.inf
-SHA1-Digest: SAqY+5ITAL0mkdYeijlSRhyIaZk=
-
-Name: launcher.gtk.linux.x86_64.properties
-SHA1-Digest: Q2rsj7VmfkLLH24miqu0v+2sZjE=
-
diff --git a/java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.0.101.R34x_v20080731/META-INF/MANIFEST.MF b/java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.0.101.R34x_v20080731/META-INF/MANIFEST.MF
deleted file mode 100644
index b790c0af9a..0000000000
--- a/java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.0.101.R34x_v20080731/META-INF/MANIFEST.MF
+++ /dev/null
@@ -1,25 +0,0 @@
-Manifest-Version: 1.0
-Bundle-SymbolicName: org.eclipse.equinox.launcher.gtk.linux.x86_64;sin
- gleton:=true
-Bundle-ManifestVersion: 2
-Bundle-Localization: launcher.gtk.linux.x86_64
-Bundle-Name: %pluginName
-Eclipse-PlatformFilter: (& (osgi.ws=gtk) (osgi.os=linux) (osgi.arch=x8
- 6_64))
-Bundle-Version: 1.0.101.R34x_v20080731
-Fragment-Host: org.eclipse.equinox.launcher;bundle-version="[1.0.0,1.1
- .0)"
-Bundle-Vendor: %providerName
-
-Name: eclipse_1115.so
-SHA1-Digest: l0VkVxLXANjcUEWTLRqXKUmIfn8=
-
-Name: about.html
-SHA1-Digest: a9lDHrGuLPkvHBUhsqWU+V2mhPw=
-
-Name: META-INF/eclipse.inf
-SHA1-Digest: KyT9FF7C7t86NoBoa2kZT3ZJBfw=
-
-Name: launcher.gtk.linux.x86_64.properties
-SHA1-Digest: thXaNI0tmsHrCOYNbQBW2zzAh+Q=
-
diff --git a/java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.0.101.R34x_v20080731/META-INF/eclipse.inf b/java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.0.101.R34x_v20080731/META-INF/eclipse.inf
deleted file mode 100644
index 7864d3c4c3..0000000000
--- a/java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.0.101.R34x_v20080731/META-INF/eclipse.inf
+++ /dev/null
@@ -1,3 +0,0 @@
-#Processed using Jarprocessor
-pack200.args = -E4
-pack200.conditioned = true
diff --git a/java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.0.101.R34x_v20080731/about.html b/java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.0.101.R34x_v20080731/about.html
deleted file mode 100644
index 395df3ba90..0000000000
--- a/java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.0.101.R34x_v20080731/about.html
+++ /dev/null
@@ -1,28 +0,0 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml">
-<head>
-<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
-<title>About</title>
-</head>
-<body lang="EN-US">
-<h2>About This Content</h2>
-
-<p>June 5, 2006</p>
-<h3>License</h3>
-
-<p>The Eclipse Foundation makes available all content in this plug-in (&quot;Content&quot;).
-Unless otherwise indicated below, the Content is provided to you under the terms and conditions of the
-Eclipse Public License Version 1.0 (&quot;EPL&quot;). A copy of the EPL is available
-at <a href="http://www.eclipse.org/org/documents/epl-v10.php">http://www.eclipse.org/legal/epl-v10.html</a>.
-For purposes of the EPL, &quot;Program&quot; will mean the Content.</p>
-
-<p>If you did not receive this Content directly from the Eclipse Foundation, the Content is
-being redistributed by another party (&quot;Redistributor&quot;) and different terms and conditions may
-apply to your use of any object code in the Content. Check the Redistributor&rsquo;s license
-that was provided with the Content. If no such license exists, contact the Redistributor. Unless otherwise
-indicated below, the terms and conditions of the EPL still apply to any source code in the Content
-and such source code may be obtained at <a href="http://www.eclipse.org/">http://www.eclipse.org</a>.</p>
-
-</body>
-</html> \ No newline at end of file
diff --git a/java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.0.101.R34x_v20080731/eclipse_1115.so b/java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.0.101.R34x_v20080731/eclipse_1115.so
deleted file mode 100644
index 8bf855533c..0000000000
--- a/java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.0.101.R34x_v20080731/eclipse_1115.so
+++ /dev/null
Binary files differ
diff --git a/java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.0.101.R34x_v20080731/launcher.gtk.linux.x86_64.properties b/java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.0.101.R34x_v20080731/launcher.gtk.linux.x86_64.properties
deleted file mode 100644
index da448aadbb..0000000000
--- a/java/lib/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.0.101.R34x_v20080731/launcher.gtk.linux.x86_64.properties
+++ /dev/null
@@ -1,12 +0,0 @@
-###############################################################################
-# Copyright (c) 2007 IBM Corporation and others.
-# All rights reserved. This program and the accompanying materials
-# are made available under the terms of the Eclipse Public License v1.0
-# which accompanies this distribution, and is available at
-# http://www.eclipse.org/legal/epl-v10.html
-#
-# Contributors:
-# IBM Corporation - initial API and implementation
-###############################################################################
-pluginName = Equinox Launcher Linux X86_64 Fragment
-providerName = Eclipse.org
diff --git a/java/lib/org.eclipse.equinox.launcher.gtk.solaris.sparc_1.0.101.R34x_v20080731/META-INF/ECLIPSE.RSA b/java/lib/org.eclipse.equinox.launcher.gtk.solaris.sparc_1.0.101.R34x_v20080731/META-INF/ECLIPSE.RSA
deleted file mode 100644
index 81599f2e21..0000000000
--- a/java/lib/org.eclipse.equinox.launcher.gtk.solaris.sparc_1.0.101.R34x_v20080731/META-INF/ECLIPSE.RSA
+++ /dev/null
Binary files differ
diff --git a/java/lib/org.eclipse.equinox.launcher.gtk.solaris.sparc_1.0.101.R34x_v20080731/META-INF/ECLIPSE.SF b/java/lib/org.eclipse.equinox.launcher.gtk.solaris.sparc_1.0.101.R34x_v20080731/META-INF/ECLIPSE.SF
deleted file mode 100644
index 20fe507cdf..0000000000
--- a/java/lib/org.eclipse.equinox.launcher.gtk.solaris.sparc_1.0.101.R34x_v20080731/META-INF/ECLIPSE.SF
+++ /dev/null
@@ -1,17 +0,0 @@
-Signature-Version: 1.0
-SHA1-Digest-Manifest: kR1kAxZlcW3W0rm/xjIZED9LrAo=
-Created-By: 1.5.0 (IBM Corporation)
-SHA1-Digest-Manifest-Main-Attributes: pqNWWWTyBz8hsANASpU3hoVl9kc=
-
-Name: about.html
-SHA1-Digest: xGcp/Hbq/ywyvVWkPzD/2vkIzdY=
-
-Name: eclipse_1115.so
-SHA1-Digest: o5PGzpcLRdWF5shzEwmVFCwZrb0=
-
-Name: META-INF/eclipse.inf
-SHA1-Digest: SAqY+5ITAL0mkdYeijlSRhyIaZk=
-
-Name: launcher.gtk.solaris.sparc.properties
-SHA1-Digest: gu+HrnaK+kn508ppLY/iXys12yA=
-
diff --git a/java/lib/org.eclipse.equinox.launcher.gtk.solaris.sparc_1.0.101.R34x_v20080731/META-INF/MANIFEST.MF b/java/lib/org.eclipse.equinox.launcher.gtk.solaris.sparc_1.0.101.R34x_v20080731/META-INF/MANIFEST.MF
deleted file mode 100644
index f81e6141bb..0000000000
--- a/java/lib/org.eclipse.equinox.launcher.gtk.solaris.sparc_1.0.101.R34x_v20080731/META-INF/MANIFEST.MF
+++ /dev/null
@@ -1,25 +0,0 @@
-Manifest-Version: 1.0
-Bundle-SymbolicName: org.eclipse.equinox.launcher.gtk.solaris.sparc;si
- ngleton:=true
-Bundle-ManifestVersion: 2
-Bundle-Localization: launcher.gtk.solaris.sparc
-Bundle-Name: %pluginName
-Eclipse-PlatformFilter: (& (osgi.ws=gtk) (osgi.os=solaris) (osgi.arch=
- sparc))
-Bundle-Version: 1.0.101.R34x_v20080731
-Fragment-Host: org.eclipse.equinox.launcher;bundle-version="[1.0.0,1.1
- .0)"
-Bundle-Vendor: %providerName
-
-Name: eclipse_1115.so
-SHA1-Digest: 5km5rPngvbWH3aWIYrl+xMejhCE=
-
-Name: about.html
-SHA1-Digest: a9lDHrGuLPkvHBUhsqWU+V2mhPw=
-
-Name: META-INF/eclipse.inf
-SHA1-Digest: KyT9FF7C7t86NoBoa2kZT3ZJBfw=
-
-Name: launcher.gtk.solaris.sparc.properties
-SHA1-Digest: B/N7qN8v4Os5flFl4mE2UaqnMZs=
-
diff --git a/java/lib/org.eclipse.equinox.launcher.gtk.solaris.sparc_1.0.101.R34x_v20080731/META-INF/eclipse.inf b/java/lib/org.eclipse.equinox.launcher.gtk.solaris.sparc_1.0.101.R34x_v20080731/META-INF/eclipse.inf
deleted file mode 100644
index 7864d3c4c3..0000000000
--- a/java/lib/org.eclipse.equinox.launcher.gtk.solaris.sparc_1.0.101.R34x_v20080731/META-INF/eclipse.inf
+++ /dev/null
@@ -1,3 +0,0 @@
-#Processed using Jarprocessor
-pack200.args = -E4
-pack200.conditioned = true
diff --git a/java/lib/org.eclipse.equinox.launcher.gtk.solaris.sparc_1.0.101.R34x_v20080731/about.html b/java/lib/org.eclipse.equinox.launcher.gtk.solaris.sparc_1.0.101.R34x_v20080731/about.html
deleted file mode 100644
index 395df3ba90..0000000000
--- a/java/lib/org.eclipse.equinox.launcher.gtk.solaris.sparc_1.0.101.R34x_v20080731/about.html
+++ /dev/null
@@ -1,28 +0,0 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml">
-<head>
-<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
-<title>About</title>
-</head>
-<body lang="EN-US">
-<h2>About This Content</h2>
-
-<p>June 5, 2006</p>
-<h3>License</h3>
-
-<p>The Eclipse Foundation makes available all content in this plug-in (&quot;Content&quot;).
-Unless otherwise indicated below, the Content is provided to you under the terms and conditions of the
-Eclipse Public License Version 1.0 (&quot;EPL&quot;). A copy of the EPL is available
-at <a href="http://www.eclipse.org/org/documents/epl-v10.php">http://www.eclipse.org/legal/epl-v10.html</a>.
-For purposes of the EPL, &quot;Program&quot; will mean the Content.</p>
-
-<p>If you did not receive this Content directly from the Eclipse Foundation, the Content is
-being redistributed by another party (&quot;Redistributor&quot;) and different terms and conditions may
-apply to your use of any object code in the Content. Check the Redistributor&rsquo;s license
-that was provided with the Content. If no such license exists, contact the Redistributor. Unless otherwise
-indicated below, the terms and conditions of the EPL still apply to any source code in the Content
-and such source code may be obtained at <a href="http://www.eclipse.org/">http://www.eclipse.org</a>.</p>
-
-</body>
-</html> \ No newline at end of file
diff --git a/java/lib/org.eclipse.equinox.launcher.gtk.solaris.sparc_1.0.101.R34x_v20080731/eclipse_1115.so b/java/lib/org.eclipse.equinox.launcher.gtk.solaris.sparc_1.0.101.R34x_v20080731/eclipse_1115.so
deleted file mode 100644
index 3d8beb88dd..0000000000
--- a/java/lib/org.eclipse.equinox.launcher.gtk.solaris.sparc_1.0.101.R34x_v20080731/eclipse_1115.so
+++ /dev/null
Binary files differ
diff --git a/java/lib/org.eclipse.equinox.launcher.gtk.solaris.sparc_1.0.101.R34x_v20080731/launcher.gtk.solaris.sparc.properties b/java/lib/org.eclipse.equinox.launcher.gtk.solaris.sparc_1.0.101.R34x_v20080731/launcher.gtk.solaris.sparc.properties
deleted file mode 100644
index c3f2ae186e..0000000000
--- a/java/lib/org.eclipse.equinox.launcher.gtk.solaris.sparc_1.0.101.R34x_v20080731/launcher.gtk.solaris.sparc.properties
+++ /dev/null
@@ -1,12 +0,0 @@
-###############################################################################
-# Copyright (c) 2007 IBM Corporation and others.
-# All rights reserved. This program and the accompanying materials
-# are made available under the terms of the Eclipse Public License v1.0
-# which accompanies this distribution, and is available at
-# http://www.eclipse.org/legal/epl-v10.html
-#
-# Contributors:
-# IBM Corporation - initial API and implementation
-###############################################################################
-pluginName = Equinox Launcher Sparc Fragment
-providerName = Eclipse.org
diff --git a/java/lib/org.eclipse.equinox.launcher.win32.win32.x86_1.0.101.R34x_v20080731/META-INF/ECLIPSE.RSA b/java/lib/org.eclipse.equinox.launcher.win32.win32.x86_1.0.101.R34x_v20080731/META-INF/ECLIPSE.RSA
deleted file mode 100644
index e2350f7b3d..0000000000
--- a/java/lib/org.eclipse.equinox.launcher.win32.win32.x86_1.0.101.R34x_v20080731/META-INF/ECLIPSE.RSA
+++ /dev/null
Binary files differ
diff --git a/java/lib/org.eclipse.equinox.launcher.win32.win32.x86_1.0.101.R34x_v20080731/META-INF/ECLIPSE.SF b/java/lib/org.eclipse.equinox.launcher.win32.win32.x86_1.0.101.R34x_v20080731/META-INF/ECLIPSE.SF
deleted file mode 100644
index a4cc0ac995..0000000000
--- a/java/lib/org.eclipse.equinox.launcher.win32.win32.x86_1.0.101.R34x_v20080731/META-INF/ECLIPSE.SF
+++ /dev/null
@@ -1,17 +0,0 @@
-Signature-Version: 1.0
-SHA1-Digest-Manifest: oXE8Y8m0B4hXXkniJ3e42s+zWZA=
-Created-By: 1.5.0 (IBM Corporation)
-SHA1-Digest-Manifest-Main-Attributes: D+OZA9EIs+7l5qfZkdxKrzNalvU=
-
-Name: about.html
-SHA1-Digest: xGcp/Hbq/ywyvVWkPzD/2vkIzdY=
-
-Name: launcher.win32.win32.x86.properties
-SHA1-Digest: TMYbn4sXlC4uxONCDt2S0kP1hTY=
-
-Name: META-INF/eclipse.inf
-SHA1-Digest: SAqY+5ITAL0mkdYeijlSRhyIaZk=
-
-Name: eclipse_1115.dll
-SHA1-Digest: ishZ405IXeNkJcKK6X6ZCmhtZOk=
-
diff --git a/java/lib/org.eclipse.equinox.launcher.win32.win32.x86_1.0.101.R34x_v20080731/META-INF/MANIFEST.MF b/java/lib/org.eclipse.equinox.launcher.win32.win32.x86_1.0.101.R34x_v20080731/META-INF/MANIFEST.MF
deleted file mode 100644
index 6acfe13c74..0000000000
--- a/java/lib/org.eclipse.equinox.launcher.win32.win32.x86_1.0.101.R34x_v20080731/META-INF/MANIFEST.MF
+++ /dev/null
@@ -1,25 +0,0 @@
-Manifest-Version: 1.0
-Bundle-SymbolicName: org.eclipse.equinox.launcher.win32.win32.x86; sin
- gleton:=true
-Bundle-ManifestVersion: 2
-Bundle-Localization: launcher.win32.win32.x86
-Bundle-Name: %pluginName
-Eclipse-PlatformFilter: (& (osgi.ws=win32) (osgi.os=win32) (osgi.arch=
- x86))
-Bundle-Version: 1.0.101.R34x_v20080731
-Fragment-Host: org.eclipse.equinox.launcher;bundle-version="[1.0.0,1.1
- .0)"
-Bundle-Vendor: %providerName
-
-Name: about.html
-SHA1-Digest: a9lDHrGuLPkvHBUhsqWU+V2mhPw=
-
-Name: META-INF/eclipse.inf
-SHA1-Digest: KyT9FF7C7t86NoBoa2kZT3ZJBfw=
-
-Name: launcher.win32.win32.x86.properties
-SHA1-Digest: rhstucCaFV5tj2GARC/9A5zdmB4=
-
-Name: eclipse_1115.dll
-SHA1-Digest: 6f1Zg9WvwnS5OsA5EB8tWKy1480=
-
diff --git a/java/lib/org.eclipse.equinox.launcher.win32.win32.x86_1.0.101.R34x_v20080731/META-INF/eclipse.inf b/java/lib/org.eclipse.equinox.launcher.win32.win32.x86_1.0.101.R34x_v20080731/META-INF/eclipse.inf
deleted file mode 100644
index 7864d3c4c3..0000000000
--- a/java/lib/org.eclipse.equinox.launcher.win32.win32.x86_1.0.101.R34x_v20080731/META-INF/eclipse.inf
+++ /dev/null
@@ -1,3 +0,0 @@
-#Processed using Jarprocessor
-pack200.args = -E4
-pack200.conditioned = true
diff --git a/java/lib/org.eclipse.equinox.launcher.win32.win32.x86_1.0.101.R34x_v20080731/about.html b/java/lib/org.eclipse.equinox.launcher.win32.win32.x86_1.0.101.R34x_v20080731/about.html
deleted file mode 100644
index 395df3ba90..0000000000
--- a/java/lib/org.eclipse.equinox.launcher.win32.win32.x86_1.0.101.R34x_v20080731/about.html
+++ /dev/null
@@ -1,28 +0,0 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml">
-<head>
-<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
-<title>About</title>
-</head>
-<body lang="EN-US">
-<h2>About This Content</h2>
-
-<p>June 5, 2006</p>
-<h3>License</h3>
-
-<p>The Eclipse Foundation makes available all content in this plug-in (&quot;Content&quot;).
-Unless otherwise indicated below, the Content is provided to you under the terms and conditions of the
-Eclipse Public License Version 1.0 (&quot;EPL&quot;). A copy of the EPL is available
-at <a href="http://www.eclipse.org/org/documents/epl-v10.php">http://www.eclipse.org/legal/epl-v10.html</a>.
-For purposes of the EPL, &quot;Program&quot; will mean the Content.</p>
-
-<p>If you did not receive this Content directly from the Eclipse Foundation, the Content is
-being redistributed by another party (&quot;Redistributor&quot;) and different terms and conditions may
-apply to your use of any object code in the Content. Check the Redistributor&rsquo;s license
-that was provided with the Content. If no such license exists, contact the Redistributor. Unless otherwise
-indicated below, the terms and conditions of the EPL still apply to any source code in the Content
-and such source code may be obtained at <a href="http://www.eclipse.org/">http://www.eclipse.org</a>.</p>
-
-</body>
-</html> \ No newline at end of file
diff --git a/java/lib/org.eclipse.equinox.launcher.win32.win32.x86_1.0.101.R34x_v20080731/eclipse_1115.dll b/java/lib/org.eclipse.equinox.launcher.win32.win32.x86_1.0.101.R34x_v20080731/eclipse_1115.dll
deleted file mode 100644
index 5e438cf505..0000000000
--- a/java/lib/org.eclipse.equinox.launcher.win32.win32.x86_1.0.101.R34x_v20080731/eclipse_1115.dll
+++ /dev/null
Binary files differ
diff --git a/java/lib/org.eclipse.equinox.launcher.win32.win32.x86_1.0.101.R34x_v20080731/launcher.win32.win32.x86.properties b/java/lib/org.eclipse.equinox.launcher.win32.win32.x86_1.0.101.R34x_v20080731/launcher.win32.win32.x86.properties
deleted file mode 100644
index e8f40bca50..0000000000
--- a/java/lib/org.eclipse.equinox.launcher.win32.win32.x86_1.0.101.R34x_v20080731/launcher.win32.win32.x86.properties
+++ /dev/null
@@ -1,12 +0,0 @@
-###############################################################################
-# Copyright (c) 2007 IBM Corporation and others.
-# All rights reserved. This program and the accompanying materials
-# are made available under the terms of the Eclipse Public License v1.0
-# which accompanies this distribution, and is available at
-# http://www.eclipse.org/legal/epl-v10.html
-#
-# Contributors:
-# IBM Corporation - initial API and implementation
-###############################################################################
-pluginName = Equinox Launcher Win32 X86 Fragment
-providerName = Eclipse.org
diff --git a/java/lib/org.eclipse.equinox.launcher_1.0.101.R34x_v20080819.jar b/java/lib/org.eclipse.equinox.launcher_1.0.101.R34x_v20080819.jar
deleted file mode 100644
index 21cc2a6a07..0000000000
--- a/java/lib/org.eclipse.equinox.launcher_1.0.101.R34x_v20080819.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/org.eclipse.equinox.preferences_3.2.201.R34x_v20080709.jar b/java/lib/org.eclipse.equinox.preferences_3.2.201.R34x_v20080709.jar
deleted file mode 100644
index 0efcea4022..0000000000
--- a/java/lib/org.eclipse.equinox.preferences_3.2.201.R34x_v20080709.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/org.eclipse.equinox.registry_3.4.0.v20080516-0950.jar b/java/lib/org.eclipse.equinox.registry_3.4.0.v20080516-0950.jar
deleted file mode 100644
index ddc97ffe7c..0000000000
--- a/java/lib/org.eclipse.equinox.registry_3.4.0.v20080516-0950.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/org.eclipse.help_3.3.101.v20080702_34x.jar b/java/lib/org.eclipse.help_3.3.101.v20080702_34x.jar
deleted file mode 100644
index 8bb2b74a73..0000000000
--- a/java/lib/org.eclipse.help_3.3.101.v20080702_34x.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/org.eclipse.jface.databinding_1.2.1.M20080827-0800a.jar b/java/lib/org.eclipse.jface.databinding_1.2.1.M20080827-0800a.jar
deleted file mode 100644
index b61037ef9f..0000000000
--- a/java/lib/org.eclipse.jface.databinding_1.2.1.M20080827-0800a.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/org.eclipse.jface_3.4.1.M20080827-2000.jar b/java/lib/org.eclipse.jface_3.4.1.M20080827-2000.jar
deleted file mode 100644
index ad1c58f0d0..0000000000
--- a/java/lib/org.eclipse.jface_3.4.1.M20080827-2000.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/org.eclipse.osgi_3.4.2.R34x_v20080826-1230.jar b/java/lib/org.eclipse.osgi_3.4.2.R34x_v20080826-1230.jar
deleted file mode 100644
index 673f3f5932..0000000000
--- a/java/lib/org.eclipse.osgi_3.4.2.R34x_v20080826-1230.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/org.eclipse.swt.carbon.macosx_3.4.1.v3449c.jar b/java/lib/org.eclipse.swt.carbon.macosx_3.4.1.v3449c.jar
deleted file mode 100644
index d64249df6a..0000000000
--- a/java/lib/org.eclipse.swt.carbon.macosx_3.4.1.v3449c.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/org.eclipse.swt.gtk.linux.x86_3.4.1.v3449c.jar b/java/lib/org.eclipse.swt.gtk.linux.x86_3.4.1.v3449c.jar
deleted file mode 100644
index cda22da341..0000000000
--- a/java/lib/org.eclipse.swt.gtk.linux.x86_3.4.1.v3449c.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/org.eclipse.swt.gtk.linux.x86_64_3.4.1.v3449c.jar b/java/lib/org.eclipse.swt.gtk.linux.x86_64_3.4.1.v3449c.jar
deleted file mode 100644
index 95909028d4..0000000000
--- a/java/lib/org.eclipse.swt.gtk.linux.x86_64_3.4.1.v3449c.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/org.eclipse.swt.gtk.solaris.sparc_3.4.1.v3449c.jar b/java/lib/org.eclipse.swt.gtk.solaris.sparc_3.4.1.v3449c.jar
deleted file mode 100644
index d7143505a4..0000000000
--- a/java/lib/org.eclipse.swt.gtk.solaris.sparc_3.4.1.v3449c.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/org.eclipse.swt.win32.win32.x86_3.4.1.v3449c.jar b/java/lib/org.eclipse.swt.win32.win32.x86_3.4.1.v3449c.jar
deleted file mode 100644
index 5c261c8411..0000000000
--- a/java/lib/org.eclipse.swt.win32.win32.x86_3.4.1.v3449c.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/org.eclipse.swt_3.4.1.v3449c.jar b/java/lib/org.eclipse.swt_3.4.1.v3449c.jar
deleted file mode 100644
index 606abc5a3b..0000000000
--- a/java/lib/org.eclipse.swt_3.4.1.v3449c.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/org.eclipse.ui.forms_3.3.101.v20080708_34x.jar b/java/lib/org.eclipse.ui.forms_3.3.101.v20080708_34x.jar
deleted file mode 100644
index a458fcb058..0000000000
--- a/java/lib/org.eclipse.ui.forms_3.3.101.v20080708_34x.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/org.eclipse.ui.workbench_3.4.1.M20080827-0800a.jar b/java/lib/org.eclipse.ui.workbench_3.4.1.M20080827-0800a.jar
deleted file mode 100644
index 3e151c8122..0000000000
--- a/java/lib/org.eclipse.ui.workbench_3.4.1.M20080827-0800a.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/org.eclipse.ui_3.4.1.M20080910-0800.jar b/java/lib/org.eclipse.ui_3.4.1.M20080910-0800.jar
deleted file mode 100644
index c7a8cf4256..0000000000
--- a/java/lib/org.eclipse.ui_3.4.1.M20080910-0800.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/poms/backport-util-concurrent-2.2.xml b/java/lib/poms/backport-util-concurrent-2.2.xml
deleted file mode 100644
index 6df4cfca40..0000000000
--- a/java/lib/poms/backport-util-concurrent-2.2.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.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.
--->
-<dep>
- <groupId>backport-util-concurrent</groupId>
- <artifactId>backport-util-concurrent</artifactId>
- <version>2.2</version>
-</dep>
diff --git a/java/lib/poms/commons-beanutils-core-1.8.0.xml b/java/lib/poms/commons-beanutils-core-1.8.0.xml
deleted file mode 100644
index 612b45e1a6..0000000000
--- a/java/lib/poms/commons-beanutils-core-1.8.0.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.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.
--->
-<dep>
- <groupId>commons-beanutils</groupId>
- <artifactId>commons-beanutils-core</artifactId>
- <version>1.8.0</version>
-</dep>
diff --git a/java/lib/poms/commons-cli-1.0.xml b/java/lib/poms/commons-cli-1.0.xml
deleted file mode 100644
index 77b47f63f1..0000000000
--- a/java/lib/poms/commons-cli-1.0.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.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.
--->
-<dep>
- <groupId>commons-cli</groupId>
- <artifactId>commons-cli</artifactId>
- <version>1.0</version>
-</dep>
diff --git a/java/lib/poms/commons-codec-1.3.xml b/java/lib/poms/commons-codec-1.3.xml
deleted file mode 100644
index 772ff6ab71..0000000000
--- a/java/lib/poms/commons-codec-1.3.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.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.
--->
-<dep>
- <groupId>commons-codec</groupId>
- <artifactId>commons-codec</artifactId>
- <version>1.3</version>
-</dep>
diff --git a/java/lib/poms/commons-collections-3.2.xml b/java/lib/poms/commons-collections-3.2.xml
deleted file mode 100644
index 3a07dc4a9d..0000000000
--- a/java/lib/poms/commons-collections-3.2.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.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.
--->
-<dep>
- <groupId>commons-collections</groupId>
- <artifactId>commons-collections</artifactId>
- <version>3.2</version>
-</dep>
diff --git a/java/lib/poms/commons-configuration-1.6.xml b/java/lib/poms/commons-configuration-1.6.xml
deleted file mode 100644
index 523310f10a..0000000000
--- a/java/lib/poms/commons-configuration-1.6.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.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.
--->
-<dep>
- <groupId>commons-configuration</groupId>
- <artifactId>commons-configuration</artifactId>
- <version>1.6</version>
-</dep>
diff --git a/java/lib/poms/commons-digester-1.8.1.xml b/java/lib/poms/commons-digester-1.8.1.xml
deleted file mode 100644
index 1edee7b5f0..0000000000
--- a/java/lib/poms/commons-digester-1.8.1.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.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.
--->
-<dep>
- <groupId>commons-digester</groupId>
- <artifactId>commons-digester</artifactId>
- <version>1.8.1</version>
-</dep>
diff --git a/java/lib/poms/commons-lang-2.2.xml b/java/lib/poms/commons-lang-2.2.xml
deleted file mode 100644
index b0bef7ca04..0000000000
--- a/java/lib/poms/commons-lang-2.2.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.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.
--->
-<dep>
- <groupId>commons-lang</groupId>
- <artifactId>commons-lang</artifactId>
- <version>2.2</version>
-</dep>
diff --git a/java/lib/poms/commons-logging-1.0.4.xml b/java/lib/poms/commons-logging-1.0.4.xml
deleted file mode 100644
index c85d0f7b29..0000000000
--- a/java/lib/poms/commons-logging-1.0.4.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.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.
--->
-<dep>
- <groupId>commons-logging</groupId>
- <artifactId>commons-logging</artifactId>
- <version>1.0.4</version>
-</dep>
diff --git a/java/lib/poms/commons-pool-1.4.xml b/java/lib/poms/commons-pool-1.4.xml
deleted file mode 100644
index 21a18596b9..0000000000
--- a/java/lib/poms/commons-pool-1.4.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.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.
--->
-<dep>
- <groupId>commons-pool</groupId>
- <artifactId>commons-pool</artifactId>
- <version>1.4</version>
-</dep>
diff --git a/java/lib/poms/derby-10.6.1.0.xml b/java/lib/poms/derby-10.6.1.0.xml
deleted file mode 100644
index de6a4d79f3..0000000000
--- a/java/lib/poms/derby-10.6.1.0.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.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.
--->
-<dep>
- <groupId>org.apache.derby</groupId>
- <artifactId>derby</artifactId>
- <version>10.6.1.0</version>
-</dep>
diff --git a/java/lib/poms/geronimo-jms_1.1_spec-1.0.xml b/java/lib/poms/geronimo-jms_1.1_spec-1.0.xml
deleted file mode 100644
index 0fe38d5477..0000000000
--- a/java/lib/poms/geronimo-jms_1.1_spec-1.0.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.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.
--->
-<dep>
- <groupId>org.apache.geronimo.specs</groupId>
- <artifactId>geronimo-jms_1.1_spec</artifactId>
- <version>1.0</version>
-</dep>
diff --git a/java/lib/poms/junit-3.8.1.xml b/java/lib/poms/junit-3.8.1.xml
deleted file mode 100644
index 0462e9c0d2..0000000000
--- a/java/lib/poms/junit-3.8.1.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.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.
--->
-<dep>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>3.8.1</version>
-</dep>
diff --git a/java/lib/poms/log4j-1.2.12.xml b/java/lib/poms/log4j-1.2.12.xml
deleted file mode 100644
index 87331f4acc..0000000000
--- a/java/lib/poms/log4j-1.2.12.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.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.
--->
-<dep>
- <groupId>log4j</groupId>
- <artifactId>log4j</artifactId>
- <version>1.2.12</version>
-</dep>
diff --git a/java/lib/poms/mina-core-1.0.1.xml b/java/lib/poms/mina-core-1.0.1.xml
deleted file mode 100644
index 87fb96999f..0000000000
--- a/java/lib/poms/mina-core-1.0.1.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.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.
--->
-<dep>
- <groupId>org.apache.mina</groupId>
- <artifactId>mina-core</artifactId>
- <version>1.0.1</version>
-</dep>
diff --git a/java/lib/poms/mina-filter-ssl-1.0.1.xml b/java/lib/poms/mina-filter-ssl-1.0.1.xml
deleted file mode 100644
index ae41d7ed63..0000000000
--- a/java/lib/poms/mina-filter-ssl-1.0.1.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.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.
--->
-<dep>
- <groupId>org.apache.mina</groupId>
- <artifactId>mina-filter-ssl</artifactId>
- <version>1.0.1</version>
-</dep>
diff --git a/java/lib/poms/org.apache.felix.framework-2.0.5.xml b/java/lib/poms/org.apache.felix.framework-2.0.5.xml
deleted file mode 100644
index cef17fe589..0000000000
--- a/java/lib/poms/org.apache.felix.framework-2.0.5.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.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.
--->
-<dep>
- <groupId>org.apache.felix</groupId>
- <artifactId>org.apache.felix.framework</artifactId>
- <version>2.0.5</version>
-</dep>
diff --git a/java/lib/poms/org.osgi.core-1.0.0.xml b/java/lib/poms/org.osgi.core-1.0.0.xml
deleted file mode 100644
index 833cc91729..0000000000
--- a/java/lib/poms/org.osgi.core-1.0.0.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.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.
--->
-<dep>
- <groupId>org.apache.felix</groupId>
- <artifactId>org.osgi.core</artifactId>
- <version>1.0.0</version>
-</dep>
diff --git a/java/lib/poms/slf4j-api-1.6.1.xml b/java/lib/poms/slf4j-api-1.6.1.xml
deleted file mode 100644
index e3f989bd4e..0000000000
--- a/java/lib/poms/slf4j-api-1.6.1.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.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.
--->
-<dep>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
- <version>1.6.1</version>
-</dep>
diff --git a/java/lib/poms/slf4j-log4j12-1.6.1.xml b/java/lib/poms/slf4j-log4j12-1.6.1.xml
deleted file mode 100644
index 482bbec894..0000000000
--- a/java/lib/poms/slf4j-log4j12-1.6.1.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.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.
--->
-<dep>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-log4j12</artifactId>
- <version>1.6.1</version>
-</dep>
diff --git a/java/lib/poms/xalan-2.7.0.xml b/java/lib/poms/xalan-2.7.0.xml
deleted file mode 100644
index 73ea2df7e2..0000000000
--- a/java/lib/poms/xalan-2.7.0.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.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.
--->
-<dep>
- <groupId>xalan</groupId>
- <artifactId>xalan</artifactId>
- <version>2.7.0</version>
-</dep>
diff --git a/java/lib/servlet-api.jar b/java/lib/servlet-api.jar
deleted file mode 100644
index e3b61e0079..0000000000
--- a/java/lib/servlet-api.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/slf4j-api-1.6.1.jar b/java/lib/slf4j-api-1.6.1.jar
deleted file mode 100644
index 42e0ad0de7..0000000000
--- a/java/lib/slf4j-api-1.6.1.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/slf4j-log4j12-1.6.1.jar b/java/lib/slf4j-log4j12-1.6.1.jar
deleted file mode 100644
index 873d11983e..0000000000
--- a/java/lib/slf4j-log4j12-1.6.1.jar
+++ /dev/null
Binary files differ
diff --git a/java/lib/xalan-2.7.0.jar b/java/lib/xalan-2.7.0.jar
deleted file mode 100644
index 007be3960a..0000000000
--- a/java/lib/xalan-2.7.0.jar
+++ /dev/null
Binary files differ
diff --git a/java/management/common/build.xml b/java/management/common/build.xml
deleted file mode 100644
index ce2ec3a106..0000000000
--- a/java/management/common/build.xml
+++ /dev/null
@@ -1,26 +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.
- -
- -->
-<project name="Management Common" default="build">
-
- <import file="../../module.xml"/>
-
- <target name="bundle" depends="bundle-tasks"/>
-</project>
diff --git a/java/management/common/src/main/java/management-common.bnd b/java/management/common/src/main/java/management-common.bnd
deleted file mode 100644
index 66eb9f156b..0000000000
--- a/java/management/common/src/main/java/management-common.bnd
+++ /dev/null
@@ -1,27 +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.
-#
-
-ver: 0.11.0
-
-Bundle-SymbolicName: qpid-management-common
-Bundle-Version: ${ver}
-Export-Package: *;version=${ver}
-Bundle-RequiredExecutionEnvironment: J2SE-1.5
-Require-Bundle: jmxremote.sasl;resolution:=optional
-
diff --git a/java/management/common/src/main/java/org/apache/qpid/management/common/JMXConnnectionFactory.java b/java/management/common/src/main/java/org/apache/qpid/management/common/JMXConnnectionFactory.java
deleted file mode 100644
index 40202c2679..0000000000
--- a/java/management/common/src/main/java/org/apache/qpid/management/common/JMXConnnectionFactory.java
+++ /dev/null
@@ -1,290 +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.management.common;
-
-import java.io.IOException;
-import java.security.Security;
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.management.remote.JMXConnector;
-import javax.management.remote.JMXConnectorFactory;
-import javax.management.remote.JMXServiceURL;
-import javax.net.ssl.SSLException;
-import javax.security.auth.callback.CallbackHandler;
-import javax.security.sasl.SaslClientFactory;
-
-import org.apache.qpid.management.common.sasl.CRAMMD5HashedSaslClientFactory;
-import org.apache.qpid.management.common.sasl.Constants;
-import org.apache.qpid.management.common.sasl.JCAProvider;
-import org.apache.qpid.management.common.sasl.SaslProvider;
-import org.apache.qpid.management.common.sasl.UserPasswordCallbackHandler;
-import org.apache.qpid.management.common.sasl.UsernameHashedPasswordCallbackHandler;
-
-public class JMXConnnectionFactory {
-
- private static final String NON_JRMP_SERVER = "non-JRMP server at remote endpoint";
- private static final String SERVER_SUPPORTED_PROFILES = "The server supported profiles";
- private static final String CLIENT_REQUIRED_PROFILES = "do not match the client required profiles";
-
- public static JMXConnector getJMXConnection(long timeout, String host, int port, String username, String password)
- throws SSLException, IOException, Exception
- {
- //auto-negotiate an RMI or JMXMP (SASL/CRAM-MD5 or SASL/PLAIN) JMX connection to broker
- try
- {
- return createJMXconnector("RMI", timeout, host, port, username, password);
- }
- catch (IOException rmiIOE)
- {
- // check if the ioe was raised because we tried connecting to a non RMI-JRMP based JMX server
- boolean jrmpServer = !rmiIOE.getMessage().contains(NON_JRMP_SERVER);
-
- if (jrmpServer)
- {
- //it was an RMI-JRMP based JMX server, so something else went wrong. Check for SSL issues.
- Throwable rmiIOECause = rmiIOE.getCause();
- boolean isSSLException = false;
- if (rmiIOECause != null)
- {
- isSSLException = rmiIOECause instanceof SSLException;
- }
-
- //if it was an SSLException based cause, throw it
- if (isSSLException)
- {
- throw (SSLException) rmiIOECause;
- }
- else
- {
- //can't determine cause, throw new IOE citing the original as cause
- IOException nioe = new IOException();
- nioe.initCause(rmiIOE);
- throw nioe;
- }
- }
- else
- {
- try
- {
- //It wasnt an RMI ConnectorServer at the broker end. Try to establish a JMXMP SASL/CRAM-MD5 connection instead.
- return createJMXconnector("JMXMP_CRAM-MD5", timeout, host, port, username, password);
- }
- catch (IOException cramIOE)
- {
- // check if the IOE was raised because we tried connecting to a SASL/PLAIN server using SASL/CRAM-MD5
- boolean plainProfileServer = cramIOE.getMessage().contains(SERVER_SUPPORTED_PROFILES +
- " [" + Constants.SASL_PLAIN + "] " + CLIENT_REQUIRED_PROFILES + " [" + Constants.SASL_CRAMMD5 + "]");
-
- if (!plainProfileServer)
- {
- IOException nioe = new IOException();
- nioe.initCause(cramIOE);
- throw nioe;
- }
- else
- {
- try
- {
- // Try to establish a JMXMP SASL/PLAIN connection instead.
- return createJMXconnector("JMXMP_PLAIN", timeout, host, port, username, password);
- }
- catch (IOException plainIOE)
- {
- /* Out of options now. Check that the IOE was raised because we tried connecting to a server
- * which didnt support SASL/PLAIN. If so, signal an unknown profile type. If not, raise the exception. */
- boolean unknownProfile = plainIOE.getMessage().contains(CLIENT_REQUIRED_PROFILES + " [" + Constants.SASL_PLAIN + "]");
-
- if (unknownProfile)
- {
- throw new Exception("Unknown JMXMP authentication mechanism, unable to connect.");
- }
- else
- {
- IOException nioe = new IOException();
- nioe.initCause(plainIOE);
- throw nioe;
- }
- }
- }
- }
- }
- }
- }
-
- private static JMXConnector createJMXconnector(String connectionType, long timeout, String host, int port,
- String userName, String password) throws IOException, Exception
- {
- Map<String, Object> env = new HashMap<String, Object>();
- JMXServiceURL jmxUrl = null;
-
- if (connectionType.equalsIgnoreCase("RMI"))
- {
- jmxUrl = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + host + ":" + port + "/jmxrmi");
-
- //Add user credential's to environment map for RMIConnector startup.
- //These will be used for authentication by the remote RMIConnectorServer if supported, or ignored otherwise.
- env.put(JMXConnector.CREDENTIALS, new String[] {userName,password});
- }
- else if (connectionType.contains("JMXMP"))
- {
- // Check that the JMXMPConnector is available to provide SASL support
- final String jmxmpcClass = "javax.management.remote.jmxmp.JMXMPConnector";
-
- try
- {
- Class.forName(jmxmpcClass);
- }
- catch (ClassNotFoundException cnfe)
- {
- throw new Exception("JMXMPConnector class not found, unable to connect to specified server.\n\n"
- + "Please add the jmxremote_optional.jar to the jmxremote.sasl plugin folder, or the classpath.");
- }
-
- jmxUrl = new JMXServiceURL("jmxmp", host, port);
- env = new HashMap<String, Object>();
-
- /* set the package in which to find the JMXMP ClientProvider.class file loaded by the
- * jmxremote.sasl plugin (from the jmxremote_optional.jar) */
- env.put("jmx.remote.protocol.provider.pkgs", "com.sun.jmx.remote.protocol");
-
- if (connectionType.equalsIgnoreCase("JMXMP_CRAM-MD5"))
- {
- Map<String, Class<? extends SaslClientFactory>> map = new HashMap<String, Class<? extends SaslClientFactory>>();
- map.put("CRAM-MD5-HASHED", CRAMMD5HashedSaslClientFactory.class);
- Security.addProvider(new JCAProvider(map));
-
- CallbackHandler handler = new UsernameHashedPasswordCallbackHandler(
- userName, password);
- env.put("jmx.remote.profiles", Constants.SASL_CRAMMD5);
- env.put("jmx.remote.sasl.callback.handler", handler);
- }
- else if (connectionType.equalsIgnoreCase("JMXMP_PLAIN"))
- {
- Security.addProvider(new SaslProvider());
- CallbackHandler handler = new UserPasswordCallbackHandler(userName, password);
- env.put("jmx.remote.profiles", Constants.SASL_PLAIN);
- env.put("jmx.remote.sasl.callback.handler", handler);
- }
- else
- {
- throw new Exception("Unknown JMXMP authentication mechanism");
- }
- }
- else
- {
- throw new Exception("Unknown connection type");
- }
-
- ConnectWaiter connector = new ConnectWaiter(jmxUrl, env);
- Thread connectorThread = new Thread(connector);
- connectorThread.start();
- connectorThread.join(timeout);
-
- if(connector.getJmxc() == null)
- {
- if (connector.getConnectionException() != null)
- {
- throw connector.getConnectionException();
- }
- else
- {
- throw new IOException("Timed out connecting to " + host + ":" + port);
- }
- }
-
- return connector.getJmxc();
- }
-
- private static class ConnectWaiter implements Runnable
- {
- private Exception _connectionException;
- private JMXConnector _jmxc;
- private JMXServiceURL _jmxUrl;
- private Map<String, ?> _env;
- private boolean _connectionRetrieved;
-
- public ConnectWaiter(JMXServiceURL url, Map<String, ?> env)
- {
- _jmxUrl = url;
- _env = env;
- }
-
- public void run()
- {
- try
- {
- synchronized (this)
- {
- if(_connectionRetrieved)
- {
- _jmxc = null;
- _connectionRetrieved = false;
- _connectionException = null;
- }
- }
-
- JMXConnector conn = JMXConnectorFactory.connect(_jmxUrl, _env);
-
- synchronized (this)
- {
- if(_connectionRetrieved)
- {
- //The app thread already timed out the attempt and retrieved the
- //null connection, so just close this orphaned connection
- try
- {
- conn.close();
- }
- catch (IOException e)
- {
- //ignore
- }
- }
- else
- {
- _jmxc = conn;
- }
- }
- }
- catch (Exception ex)
- {
- _connectionException = ex;
- }
- }
-
- public Exception getConnectionException()
- {
- return _connectionException;
- }
-
- public JMXConnector getJmxc()
- {
- synchronized (this)
- {
- _connectionRetrieved = true;
-
- return _jmxc;
- }
- }
- }
-}
diff --git a/java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/ConfigurationManagement.java b/java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/ConfigurationManagement.java
deleted file mode 100644
index a21a6713cc..0000000000
--- a/java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/ConfigurationManagement.java
+++ /dev/null
@@ -1,41 +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.management.common.mbeans;
-
-import javax.management.MBeanOperationInfo;
-
-import org.apache.qpid.management.common.mbeans.annotations.MBeanOperation;
-
-public interface ConfigurationManagement
-{
-
- String TYPE = "ConfigurationManagement";
-
- /**
- * Reload the
- * @throws ConfigurationException
- */
- @MBeanOperation(name="reloadSecurityConfiguration",
- description = "Force a reload of the security configuration sections",
- impact = MBeanOperationInfo.ACTION)
- void reloadSecurityConfiguration() throws Exception;
-
-}
diff --git a/java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/LoggingManagement.java b/java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/LoggingManagement.java
deleted file mode 100644
index 6d15869f0c..0000000000
--- a/java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/LoggingManagement.java
+++ /dev/null
@@ -1,164 +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.management.common.mbeans;
-
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-
-import org.apache.qpid.management.common.mbeans.annotations.MBeanAttribute;
-import org.apache.qpid.management.common.mbeans.annotations.MBeanOperation;
-import org.apache.qpid.management.common.mbeans.annotations.MBeanOperationParameter;
-
-import javax.management.MBeanOperationInfo;
-import javax.management.openmbean.TabularData;
-
-/**
- * Interface for the LoggingManagement MBean
- * @since Qpid JMX API 1.2
- */
-public interface LoggingManagement
-{
- String TYPE = "LoggingManagement";
-
- //TabularType and contained CompositeType key/description information
- //For compatibility reasons, DONT MODIFY the existing key values if expanding the set.
- String LOGGER_NAME = "LoggerName";
- String LOGGER_LEVEL = "Level";
- List<String> COMPOSITE_ITEM_NAMES = Collections.unmodifiableList(Arrays.asList(LOGGER_NAME, LOGGER_LEVEL));
- List<String> COMPOSITE_ITEM_DESCRIPTIONS = Collections.unmodifiableList(Arrays.asList("Name of the logger", "Level of the logger"));
- List<String> TABULAR_UNIQUE_INDEX = Collections.unmodifiableList(Arrays.asList(LOGGER_NAME));
-
- /**
- * Attribute to represent the log4j xml configuration file's LogWatch interval.
- * @return The logwatch interval in seconds.
- * @since Qpid JMX API 1.2
- */
- @MBeanAttribute(name="Log4jLogWatchInterval",
- description = "The log4j xml configuration file LogWatch interval (in seconds). 0 indicates not being checked.")
- Integer getLog4jLogWatchInterval();
-
- /**
- * Attribute to represent the available log4j logger output levels.
- * @return The logging level names.
- * @since Qpid JMX API 1.2
- */
- @MBeanAttribute(name="AvailableLoggerLevels", description = "The values to which log output level can be set.")
- String[] getAvailableLoggerLevels();
-
-
- //****** log4j runtime operations ****** //
-
- /**
- * Sets the level of an active Log4J logger
- * @param logger The name of the logger
- * @param level The level to set the logger to
- * @return True if successful, false if unsuccessful (eg if an invalid level is specified)
- * @since Qpid JMX API 1.2
- */
- @MBeanOperation(name = "setRuntimeLoggerLevel", description = "Set the runtime logging level for an active log4j logger.",
- impact = MBeanOperationInfo.ACTION)
- boolean setRuntimeLoggerLevel(@MBeanOperationParameter(name = "logger", description = "Logger name")String logger,
- @MBeanOperationParameter(name = "level", description = "Logger level")String level);
-
- /**
- * Retrieves a TabularData set of the active log4j loggers and their levels
- * @return TabularData set of CompositeData rows with logger name and level, or null if there is a problem with the TabularData type
- * @since Qpid JMX API 1.2
- */
- @MBeanOperation(name = "viewEffectiveRuntimeLoggerLevels", description = "View the effective runtime logging level " +
- "for active log4j logger's.", impact = MBeanOperationInfo.INFO)
- TabularData viewEffectiveRuntimeLoggerLevels();
-
- /**
- * Sets the level of the active Log4J RootLogger
- * @param level The level to set the RootLogger to
- * @return True if successful, false if unsuccessful (eg if an invalid level is specified)
- * @since Qpid JMX API 1.2
- */
- @MBeanOperation(name = "setRuntimeRootLoggerLevel", description = "Set the runtime logging level for the active log4j Root Logger.",
- impact = MBeanOperationInfo.ACTION)
- boolean setRuntimeRootLoggerLevel(@MBeanOperationParameter(name = "level", description = "Logger level")String level);
-
- /**
- * Attribute to represent the level of the active Log4J RootLogger
- * @return The level of the RootLogger.
- * @since Qpid JMX API 1.2
- */
- @MBeanAttribute(name = "getRuntimeRootLoggerLevel", description = "Get the runtime logging level for the active log4j Root Logger.")
- String getRuntimeRootLoggerLevel();
-
-
- //****** log4j XML configuration file operations ****** //
-
- /**
- * Reloads the log4j configuration file, applying any changes made.
- *
- * @throws IOException
- * @since Qpid JMX API 1.4
- */
- @MBeanOperation(name = "reloadConfigFile", description = "Reload the log4j xml configuration file", impact = MBeanOperationInfo.ACTION)
- void reloadConfigFile() throws IOException;
-
- /**
- * Updates the level of an existing Log4J logger within the xml configuration file
- * @param logger The name of the logger
- * @param level The level to set the logger to
- * @return True if successful, false if unsuccessful (eg if an invalid logger or level is specified)
- * @throws IOException if there is an error parsing the configuration file.
- * @since Qpid JMX API 1.2
- */
- @MBeanOperation(name = "setConfigFileLoggerLevel", description = "Set the logging level for an existing logger " +
- "in the log4j xml configuration file", impact = MBeanOperationInfo.ACTION)
- boolean setConfigFileLoggerLevel(@MBeanOperationParameter(name = "logger", description = "logger name")String logger,
- @MBeanOperationParameter(name = "level", description = "Logger level")String level) throws IOException;
-
- /**
- * Retrieves a TabularData set of the existing Log4J loggers within the xml configuration file
- * @return TabularData set of CompositeData rows with logger name and level, or null if there is a problem with the TabularData type
- * @throws IOException if there is an error parsing the configuration file.
- * @since Qpid JMX API 1.2
- */
- @MBeanOperation(name = "viewConfigFileLoggerLevels", description = "Get the logging level defined for the logger's " +
- "in the log4j xml configuration file.", impact = MBeanOperationInfo.INFO)
- TabularData viewConfigFileLoggerLevels() throws IOException;
-
- /**
- * Updates the level of the Log4J RootLogger within the xml configuration file if it is present
- * @param level The level to set the logger to
- * @return True if successful, false if not (eg an invalid level is specified, or root logger level isnt already defined)
- * @throws IOException if there is an error parsing the configuration file.
- * @since Qpid JMX API 1.2
- */
- @MBeanOperation(name = "setConfigFileRootLoggerLevel", description = "Set the logging level for the Root Logger " +
- "in the log4j xml configuration file.", impact = MBeanOperationInfo.ACTION)
- boolean setConfigFileRootLoggerLevel(@MBeanOperationParameter(name = "level", description = "Logger level")String level) throws IOException;
-
- /**
- * Attribute to represent the level of the Log4J RootLogger within the xml configuration file
- * @return The level of the RootLogger, or null if it is not present
- * @since Qpid JMX API 1.2
- */
- @MBeanAttribute(name = "getConfigFileRootLoggerLevel", description = "Get the logging level for the Root Logger " +
- "in the log4j xml configuration file.")
- String getConfigFileRootLoggerLevel() throws IOException;
-}
diff --git a/java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/ManagedBroker.java b/java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/ManagedBroker.java
deleted file mode 100644
index b5c80a4fed..0000000000
--- a/java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/ManagedBroker.java
+++ /dev/null
@@ -1,248 +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.management.common.mbeans;
-
-import java.io.IOException;
-import java.util.List;
-
-import javax.management.JMException;
-import javax.management.MBeanException;
-import javax.management.MBeanOperationInfo;
-
-import org.apache.qpid.management.common.mbeans.annotations.MBeanAttribute;
-import org.apache.qpid.management.common.mbeans.annotations.MBeanOperation;
-import org.apache.qpid.management.common.mbeans.annotations.MBeanOperationParameter;
-
-/**
- * The ManagedBroker is the management interface to expose management
- * features of the Broker.
- *
- * @version Qpid JMX API 2.2
- * @since Qpid JMX API 1.3
- */
-public interface ManagedBroker
-{
- static final String TYPE = "VirtualHostManager";
-
- /**
- * Returns an array of the exchange types available for creation.
- * @since Qpid JMX API 1.3
- * @throws IOException
- */
- @MBeanAttribute(name="ExchangeTypes", description = "The types of Exchange available for creation.")
- String[] getExchangeTypes() throws IOException;
-
- /**
- * Returns a list containing the names of the attributes available for the Queue mbeans.
- * @since Qpid JMX API 1.3
- * @throws IOException
- */
- @MBeanOperation(name = "retrieveQueueAttributeNames", description = "Retrieve the attribute names for queues in this virtualhost",
- impact = MBeanOperationInfo.INFO)
- List<String> retrieveQueueAttributeNames() throws IOException;
-
- /**
- * Returns a List of Object Lists containing the requested attribute values (in the same sequence requested) for each queue in the virtualhost.
- * If a particular attribute cant be found or raises an mbean/reflection exception whilst being gathered its value is substituted with the String "-".
- * @since Qpid JMX API 1.3
- * @throws IOException
- */
- @MBeanOperation(name = "retrieveQueueAttributeValues", description = "Retrieve the indicated attributes for queues in this virtualhost",
- impact = MBeanOperationInfo.INFO)
- List<List<Object>> retrieveQueueAttributeValues(@MBeanOperationParameter(name="attributes", description="Attributes to retrieve") String[] attributes) throws IOException;
-
- /**
- * Creates a new Exchange.
- *
- * @param name
- * @param type
- * @param durable
- * @throws IOException
- * @throws JMException
- * @throws MBeanException
- */
- @MBeanOperation(name="createNewExchange", description="Creates a new Exchange", impact= MBeanOperationInfo.ACTION)
- void createNewExchange(@MBeanOperationParameter(name="name", description="Name of the new exchange")String name,
- @MBeanOperationParameter(name="ExchangeType", description="Type of the exchange")String type,
- @MBeanOperationParameter(name="durable", description="true if the Exchang should be durable")boolean durable)
- throws IOException, JMException, MBeanException;
-
- /**
- * unregisters all the channels, queuebindings etc and unregisters
- * this exchange from managed objects.
- *
- * @param exchange
- * @throws IOException
- * @throws JMException
- * @throws MBeanException
- */
- @MBeanOperation(name="unregisterExchange",
- description="Unregisters all the related channels and queuebindings of this exchange",
- impact= MBeanOperationInfo.ACTION)
- void unregisterExchange(@MBeanOperationParameter(name= ManagedExchange.TYPE, description="Exchange Name")String exchange)
- throws IOException, JMException, MBeanException;
-
- /**
- * Create a new Queue on the Broker server.
- *
- * @param queueName
- * @param durable
- * @param owner
- * @throws IOException
- * @throws JMException
- * @throws MBeanException
- */
- @MBeanOperation(name="createNewQueue", description="Create a new Queue on the Broker server", impact= MBeanOperationInfo.ACTION)
- void createNewQueue(@MBeanOperationParameter(name="queue name", description="Name of the new queue")String queueName,
- @MBeanOperationParameter(name="owner", description="Owner name")String owner,
- @MBeanOperationParameter(name="durable", description="true if the queue should be durable")boolean durable)
- throws IOException, JMException, MBeanException;
-
- /**
- * Unregisters the Queue bindings, removes the subscriptions and unregisters
- * from the managed objects.
- *
- * @param queueName
- * @throws IOException
- * @throws JMException
- * @throws MBeanException
- */
- @MBeanOperation(name="deleteQueue",
- description="Unregisters the Queue bindings, removes the subscriptions and deletes the queue",
- impact= MBeanOperationInfo.ACTION)
- void deleteQueue(@MBeanOperationParameter(name= ManagedQueue.TYPE, description="Queue Name")String queueName)
- throws IOException, JMException, MBeanException;
-
- /**
- * Resets all message and data statistics for the virtual host.
- *
- * @since Qpid JMX API 2.2
- */
- @MBeanOperation(name="resetStatistics",
- description="Resets all message and data statistics for the virtual host",
- impact= MBeanOperationInfo.ACTION)
- void resetStatistics() throws Exception;
-
- /**
- * Peak rate of messages delivered per second for the virtual host.
- *
- * @since Qpid JMX API 2.2
- */
- @MBeanAttribute(name="PeakMessageDeliveryRate", description=TYPE + " Peak Message Delivery Rate")
- double getPeakMessageDeliveryRate();
-
- /**
- * Peak rate of bytes delivered per second for the virtual host.
- *
- * @since Qpid JMX API 2.2
- */
- @MBeanAttribute(name="PeakDataDeliveryRate", description=TYPE + " Peak Data Delivery Rate")
- double getPeakDataDeliveryRate();
-
- /**
- * Rate of messages delivered per second for the virtual host.
- *
- * @since Qpid JMX API 2.2
- */
- @MBeanAttribute(name="MessageDeliveryRate", description=TYPE + " Message Delivery Rate")
- double getMessageDeliveryRate();
-
- /**
- * Rate of bytes delivered per second for the virtual host.
- *
- * @since Qpid JMX API 2.2
- */
- @MBeanAttribute(name="DataDeliveryRate", description=TYPE + " Data Delivery Rate")
- double getDataDeliveryRate();
-
- /**
- * Total count of messages delivered for the virtual host.
- *
- * @since Qpid JMX API 2.2
- */
- @MBeanAttribute(name="TotalMessagesDelivered", description=TYPE + " Total Messages Delivered")
- long getTotalMessagesDelivered();
-
- /**
- * Total count of bytes for the virtual host.
- *
- * @since Qpid JMX API 2.2
- */
- @MBeanAttribute(name="TotalDataDelivered", description=TYPE + " Total Data Delivered")
- long getTotalDataDelivered();
-
- /**
- * Peak rate of messages received per second for the virtual host.
- *
- * @since Qpid JMX API 2.2
- */
- @MBeanAttribute(name="PeakMessageReceiptRate", description=TYPE + " Peak Message Receipt Rate")
- double getPeakMessageReceiptRate();
-
- /**
- * Peak rate of bytes received per second for the virtual host.
- *
- * @since Qpid JMX API 2.2
- */
- @MBeanAttribute(name="PeakDataReceiptRate", description=TYPE + " Peak Data Receipt Rate")
- double getPeakDataReceiptRate();
-
- /**
- * Rate of messages received per second for the virtual host.
- *
- * @since Qpid JMX API 2.2
- */
- @MBeanAttribute(name="MessageReceiptRate", description=TYPE + " Message Receipt Rate")
- double getMessageReceiptRate();
-
- /**
- * Rate of bytes received per second for the virtual host.
- *
- * @since Qpid JMX API 2.2
- */
- @MBeanAttribute(name="DataReceiptRate", description=TYPE + " Data Receipt Rate")
- double getDataReceiptRate();
-
- /**
- * Total count of messages received for the virtual host.
- *
- * @since Qpid JMX API 2.2
- */
- @MBeanAttribute(name="TotalMessagesReceived", description=TYPE + " Total Messages Received")
- long getTotalMessagesReceived();
-
- /**
- * Total count of bytes received for the virtual host.
- *
- * @since Qpid JMX API 2.2
- */
- @MBeanAttribute(name="TotalDataReceived", description=TYPE + " Total Data Received")
- long getTotalDataReceived();
-
- /**
- * Is statistics collection enabled for this connection.
- *
- * @since Qpid JMX API 2.2
- */
- @MBeanAttribute(name="StatisticsEnabled", description=TYPE + " Statistics Enabled")
- boolean isStatisticsEnabled();
-}
diff --git a/java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/ManagedConnection.java b/java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/ManagedConnection.java
deleted file mode 100644
index d16db65d5d..0000000000
--- a/java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/ManagedConnection.java
+++ /dev/null
@@ -1,271 +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.management.common.mbeans;
-
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.Date;
-import java.util.List;
-
-import javax.management.JMException;
-import javax.management.MBeanOperationInfo;
-import javax.management.openmbean.TabularData;
-
-import org.apache.qpid.management.common.mbeans.annotations.MBeanAttribute;
-import org.apache.qpid.management.common.mbeans.annotations.MBeanOperation;
-import org.apache.qpid.management.common.mbeans.annotations.MBeanOperationParameter;
-
-/**
- * The management interface exposed to allow management of Connections.
- *
- * @version Qpid JMX API 2.2
- * @since Qpid JMX API 1.3
- */
-public interface ManagedConnection
-{
- static final String TYPE = "Connection";
-
- //TabularType and contained CompositeType key/description information
- //For compatibility reasons, DONT MODIFY the existing key values if expanding the set.
- //"Flow Blocked" added in Qpid JMX API 1.5
- String CHAN_ID = "Channel Id";
- String TRANSACTIONAL = "Transactional";
- String DEFAULT_QUEUE = "Default Queue";
- String UNACKED_COUNT = "Unacknowledged Message Count";
- String FLOW_BLOCKED = "Flow Blocked";
- List<String> COMPOSITE_ITEM_NAMES_DESC = Collections.unmodifiableList(Arrays.asList(CHAN_ID, TRANSACTIONAL, DEFAULT_QUEUE, UNACKED_COUNT, FLOW_BLOCKED));
- List<String> TABULAR_UNIQUE_INDEX = Collections.unmodifiableList(Arrays.asList(CHAN_ID));
-
- @MBeanAttribute(name = "ClientId", description = "Client Id")
- String getClientId();
-
- @MBeanAttribute(name = "AuthorizedId", description = "User Name")
- String getAuthorizedId();
-
- @MBeanAttribute(name = "Version", description = "Client Version")
- String getVersion();
-
- /**
- * Tells the remote address of this connection.
- * @return remote address
- */
- @MBeanAttribute(name="RemoteAddress", description=TYPE + " Address")
- String getRemoteAddress();
-
- /**
- * Tells the last time, the IO operation was done.
- * @return last IO time.
- */
- @MBeanAttribute(name="LastIOTime", description="The last time, the IO operation was done")
- Date getLastIoTime();
-
- /**
- * Tells the total number of bytes written till now.
- * @return number of bytes written.
- *
- @MBeanAttribute(name="WrittenBytes", description="The total number of bytes written till now")
- Long getWrittenBytes();
- */
- /**
- * Tells the total number of bytes read till now.
- * @return number of bytes read.
- *
- @MBeanAttribute(name="ReadBytes", description="The total number of bytes read till now")
- Long getReadBytes();
- */
-
- /**
- * Threshold high value for no of channels. This is useful in setting notifications or
- * taking required action is there are more channels being created.
- * @return threshold limit for no of channels
- */
- Long getMaximumNumberOfChannels();
-
- /**
- * Sets the threshold high value for number of channels for a connection
- * @param value
- */
- @MBeanAttribute(name="MaximumNumberOfChannels", description="The threshold high value for number of channels for this connection")
- void setMaximumNumberOfChannels(Long value);
-
- //********** Operations *****************//
-
- /**
- * channel details of all the channels opened for this connection.
- * @return general channel details
- * @throws IOException
- * @throws JMException
- */
- @MBeanOperation(name="channels", description="Channel details for this connection")
- TabularData channels() throws IOException, JMException;
-
- /**
- * Commits the transactions if the channel is transactional.
- * @param channelId
- * @throws JMException
- */
- @MBeanOperation(name="commitTransaction",
- description="Commits the transactions for given channel Id, if the channel is transactional",
- impact= MBeanOperationInfo.ACTION)
- void commitTransactions(@MBeanOperationParameter(name="channel Id", description="channel Id")int channelId) throws JMException;
-
- /**
- * Rollsback the transactions if the channel is transactional.
- * @param channelId
- * @throws JMException
- */
- @MBeanOperation(name="rollbackTransactions",
- description="Rollsback the transactions for given channel Id, if the channel is transactional",
- impact= MBeanOperationInfo.ACTION)
- void rollbackTransactions(@MBeanOperationParameter(name="channel Id", description="channel Id")int channelId) throws JMException;
-
- /**
- * Closes all the related channels and unregisters this connection from managed objects.
- */
- @MBeanOperation(name="closeConnection",
- description="Closes this connection and all related channels",
- impact= MBeanOperationInfo.ACTION)
- void closeConnection() throws Exception;
-
- /**
- * Resets message and data statistics for this connection.
- *
- * @since Qpid JMX API 2.2
- */
- @MBeanOperation(name="resetStatistics",
- description="Resets message and data statistics for this connection",
- impact= MBeanOperationInfo.ACTION)
- void resetStatistics() throws Exception;
-
- /**
- * Peak rate of messages delivered per second for the virtual host.
- *
- * @since Qpid JMX API 2.2
- */
- @MBeanAttribute(name="PeakMessageDeliveryRate", description=TYPE + " Peak Message Delivery Rate")
- double getPeakMessageDeliveryRate();
-
- /**
- * Peak rate of bytes delivered per second for the virtual host.
- *
- * @since Qpid JMX API 2.2
- */
- @MBeanAttribute(name="PeakDataDeliveryRate", description=TYPE + " Peak Data Delivery Rate")
- double getPeakDataDeliveryRate();
-
- /**
- * Rate of messages delivered per second for the virtual host.
- *
- * @since Qpid JMX API 2.2
- */
- @MBeanAttribute(name="MessageDeliveryRate", description=TYPE + " Message Delivery Rate")
- double getMessageDeliveryRate();
-
- /**
- * Rate of bytes delivered per second for the virtual host.
- *
- * @since Qpid JMX API 2.2
- */
- @MBeanAttribute(name="DataDeliveryRate", description=TYPE + " Data Delivery Rate")
- double getDataDeliveryRate();
-
- /**
- * Total count of messages delivered for the virtual host.
- *
- * @since Qpid JMX API 2.2
- */
- @MBeanAttribute(name="TotalMessagesDelivered", description=TYPE + " Total Messages Delivered")
- long getTotalMessagesDelivered();
-
- /**
- * Total count of bytes for the virtual host.
- *
- * @since Qpid JMX API 2.2
- */
- @MBeanAttribute(name="TotalDataDelivered", description=TYPE + " Total Data Delivered")
- long getTotalDataDelivered();
-
- /**
- * Peak rate of messages received per second for this connection.
- *
- * @since Qpid JMX API 2.2
- */
- @MBeanAttribute(name="PeakMessageReceiptRate", description=TYPE + " Peak Message Receipt Rate")
- double getPeakMessageReceiptRate();
-
- /**
- * Peak rate of bytes received per second for this connection.
- *
- * @since Qpid JMX API 2.2
- */
- @MBeanAttribute(name="PeakDataReceiptRate", description=TYPE + " Peak Data Receipt Rate")
- double getPeakDataReceiptRate();
-
- /**
- * Rate of messages received per second for this connection.
- *
- * @since Qpid JMX API 2.2
- */
- @MBeanAttribute(name="MessageReceiptRate", description=TYPE + " Message Receipt Rate")
- double getMessageReceiptRate();
-
- /**
- * Rate of bytes received per second for this connection.
- *
- * @since Qpid JMX API 2.2
- */
- @MBeanAttribute(name="DataReceiptRate", description=TYPE + " Data Receipt Rate")
- double getDataReceiptRate();
-
- /**
- * Total count of messages received for this connection.
- *
- * @since Qpid JMX API 2.2
- */
- @MBeanAttribute(name="TotalMessagesReceived", description=TYPE + " Total Messages Received")
- long getTotalMessagesReceived();
-
- /**
- * Total count of bytes received for this connection.
- *
- * @since Qpid JMX API 2.2
- */
- @MBeanAttribute(name="TotalDataReceived", description=TYPE + " Total Data Received")
- long getTotalDataReceived();
-
- /**
- * Is statistics collection enabled for this connection.
- *
- * @since Qpid JMX API 2.2
- */
- @MBeanAttribute(name="StatisticsEnabled", description=TYPE + " Statistics Enabled")
- boolean isStatisticsEnabled();
-
- /**
- * Sets statistics collection enabled/disabled for this connection.
- *
- * @param enabled
- * @since Qpid JMX API 2.2
- */
- void setStatisticsEnabled(boolean enabled);
-}
diff --git a/java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/ManagedExchange.java b/java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/ManagedExchange.java
deleted file mode 100644
index 78a1eb964f..0000000000
--- a/java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/ManagedExchange.java
+++ /dev/null
@@ -1,133 +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.management.common.mbeans;
-
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-
-import javax.management.JMException;
-import javax.management.MBeanOperationInfo;
-import javax.management.openmbean.TabularData;
-
-import org.apache.qpid.management.common.mbeans.annotations.MBeanAttribute;
-import org.apache.qpid.management.common.mbeans.annotations.MBeanOperation;
-import org.apache.qpid.management.common.mbeans.annotations.MBeanOperationParameter;
-
-/**
- * The management interface exposed to allow management of an Exchange.
- *
- * @version 1.8
- */
-public interface ManagedExchange
-{
- static final String TYPE = "Exchange";
-
- //TabularType and contained CompositeType key/description info for DIRECT/TOPIC/FANOUT exchanges.
- //For compatibility reasons, DONT MODIFY the existing key values if expanding the set.
- String BINDING_KEY = "Binding Key";
- String QUEUE_NAMES = "Queue Names";
-
- List<String> COMPOSITE_ITEM_NAMES = Collections.unmodifiableList(Arrays.asList(BINDING_KEY, QUEUE_NAMES));
- List<String> COMPOSITE_ITEM_DESCRIPTIONS = Collections.unmodifiableList(Arrays.asList(BINDING_KEY, QUEUE_NAMES));
- List<String> TABULAR_UNIQUE_INDEX = Collections.unmodifiableList(Arrays.asList(BINDING_KEY));
-
- //TabularType and contained CompositeType key/description info for HEADERS exchange only.
- //For compatibility reasons, DONT MODIFY the existing key values if expanding the set.
- String HDR_BINDING_NUMBER = "Binding No";
- String HDR_QUEUE_NAME = "Queue Name";
- String HDR_QUEUE_BINDINGS = "Queue Bindings";
-
- List<String> HEADERS_COMPOSITE_ITEM_NAMES = Collections.unmodifiableList(Arrays.asList(HDR_BINDING_NUMBER, HDR_QUEUE_NAME, HDR_QUEUE_BINDINGS));
- List<String> HEADERS_COMPOSITE_ITEM_DESC = Collections.unmodifiableList(Arrays.asList(HDR_BINDING_NUMBER, HDR_QUEUE_NAME, HDR_QUEUE_BINDINGS));
- List<String> HEADERS_TABULAR_UNIQUE_INDEX = Collections.unmodifiableList(Arrays.asList(HDR_BINDING_NUMBER));
-
- /**
- * Returns the name of the managed exchange.
- * @return the name of the exchange.
- * @throws IOException
- */
- @MBeanAttribute(name="Name", description=TYPE + " Name")
- String getName() throws IOException;
-
- @MBeanAttribute(name="ExchangeType", description="Exchange Type")
- String getExchangeType() throws IOException;
-
- @MBeanAttribute(name="TicketNo", description="Exchange Ticket No")
- Integer getTicketNo() throws IOException;
-
- /**
- * Tells if the exchange is durable or not.
- * @return true if the exchange is durable.
- * @throws IOException
- */
- @MBeanAttribute(name="Durable", description="true if Exchange is durable")
- boolean isDurable() throws IOException;
-
- /**
- * Tells if the exchange is set for autodelete or not.
- * @return true if the exchange is set as autodelete.
- * @throws IOException
- */
- @MBeanAttribute(name="AutoDelete", description="true if Exchange is AutoDelete")
- boolean isAutoDelete() throws IOException;
-
- // Operations
-
- /**
- * Returns all the bindings this exchange has with the queues.
- * @return the bindings with the exchange.
- * @throws IOException
- * @throws JMException
- */
- @MBeanOperation(name="bindings", description="view the queue bindings for this exchange")
- TabularData bindings() throws IOException, JMException;
-
- /**
- * Creates new binding with the given queue and binding.
- * @param queueName
- * @param binding
- * @throws JMException
- */
- @MBeanOperation(name="createNewBinding",
- description="create a new binding with this exchange",
- impact= MBeanOperationInfo.ACTION)
- void createNewBinding(@MBeanOperationParameter(name= ManagedQueue.TYPE, description="Queue name") String queueName,
- @MBeanOperationParameter(name="Binding", description="New binding")String binding)
- throws JMException;
-
- /**
- * Removes an exchange binding from a queue.
- *
- * @param exchangeName the Exchange name
- * @param routingKey the routing key
- * @throws IOException
- * @throws JMException
- * @since Qpid JMX API 1.8
- */
- @MBeanOperation(name="removeBinding",
- description="Removes an exchange binding from the Queue",
- impact= MBeanOperationInfo.ACTION)
- void removeBinding(@MBeanOperationParameter(name= ManagedQueue.TYPE, description="Queue name") String queueName,
- @MBeanOperationParameter(name="Binding", description="Binding key")String binding)
- throws IOException, JMException;
-}
diff --git a/java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/ManagedQueue.java b/java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/ManagedQueue.java
deleted file mode 100644
index be31d8ef88..0000000000
--- a/java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/ManagedQueue.java
+++ /dev/null
@@ -1,438 +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.management.common.mbeans;
-
-import java.io.IOException;
-import java.util.*;
-
-import javax.management.JMException;
-import javax.management.MBeanOperationInfo;
-import javax.management.openmbean.CompositeData;
-import javax.management.openmbean.TabularData;
-
-import org.apache.qpid.management.common.mbeans.annotations.MBeanAttribute;
-import org.apache.qpid.management.common.mbeans.annotations.MBeanOperation;
-import org.apache.qpid.management.common.mbeans.annotations.MBeanOperationParameter;
-
-/**
- * The management interface exposed to allow management of a queue.
- * @author Robert J. Greig
- * @author Bhupendra Bhardwaj
- * @version 0.1
- */
-public interface ManagedQueue
-{
- static final String TYPE = "Queue";
-
- //TabularType and contained CompositeType key/description information for message list
- //For compatibility reasons, DONT MODIFY the existing key values if expanding the set.
- //"Queue Position" added in Qpid JMX API 1.3
- String MSG_AMQ_ID = "AMQ MessageId";
- String MSG_HEADER = "Header";
- String MSG_SIZE = "Size(bytes)";
- String MSG_REDELIVERED = "Redelivered";
- String MSG_QUEUE_POS = "Queue Position";
- List<String> VIEW_MSGS_COMPOSITE_ITEM_NAMES_DESC = Collections.unmodifiableList(Arrays.asList(MSG_AMQ_ID, MSG_HEADER, MSG_SIZE, MSG_REDELIVERED, MSG_QUEUE_POS));
- List<String> VIEW_MSGS_TABULAR_UNIQUE_INDEX = Collections.unmodifiableList(Arrays.asList(MSG_QUEUE_POS));
-
- //CompositeType key/description information for message content
- //For compatibility reasons, DONT MODIFY the existing key values if expanding the set.
- String MIME = "MimeType";
- String ENCODING = "Encoding";
- String CONTENT = "Content";
- List<String> VIEW_MSG_CONTENT_COMPOSITE_ITEM_NAMES_DESC = Collections.unmodifiableList(Arrays.asList(MSG_AMQ_ID, MIME, ENCODING, CONTENT));
-
- //Individual attribute name constants
- static final String ATTR_NAME = "Name";
- static final String ATTR_OWNER = "Owner";
- static final String ATTR_MAX_MSG_AGE = "MaximumMessageAge";
- static final String ATTR_MAX_MSG_COUNT = "MaximumMessageCount";
- static final String ATTR_MAX_QUEUE_DEPTH = "MaximumQueueDepth";
- static final String ATTR_MAX_MSG_SIZE = "MaximumMessageSize";
- static final String ATTR_DURABLE = "Durable";
- static final String ATTR_AUTODELETE = "AutoDelete";
- static final String ATTR_CONSUMER_COUNT = "ConsumerCount";
- static final String ATTR_ACTIVE_CONSUMER_COUNT = "ActiveConsumerCount";
- static final String ATTR_MSG_COUNT = "MessageCount";
- static final String ATTR_QUEUE_DEPTH = "QueueDepth";
- static final String ATTR_RCVD_MSG_COUNT = "ReceivedMessageCount";
- static final String ATTR_CAPACITY = "Capacity";
- static final String ATTR_FLOW_OVERFULL = "FlowOverfull";
- static final String ATTR_FLOW_RESUME_CAPACITY = "FlowResumeCapacity";
- static final String ATTR_EXCLUSIVE = "Exclusive";
-
- //All attribute names constant
- static final List<String> QUEUE_ATTRIBUTES
- = Collections.unmodifiableList(
- new ArrayList<String>(
- new HashSet<String>(
- Arrays.asList(
- ATTR_NAME,
- ATTR_OWNER,
- ATTR_MAX_MSG_AGE,
- ATTR_MAX_MSG_COUNT,
- ATTR_MAX_QUEUE_DEPTH,
- ATTR_MAX_MSG_SIZE,
- ATTR_DURABLE,
- ATTR_AUTODELETE,
- ATTR_CONSUMER_COUNT,
- ATTR_ACTIVE_CONSUMER_COUNT,
- ATTR_MSG_COUNT,
- ATTR_QUEUE_DEPTH,
- ATTR_RCVD_MSG_COUNT,
- ATTR_CAPACITY,
- ATTR_FLOW_OVERFULL,
- ATTR_FLOW_RESUME_CAPACITY,
- ATTR_EXCLUSIVE))));
-
- /**
- * Returns the Name of the ManagedQueue.
- * @return the name of the managedQueue.
- * @throws IOException
- */
- @MBeanAttribute(name="Name", description = TYPE + " Name")
- String getName() throws IOException;
-
- /**
- * Total number of messages on the queue, which are yet to be delivered to the consumer(s).
- * @return number of undelivered message in the Queue.
- * @throws IOException
- */
- @MBeanAttribute(name="MessageCount", description = "Total number of undelivered messages on the queue")
- Integer getMessageCount() throws IOException;
-
- /**
- * Tells the total number of messages receieved by the queue since startup.
- * @return total number of messages received.
- * @throws IOException
- */
- @MBeanAttribute(name="ReceivedMessageCount", description="The total number of messages receieved by the queue since startup")
- Long getReceivedMessageCount() throws IOException;
-
- /**
- * Size of messages in the queue
- *
- * Since Qpid JMX API 1.2 this operation returns in units of bytes. Prior to this, the result was in units of kilobytes.
- * @return
- * @throws IOException
- */
- @MBeanAttribute(name="QueueDepth", description="The total size(Bytes) of messages in the queue")
- Long getQueueDepth() throws IOException, JMException;
-
- /**
- * Returns the total number of active subscribers to the queue.
- * @return the number of active subscribers
- * @throws IOException
- */
- @MBeanAttribute(name="ActiveConsumerCount", description="The total number of active subscribers to the queue")
- Integer getActiveConsumerCount() throws IOException;
-
- /**
- * Returns the total number of subscribers to the queue.
- * @return the number of subscribers.
- * @throws IOException
- */
- @MBeanAttribute(name="ConsumerCount", description="The total number of subscribers to the queue")
- Integer getConsumerCount() throws IOException;
-
- /**
- * Tells the Owner of the ManagedQueue.
- * @return the owner's name.
- * @throws IOException
- */
- @MBeanAttribute(name="Owner", description = "Owner")
- String getOwner() throws IOException;
-
- /**
- * Tells whether this ManagedQueue is durable or not.
- * @return true if this ManagedQueue is a durable queue.
- * @throws IOException
- */
- @MBeanAttribute(name="Durable", description = "true if the AMQQueue is durable")
- boolean isDurable() throws IOException;
-
- /**
- * Tells if the ManagedQueue is set to AutoDelete.
- * @return true if the ManagedQueue is set to AutoDelete.
- * @throws IOException
- */
- @MBeanAttribute(name="AutoDelete", description = "true if the AMQQueue is AutoDelete")
- boolean isAutoDelete() throws IOException;
-
- /**
- * Returns the maximum age of a message (expiration time) in milliseconds
- * @return the maximum age
- * @throws IOException
- */
- Long getMaximumMessageAge() throws IOException;
-
- /**
- * Sets the maximum age of a message in milliseconds
- * @param age maximum age of message.
- * @throws IOException
- */
- @MBeanAttribute(name="MaximumMessageAge", description="Threshold high value(milliseconds) for message age")
- void setMaximumMessageAge(Long age) throws IOException;
-
- /**
- * Returns the maximum size of a message (in Bytes) allowed to be accepted by the
- * ManagedQueue. This is useful in setting notifications or taking
- * appropriate action, if the size of the message received is more than
- * the allowed size.
- * @return the maximum size of a message allowed to be aceepted by the
- * ManagedQueue.
- * @throws IOException
- */
- Long getMaximumMessageSize() throws IOException;
-
- /**
- * Sets the maximum size of the message (in Bytes) that is allowed to be
- * accepted by the Queue.
- * @param size maximum size of message.
- * @throws IOException
- */
- @MBeanAttribute(name="MaximumMessageSize", description="Threshold high value(Bytes) for a message size")
- void setMaximumMessageSize(Long size) throws IOException;
-
- /**
- * Tells the maximum number of messages that can be stored in the queue.
- * This is useful in setting the notifications or taking required
- * action is the number of message increase this limit.
- * @return maximum muber of message allowed to be stored in the queue.
- * @throws IOException
- */
- Long getMaximumMessageCount() throws IOException;
-
- /**
- * Sets the maximum number of messages allowed to be stored in the queue.
- * @param value the maximum number of messages allowed to be stored in the queue.
- * @throws IOException
- */
- @MBeanAttribute(name="MaximumMessageCount", description="Threshold high value for number of undelivered messages in the queue")
- void setMaximumMessageCount(Long value) throws IOException;
-
- /**
- * This is useful for setting notifications or taking required action if the size of messages
- * stored in the queue increases over this limit.
- *
- * Since Qpid JMX API 1.2 this operation returns in units of bytes. Prior to this, the result was in units of kilobytes.
- * @return threshold high value for Queue Depth
- * @throws IOException
- */
- Long getMaximumQueueDepth() throws IOException;
-
- /**
- * Sets the maximum size of all the messages together, that can be stored
- * in the queue.
- * @param value
- * @throws IOException
- */
- @MBeanAttribute(name="MaximumQueueDepth", description="The threshold high value(Bytes) for Queue Depth")
- void setMaximumQueueDepth(Long value) throws IOException;
-
-
- /**
- * Returns the current flow control Capacity of the queue in bytes.
- *
- * @since Qpid JMX API 1.6
- * @return Capacity at which flow control is enforced
- * @throws IOException
- */
- Long getCapacity() throws IOException;
-
- /**
- * Sets the Capacity in bytes above which flow is blocked.
- *
- * @since Qpid JMX API 1.6
- * @param value the capacity in bytes
- * @throws IOException
- * @throws IllegalArgumentException If the given value is less than the queue FloeResumeCapacity
- */
- @MBeanAttribute(name="Capacity", description="The flow control Capacity (Bytes) of the queue")
- void setCapacity(Long value) throws IOException, IllegalArgumentException;
-
- /**
- * Returns the current flow control FlowResumeCapacity of the queue in bytes.
- *
- * @since Qpid JMX API 1.6
- * @return Capacity below which flow resumes in bytes
- * @throws IOException
- */
- Long getFlowResumeCapacity() throws IOException;
-
- /**
- * Sets the FlowResumeCapacity in bytes below which flow resumes.
- *
- * @since Qpid JMX API 1.6
- * @param value of the resume capacity in bytes
- * @throws IOException
- * @throws IllegalArgumentException If the given value exceeds the queue Capacity
- */
- @MBeanAttribute(name="FlowResumeCapacity", description="The flow resume Capacity (Bytes) of the queue")
- void setFlowResumeCapacity(Long value) throws IOException, IllegalArgumentException;
-
- /**
- * Indicates whether the Queue is currently considered overfull by the FlowControl system
- *
- * @since Qpid JMX API 1.6
- * @throws IOException
- */
- @MBeanAttribute(name="FlowOverfull", description="true if the queue is considered overfull by the Flow Control system")
- boolean isFlowOverfull() throws IOException;
-
- /**
- * Returns whether the queue is exclusive or not.
- *
- * @since Qpid JMX API 2.0
- * @return whether the queue is exclusive.
- * @throws IOException
- */
- boolean isExclusive() throws IOException;
-
- /**
- * Sets whether the queue is exclusive or not.
- *
- * @since Qpid JMX API 2.0
- * @param exclusive the capacity in bytes
- * @throws IOException
- * @throws JMException
- */
- @MBeanAttribute(name="Exclusive", description="Whether the queue is Exclusive or not")
- void setExclusive(boolean exclusive) throws IOException, JMException;
-
- //********** Operations *****************//
-
-
- /**
- * Returns a subset of all the messages stored in the queue. The messages
- * are returned based on the given index numbers.
- *
- * Deprecated as of Qpid JMX API 1.3
- * @param fromIndex
- * @param toIndex
- * @return
- * @throws IOException
- * @throws JMException
- */
- @Deprecated
- @MBeanOperation(name="viewMessages",
- description="Message headers for messages in this queue within given index range. eg. from index 1 - 100")
- TabularData viewMessages(@MBeanOperationParameter(name="from index", description="from index")int fromIndex,
- @MBeanOperationParameter(name="to index", description="to index")int toIndex)
- throws IOException, JMException;
-
- /**
- * Returns a subset (up to 2^31 messages at a time) of all the messages stored on the queue.
- * The messages are returned based on the given queue position range.
- * @param startPosition
- * @param endPosition
- * @return
- * @throws IOException
- * @throws JMException
- */
- @MBeanOperation(name="viewMessages",
- description="Message headers for messages in this queue within given queue positions range. eg. from index 1 - 100")
- TabularData viewMessages(@MBeanOperationParameter(name="start position", description="start position")long startPosition,
- @MBeanOperationParameter(name="end position", description="end position")long endPosition)
- throws IOException, JMException;
-
- /**
- * Returns the content for the given AMQ Message ID.
- *
- * @throws IOException
- * @throws JMException
- */
- @MBeanOperation(name="viewMessageContent", description="The message content for given Message Id")
- CompositeData viewMessageContent(@MBeanOperationParameter(name="Message Id", description="Message Id")long messageId)
- throws IOException, JMException;
-
- /**
- * Deletes the first message from top.
- *
- * Deprecated as of Qpid JMX API 1.3
- * @throws IOException
- * @throws JMException
- */
- @Deprecated
- @MBeanOperation(name="deleteMessageFromTop", description="Deletes the first message from top",
- impact= MBeanOperationInfo.ACTION)
- void deleteMessageFromTop() throws IOException, JMException;
-
- /**
- * Clears the queue by deleting all the messages from the queue that have not been acquired by consumers"
- *
- * Since Qpid JMX API 1.3 this returns the number of messages deleted. Prior to this, the return type was void.
- * @return the number of messages deleted
- * @throws IOException
- * @throws JMException
- */
- @MBeanOperation(name="clearQueue",
- description="Clears the queue by deleting all the messages from the queue " +
- "that have not been acquired by consumers",
- impact= MBeanOperationInfo.ACTION)
- Long clearQueue() throws IOException, JMException;
-
- /**
- * Moves the messages in given range of message Ids to given Queue. QPID-170
- * @param fromMessageId first in the range of message ids
- * @param toMessageId last in the range of message ids
- * @param toQueue where the messages are to be moved
- * @throws IOException
- * @throws JMException
- */
- @MBeanOperation(name="moveMessages",
- description="You can move messages to another queue from this queue ",
- impact= MBeanOperationInfo.ACTION)
- void moveMessages(@MBeanOperationParameter(name="from MessageId", description="from MessageId")long fromMessageId,
- @MBeanOperationParameter(name="to MessageId", description="to MessageId")long toMessageId,
- @MBeanOperationParameter(name= ManagedQueue.TYPE, description="to Queue Name")String toQueue)
- throws IOException, JMException;
-
- /**
- * Deletes the messages in given range of AMQ message Ids in the given Queue.
- * @param fromMessageId first in the range of message ids
- * @param toMessageId last in the range of message ids
- * @throws IOException
- * @throws JMException
- */
- @MBeanOperation(name="deleteMessages",
- description="Delete a range of messages from a specified queue",
- impact= MBeanOperationInfo.ACTION)
- void deleteMessages(@MBeanOperationParameter(name="from MessageId", description="from MessageId")long fromMessageId,
- @MBeanOperationParameter(name="to MessageId", description="to MessageId")long toMessageId)
- throws IOException, JMException;
-
- /**
- * Copies the messages in given range of AMQ message Ids to a given Queue.
- * @param fromMessageId first in the range of message ids
- * @param toMessageId last in the range of message ids
- * @param toQueue where the messages are to be copied
- * @throws IOException
- * @throws JMException
- */
- @MBeanOperation(name="copyMessages",
- description="Copies a range of messages to a specified queue",
- impact= MBeanOperationInfo.ACTION)
- void copyMessages(@MBeanOperationParameter(name="from MessageId", description="from MessageId")long fromMessageId,
- @MBeanOperationParameter(name="to MessageId", description="to MessageId")long toMessageId,
- @MBeanOperationParameter(name= ManagedQueue.TYPE, description="to Queue Name")String toQueue)
- throws IOException, JMException;
-}
diff --git a/java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/ServerInformation.java b/java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/ServerInformation.java
deleted file mode 100644
index 12ae69571e..0000000000
--- a/java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/ServerInformation.java
+++ /dev/null
@@ -1,202 +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.management.common.mbeans;
-
-import java.io.IOException;
-
-import javax.management.MBeanOperationInfo;
-
-import org.apache.qpid.management.common.mbeans.annotations.MBeanAttribute;
-import org.apache.qpid.management.common.mbeans.annotations.MBeanOperation;
-
-/**
- * Interface for the ServerInformation MBean
- *
- * @version Qpid JMX API 2.3
- * @since Qpid JMX API 1.3
- */
-public interface ServerInformation
-{
- String TYPE = "ServerInformation";
-
- /* API version info for the brokers JMX management interface
- *
- * As the ServerInformation MBean was only introduced in Qpid JMX API 1.3 it is not possible to use it
- * for identifying earlier broker JMX APIs for compatibility purposes. However, this can be accomplished
- * by inspecting the 'version' property key of the UserManagement MBean JMX ObjectName. This was first
- * introduced in Qpid JMX API 1.2 and so if present in the absence of the ServerInformation MBean
- * indicates that version. If it is not present then a null value will be returned upon inspection and
- * Qpid JMX API 1.1 can be assumed.
- */
- int QPID_JMX_API_MAJOR_VERSION = 2;
- int QPID_JMX_API_MINOR_VERSION = 3;
-
-
- /**
- * Attribute to represent the major version number for the management API.
- * @return The major management version number.
- * @since Qpid JMX API 1.3
- */
- @MBeanAttribute(name="ManagementApiMajorVersion",
- description = "The major version number for the broker management API")
- Integer getManagementApiMajorVersion() throws IOException;
-
- /**
- * Attribute to represent the minor version number for the management API.
- * @return The minor management version number.
- * @since Qpid JMX API 1.3
- */
- @MBeanAttribute(name="ManagementApiMinorVersion",
- description = "The minor version number for the broker management API")
- Integer getManagementApiMinorVersion() throws IOException;
-
- /**
- * Attribute to represent the build version string.
- * @return The build version string
- * @since Qpid JMX API 1.3
- */
- @MBeanAttribute(name="BuildVersion",
- description = "The repository build version string")
- String getBuildVersion() throws IOException;
-
- /**
- * Attribute to represent the product version string.
- * @return The product version string
- * @since Qpid JMX API 1.3
- */
- @MBeanAttribute(name="ProductVersion",
- description = "The product version string")
- String getProductVersion() throws IOException;
-
- /**
- * Resets all message and data statistics for the broker.
- *
- * @since Qpid JMX API 2.2
- */
- @MBeanOperation(name="resetStatistics",
- description="Resets all message and data statistics for the broker",
- impact= MBeanOperationInfo.ACTION)
- void resetStatistics() throws Exception;
-
- /**
- * Peak rate of messages delivered per second for the virtual host.
- *
- * @since Qpid JMX API 2.2
- */
- @MBeanAttribute(name="PeakMessageDeliveryRate", description=TYPE + " Peak Message Delivery Rate")
- double getPeakMessageDeliveryRate();
-
- /**
- * Peak rate of bytes delivered per second for the broker.
- *
- * @since Qpid JMX API 2.2
- */
- @MBeanAttribute(name="PeakDataDeliveryRate", description=TYPE + " Peak Data Delivery Rate")
- double getPeakDataDeliveryRate();
-
- /**
- * Rate of messages delivered per second for the broker.
- *
- * @since Qpid JMX API 2.2
- */
- @MBeanAttribute(name="MessageDeliveryRate", description=TYPE + " Message Delivery Rate")
- double getMessageDeliveryRate();
-
- /**
- * Rate of bytes delivered per second for the broker.
- *
- * @since Qpid JMX API 2.2
- */
- @MBeanAttribute(name="DataDeliveryRate", description=TYPE + " Data Delivery Rate")
- double getDataDeliveryRate();
-
- /**
- * Total count of messages delivered for the broker.
- *
- * @since Qpid JMX API 2.2
- */
- @MBeanAttribute(name="TotalMessagesDelivered", description=TYPE + " Total Messages Delivered")
- long getTotalMessagesDelivered();
-
- /**
- * Total count of bytes for the broker.
- *
- * @since Qpid JMX API 2.2
- */
- @MBeanAttribute(name="TotalDataDelivered", description=TYPE + " Total Data Delivered")
- long getTotalDataDelivered();
-
- /**
- * Peak rate of messages received per second for the broker.
- *
- * @since Qpid JMX API 2.2
- */
- @MBeanAttribute(name="PeakMessageReceiptRate", description=TYPE + " Peak Message Receipt Rate")
- double getPeakMessageReceiptRate();
-
- /**
- * Peak rate of bytes received per second for the broker.
- *
- * @since Qpid JMX API 2.2
- */
- @MBeanAttribute(name="PeakDataReceiptRate", description=TYPE + " Peak Data Receipt Rate")
- double getPeakDataReceiptRate();
-
- /**
- * Rate of messages received per second for the broker.
- *
- * @since Qpid JMX API 2.2
- */
- @MBeanAttribute(name="MessageReceiptRate", description=TYPE + " Message Receipt Rate")
- double getMessageReceiptRate();
-
- /**
- * Rate of bytes received per second for the broker.
- *
- * @since Qpid JMX API 2.2
- */
- @MBeanAttribute(name="DataReceiptRate", description=TYPE + " Data Receipt Rate")
- double getDataReceiptRate();
-
- /**
- * Total count of messages received for the broker.
- *
- * @since Qpid JMX API 2.2
- */
- @MBeanAttribute(name="TotalMessagesReceived", description=TYPE + " Total Messages Received")
- long getTotalMessagesReceived();
-
- /**
- * Total count of bytes received for the broker.
- *
- * @since Qpid JMX API 2.2
- */
- @MBeanAttribute(name="TotalDataReceived", description=TYPE + " Total Data Received")
- long getTotalDataReceived();
-
- /**
- * Is statistics collection enabled for this connection.
- *
- * @since Qpid JMX API 2.2
- */
- @MBeanAttribute(name="StatisticsEnabled", description=TYPE + " Statistics Enabled")
- boolean isStatisticsEnabled();
-}
diff --git a/java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/UserManagement.java b/java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/UserManagement.java
deleted file mode 100644
index 194bd83752..0000000000
--- a/java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/UserManagement.java
+++ /dev/null
@@ -1,214 +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.management.common.mbeans;
-
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-
-import org.apache.qpid.management.common.mbeans.annotations.MBeanOperation;
-import org.apache.qpid.management.common.mbeans.annotations.MBeanOperationParameter;
-
-import javax.management.openmbean.TabularData;
-import javax.management.MBeanOperationInfo;
-
-public interface UserManagement
-{
-
- String TYPE = "UserManagement";
-
- //TabularType and contained CompositeType key/description information.
- //For compatibility reasons, DONT MODIFY the existing key values if expanding the set.
- String USERNAME = "Username";
- String RIGHTS_READ_ONLY = "read"; // item deprecated
- String RIGHTS_READ_WRITE = "write"; // item deprecated
- String RIGHTS_ADMIN = "admin"; // item deprecated
-
- List<String> COMPOSITE_ITEM_NAMES = Collections.unmodifiableList(Arrays.asList(USERNAME, RIGHTS_READ_ONLY, RIGHTS_READ_WRITE, RIGHTS_ADMIN));
- List<String> COMPOSITE_ITEM_DESCRIPTIONS = Collections.unmodifiableList(
- Arrays.asList("Broker Login username",
- "Item no longer used",
- "Item no longer used",
- "Item no longer used"));
-
- List<String> TABULAR_UNIQUE_INDEX = Collections.unmodifiableList(Arrays.asList(USERNAME));
-
- //********** Operations *****************//
- /**
- * set password for user.
- *
- * Since Qpid JMX API 1.2 this operation expects plain text passwords to be provided. Prior to this, MD5 hashed passwords were supplied.
- *
- * @deprecated since Qpid JMX API 1.7
- *
- * @param username The username for which the password is to be set
- * @param password The password for the user
- *
- * @return The result of the operation
- */
- @Deprecated
- @MBeanOperation(name = "setPassword", description = "Set password for user.",
- impact = MBeanOperationInfo.ACTION)
- boolean setPassword(@MBeanOperationParameter(name = "username", description = "Username")String username,
- //NOTE: parameter name was changed to 'passwd' in Qpid JMX API 1.7 to protect against older, incompatible management clients
- @MBeanOperationParameter(name = "passwd", description = "Password")char[] password);
-
- /**
- * Set password for a given user.
- *
- * @since Qpid JMX API 1.7
- *
- * @param username The username to create
- * @param password The password for the user
- *
- * @return The result of the operation
- */
- @MBeanOperation(name = "setPassword", description = "Set password for user.",
- impact = MBeanOperationInfo.ACTION)
- boolean setPassword(@MBeanOperationParameter(name = "username", description = "Username")String username,
- @MBeanOperationParameter(name = "password", description = "Password")String password);
-
- /**
- * Set rights for users with given details.
- * Since Qpid JMX API 2.3 all invocations will cause an exception to be thrown
- * as access rights can no longer be maintain via this interface.
- *
- * @deprecated since Qpid JMX API 2.3
- *
- * @param username The username to create
- * @param read The set of permission to give the new user
- * @param write The set of permission to give the new user
- * @param admin The set of permission to give the new user
- *
- * @return The result of the operation
- */
- @Deprecated
- @MBeanOperation(name = "setRights", description = "Set access rights for user.",
- impact = MBeanOperationInfo.ACTION)
- boolean setRights(@MBeanOperationParameter(name = "username", description = "Username")String username,
- @MBeanOperationParameter(name = "read", description = "Administration read")boolean read,
- @MBeanOperationParameter(name = "readAndWrite", description = "Administration write")boolean write,
- @MBeanOperationParameter(name = "admin", description = "Administration rights")boolean admin);
-
- /**
- * Create users with given details.
- * Since Qpid JMX API 2.3 if the user passes true for parameters read, write, or admin, a
- * exception will be thrown as access rights can no longer be maintain via this interface.
- *
- * Since Qpid JMX API 1.2 this operation expects plain text passwords to be provided. Prior to this, MD5 hashed passwords were supplied.
- *
- * @deprecated since Qpid JMX API 1.7
- *
- * @param username The username to create
- * @param password The password for the user
- * @param read The set of permission to give the new user
- * @param write The set of permission to give the new user
- * @param admin The set of permission to give the new user
- *
- * @return true if the user was created successfully, or false otherwise
- */
- @Deprecated
- @MBeanOperation(name = "createUser", description = "Create new user from system.",
- impact = MBeanOperationInfo.ACTION)
- boolean createUser(@MBeanOperationParameter(name = "username", description = "Username")String username,
- //NOTE: parameter name was changed to 'passwd' in Qpid JMX API 1.7 to protect against older, incompatible management clients
- @MBeanOperationParameter(name = "passwd", description = "Password")char[] password,
- @MBeanOperationParameter(name = "read", description = "Administration read")boolean read,
- @MBeanOperationParameter(name = "readAndWrite", description = "Administration write")boolean write,
- @MBeanOperationParameter(name = "admin", description = "Administration rights")boolean admin);
-
- /**
- * Create users with given details.
- * Since Qpid JMX API 2.3 if the user passes true for parameters read, write, or admin, a
- * exception will be thrown as access rights can no longer be maintain via this interface.
- *
- * @deprecated since Qpid JMX API 2.3
- * @since Qpid JMX API 1.7
- *
- * @param username The username to create
- * @param password The password for the user
- * @param read The set of permission to give the new user
- * @param write The set of permission to give the new user
- * @param admin The set of permission to give the new user
- *
- * @return true if the user was created successfully, or false otherwise
- */
- @Deprecated
- @MBeanOperation(name = "createUser", description = "Create a new user.",
- impact = MBeanOperationInfo.ACTION)
- boolean createUser(@MBeanOperationParameter(name = "username", description = "Username")String username,
- @MBeanOperationParameter(name = "password", description = "Password")String password,
- @MBeanOperationParameter(name = "read", description = "Administration read")boolean read,
- @MBeanOperationParameter(name = "readAndWrite", description = "Administration write")boolean write,
- @MBeanOperationParameter(name = "admin", description = "Administration rights")boolean admin);
-
- /**
- * Create users with given details.
- *
- * @since Qpid JMX API 2.3
- *
- * @param username The username to create
- * @param password The password for the user
- *
- * @return true if the user was created successfully, or false otherwise
- */
- @MBeanOperation(name = "createUser", description = "Create a new user.",
- impact = MBeanOperationInfo.ACTION)
- boolean createUser(@MBeanOperationParameter(name = "username", description = "Username")String username,
- @MBeanOperationParameter(name = "password", description = "Password")String password);
-
- /**
- * View users returns all the users that are currently available to the system.
- *
- * @param username The user to delete
- *
- * @return The result of the operation
- */
- @MBeanOperation(name = "deleteUser", description = "Delete user from system.",
- impact = MBeanOperationInfo.ACTION)
- boolean deleteUser(@MBeanOperationParameter(name = "username", description = "Username")String username);
-
-
- /**
- * Reload the date from disk
- *
- * Since Qpid JMX API 1.2 this operation reloads the password and authorisation files. Prior to this, only the authorisation file was reloaded.
- *
- * @return The result of the operation
- */
- @MBeanOperation(name = "reloadData", description = "Reload the authentication and authorisation files from disk.",
- impact = MBeanOperationInfo.ACTION)
- boolean reloadData();
-
- /**
- * View users returns all the users that are currently available to the system.
- *
- * Since Qpid JMX API 2.3 the items that corresponded to read, write and admin flags
- * are deprecated and always return false.
- *
- * @return a table of users data (Username, read, write, admin)
- */
- @MBeanOperation(name = "viewUsers", description = "All users that are currently available to the system.",
- impact = MBeanOperationInfo.INFO)
- TabularData viewUsers();
-
-
-}
diff --git a/java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/annotations/MBeanAttribute.java b/java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/annotations/MBeanAttribute.java
deleted file mode 100644
index 14e7211049..0000000000
--- a/java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/annotations/MBeanAttribute.java
+++ /dev/null
@@ -1,41 +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.management.common.mbeans.annotations;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Inherited;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- * Annotation for MBean attributes. This should be used with getter or setter
- * methods of attributes.
- */
-@Retention(RetentionPolicy.RUNTIME)
-@Target(ElementType.METHOD)
-@Inherited
-public @interface MBeanAttribute
-{
- String name();
- String description();
-}
diff --git a/java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/annotations/MBeanConstructor.java b/java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/annotations/MBeanConstructor.java
deleted file mode 100644
index 3131969813..0000000000
--- a/java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/annotations/MBeanConstructor.java
+++ /dev/null
@@ -1,39 +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.management.common.mbeans.annotations;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Inherited;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- * Annotation for MBean constructors.
- */
-@Retention(RetentionPolicy.RUNTIME)
-@Target(ElementType.CONSTRUCTOR)
-@Inherited
-public @interface MBeanConstructor
-{
- String value();
-}
diff --git a/java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/annotations/MBeanDescription.java b/java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/annotations/MBeanDescription.java
deleted file mode 100644
index d70c7dd8f3..0000000000
--- a/java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/annotations/MBeanDescription.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.management.common.mbeans.annotations;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Inherited;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- * Annotation for MBean class.
- */
-@Retention(RetentionPolicy.RUNTIME)
-@Target(ElementType.TYPE)
-@Inherited
-public @interface MBeanDescription {
- String value();
-}
diff --git a/java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/annotations/MBeanOperation.java b/java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/annotations/MBeanOperation.java
deleted file mode 100644
index c608f64817..0000000000
--- a/java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/annotations/MBeanOperation.java
+++ /dev/null
@@ -1,43 +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.management.common.mbeans.annotations;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Inherited;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-import javax.management.MBeanOperationInfo;
-
-/**
- * Annotation for MBean operations.
- */
-@Retention(RetentionPolicy.RUNTIME)
-@Target(ElementType.METHOD)
-@Inherited
-public @interface MBeanOperation
-{
- String name();
- String description();
- int impact() default MBeanOperationInfo.INFO;
-}
diff --git a/java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/annotations/MBeanOperationParameter.java b/java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/annotations/MBeanOperationParameter.java
deleted file mode 100644
index 25f2d09608..0000000000
--- a/java/management/common/src/main/java/org/apache/qpid/management/common/mbeans/annotations/MBeanOperationParameter.java
+++ /dev/null
@@ -1,37 +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.management.common.mbeans.annotations;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- * Annotation for MBean operation parameters.
- */
-@Retention(RetentionPolicy.RUNTIME)
-@Target(ElementType.PARAMETER)
-public @interface MBeanOperationParameter {
- String name();
- String description();
-}
diff --git a/java/management/common/src/main/java/org/apache/qpid/management/common/sasl/CRAMMD5HashedSaslClientFactory.java b/java/management/common/src/main/java/org/apache/qpid/management/common/sasl/CRAMMD5HashedSaslClientFactory.java
deleted file mode 100644
index be4897d6c4..0000000000
--- a/java/management/common/src/main/java/org/apache/qpid/management/common/sasl/CRAMMD5HashedSaslClientFactory.java
+++ /dev/null
@@ -1,60 +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.management.common.sasl;
-
-import java.util.Map;
-
-import javax.security.auth.callback.CallbackHandler;
-import javax.security.sasl.Sasl;
-import javax.security.sasl.SaslClient;
-import javax.security.sasl.SaslClientFactory;
-import javax.security.sasl.SaslException;
-
-public class CRAMMD5HashedSaslClientFactory implements SaslClientFactory
-{
- /** The name of this mechanism */
- public static final String MECHANISM = "CRAM-MD5-HASHED";
-
- public SaslClient createSaslClient(String[] mechanisms, String authorizationId, String protocol,
- String serverName, Map<String, ?> props, CallbackHandler cbh)
- throws SaslException
- {
- for (int i = 0; i < mechanisms.length; i++)
- {
- if (mechanisms[i].equals(MECHANISM))
- {
- if (cbh == null)
- {
- throw new SaslException("CallbackHandler must not be null");
- }
-
- String[] mechs = {"CRAM-MD5"};
- return Sasl.createSaslClient(mechs, authorizationId, protocol, serverName, props, cbh);
- }
- }
- return null;
- }
-
- public String[] getMechanismNames(Map props)
- {
- return new String[]{MECHANISM};
- }
-}
diff --git a/java/management/common/src/main/java/org/apache/qpid/management/common/sasl/ClientSaslFactory.java b/java/management/common/src/main/java/org/apache/qpid/management/common/sasl/ClientSaslFactory.java
deleted file mode 100644
index ee5803a220..0000000000
--- a/java/management/common/src/main/java/org/apache/qpid/management/common/sasl/ClientSaslFactory.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.management.common.sasl;
-
-import java.util.Map;
-
-import javax.security.auth.callback.CallbackHandler;
-import javax.security.sasl.SaslClient;
-import javax.security.sasl.SaslClientFactory;
-import javax.security.sasl.SaslException;
-
-public class ClientSaslFactory implements SaslClientFactory
-{
- public SaslClient createSaslClient(String[] mechs, String authorizationId, String protocol,
- String serverName, Map props, CallbackHandler cbh)
- throws SaslException
- {
- for (int i = 0; i < mechs.length; i++)
- {
- if (mechs[i].equals("PLAIN"))
- {
- return new PlainSaslClient(authorizationId, cbh);
- }
- }
- return null;
- }
-
- /**
- * Simple-minded implementation that ignores props
- */
- public String[] getMechanismNames(Map props)
- {
- return new String[]{"PLAIN"};
- }
-
-}
diff --git a/java/management/common/src/main/java/org/apache/qpid/management/common/sasl/Constants.java b/java/management/common/src/main/java/org/apache/qpid/management/common/sasl/Constants.java
deleted file mode 100644
index 31010baf8b..0000000000
--- a/java/management/common/src/main/java/org/apache/qpid/management/common/sasl/Constants.java
+++ /dev/null
@@ -1,33 +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.management.common.sasl;
-
-public class Constants
-{
-
- public final static String MECH_CRAMMD5 = "CRAM-MD5";
- public final static String MECH_PLAIN = "PLAIN";
- public final static String SASL_CRAMMD5 = "SASL/CRAM-MD5";
- public final static String SASL_PLAIN = "SASL/PLAIN";
-
-}
-
diff --git a/java/management/common/src/main/java/org/apache/qpid/management/common/sasl/JCAProvider.java b/java/management/common/src/main/java/org/apache/qpid/management/common/sasl/JCAProvider.java
deleted file mode 100644
index f5a3ca8ccc..0000000000
--- a/java/management/common/src/main/java/org/apache/qpid/management/common/sasl/JCAProvider.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.management.common.sasl;
-
-import java.security.Provider;
-import java.util.Map;
-
-import javax.security.sasl.SaslClientFactory;
-
-public class JCAProvider extends Provider
-{
- private static final long serialVersionUID = 1L;
-
- /**
- * Creates the security provider with a map from SASL mechanisms to implementing factories.
- *
- * @param providerMap The map from SASL mechanims to implementing factory classes.
- */
- public JCAProvider(Map<String, Class<? extends SaslClientFactory>> providerMap)
- {
- super("AMQSASLProvider", 1.0, "A JCA provider that registers all "
- + "AMQ SASL providers that want to be registered");
- register(providerMap);
- }
-
- /**
- * Registers client factory classes for a map of mechanism names to client factory classes.
- *
- * @param providerMap The map from SASL mechanims to implementing factory classes.
- */
- private void register(Map<String, Class<? extends SaslClientFactory>> providerMap)
- {
- for (Map.Entry<String, Class<? extends SaslClientFactory>> me : providerMap.entrySet())
- {
- put("SaslClientFactory." + me.getKey(), me.getValue().getName());
- }
- }
-}
diff --git a/java/management/common/src/main/java/org/apache/qpid/management/common/sasl/PlainSaslClient.java b/java/management/common/src/main/java/org/apache/qpid/management/common/sasl/PlainSaslClient.java
deleted file mode 100644
index 806975c32f..0000000000
--- a/java/management/common/src/main/java/org/apache/qpid/management/common/sasl/PlainSaslClient.java
+++ /dev/null
@@ -1,203 +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.management.common.sasl;
-
-import java.io.*;
-import javax.security.auth.callback.*;
-import javax.security.sasl.*;
-
-public class PlainSaslClient implements SaslClient
-{
-
- private boolean completed;
- private CallbackHandler cbh;
- private String authorizationID;
- private String authenticationID;
- private byte password[];
- private static byte SEPARATOR = 0;
-
- public PlainSaslClient(String authorizationID, CallbackHandler cbh) throws SaslException
- {
- completed = false;
- this.cbh = cbh;
- Object[] userInfo = getUserInfo();
- this.authorizationID = authorizationID;
- this.authenticationID = (String) userInfo[0];
- this.password = (byte[]) userInfo[1];
- if (authenticationID == null || password == null)
- {
- throw new SaslException("PLAIN: authenticationID and password must be specified");
- }
- }
-
- public byte[] evaluateChallenge(byte[] challenge) throws SaslException
- {
- if (completed)
- {
- throw new IllegalStateException("PLAIN: authentication already " +
- "completed");
- }
- completed = true;
- try
- {
- byte authzid[] =
- authorizationID == null ? null : authorizationID.getBytes("UTF8");
- byte authnid[] = authenticationID.getBytes("UTF8");
- byte response[] =
- new byte[
- password.length +
- authnid.length +
- 2 + // SEPARATOR
- (authzid != null ? authzid.length : 0)
- ];
- int size = 0;
- if (authzid != null) {
- System.arraycopy(authzid, 0, response, 0, authzid.length);
- size = authzid.length;
- }
- response[size++] = SEPARATOR;
- System.arraycopy(authnid, 0, response, size, authnid.length);
- size += authnid.length;
- response[size++] = SEPARATOR;
- System.arraycopy(password, 0, response, size, password.length);
- clearPassword();
- return response;
- } catch (UnsupportedEncodingException e) {
- throw new SaslException("PLAIN: Cannot get UTF-8 encoding of ids",
- e);
- }
- }
-
- public String getMechanismName()
- {
- return "PLAIN";
- }
-
- public boolean hasInitialResponse()
- {
- return true;
- }
-
- public boolean isComplete()
- {
- return completed;
- }
-
- public byte[] unwrap(byte[] incoming, int offset, int len) throws SaslException
- {
- if (completed) {
- throw new IllegalStateException("PLAIN: this mechanism supports " +
- "neither integrity nor privacy");
- } else {
- throw new IllegalStateException("PLAIN: authentication not " +
- "completed");
- }
- }
-
- public byte[] wrap(byte[] outgoing, int offset, int len) throws SaslException
- {
- if (completed)
- {
- throw new IllegalStateException("PLAIN: this mechanism supports " +
- "neither integrity nor privacy");
- }
- else
- {
- throw new IllegalStateException("PLAIN: authentication not " +
- "completed");
- }
- }
-
- public Object getNegotiatedProperty(String propName)
- {
- if (completed)
- {
- if (propName.equals(Sasl.QOP))
- {
- return "auth";
- }
- else
- {
- return null;
- }
- }
- else
- {
- throw new IllegalStateException("PLAIN: authentication not " +
- "completed");
- }
- }
-
- private void clearPassword()
- {
- if (password != null)
- {
- for (int i = 0 ; i < password.length ; i++)
- {
- password[i] = 0;
- }
- password = null;
- }
- }
-
- public void dispose() throws SaslException
- {
- clearPassword();
- }
-
- protected void finalize()
- {
- clearPassword();
- }
-
- private Object[] getUserInfo() throws SaslException
- {
- try
- {
- final String userPrompt = "PLAIN authentication id: ";
- final String pwPrompt = "PLAIN password: ";
- NameCallback nameCb = new NameCallback(userPrompt);
- PasswordCallback passwordCb = new PasswordCallback(pwPrompt, false);
- cbh.handle(new Callback[] { nameCb, passwordCb });
- String userid = nameCb.getName();
- char pwchars[] = passwordCb.getPassword();
- byte pwbytes[];
- if (pwchars != null)
- {
- pwbytes = (new String(pwchars)).getBytes("UTF8");
- passwordCb.clearPassword();
- }
- else
- {
- pwbytes = null;
- }
- return (new Object[] { userid, pwbytes });
- }
- catch (IOException e)
- {
- throw new SaslException("Cannot get password", e);
- }
- catch (UnsupportedCallbackException e)
- {
- throw new SaslException("Cannot get userid/password", e);
- }
- }
-}
diff --git a/java/management/common/src/main/java/org/apache/qpid/management/common/sasl/SaslProvider.java b/java/management/common/src/main/java/org/apache/qpid/management/common/sasl/SaslProvider.java
deleted file mode 100644
index 1eb44e35df..0000000000
--- a/java/management/common/src/main/java/org/apache/qpid/management/common/sasl/SaslProvider.java
+++ /dev/null
@@ -1,35 +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.management.common.sasl;
-
-import java.security.Provider;
-
-public class SaslProvider extends Provider
-{
- private static final long serialVersionUID = -6978096016899676466L;
-
- public SaslProvider()
- {
- super("SaslClientFactory", 1.0, "SASL PLAIN CLIENT MECHANISM");
- put("SaslClientFactory.PLAIN", "ClientSaslFactory");
- }
-
-}
diff --git a/java/management/common/src/main/java/org/apache/qpid/management/common/sasl/UserPasswordCallbackHandler.java b/java/management/common/src/main/java/org/apache/qpid/management/common/sasl/UserPasswordCallbackHandler.java
deleted file mode 100644
index a1634f86d9..0000000000
--- a/java/management/common/src/main/java/org/apache/qpid/management/common/sasl/UserPasswordCallbackHandler.java
+++ /dev/null
@@ -1,73 +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.management.common.sasl;
-
-import java.io.*;
-import javax.security.auth.callback.*;
-
-public class UserPasswordCallbackHandler implements CallbackHandler
-{
- private String user;
- private char[] pwchars;
-
- public UserPasswordCallbackHandler(String user, String password)
- {
- this.user = user;
- this.pwchars = password.toCharArray();
- }
-
- public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException
- {
- for (int i = 0; i < callbacks.length; i++)
- {
- if (callbacks[i] instanceof NameCallback)
- {
- NameCallback ncb = (NameCallback) callbacks[i];
- ncb.setName(user);
- }
- else if (callbacks[i] instanceof PasswordCallback)
- {
- PasswordCallback pcb = (PasswordCallback) callbacks[i];
- pcb.setPassword(pwchars);
- }
- else
- {
- throw new UnsupportedCallbackException(callbacks[i]);
- }
- }
- }
-
- private void clearPassword()
- {
- if (pwchars != null)
- {
- for (int i = 0 ; i < pwchars.length ; i++)
- {
- pwchars[i] = 0;
- }
- pwchars = null;
- }
- }
-
- protected void finalize()
- {
- clearPassword();
- }
-}
diff --git a/java/management/common/src/main/java/org/apache/qpid/management/common/sasl/UsernameHashedPasswordCallbackHandler.java b/java/management/common/src/main/java/org/apache/qpid/management/common/sasl/UsernameHashedPasswordCallbackHandler.java
deleted file mode 100644
index 09aba1f3e1..0000000000
--- a/java/management/common/src/main/java/org/apache/qpid/management/common/sasl/UsernameHashedPasswordCallbackHandler.java
+++ /dev/null
@@ -1,108 +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.management.common.sasl;
-
-import java.io.IOException;
-import java.io.UnsupportedEncodingException;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-
-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;
-
-
-public class UsernameHashedPasswordCallbackHandler implements CallbackHandler
-{
- private String user;
- private char[] pwchars;
-
- public UsernameHashedPasswordCallbackHandler(String user, String password) throws Exception
- {
- this.user = user;
- this.pwchars = getHash(password);
- }
-
- public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException
- {
- for (int i = 0; i < callbacks.length; i++)
- {
- if (callbacks[i] instanceof NameCallback)
- {
- NameCallback ncb = (NameCallback) callbacks[i];
- ncb.setName(user);
- }
- else if (callbacks[i] instanceof PasswordCallback)
- {
- PasswordCallback pcb = (PasswordCallback) callbacks[i];
- pcb.setPassword(pwchars);
- }
- else
- {
- throw new UnsupportedCallbackException(callbacks[i]);
- }
- }
- }
-
-
- private void clearPassword()
- {
- if (pwchars != null)
- {
- for (int i = 0 ; i < pwchars.length ; i++)
- {
- pwchars[i] = 0;
- }
- pwchars = null;
- }
- }
-
- protected void finalize()
- {
- clearPassword();
- }
-
- public static char[] getHash(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException
- {
- byte[] data = text.getBytes("utf-8");
-
- MessageDigest md = MessageDigest.getInstance("MD5");
-
- for (byte b : data)
- {
- md.update(b);
- }
-
- byte[] digest = md.digest();
-
- char[] hash = new char[digest.length ];
-
- int index = 0;
- for (byte b : digest)
- {
- hash[index++] = (char) b;
- }
-
- return hash;
- }
-}
diff --git a/java/management/common/src/test/java/org/apache/qpid/management/common/mbeans/ManagedQueueTest.java b/java/management/common/src/test/java/org/apache/qpid/management/common/mbeans/ManagedQueueTest.java
deleted file mode 100644
index 1a4a73f207..0000000000
--- a/java/management/common/src/test/java/org/apache/qpid/management/common/mbeans/ManagedQueueTest.java
+++ /dev/null
@@ -1,80 +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.management.common.mbeans;
-
-import java.lang.reflect.InvocationHandler;
-import java.lang.reflect.Method;
-import java.lang.reflect.Proxy;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.management.MBeanAttributeInfo;
-import javax.management.NotCompliantMBeanException;
-import javax.management.StandardMBean;
-
-import junit.framework.TestCase;
-
-public class ManagedQueueTest extends TestCase
-{
- public void testAttributesContants()
- {
- //Construct a test MBeanInfo that matches what we would get from a real
- //MBean using the ManagedQueue management interface. Use this to test
- //that all attributes have a listing in the attribute array constant.
-
- StubInvocationHandler stubIH = new StubInvocationHandler();
- Class<ManagedQueue> mq = ManagedQueue.class;
-
- ManagedQueue impl = mq.cast(Proxy.newProxyInstance(mq.getClassLoader(), new Class<?>[] {mq}, stubIH));
- try
- {
- StandardMBean mbean = new StandardMBean(impl, ManagedQueue.class);
-
- List<String> attributeList = ManagedQueue.QUEUE_ATTRIBUTES;
-
- //retrieve the attributes from the constructed MBeanInfo
- MBeanAttributeInfo[] attributes = mbean.getMBeanInfo().getAttributes();
-
- for(MBeanAttributeInfo info : attributes)
- {
- if(!attributeList.contains(info.getName()))
- {
- fail(mq.getSimpleName() + " attributes constant array does not include the attribute: " + info.getName());
- }
- }
- }
- catch (NotCompliantMBeanException e)
- {
- fail("Unable to create the test proxy mbean to generate the MBeanInfo");
- }
-
- }
-
- private static class StubInvocationHandler implements InvocationHandler
- {
- //invocation handler used to present a stub implementation when generating the StandardMBean
- public Object invoke(Object proxy, Method method, Object[] args)
- {
- return null;
- }
- }
-
-}
diff --git a/java/management/eclipse-plugin/META-INF/MANIFEST.MF b/java/management/eclipse-plugin/META-INF/MANIFEST.MF
deleted file mode 100644
index 2164c5d326..0000000000
--- a/java/management/eclipse-plugin/META-INF/MANIFEST.MF
+++ /dev/null
@@ -1,22 +0,0 @@
-Manifest-Version: 1.0
-Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt
-Bundle-ManifestVersion: 2
-Bundle-Name: Qpid JMX Management Console Plug-in
-Bundle-SymbolicName: org.apache.qpid.management.ui; singleton:=true
-Bundle-Version: 0.11.0
-Bundle-Activator: org.apache.qpid.management.ui.Activator
-Bundle-Vendor: Apache Software Foundation
-Bundle-Localization: plugin
-Require-Bundle: org.eclipse.ui,
- org.eclipse.core.runtime,
- org.eclipse.ui.forms,
- qpid-management-common,
- org.apache.commons.codec;bundle-version="1.3.0"
-Eclipse-LazyStart: true
-Export-Package: org.apache.qpid.management.ui,
- org.apache.qpid.management.ui.actions,
- org.apache.qpid.management.ui.exceptions,
- org.apache.qpid.management.ui.jmx,
- org.apache.qpid.management.ui.model,
- org.apache.qpid.management.ui.sasl,
- org.apache.qpid.management.ui.views
diff --git a/java/management/eclipse-plugin/build-release-common.properties b/java/management/eclipse-plugin/build-release-common.properties
deleted file mode 100644
index 7ccbd750cf..0000000000
--- a/java/management/eclipse-plugin/build-release-common.properties
+++ /dev/null
@@ -1,33 +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.
-#
-#
-
-app.namever=jmx-management-console-${project.version}
-
-artifact.id=org.apache.qpid.management.ui
-mcplugin.version=${project.version}.0
-mcplugin.filename=${artifact.id}_${mcplugin.version}
-
-mcplugin.contents.dir=${module.classes}
-
-mcplugin.manifest=${module.manifest}
-
-jmxremote.sasl.manifest=src/main/resources/jmxremote.sasl-plugin/MANIFEST.MF
-
diff --git a/java/management/eclipse-plugin/build-release-linux-gtk-x86.properties b/java/management/eclipse-plugin/build-release-linux-gtk-x86.properties
deleted file mode 100644
index 51c4bfa8d0..0000000000
--- a/java/management/eclipse-plugin/build-release-linux-gtk-x86.properties
+++ /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.
-#
-#
-
-release.name=${project.name}-${app.namever}-linux-gtk-x86
-
-release.subdir=${module.release.base}/${release.name}
-
-release.tar.gz=${module.release.base}/${release.name}.tar.gz
-
-qpidmc.ini=src/main/resources/linux-gtk-x86/qpidmc.ini
-
-qpidmc.executable=src/main/resources/linux-gtk-x86/qpidmc
-
-qpidmc.companion.library=src/main/resources/linux-gtk-x86/libcairo-swt.so
-
-rcp.libs=${management-eclipse-plugin-linux-gtk-x86.libs}
-
-rcp.configuration.dir=src/main/resources/linux-gtk-x86/Configuration
diff --git a/java/management/eclipse-plugin/build-release-linux-gtk-x86_64.properties b/java/management/eclipse-plugin/build-release-linux-gtk-x86_64.properties
deleted file mode 100644
index bf58d9c08e..0000000000
--- a/java/management/eclipse-plugin/build-release-linux-gtk-x86_64.properties
+++ /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.
-#
-#
-
-release.name=${project.name}-${app.namever}-linux-gtk-x86_64
-
-release.subdir=${module.release.base}/${release.name}
-
-release.tar.gz=${module.release.base}/${release.name}.tar.gz
-
-qpidmc.ini=src/main/resources/linux-gtk-x86_64/qpidmc.ini
-
-qpidmc.executable=src/main/resources/linux-gtk-x86_64/qpidmc
-
-qpidmc.companion.library=src/main/resources/linux-gtk-x86_64/libcairo-swt.so
-
-rcp.libs=${management-eclipse-plugin-linux-gtk-x86_64.libs}
-
-rcp.configuration.dir=src/main/resources/linux-gtk-x86_64/Configuration
diff --git a/java/management/eclipse-plugin/build-release-macosx.properties b/java/management/eclipse-plugin/build-release-macosx.properties
deleted file mode 100644
index bdb2f0d7da..0000000000
--- a/java/management/eclipse-plugin/build-release-macosx.properties
+++ /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.
-#
-#
-
-application.name=Qpid JMX Management Console
-
-application.dir=${application.name}.app
-
-release.name=${project.name}-${app.namever}-macosx
-
-release.subdir=${module.release.base}/${release.name}
-
-release.zip=${module.release.base}/${release.name}.zip
-
-rcp.libs=${management-eclipse-plugin-macosx.libs}
-
-rcp.configuration.dir=src/main/resources/macosx/Configuration
-
-qpidmc.ini=src/main/resources/macosx/Contents/MacOS/qpidmc.ini
-qpidmc.executable=src/main/resources/macosx/Contents/MacOS/qpidmc
-
-eclipse.icns=src/main/resources/macosx/Contents/Resources/Console.icns
-macosx.plist=src/main/resources/macosx/Contents/Info.plist
diff --git a/java/management/eclipse-plugin/build-release-macosx.xml b/java/management/eclipse-plugin/build-release-macosx.xml
deleted file mode 100644
index 2aa63d7f2f..0000000000
--- a/java/management/eclipse-plugin/build-release-macosx.xml
+++ /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.
- -
- -->
-<project name="JMX Management Console MacOSX Binary Release" default="release-bin">
-
- <import file="build-release.xml"/>
-
- <property name="release.app" value="${release.subdir}/${application.dir}"/>
-
- <target name="release-bin-qpid-mc-plugin">
- <available file="${build.lib}/qpid-management-eclipse-plugin-${project.version}.jar" property="management-eclipse-plugin.jar.present"/>
- <fail unless="management-eclipse-plugin.jar.present" message="Please run ant build for the management-eclipse-plugin module"/>
-
- <!-- Copy the qpid management-eclipse-plugin module jar -->
- <copy tofile="${release.app}/plugins/${mcplugin.filename}.jar" flatten="true" failonerror="true">
- <fileset file="${build.lib}/qpid-management-eclipse-plugin-${project.version}.jar"/>
- </copy>
- </target>
-
- <target name="release-bin-jmxremote-plugin">
- <!-- Copy the jmxremote.sasl plugin's manifest, creating its plugin directory -->
- <copy todir="${release.app}/plugins/jmxremote.sasl_1.0.1/META-INF" flatten="true" failonerror="true">
- <fileset file="${jmxremote.sasl.manifest}"/>
- </copy>
- </target>
-
- <target name="release-bin-qpid-management-common-plugin">
- <available file="${build.lib}/qpid-management-common_${project.version}.0.osgi.jar" property="management-common.jar.present"/>
- <fail unless="management-common.jar.present" message="Please run ant bundle for the management-common module"/>
-
- <!-- Copy the qpid-management-common module osgi jar -->
- <copy todir="${release.app}/plugins" flatten="true" failonerror="true">
- <fileset file="${build.lib}/qpid-management-common_${project.version}.0.osgi.jar"/>
- </copy>
- </target>
-
-
- <target name="release-bin-rcp-deps" description="copy eclipse-rcp dependencies into module release">
-
- <!-- Copy Eclipse binary and start-up files -->
- <copy todir="${release.app}/Contents/MacOS" flatten="true" failonerror="true">
- <fileset file="${qpidmc.ini}"/>
- <fileset file="${qpidmc.executable}"/>
- </copy>
-
- <chmod dir="${release.app}/Contents/MacOS" perm="u+rx" includes="**/*"/>
-
- <!-- Copy MacOS plist file -->
- <copy todir="${release.app}/Contents" flatten="true" failonerror="true">
- <fileset file="${macosx.plist}"/>
- </copy>
-
- <!-- Copy Icns icon file -->
- <copy todir="${release.app}/Contents/Resources" flatten="true" failonerror="true">
- <fileset file="${eclipse.icns}"/>
- </copy>
-
- <!-- Copy the eclipse rcp module libs -->
- <copy todir="${release.app}/plugins" failonerror="true">
- <fileset dir="${project.root}" includes="${rcp.libs}"/>
- <globmapper from="lib${file.separator}*" to="*"/>
- </copy>
-
- <!-- Copy the relevant configuration dir -->
- <copy todir="${release.app}/Configuration" failonerror="true">
- <fileset dir="${rcp.configuration.dir}"/>
- </copy>
- <chmod dir="${release.app}/Configuration" perm="ugo+r" includes="**/*"/>
- </target>
-
- <target name="release-bin-zip" if="release.zip" description="build mc zip archive">
-
- <zip destfile="${release.zip}">
- <zipfileset dir="${release.subdir}" filemode="755">
- <include name="${application.dir}/Contents/MacOS/**"/>
- </zipfileset>
-
- <zipfileset dir="${release.subdir}" filemode="644" dirmode="755">
- <exclude name="${application.dir}/Contents/MacOS/**"/>
- </zipfileset>
- </zip>
- </target>
-
-</project>
diff --git a/java/management/eclipse-plugin/build-release-solaris-gtk-sparc.properties b/java/management/eclipse-plugin/build-release-solaris-gtk-sparc.properties
deleted file mode 100644
index d58d0c9ac0..0000000000
--- a/java/management/eclipse-plugin/build-release-solaris-gtk-sparc.properties
+++ /dev/null
@@ -1,39 +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.
-#
-#
-
-release.name=${project.name}-${app.namever}-solaris-gtk-sparc
-
-release.subdir=${module.release.base}/${release.name}
-
-release.tar.gz=${module.release.base}/${release.name}.tar.gz
-
-qpidmc.ini=src/main/resources/solaris-gtk-sparc/qpidmc.ini
-
-qpidmc.solaris.xpm.files=src/main/resources/solaris-gtk-sparc/Qpidmc.l.pm \
- src/main/resources/solaris-gtk-sparc/Qpidmc.m.pm \
- src/main/resources/solaris-gtk-sparc/Qpidmc.s.pm \
- src/main/resources/solaris-gtk-sparc/Qpidmc.t.pm
-
-qpidmc.executable=src/main/resources/solaris-gtk-sparc/qpidmc
-
-rcp.libs=${management-eclipse-plugin-solaris-gtk-sparc.libs}
-
-rcp.configuration.dir=src/main/resources/solaris-gtk-sparc/Configuration
diff --git a/java/management/eclipse-plugin/build-release-win32-win32-x86.properties b/java/management/eclipse-plugin/build-release-win32-win32-x86.properties
deleted file mode 100644
index ee678a92c9..0000000000
--- a/java/management/eclipse-plugin/build-release-win32-win32-x86.properties
+++ /dev/null
@@ -1,34 +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.
-#
-#
-
-release.name=${project.name}-${app.namever}-win32-win32-x86
-
-release.subdir=${module.release.base}/${release.name}
-
-release.zip=${module.release.base}/${release.name}.zip
-
-qpidmc.executable=src/main/resources/win32-win32-x86/qpidmc.exe
-
-qpidmc.ini=src/main/resources/win32-win32-x86/qpidmc.ini
-
-rcp.libs=${management-eclipse-plugin-win32-win32-x86.libs}
-
-rcp.configuration.dir=src/main/resources/win32-win32-x86/Configuration
diff --git a/java/management/eclipse-plugin/build-release.xml b/java/management/eclipse-plugin/build-release.xml
deleted file mode 100644
index dec4cd5f32..0000000000
--- a/java/management/eclipse-plugin/build-release.xml
+++ /dev/null
@@ -1,172 +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.
- -
- -->
-<project name="JMX Management Console Binary Release" default="release-bin">
-
- <!-- check properties that must be set by caller -->
- <target name="check" description="ensure all required properties are set">
- <condition property="properties.set">
- <and>
- <!-- common properties -->
- <isset property ="mcplugin.filename"/>
- <isset property ="jmxremote.sasl.manifest"/>
- <!-- platform specific properties -->
- <isset property ="qpidmc.ini"/>
- <isset property ="qpidmc.executable"/>
- <isset property ="release.name"/>
- <isset property ="release.subdir"/>
- <isset property ="rcp.libs"/>
- <isset property ="rcp.configuration.dir"/>
- <or>
- <isset property ="release.zip"/>
- <isset property ="release.tar.gz"/>
- </or>
- </and>
- <!-- Optional Properties:
-
- For linux libcairo-swt.so file:
- qpidmc.companion.library
-
- For solaris .xpm files:
- qpidmc.solaris.xpm.files
-
- -->
- </condition>
-
- <fail unless="properties.set" message="some required properties were not set"/>
- </target>
-
- <target name="release-bin-prepare">
- <mkdir dir="${release.subdir}"/>
- </target>
-
- <target name="release-bin-qpid-mc-plugin">
- <available file="${build.lib}/qpid-management-eclipse-plugin-${project.version}.jar" property="management-eclipse-plugin.jar.present"/>
- <fail unless="management-eclipse-plugin.jar.present" message="Please run ant build for the management-eclipse-plugin module"/>
-
- <!-- Copy the qpid management-eclipse-plugin module jar -->
- <copy tofile="${release.subdir}/plugins/${mcplugin.filename}.jar" flatten="true" failonerror="true">
- <fileset file="${build.lib}/qpid-management-eclipse-plugin-${project.version}.jar"/>
- </copy>
- </target>
-
- <target name="release-bin-jmxremote-plugin">
- <!-- Copy the jmxremote.sasl plugin's manifest, creating its plugin directory -->
- <copy todir="${release.subdir}/plugins/jmxremote.sasl_1.0.1/META-INF" flatten="true" failonerror="true">
- <fileset file="${jmxremote.sasl.manifest}"/>
- </copy>
- </target>
-
- <target name="release-bin-qpid-management-common-plugin">
- <available file="${build.lib}/qpid-management-common_${project.version}.0.osgi.jar" property="management-common.jar.present"/>
- <fail unless="management-common.jar.present" message="Please run ant bundle for the management-common module"/>
-
- <!-- Copy the qpid-management-common module osgi jar -->
- <copy todir="${release.subdir}/plugins" failonerror="true">
- <fileset file="${build.lib}/qpid-management-common_${project.version}.0.osgi.jar"/>
- </copy>
- </target>
-
- <target name="release-bin-executable-companion-library" if="qpidmc.companion.library">
- <!-- Copy the rcp executable companion library file -->
- <copy todir="${release.subdir}" flatten="true" failonerror="true">
- <fileset file="${qpidmc.companion.library}"/>
- </copy>
- </target>
-
- <target name="release-bin-executable-solaris-xpm-files" if="qpidmc.solaris.xpm.files">
- <!-- Copy the solaris xpm files -->
- <copy todir="${release.subdir}" flatten="true" failonerror="true">
- <fileset dir="${basedir}" includes="${qpidmc.solaris.xpm.files}"/>
- </copy>
- </target>
-
- <target name="release-bin-rcp-deps" description="copy eclipse-rcp dependencies into module release"
- depends="release-bin-executable-companion-library, release-bin-executable-solaris-xpm-files">
-
- <!-- Copy the rcp executable file -->
- <copy todir="${release.subdir}" flatten="true" failonerror="true">
- <fileset file="${qpidmc.executable}"/>
- </copy>
- <chmod dir="${release.subdir}" perm="u+rx" includes="qpidmc*"/>
-
- <!-- Copy remaining startup & license files -->
- <copy todir="${release.subdir}" flatten="true" failonerror="true">
- <fileset file="${qpidmc.ini}"/>
- </copy>
-
- <!-- Copy the rcp module libs -->
- <copy todir="${release.subdir}/plugins" failonerror="true">
- <fileset dir="${project.root}" includes="${rcp.libs}"/>
- <globmapper from="lib${file.separator}*" to="*"/>
- </copy>
-
- <!-- Copy the relevant configuration dir -->
- <copy todir="${release.subdir}/configuration" failonerror="true">
- <fileset dir="${rcp.configuration.dir}"/>
- </copy>
- <chmod dir="${release.subdir}/configuration" perm="ugo+r" includes="**/*"/>
- </target>
-
- <target name="release-bin-zip" if="release.zip" description="build mc zip archive">
- <zip destfile="${release.zip}">
- <zipfileset dir="${release.subdir}" prefix="${release.name}" filemode="755">
- <include name="qpidmc*"/>
- <exclude name="qpidmc.ini"/>
- </zipfileset>
-
- <zipfileset dir="${release.subdir}" prefix="${release.name}" filemode="644">
- <include name="qpidmc.ini"/>
- </zipfileset>
-
- <zipfileset dir="${release.subdir}" prefix="${release.name}" filemode="644" dirmode="755">
- <exclude name="qpidmc*"/>
- </zipfileset>
- </zip>
- </target>
-
- <target name="release-bin-gzip" if="release.tar.gz" description="build mc tar.gz archive">
- <tar destfile="${release.tar.gz}" longfile="gnu" compression="gzip">
- <tarfileset dir="${release.subdir}" prefix="${release.name}" filemode="755">
- <include name="qpidmc*"/>
- <exclude name="qpidmc.ini"/>
- </tarfileset>
-
- <tarfileset dir="${release.subdir}" prefix="${release.name}" filemode="644">
- <include name="qpidmc.ini"/>
- </tarfileset>
-
- <tarfileset dir="${release.subdir}" prefix="${release.name}" filemode="644" dirmode="755">
- <exclude name="qpidmc*"/>
- </tarfileset>
- </tar>
- </target>
-
- <target name="release-bin-resources" description="copy project resources into module release">
- <copy todir="${release.subdir}" failonerror="false" flatten="true">
- <fileset dir="${resources}" excludes="META-INF"/>
- </copy>
- </target>
-
- <!-- override imported module.xml release-bin target -->
- <target name="release-bin" depends="check,release-bin-prepare,release-bin-rcp-deps,release-bin-resources,
- release-bin-qpid-mc-plugin,release-bin-qpid-management-common-plugin,release-bin-jmxremote-plugin,release-bin-zip,release-bin-gzip"/>
-
-</project>
diff --git a/java/management/eclipse-plugin/build.xml b/java/management/eclipse-plugin/build.xml
deleted file mode 100644
index 527fc1cd09..0000000000
--- a/java/management/eclipse-plugin/build.xml
+++ /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.
- -
- -->
-<project name="Eclipse Plugin" default="build">
-
- <property name="module.depends" value="broker common management/common"/>
- <property name="module.test.depends" value="broker/test common/test" />
-
- <import file="../../module.xml"/>
-
- <!-- module.manifest property to invoke use of 'jar.manifest' jar target when building -->
- <property name="module.manifest" value="${module.classes}/META-INF/MANIFEST.MF"/>
-
- <!-- override module.xml 'libs' target, avoids cluttering the 'build/lib' dir as the
- MC build/packaging process does not use the libs from there -->
- <target name="libs"/>
-
- <target name="copy-plugin-files" description="copy eclipse management plugin files into build tree">
- <copy todir="${module.classes}/icons" failonerror="true">
- <fileset dir="icons/"/>
- </copy>
- <copy todir="${module.classes}/META-INF/" failonerror="true">
- <fileset dir="META-INF/"/>
- </copy>
- <copy todir="${module.classes}" failonerror="true">
- <fileset file="icons/splash.bmp"/>
- </copy>
- <copy todir="${module.classes}" failonerror="true">
- <fileset file="plugin.properties"/>
- </copy>
- <copy todir="${module.classes}" failonerror="true">
- <fileset file="plugin.xml"/>
- </copy>
- </target>
-
- <target name="precompile" depends="copy-plugin-files, create-version" />
-
- <!-- Override imported module.xml release-bin target -->
- <target name="release-bin" depends="build">
- <!-- linux gtk x86 -->
- <ant antfile="build-release.xml">
- <property file="build-release-common.properties"/>
- <property file="build-release-linux-gtk-x86.properties"/>
- </ant>
-
- <!-- linux gtk x86_64 -->
- <ant antfile="build-release.xml">
- <property file="build-release-common.properties"/>
- <property file="build-release-linux-gtk-x86_64.properties"/>
- </ant>
-
- <!-- solaris gtk sparc -->
- <ant antfile="build-release.xml">
- <property file="build-release-common.properties"/>
- <property file="build-release-solaris-gtk-sparc.properties"/>
- </ant>
-
- <!-- mac os x -->
- <ant antfile="build-release-macosx.xml">
- <property file="build-release-common.properties"/>
- <property file="build-release-macosx.properties"/>
- </ant>
-
- <!-- win32 win32 x86 -->
- <ant antfile="build-release.xml">
- <property file="build-release-common.properties"/>
- <property file="build-release-win32-win32-x86.properties"/>
- </ant>
- </target>
-
-</project>
diff --git a/java/management/eclipse-plugin/icons/add.gif b/java/management/eclipse-plugin/icons/add.gif
deleted file mode 100644
index 252d7ebcb8..0000000000
--- a/java/management/eclipse-plugin/icons/add.gif
+++ /dev/null
Binary files differ
diff --git a/java/management/eclipse-plugin/icons/back.gif b/java/management/eclipse-plugin/icons/back.gif
deleted file mode 100644
index d3a10077a5..0000000000
--- a/java/management/eclipse-plugin/icons/back.gif
+++ /dev/null
Binary files differ
diff --git a/java/management/eclipse-plugin/icons/configuration_management.gif b/java/management/eclipse-plugin/icons/configuration_management.gif
deleted file mode 100644
index d11c996e57..0000000000
--- a/java/management/eclipse-plugin/icons/configuration_management.gif
+++ /dev/null
Binary files differ
diff --git a/java/management/eclipse-plugin/icons/delete.gif b/java/management/eclipse-plugin/icons/delete.gif
deleted file mode 100644
index 6f647666d3..0000000000
--- a/java/management/eclipse-plugin/icons/delete.gif
+++ /dev/null
Binary files differ
diff --git a/java/management/eclipse-plugin/icons/failure.gif b/java/management/eclipse-plugin/icons/failure.gif
deleted file mode 100644
index 9b048d6053..0000000000
--- a/java/management/eclipse-plugin/icons/failure.gif
+++ /dev/null
Binary files differ
diff --git a/java/management/eclipse-plugin/icons/icon_ClosedFolder.gif b/java/management/eclipse-plugin/icons/icon_ClosedFolder.gif
deleted file mode 100644
index beb6ed134c..0000000000
--- a/java/management/eclipse-plugin/icons/icon_ClosedFolder.gif
+++ /dev/null
Binary files differ
diff --git a/java/management/eclipse-plugin/icons/icon_OpenFolder.gif b/java/management/eclipse-plugin/icons/icon_OpenFolder.gif
deleted file mode 100644
index a9c777343c..0000000000
--- a/java/management/eclipse-plugin/icons/icon_OpenFolder.gif
+++ /dev/null
Binary files differ
diff --git a/java/management/eclipse-plugin/icons/logging_management.gif b/java/management/eclipse-plugin/icons/logging_management.gif
deleted file mode 100644
index 7f5fe98a73..0000000000
--- a/java/management/eclipse-plugin/icons/logging_management.gif
+++ /dev/null
Binary files differ
diff --git a/java/management/eclipse-plugin/icons/mbean_view.png b/java/management/eclipse-plugin/icons/mbean_view.png
deleted file mode 100644
index 9871b72bb8..0000000000
--- a/java/management/eclipse-plugin/icons/mbean_view.png
+++ /dev/null
Binary files differ
diff --git a/java/management/eclipse-plugin/icons/notifications.gif b/java/management/eclipse-plugin/icons/notifications.gif
deleted file mode 100644
index f1e585bdf7..0000000000
--- a/java/management/eclipse-plugin/icons/notifications.gif
+++ /dev/null
Binary files differ
diff --git a/java/management/eclipse-plugin/icons/qpidConnections.gif b/java/management/eclipse-plugin/icons/qpidConnections.gif
deleted file mode 100644
index 17f927e9a4..0000000000
--- a/java/management/eclipse-plugin/icons/qpidConnections.gif
+++ /dev/null
Binary files differ
diff --git a/java/management/eclipse-plugin/icons/qpidmc.gif b/java/management/eclipse-plugin/icons/qpidmc.gif
deleted file mode 100644
index baf929fbc5..0000000000
--- a/java/management/eclipse-plugin/icons/qpidmc.gif
+++ /dev/null
Binary files differ
diff --git a/java/management/eclipse-plugin/icons/qpidmc16.gif b/java/management/eclipse-plugin/icons/qpidmc16.gif
deleted file mode 100644
index 4df535bb9a..0000000000
--- a/java/management/eclipse-plugin/icons/qpidmc16.gif
+++ /dev/null
Binary files differ
diff --git a/java/management/eclipse-plugin/icons/qpidmc32.bmp b/java/management/eclipse-plugin/icons/qpidmc32.bmp
deleted file mode 100644
index e42ce01dff..0000000000
--- a/java/management/eclipse-plugin/icons/qpidmc32.bmp
+++ /dev/null
Binary files differ
diff --git a/java/management/eclipse-plugin/icons/qpidmc32.gif b/java/management/eclipse-plugin/icons/qpidmc32.gif
deleted file mode 100644
index e42ce01dff..0000000000
--- a/java/management/eclipse-plugin/icons/qpidmc32.gif
+++ /dev/null
Binary files differ
diff --git a/java/management/eclipse-plugin/icons/reconnect.gif b/java/management/eclipse-plugin/icons/reconnect.gif
deleted file mode 100644
index e2f8c3e1fe..0000000000
--- a/java/management/eclipse-plugin/icons/reconnect.gif
+++ /dev/null
Binary files differ
diff --git a/java/management/eclipse-plugin/icons/refresh.gif b/java/management/eclipse-plugin/icons/refresh.gif
deleted file mode 100644
index 1b724a6784..0000000000
--- a/java/management/eclipse-plugin/icons/refresh.gif
+++ /dev/null
Binary files differ
diff --git a/java/management/eclipse-plugin/icons/server_information.gif b/java/management/eclipse-plugin/icons/server_information.gif
deleted file mode 100644
index 716df436f9..0000000000
--- a/java/management/eclipse-plugin/icons/server_information.gif
+++ /dev/null
Binary files differ
diff --git a/java/management/eclipse-plugin/icons/splash.bmp b/java/management/eclipse-plugin/icons/splash.bmp
deleted file mode 100644
index cf3b93d523..0000000000
--- a/java/management/eclipse-plugin/icons/splash.bmp
+++ /dev/null
Binary files differ
diff --git a/java/management/eclipse-plugin/icons/stop.gif b/java/management/eclipse-plugin/icons/stop.gif
deleted file mode 100644
index dc47edf069..0000000000
--- a/java/management/eclipse-plugin/icons/stop.gif
+++ /dev/null
Binary files differ
diff --git a/java/management/eclipse-plugin/icons/success.gif b/java/management/eclipse-plugin/icons/success.gif
deleted file mode 100644
index 9cacb96dca..0000000000
--- a/java/management/eclipse-plugin/icons/success.gif
+++ /dev/null
Binary files differ
diff --git a/java/management/eclipse-plugin/icons/user_management.gif b/java/management/eclipse-plugin/icons/user_management.gif
deleted file mode 100644
index d28c326dea..0000000000
--- a/java/management/eclipse-plugin/icons/user_management.gif
+++ /dev/null
Binary files differ
diff --git a/java/management/eclipse-plugin/icons/virtualhost_manager.gif b/java/management/eclipse-plugin/icons/virtualhost_manager.gif
deleted file mode 100644
index e7ec2a1544..0000000000
--- a/java/management/eclipse-plugin/icons/virtualhost_manager.gif
+++ /dev/null
Binary files differ
diff --git a/java/management/eclipse-plugin/plugin.properties b/java/management/eclipse-plugin/plugin.properties
deleted file mode 100644
index 8507441886..0000000000
--- a/java/management/eclipse-plugin/plugin.properties
+++ /dev/null
@@ -1,20 +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.
-###############################################################################
-pluginName = Qpid Management Console Plug-in
-providerName = Apache Software Foundation \ No newline at end of file
diff --git a/java/management/eclipse-plugin/plugin.xml b/java/management/eclipse-plugin/plugin.xml
deleted file mode 100644
index e151456fa1..0000000000
--- a/java/management/eclipse-plugin/plugin.xml
+++ /dev/null
@@ -1,225 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<?eclipse version="3.2"?>
-<!--
- 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.
--->
-<plugin>
-
- <extension
- id="application"
- point="org.eclipse.core.runtime.applications">
- <application>
- <run
- class="org.apache.qpid.management.ui.Application">
- </run>
- </application>
- </extension>
- <extension
- point="org.eclipse.ui.perspectives">
- <perspective
- name="Qpid Management"
- icon="icons/mbean_view.png"
- class="org.apache.qpid.management.ui.Perspective"
- id="org.apache.qpid.management.ui.perspective">
- </perspective>
- </extension>
- <extension
- point="org.eclipse.ui.views">
- <category
- id="org.apache.qpid.management.ui.viewcategory"
- name="Qpid Management Console"/>
- <view
- allowMultiple="false"
- category="org.apache.qpid.management.ui.viewcategory"
- class="org.apache.qpid.management.ui.views.NavigationView"
- icon="icons/qpidConnections.gif"
- id="org.apache.qpid.management.ui.navigationView"
- name="Qpid Connections">
- </view>
- <view
- allowMultiple="false"
- category="org.apache.qpid.management.ui.viewcategory"
- class="org.apache.qpid.management.ui.views.MBeanView"
- icon="icons/mbean_view.png"
- id="org.apache.qpid.management.ui.mbeanView"
- name="Qpid Management">
- </view>
- </extension>
- <extension
- point="org.eclipse.ui.commands">
- <category
- name="qpid.manager.commands"
- id="org.apache.qpid.management.ui.category">
- </category>
- <command
- name="New Connection"
- description="Created a new Qpid server connection"
- categoryId="org.apache.qpid.management.ui.category"
- id="org.apache.qpid.management.ui.actions.cmd_add">
- </command>
- <command
- categoryId="org.apache.qpid.management.ui.category"
- description="Reconnect the Qpid server connection"
- id="org.apache.qpid.management.ui.actions.cmd_reconnect"
- name="Reconnect"/>
- <command
- categoryId="org.apache.qpid.management.ui.category"
- description="Disconnects the Qpid server connection"
- id="org.apache.qpid.management.ui.actions.cmd_disconnect"
- name="Disconnect"/>
- <command
- categoryId="org.apache.qpid.management.ui.category"
- description="Removes the server from management console"
- id="org.apache.qpid.management.ui.actions.cmd_remove"
- name="Remove Connection"/>
- <command
- categoryId="org.apache.qpid.management.ui.category"
- description="refreshes the views"
- id="org.apache.qpid.management.ui.actions.cmd_refresh"
- name="Refresh"/>
- <command
- categoryId="org.apache.qpid.management.ui.category"
- description="About Qpid Management Console"
- id="qpidmc.about"
- name="About"/>
- </extension>
- <extension
- point="org.eclipse.ui.bindings">
- <key
- commandId="org.apache.qpid.management.ui.actions.cmd_add"
- schemeId="org.eclipse.ui.defaultAcceleratorConfiguration"
- sequence="CTRL+Alt+N">
- </key>
- <key
- commandId="org.apache.qpid.management.ui.actions.cmd_reconnect"
- schemeId="org.eclipse.ui.defaultAcceleratorConfiguration"
- sequence="CTRL+Alt+C"/>
- <key
- commandId="org.apache.qpid.management.ui.actions.cmd_disconnect"
- schemeId="org.eclipse.ui.defaultAcceleratorConfiguration"
- sequence="CTRL+Alt+D">
- </key>
- <key
- commandId="org.apache.qpid.management.ui.actions.cmd_remove"
- schemeId="org.eclipse.ui.defaultAcceleratorConfiguration"
- sequence="CTRL+Alt+R"/>
- <key
- commandId="org.apache.qpid.management.ui.actions.cmd_refresh"
- schemeId="org.eclipse.ui.defaultAcceleratorConfiguration"
- sequence="CTRL+Alt+F5"/>
- <key
- commandId="org.eclipse.ui.file.exit"
- schemeId="org.eclipse.ui.defaultAcceleratorConfiguration"
- sequence="CTRL+Alt+X">
- </key>
- </extension>
-
- <extension
- id="product"
- point="org.eclipse.core.runtime.products">
- <product
- application="org.apache.qpid.management.ui.application"
- name="Qpid Management Console">
- <property
- name="windowImages"
- value="icons/qpidmc16.gif,icons/qpidmc32.gif">
- </property>
- <property
- name="aboutText"
- value="Qpid Management Console"/>
- </product>
- </extension>
-
- <extension point="org.eclipse.ui.menus">
- <menuContribution locationURI="toolbar:org.eclipse.ui.main.toolbar?after=additions">
- <toolbar id="qpidMC">
- <separator name="qpidActionsGroup" visible="false"/>
- <separator name="refresh" visible="true"/>
- <separator name="refresh2" visible="false"/>
- <separator name="additions" visible="false"/>
- </toolbar>
- </menuContribution>
- <menuContribution locationURI="toolbar:qpidMC?after=refresh">
- <control
- class="org.apache.qpid.management.ui.RefreshIntervalComboPanel">
- </control>
- </menuContribution>
- </extension>
-
- <extension
- point="org.eclipse.ui.actionSets">
- <actionSet
- id="org.apache.qpid.management.ui.actionSet"
- label="Qpid Action Set"
- visible="true">
- <menu
- id="qpidmanager"
- label="&amp;Qpid Manager">
- <separator name="qpidActionsGroup"/>
- </menu>
- <action
- class="org.apache.qpid.management.ui.actions.Refresh"
- definitionId="org.apache.qpid.management.ui.actions.cmd_refresh"
- icon="icons/refresh.gif"
- id="org.apache.qpid.management.ui.actions.refresh"
- label="Refresh"
- menubarPath="qpidmanager/additions"
- style="push"
- toolbarPath="qpidMC/refresh2"
- tooltip="Refresh Now"/>
- <action
- class="org.apache.qpid.management.ui.actions.RemoveServer"
- definitionId="org.apache.qpid.management.ui.actions.cmd_remove"
- icon="icons/delete.gif"
- id="org.apache.qpid.management.ui.actions.remove"
- label="Remove Connection"
- menubarPath="qpidmanager/additions"
- style="push"
- toolbarPath="qpidMC/qpidActionsGroup"
- tooltip="Remove Server"/>
- <action
- class="org.apache.qpid.management.ui.actions.CloseConnection"
- definitionId="org.apache.qpid.management.ui.actions.cmd_disconnect"
- icon="icons/stop.gif"
- id="org.apache.qpid.management.ui.disconnect"
- label="Disconnect"
- menubarPath="qpidmanager/additions"
- toolbarPath="qpidMC/qpidActionsGroup"
- tooltip="Disconnect"/>
- <action
- class="org.apache.qpid.management.ui.actions.ReconnectServer"
- definitionId="org.apache.qpid.management.ui.actions.cmd_reconnect"
- icon="icons/reconnect.gif"
- id="org.apache.qpid.management.ui.reconnect"
- label="Reconnect"
- menubarPath="qpidmanager/additions"
- toolbarPath="qpidMC/qpidActionsGroup"
- tooltip="Reconnect"/>
- <action
- class="org.apache.qpid.management.ui.actions.AddServer"
- definitionId="org.apache.qpid.management.ui.actions.cmd_add"
- icon="icons/add.gif"
- id="org.apache.qpid.management.ui.add"
- label="New Connection"
- menubarPath="qpidmanager/additions"
- toolbarPath="qpidMC/qpidActionsGroup"
- tooltip="New Connection"/>
- </actionSet>
- </extension>
-
-</plugin>
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/Activator.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/Activator.java
deleted file mode 100644
index d6a9c0b0c6..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/Activator.java
+++ /dev/null
@@ -1,83 +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.management.ui;
-
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.ui.plugin.AbstractUIPlugin;
-import org.osgi.framework.BundleContext;
-
-/**
- * The activator class controls the plug-in life cycle
- * @author Bhupendra Bhardwaj
- */
-public class Activator extends AbstractUIPlugin
-{
- // The plug-in ID
- public static final String PLUGIN_ID = "org.apache.qpid.management.ui";
-
- // The shared instance
- private static final Activator PLUGIN = new Activator();
-
- /**
- * The constructor
- */
- public Activator()
- {
-
- }
-
- /*
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
- */
- public void start(BundleContext context) throws Exception
- {
- super.start(context);
- }
-
- /*
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
- */
- public void stop(BundleContext context) throws Exception
- {
- super.stop(context);
- }
-
- /**
- * Returns the shared instance
- *
- * @return the shared instance
- */
- public static Activator getDefault()
- {
- return PLUGIN;
- }
-
- /**
- * Returns an image descriptor for the image file at the given plug-in relative path
- *
- * @param path the path
- * @return the image descriptor
- */
- public static ImageDescriptor getImageDescriptor(String path)
- {
- return imageDescriptorFromPlugin(PLUGIN_ID, path);
- }
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ApiVersion.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ApiVersion.java
deleted file mode 100644
index 2bdcd77f08..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ApiVersion.java
+++ /dev/null
@@ -1,110 +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.management.ui;
-
-public class ApiVersion
-{
- private int major;
- private int minor;
-
- public ApiVersion(int major, int minor)
- {
- this.major = major;
- this.minor = minor;
- }
-
- public int getMajor()
- {
- return major;
- }
-
- public int getMinor()
- {
- return minor;
- }
-
- public boolean greaterThanOrEqualTo(int major, int minor)
- {
- if((this.major == major) && (this.minor >= minor))
- {
- return true;
- }
- else if (this.major > major)
- {
- return true;
- }
-
- return false;
- }
-
- public boolean lessThanOrEqualTo(int major, int minor)
- {
- if((this.major == major) && (this.minor <= minor))
- {
- return true;
- }
- else if (this.major < major)
- {
- return true;
- }
-
- return false;
- }
-
- public boolean greaterThan(int major, int minor)
- {
- if(this.major > major)
- {
- return true;
- }
- else if ((this.major == major) && (this.minor > minor))
- {
- return true;
- }
-
- return false;
- }
-
- public boolean lessThan(int major, int minor)
- {
- if(this.major < major)
- {
- return true;
- }
- else if ((this.major == major) && (this.minor < minor))
- {
- return true;
- }
-
- return false;
- }
-
- public boolean equals(int major, int minor)
- {
- return (this.major == major) && (this.minor == minor);
- }
-
- public String toString()
- {
- return "major=" + major + ",minor=" + minor;
- }
-
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/Application.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/Application.java
deleted file mode 100644
index a1c4b7ddb0..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/Application.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.management.ui;
-
-import org.eclipse.core.runtime.IPlatformRunnable;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.PlatformUI;
-
-/**
- * This class controls all aspects of the application's execution
- * @author Bhupendra Bhardwaj
- */
-public class Application implements IPlatformRunnable
-{
- static Shell shell = null;
-
- /*
- * The call to createAndRunWorkbench will not return until the workbench is closed.
- * The SWT event loop and other low-level logistics are handled inside this method.
- * @see org.eclipse.core.runtime.IPlatformRunnable#run(java.lang.Object)
- */
- public Object run(Object args) throws Exception
- {
- Display display = PlatformUI.createDisplay();
- try
- {
- int returnCode = PlatformUI.createAndRunWorkbench(display,
- new ApplicationWorkbenchAdvisor());
- if (returnCode == PlatformUI.RETURN_RESTART)
- {
- return IPlatformRunnable.EXIT_RESTART;
- }
- return IPlatformRunnable.EXIT_OK;
- } finally
- {
- display.dispose();
- }
- }
-
- static Shell getActiveShell()
- {
- return shell;
- }
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ApplicationActionBarAdvisor.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ApplicationActionBarAdvisor.java
deleted file mode 100644
index b5c1b5074a..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ApplicationActionBarAdvisor.java
+++ /dev/null
@@ -1,96 +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.management.ui;
-
-import org.apache.qpid.management.ui.actions.VersionAction;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.GroupMarker;
-import org.eclipse.jface.action.ICoolBarManager;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.ui.IWorkbenchActionConstants;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.actions.ActionFactory;
-import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction;
-import org.eclipse.ui.application.ActionBarAdvisor;
-import org.eclipse.ui.application.IActionBarConfigurer;
-
-/**
- * An action bar advisor is responsible for creating, adding, and disposing of the
- * actions added to a workbench window. Each window will be populated with
- * new actions.
- */
-public class ApplicationActionBarAdvisor extends ActionBarAdvisor
-{
-
- // Actions - important to allocate these only in makeActions, and then use them
- // in the fill methods. This ensures that the actions aren't recreated
- // when fillActionBars is called with FILL_PROXY.
- private IWorkbenchAction exitAction;
- private Action _aboutAction;
-
- public ApplicationActionBarAdvisor(IActionBarConfigurer configurer)
- {
- super(configurer);
- }
-
- protected void makeActions(final IWorkbenchWindow window)
- {
- // Creates the actions and registers them.
- // Registering is needed to ensure that key bindings work.
- // The corresponding commands keybindings are defined in the plugin.xml file.
- // Registering also provides automatic disposal of the actions when
- // the window is closed.
-
- exitAction = ActionFactory.QUIT.create(window);
- register(exitAction);
-
- _aboutAction = new VersionAction(window);
- register(_aboutAction);
- }
-
-
- protected void fillMenuBar(IMenuManager menuBar)
- {
- MenuManager fileMenu = new MenuManager("&Qpid Manager", "qpidmanager");
- MenuManager helpMenu = new MenuManager("&Help", IWorkbenchActionConstants.M_HELP);
-
- menuBar.add(fileMenu);
- // Add a group marker indicating where action set menus will appear.
- menuBar.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
- menuBar.add(helpMenu);
-
- fileMenu.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
- fileMenu.add(new Separator());
- fileMenu.add(new GroupMarker("mbeanactions"));
- fileMenu.add(new Separator());
- fileMenu.add(exitAction);
-
- // Help
- helpMenu.add(_aboutAction);
- }
-
- protected void fillCoolBar(ICoolBarManager coolBar)
- {
-
- }
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ApplicationRegistry.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ApplicationRegistry.java
deleted file mode 100644
index 4a59176374..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ApplicationRegistry.java
+++ /dev/null
@@ -1,189 +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.management.ui;
-
-import java.io.File;
-import java.util.List;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.CopyOnWriteArrayList;
-
-import org.eclipse.jface.resource.FontRegistry;
-import org.eclipse.jface.resource.ImageRegistry;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.graphics.FontData;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.PlatformUI;
-
-/**
- * Main Application Registry, which contains shared resources and map to all connected servers.
- * @author Bhupendra Bhardwaj
- */
-public abstract class ApplicationRegistry
-{
- private static ImageRegistry imageRegistry = new ImageRegistry();
- private static FontRegistry fontRegistry = new FontRegistry();
- public static final boolean debug = Boolean.getBoolean("eclipse.consoleLog");
- public static final long timeout = Long.parseLong(System.getProperty("timeout", "15000"));
-
- //max supported broker management interface supported by this release of the management console
- public static final int SUPPORTED_QPID_JMX_API_MAJOR_VERSION = 2;
- public static final int SUPPORTED_QPID_JMX_API_MINOR_VERSION = 3;
-
- public static final String DATA_DIR = System.getProperty("user.home") + File.separator + ".qpidmc";
-
- static
- {
- imageRegistry.put(Constants.SUCCESS_IMAGE,
- org.apache.qpid.management.ui.Activator.getImageDescriptor("/icons/success.gif"));
- imageRegistry.put(Constants.FAILURE_IMAGE,
- org.apache.qpid.management.ui.Activator.getImageDescriptor("/icons/failure.gif"));
- imageRegistry.put(Constants.CONSOLE_IMAGE,
- org.apache.qpid.management.ui.Activator.getImageDescriptor("/icons/qpidmc.gif"));
- imageRegistry.put(Constants.CLOSED_FOLDER_IMAGE,
- org.apache.qpid.management.ui.Activator.getImageDescriptor("/icons/icon_ClosedFolder.gif"));
- imageRegistry.put(Constants.OPEN_FOLDER_IMAGE,
- PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_FOLDER));
- imageRegistry.put(Constants.MBEAN_IMAGE,
- PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_ELEMENT));
- imageRegistry.put(Constants.NOTIFICATION_IMAGE,
- org.apache.qpid.management.ui.Activator.getImageDescriptor("/icons/notifications.gif"));
- imageRegistry.put(Constants.LOGGING_MANAGEMENT_IMAGE,
- org.apache.qpid.management.ui.Activator.getImageDescriptor("/icons/logging_management.gif"));
- imageRegistry.put(Constants.USER_MANAGEMENT_IMAGE,
- org.apache.qpid.management.ui.Activator.getImageDescriptor("/icons/user_management.gif"));
- imageRegistry.put(Constants.CONFIGURATION_MANAGEMENT_IMAGE,
- org.apache.qpid.management.ui.Activator.getImageDescriptor("/icons/configuration_management.gif"));
- imageRegistry.put(Constants.SERVER_INFO_IMAGE,
- org.apache.qpid.management.ui.Activator.getImageDescriptor("/icons/server_information.gif"));
- imageRegistry.put(Constants.VHOST_MANAGER_IMAGE,
- org.apache.qpid.management.ui.Activator.getImageDescriptor("/icons/virtualhost_manager.gif"));
- }
-
- static
- {
- fontRegistry.put(Constants.FONT_BUTTON, new FontData[]{new FontData("Arial", 8, SWT.BOLD)} );
- fontRegistry.put(Constants.FONT_BOLD, new FontData[]{new FontData("Bold", 9, SWT.BOLD)} );
- fontRegistry.put(Constants.FONT_ITALIC, new FontData[]{new FontData("Italic", 9, SWT.ITALIC)} );
- fontRegistry.put(Constants.FONT_TABLE_CELL, new FontData[]{new FontData("Tablecell", 8, SWT.NORMAL)} );
- fontRegistry.put(Constants.FONT_NORMAL, new FontData[]{new FontData("Normal", 9, SWT.NORMAL)} );
- }
-
- /*
- * This maps all the managed servers to the respective server registry.
- */
- private static ConcurrentHashMap<ManagedServer, ServerRegistry> _serverRegistryMap = new ConcurrentHashMap<ManagedServer, ServerRegistry>();
-
- // This map gets updated when a server connection closes.
- private static List<ManagedServer> _closedServerList = new CopyOnWriteArrayList<ManagedServer>();
-
- public static Image getImage(String key)
- {
- return imageRegistry.get(key);
- }
-
- public static Font getFont(String key)
- {
- return fontRegistry.get(key);
- }
-
- public static void addServer(ManagedServer server, ServerRegistry registry)
- {
- _serverRegistryMap.put(server, registry);
- }
-
- public static void removeServer(ManagedServer server)
- {
- _serverRegistryMap.remove(server);
- }
-
- public static ServerRegistry getServerRegistry(ManagedServer server)
- {
- return _serverRegistryMap.get(server);
- }
-
- public static ServerRegistry getServerRegistry(ManagedBean mbean)
- {
- ManagedServer server = mbean.getServer();
- return getServerRegistry(server);
- }
-
- public static boolean isServerConnected(ManagedServer server)
- {
- if(server == null)
- {
- //checking for null is not permitted in a CHM
- return false;
- }
-
- ServerRegistry reg = _serverRegistryMap.get(server);
- if(reg !=null)
- {
- return !reg.isServerConnectionClosed();
- }
-
- return false;
- }
-
- // remove the server from the registry
- public static void serverConnectionClosed(ManagedServer server)
- {
- _closedServerList.add(server);
- removeServer(server);
- }
-
- // remove the server from the registry
- public static void serverConnectionClosedRemotely(ManagedServer server)
- {
- ServerRegistry reg = _serverRegistryMap.get(server);
- if(reg !=null)
- {
- synchronized(server)
- {
- if(reg.isServerConnectionClosed())
- {
- //the connection closure was already processed
- return;
- }
-
- reg.serverConnectionClosed();
- }
- }
-
- serverConnectionClosed(server);
- }
-
- /*
- * Returns the lis of closed servers. The Thread in GUI, which keeps checking for closed connection
- * will check this and will remove the server links from the GUI.
- */
- public static List<ManagedServer> getClosedServers()
- {
- if (_closedServerList.isEmpty())
- return null;
-
- List<ManagedServer> list = new CopyOnWriteArrayList<ManagedServer>(_closedServerList);
- _closedServerList.clear();
- return list;
- }
-
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ApplicationWorkbenchAdvisor.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ApplicationWorkbenchAdvisor.java
deleted file mode 100644
index a46fa870e4..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ApplicationWorkbenchAdvisor.java
+++ /dev/null
@@ -1,46 +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.management.ui;
-
-import org.eclipse.ui.application.IWorkbenchWindowConfigurer;
-import org.eclipse.ui.application.WorkbenchAdvisor;
-import org.eclipse.ui.application.WorkbenchWindowAdvisor;
-
-/**
- * This workbench advisor creates the window advisor, and specifies
- * the perspective id for the initial window.
- */
-public class ApplicationWorkbenchAdvisor extends WorkbenchAdvisor
-{
- public static final String PERSPECTIVE_ID = "org.apache.qpid.management.ui.perspective";
-
- public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer)
- {
- return new ApplicationWorkbenchWindowAdvisor(configurer);
- }
-
-
- public String getInitialWindowPerspectiveId()
- {
- return PERSPECTIVE_ID;
- }
-
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ApplicationWorkbenchWindowAdvisor.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ApplicationWorkbenchWindowAdvisor.java
deleted file mode 100644
index 00574440c5..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ApplicationWorkbenchWindowAdvisor.java
+++ /dev/null
@@ -1,65 +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.management.ui;
-
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.application.ActionBarAdvisor;
-import org.eclipse.ui.application.IActionBarConfigurer;
-import org.eclipse.ui.application.IWorkbenchWindowConfigurer;
-import org.eclipse.ui.application.WorkbenchWindowAdvisor;
-
-/**
- *
- * @author Bhupendra Bhardwaj
- */
-public class ApplicationWorkbenchWindowAdvisor extends WorkbenchWindowAdvisor
-{
- public ApplicationWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer)
- {
- super(configurer);
- }
-
- public ActionBarAdvisor createActionBarAdvisor(IActionBarConfigurer configurer)
- {
- return new ApplicationActionBarAdvisor(configurer);
- }
-
- public void preWindowOpen()
- {
- IWorkbenchWindowConfigurer configurer = getWindowConfigurer();
- int x = Display.getDefault().getBounds().width;
- int y = Display.getDefault().getBounds().height;
- configurer.setInitialSize(new Point(9*x/10, 8*y/10));
- configurer.setShowCoolBar(true);
- configurer.setShowStatusLine(true);
-
- configurer.setTitle(Constants.APPLICATION_NAME);
- }
-
- public void postWindowCreate()
- {
- IWorkbenchWindowConfigurer configurer = getWindowConfigurer();
- Shell shell = configurer.getWindow().getShell();
- shell.setImage(ApplicationRegistry.getImage(Constants.CONSOLE_IMAGE));
- }
-} \ No newline at end of file
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/Constants.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/Constants.java
deleted file mode 100644
index c8f95dd8cb..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/Constants.java
+++ /dev/null
@@ -1,153 +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.management.ui;
-
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-
-/**
- * Contains constants for the application
- * @author Bhupendra Bhardwaj
- *
- */
-public class Constants
-{
- public final static String APPLICATION_NAME = "Qpid JMX Management Console";
- public static final String DEFAULT_DOMAIN = "org.apache.qpid";
-
- public final static String ACTION_REMOVE_MBEANNODE = "Remove from list";
- public final static String VALUE = "value";
- public final static String TYPE = "type";
- public final static String VERSION = "version";
- public final static String NODE_TYPE_SERVER = "server";
- public final static String NODE_TYPE_MBEANTYPE = "mbeantype";
- // currently used only for virtual host instances, but will work as general also
- public final static String NODE_TYPE_TYPEINSTANCE = "mbeantype_instance";
- public final static String MBEAN = "mbean";
- public final static String ATTRIBUTE = "Attribute";
- public final static String ATTRIBUTES = "Attributes";
- public final static String NOTIFICATIONS = "Notifications";
- public final static String RESULT = "Result";
- public final static String VIRTUAL_HOST = "VirtualHost";
- public final static String DEFAULT_VH = "Default";
- public final static String DEFAULT_USERNAME = "guest";
- public final static String DEFAULT_PASSWORD = "guest";
-
- public final static String USERNAME = "Username";
- public final static String PASSWORD = "Password";
-
- // Attributes and operations are used to customize the GUI for Qpid. If these are changes in the
- // Qpid server, then these should be updated accordingly
- public final static String ATTRIBUTE_QUEUE_OWNER = "owner";
- public final static String ATTRIBUTE_QUEUE_DEPTH = "QueueDepth";
- public final static String ATTRIBUTE_QUEUE_CONSUMERCOUNT = "ActiveConsumerCount";
- public final static String OPERATION_CREATE_QUEUE = "createNewQueue";
- public final static String OPERATION_CREATE_BINDING = "createNewBinding";
- public final static String OPERATION_MOVE_MESSAGES = "moveMessages";
-
- public final static String OPERATION_CREATEUSER = "createUser";
- public final static String OPERATION_DELETEUSER = "deleteUser";
- public final static String OPERATION_VIEWUSERS = "viewUsers";
- public final static String OPERATION_PARAM_USERNAME = "username";
-
- public final static String OPERATION_SUCCESSFUL = "Operation successful";
- public final static String OPERATION_UNSUCCESSFUL = "Operation unsuccessful";
-
- public final static String ALL = "All";
-
- public final static String NAVIGATION_ROOT = "Qpid Connections";
- public final static String DESCRIPTION = " Description";
-
- public final static String ADMIN_MBEAN_TYPE = "UserManagement";
- public final static String QUEUE = "Queue";
- public final static String CONNECTION ="Connection";
- public final static String EXCHANGE = "Exchange";
- public final static String EXCHANGE_TYPE = "ExchangeType";
-
- public final static String DIRECT_EXCHANGE = "direct";
- public final static String FANOUT_EXCHANGE = "fanout";
- public final static String HEADERS_EXCHANGE = "headers";
- public final static String TOPIC_EXCHANGE = "topic";
- public final static List<String> DEFAULT_EXCHANGE_TYPE_VALUES = Collections.unmodifiableList(
- Arrays.asList(DIRECT_EXCHANGE, FANOUT_EXCHANGE, HEADERS_EXCHANGE, TOPIC_EXCHANGE));
- public final static List<String> ATTRIBUTE_TABLE_TITLES = Collections.unmodifiableList(
- Arrays.asList("Attribute Name", "Value"));
-
- public final static String ACTION_ADDSERVER = "New Connection";
- public final static String ACTION_RECONNECT = "Reconnect";
- public final static String ACTION_CLOSE = "Close Connection";
- public final static String ACTION_EDITATTRIBUTE = "Edit Attribute";
- public final static String ACTION_LOGIN = "Login";
-
- public final static String QUEUE_SORT_BY_NAME = "Queue Name";
- public final static String QUEUE_SORT_BY_DEPTH = "Queue Depth";
- public final static String QUEUE_SORT_BY_CONSUMERCOUNT = "Consumer Count";
- public final static String QUEUE_SHOW_TEMP_QUEUES= "show temporary queues";
-
- public final static String SUBSCRIBE_BUTTON = "Subscribe";
- public final static String UNSUBSCRIBE_BUTTON = "Unsubscribe";
-
-
- public final static String SUCCESS_IMAGE = "SuccessImage";
- public final static String FAILURE_IMAGE = "FailureImage";
- public final static String CONSOLE_IMAGE = "ConsoleImage";
- public final static String CLOSED_FOLDER_IMAGE = "ClosedFolderImage";
- public final static String OPEN_FOLDER_IMAGE = "OpenFolderImage";
- public final static String MBEAN_IMAGE = "MBeanImage";
- public final static String NOTIFICATION_IMAGE = "NotificationImage";
- public final static String LOGGING_MANAGEMENT_IMAGE = "LoggingManagementImage";
- public final static String USER_MANAGEMENT_IMAGE = "UserManagementImage";
- public final static String CONFIGURATION_MANAGEMENT_IMAGE = "ConfigurationManagementImage";
- public final static String SERVER_INFO_IMAGE = "ServerInfoImage";
- public final static String VHOST_MANAGER_IMAGE = "VhostManagerImage";
-
- public final static String FONT_BUTTON = "ButtonFont";
- public final static String FONT_BOLD = "BoldFont";
- public final static String FONT_ITALIC = "ItalicFont";
- public final static String FONT_TABLE_CELL = "TableCellFont";
- public final static String FONT_NORMAL = "Normal";
-
- public final static String BUTTON_DETAILS = "Details";
- public final static String BUTTON_EDIT_ATTRIBUTE = "Edit";
- public final static String BUTTON_REFRESH = "Refresh";
- public final static String BUTTON_GRAPH = "Graph";
- public final static int TIMER_INTERVAL = 5000;
- public final static String BUTTON_EXECUTE = "Execute";
- public final static String BUTTON_CLEAR = "Clear";
- public final static String BUTTON_CONNECT = "Connect";
- public final static String BUTTON_CANCEL = "Cancel";
- public final static String BUTTON_UPDATE = "Update";
-
-
- public final static int OPERATION_IMPACT_INFO = 0;
- public final static int OPERATION_IMPACT_ACTION = 1;
- public final static int OPERATION_IMPACT_ACTIONINFO = 2;
- public final static int OPERATION_IMPACT_UNKNOWN = 3;
-
- public final static String ERROR_SERVER_CONNECTION = "Server Connection Failed";
- public final static String INFO_PROTOCOL = "Please select the protocol";
- public final static String INFO_HOST_ADDRESS = "Please enter the host address";
- public final static String INFO_HOST_PORT = "Please enter the port number";
- public final static String INFO_USERNAME = "Please enter the " + USERNAME;
- public final static String INFO_PASSWORD = "Please enter the " + PASSWORD;
-
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ManagedBean.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ManagedBean.java
deleted file mode 100644
index 8ded3f35c6..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ManagedBean.java
+++ /dev/null
@@ -1,176 +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.management.ui;
-
-import static org.apache.qpid.management.ui.Constants.ADMIN_MBEAN_TYPE;
-import static org.apache.qpid.management.ui.Constants.CONNECTION;
-import static org.apache.qpid.management.ui.Constants.DEFAULT_VH;
-import static org.apache.qpid.management.ui.Constants.EXCHANGE;
-import static org.apache.qpid.management.ui.Constants.QUEUE;
-import static org.apache.qpid.management.ui.Constants.VIRTUAL_HOST;
-
-import java.util.HashMap;
-
-import org.apache.qpid.management.common.mbeans.ManagedBroker;
-
-/**
- * Class representing a managed bean on the managed server
- */
-public abstract class ManagedBean extends ManagedObject
-{
- private String _uniqueName = "";
- private String _domain = "";
- private String _type = "";
- private String _virtualHostName = null;
- private ManagedServer _server = null;
- private HashMap _properties = null;
- private int _version;
-
- public String getProperty(String key)
- {
- return (String) _properties.get(key);
- }
-
- public HashMap getProperties()
- {
- return _properties;
- }
-
- public void setProperties(HashMap properties)
- {
- this._properties = properties;
- setName(getProperty("name"));
- setType(getProperty("type"));
- setVersion(getProperty("version"));
- _virtualHostName = getProperty(VIRTUAL_HOST);
- }
-
- public void setVersion(String version)
- {
- try
- {
- _version = Integer.parseInt(version);
- }
- catch (NumberFormatException nfe)
- {
- _version = 1;
- }
-
- }
-
- public int getVersion()
- {
- return _version;
- }
-
- public String getDomain()
- {
- return _domain;
- }
-
- public void setDomain(String domain)
- {
- this._domain = domain;
- }
-
- public ManagedServer getServer()
- {
- return _server;
- }
-
- public void setServer(ManagedServer server)
- {
- this._server = server;
- }
-
- public String getType()
- {
- return _type;
- }
-
- public void setType(String type)
- {
- this._type = type;
- }
-
- public String getUniqueName()
- {
- return _uniqueName;
- }
-
- public void setUniqueName(String uniqueName)
- {
- this._uniqueName = uniqueName;
- }
-
- public String getVirtualHostName()
- {
- // To make it work with the broker with no virtual host implementation
- return _virtualHostName == null ? DEFAULT_VH : _virtualHostName;
- }
-
- /**
- * Returns mbean instance name. MBeans which have only one instance, the type attribute will be returned
- *
- * @return
- */
- public String getInstanceName()
- {
- if (getName() != null)
- {
- return getName();
- }
- else
- {
- return getType();
- }
- }
-
- public boolean isQueue()
- {
- return _type.endsWith(QUEUE);
- }
-
- public boolean isConnection()
- {
- return _type.endsWith(CONNECTION);
- }
-
- public boolean isExchange()
- {
- return _type.endsWith(EXCHANGE);
- }
-
- public boolean isVirtualHostManager()
- {
- return _type.endsWith(ManagedBroker.TYPE);
- }
-
- public boolean isTempQueue()
- {
- return (isQueue() && getName().startsWith("tmp_"));
- }
-
- public boolean isAdmin()
- {
- return _type.endsWith(ADMIN_MBEAN_TYPE);
- }
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ManagedObject.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ManagedObject.java
deleted file mode 100644
index 96e0fa46c6..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ManagedObject.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.management.ui;
-
-/**
- * Abstract class representing a managed object
- * @author Bhupendra Bhardwaj
- */
-public abstract class ManagedObject
-{
- private String _name;
-
- public String getName()
- {
- return _name;
- }
-
- public void setName(String name)
- {
- this._name = name;
- }
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ManagedServer.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ManagedServer.java
deleted file mode 100644
index 9ca8787bb5..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ManagedServer.java
+++ /dev/null
@@ -1,84 +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.management.ui;
-
-/**
- * Class representing a server being managed eg. MBeanServer
- */
-public class ManagedServer extends ManagedObject
-{
- private String _host;
- private int _port;
- private String _domain;
- private String _user;
- private String _password;
-
- public ManagedServer(String host, int port, String domain)
- {
- this(host, port, domain, null, null);
- }
-
- public ManagedServer(String host, int port, String domain, String user, String password)
- {
- setName(host + ":" + port);
- _host = host;
- _port = port;
- _domain = domain;
- _user = user;
- _password = password;
- }
-
- public String getDomain()
- {
- return _domain;
- }
-
- public String getHost()
- {
- return _host;
- }
-
- public int getPort()
- {
- return _port;
- }
-
- public String getPassword()
- {
- return _password;
- }
-
- public void setPassword(String password)
- {
- _password = password;
- }
-
- public String getUser()
- {
- return _user;
- }
-
- public void setUser(String user)
- {
- _user = user;
- }
-
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/Perspective.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/Perspective.java
deleted file mode 100644
index f93200cadf..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/Perspective.java
+++ /dev/null
@@ -1,46 +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.management.ui;
-
-import org.apache.qpid.management.ui.views.MBeanView;
-import org.apache.qpid.management.ui.views.NavigationView;
-import org.eclipse.ui.IPageLayout;
-import org.eclipse.ui.IPerspectiveFactory;
-
-/**
- *
- * @author Bhupendra Bhardwaj
- */
-public class Perspective implements IPerspectiveFactory
-{
- public void createInitialLayout(IPageLayout layout)
- {
- String editorArea = layout.getEditorArea();
- layout.setEditorAreaVisible(false);
-
- // standalone view meaning it can't be docked or stacked with other views, and it doesn't have a title bar.
- layout.addStandaloneView(NavigationView.ID, true, IPageLayout.LEFT, 0.30f, editorArea);
- layout.addStandaloneView(MBeanView.ID, true, IPageLayout.RIGHT, 0.70f, editorArea);
-
- layout.getViewLayout(NavigationView.ID).setCloseable(false);
- layout.getViewLayout(MBeanView.ID).setCloseable(false);
- }
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/RefreshIntervalComboPanel.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/RefreshIntervalComboPanel.java
deleted file mode 100644
index ae60467bf5..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/RefreshIntervalComboPanel.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.management.ui;
-
-import org.apache.qpid.management.ui.jmx.MBeanUtility;
-import org.apache.qpid.management.ui.views.MBeanView;
-import org.apache.qpid.management.ui.views.NavigationView;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.menus.WorkbenchWindowControlContribution;
-
-public class RefreshIntervalComboPanel extends WorkbenchWindowControlContribution
-{
- private Display _display = null;
- private RefreshTask _refreshTask = null;
-
- private static int DEFAULT_INDEX = 2; //15seconds
- private static final int[] INTERVALS = new int[]{5,10,15,30,60,120,300,600};
-
- public RefreshIntervalComboPanel()
- {
- super();
- }
-
- public RefreshIntervalComboPanel(String id)
- {
- super(id);
- }
-
- @Override
- public Control createControl(Composite parent)
- {
- _display = parent.getDisplay();
-
- Composite holder = new Composite(parent,SWT.NONE);
- holder.setLayout(new GridLayout(2,false));
- holder.setLayoutData(new GridData(SWT.LEFT,SWT.TOP,false,false));
-
- Label refreshLabel = new Label(holder,SWT.NONE);
- refreshLabel.setLayoutData(new GridData(SWT.LEFT,SWT.TOP,false,true));
- refreshLabel.setText("Refresh Interval: ");
-
- final Combo combo = new Combo(holder, SWT.NONE | SWT.DROP_DOWN | SWT.READ_ONLY);
- combo.setLayoutData(new GridData(SWT.LEFT,SWT.TOP,false,false));
- for(int i=0; i< INTERVALS.length ; i++)
- {
- combo.add(String.valueOf(INTERVALS[i]) + " seconds");
- }
- combo.select(DEFAULT_INDEX);
-
- _refreshTask = new RefreshTask(INTERVALS[DEFAULT_INDEX]);
- _display.timerExec(1000 * INTERVALS[DEFAULT_INDEX], _refreshTask);
-
- combo.addModifyListener(
- new ModifyListener()
- {
- public void modifyText(final ModifyEvent e)
- {
- _display.timerExec(-1, _refreshTask); //cancels existing refresh runnable
- _refreshTask = new RefreshTask(INTERVALS[combo.getSelectionIndex()]);
- _display.timerExec(0, _refreshTask); //immediately refresh and begin new schedule
- }
- });
-
- return holder;
- }
-
-
- private class RefreshTask implements Runnable
- {
- private int seconds;
-
- public RefreshTask(int secs)
- {
- this.seconds = secs;
- }
-
- @Override
- public void run()
- {
- IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- if(window != null)
- {
- final MBeanView mbView = (MBeanView)window.getActivePage().findView(MBeanView.ID);
-
- final NavigationView navView = (NavigationView)window.getActivePage().findView(NavigationView.ID);
- try
- {
- mbView.refresh();
- navView.refresh();
- }
- catch (Exception ex)
- {
- MBeanUtility.handleException(ex);
- }
-
- _display.timerExec(1000 * seconds, this);
- }
- }
-
- }
-
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ServerRegistry.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ServerRegistry.java
deleted file mode 100644
index c3c0277f7d..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ServerRegistry.java
+++ /dev/null
@@ -1,264 +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.management.ui;
-
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import org.apache.qpid.management.ui.jmx.ClientListener;
-import org.apache.qpid.management.ui.model.ManagedAttributeModel;
-import org.apache.qpid.management.ui.model.NotificationObject;
-import org.apache.qpid.management.ui.model.OperationDataModel;
-
-import java.util.Collections;
-
-public abstract class ServerRegistry
-{
- private ManagedServer _managedServer = null;
-
- // API version for the management interface on the broker
- private ApiVersion _managementApiVersion = new ApiVersion(0,0);
-
- // list of virtual hosts for this server
- private List<String> _virtualHosts = new ArrayList<String>();
- // map of all Connection mbeans
- private ConcurrentMap<String,List<ManagedBean>> _connections = new ConcurrentHashMap<String,List<ManagedBean>>();
- // map of all exchange mbeans
- private ConcurrentMap<String,List<ManagedBean>> _exchanges = new ConcurrentHashMap<String,List<ManagedBean>>();
- // map of all queue mbenas
- private ConcurrentMap<String,List<ManagedBean>> _queues = new ConcurrentHashMap<String,List<ManagedBean>>();
- // map of all virtual host manager mbeans
- private ConcurrentMap<String,ManagedBean> _vhostManagers = new ConcurrentHashMap<String,ManagedBean>();
-
- private AtomicBoolean _serverConnectionClosed = new AtomicBoolean(false);
-
- public ServerRegistry()
- {
-
- }
-
- public ServerRegistry(ManagedServer server)
- {
- _managedServer = server;
- }
-
- public void serverConnectionClosed()
- {
- _serverConnectionClosed.set(true);
- }
-
- public boolean isServerConnectionClosed()
- {
- return _serverConnectionClosed.get();
- }
-
- public void setManagementApiVersion(ApiVersion mgmtApiVersion)
- {
- _managementApiVersion = mgmtApiVersion;
- }
-
- public ApiVersion getManagementApiVersion()
- {
- return _managementApiVersion;
- }
-
- public ManagedServer getManagedServer()
- {
- return _managedServer;
- }
-
- public void setManagedServer(ManagedServer server)
- {
- _managedServer = server;
- }
-
- protected void addConnectionMBean(ManagedBean mbean)
- {
- String vHost = mbean.getVirtualHostName();
- List<ManagedBean> vhostConnections = getVhostSubList(vHost, _connections);
- vhostConnections.add(mbean);
- }
-
- protected void addExchangeMBean(ManagedBean mbean)
- {
- String vHost = mbean.getVirtualHostName();
- List<ManagedBean> vhostExchanges = getVhostSubList(vHost, _exchanges);
- vhostExchanges.add(mbean);
- }
-
- protected void addQueueMBean(ManagedBean mbean)
- {
- String vHost = mbean.getVirtualHostName();
- List<ManagedBean> vhostQueues = getVhostSubList(vHost, _queues);
- vhostQueues.add(mbean);
- }
-
- private List<ManagedBean> getVhostSubList(String vHost, ConcurrentMap<String,List<ManagedBean>> parentList)
- {
- //add an empty sublist for the vhost if required
- if (!parentList.containsKey(vHost))
- {
- List<ManagedBean> subList = Collections.synchronizedList(new ArrayList<ManagedBean>());
- parentList.putIfAbsent(vHost, subList);
- }
-
- return parentList.get(vHost);
- }
-
- protected void addVirtualHostManagerMBean(ManagedBean mbean)
- {
- String vHost = mbean.getVirtualHostName();
- _vhostManagers.put(vHost, mbean);
- }
-
- protected void removeVirtualHostManagerMBean(ManagedBean mbean)
- {
- _vhostManagers.remove(mbean.getVirtualHostName());
- }
-
- public ManagedBean getVirtualHostManagerMBean(String virtualHost)
- {
- return _vhostManagers.get(virtualHost);
- }
-
- protected void removeConnectionMBean(ManagedBean mbean)
- {
- _connections.get(mbean.getVirtualHostName()).remove(mbean);
- }
-
- protected void removeExchangeMBean(ManagedBean mbean)
- {
- _exchanges.get(mbean.getVirtualHostName()).remove(mbean);
- }
-
- protected void removeQueueMBean(ManagedBean mbean)
- {
- _queues.get(mbean.getVirtualHostName()).remove(mbean);
- }
-
- public List<ManagedBean> getConnections(String virtualHost)
- {
- return getVhostObjects(virtualHost, _connections);
- }
-
- public List<ManagedBean> getExchanges(String virtualHost)
- {
- return getVhostObjects(virtualHost, _exchanges);
- }
-
- public List<ManagedBean> getQueues(String virtualHost)
- {
- return getVhostObjects(virtualHost, _queues);
- }
-
- public List<ManagedBean> getVhostObjects(String virtualHost, ConcurrentMap<String,List<ManagedBean>> parentList)
- {
- List<ManagedBean> objects = parentList.get(virtualHost);
-
- if(objects == null)
- {
- return new ArrayList<ManagedBean>();
- }
-
- synchronized (objects)
- {
- return new ArrayList<ManagedBean>(objects);
- }
- }
-
- //returns the requested ManagedBean, or null if it cant be found
- public ManagedBean getQueue(String queueName, String virtualHost)
- {
- ManagedBean requestedQueue = null;
-
- for(ManagedBean queue : _queues.get(virtualHost))
- {
- if(queueName.equals(queue.getName()))
- {
- requestedQueue = queue;
- break;
- }
- }
-
- return requestedQueue;
- }
-
- public void addVirtualHost(String name)
- {
- if (!_virtualHosts.contains(name))
- {
- _virtualHosts.add(name);
- }
- }
-
- public List<String> getVirtualHosts()
- {
- return _virtualHosts;
- }
-
- public abstract void setUserList(List<String> list);
-
- public abstract List<String> getUsernames();
-
- public abstract void addManagedObject(ManagedBean key);
-
- public abstract List<ManagedBean> getMBeans();
-
- public abstract void removeManagedObject(ManagedBean mbean);
-
- public abstract List<ManagedBean> getObjectsToBeRemoved();
-
- public abstract ManagedAttributeModel getAttributeModel(ManagedBean mbean);
-
- public abstract Object getServerConnection();
-
- public abstract void closeServerConnection() throws Exception;
-
- public abstract OperationDataModel getOperationModel(ManagedBean mbean);
-
- public abstract List<String> getQueueNames(String vistualHostName);
-
- public abstract String[] getExchangeNames(String vistualHostName);
-
- public abstract String[] getConnectionNames(String vistualHostName);
-
- public abstract List<NotificationObject> getNotifications(ManagedBean mbean);
-
- public abstract List<NotificationObject> getNotifications(String virtualhost);
-
- public abstract boolean hasSubscribedForNotifications(ManagedBean mbean, String name, String type);
-
- public abstract void clearNotifications(ManagedBean mbean, List<NotificationObject> list);
-
- public ClientListener getNotificationListener()
- {
- return null;
- }
-
- public ClientListener getClientListener()
- {
- return null;
- }
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/AbstractAction.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/AbstractAction.java
deleted file mode 100644
index 5d892f5503..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/AbstractAction.java
+++ /dev/null
@@ -1,220 +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.management.ui.actions;
-
-import static org.apache.qpid.management.ui.Constants.ERROR_SERVER_CONNECTION;
-
-import java.io.IOException;
-
-import javax.net.ssl.SSLException;
-import javax.net.ssl.SSLHandshakeException;
-import javax.net.ssl.SSLKeyException;
-import javax.net.ssl.SSLPeerUnverifiedException;
-
-import org.apache.qpid.management.ui.ApplicationRegistry;
-import org.apache.qpid.management.ui.ApplicationWorkbenchAdvisor;
-import org.apache.qpid.management.ui.Constants;
-import org.apache.qpid.management.ui.exceptions.ManagementConsoleException;
-import org.apache.qpid.management.ui.jmx.MBeanUtility;
-import org.apache.qpid.management.ui.views.NavigationView;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.dialogs.ErrorDialog;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.IWorkbenchWindowActionDelegate;
-
-public class AbstractAction
-{
- private NavigationView _navigationView;
-
- protected IWorkbenchWindow _window;
-
- public static final String INVALID_PERSPECTIVE = "Invalid Perspective";
- public static final String CHANGE_PERSPECTIVE = "Please use the Qpid Management Perspective";
-
- private static final String SSL_EMPTY_TRUSTANCHORS = "the trustAnchors parameter must be non-empty";
- private static final String SSL_UNABLE_TO_FIND_CERTPATH = "sun.security.provider.certpath.SunCertPathBuilderException: " +
- "unable to find valid certification path to requested target";
-
- /**
- * We will cache window object in order to
- * be able to provide parent shell for the message dialog.
- * @see IWorkbenchWindowActionDelegate#init
- */
- public void init(IWorkbenchWindow window)
- {
- this._window = window;
- if (_window.getShell() != null)
- {
- _window.getShell().setImage(ApplicationRegistry.getImage(Constants.CONSOLE_IMAGE));
- }
- }
-
- protected NavigationView getNavigationView()
- {
- if (_navigationView == null)
- {
- _navigationView = (NavigationView)_window.getActivePage().findView(NavigationView.ID);
- }
-
- return _navigationView;
- }
-
- protected void handleException(Throwable ex, String title, String msg)
- {
- //ensure first that the exception is not due to running in the wrong eclipse perspective
- NavigationView view = (NavigationView)_window.getActivePage().findView(NavigationView.ID);
- if (view == null)
- {
- IStatus status = new Status(IStatus.WARNING, ApplicationWorkbenchAdvisor.PERSPECTIVE_ID,
- IStatus.OK, CHANGE_PERSPECTIVE, null);
- ErrorDialog.openError(_window.getShell(), "Warning", INVALID_PERSPECTIVE, status);
- return;
- }
-
- //default title if none given
- if (title == null)
- {
- title = ERROR_SERVER_CONNECTION;
- }
-
- //determine the error message to display
- if (msg == null)
- {
- if (ex instanceof SSLException)
- {
- if (ex instanceof SSLKeyException)
- {
- msg = "SSL key was invalid, please check the certificate configuration.";
- //Display error dialogue and return
- displayErrorDialogue(msg, title);
- return;
- }
- else if (ex instanceof SSLPeerUnverifiedException)
- {
- msg = "SSL peer identity could not be verified, please ensure valid certificate configuration.";
- //Display error dialogue and return
- displayErrorDialogue(msg, title);
- return;
- }
- else if (ex instanceof SSLHandshakeException)
- {
- if (ex.getMessage().contains(SSL_UNABLE_TO_FIND_CERTPATH))
- {
- msg = "Unable to certify the provided SSL certificate using the current SSL trust store.";
- }
- else
- {
- //cause unknown, provide a trace too
- MBeanUtility.printStackTrace(ex);
- msg = "SSL handhshake error.";
- }
- //Display error dialogue and return
- displayErrorDialogue(msg, title);
- return;
- }
- else
- {
- //general SSL Exception.
- if (ex.getMessage().contains(SSL_EMPTY_TRUSTANCHORS))
- {
- msg = "Unable to locate the specified SSL certificate trust store, please check the configuration.";
- }
- else
- {
- //cause unknown, print stack trace
- MBeanUtility.printStackTrace(ex);
- msg = "SSL connection error.";
- }
- //Display error dialogue and return
- displayErrorDialogue(msg, title);
- return;
- }
- }
- else if (ex instanceof IOException || ex instanceof SecurityException )
- {
- msg = ex.getMessage();
-
- //if msg is still null, try reporting the cause.
- if ((msg == null) && (ex.getCause() != null))
- {
- msg = ex.getCause().getMessage();
- }
-
- //Display error dialogue and return
- displayErrorDialogue(msg, title);
- return;
- }
- else if (ex instanceof ManagementConsoleException)
- {
- msg = ex.getMessage();
- displayErrorDialogue(msg, title);
- return;
- }
- else
- {
- //Unknown exception type/reason.
- msg = ex.getMessage();
- }
-
- //if msg is still null, try reporting the cause.
- if ((msg == null) && (ex.getCause() != null))
- {
- msg = ex.getCause().getMessage();
- }
-
- //failing all else, default non-descript error message.
- if (msg == null)
- {
- msg = "An unknown error has occured.";
- }
- }
-
- //Display error dialogue and print the exception stack trace
- MBeanUtility.printStackTrace(ex);
- displayErrorDialogue(msg, title);
- }
-
- private void displayErrorDialogue(String msg, String title)
- {
- IStatus status = new Status(IStatus.ERROR, ApplicationWorkbenchAdvisor.PERSPECTIVE_ID,
- IStatus.OK, msg, null);
- ErrorDialog.openError(_window.getShell(), "Error", title, status);
- }
-
- /**
- * Selection in the workbench has been changed. We can change the state of the 'real' action here
- * if we want, but this can only happen after the delegate has been created.
- * @see IWorkbenchWindowActionDelegate#selectionChanged
- */
- public void selectionChanged(IAction action, ISelection selection) {
- }
-
- /**
- * We can use this method to dispose of any system resources we previously allocated.
- * @see IWorkbenchWindowActionDelegate#dispose
- */
- public void dispose() {
-
- }
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/AddServer.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/AddServer.java
deleted file mode 100644
index e487c02a67..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/AddServer.java
+++ /dev/null
@@ -1,313 +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.management.ui.actions;
-
-import static org.apache.qpid.management.ui.Constants.*;
-
-import org.apache.qpid.management.ui.ApplicationRegistry;
-import org.apache.qpid.management.ui.exceptions.InfoRequiredException;
-import org.apache.qpid.management.ui.views.NumberVerifyListener;
-import org.apache.qpid.management.ui.views.ViewUtility;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.KeyAdapter;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.IWorkbenchWindowActionDelegate;
-
-public class AddServer extends AbstractAction implements IWorkbenchWindowActionDelegate
-{
- private String _host;
- private String _port;
- private String _domain = DEFAULT_DOMAIN;
- private String _user;
- private String _password;
-
- private boolean _addServer;
-
- public AddServer()
- {
-
- }
-
- public void run(IAction action)
- {
- if(_window == null)
- return;
-
- reset();
- createAddServerPopup();
- try
- {
- if (_addServer)
- {
- getNavigationView().addNewServer(_host, Integer.parseInt(_port), _domain, _user, _password);
- }
- }
- catch(InfoRequiredException ex)
- {
- ViewUtility.popupInfoMessage(ACTION_ADDSERVER, ex.getMessage());
- }
- catch (Exception ex)
- {
- handleException(ex, null, null);
- }
- }
-
- private void reset()
- {
- _addServer = false;
- _host = null;
- _port = null;
- _user = null;
- _password = null;
- }
-
- /**
- * Creates the shell and then opens the popup where user can enter new connection details.
- * Connects to the new server and adds the server in the navigation page.
- * Pops up any error occured in connecting to the new server
- */
- private void createAddServerPopup()
- {
- final Shell appShell = _window.getShell();
-
- Display display = Display.getCurrent();
- final Shell shell = new Shell(display, SWT.BORDER | SWT.CLOSE);
- shell.setText(ACTION_ADDSERVER);
- shell.setImage(ApplicationRegistry.getImage(CONSOLE_IMAGE));
- shell.setLayout(new GridLayout());
-
- createWidgets(shell);
- shell.pack();
-
- //get current size dialog, and application window size and location
- int appWidth = appShell.getBounds().width;
- int appHeight = appShell.getBounds().height;
- int appLocX = appShell.getBounds().x;
- int appLocY = appShell.getBounds().y;
- int currentShellWidth = shell.getSize().x;
- int currentShellHeight = shell.getSize().y;
-
- //default sizes for the dialog
- int minShellWidth = 425;
- int minShellHeight= 265;
- //ensure this is large enough, increase it if its not
- int newShellWidth = currentShellWidth > minShellWidth ? currentShellWidth : minShellWidth;
- int newShellHeight = currentShellHeight > minShellHeight ? currentShellHeight : minShellHeight;
-
- //set the final size and centre the dialog within the app window
- shell.setBounds((appWidth - newShellWidth)/2 + appLocX, (appHeight - newShellHeight)/2 + appLocY, newShellWidth, newShellHeight);
-
- shell.open();
- _window.getShell().setEnabled(false);
-
- while (!shell.isDisposed())
- {
- if (!display.readAndDispatch())
- {
- display.sleep();
- }
- }
-
- // enable the main shell
- _window.getShell().setEnabled(true);
- _window.getShell().open();
- }
-
- // Creates SWT widgets for the user to add server connection details.
- // Adds listeners to the widgets to take appropriate action
- private void createWidgets(final Shell shell)
- {
- Composite composite = new Composite(shell, SWT.NONE);
- composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- GridLayout layout = new GridLayout(2, false);
- layout.horizontalSpacing = 10;
- layout.verticalSpacing = 10;
- layout.marginHeight = 20;
- layout.marginWidth = 20;
- composite.setLayout(layout);
-
- /* Commenting this, as there is only one protocol at the moment.
- * This can be uncommented and enhanced, if more protocols are added in future
- Label name = new Label(composite, SWT.NONE);
- name.setText("Connection Type");
- GridData layoutData = new GridData(SWT.TRAIL, SWT.TOP, false, false);
- name.setLayoutData(layoutData);
-
- final Combo comboTransport = new Combo(composite, SWT.READ_ONLY);
- comboTransport.setItems(CONNECTION_PROTOCOLS);
- comboTransport.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- comboTransport.select(0);
- */
-
- Label host = new Label(composite, SWT.NONE);
- host.setText("Host");
- host.setLayoutData(new GridData(SWT.TRAIL, SWT.TOP, false, false));
-
- final Text textHost = new Text(composite, SWT.BORDER);
- textHost.setText("");
- textHost.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- textHost.setFocus();
-
- Label port = new Label(composite, SWT.NONE);
- port.setText("Port");
- port.setLayoutData(new GridData(SWT.TRAIL, SWT.TOP, false, false));
-
- final Text textPort = new Text(composite, SWT.BORDER);
- textPort.setText("");
- textPort.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- // Verify if the value entered is numeric
- textPort.addVerifyListener(new NumberVerifyListener());
-
- Label user = new Label(composite, SWT.NONE);
- user.setText(USERNAME);
- user.setLayoutData(new GridData(SWT.TRAIL, SWT.TOP, false, false));
-
- final Text textUser = new Text(composite, SWT.BORDER);
- textUser.setText("");
- textUser.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
-
- Label password = new Label(composite, SWT.NONE);
- password.setText(PASSWORD);
- password.setLayoutData(new GridData(SWT.TRAIL, SWT.TOP, false, false));
-
- final Text textPwd = new Text(composite, SWT.BORDER | SWT.SINGLE | SWT.PASSWORD);
- textPwd.setText("");
- //textPwd.setEchoChar('*');
- textPwd.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
-
- //Get the text widgets
- Control[] widgets = composite.getChildren();
- for (int i=0; i < widgets.length; i++)
- {
- widgets[i].addKeyListener(new KeyAdapter()
- {
- public void keyPressed(KeyEvent event)
- {
- if (event.character == SWT.ESC)
- {
- //Escape key acts as cancel on all widgets
- shell.dispose();
- }
- }
- });
- }
-
- Composite buttonsComposite = new Composite(composite, SWT.NONE);
- buttonsComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1));
- buttonsComposite.setLayout(new GridLayout(2, true));
-
- final Button connectButton = new Button(buttonsComposite, SWT.PUSH | SWT.CENTER);
- connectButton.setText(BUTTON_CONNECT);
- GridData gridData = new GridData (SWT.TRAIL, SWT.BOTTOM, true, true);
- gridData.widthHint = 100;
- connectButton.setLayoutData(gridData);
- connectButton.setFont(ApplicationRegistry.getFont(FONT_BUTTON));
- connectButton.addSelectionListener(new SelectionAdapter(){
- public void widgetSelected(SelectionEvent event)
- {
- _host = textHost.getText();
- if ((_host == null) || (_host.trim().length() == 0))
- {
- ViewUtility.popupInfoMessage(ACTION_ADDSERVER, INFO_HOST_ADDRESS);
- textHost.setText("");
- textHost.setFocus();
- return;
- }
-
- _port = textPort.getText();
- if ((_port == null) || (_port.trim().length() == 0))
- {
- ViewUtility.popupInfoMessage(ACTION_ADDSERVER, INFO_HOST_PORT);
- textPort.setText("");
- textPort.setFocus();
- return;
- }
-
- _user = textUser.getText();
- if ((_user == null) || (_user.trim().length() == 0))
- {
- ViewUtility.popupInfoMessage(ACTION_ADDSERVER, INFO_USERNAME);
- textUser.setText("");
- textUser.setFocus();
- return;
- }
-
- _password = textPwd.getText();
- if (_password == null)
- {
- ViewUtility.popupInfoMessage(ACTION_ADDSERVER, INFO_PASSWORD);
- textPwd.setText("");
- textPwd.setFocus();
- return;
- }
-
- _addServer = true;
- shell.dispose();
- }
- });
-
- final Button cancelButton = new Button(buttonsComposite, SWT.PUSH);
- cancelButton.setText(BUTTON_CANCEL);
- gridData = new GridData (SWT.LEAD, SWT.BOTTOM, true, true);
- gridData.widthHint = 100;
- cancelButton.setLayoutData(gridData);
- cancelButton.setFont(ApplicationRegistry.getFont(FONT_BUTTON));
- cancelButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent event)
- {
- shell.dispose();
- }
- });
-
- //Get the ok/cancel button widgets and add a new key listener
- widgets = buttonsComposite.getChildren();
- for (int i=0; i < widgets.length; i++)
- {
- widgets[i].addKeyListener(new KeyAdapter()
- {
- public void keyPressed(KeyEvent event)
- {
- if (event.character == SWT.ESC)
- {
- //Escape key acts as cancel on all widgets
- shell.dispose();
- }
- }
- });
- }
-
- shell.setDefaultButton(connectButton);
- }
-
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/BackAction.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/BackAction.java
deleted file mode 100644
index 2998c5db53..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/BackAction.java
+++ /dev/null
@@ -1,59 +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.management.ui.actions;
-
-import org.apache.qpid.management.ui.jmx.MBeanUtility;
-import org.apache.qpid.management.ui.views.MBeanView;
-import org.eclipse.jface.action.Action;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction;
-
-
-public class BackAction extends Action implements IWorkbenchAction
-{
- private static final String ID = "org.apache.qpid.management.ui.actions.back";
-
- public BackAction()
- {
- setText("Back");
- setImageDescriptor(org.apache.qpid.management.ui.Activator.getImageDescriptor("/icons/back.gif"));
- setId(ID);
- }
-
- public void run()
- {
- MBeanView mbeanview = (MBeanView)PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().findView(MBeanView.ID);
- try
- {
- mbeanview.back();
- }
- catch (Exception ex)
- {
- MBeanUtility.handleException(ex);
- }
-
- }
-
- public void dispose()
- {
-
- }
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/CloseConnection.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/CloseConnection.java
deleted file mode 100644
index a3e52149df..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/CloseConnection.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.management.ui.actions;
-
-import static org.apache.qpid.management.ui.Constants.ACTION_CLOSE;
-import org.apache.qpid.management.ui.exceptions.InfoRequiredException;
-import org.apache.qpid.management.ui.views.NavigationView;
-import org.apache.qpid.management.ui.views.ViewUtility;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.ui.IWorkbenchWindowActionDelegate;
-
-public class CloseConnection extends AbstractAction implements IWorkbenchWindowActionDelegate
-{
- public CloseConnection()
- {
-
- }
-
- public void run(IAction action)
- {
- if(_window != null)
- {
- NavigationView view = (NavigationView)_window.getActivePage().findView(NavigationView.ID);
- try
- {
- view.disconnect();
- }
- catch(InfoRequiredException ex)
- {
- ViewUtility.popupInfoMessage(ACTION_CLOSE, ex.getMessage());
- }
- catch(Exception ex)
- {
- handleException(ex, null, null);
- }
- }
- }
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/ReconnectServer.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/ReconnectServer.java
deleted file mode 100644
index 5eb9d9a168..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/ReconnectServer.java
+++ /dev/null
@@ -1,264 +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.management.ui.actions;
-
-import static org.apache.qpid.management.ui.Constants.ACTION_LOGIN;
-import static org.apache.qpid.management.ui.Constants.CONSOLE_IMAGE;
-import static org.apache.qpid.management.ui.Constants.INFO_PASSWORD;
-import static org.apache.qpid.management.ui.Constants.INFO_USERNAME;
-import static org.apache.qpid.management.ui.Constants.PASSWORD;
-import static org.apache.qpid.management.ui.Constants.USERNAME;
-
-import org.apache.qpid.management.ui.ApplicationRegistry;
-import org.apache.qpid.management.ui.Constants;
-import org.apache.qpid.management.ui.exceptions.InfoRequiredException;
-import org.apache.qpid.management.ui.views.TreeObject;
-import org.apache.qpid.management.ui.views.ViewUtility;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.KeyAdapter;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.IWorkbenchWindowActionDelegate;
-
-public class ReconnectServer extends AbstractAction implements IWorkbenchWindowActionDelegate
-{
- private String _title;
- private String _serverName;
- private String _user;
- private String _password;
- private boolean _connect;
-
- public void run(IAction action)
- {
- if(_window == null)
- return;
-
- try
- {
- reset();
- // Check if a server node is selected to be reconnected.
- TreeObject serverNode = getNavigationView().getSelectedServerNode();
- _serverName = serverNode.getName();
- _title = ACTION_LOGIN + " (" + _serverName + ")";
-
- // Get the login details(username/password)
- createLoginPopup();
-
- if (_connect)
- {
- // Connect the server
- getNavigationView().reconnect(_user, _password);
- }
- }
- catch(InfoRequiredException ex)
- {
- ViewUtility.popupInfoMessage("Reconnect Qpid server", ex.getMessage());
- }
- catch (Exception ex)
- {
- handleException(ex, null, null);
- }
- }
-
- private void reset()
- {
- _connect = false;
- _user = null;
- _password = null;
- }
-
- // Create the login popup fot th user to enter usernaem and password
- private void createLoginPopup()
- {
- final Shell appShell = _window.getShell();
-
- Display display = Display.getCurrent();
- final Shell shell = new Shell(display, SWT.BORDER | SWT.CLOSE);
- shell.setText(_title);
- shell.setImage(ApplicationRegistry.getImage(CONSOLE_IMAGE));
- shell.setLayout(new GridLayout());
-
- createWidgets(shell);
- shell.pack();
-
- //get current size dialog, and application window size and location
- int appWidth = appShell.getBounds().width;
- int appHeight = appShell.getBounds().height;
- int appLocX = appShell.getBounds().x;
- int appLocY = appShell.getBounds().y;
- int currentShellWidth = shell.getSize().x;
- int currentShellHeight = shell.getSize().y;
-
- //default sizes for the dialog
- int minShellWidth = 350;
- int minShellHeight= 200;
- //ensure this is large enough, increase it if its not
- int newShellWidth = currentShellWidth > minShellWidth ? currentShellWidth : minShellWidth;
- int newShellHeight = currentShellHeight > minShellHeight ? currentShellHeight : minShellHeight;
-
- //set the final size and centre the dialog within the app window
- shell.setBounds((appWidth - newShellWidth)/2 + appLocX, (appHeight - newShellHeight)/2 + appLocY, newShellWidth, newShellHeight);
-
- shell.open();
- _window.getShell().setEnabled(false);
-
- while (!shell.isDisposed())
- {
- if (!display.readAndDispatch())
- {
- display.sleep();
- }
- }
-
- // enable the main shell
- _window.getShell().setEnabled(true);
- _window.getShell().open();
- }
-
- // Creates the SWT widgets in the popup shell, to enter username and password.
- // Adds listeners to the widgets to take appropriate action
- private void createWidgets(final Shell shell)
- {
- Composite composite = new Composite(shell, SWT.NONE);
- composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- GridLayout layout = new GridLayout(2, false);
- layout.horizontalSpacing = 10;
- layout.verticalSpacing = 10;
- layout.marginHeight = 20;
- layout.marginWidth = 20;
- composite.setLayout(layout);
-
- Label user = new Label(composite, SWT.NONE);
- user.setText(USERNAME);
- user.setLayoutData(new GridData(SWT.TRAIL, SWT.TOP, false, false));
-
- final Text textUser = new Text(composite, SWT.BORDER);
- textUser.setText("");
- textUser.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- // Put cursor on this field
- textUser.setFocus();
-
- Label password = new Label(composite, SWT.NONE);
- password.setText(PASSWORD);
- password.setLayoutData(new GridData(SWT.TRAIL, SWT.TOP, false, false));
-
- final Text textPwd = new Text(composite, SWT.BORDER | SWT.SINGLE | SWT.PASSWORD);
- textPwd.setText("");
- textPwd.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
-
- //Get the text widgets
- Control[] widgets = composite.getChildren();
- for (int i=0; i < widgets.length; i++)
- {
- widgets[i].addKeyListener(new KeyAdapter()
- {
- public void keyPressed(KeyEvent event)
- {
- if (event.character == SWT.ESC)
- {
- //Escape key acts as cancel on all widgets
- shell.dispose();
- }
- }
- });
- }
-
- Composite buttonsComposite = new Composite(composite, SWT.NONE);
- buttonsComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1));
- buttonsComposite.setLayout(new GridLayout(2, true));
-
- final Button connectButton = new Button(buttonsComposite, SWT.PUSH | SWT.CENTER);
- connectButton.setText(Constants.BUTTON_CONNECT);
- GridData gridData = new GridData (SWT.TRAIL, SWT.BOTTOM, true, true);
- gridData.widthHint = 100;
- connectButton.setLayoutData(gridData);
- connectButton.setFont(ApplicationRegistry.getFont(Constants.FONT_BUTTON));
- connectButton.addSelectionListener(new SelectionAdapter(){
- public void widgetSelected(SelectionEvent event)
- {
- _user = textUser.getText();
- if ((_user == null) || (_user.trim().length() == 0))
- {
- ViewUtility.popupInfoMessage(_title, INFO_USERNAME);
- textUser.setText("");
- textUser.setFocus();
- return;
- }
-
- _password = textPwd.getText();
- if (_password == null)
- {
- ViewUtility.popupInfoMessage(_title, INFO_PASSWORD);
- textPwd.setText("");
- textPwd.setFocus();
- return;
- }
-
- _connect = true;
- shell.dispose();
- }
- });
-
- final Button cancelButton = new Button(buttonsComposite, SWT.PUSH);
- cancelButton.setText(Constants.BUTTON_CANCEL);
- gridData = new GridData (SWT.LEAD, SWT.BOTTOM, true, true);
- gridData.widthHint = 100;
- cancelButton.setLayoutData(gridData);
- cancelButton.setFont(ApplicationRegistry.getFont(Constants.FONT_BUTTON));
- cancelButton.addSelectionListener(new SelectionAdapter(){
- public void widgetSelected(SelectionEvent event)
- {
- shell.dispose();
- }
- });
-
- //Get the ok/cancel button widgets and add a new key listener
- widgets = buttonsComposite.getChildren();
- for (int i=0; i < widgets.length; i++)
- {
- widgets[i].addKeyListener(new KeyAdapter()
- {
- public void keyPressed(KeyEvent event)
- {
- if (event.character == SWT.ESC)
- {
- //Escape key acts as cancel on all widgets
- shell.dispose();
- }
- }
- });
- }
-
- shell.setDefaultButton(connectButton);
- }
-
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/Refresh.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/Refresh.java
deleted file mode 100644
index dd4cbffd84..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/Refresh.java
+++ /dev/null
@@ -1,53 +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.management.ui.actions;
-
-import org.apache.qpid.management.ui.jmx.MBeanUtility;
-import org.apache.qpid.management.ui.views.MBeanView;
-import org.apache.qpid.management.ui.views.NavigationView;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.ui.IWorkbenchWindowActionDelegate;
-
-/**
- * This action refreshes both the views -Navigation and MBeanView
- * @author Bhupendra Bhardwaj
- */
-public class Refresh extends AbstractAction implements IWorkbenchWindowActionDelegate
-{
- public void run(IAction action)
- {
- if(_window != null)
- {
- NavigationView view = (NavigationView)_window.getActivePage().findView(NavigationView.ID);
- view.refresh();
-
- MBeanView mbeanview = (MBeanView)_window.getActivePage().findView(MBeanView.ID);
- try
- {
- mbeanview.refresh();
- }
- catch (Exception ex)
- {
- MBeanUtility.handleException(ex);
- }
- }
- }
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/RemoveServer.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/RemoveServer.java
deleted file mode 100644
index e329255414..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/RemoveServer.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.management.ui.actions;
-
-import org.apache.qpid.management.ui.exceptions.InfoRequiredException;
-import org.apache.qpid.management.ui.views.NavigationView;
-import org.apache.qpid.management.ui.views.ViewUtility;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.ui.IWorkbenchWindowActionDelegate;
-
-public class RemoveServer extends AbstractAction implements IWorkbenchWindowActionDelegate
-{
- public void run(IAction action)
- {
- if(_window != null)
- {
- NavigationView view = (NavigationView)_window.getActivePage().findView(NavigationView.ID);
- try
- {
- view.removeServer();
- }
- catch(InfoRequiredException ex)
- {
- ViewUtility.popupInfoMessage("Remove Qpid server", ex.getMessage());
- }
- catch(Exception ex)
- {
- handleException(ex, "Server could not be removed", null);
- }
- }
- }
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/VersionAction.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/VersionAction.java
deleted file mode 100644
index be69fadbe8..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/VersionAction.java
+++ /dev/null
@@ -1,94 +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.management.ui.actions;
-
-import java.io.InputStream;
-import java.util.Properties;
-
-import org.apache.qpid.management.ui.Constants;
-import org.apache.qpid.management.ui.jmx.MBeanUtility;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.ui.IWorkbenchWindow;
-
-public class VersionAction extends Action
-{
- private IWorkbenchWindow _window;
- public static final String VERSION_RESOURCE = "qpidversion.properties";
-
- public static final String PRODUCT_NAME_PROPERTY = "qpid.name";
- public static final String RELEASE_VERSION_PROPERTY = "qpid.version";
- public static final String BUILD_VERSION_PROPERTY = "qpid.svnversion";
-
- private static final String DEFAULT = "unknown";
- private static String _releaseVersion;
- private static String _buildVersion;
- private static String _text;
-
- static
- {
- Properties props = new Properties();
- try
- {
- InputStream propertyStream = VersionAction.class.getClassLoader().getResourceAsStream(VERSION_RESOURCE);
- if (propertyStream != null)
- {
- props.load(propertyStream);
- _releaseVersion = readPropertyValue(props, RELEASE_VERSION_PROPERTY);
- _buildVersion = readPropertyValue(props, BUILD_VERSION_PROPERTY);
- _text = "Build Version : " + _buildVersion + "\n" +
- "Release Version : " + _releaseVersion;
- }
- else
- {
- _text = "Build Version : \n" +
- "Release Version : ";
- }
- }
- catch (Exception ex)
- {
- MBeanUtility.printStackTrace(ex);
- }
- }
-
- public VersionAction(IWorkbenchWindow window)
- {
- _window = window;
- setText("About " + Constants.APPLICATION_NAME);
- setId("qpidmc.about");
- setActionDefinitionId("qpidmc.about");
- }
-
- private static String readPropertyValue(Properties props, String propertyName)
- {
- String retVal = (String) props.get(propertyName);
- if (retVal == null)
- {
- retVal = DEFAULT;
- }
- return retVal;
- }
-
- public void run()
- {
- MessageDialog.openInformation(_window.getShell(), Constants.APPLICATION_NAME, _text);
- }
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/exceptions/InfoRequiredException.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/exceptions/InfoRequiredException.java
deleted file mode 100644
index 672426a59d..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/exceptions/InfoRequiredException.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.management.ui.exceptions;
-
-public class InfoRequiredException extends Exception
-{
- private static final long serialVersionUID = 1L;
-
- public InfoRequiredException(String message)
- {
- super(message);
- }
-
- public InfoRequiredException(String msg, Throwable t)
- {
- super(msg, t);
- }
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/exceptions/ManagementConsoleException.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/exceptions/ManagementConsoleException.java
deleted file mode 100644
index 17c127c01a..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/exceptions/ManagementConsoleException.java
+++ /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.
- *
- */
-
-package org.apache.qpid.management.ui.exceptions;
-
-@SuppressWarnings("serial")
-public class ManagementConsoleException extends Exception
-{
- public ManagementConsoleException(String message)
- {
- super(message);
- }
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/ClientListener.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/ClientListener.java
deleted file mode 100644
index 6fa78b1d36..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/ClientListener.java
+++ /dev/null
@@ -1,84 +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.management.ui.jmx;
-
-import javax.management.MBeanServerNotification;
-import javax.management.Notification;
-import javax.management.NotificationListener;
-import javax.management.ObjectName;
-import javax.management.remote.JMXConnectionNotification;
-
-import org.apache.qpid.management.ui.ApplicationRegistry;
-import org.apache.qpid.management.ui.ManagedServer;
-
-
-public class ClientListener implements NotificationListener
-{
- protected ManagedServer server = null;
- protected JMXServerRegistry serverRegistry = null;
-
- public ClientListener(ManagedServer server)
- {
- this.server = server;
- serverRegistry = (JMXServerRegistry)ApplicationRegistry.getServerRegistry(server);
- }
-
- public void handleNotification(Notification notification, Object handback)
- {
- String type = notification.getType();
-
- if(notification instanceof MBeanServerNotification)
- {
- ObjectName objName = ((MBeanServerNotification)notification).getMBeanName();
-
- if (MBeanServerNotification.REGISTRATION_NOTIFICATION.equals(type))
- {
- getServerRegistry().registerManagedObject(objName);
- }
- else if (MBeanServerNotification.UNREGISTRATION_NOTIFICATION.equals(type))
- {
- getServerRegistry().unregisterManagedObject(objName);
- }
- }
- else if (JMXConnectionNotification.FAILED.equals(type))
- {
- ApplicationRegistry.serverConnectionClosedRemotely(server);
- MBeanUtility.printOutput("JMX Connection to " + server.getName() + " failed.");
- }
- else if (JMXConnectionNotification.CLOSED.equals(type))
- {
- ApplicationRegistry.serverConnectionClosedRemotely(server);
- MBeanUtility.printOutput("JMX Connection to " + server.getName() + " was closed.");
- }
- }
-
- protected JMXServerRegistry getServerRegistry()
- {
- if (serverRegistry == null)
- serverRegistry = (JMXServerRegistry)ApplicationRegistry.getServerRegistry(server);
-
- return serverRegistry;
- }
- public ManagedServer getServer()
- {
- return server;
- }
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/ClientNotificationListener.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/ClientNotificationListener.java
deleted file mode 100644
index 2af8e681ae..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/ClientNotificationListener.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.management.ui.jmx;
-
-import javax.management.Notification;
-import javax.management.ObjectName;
-
-import org.apache.qpid.management.ui.ManagedServer;
-
-public class ClientNotificationListener extends ClientListener
-{
- public ClientNotificationListener(ManagedServer server)
- {
- super(server);
- }
-
- public void handleNotification(Notification notification, Object handback)
- {
- ObjectName objName = (ObjectName)notification.getSource();
- getServerRegistry().addNotification(objName, notification);
- }
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/JMXManagedObject.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/JMXManagedObject.java
deleted file mode 100644
index a8fb864cf6..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/JMXManagedObject.java
+++ /dev/null
@@ -1,71 +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.management.ui.jmx;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.management.ObjectName;
-
-import org.apache.qpid.management.ui.ManagedBean;
-
-
-public class JMXManagedObject extends ManagedBean
-{
- private ObjectName _objName;
-
- public JMXManagedObject(ObjectName objName)
- {
- super();
- this._objName = objName;
- setUniqueName(_objName.toString());
- setDomain(_objName.getDomain());
-
- HashMap<String,String> props = new HashMap<String,String>(_objName.getKeyPropertyList());
-
- for(Map.Entry<String,String> entry : props.entrySet())
- {
- String value = entry.getValue();
-
- if(value != null)
- {
- try
- {
- //if the name is quoted in the ObjectName, unquote it
- value = ObjectName.unquote(value);
- entry.setValue(value);
- }
- catch(IllegalArgumentException e)
- {
- //ignore, this just means the name is not quoted
- //and can be left unchanged
- }
- }
- }
-
- super.setProperties(props);
- }
-
- public ObjectName getObjectName()
- {
- return _objName;
- }
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/JMXServerRegistry.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/JMXServerRegistry.java
deleted file mode 100644
index 717f781334..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/JMXServerRegistry.java
+++ /dev/null
@@ -1,612 +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.management.ui.jmx;
-
-import static org.apache.qpid.management.ui.Constants.ALL;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.List;
-import java.util.concurrent.CopyOnWriteArrayList;
-
-import javax.management.MBeanInfo;
-import javax.management.MBeanServerConnection;
-import javax.management.Notification;
-import javax.management.ObjectName;
-import javax.management.remote.JMXConnector;
-
-import org.apache.qpid.management.common.JMXConnnectionFactory;
-import org.apache.qpid.management.ui.ApplicationRegistry;
-import org.apache.qpid.management.ui.ManagedBean;
-import org.apache.qpid.management.ui.ManagedServer;
-import org.apache.qpid.management.ui.ServerRegistry;
-import org.apache.qpid.management.ui.model.ManagedAttributeModel;
-import org.apache.qpid.management.ui.model.NotificationInfoModel;
-import org.apache.qpid.management.ui.model.NotificationObject;
-import org.apache.qpid.management.ui.model.OperationDataModel;
-
-
-public class JMXServerRegistry extends ServerRegistry
-{
- private ObjectName _serverObjectName = null;
- private JMXConnector _jmxc = null;
- private MBeanServerConnection _mbsc = null;
- private String _securityMechanism = null;
-
- private List<String> _usersList;
- // When an mbean gets removed from mbean server, then the notification listener
- // will add that mbean in this list.
- private List<ManagedBean> _mbeansToBeRemoved = new ArrayList<ManagedBean>();
-
- // Map containing all managed beans and mapped with unique mbean name
- private HashMap<String, ManagedBean> _mbeansMap = new HashMap<String, ManagedBean>();
- // Map containing MBeanInfo for all mbeans and mapped with unique mbean name
- private HashMap<String, MBeanInfo> _mbeanInfoMap = new HashMap<String, MBeanInfo>();
- // Map containing attribute model for all mbeans and mapped with unique mbean name
- private HashMap<String, ManagedAttributeModel> _attributeModelMap = new HashMap<String, ManagedAttributeModel>();
- // Map containing operation model for all mbeans and mapped with unique mbean name
- private HashMap<String, OperationDataModel> _operationModelMap = new HashMap<String, OperationDataModel>();
- // Map containing NotificationInfo for all mbeans and mapped with unique mbean name
- private HashMap<String, List<NotificationInfoModel>> _notificationInfoMap = new HashMap<String, List<NotificationInfoModel>>();
- // Map containing all notifications sent for all mbeans, which are registered for notification
- private HashMap<String, List<NotificationObject>> _notificationsMap = new HashMap<String, List<NotificationObject>>();
- // For mbeans which have subscribed for a notification type
- // mbean unique name mapped with notification map. Notification map contains list of notification type
- // mapped with notification name. Notification type list contains those notification types,
- // which are subscribed for notification.
- private HashMap<String, HashMap<String, List<String>>> _subscribedNotificationMap = new HashMap<String, HashMap<String, List<String>>>();
-
- // listener for registration or unregistratioj of mbeans on mbean server
- private ClientNotificationListener _notificationListener = null;
- // listener for server connection. Receives notification if server connection goes down
- private ClientListener _clientListener = null;
-
- public JMXServerRegistry(ManagedServer server) throws Exception
- {
- super(server);
-
- _jmxc = JMXConnnectionFactory.getJMXConnection(
- ApplicationRegistry.timeout, server.getHost(),
- server.getPort(), server.getUser(), server.getPassword());
-
- _mbsc = _jmxc.getMBeanServerConnection();
-
- _clientListener = new ClientListener(server);
- _notificationListener = new ClientNotificationListener(server);
-
- _jmxc.addConnectionNotificationListener(_clientListener, null, null);
- _serverObjectName = new ObjectName("JMImplementation:type=MBeanServerDelegate");
- _mbsc.addNotificationListener(_serverObjectName, _clientListener, null, null);
-
- }
-
- public MBeanServerConnection getServerConnection()
- {
- return _mbsc;
- }
-
-
- public String getSecurityMechanism()
- {
- return _securityMechanism;
- }
-
- /**
- * removes all listeners from the mbean server. This is required when user
- * disconnects the Qpid server connection
- */
- public void closeServerConnection() throws IOException
- {
- if(isServerConnectionClosed())
- {
- //connection was already closed
- return;
- }
-
- try
- {
- //remove the listener from the JMXConnector
- if (_jmxc != null && _clientListener != null)
- {
- _jmxc.removeConnectionNotificationListener(_clientListener);
- }
- }
- catch (Exception e)
- {
- //ignore
- }
-
- try
- {
- //remove the listener from the MBeanServerDelegate MBean
- if (_mbsc != null && _clientListener != null)
- {
- _mbsc.removeNotificationListener(_serverObjectName, _clientListener);
- }
- }
- catch (Exception e)
- {
- //ignore
- }
-
- if (_mbsc != null && _clientListener != null)
- {
- //remove any listeners from the Qpid MBeans
- for (String mbeanName : _subscribedNotificationMap.keySet())
- {
- try
- {
- _mbsc.removeNotificationListener(new ObjectName(mbeanName), _notificationListener);
- }
- catch (Exception e)
- {
- //ignore
- }
- }
- }
-
- //close the JMXConnector
- if (_jmxc != null)
- {
- _jmxc.close();
- }
-
- serverConnectionClosed();
- }
-
- public ManagedBean getManagedObject(String uniqueName)
- {
- return _mbeansMap.get(uniqueName);
- }
-
- public void addManagedObject(ManagedBean mbean)
- {
- if (mbean.isQueue())
- {
- addQueueMBean(mbean);
- }
- else if (mbean.isExchange())
- {
- addExchangeMBean(mbean);
- }
- else if (mbean.isConnection())
- {
- addConnectionMBean(mbean);
- }
- else if (mbean.isVirtualHostManager())
- {
- addVirtualHostManagerMBean(mbean);
- }
-
- addVirtualHost(mbean.getVirtualHostName());
- _mbeansMap.put(mbean.getUniqueName(), mbean);
- }
-
- public void removeManagedObject(ManagedBean mbean)
- {
- if (mbean == null)
- {
- return;
- }
-
- _mbeansMap.remove(mbean.getUniqueName());
-
- if (mbean.isQueue())
- {
- removeQueueMBean(mbean);
- }
- else if (mbean.isExchange())
- {
- removeExchangeMBean(mbean);
- }
- else if (mbean.isConnection())
- {
- removeConnectionMBean(mbean);
- }
- else if (mbean.isVirtualHostManager())
- {
- removeVirtualHostManagerMBean(mbean);
- }
- }
-
- public void putMBeanInfo(ManagedBean mbean, MBeanInfo mbeanInfo)
- {
- _mbeanInfoMap.put(mbean.getUniqueName(), mbeanInfo);
- }
- public MBeanInfo getMBeanInfo(ManagedBean mbean)
- {
- return _mbeanInfoMap.get(mbean.getUniqueName());
- }
-
- public List<ManagedBean> getMBeans()
- {
- return new ArrayList<ManagedBean>(_mbeansMap.values());
- }
-
- public void setNotificationInfo(ManagedBean mbean, List<NotificationInfoModel>value)
- {
- _notificationInfoMap.put(mbean.getUniqueName(), value);
- }
-
- public List<NotificationInfoModel> getNotificationInfo(ManagedBean mbean)
- {
- return _notificationInfoMap.get(mbean.getUniqueName());
- }
-
- public void addNotification(ObjectName objName, Notification notification)
- {
- List<NotificationObject> list = _notificationsMap.get(objName.toString());
- NotificationObject obj = new NotificationObject(notification.getSequenceNumber(),
- new Date(notification.getTimeStamp()),
- notification.getMessage(),
- notification.getSource(),
- notification.getType());
-
- if (list == null)
- {
- list = new ArrayList<NotificationObject>();
- _notificationsMap.put(objName.toString(), list);
- }
-
- list.add(obj);
- }
-
- /**
- * Returns all the notification objects for a given mbean. If mbean is null, it returns
- * notification objects for all the mbeans.
- */
- public List<NotificationObject> getNotifications(ManagedBean mbean)
- {
- if (mbean == null)
- {
- List<NotificationObject> totalList = new ArrayList<NotificationObject>();
- for (List<NotificationObject> list : _notificationsMap.values())
- {
- totalList.addAll(list);
- }
- return totalList;
- }
- else
- {
- return _notificationsMap.get(mbean.getUniqueName());
- }
- }
-
- public List<NotificationObject> getNotifications(String virtualhost)
- {
- List<NotificationObject> vhostNotificationsList = new ArrayList<NotificationObject>();
-
- //iterate over all the notification lists for mbeans with subscribed notifications
- for (List<NotificationObject> list : _notificationsMap.values())
- {
- if(list == null || list.isEmpty())
- {
- continue;
- }
-
- //Check the source vhost of the first notification
- NotificationObject notification = list.get(0);
-
- if (notification != null)
- {
- String sourceVhost = notification.getSourceVirtualHost();
- if(sourceVhost != null)
- {
- if(sourceVhost.equalsIgnoreCase(virtualhost))
- {
- //If it matches, add the entire list as they are from the same vhost (same source mbean)
- vhostNotificationsList.addAll(list);
- }
- }
- }
- }
-
- return vhostNotificationsList;
- }
-
- public void clearNotifications(ManagedBean mbean, List<NotificationObject> list)
- {
- if (mbean == null)
- {
- if (list == null || list.isEmpty())
- {
- // All notifications of all mbeans to be cleared
- _notificationsMap.clear();
- }
- else
- {
- // Clear the selected notifications
- for (NotificationObject obj : list)
- {
- mbean = _mbeansMap.get(obj.getSource().toString());
- List<NotificationObject> nList = _notificationsMap.get(mbean.getUniqueName());
- if (nList != null && !nList.isEmpty())
- {
- nList.remove(obj);
- }
- }
- }
- }
- else
- {
- if (list == null || list.isEmpty())
- {
- // All notifications of this mbean to be cleared
- List<NotificationObject> nList = _notificationsMap.get(mbean.getUniqueName());
- if (nList != null && !nList.isEmpty())
- {
- nList.clear();
- }
- }
- else
- {
- // Clear the selected notifications
- for (NotificationObject obj : list)
- {
- List<NotificationObject> nList = _notificationsMap.get(mbean.getUniqueName());
- if (nList != null && !nList.isEmpty())
- {
- nList.remove(obj);
- }
- }
- }
- }
- }
-
-
-
- /**
- * Adds notification name and type to the map. The map contains all the notification names,
- * subscribed for an mbean.
- * @param mbean
- * @param name
- * @param type
- */
- public void addNotificationListener(ManagedBean mbean, String name, String type)
- {
- // Get the subscribed notifications map for given mbean. If map is null then create a new one.
- HashMap<String, List<String>> map = _subscribedNotificationMap.get(mbean.getUniqueName());
- if (map == null)
- {
- map = new HashMap<String, List<String>>();
- _subscribedNotificationMap.put(mbean.getUniqueName(),map);
- }
-
- // Get the list of notification types for given notification name. If null, then create a new list.
- List<String> list = map.get(name);
- if (list == null)
- {
- list = new ArrayList<String>();
- map.put(name, list);
- }
- // Now add the notification type to the list
- if (ALL.equals(type))
- {
- List<NotificationInfoModel> infoList = _notificationInfoMap.get(mbean.getUniqueName());
- for (NotificationInfoModel model : infoList)
- {
- if (model.getName().equals(name))
- {
- String[] types = model.getTypes();
- for (int i = 0; i < types.length; i++)
- {
- list.add(types[i]);
- }
- }
- }
- }
- else
- {
- list.add(type);
- }
-
- //System.out.println("Subscribed for notification :" + mbean.getUniqueName());
- }
-
- /**
- * Checks if the given notification name and type are subscribed for the mbean.
- */
- public boolean hasSubscribedForNotifications(ManagedBean mbean, String name, String type)
- {
- if (_subscribedNotificationMap.containsKey(mbean.getUniqueName()))
- {
- HashMap<String, List<String>> map = _subscribedNotificationMap.get(mbean.getUniqueName());
- if (map.containsKey(name))
- {
- if (map.get(name).contains(type))
- {
- return true;
- }
- }
- }
- return false;
- }
-
- /**
- * Clears the notification name and type information from the subscribed notifications map
- * and removes the listener from mbeanserver connection
- * @param mbean
- * @param name
- * @param type
- * @throws Exception
- */
- public void removeNotificationListener(ManagedBean mbean, String name, String type) throws Exception
- {
- //System.out.println("Removed notification listener :" + mbean.getUniqueName() + name +type);
- if (_subscribedNotificationMap.containsKey(mbean.getUniqueName()))
- {
- // get the notifications map. This map contains the notification name mapped with the notification types
- HashMap<String, List<String>> map = _subscribedNotificationMap.get(mbean.getUniqueName());
- if (map.containsKey(name))
- {
- if (ALL.equals(type))
- {
- map.remove(name);
- }
- else if (type != null)
- {
- map.get(name).remove(type);
- if (map.get(name).isEmpty())
- {
- map.remove(name);
- }
- }
- }
- if (map.size() == 0)
- {
- _subscribedNotificationMap.remove(mbean.getUniqueName());
- }
-
- JMXManagedObject jmxbean = (JMXManagedObject)mbean;
- _mbsc.removeNotificationListener(jmxbean.getObjectName(), _notificationListener);
- }
- }
-
- /**
- * When the mbean registration request is received from the mbean server, then the client listener
- * can use this method. It will add the mbean to a list, which will be used to add the mbean to
- * the registry and gui
- * @param objName
- */
- public void registerManagedObject(ObjectName objName)
- {
- JMXManagedObject managedObject = new JMXManagedObject(objName);
- managedObject.setServer(getManagedServer());
- addManagedObject(managedObject);
- }
-
- /**
- * When mbean unregistration notification is received from the mbean server, then client listener
- * can invoke this method. It will add the mbean to the list of mbeans to be removed from registry
- * @param objName
- */
- public void unregisterManagedObject(ObjectName objName)
- {
- ManagedBean mbean = _mbeansMap.get(objName.toString());
- // Check if mbean was not available in the map. It can happen if mbean unregistration
- // notification is received and the mbean is not added in the map.
- if (mbean != null)
- {
- removeManagedObject(mbean);
- _mbeansToBeRemoved.add(mbean);
- }
- }
-
- public List<ManagedBean> getObjectsToBeRemoved()
- {
- if (_mbeansToBeRemoved.isEmpty())
- return null;
- else
- {
- List<ManagedBean> list = new CopyOnWriteArrayList<ManagedBean>(_mbeansToBeRemoved);
- _mbeansToBeRemoved.clear();
- return list;
- }
- }
-
- public void setAttributeModel(ManagedBean mbean, ManagedAttributeModel value)
- {
- _attributeModelMap.put(mbean.getUniqueName(), value);
- }
-
- public ManagedAttributeModel getAttributeModel(ManagedBean mbean)
- {
- return _attributeModelMap.get(mbean.getUniqueName());
- }
-
- public void setOperationModel(ManagedBean mbean, OperationDataModel value)
- {
- _operationModelMap.put(mbean.getUniqueName(), value);
- }
-
- public OperationDataModel getOperationModel(ManagedBean mbean)
- {
- return _operationModelMap.get(mbean.getUniqueName());
- }
-
- public List<String> getQueueNames(String virtualHostName)
- {
- List<ManagedBean> list = getQueues(virtualHostName);
- if (list == null)
- return null;
-
- List<String> queueNames = new ArrayList<String>();
- for (ManagedBean mbean : list)
- {
- queueNames.add(mbean.getName());
- }
- return queueNames;
- }
-
- public String[] getExchangeNames(String virtualHostName)
- {
- List<ManagedBean> list = getExchanges(virtualHostName);
- if (list == null)
- return null;
-
- String[] exchanges = new String[list.size()];
- int i = 0;
- for (ManagedBean mbean : list)
- {
- exchanges[i++] = mbean.getName();
- }
- return exchanges;
- }
-
- public String[] getConnectionNames(String virtualHostName)
- {
- List<ManagedBean> list = getExchanges(virtualHostName);
- if (list == null)
- return null;
-
- String[] connections = new String[list.size()];
- int i = 0;
- for (ManagedBean mbean : list)
- {
- connections[i++] = mbean.getName();
- }
- return connections;
- }
-
- public void setUserList(List<String> list)
- {
- _usersList = list;
- Collections.sort(_usersList);
- }
-
- public List<String> getUsernames()
- {
- return _usersList;
- }
-
- public ClientNotificationListener getNotificationListener()
- {
- return _notificationListener;
- }
-
- public ClientListener getClientListener()
- {
- return _clientListener;
- }
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/MBeanUtility.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/MBeanUtility.java
deleted file mode 100644
index 6d6aa80f4d..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/MBeanUtility.java
+++ /dev/null
@@ -1,619 +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.management.ui.jmx;
-
-import java.io.IOException;
-import java.math.BigInteger;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-
-import javax.management.Attribute;
-import javax.management.AttributeList;
-import javax.management.InstanceNotFoundException;
-import javax.management.JMException;
-import javax.management.MBeanAttributeInfo;
-import javax.management.MBeanException;
-import javax.management.MBeanInfo;
-import javax.management.MBeanNotificationInfo;
-import javax.management.MBeanOperationInfo;
-import javax.management.MBeanServerConnection;
-import javax.management.MBeanServerInvocationHandler;
-import javax.management.MalformedObjectNameException;
-import javax.management.ObjectInstance;
-import javax.management.ObjectName;
-import javax.management.ReflectionException;
-
-import org.apache.qpid.management.common.mbeans.ServerInformation;
-import org.apache.qpid.management.ui.ApiVersion;
-import org.apache.qpid.management.ui.ApplicationRegistry;
-import org.apache.qpid.management.ui.Constants;
-import org.apache.qpid.management.ui.ManagedBean;
-import org.apache.qpid.management.ui.ManagedServer;
-import org.apache.qpid.management.ui.exceptions.ManagementConsoleException;
-import org.apache.qpid.management.ui.model.AttributeData;
-import org.apache.qpid.management.ui.model.ManagedAttributeModel;
-import org.apache.qpid.management.ui.model.NotificationInfoModel;
-import org.apache.qpid.management.ui.model.OperationData;
-import org.apache.qpid.management.ui.model.OperationDataModel;
-import org.apache.qpid.management.ui.model.ParameterData;
-import org.apache.qpid.management.ui.views.ViewUtility;
-
-/**
- * Utility class for all mbeanserver related operations. Keeps all JMX code out from view and model classes
- * @author Bhupendra Bhardwaj
- */
-public class MBeanUtility
-{
- public static final BigInteger MAX_LONG = BigInteger.valueOf(Long.MAX_VALUE);
- public static final BigInteger MAX_INT = BigInteger.valueOf(Integer.MAX_VALUE);
- /**
- * Retrieves the MBeanInfo from MBeanServer and stores in the application registry
- * @param mbean managed bean
- * @return MBeanInfo
- * @throws Exception, if server connection is null or if server throws Exception
- */
- public static MBeanInfo getMBeanInfo(ManagedBean mbean) throws Exception
- {
- ManagedServer server = mbean.getServer();
- JMXServerRegistry serverRegistry = (JMXServerRegistry)ApplicationRegistry.getServerRegistry(server);
-
- MBeanServerConnection mbsc = serverRegistry.getServerConnection();
- if (mbsc == null)
- {
- throw new ManagementConsoleException("Server connection is broken");
- }
-
- JMXManagedObject jmxbean = (JMXManagedObject)mbean;
- MBeanInfo mbeanInfo = mbsc.getMBeanInfo(jmxbean.getObjectName());
- serverRegistry.putMBeanInfo(mbean, mbeanInfo);
-
- // populate the server registry with attribute and operation info
- getAttributes(mbean);
- getOperations(mbean);
-
- return mbeanInfo;
- }
-
- /**
- * executes the MBean operation
- * @param mbean
- * @param opData
- * @return MBean operation return value
- * @throws Exception if server connection is broken or if operation execution fails on the mbean server
- */
- public static Object execute(ManagedBean mbean, OperationData opData) throws Exception
- {
- String opName = opData.getName();
- Object[] values = null;
- String[] signature = null;
-
- List<ParameterData> params = opData.getParameters();
- if (params != null && !params.isEmpty())
- {
- signature = new String[params.size()];;
- values = new Object[params.size()];
- for (int i = 0; i < params.size(); i++)
- {
- signature[i] = params.get(i).getType();
- values[i] = params.get(i).getValue();
- }
- }
-
- ManagedServer server = mbean.getServer();
- JMXServerRegistry serverRegistry = (JMXServerRegistry)ApplicationRegistry.getServerRegistry(server);
-
- MBeanServerConnection mbsc = serverRegistry.getServerConnection();
- if (mbsc == null)
- {
- throw new ManagementConsoleException("Server connection is broken");
- // TODO
- // try and get the connection again if it was disconnected
- }
- JMXManagedObject jmxbean = (JMXManagedObject)mbean;
- return mbsc.invoke(jmxbean.getObjectName(), opName, values, signature);
- }
-
- /**
- * @see MBeanUtility#handleException(ManagedBean, Exception)
- */
- public static void handleException(Exception ex)
- {
- handleException(null, ex);
- }
-
- /**
- * handels the exception received. Shows the exception to the user in best suitable way
- * @param mbean managed bean
- * @param ex Exception
- */
- public static void handleException(ManagedBean mbean, Throwable ex)
- {
- if (mbean == null)
- {
- ViewUtility.popupErrorMessage("Error", "Managed Object is null \n" + ex.toString());
- printStackTrace(ex);
- }
- else if (ex instanceof ReflectionException)
- {
- ViewUtility.popupErrorMessage(mbean.getInstanceName(), "Server has thrown error \n" + ex.toString());
- printStackTrace(ex);
- }
- else if (ex instanceof InstanceNotFoundException)
- {
- ViewUtility.popupErrorMessage(mbean.getInstanceName(), "Managed Object Not Found \n" + ex.toString());
- printStackTrace(ex);
- }
- else if (ex instanceof MBeanException)
- {
- String cause = ((MBeanException)ex).getTargetException().getMessage();
- if (cause == null)
- cause = ex.toString();
- ViewUtility.popupInfoMessage(mbean.getInstanceName(), cause);
- }
- else if (ex instanceof JMException)
- {
- ViewUtility.popupErrorMessage(mbean.getInstanceName(), "Management Exception occured \n" + ex.toString());
- }
- else if (ex instanceof ManagementConsoleException)
- {
- ViewUtility.popupErrorMessage(mbean.getInstanceName(), ex.getMessage());
- }
- else if (ex instanceof SecurityException)
- {
- ViewUtility.popupErrorMessage(mbean.getInstanceName(), ex.getMessage());
- }
- else
- {
- if (ex.getCause() != null)
- {
- handleException(mbean, ex.getCause());
- }
- else
- {
- String msg = ex.getMessage();
- if (msg == null)
- {
- msg = ex.toString();
- }
- ViewUtility.popupErrorMessage(mbean.getInstanceName(), msg);
- printStackTrace(ex);
- }
- }
-
- }
-
- /**
- * Registers the notification listener with the MBeanServer
- * @param mbean managed bean
- * @param name notification name
- * @param type notification type
- * @throws Exception if server connection is broken or if listener could not be created
- */
- public static void createNotificationlistener(ManagedBean mbean, String name, String type)
- throws Exception
- {
- JMXManagedObject jmxbean = (JMXManagedObject)mbean;
- JMXServerRegistry serverRegistry = (JMXServerRegistry)ApplicationRegistry.getServerRegistry(mbean);
- serverRegistry.addNotificationListener(mbean, name, type);
- MBeanServerConnection mbsc = serverRegistry.getServerConnection();
-
- if (mbsc == null)
- {
- throw new ManagementConsoleException("Server connection is broken");
- }
- mbsc.addNotificationListener(jmxbean.getObjectName(), serverRegistry.getNotificationListener(), null, null);
- }
-
- public static void removeNotificationListener(ManagedBean mbean, String name, String type) throws Exception
- {
- JMXServerRegistry serverRegistry = (JMXServerRegistry)ApplicationRegistry.getServerRegistry(mbean);
- serverRegistry.removeNotificationListener(mbean, name, type);
- }
-
- /**
- * Checks if the server registry contains attribute information for this mbean. If not then it queries the
- * mbean server for complete mbean information, else it gets the latest value of the given attribute
- * from mbean server.
- * @return attribute data for the given mbean attribute
- */
- public static AttributeData getAttributeData(ManagedBean mbean, String attribute) throws Exception
- {
- JMXServerRegistry serverRegistry = (JMXServerRegistry)ApplicationRegistry.getServerRegistry(mbean);
- ManagedAttributeModel attributeModel = serverRegistry.getAttributeModel(mbean);
- if (attributeModel == null)
- {
- // If process is here, it means the mbeanInfo is not retrieved from mbean server even once for this mbean
- getMBeanInfo(mbean);
- }
- else
- {
- // refresh attribute value from mbean server
- refreshAttribute(mbean, attribute);
- }
- attributeModel = serverRegistry.getAttributeModel(mbean);
- return attributeModel.getAttribute(attribute);
- }
-
- /**
- * Retrieves the latest attribute value from mbean server for the given mbean attribute
- * and also sets that value in the attribute model in the server registry
- * @return latest attribute value for the given mbean attribute
- */
- public static Object refreshAttribute(ManagedBean mbean, String attribute) throws Exception
- {
- JMXServerRegistry serverRegistry = (JMXServerRegistry)ApplicationRegistry.getServerRegistry(mbean);
- MBeanServerConnection mbsc = serverRegistry.getServerConnection();
-
- if (mbsc == null)
- {
- throw new ManagementConsoleException("Server connection is broken");
- }
-
- Object value = mbsc.getAttribute(((JMXManagedObject)mbean).getObjectName(), attribute);
- // update the attribute data in server registry for this attribute
- ManagedAttributeModel attributeModel = serverRegistry.getAttributeModel(mbean);
- attributeModel.setAttributeValue(attribute, value);
- return value;
- }
-
-
- /**
- * Returns a List of Object arrays containing the requested attribute values (in the same sequence requested) for each queue in the virtualhost.
- * If a particular attribute cant be found or raises an mbean/reflection exception whilst being gathered its value is substituted with the String "-".
- */
- public static List<List<Object>> getQueueAttributes(List<ManagedBean> mbeans, String[] attributes)
- {
- List<List<Object>> results = new ArrayList<List<Object>>();
-
- MBeanServerConnection mbsc = null;
- if(mbeans.isEmpty())
- {
- return results;
- }
- else
- {
- ManagedBean mbean = mbeans.get(0);
- JMXServerRegistry serverRegistry = (JMXServerRegistry)ApplicationRegistry.getServerRegistry(mbean);
- mbsc = serverRegistry.getServerConnection();
- }
-
- if(mbsc == null)
- {
- return results;
- }
-
- for(ManagedBean mbean : mbeans)
- {
- HashMap<String,Object> tempResults = new HashMap<String,Object>();
-
- ObjectName objName = ((JMXManagedObject)mbean).getObjectName();
- try
- {
- AttributeList list = mbsc.getAttributes(objName, attributes);
-
- for (Attribute attr : list.toArray(new Attribute[0]))
- {
- tempResults.put(attr.getName(), attr.getValue());
- }
-
- List<Object> attributeValues = new ArrayList<Object>(attributes.length);
-
- for(int i = 0; i <attributes.length; i++)
- {
- if(tempResults.containsKey(attributes[i]))
- {
- attributeValues.add(tempResults.get(attributes[i]));
- }
- else
- {
- attributeValues.add("-");
- }
- }
-
- results.add(attributeValues);
- }
- catch (Exception ignore)
- {
- continue;
- }
- }
-
- return results;
- }
-
-
- /**
- * Retrieves the attribute values from MBeanSever and stores in the server registry.
- * @param mbean
- * @return the attribute model
- * @throws Exception if attributes can not be retrieved from MBeanServer
- */
- public static ManagedAttributeModel getAttributes(ManagedBean mbean) throws Exception
- {
- ObjectName objName = ((JMXManagedObject)mbean).getObjectName();
- String[] attributes = null;
- AttributeList list = null;
-
- JMXServerRegistry serverRegistry = (JMXServerRegistry)ApplicationRegistry.getServerRegistry(mbean);
- MBeanServerConnection mbsc = serverRegistry.getServerConnection();
- MBeanAttributeInfo[] attributesInfo = null;
- ManagedAttributeModel attributeModel = serverRegistry.getAttributeModel(mbean);
-
- if (attributeModel == null)
- {
- // If the process is here, then it means the attribute values are not retrieved from mbean server
- // even once for this mbean. Create attribute model, retrieve values from mbean server and
- // set the attribute model in server registry for this mbean
- attributeModel = new ManagedAttributeModel();
- attributesInfo = serverRegistry.getMBeanInfo(mbean).getAttributes();
- attributes = new String[attributesInfo.length];
- for (int i = 0; i< attributesInfo.length ; i++)
- {
- attributes[i] = attributesInfo[i].getName();
- attributeModel.setAttributeDescription(attributes[i], attributesInfo[i].getDescription());
- attributeModel.setAttributeWritable(attributes[i], attributesInfo[i].isWritable());
- attributeModel.setAttributeReadable(attributes[i], attributesInfo[i].isReadable());
- }
- }
- else
- {
- attributes = attributeModel.getAttributeNames().toArray(new String[0]);
- }
-
- if (attributes.length != 0)
- {
- list = mbsc.getAttributes(objName, attributes);
- for (Iterator itr = list.iterator(); itr.hasNext();)
- {
- Attribute attrib = (Attribute)itr.next();
- attributeModel.setAttributeValue(attrib.getName(), attrib.getValue());
- }
- }
-
- serverRegistry.setAttributeModel(mbean, attributeModel);
- return attributeModel;
- }
-
- /**
- * Updates the attribute value of an MBean
- * @param mbean
- * @param attribute
- * @param value
- * @throws Exception if MBeanServer throws exception in updating the attribute value
- */
- public static void updateAttribute(ManagedBean mbean, AttributeData attribute, String value) throws Exception
- {
- JMXManagedObject jmxbean = (JMXManagedObject)mbean;
- JMXServerRegistry serverRegistry = (JMXServerRegistry)ApplicationRegistry.getServerRegistry(mbean);
-
- MBeanServerConnection mbsc = serverRegistry.getServerConnection();
-
- Object newValue = value;
- if (attribute.getDataType().equals(Long.class.getName()))
- {
- if (MAX_LONG.compareTo(new BigInteger(value)) == -1)
- {
- throw new ManagementConsoleException("Entered value is too big for \"" +
- ViewUtility.getDisplayText(attribute.getName()) + "\"");
- }
- newValue = Long.parseLong(value);
- }
- else if (attribute.getDataType().equals(Integer.class.getName()))
- {
- if (MAX_INT.compareTo(new BigInteger(value)) == -1)
- {
- throw new ManagementConsoleException("Entered value is too big for " + attribute.getName());
- }
- newValue = Integer.parseInt(value);
- }
- else if (attribute.getDataType().equals(Boolean.class.getName()))
- {
- if (!value.equalsIgnoreCase("true") && !value.equalsIgnoreCase("false"))
- {
- throw new ManagementConsoleException("Entered value was not true or false");
- }
-
- newValue = Boolean.valueOf(value);
- }
-
- mbsc.setAttribute(jmxbean.getObjectName(), new Attribute(attribute.getName(), newValue));
- // Update the value in the registry, to avoid refreshing from mbsc
- ManagedAttributeModel attributeModel = serverRegistry.getAttributeModel(mbean);
- attributeModel.setAttributeValue(attribute.getName(), newValue);
- }
-
- /**
- * populates the operation data model in server registry for given mbean
- * @param mbean
- * @return operation data model
- */
- public static OperationDataModel getOperations(ManagedBean mbean)
- {
- JMXServerRegistry serverRegistry = (JMXServerRegistry)ApplicationRegistry.getServerRegistry(mbean);
- OperationDataModel dataModel = serverRegistry.getOperationModel(mbean);
- if (dataModel == null)
- {
- // Create operation model and set it in server registry for this mbean
- MBeanOperationInfo[] operationsInfo = serverRegistry.getMBeanInfo(mbean).getOperations();
- dataModel = new OperationDataModel();
-
- for (int i = 0; i < operationsInfo.length; i++)
- {
- dataModel.addOperation(operationsInfo[i]);
- }
-
- serverRegistry.setOperationModel(mbean, dataModel);
- }
- return dataModel;
- }
-
- /**
- * populates the notification in the server registry for given mbean
- * @param mbean
- * @return notification info model
- */
- public static NotificationInfoModel[] getNotificationInfo(ManagedBean mbean)
- {
- JMXServerRegistry serverRegistry = (JMXServerRegistry)ApplicationRegistry.getServerRegistry(mbean);
- MBeanNotificationInfo[] info = serverRegistry.getMBeanInfo(mbean).getNotifications();
-
- // Check if this mbean sends any notification
- if (info == null || info.length == 0)
- return null;
-
- // Create notification model if not already set in the server registry for this mbean
- List<NotificationInfoModel> list = serverRegistry.getNotificationInfo(mbean);
- if (list != null)
- return list.toArray(new NotificationInfoModel[0]);
- else
- list = new ArrayList<NotificationInfoModel>();
-
- for (int i = 0; i < info.length; i++)
- {
- list.add(new NotificationInfoModel(info[i].getName(), info[i].getDescription(), info[i].getNotifTypes()));
- }
-
- // Set the notification model in the server registry for this mbean
- serverRegistry.setNotificationInfo(mbean, list);
- return list.toArray(new NotificationInfoModel[0]);
- }
-
- /**
- * Retrieves all the MBeans from mbean server for a given domain
- * @return list of ManagedBeans
- */
- public static List<ManagedBean> getManagedObjectsForDomain(ManagedServer server, String domain) throws MalformedObjectNameException, NullPointerException, IOException
- {
- JMXServerRegistry serverRegistry = (JMXServerRegistry)ApplicationRegistry.getServerRegistry(server);
- return getManagedObjectsForDomain(server,serverRegistry, domain);
- }
-
- /**
- * Retrieves all the MBeans from mbean server for a given domain
- * @return list of ManagedBeans
- */
- public static List<ManagedBean> getManagedObjectsForDomain(ManagedServer server, JMXServerRegistry serverRegistry, String domain) throws MalformedObjectNameException, NullPointerException, IOException
- {
- List<ManagedBean> mbeans = new ArrayList<ManagedBean>();
-
- MBeanServerConnection mbsc = serverRegistry.getServerConnection();
- ObjectName objName = new ObjectName(domain + ":*");
- Set objectInstances = mbsc.queryMBeans(objName, null);
-
- for (Iterator itr = objectInstances.iterator(); itr.hasNext();)
- {
- ObjectInstance instance = (ObjectInstance)itr.next();
- ManagedBean obj = new JMXManagedObject(instance.getObjectName());
- mbeans.add(obj);
- }
-
- return mbeans;
- }
-
- /**
- * Classifies the management API version of the given server
- * @return list of ManagedBeans
- * @throws NullPointerException
- * @throws ManagementConsoleException
- * @throws MalformedObjectNameException
- * @throws IOException
- */
- public static void classifyManagementApiVersion(ManagedServer server, JMXServerRegistry serverRegistry)
- throws MalformedObjectNameException, NullPointerException, IOException
- {
- MBeanServerConnection mbsc = serverRegistry.getServerConnection();
-
- //Detect if the ServerInformation MBean is present, and use it to retrieve the API version.
- ObjectName objName = new ObjectName(server.getDomain() + ":type="+ ServerInformation.TYPE + ",*");
- Set<ObjectName> objectInstances = mbsc.queryNames(objName, null);
-
- if(objectInstances.size() != 0)
- {
- for (Iterator<ObjectName> itr = objectInstances.iterator(); itr.hasNext();)
- {
- ObjectName instance = (ObjectName)itr.next();
- ServerInformation simb = (ServerInformation)
- MBeanServerInvocationHandler.newProxyInstance(mbsc,
- instance, ServerInformation.class, false);
-
- int major = simb.getManagementApiMajorVersion();
- int minor = simb.getManagementApiMinorVersion();
-
- serverRegistry.setManagementApiVersion(new ApiVersion(major, minor));
- }
-
- return;
- }
-
- //ServerInformation mbean was not present, so this is a older pre-v1.3 API server.
-
- //Detect the value of the 'version' key property on the UserManagement MBean ObjectName.
- //If present, we have a v1.2 API server. If null, we have a v1.1 API server.
- ObjectName umMBeanObjectName = null;
- List<ManagedBean> mbeans = getManagedObjectsForDomain(server, serverRegistry, Constants.DEFAULT_DOMAIN);
- for(ManagedBean mbean: mbeans)
- {
- if("UserManagement".equalsIgnoreCase(mbean.getType()))
- {
- umMBeanObjectName = ((JMXManagedObject) mbean).getObjectName();
- break;
- }
- }
-
- if(umMBeanObjectName != null)
- {
- //UserManagement MBean was present, determine if it has a version key
- if(umMBeanObjectName.getKeyProperty("version") != null)
- {
- serverRegistry.setManagementApiVersion(new ApiVersion(1, 2));
- }
- else
- {
- //no version key,
- serverRegistry.setManagementApiVersion(new ApiVersion(1, 1));
- }
-
- return;
- }
-
- //UserManagement MBean was not present, connected to an old server: classify as v1.0 API
- serverRegistry.setManagementApiVersion(new ApiVersion(1, 0));
- }
-
- public static void printOutput(String statement)
- {
- if (ApplicationRegistry.debug)
- {
- System.out.println(statement);
- }
- }
-
- public static void printStackTrace(Throwable ex)
- {
- if (ApplicationRegistry.debug)
- {
- ex.printStackTrace();
- }
- }
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/AttributeData.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/AttributeData.java
deleted file mode 100644
index ccd4cf8df8..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/AttributeData.java
+++ /dev/null
@@ -1,96 +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.management.ui.model;
-
-public class AttributeData
-{
- String name = "";
- String description = "";
- String dataType = "";
- Object value = "";
- boolean readable = true;
- boolean writable = false;
-
-
- public String getDataType()
- {
- return dataType;
- }
- public void setDataType(String dataType)
- {
- this.dataType = dataType;
- }
-
- public String getDescription()
- {
- return description;
- }
- public void setDescription(String description)
- {
- this.description = description;
- }
-
- public String getName()
- {
- return name;
- }
- public void setName(String name)
- {
- this.name = name;
- }
-
- public Object getValue()
- {
- return value;
- }
- public void setValue(Object value)
- {
- if (value != null)
- this.value = value;
- }
- public boolean isReadable()
- {
- return readable;
- }
- public void setReadable(boolean readable)
- {
- this.readable = readable;
- }
- public boolean isWritable()
- {
- return writable;
- }
- public void setWritable(boolean writable)
- {
- this.writable = writable;
- }
-
- public boolean isNumber()
- {
- if ("int".equals(dataType) || "java.lang.Integer".equals(dataType) ||
- "long".equals(dataType) || "java.lang.Long".equals(dataType) )
- {
- return true;
- }
- else
- return false;
- }
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/ManagedAttributeModel.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/ManagedAttributeModel.java
deleted file mode 100644
index b3219f15ea..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/ManagedAttributeModel.java
+++ /dev/null
@@ -1,118 +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.management.ui.model;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-
-public class ManagedAttributeModel
-{
- HashMap<String, AttributeData> _attributeMap = new HashMap<String, AttributeData>();
-
- public void setAttributeValue(String name, Object value)
- {
- if (value == null)
- return;
-
- AttributeData data = null;
- String dataType = value.getClass().getName();
- if (_attributeMap.containsKey(name))
- {
- data = _attributeMap.get(name);
- data.setValue(value);
- }
- else
- {
- data = new AttributeData();
- data.setName(name);
- data.setValue(value);
- _attributeMap.put(name, data);
- }
- data.setDataType(dataType);
- }
-
-
- public void setAttributeDescription(String name, String value)
- {
- if (_attributeMap.containsKey(name))
- {
- _attributeMap.get(name).setDescription(value);
- }
- else
- {
- AttributeData data = new AttributeData();
- data.setName(name);
- data.setDescription(value);
- _attributeMap.put(name, data);
- }
- }
-
- public void setAttributeReadable(String name, boolean readable)
- {
- if (_attributeMap.containsKey(name))
- {
- _attributeMap.get(name).setReadable(readable);
- }
- else
- {
- AttributeData data = new AttributeData();
- data.setName(name);
- data.setReadable(readable);
- _attributeMap.put(name, data);
- }
- }
-
- public void setAttributeWritable(String name, boolean writable)
- {
- if (_attributeMap.containsKey(name))
- {
- _attributeMap.get(name).setWritable(writable);
- }
- else
- {
- AttributeData data = new AttributeData();
- data.setName(name);
- data.setWritable(writable);
- _attributeMap.put(name, data);
- }
- }
-
- public List<String> getAttributeNames()
- {
- return new ArrayList<String>(_attributeMap.keySet());
- }
-
- public AttributeData[] getAttributes()
- {
- return _attributeMap.values().toArray(new AttributeData[0]);
- }
-
- public AttributeData getAttribute(String name)
- {
- return _attributeMap.get(name);
- }
-
- public int getCount()
- {
- return _attributeMap.size();
- }
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/NotificationInfoModel.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/NotificationInfoModel.java
deleted file mode 100644
index 6d4160889e..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/NotificationInfoModel.java
+++ /dev/null
@@ -1,51 +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.management.ui.model;
-
-public class NotificationInfoModel
-{
- String name;
- String description;
- String[] types;
-
- public NotificationInfoModel(String name, String desc, String[] types)
- {
- this.name = name;
- this.description = desc;
- this.types = types;
- }
-
- public String getDescription()
- {
- return description;
- }
-
- public String getName()
- {
- return name;
- }
-
- public String[] getTypes()
- {
- return types;
- }
-
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/NotificationObject.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/NotificationObject.java
deleted file mode 100644
index 35cc9f6e27..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/NotificationObject.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.management.ui.model;
-
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.TimeZone;
-
-import javax.management.ObjectName;
-
-import static org.apache.qpid.management.ui.Constants.VIRTUAL_HOST;
-
-public class NotificationObject
-{
-
- private long _sequenceNo;
- private Date _timeStamp;
- private String _message;
- private Object _source;
- private String _type; // INFO, WARN, etc
- private static final SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm:ss dd/MM/yy z");
-
- public NotificationObject(long seqNo, Date timeStamp, String message, Object source, String type)
- {
- this._sequenceNo = seqNo;
- this._message = message;
- this._source = source;
- this._type = type;
- this._timeStamp = timeStamp;
- dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
- }
-
- public Object getSource()
- {
- return _source;
- }
- public void setSource(Object _source)
- {
- this._source = _source;
- }
-
- public String getSourceName()
- {
- if (_source instanceof ObjectName)
- {
- return unquote(((ObjectName)_source).getKeyProperty("name"));
- }
-
- return null;
- }
-
- public String getSourceVirtualHost()
- {
- if (_source instanceof ObjectName)
- {
- return unquote(((ObjectName)_source).getKeyProperty(VIRTUAL_HOST));
- }
-
- return null;
- }
-
- private String unquote(String value)
- {
- if(value != null)
- {
- try
- {
- //if the value is quoted in the ObjectName, unquote it
- value = ObjectName.unquote(value);
- }
- catch(IllegalArgumentException e)
- {
- //ignore, this just means the value is not quoted
- //and can be left unchanged
- }
- }
-
- return value;
- }
-
- public String getMessage()
- {
- return _message;
- }
- public void setMessage(String _message)
- {
- this._message = _message;
- }
- public long getSequenceNo()
- {
- return _sequenceNo;
- }
- public void setSequenceNo(long no)
- {
- _sequenceNo = no;
- }
- public String getTimeStamp()
- {
- return dateFormat.format(_timeStamp);
- }
- public void setTimeStamp(Date stamp)
- {
- _timeStamp = stamp;
- }
- public String getType()
- {
- return _type;
- }
- public void setType(String _type)
- {
- this._type = _type;
- }
-
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/OperationData.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/OperationData.java
deleted file mode 100644
index bf3b730b3e..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/OperationData.java
+++ /dev/null
@@ -1,110 +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.management.ui.model;
-
-import java.util.List;
-
-public class OperationData
-{
- private String _name;
- private String _description;
- private String _returnType;
- private int _impact;
- private List<ParameterData> _parameters;
-
- public OperationData(String value)
- {
- this._name = value;
- }
-
- public String getName()
- {
- return _name;
- }
-
- public String getDescription()
- {
- return _description;
- }
-
- public void setDescription(String description)
- {
- this._description = description;
- }
-
- public List<ParameterData> getParameters()
- {
- return _parameters;
- }
-
- public void setParameters(List<ParameterData> parameters)
- {
- this._parameters = parameters;
- }
-
- public int getImpact()
- {
- return _impact;
- }
-
- public void setImpact(int impact)
- {
- this._impact = impact;
- }
-
- public String getReturnType()
- {
- return _returnType;
- }
-
- public void setReturnType(String returnType)
- {
- this._returnType = returnType;
- }
-
- public boolean isReturnTypeBoolean()
- {
- return (_returnType.equals("boolean") || _returnType.equals("java.lang.Boolean"));
- }
-
- public boolean isReturnTypeVoid()
- {
- return (_returnType.equals("void") || _returnType.equals("java.lang.Void"));
- }
-
- public Object getParameterValue(String paramName)
- {
- if (_parameters == null)
- {
- return null;
- }
-
- for (int i = 0; i < _parameters.size(); i++)
- {
- if (paramName.equalsIgnoreCase(_parameters.get(i).getName()))
- {
- return _parameters.get(i).getValue();
- }
- }
-
- return null;
- }
-} \ No newline at end of file
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/OperationDataModel.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/OperationDataModel.java
deleted file mode 100644
index 96964a81ef..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/OperationDataModel.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.management.ui.model;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-
-import javax.management.MBeanOperationInfo;
-import javax.management.MBeanParameterInfo;
-
-public class OperationDataModel
-{
- HashMap<String, OperationData> _operationMap = new HashMap<String, OperationData>();
-
- public void addOperation(MBeanOperationInfo opInfo)
- {
- OperationData opData = new OperationData(opInfo.getName());
- opData.setDescription(opInfo.getDescription());
- opData.setImpact(opInfo.getImpact());
- opData.setReturnType(opInfo.getReturnType());
-
- int parametersCount = opInfo.getSignature().length;
- if (parametersCount != 0)
- {
- List<ParameterData> paramList = new ArrayList<ParameterData>();
- for (int i = 0; i < parametersCount; i++)
- {
- MBeanParameterInfo paramInfo = opInfo.getSignature()[i];
- ParameterData param = new ParameterData(paramInfo.getName(), paramInfo.getDescription(),
- paramInfo.getType());
- paramList.add(param);
- }
- opData.setParameters(paramList);
- }
-
- _operationMap.put(opInfo.getName(), opData);
- }
-
- public OperationData getOperation(String name)
- {
- return _operationMap.get(name);
- }
-
- public List<OperationData> getOperations()
- {
- return new ArrayList<OperationData>(_operationMap.values());
- }
-
- public int getCount()
- {
- return _operationMap.size();
- }
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/ParameterData.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/ParameterData.java
deleted file mode 100644
index d12217c6eb..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/ParameterData.java
+++ /dev/null
@@ -1,95 +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.management.ui.model;
-
-/**
- * Class representing an mbean operation parameter
- * @author Bhupendra Bhardwaj
- */
-public class ParameterData
-{
- private String _name;
- private String _description;
- private String _type;
- private Object _value;
-
- ParameterData(String name, String desc, String type)
- {
- this._name = name;
- this._description = desc;
- this._type = type;
- setDefaultValue();
- }
-
- public String getDescription()
- {
- return _description;
- }
-
- public String getName()
- {
- return _name;
- }
-
- public String getType()
- {
- return _type;
- }
-
- public Object getValue()
- {
- return _value;
- }
-
- public void setValueFromString(String strValue)
- {
- if ("int".equals(_type))
- _value = Integer.parseInt(strValue);
- else if (isBoolean())
- _value = Boolean.valueOf(strValue);
- else if ("long".equals(_type))
- _value = Long.parseLong(strValue);
- else
- _value = strValue;
- }
-
- public void setValue(Object value)
- {
- this._value = value;
- }
-
- public boolean isBoolean()
- {
- return (_type.equals("boolean") || _type.equals("java.lang.Boolean"));
- }
-
- public void setDefaultValue()
- {
- if (isBoolean())
- {
- _value = Boolean.valueOf("false");
- }
- else
- {
- _value = null;
- }
- }
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/AttributesTabControl.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/AttributesTabControl.java
deleted file mode 100644
index 2b9f5042dc..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/AttributesTabControl.java
+++ /dev/null
@@ -1,922 +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.management.ui.views;
-
-import static org.apache.qpid.management.ui.Constants.*;
-
-import org.apache.qpid.management.ui.ApplicationRegistry;
-import org.apache.qpid.management.ui.ManagedBean;
-import org.apache.qpid.management.ui.jmx.JMXServerRegistry;
-import org.apache.qpid.management.ui.jmx.MBeanUtility;
-import org.apache.qpid.management.ui.model.AttributeData;
-import org.apache.qpid.management.ui.model.ManagedAttributeModel;
-import org.eclipse.jface.viewers.IColorProvider;
-import org.eclipse.jface.viewers.IFontProvider;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITableLabelProvider;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerSorter;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.DisposeEvent;
-import org.eclipse.swt.events.DisposeListener;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.events.KeyListener;
-import org.eclipse.swt.events.MouseEvent;
-import org.eclipse.swt.events.MouseListener;
-import org.eclipse.swt.events.MouseMoveListener;
-import org.eclipse.swt.events.MouseTrackListener;
-import org.eclipse.swt.events.PaintEvent;
-import org.eclipse.swt.events.PaintListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.layout.FillLayout;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Canvas;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Event;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Listener;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.TabFolder;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.TableColumn;
-import org.eclipse.swt.widgets.TableItem;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.ScrolledForm;
-
-
-/**
- * Creates controller composite for the attribute's tab.
- * @author Bhupendra Bhardwaj
- */
-public class AttributesTabControl extends TabControl
-{
- private FormToolkit _toolkit;
- private ScrolledForm _form;
- private Table _table = null;
- private TableViewer _tableViewer = null;
- private int[] tableWidths = new int[] {275, 275};
-
- private Composite _tableComposite = null;
- private Composite _buttonsComposite = null;
-
- private DisposeListener tableDisposeListener = new DisposeListenerImpl();
- final Image image;
- private Button _detailsButton = null;
- private Button _editButton = null;
- private Button _graphButton = null;
- private boolean disableEditing = false;
-
- private static final String MAX_VALUE = "MaxValue";
- private static final String GRAPH_VALUES = "GraphValues";
- private int GRAPH_WIDTH = 700;
- private int GRAPH_HEIGHT = 450;
- private int GRAPH_ITEM_GAP = 100;
- private int startX = 80;
- private int startY = 60;
-
- public AttributesTabControl(TabFolder tabFolder)
- {
- super(tabFolder);
- _toolkit = new FormToolkit(_tabFolder.getDisplay());
- _form = _toolkit.createScrolledForm(_tabFolder);
- GridLayout gridLayout = new GridLayout(2, false);
- gridLayout.marginWidth = 0;
- gridLayout.marginHeight = 0;
- _form.getBody().setLayout(gridLayout);
- _tableComposite = _toolkit.createComposite(_form.getBody());
- _tableComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- _tableComposite.setLayout(new GridLayout());
- _buttonsComposite = _toolkit.createComposite(_form.getBody());
- _buttonsComposite.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, true));
- _buttonsComposite.setLayout(new GridLayout());
-
- image = Display.getCurrent().getSystemImage(SWT.ICON_INFORMATION);
- createWidgets();
- }
-
- /**
- * @see TabControl#getControl()
- */
- public Control getControl()
- {
- return _form;
- }
-
- /**
- * Creates required widgets for Attribute's tab
- */
- protected void createWidgets()
- {
- createTable();
- createTableViewer();
- createButtons();
- addTableListeners();
- }
-
- /**
- * Creates table for listing the MBean attributes
- */
- private void createTable()
- {
- _table = _toolkit.createTable(_tableComposite, SWT.FULL_SELECTION);
- GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
- _table.setLayoutData(gridData);
-
- for (int i = 0; i < ATTRIBUTE_TABLE_TITLES.size(); ++i)
- {
- final TableColumn column = new TableColumn(_table, SWT.NONE);
- column.setText(ATTRIBUTE_TABLE_TITLES.get(i));
- column.setWidth(tableWidths[i]);
- column.setResizable(true);
- }
-
- _table.setLinesVisible (true);
- _table.setHeaderVisible (true);
- }
-
- /**
- * Creates tableviewer for the attribute's table
- */
- private void createTableViewer()
- {
- _tableViewer = new TableViewer(_table);
- _tableViewer.setUseHashlookup(true);
- _tableViewer.setColumnProperties(
- ATTRIBUTE_TABLE_TITLES.toArray(new String[ATTRIBUTE_TABLE_TITLES.size()]));
- _tableViewer.setContentProvider(new ContentProviderImpl());
- _tableViewer.setLabelProvider(new LabelProviderImpl());
- _tableViewer.setSorter(new ViewerSorterImpl());
- }
-
- private void createButtons()
- {
- addDetailsButton();
- addEditButton();
- addGraphButton();
- }
-
- private void addDetailsButton()
- {
- // Create and configure the button for attribute details
- _detailsButton = _toolkit.createButton(_buttonsComposite, BUTTON_DETAILS, SWT.PUSH | SWT.CENTER);
- _detailsButton.setFont(ApplicationRegistry.getFont(FONT_BUTTON));
- GridData gridData = new GridData(SWT.FILL, SWT.TOP, false, false);
- gridData.widthHint = 80;
- _detailsButton.setLayoutData(gridData);
- _detailsButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- disableEditing = true;
- int index = _table.getSelectionIndex();
- TableItem item = _table.getItem(index);
- createDetailsPopup((AttributeData)item.getData());
- disableEditing = false;
- setFocus();
- }
- });
- }
-
- /**
- * Creates the button for editing attributes.
- */
- private void addEditButton()
- {
- // Create and configure the button for editing attribute
- _editButton = _toolkit.createButton(_buttonsComposite, BUTTON_EDIT_ATTRIBUTE, SWT.PUSH | SWT.CENTER);
- _editButton.setFont(ApplicationRegistry.getFont(FONT_BUTTON));
- GridData gridData = new GridData(SWT.FILL, SWT.TOP, false, false);
- gridData.widthHint = 80;
- _editButton.setLayoutData(gridData);
- _editButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- int index = _table.getSelectionIndex();
- TableItem item = _table.getItem(index);
- createDetailsPopup((AttributeData)item.getData());
- setFocus();
- }
- });
- }
-
- /**
- * Creates the button for viewing Graphs
- */
- private void addGraphButton()
- {
- _graphButton = _toolkit.createButton(_buttonsComposite, BUTTON_GRAPH, SWT.PUSH | SWT.CENTER);
- _graphButton.setFont(ApplicationRegistry.getFont(FONT_BUTTON));
- GridData gridData = new GridData(SWT.FILL, SWT.TOP, false, false);
- gridData.widthHint = 80;
- _graphButton.setLayoutData(gridData);
- _graphButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent event)
- {
- int selectionIndex = _table.getSelectionIndex();
- AttributeData data = (AttributeData)_table.getItem(selectionIndex).getData();
- createGraph(data);
- setFocus();
- }
- });
- }
-
- private void addTableListeners()
- {
- _tableViewer.addSelectionChangedListener(new ISelectionChangedListener(){
- public void selectionChanged(SelectionChangedEvent evt)
- {
- IStructuredSelection ss = (IStructuredSelection)evt.getSelection();
- checkForEnablingButtons((AttributeData)ss.getFirstElement());
- }
- });
-
- MouseListenerImpl listener = new MouseListenerImpl();
- _tableViewer.getTable().addMouseTrackListener(listener);
- _tableViewer.getTable().addMouseMoveListener(listener);
- _tableViewer.getTable().addMouseListener(listener);
-
- _table.addDisposeListener(tableDisposeListener);
-
- // _table is equal to _tableViewer.getControl()
- _table.addListener(SWT.MeasureItem, new Listener() {
- public void handleEvent(Event event)
- {
- event.height = event.gc.getFontMetrics().getHeight() * 3/2;
- }
- });
- }
-
- /**
- * Listeners implementation class for showing table tooltip
- * @author Bhupendra Bhardwaj
- */
- private class MouseListenerImpl implements MouseTrackListener, MouseMoveListener, KeyListener, MouseListener
- {
- Shell tooltipShell = null;
- Label tooltipLabel = null;
- public void mouseHover(MouseEvent event)
- {
- TableItem item = _table.getItem (new Point (event.x, event.y));
-
- if (item != null)
- {
- AttributeData data = (AttributeData)item.getData();
- if (tooltipShell != null && !tooltipShell.isDisposed ()) tooltipShell.dispose ();
- tooltipShell = new Shell(_table.getShell(), SWT.ON_TOP | SWT.NO_FOCUS | SWT.TOOL);
- tooltipShell.setBackground(event.display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
- FillLayout layout = new FillLayout();
- layout.marginWidth = 2;
- tooltipShell.setLayout(layout);
- tooltipLabel = new Label(tooltipShell, SWT.NONE);
- tooltipLabel.setForeground(event.display.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
- tooltipLabel.setBackground(event.display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
- tooltipLabel.setText(data.getDescription());
- tooltipLabel.setData("_TABLEITEM", item);
- tooltipLabel.addListener(SWT.MouseExit, tooltipLabelListener);
- tooltipLabel.addListener(SWT.MouseDown, tooltipLabelListener);
- Point size = tooltipShell.computeSize(SWT.DEFAULT, SWT.DEFAULT);
- Rectangle rect = item.getBounds(0);
- Point pt = _table.toDisplay(rect.x, rect.y);
- tooltipShell.setBounds(pt.x, pt.y, size.x, size.y);
- tooltipShell.setVisible(true);
- }
- }
- public void mouseEnter(MouseEvent e)
- {
- }
- public void mouseExit(MouseEvent e)
- {
- }
-
- // MouseMoveListener implementation
- public void mouseMove(MouseEvent event)
- {
- if (tooltipShell == null)
- return;
-
- tooltipShell.dispose();
- tooltipShell = null;
- tooltipLabel = null;
- }
-
- // KeyListener implementation
- public void keyPressed(KeyEvent e)
- {
- if (tooltipShell == null)
- return;
-
- tooltipShell.dispose();
- tooltipShell = null;
- tooltipLabel = null;
- }
- public void keyReleased(KeyEvent e)
- {
-
- }
-
- // MouseListener implementation
- public void mouseDoubleClick(MouseEvent event)
- {
- if (tooltipShell != null)
- {
- tooltipShell.dispose();
- tooltipShell = null;
- tooltipLabel = null;
- }
- Table table = (Table)event.getSource();
- int selectionIndex = table.getSelectionIndex();
- AttributeData data = (AttributeData)table.getItem(selectionIndex).getData();
- createDetailsPopup(data);
- }
- public void mouseDown(MouseEvent e)
- {
- if (tooltipShell != null)
- {
- tooltipShell.dispose();
- tooltipShell = null;
- tooltipLabel = null;
- }
- }
- public void mouseUp(MouseEvent e)
- {
-
- }
- } // end of MouseListenerImpl
-
- /**
- * Creates pop-up window for showing attribute details
- * @param data - Selectes attribute
- */
- public void createDetailsPopup(AttributeData data)
- {
- int width = 500;
- int height = 250;
- if (!isSimpleType(data.getValue()))
- {
- width = 650;
- height = 450;
- }
-
- Display display = Display.getCurrent();
- Shell shell = ViewUtility.createPopupShell(ATTRIBUTE, width, height);
- createDetailsPopupContents(shell, data);
-
- shell.open();
- while (!shell.isDisposed())
- {
- if (!display.readAndDispatch())
- {
- display.sleep();
- }
- }
- shell.dispose();
- }
-
- /**
- * Listener class for table tooltip label
- */
- final Listener tooltipLabelListener = new Listener ()
- {
- public void handleEvent (Event event)
- {
- Label label = (Label)event.widget;
- Shell shell = label.getShell();
- switch (event.type)
- {
- case SWT.MouseDown:
- Event e = new Event();
- e.item = (TableItem)label.getData ("_TABLEITEM");
- _table.setSelection(new TableItem[] {(TableItem)e.item});
- shell.dispose();
- _table.setFocus();
- break;
- case SWT.MouseExit:
- shell.dispose();
- break;
- }
- }
- };
-
-
- /**
- * Create the contents for the attribute details window pop-up
- * @param shell - The shell that will be filled with details.
- * @param attribute - Selected attribute
- */
- private void createDetailsPopupContents(Composite shell, AttributeData attribute)
- {
- GridLayout layout = new GridLayout(2, false);
- layout.horizontalSpacing = 10;
- layout.verticalSpacing = 10;
- layout.marginHeight = 20;
- layout.marginWidth = 20;
-
- Composite parent = _toolkit.createComposite(shell, SWT.NONE);
- parent.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- parent.setLayout(layout);
-
- // Name
- Label label = _toolkit.createLabel(parent, ATTRIBUTE_TABLE_TITLES.get(0), SWT.NONE);
- GridData layoutData = new GridData(SWT.TRAIL, SWT.TOP, false, false);
- label.setLayoutData(layoutData);
- int textStyle = SWT.BEGINNING | SWT.BORDER |SWT.READ_ONLY;
- Text value = _toolkit.createText(parent, ViewUtility.getDisplayText(attribute.getName()), textStyle);
- value.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
-
-
- // Description
- label = _toolkit.createLabel(parent, DESCRIPTION, SWT.NONE);
- label.setLayoutData(new GridData(SWT.TRAIL, SWT.TOP, false, false));
- value = _toolkit.createText(parent, attribute.getDescription(), textStyle);
- value.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
-
- // value
- label = _toolkit.createLabel(parent, ATTRIBUTE_TABLE_TITLES.get(1), SWT.NONE);
- label.setLayoutData(new GridData(SWT.TRAIL, SWT.TOP, false, false));
-
- if (!attribute.isReadable())
- {
- value = _toolkit.createText(parent, "", textStyle);
- value.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- }
- else
- {
- if (!isSimpleType(attribute.getValue()))
- {
- if (attribute.getValue() instanceof String[])
- {
- String result = "";
- for(String val : (String[]) attribute.getValue()){
- result = result.concat(val+ "; ");
- }
- value = _toolkit.createText(parent, "", textStyle);
-
- value.setText(result);
- value.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- }
- else
- {
- Composite composite = new Composite(parent, SWT.BORDER);
- composite.setLayout(new GridLayout());
- composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
- ViewUtility.populateCompositeWithData(_toolkit, composite, attribute.getValue());
- }
- }
- else
- {
- if (attribute.isWritable())
- {
- value = _toolkit.createText(parent, "", SWT.BEGINNING | SWT.BORDER);
- if(attribute.isNumber())
- {
- value.addVerifyListener(new NumberVerifyListener());
- }
-
- // set data to access in the listener
- parent.setData(attribute);
- }
- else
- {
- value = _toolkit.createText(parent, "", textStyle);
- }
-
- value.setText(attribute.getValue().toString());
- value.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- }
- }
-
-
- // Update button
- Button updateButton = addUpdateButton(parent);
- updateButton.setData(value);
- if (!attribute.isWritable())
- {
- updateButton.setVisible(false);
- }
-
- if (disableEditing)
- {
- value.setEditable(false);
- updateButton.setVisible(false);
- }
- }
-
- /**
- * Create the button for updating attributes. This should be enabled for writable attribute
- */
- private Button addUpdateButton(Composite parent)
- {
- final Button updateButton = new Button(parent, SWT.PUSH | SWT.CENTER);
- // set the data to access in the listener
- parent.setData(BUTTON_UPDATE, updateButton);
-
- updateButton.setText(BUTTON_UPDATE);
- GridData gridData = new GridData (SWT.CENTER, SWT.BOTTOM, true, true, 2, 1);
- gridData.widthHint = 100;
- updateButton.setLayoutData(gridData);
- updateButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent event)
- {
- try
- {
- Button button = (Button)event.widget;
- Text text = (Text)button.getData();
- AttributeData data = (AttributeData)button.getParent().getData();
- MBeanUtility.updateAttribute(_mbean, data, text.getText());
- button.getShell().close();
- refresh(_mbean);
- }
- catch (Exception ex)
- {
- MBeanUtility.handleException(_mbean, ex);
- }
- }
- });
-
- return updateButton;
- }
-
- /**
- * Refreshes the attribute tab by querying the mbean server for latest values
- */
- @Override
- public void refresh(ManagedBean mbean)
- {
- _mbean = mbean;
- if (_mbean == null)
- {
- _tableViewer.setInput(null);
- return;
- }
- ManagedAttributeModel attributesList = null;
- try
- {
- attributesList = MBeanUtility.getAttributes(mbean);
- }
- catch(Exception ex)
- {
- MBeanUtility.handleException(_mbean, ex);
- }
- _tableViewer.setInput(attributesList);
- checkForEnablingButtons(getSelectionAttribute());
-
- _form.layout(true);
- _form.getBody().layout(true, true);
- }
-
- /**
- * @see TabControl#setFocus()
- */
- public void setFocus()
- {
- _table.setFocus();
- }
-
- /**
- * Checks which buttons are to be enabled or disabled. The graph button will be enabled only
- * for readable number attributes. Editing is enabled for writeable attribtues.
- * @param attribute
- */
- private void checkForEnablingButtons(AttributeData attribute)
- {
- if (attribute == null)
- {
- _detailsButton.setEnabled(false);
- _editButton.setEnabled(false);
- _graphButton.setEnabled(false);
- return;
- }
-
- _detailsButton.setEnabled(true);
- if (attribute.isWritable())
- {
- _editButton.setEnabled(true);
- _graphButton.setEnabled(false);
- }
- else
- {
- _editButton.setEnabled(false);
- // Currently only Queues are having attributes, which are suitable for a graph
- if (attribute.isNumber() && _mbean.isQueue())
- {
- _graphButton.setEnabled(true);
- }
- else
- {
- _graphButton.setEnabled(false);
- }
- }
- }
-
- /**
- * Creates graph in a pop-up window for given attribute.
- * @param data
- */
- private void createGraph(final AttributeData data)
- {
- Display display = Display.getCurrent();
- Shell shell = new Shell(display, SWT.BORDER | SWT.CLOSE | SWT.MIN | SWT.MAX);
- shell.setText(_mbean.getName());
- int x = display.getBounds().width;
- int y = display.getBounds().height;
- shell.setBounds(x/4, y/4, GRAPH_WIDTH, GRAPH_HEIGHT);
- shell.setLayout(new FillLayout());
-
- final Canvas canvas = new Canvas(shell, SWT.NONE);
- long currentValue = Long.parseLong(data.getValue().toString());
- long mValue = getGraphMaxValue(currentValue);
- canvas.setData(MAX_VALUE, mValue);
- canvas.setData(GRAPH_VALUES, new long[] {0,0,0,0,0,currentValue});
-
- canvas.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE));
- canvas.addPaintListener(new PaintListener()
- {
- public void paintControl(PaintEvent event)
- {
- Canvas canvas = (Canvas)event.widget;
- int maxX = canvas.getSize().x;
- int maxY = canvas.getSize().y;
- event.gc.fillRectangle(canvas.getBounds());
- event.gc.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_BLACK));
- event.gc.setLineWidth(4);
-
- Object canvasData = canvas.getData(MAX_VALUE);
- String str = canvasData.toString();
- long maxValue = Long.parseLong(str);
- // Set the graph dimensions
- event.gc.drawText("0", startX - 40, maxY - startY - 10);
- event.gc.drawText("" + maxValue/2, startX - 40, maxY/2);
- event.gc.drawText("" + maxValue, startX - 40, startY);
-
- // horizontal line
- event.gc.drawLine(startX, maxY - startY, maxX - 60, maxY - startY);
- // vertical line
- event.gc.drawLine(startX, maxY - startY, startX, startY);
- // set graph text
- event.gc.drawText(data.getName(), startX - 40, startY - 40);
- event.gc.drawText("25 sec", startX, maxY - startY + 10);
- event.gc.drawText("20 sec", startX + GRAPH_ITEM_GAP, maxY - startY + 10);
- event.gc.drawText("15 sec", startX + GRAPH_ITEM_GAP * 2, maxY - startY + 10);
- event.gc.drawText("10 sec", startX + GRAPH_ITEM_GAP * 3, maxY - startY + 10);
- event.gc.drawText(" 5 sec", startX + GRAPH_ITEM_GAP * 4, maxY - startY + 10);
- event.gc.drawText(" 0 sec", startX + GRAPH_ITEM_GAP * 5, maxY - startY + 10);
-
- // plot the graph now for values
- event.gc.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_BLUE));
- canvasData = canvas.getData(GRAPH_VALUES);
- long[] graphValues = (long[]) canvasData;
- for (int i = 0; i < graphValues.length; i++)
- {
- int x = startX + i * GRAPH_ITEM_GAP;
- int yTotalLength = (maxY - 2 * startY);
- float ratio = ((float)graphValues[i]/(float)maxValue);
- int itemlength = (int)(yTotalLength * ratio);
- int y = maxY - startY - itemlength;
- event.gc.drawLine(x, maxY- startY, x, y);
- event.gc.drawText(String.valueOf(graphValues[i]), x, y - 20);
- }
- }
- });
-
- shell.open();
-
- // Set up the timer for the animation
- Runnable runnable = new Runnable()
- {
- public void run()
- {
- try
- {
- animate(canvas, data);
- Display.getCurrent().timerExec(TIMER_INTERVAL, this);
- }
- catch(Exception ex)
- {
- MBeanUtility.handleException(ex);
- }
- }
- };
-
- // Launch the timer
- display.timerExec(TIMER_INTERVAL, runnable);
-
- while (!shell.isDisposed())
- {
- if (!display.readAndDispatch())
- {
- display.sleep();
- }
- }
-
- // Kill the timer
- display.timerExec(-1, runnable);
- shell.dispose();
- }
-
- /**
- * @return selected attribute in the table
- */
- public AttributeData getSelectionAttribute()
- {
- int index = _table.getSelectionIndex();
- if (index == -1)
- return null;
-
- return (AttributeData)_table.getItem(index).getData();
- }
-
- /**
- * checks for newer values of selected attribute to update the graph
- * @param canvas
- * @param data
- * @throws Exception
- */
- private void animate(Canvas canvas, AttributeData data) throws Exception
- {
- String attribute = data.getName();
- Object valueObj = MBeanUtility.refreshAttribute(_mbean, attribute);
- int value = Integer.parseInt(String.valueOf(valueObj));
- Object canvasData = canvas.getData(GRAPH_VALUES);
- long[] graphValues = (long[]) canvasData;
-
- for (int i = 0; i < graphValues.length -1; i++)
- {
- graphValues[i] = graphValues[i + 1];
- }
- graphValues[graphValues.length - 1] = value;
-
- canvasData = canvas.getData(MAX_VALUE);
- long maxValue = Long.parseLong(String.valueOf(canvasData));
- if (maxValue < value)
- {
- maxValue = getGraphMaxValue(value);
- canvas.setData(MAX_VALUE, maxValue);
- }
-
- canvas.redraw();
- }
-
- /**
- * @param maxAttributeValue
- * @return dynamically calculated value for y-axis on the graph
- */
- private long getGraphMaxValue(long maxAttributeValue)
- {
- long maxGraphValue = 100;
- long temp = maxAttributeValue * 3/2;
- if (temp > maxGraphValue)
- {
- long modulus = temp % 100;
- maxGraphValue = temp + ( 100 - modulus);
- }
-
- return maxGraphValue;
- }
-
- /**
- * Content Provider class for the table viewer
- * @author Bhupendra Bhardwaj
- */
- private static class ContentProviderImpl implements IStructuredContentProvider
- {
-
- public void inputChanged(Viewer v, Object oldInput, Object newInput)
- {
-
- }
-
- public void dispose()
- {
-
- }
-
- public Object[] getElements(Object parent)
- {
- return ((ManagedAttributeModel)parent).getAttributes();
- }
- }
-
- /**
- * Label Provider class for the table viewer
- * @author Bhupendra Bhardwaj
- */
- private class LabelProviderImpl extends LabelProvider implements ITableLabelProvider,
- IFontProvider,
- IColorProvider
- {
- AttributeData attribute = null;
- public String getColumnText(Object element, int columnIndex)
- {
- String result = "";
- attribute = (AttributeData) element;
-
- switch (columnIndex)
- {
- case 0 : // attribute name column
- result = ViewUtility.getDisplayText(attribute.getName());
- break;
- case 1 : // attribute value column
- if (attribute.getValue() != null)
- if (attribute.getValue() instanceof String[])
- {
- for(String val : (String[]) attribute.getValue()){
- result = result.concat(val+ "; ");
- }
- }
- else
- {
- result = String.valueOf(attribute.getValue());
- }
- break;
- default :
- result = "";
- }
-
- return result;
- }
-
- public Image getColumnImage(Object element, int columnIndex)
- {
- return null;
- }
-
- public Font getFont(Object element)
- {
- return ApplicationRegistry.getFont(FONT_TABLE_CELL);
- }
-
- public Color getForeground(Object element)
- {
- attribute = (AttributeData) element;
- if (attribute.isWritable())
- return Display.getCurrent().getSystemColor(SWT.COLOR_BLUE);
- else
- return Display.getCurrent().getSystemColor(SWT.COLOR_BLACK);
- }
- public Color getBackground(Object element)
- {
- return _form.getBackground();
- }
- }
-
- private static class DisposeListenerImpl implements DisposeListener
- {
- public void widgetDisposed(DisposeEvent e)
- {
-
- }
- }
-
- /**
- * Sorter class for the table viewer. It sorts the table for according to attribute name.
- * @author Bhupendra Bhardwaj
- *
- */
- private static class ViewerSorterImpl extends ViewerSorter
- {
- public int compare(Viewer viewer, Object o1, Object o2)
- {
- AttributeData attribtue1 = (AttributeData)o1;
- AttributeData attribtue2 = (AttributeData)o2;
-
- return collator.compare(attribtue1.getName(), attribtue2.getName());
- }
- }
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/INotificationViewer.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/INotificationViewer.java
deleted file mode 100644
index bc560b6064..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/INotificationViewer.java
+++ /dev/null
@@ -1,32 +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.management.ui.views;
-
-import java.util.List;
-
-import org.apache.qpid.management.ui.model.NotificationObject;
-
-public interface INotificationViewer
-{
- public void addNotification(NotificationObject notification);
-
- public void addNotification(List<NotificationObject> notificationList);
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/MBeanTabFolderFactory.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/MBeanTabFolderFactory.java
deleted file mode 100644
index 527fc67be3..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/MBeanTabFolderFactory.java
+++ /dev/null
@@ -1,466 +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.management.ui.views;
-
-import static org.apache.qpid.management.ui.Constants.ATTRIBUTES;
-import static org.apache.qpid.management.ui.Constants.CONNECTION;
-import static org.apache.qpid.management.ui.Constants.EXCHANGE;
-import static org.apache.qpid.management.ui.Constants.EXCHANGE_TYPE;
-import static org.apache.qpid.management.ui.Constants.NOTIFICATIONS;
-import static org.apache.qpid.management.ui.Constants.QUEUE;
-
-import java.util.EnumSet;
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.management.MBeanServerConnection;
-
-import org.apache.qpid.management.ui.ApplicationRegistry;
-import org.apache.qpid.management.ui.ManagedServer;
-import org.apache.qpid.management.ui.ServerRegistry;
-import org.apache.qpid.management.ui.jmx.JMXManagedObject;
-import org.apache.qpid.management.ui.jmx.MBeanUtility;
-import org.apache.qpid.management.ui.model.NotificationInfoModel;
-import org.apache.qpid.management.ui.model.OperationData;
-import org.apache.qpid.management.ui.model.OperationDataModel;
-import org.apache.qpid.management.ui.views.queue.QueueOperationsTabControl;
-import org.apache.qpid.management.ui.views.type.ConnectionTypeTabControl;
-import org.apache.qpid.management.ui.views.type.ExchangeTypeTabControl;
-import org.apache.qpid.management.ui.views.type.QueueTypeTabControl;
-import org.apache.qpid.management.ui.views.users.UserManagementTabControl;
-import org.apache.qpid.management.ui.views.vhost.VHostTabControl;
-import org.apache.qpid.management.ui.views.connection.ConnectionOperationsTabControl;
-import org.apache.qpid.management.ui.views.exchange.ExchangeOperationsTabControl;
-import org.apache.qpid.management.ui.views.exchange.HeadersExchangeOperationsTabControl;
-import org.apache.qpid.management.ui.views.logging.ConfigurationFileTabControl;
-import org.apache.qpid.management.ui.views.logging.RuntimeTabControl;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.FormAttachment;
-import org.eclipse.swt.layout.FormData;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Event;
-import org.eclipse.swt.widgets.Listener;
-import org.eclipse.swt.widgets.TabFolder;
-import org.eclipse.swt.widgets.TabItem;
-
-public class MBeanTabFolderFactory
-{
- private static final String MBEANTYPE_QUEUE = "VirtualHost.Queue";
- private static final String MBEANTYPE_CONNECTION = "VirtualHost.Connection";
- private static final String MBEANTYPE_EXCHANGE = "VirtualHost.Exchange";
- private static final String MBEANTYPE_VHOST_MANAGER = "VirtualHost.VirtualHostManager";
- private static final String MBEANTYPE_LOGGING_MANAGEMENT = "LoggingManagement";
- private static final String MBEANTYPE_USER_MANAGEMENT = "UserManagement";
- private static final String MBEANTYPE_CONFIGURATION_MANAGEMENT = "ConfigurationManagement";
-
- private MBeanTabFolderFactory()
- {
- //no instances
- }
-
- public static TabFolder generateMBeanTabFolder(final Composite parent, final JMXManagedObject mbean, final MBeanServerConnection mbsc)
- {
- TabFolder tabFolder = new TabFolder(parent, SWT.NONE);
- FormData layoutData = new FormData();
- layoutData.left = new FormAttachment(0);
- layoutData.top = new FormAttachment(0);
- layoutData.right = new FormAttachment(100);
- layoutData.bottom = new FormAttachment(100);
- tabFolder.setLayoutData(layoutData);
-
- TabItem tab;
- TabControl controller;
- QpidMBeanType mbeanType = QpidMBeanType.get(mbean.getType());
-
- switch(mbeanType)
- {
- case QUEUE:
- createAttributesTab(tabFolder, mbean);
-
- tab = new TabItem(tabFolder, SWT.NONE);
- tab.setText("Operations");
- controller = new QueueOperationsTabControl(tabFolder, mbean, mbsc);
- tab.setControl(controller.getControl());
- tab.setData(TabControl.CONTROLLER, controller);
- break;
- case CONNECTION:
- createAttributesTab(tabFolder, mbean);
-
- tab = new TabItem(tabFolder, SWT.NONE);
- tab.setText("Operations");
- controller = new ConnectionOperationsTabControl(tabFolder, mbean, mbsc);
- tab.setControl(controller.getControl());
- tab.setData(TabControl.CONTROLLER, controller);
- break;
- case EXCHANGE:
- createAttributesTab(tabFolder, mbean);
-
- if (mbean.getProperty(EXCHANGE_TYPE).equalsIgnoreCase("headers"))
- {
- tab = new TabItem(tabFolder, SWT.NONE);
- tab.setText("Operations");
- controller = new HeadersExchangeOperationsTabControl(tabFolder, mbean, mbsc);
- tab.setControl(controller.getControl());
- tab.setData(TabControl.CONTROLLER, controller);
- }
- else
- {
- tab = new TabItem(tabFolder, SWT.NONE);
- tab.setText("Operations");
- controller = new ExchangeOperationsTabControl(tabFolder, mbean, mbsc);
- tab.setControl(controller.getControl());
- tab.setData(TabControl.CONTROLLER, controller);
- }
- break;
- case VHOST_MANAGER:
- createAttributesTab(tabFolder, mbean);
-
- tab = new TabItem(tabFolder, SWT.NONE);
- tab.setText("Operations");
- controller = new VHostTabControl(tabFolder, mbean, mbsc);
- tab.setControl(controller.getControl());
- tab.setData(TabControl.CONTROLLER, controller);
- break;
- case LOGGING_MANAGEMENT:
- tab = new TabItem(tabFolder, SWT.NONE);
- tab.setText("Runtime Options");
- controller = new RuntimeTabControl(tabFolder, mbean, mbsc);
- tab.setControl(controller.getControl());
- tab.setData(TabControl.CONTROLLER, controller);
-
- tab = new TabItem(tabFolder, SWT.NONE);
- tab.setText("ConfigurationFile Options");
- controller = new ConfigurationFileTabControl(tabFolder, mbean, mbsc);
- tab.setControl(controller.getControl());
- tab.setData(TabControl.CONTROLLER, controller);
- break;
- case USER_MANAGEMENT:
- tab = new TabItem(tabFolder, SWT.NONE);
- tab.setText("Operations");
- controller = new UserManagementTabControl(tabFolder, mbean, mbsc);
- tab.setControl(controller.getControl());
- tab.setData(TabControl.CONTROLLER, controller);
- break;
- case CONFIGURATION_MANAGEMENT:
- createGenericTabFolder(tabFolder, mbean);
- break;
- case UNKNOWN:
- createGenericTabFolder(tabFolder, mbean);
- break;
- }
-
- createNotificationsTabIfNecessary(tabFolder, mbean);
-
- tabFolder.addListener(SWT.Selection, new Listener()
- {
- public void handleEvent(Event evt)
- {
- TabItem tab = (TabItem)evt.item;
- TabControl controller = (TabControl)tab.getData(TabControl.CONTROLLER);
- if(controller != null)
- {
- controller.refresh(mbean);
- }
- }
- });
-
- return tabFolder;
- }
-
- private static void createGenericTabFolder(TabFolder tabFolder, JMXManagedObject mbean)
- {
- createAttributesTab(tabFolder, mbean);
- createOperationTabs(tabFolder, mbean);
- }
-
- private static void createAttributesTab(TabFolder tabFolder, JMXManagedObject mbean)
- {
- ServerRegistry serverRegistry = ApplicationRegistry.getServerRegistry(mbean);
- if(serverRegistry.getAttributeModel(mbean).getCount() == 0)
- {
- return;
- }
-
- TabItem tab = new TabItem(tabFolder, SWT.NONE);
- tab.setText(ATTRIBUTES);
- AttributesTabControl controller = new AttributesTabControl(tabFolder);
- tab.setControl(controller.getControl());
- tab.setData(TabControl.CONTROLLER, controller);
- }
-
- private static void createOperationTabs(TabFolder tabFolder, JMXManagedObject mbean)
- {
- ServerRegistry serverRegistry = ApplicationRegistry.getServerRegistry(mbean);
- int operationsCount = serverRegistry.getOperationModel(mbean).getCount();
- if(operationsCount == 0)
- {
- return;
- }
-
- OperationDataModel operationModel = serverRegistry.getOperationModel(mbean);
- for(OperationData operationData : operationModel.getOperations())
- {
- TabItem operationTab = new TabItem(tabFolder, SWT.NONE);
- operationTab.setText(ViewUtility.getDisplayText(operationData.getName()));
- operationTab.setData(operationData);
- OperationTabControl control = new OperationTabControl(tabFolder, operationData);
- operationTab.setData(TabControl.CONTROLLER, control);
- operationTab.setControl(control.getControl());
- }
- }
-
- private static void createNotificationsTabIfNecessary(TabFolder tabFolder, JMXManagedObject mbean)
- {
- NotificationInfoModel[] items = MBeanUtility.getNotificationInfo(mbean);
- if(items == null || items.length == 0)
- {
- //the mbean has no notifications to subscribe for, do not create the tab.
- return;
- }
-
- NotificationsTabControl controller = new NotificationsTabControl(tabFolder, mbean);
-
- TabItem tab = new TabItem(tabFolder, SWT.NONE);
- tab.setText(NOTIFICATIONS);
- tab.setData(TabControl.CONTROLLER, controller);
- tab.setControl(controller.getControl());
- }
-
- /**
- * Creates TabFolder and tabs for all mbeantype (Connection, Queue, and Exchange)
- */
- public static TabFolder generateMBeanTypeTabFolder(final Composite parent, ManagedServer server, String virtualHost)
- {
- TabFolder tabFolder = new TabFolder(parent, SWT.NONE);
- FormData layoutData = new FormData();
- layoutData.left = new FormAttachment(0);
- layoutData.top = new FormAttachment(0);
- layoutData.right = new FormAttachment(100);
- layoutData.bottom = new FormAttachment(100);
- tabFolder.setLayoutData(layoutData);
-
-
- TabItem tab;
- TabControl controller;
-
- tab = new TabItem(tabFolder, SWT.NONE);
- tab.setText(CONNECTION);
- controller = new ConnectionTypeTabControl(tabFolder,server,virtualHost);
- tab.setData(TabControl.CONTROLLER, controller);
- tab.setControl(controller.getControl());
-
- tab = new TabItem(tabFolder, SWT.NONE);
- tab.setText(EXCHANGE);
- controller = new ExchangeTypeTabControl(tabFolder,server,virtualHost);
- tab.setData(TabControl.CONTROLLER, controller);
- tab.setControl(controller.getControl());
-
- tab = new TabItem(tabFolder, SWT.NONE);
- tab.setText(QUEUE);
- controller = new QueueTypeTabControl(tabFolder,server,virtualHost);
- tab.setData(TabControl.CONTROLLER, controller);
- tab.setControl(controller.getControl());
-
- tabFolder.addListener(SWT.Selection, new Listener()
- {
- public void handleEvent(Event evt)
- {
- TabItem tab = (TabItem)evt.item;
- TabControl controller = (TabControl)tab.getData(TabControl.CONTROLLER);
- if(controller != null)
- {
- controller.refresh(null);
- }
- }
- });
-
- return tabFolder;
- }
-
- /**
- * Creates TabFolder and tab for the Connection selection view
- */
- public static TabFolder generateConnectionTypeTabFolder(final Composite parent, ManagedServer server, String virtualHost)
- {
- TabFolder tabFolder = new TabFolder(parent, SWT.NONE);
- FormData layoutData = new FormData();
- layoutData.left = new FormAttachment(0);
- layoutData.top = new FormAttachment(0);
- layoutData.right = new FormAttachment(100);
- layoutData.bottom = new FormAttachment(100);
- tabFolder.setLayoutData(layoutData);
-
- TabItem tab;
- TabControl controller;
-
- tab = new TabItem(tabFolder, SWT.NONE);
- tab.setText(CONNECTION);
- controller = new ConnectionTypeTabControl(tabFolder,server,virtualHost);
- tab.setData(TabControl.CONTROLLER, controller);
- tab.setControl(controller.getControl());
-
- tabFolder.addListener(SWT.Selection, new Listener()
- {
- public void handleEvent(Event evt)
- {
- TabItem tab = (TabItem)evt.item;
- TabControl controller = (TabControl)tab.getData(TabControl.CONTROLLER);
- if(controller != null)
- {
- controller.refresh(null);
- }
- }
- });
-
- return tabFolder;
- }
-
- /**
- * Creates TabFolder and tab for the Exchange selection view
- */
- public static TabFolder generateExchangeTypeTabFolder(final Composite parent, ManagedServer server, String virtualHost)
- {
- TabFolder tabFolder = new TabFolder(parent, SWT.NONE);
- FormData layoutData = new FormData();
- layoutData.left = new FormAttachment(0);
- layoutData.top = new FormAttachment(0);
- layoutData.right = new FormAttachment(100);
- layoutData.bottom = new FormAttachment(100);
- tabFolder.setLayoutData(layoutData);
-
- TabItem tab;
- TabControl controller;
-
- tab = new TabItem(tabFolder, SWT.NONE);
- tab.setText(EXCHANGE);
- controller = new ExchangeTypeTabControl(tabFolder,server,virtualHost);
- tab.setData(TabControl.CONTROLLER, controller);
- tab.setControl(controller.getControl());
-
- tabFolder.addListener(SWT.Selection, new Listener()
- {
- public void handleEvent(Event evt)
- {
- TabItem tab = (TabItem)evt.item;
- TabControl controller = (TabControl)tab.getData(TabControl.CONTROLLER);
- if(controller != null)
- {
- controller.refresh(null);
- }
- }
- });
-
- return tabFolder;
- }
-
- /**
- * Creates TabFolder and tab for the Queue selection view
- */
- public static TabFolder generateQueueTypeTabFolder(final Composite parent, ManagedServer server, String virtualHost)
- {
- TabFolder tabFolder = new TabFolder(parent, SWT.NONE);
- FormData layoutData = new FormData();
- layoutData.left = new FormAttachment(0);
- layoutData.top = new FormAttachment(0);
- layoutData.right = new FormAttachment(100);
- layoutData.bottom = new FormAttachment(100);
- tabFolder.setLayoutData(layoutData);
-
- TabItem tab;
- TabControl controller;
-
- tab = new TabItem(tabFolder, SWT.NONE);
- tab.setText(QUEUE);
- controller = new QueueTypeTabControl(tabFolder,server,virtualHost);
- tab.setData(TabControl.CONTROLLER, controller);
- tab.setControl(controller.getControl());
-
- tabFolder.addListener(SWT.Selection, new Listener()
- {
- public void handleEvent(Event evt)
- {
- TabItem tab = (TabItem)evt.item;
- TabControl controller = (TabControl)tab.getData(TabControl.CONTROLLER);
- if(controller != null)
- {
- controller.refresh(null);
- }
- }
- });
-
- return tabFolder;
- }
-
- private enum QpidMBeanType
- {
- QUEUE (MBEANTYPE_QUEUE),
- CONNECTION (MBEANTYPE_CONNECTION),
- EXCHANGE (MBEANTYPE_EXCHANGE),
- VHOST_MANAGER (MBEANTYPE_VHOST_MANAGER),
- LOGGING_MANAGEMENT (MBEANTYPE_LOGGING_MANAGEMENT),
- USER_MANAGEMENT (MBEANTYPE_USER_MANAGEMENT),
- CONFIGURATION_MANAGEMENT (MBEANTYPE_CONFIGURATION_MANAGEMENT),
- UNKNOWN (null);
-
- private static final Map<String,QpidMBeanType> lookup = new HashMap<String,QpidMBeanType>();
-
- static
- {
- for(QpidMBeanType m : EnumSet.allOf(QpidMBeanType.class))
- {
- lookup.put(m.getType(), m);
- }
- }
-
- private String type;
-
- private QpidMBeanType()
- {
-
- }
-
- private QpidMBeanType(String type)
- {
- this.type = type;
- }
-
- public String getType()
- {
- return type;
- }
-
- public static QpidMBeanType get(String type)
- {
- QpidMBeanType t= lookup.get(type);
- if (t != null)
- {
- return t;
- }
- else
- {
- return UNKNOWN;
- }
-
- }
- }
-
-
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/MBeanView.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/MBeanView.java
deleted file mode 100644
index 65615a6d18..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/MBeanView.java
+++ /dev/null
@@ -1,605 +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.management.ui.views;
-
-import java.util.LinkedList;
-
-import javax.management.MBeanServerConnection;
-
-import static org.apache.qpid.management.ui.Constants.*;
-
-import org.apache.qpid.management.ui.ApiVersion;
-import org.apache.qpid.management.ui.ApplicationRegistry;
-import org.apache.qpid.management.ui.ManagedBean;
-import org.apache.qpid.management.ui.ManagedServer;
-import org.apache.qpid.management.ui.ServerRegistry;
-import org.apache.qpid.management.ui.actions.BackAction;
-import org.apache.qpid.management.ui.jmx.JMXManagedObject;
-import org.apache.qpid.management.ui.jmx.JMXServerRegistry;
-import org.apache.qpid.management.ui.jmx.MBeanUtility;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.FormAttachment;
-import org.eclipse.swt.layout.FormData;
-import org.eclipse.swt.layout.FormLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.TabFolder;
-import org.eclipse.swt.widgets.TabItem;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.ISelectionListener;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.forms.widgets.Form;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.part.ViewPart;
-
-/**
- * MBean View create appropriate view based on the user selection on the Navigation View.
- */
-public class MBeanView extends ViewPart
-{
- public static final String ID = "org.apache.qpid.management.ui.mbeanView";
-
- private FormToolkit _toolkit = null;
- private Form _form = null;
- private String _formText = APPLICATION_NAME;
- private static ManagedServer _server = null;
- private TreeObject _selectedNode = null;
- private ManagedBean _mbean = null;
- private static String _virtualHostName = null;
- private static MBeanServerConnection _mbsc = null;
- private TabFolder _tabFolder = null;
- private ISelectionListener _selectionListener = new SelectionListenerImpl();
-
- // TabFolder to list all the mbeans for a given mbeantype(eg Connection, Queue, Exchange)
- private TabFolder _typeTabFolder = null;
-
- private TabFolder _notificationTabFolder = null;
-
- private LinkedList<Object> _backHistory;
- private BackAction _backAction;
-
- /*
- * Listener for the selection events in the navigation view
- */
- private class SelectionListenerImpl implements ISelectionListener
- {
- public void selectionChanged(IWorkbenchPart part, ISelection sel)
- {
- if (!(sel instanceof IStructuredSelection))
- return;
-
- IStructuredSelection ss = (IStructuredSelection) sel;
- _selectedNode = (TreeObject)ss.getFirstElement();
-
-
- // mbean should be set to null. A selection done on the navigation view can be either an mbean or
- // an mbeantype. For mbeantype selection(eg Connection, Queue, Exchange) _mbean will remain null.
- _mbean = null;
- clearView();
-
- //clear the back history, it is only for use when opening subsequent mbeans not in the nav tree
- _backHistory.clear();
- _backAction.setEnabled(false);
-
- // If a selected node(mbean) gets unregistered from mbean server, mbeanview should
- // make the tabfolber for that mbean invisible
- if (_selectedNode == null)
- {
- return;
- }
-
- setServer();
-
- if(!ApplicationRegistry.isServerConnected(_server))
- {
- return;
- }
-
- if (MBEAN.equals(_selectedNode.getType()))
- {
- _mbean = (ManagedBean)_selectedNode.getManagedObject();
- }
-
- setFormTitle();
- showRelevantTabView();
- }
- }
-
- public void openMBean(ManagedBean mbean)
- {
- openMBean(mbean, false);
- }
-
- private void openMBean(ManagedBean mbean, boolean undoing)
- {
- if(mbean == null)
- {
- return;
- }
-
- //if an mbean is about to be opened (but not returning to using back) from the mbean view,
- //then record the current viewed area/object as a means of back history
- if(!undoing)
- {
- if(_backHistory.isEmpty())
- {
- //ensure the button is enabled if this is to be the first history item
- _backAction.setEnabled(true);
- }
-
- if(_mbean == null)
- {
- //queue etc selection area is open, record the tree object
- _backHistory.addLast(_selectedNode);
- }
- else
- {
- _backHistory.addLast(_mbean);
- }
- }
-
- _mbean = mbean;
-
- try
- {
- clearView();
-
- setFormTitle();
- showMBean(mbean);
-
- _form.layout(true);
- _form.getBody().layout(true, true);
- }
- catch(Exception ex)
- {
- MBeanUtility.handleException(mbean, ex);
- }
- }
-
- private void setFormTitle()
- {
- if (_mbean != null)
- {
- _formText = _mbean.getType();
- if ((_mbean.getVirtualHostName() != null) && (!DEFAULT_VH.equals(_mbean.getVirtualHostName())) )
- {
- _formText = _formText.replaceFirst(VIRTUAL_HOST, _mbean.getVirtualHostName());
- if (_mbean.getName() != null && _mbean.getName().length() != 0)
- {
- _formText = _formText + ": " + _mbean.getName();
- }
- }
- }
- else if ((_selectedNode.getVirtualHost() != null) && (!DEFAULT_VH.equals(_selectedNode.getVirtualHost())))
- {
- _formText = _selectedNode.getVirtualHost();
- }
- else
- {
- _formText = APPLICATION_NAME;
- }
- _form.setText(_formText);
- }
-
- public void showRelevantTabView()
- {
- try
- {
- if (_selectedNode == null)
- {
- return;
- }
-
- String mbeanType = _selectedNode.getType();
-
- if (NODE_TYPE_TYPEINSTANCE.equals(mbeanType))
- {
- // An virtual host instance is selected
- generateTypeTabFolder();
- }
- else if (NODE_TYPE_MBEANTYPE.equals(mbeanType))
- {
- showTypeTabFolder(_selectedNode.getName());
- }
- else if (NOTIFICATIONS.equals(mbeanType))
- {
- refreshNotificationPage();
- }
- else if (MBEAN.equals(mbeanType))
- {
- showMBean(_mbean);
- }
- else if(NODE_TYPE_SERVER.equals(mbeanType))
- {
- ServerRegistry serverReg = ApplicationRegistry.getServerRegistry(_server);
-
- //check the server is connected
- if(serverReg != null)
- {
- //post a message if the server supports a newer API version.
- ApiVersion serverAPI = serverReg.getManagementApiVersion();
- int supportedMajor = ApplicationRegistry.SUPPORTED_QPID_JMX_API_MAJOR_VERSION;
- int supportedMinor = ApplicationRegistry.SUPPORTED_QPID_JMX_API_MINOR_VERSION;
-
- if(serverAPI.greaterThan(supportedMajor, supportedMinor))
- {
- _form.setText("The server supports an updated management API and may offer " +
- "functionality not available with this console. " +
- "Please check for an updated console release.");
- }
-
- }
- }
- else
- {
- return;
- }
-
- _form.layout(true);
- _form.getBody().layout(true, true);
- }
- catch(Exception ex)
- {
- MBeanUtility.handleException(_mbean, ex);
- }
- }
-
- /**
- * Sets the managedServer based on the selection in the navigation view
- * At any given time MBeanView will be displaying information for an mbean of mbeantype
- * for a specifiv managed server. This server information will be used by the tab controllers
- * to get server registry.
- */
- private void setServer()
- {
- if (NODE_TYPE_SERVER.equals(_selectedNode.getType()))
- {
- _server = (ManagedServer)_selectedNode.getManagedObject();
- _virtualHostName = null;
- }
- else
- {
- TreeObject parent = _selectedNode.getParent();
- while (parent != null && !parent.getType().equals(NODE_TYPE_SERVER))
- {
- parent = parent.getParent();
- }
-
- if (parent != null && parent.getType().equals(NODE_TYPE_SERVER))
- _server = (ManagedServer)parent.getManagedObject();
-
- _virtualHostName = _selectedNode.getVirtualHost();
- }
-
- JMXServerRegistry serverRegistry = (JMXServerRegistry)ApplicationRegistry.getServerRegistry(_server);
- if(serverRegistry != null){
- _mbsc = serverRegistry.getServerConnection();
- }
- }
-
- public static ManagedServer getServer()
- {
- return _server;
- }
-
- public static String getVirtualHost()
- {
- return _virtualHostName;
- }
-
- private void showMBean(ManagedBean mbean) throws Exception
- {
- try
- {
- MBeanUtility.getMBeanInfo(mbean);
- }
- catch(Exception ex)
- {
- MBeanUtility.handleException(mbean, ex);
- return;
- }
-
- if (_tabFolder != null && !_tabFolder.isDisposed())
- {
- _tabFolder.dispose();
- }
-
- _tabFolder = MBeanTabFolderFactory.generateMBeanTabFolder(_form.getBody(),(JMXManagedObject)mbean,_mbsc);
-
- int tabIndex = 0;
- if (NOTIFICATIONS.equals(_selectedNode.getType()))
- {
- tabIndex = _tabFolder.getItemCount() -1;
- }
-
- TabItem tab = _tabFolder.getItem(tabIndex);
- // If folder is being set as visible after tab refresh, then the tab
- // doesn't have the focus.
- _tabFolder.setSelection(tabIndex);
- refreshTab(tab);
- }
-
- public void createPartControl(Composite parent)
- {
- // Create the Form
- _toolkit = new FormToolkit(parent.getDisplay());
- _form = _toolkit.createForm(parent);
- _form.getBody().setLayout(new FormLayout());
- _form.setText(APPLICATION_NAME);
-
- // Add selection listener for selection events in the Navigation view
- getSite().getPage().addSelectionListener(NavigationView.ID, _selectionListener);
-
- createNotificationsTabFolder();
-
- ViewUtility.setMBeanView(this);
-
- _backAction = new BackAction();
- getViewSite().getActionBars().getToolBarManager().add(_backAction);
- _backAction.setEnabled(false);
- _backHistory = new LinkedList<Object>();
- }
-
- private void refreshTab(TabItem tab)
- {
- if (tab == null)
- {
- return;
- }
-
- TabControl controller = (TabControl)tab.getData(TabControl.CONTROLLER);
- if(controller != null)
- {
- controller.refresh(_mbean);
- }
- }
-
- public void setFocus()
- {
- //_form.setFocus();
- }
-
- public void dispose()
- {
- _toolkit.dispose();
- super.dispose();
- }
-
-
- private void createNotificationsTabFolder()
- {
- _notificationTabFolder = new TabFolder(_form.getBody(), SWT.NONE);
- FormData layoutData = new FormData();
- layoutData.left = new FormAttachment(0);
- layoutData.top = new FormAttachment(0);
- layoutData.right = new FormAttachment(100);
- layoutData.bottom = new FormAttachment(100);
- _notificationTabFolder.setLayoutData(layoutData);
- _notificationTabFolder.setVisible(false);
-
- VHNotificationsTabControl controller = new VHNotificationsTabControl(_notificationTabFolder);
- TabItem tab = new TabItem(_notificationTabFolder, SWT.NONE);
- tab.setText(NOTIFICATIONS);
- tab.setData(TabControl.CONTROLLER, controller);
- tab.setControl(controller.getControl());
- }
-
- private void refreshNotificationPage()
- {
- TabItem tab = _notificationTabFolder.getItem(0);
- VHNotificationsTabControl controller = (VHNotificationsTabControl)tab.getData(TabControl.CONTROLLER);
- controller.refresh();
- _notificationTabFolder.setVisible(true);
- }
-
-
-
- private void generateTypeTabFolder() throws Exception
- {
- if (_typeTabFolder != null && !_typeTabFolder.isDisposed())
- {
- _typeTabFolder.dispose();
- }
-
- //Generates the full Queue/Connection/Exchange selection tab set
- _typeTabFolder = MBeanTabFolderFactory.generateMBeanTypeTabFolder(
- _form.getBody(), getServer(), getVirtualHost());
- refreshTab(_typeTabFolder.getItem(0));
- }
-
- private void showTypeTabFolder(String type) throws Exception
- {
- if (_typeTabFolder != null && !_typeTabFolder.isDisposed())
- {
- _typeTabFolder.dispose();
- }
-
- if (CONNECTION.equals(type))
- {
- //Generates the Connection selection tab
- _typeTabFolder = MBeanTabFolderFactory.generateConnectionTypeTabFolder(
- _form.getBody(), getServer(), getVirtualHost());
- refreshTab(_typeTabFolder.getItem(0));
- }
- else if (EXCHANGE.equals(type))
- {
- //Generates the Exchange selection tab
- _typeTabFolder = MBeanTabFolderFactory.generateExchangeTypeTabFolder(
- _form.getBody(), getServer(), getVirtualHost());
- refreshTab(_typeTabFolder.getItem(0));
- }
- else if (QUEUE.equals(type))
- {
- //Generates the Queue selection tab
- _typeTabFolder = MBeanTabFolderFactory.generateQueueTypeTabFolder(
- _form.getBody(), getServer(), getVirtualHost());
- refreshTab(_typeTabFolder.getItem(0));
- }
- }
-
- private void clearView()
- {
- if (_tabFolder != null && !_tabFolder.isDisposed())
- {
- _tabFolder.setVisible(false);
- }
-
- if (_typeTabFolder != null && !_typeTabFolder.isDisposed())
- {
- _typeTabFolder.setVisible(false);
- }
-
- if (_notificationTabFolder != null && !_notificationTabFolder.isDisposed())
- {
- _notificationTabFolder.setVisible(false);
- }
-
- _form.setText(APPLICATION_NAME);
- clearStatusBar();
- }
-
- public void mbeanUnregistered(ManagedBean mbean)
- {
- //if the mbean is actually open, clear the view and empty the Back history
- if(mbean == _mbean)
- {
- clearView();
- _backHistory.clear();
- _backAction.setEnabled(false);
- ViewUtility.popupInfoMessage("MBean Unregistered",
- "The open MBean was unregistered from the server.");
- }
- }
-
- public void refresh()
- {
- if(!ApplicationRegistry.isServerConnected(_server))
- {
- return;
- }
-
- if (_tabFolder != null && !_tabFolder.isDisposed())
- {
- if(_tabFolder.getVisible())
- {
- int selectedTab = _tabFolder.getSelectionIndex();
- TabItem tab = _tabFolder.getItem(selectedTab);
- TabControl controller = (TabControl) tab.getData(TabControl.CONTROLLER);
- if(controller != null)
- {
- controller.refresh(_mbean);
- }
- return;
- }
- }
-
- if (_typeTabFolder != null && !_typeTabFolder.isDisposed())
- {
-
- if(_typeTabFolder.getVisible())
- {
- int selectedTab = _typeTabFolder.getSelectionIndex();
- TabItem tab = _typeTabFolder.getItem(selectedTab);
- TabControl controller = (TabControl) tab.getData(TabControl.CONTROLLER);
- if(controller != null)
- {
- controller.refresh(_mbean);
- }
- return;
- }
- }
-
- if (_notificationTabFolder != null && !_notificationTabFolder.isDisposed())
- {
- if(_notificationTabFolder.getVisible())
- {
- int selectedTab = _notificationTabFolder.getSelectionIndex();
- TabItem tab = _notificationTabFolder.getItem(selectedTab);
- TabControl controller = (TabControl) tab.getData(TabControl.CONTROLLER);
- if(controller != null)
- {
- controller.refresh(_mbean);
- }
- return;
- }
- }
- }
-
- public void populateStatusBar(Image icon, String message)
- {
- IActionBars bars = getViewSite().getActionBars();
- bars.getStatusLineManager().setMessage(icon, message);
- }
-
- public void populateStatusBar(String message)
- {
- IActionBars bars = getViewSite().getActionBars();
- bars.getStatusLineManager().setMessage(message);
- }
-
- public void clearStatusBar()
- {
- populateStatusBar("");
- }
-
- public void back() throws Exception
- {
- if(_backHistory.isEmpty())
- {
- return;
- }
-
- Object previous = _backHistory.removeLast();
- if(_backHistory.isEmpty())
- {
- //if this is the last history item, disable the action button
- _backAction.setEnabled(false);
- }
-
- if(previous instanceof ManagedBean)
- {
- openMBean((ManagedBean)previous, true);
- }
- else if (previous instanceof TreeObject)
- {
- _mbean = null;
- clearView();
- setFormTitle();
-
- TreeObject node = (TreeObject) previous;
- String mbeanType = node.getType();
-
- if (NODE_TYPE_TYPEINSTANCE.equals(mbeanType))
- {
- generateTypeTabFolder();
- }
- else if (NODE_TYPE_MBEANTYPE.equals(mbeanType))
- {
- showTypeTabFolder(node.getName());
- }
- }
-
- _form.layout(true);
- _form.getBody().layout(true, true);
- }
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/NavigationView.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/NavigationView.java
deleted file mode 100644
index 417734e5fb..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/NavigationView.java
+++ /dev/null
@@ -1,1372 +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.management.ui.views;
-
-import static org.apache.qpid.management.ui.Constants.*;
-import static org.apache.qpid.management.ui.ApplicationRegistry.DATA_DIR;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.concurrent.ConcurrentHashMap;
-
-import org.apache.qpid.management.common.mbeans.ConfigurationManagement;
-import org.apache.qpid.management.common.mbeans.LoggingManagement;
-import org.apache.qpid.management.common.mbeans.ServerInformation;
-import org.apache.qpid.management.common.mbeans.UserManagement;
-import org.apache.qpid.management.ui.ApiVersion;
-import org.apache.qpid.management.ui.ApplicationRegistry;
-import org.apache.qpid.management.ui.ManagedBean;
-import org.apache.qpid.management.ui.ManagedObject;
-import org.apache.qpid.management.ui.ManagedServer;
-import org.apache.qpid.management.ui.ServerRegistry;
-import org.apache.qpid.management.ui.exceptions.InfoRequiredException;
-import org.apache.qpid.management.ui.exceptions.ManagementConsoleException;
-import org.apache.qpid.management.ui.jmx.JMXServerRegistry;
-import org.apache.qpid.management.ui.jmx.MBeanUtility;
-import org.eclipse.jface.preference.PreferenceStore;
-import org.eclipse.jface.viewers.DoubleClickEvent;
-import org.eclipse.jface.viewers.IDoubleClickListener;
-import org.eclipse.jface.viewers.IFontProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.ITreeViewerListener;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.TreeExpansionEvent;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerSorter;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Event;
-import org.eclipse.swt.widgets.Listener;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.MenuItem;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Tree;
-import org.eclipse.swt.widgets.TreeItem;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.part.ViewPart;
-
-/**
- * Navigation View for navigating the managed servers and managed beans on
- * those servers
- * @author Bhupendra Bhardwaj
- */
-public class NavigationView extends ViewPart
-{
- public static final String ID = "org.apache.qpid.management.ui.navigationView";
- public static final String INI_FILENAME = DATA_DIR + File.separator + "qpidmc_navigation.ini";
-
- private static final String INI_SERVERS = "Servers";
- private static final String INI_QUEUES = QUEUE + "s";
- private static final String INI_CONNECTIONS = CONNECTION + "s";
- private static final String INI_EXCHANGES = EXCHANGE + "s";
-
- private TreeViewer _treeViewer = null;
- private TreeObject _serversRootNode = null;
-
- private PreferenceStore _preferences;
- // Map of connected servers
- private ConcurrentHashMap<ManagedServer, TreeObject> _managedServerMap = new ConcurrentHashMap<ManagedServer, TreeObject>();
-
- private static HashSet<String> _serverTopLevelMBeans = new HashSet<String>();
- {
- _serverTopLevelMBeans.add(UserManagement.TYPE);
- _serverTopLevelMBeans.add(LoggingManagement.TYPE);
- _serverTopLevelMBeans.add(ConfigurationManagement.TYPE);
- _serverTopLevelMBeans.add(ServerInformation.TYPE);
- }
-
- private void createTreeViewer(Composite parent)
- {
- _treeViewer = new TreeViewer(parent);
- _treeViewer.setContentProvider(new ContentProviderImpl());
- _treeViewer.setLabelProvider(new LabelProviderImpl());
- _treeViewer.setSorter(new ViewerSorterImpl());
-
- // layout the tree viewer below the label field, to cover the area
- GridData layoutData = new GridData();
- layoutData.grabExcessHorizontalSpace = true;
- layoutData.grabExcessVerticalSpace = true;
- layoutData.horizontalAlignment = GridData.FILL;
- layoutData.verticalAlignment = GridData.FILL;
- _treeViewer.getControl().setLayoutData(layoutData);
- _treeViewer.setUseHashlookup(true);
-
- createListeners();
- }
-
- /**
- * Creates listeners for the JFace treeviewer
- */
- private void createListeners()
- {
- _treeViewer.addDoubleClickListener(new IDoubleClickListener()
- {
- public void doubleClick(DoubleClickEvent event)
- {
- IStructuredSelection ss = (IStructuredSelection) event.getSelection();
- if ((ss == null) || (ss.getFirstElement() == null))
- {
- return;
- }
-
- boolean state = _treeViewer.getExpandedState(ss.getFirstElement());
- _treeViewer.setExpandedState(ss.getFirstElement(), !state);
- }
- });
-
- _treeViewer.addTreeListener(new ITreeViewerListener()
- {
- public void treeExpanded(TreeExpansionEvent event)
- {
- getSite().getShell().getDisplay().asyncExec(
- new Runnable()
- {
- public void run()
- {
- _treeViewer.refresh();
- }
- });
- }
-
- public void treeCollapsed(TreeExpansionEvent event)
- {
- getSite().getShell().getDisplay().asyncExec(
- new Runnable()
- {
- public void run()
- {
- _treeViewer.refresh();
- }
- });
- }
- });
-
- // This listener is for popup menu, which pops up if a queue,exchange or connection is selected
- // with right click.
- _treeViewer.getTree().addListener(SWT.MenuDetect, new Listener()
- {
- Display display = getSite().getShell().getDisplay();
- final Shell shell = new Shell(display);
-
- public void handleEvent(Event event)
- {
- Tree widget = (Tree) event.widget;
- TreeItem[] items = widget.getSelection();
- if (items == null)
- {
- return;
- }
-
- // Get the selected node
- final TreeObject selectedNode = (TreeObject) items[0].getData();
- final TreeObject parentNode = selectedNode.getParent();
-
- // This popup is only for mbeans and only connection,exchange and queue types
- if ((parentNode == null) || !MBEAN.equals(selectedNode.getType())
- || !(CONNECTION.equals(parentNode.getName()) || QUEUE.equals(parentNode.getName())
- || EXCHANGE.equals(parentNode.getName())))
- {
- return;
- }
-
- Menu menu = new Menu(shell, SWT.POP_UP);
- MenuItem item = new MenuItem(menu, SWT.PUSH);
- // Add the action item, which will remove the node from the tree if selected
- item.setText(ACTION_REMOVE_MBEANNODE);
- item.addListener(SWT.Selection, new Listener()
- {
- public void handleEvent(Event e)
- {
- removeManagedObject(parentNode, (ManagedBean) selectedNode.getManagedObject(), true);
- _treeViewer.refresh();
- // set the selection to the parent node
- _treeViewer.setSelection(new StructuredSelection(parentNode));
- }
- });
- menu.setLocation(event.x, event.y);
- menu.setVisible(true);
- while (!menu.isDisposed() && menu.isVisible())
- {
- if (!display.readAndDispatch())
- {
- display.sleep();
- }
- }
-
- menu.dispose();
- }
- });
- }
-
- /**
- * Creates Qpid Server connection
- * @param server
- * @throws Exception
- */
- private void createJMXServerConnection(ManagedServer server) throws Exception
- {
- // Currently Qpid Management Console only supports JMX MBeanServer
- JMXServerRegistry serverRegistry = new JMXServerRegistry(server);
-
- try
- {
- //determine the management API version of the server just connected to
- MBeanUtility.classifyManagementApiVersion(server, serverRegistry);
- }
- catch (Exception e)
- {
- //Exception classifying the server API, clean up the connection and rethrow
- serverRegistry.closeServerConnection();
- throw e;
- }
-
- //check that the console supports the API major version encountered, otherwise abort.
- ApiVersion serverAPI = serverRegistry.getManagementApiVersion();
-
- int serverMajor = serverAPI.getMajor();
- int supportedMajor = ApplicationRegistry.SUPPORTED_QPID_JMX_API_MAJOR_VERSION;
-
- if(serverMajor > supportedMajor)
- {
- serverRegistry.closeServerConnection();
- throw new ManagementConsoleException("The server management API version encountered is not supported"
- + " by this console release. Please check for an updated console release.");
- }
-
- //connection succeeded, add the ServerRegistry to the ApplicationRegistry
- ApplicationRegistry.addServer(server, serverRegistry);
- }
-
- /**
- * Adds a new server node in the navigation view if server connection is successful.
- * @param transportProtocol
- * @param host
- * @param port
- * @param domain
- * @throws Exception
- */
- public void addNewServer(String host, int port, String domain, String user, String pwd)
- throws Exception
- {
- ManagedServer managedServer = new ManagedServer(host, port, domain, user, pwd);
-
- String server = managedServer.getName();
- List<TreeObject> list = _serversRootNode.getChildren();
- for (TreeObject node : list)
- {
- ManagedServer nodeServer = (ManagedServer)node.getManagedObject();
- if (server.equals(nodeServer.getName()))
- {
- // Server is already in the list of added servers, so now connect it.
- // Set the server node as selected and then connect it.
- _treeViewer.setSelection(new StructuredSelection(node));
- reconnect(user, pwd);
-
- return;
- }
- }
-
- // The server is not in the list of already added servers, so now connect and add it.
- createJMXServerConnection(managedServer);
-
- // Server connection is successful. Now add the server in the tree
- TreeObject serverNode = new TreeObject(server, NODE_TYPE_SERVER);
- serverNode.setManagedObject(managedServer);
- _serversRootNode.addChild(serverNode);
-
- // Add server in the connected server map
- _managedServerMap.put(managedServer, serverNode);
-
- // populate the server tree
- try
- {
- populateServer(serverNode);
- }
- catch (SecurityException ex)
- {
- disconnect(managedServer);
- throw ex;
- }
-
- // Add the Queue/Exchanges/Connections from config file into the navigation tree
- addConfiguredItems(managedServer);
-
- _treeViewer.refresh();
-
- expandInitialMBeanView(serverNode);
-
- //(re)select the server node now that it is connected to force a selectionEvent
- _treeViewer.setSelection(new StructuredSelection(serverNode));
- _treeViewer.refresh();
-
- // save server address in file
- addServerInConfigFile(server);
- }
-
- /**
- * Create the config file, if it doesn't already exist.
- * Exits the application if the file could not be created.
- */
- private void createConfigFile()
- {
- File dir = new File(DATA_DIR);
- if (!dir.exists())
- {
- if(!dir.mkdir())
- {
- System.out.println("Could not create application data directory " + DATA_DIR);
- System.exit(1);
- }
- }
-
- File file = new File(INI_FILENAME);
- try
- {
- if (!file.exists())
- {
- file.createNewFile();
- }
- }
- catch (IOException ex)
- {
- System.out.println("Could not write to the file " + INI_FILENAME);
- System.out.println(ex);
- System.exit(1);
- }
- }
-
- /**
- * Server addresses are stored in a file. When user launches the application again, the
- * server addresses are picked up from the file and shown in the navigfation view. This method
- * adds the server address in a file, when a new server is added in the navigation view.
- * @param serverAddress
- */
- private void addServerInConfigFile(String serverAddress)
- {
- // Check if the address already exists
- List<String> list = getServerListFromFile();
- if ((list != null) && list.contains(serverAddress))
- {
- return;
- }
-
- // Get the existing server list and add to that
- String servers = _preferences.getString(INI_SERVERS);
- String value = (servers.length() != 0) ? (servers + "," + serverAddress) : serverAddress;
- _preferences.putValue(INI_SERVERS, value);
- try
- {
- _preferences.save();
- }
- catch (IOException ex)
- {
- System.err.println("Could not add " + serverAddress + " in " + INI_SERVERS + " (" + INI_FILENAME + ")");
- System.out.println(ex);
- }
- }
-
- /**
- * Adds the item (Queue/Exchange/Connection) to the config file
- * @param server
- * @param virtualhost
- * @param type - (Queue or Exchange or Connection)
- * @param name - item name
- */
- private void addItemInConfigFile(TreeObject node)
- {
- ManagedBean mbean = (ManagedBean) node.getManagedObject();
- String server = mbean.getServer().getName();
- String virtualhost = mbean.getVirtualHostName();
- String type = node.getParent().getName() + "s";
- String name = node.getName();
- String itemKey = server + "." + virtualhost + "." + type;
-
- // Check if the item already exists in the config file
- List<String> list = getConfiguredItemsFromFile(itemKey);
- if ((list != null) && list.contains(name))
- {
- return;
- }
-
- // Add this item to the existing list of items
- String items = _preferences.getString(itemKey);
- String value = (items.length() != 0) ? (items + "," + name) : name;
- _preferences.putValue(itemKey, value);
- try
- {
- _preferences.save();
- }
- catch (IOException ex)
- {
- System.err.println("Could not add " + name + " in " + itemKey + " (" + INI_FILENAME + ")");
- System.out.println(ex);
- }
- }
-
- private void removeItemFromConfigFile(TreeObject node)
- {
- ManagedBean mbean = (ManagedBean) node.getManagedObject();
- String server = mbean.getServer().getName();
- String vHost = mbean.getVirtualHostName();
- String type = node.getParent().getName() + "s";
- String itemKey = server + "." + vHost + "." + type;
-
- List<String> list = getConfiguredItemsFromFile(itemKey);
- if (list.contains(node.getName()))
- {
- list.remove(node.getName());
- String value = "";
- for (String item : list)
- {
- value += item + ",";
- }
-
- value = (value.lastIndexOf(",") != -1) ? value.substring(0, value.lastIndexOf(",")) : value;
-
- _preferences.putValue(itemKey, value);
- try
- {
- _preferences.save();
- }
- catch (IOException ex)
- {
- System.err.println("Error in updating the config file " + INI_FILENAME);
- System.out.println(ex);
- }
- }
- }
-
- //check if the MBeanInfo can be retrieved.
- private boolean haveAccessPermission(ManagedBean mbean)
- {
- try
- {
- MBeanUtility.getMBeanInfo(mbean);
- }
- catch(Exception ex)
- {
- return false;
- }
-
- return true;
- }
-
- /**
- * Queries the qpid server for MBeans and populates the navigation view with all MBeans for
- * the given server node.
- * @param serverNode
- * @throws Exception
- */
- private void populateServer(TreeObject serverNode) throws Exception
- {
- ManagedServer server = (ManagedServer) serverNode.getManagedObject();
- String domain = server.getDomain();
-
- List<ManagedBean> mbeans = MBeanUtility.getManagedObjectsForDomain(server, domain);
- for (ManagedBean mbean : mbeans)
- {
- mbean.setServer(server);
- ServerRegistry serverRegistry = ApplicationRegistry.getServerRegistry(server);
- serverRegistry.addManagedObject(mbean);
-
- // Add all mbeans other than Connections, Exchanges and Queues. Because these will be added
- // manually by selecting from MBeanView
- if (!(mbean.isConnection() || mbean.isExchange() || mbean.isQueue()))
- {
- //if we cant get the MBeanInfo then we cant display the mbean, so dont add it to the tree
- if (haveAccessPermission(mbean))
- {
- addManagedBean(serverNode, mbean);
- }
- }
- }
- // To make it work with the broker without virtual host implementation.
- // This will add the default nodes to the domain node
- boolean hasVirtualHost = false;
- for (TreeObject child : serverNode.getChildren())
- {
- if (child.getName().startsWith(VIRTUAL_HOST))
- {
- hasVirtualHost = true;
- break;
- }
- }
-
- if (!hasVirtualHost){
- addDefaultNodes(serverNode);
- }
- }
-
- /**
- * Add these three types - Connection, Exchange, Queue
- * By adding these, these will always be available, even if there are no mbeans under thse types
- * This is required because, the mbeans will be added from mbeanview, by selecting from the list
- * @param parent Node
- */
- private void addDefaultNodes(TreeObject parent)
- {
- TreeObject typeChild = new TreeObject(CONNECTION, NODE_TYPE_MBEANTYPE);
- typeChild.setParent(parent);
- typeChild.setVirtualHost(parent.getVirtualHost());
- typeChild = new TreeObject(EXCHANGE, NODE_TYPE_MBEANTYPE);
- typeChild.setParent(parent);
- typeChild.setVirtualHost(parent.getVirtualHost());
- typeChild = new TreeObject(QUEUE, NODE_TYPE_MBEANTYPE);
- typeChild.setParent(parent);
- typeChild.setVirtualHost(parent.getVirtualHost());
-
- // Add common notification node for virtual host
- TreeObject notificationNode = new TreeObject(NOTIFICATIONS, NOTIFICATIONS);
- notificationNode.setParent(parent);
- notificationNode.setVirtualHost(parent.getVirtualHost());
- }
-
- /**
- * Checks if a particular mbeantype is already there in the navigation view for a domain.
- * This is used while populating domain with mbeans.
- * @param parent
- * @param typeName
- * @return Node if given mbeantype already exists, otherwise null
- */
- private TreeObject getMBeanTypeNode(TreeObject parent, String typeName)
- {
- List<TreeObject> childNodes = parent.getChildren();
- for (TreeObject child : childNodes)
- {
- if ((NODE_TYPE_MBEANTYPE.equals(child.getType()) || NODE_TYPE_TYPEINSTANCE.equals(child.getType()))
- && typeName.equals(child.getName()))
- {
- return child;
- }
- }
-
- return null;
- }
-
- private boolean doesMBeanNodeAlreadyExist(TreeObject typeNode, String mbeanName)
- {
- List<TreeObject> childNodes = typeNode.getChildren();
- for (TreeObject child : childNodes)
- {
- if (MBEAN.equals(child.getType()) && mbeanName.equals(child.getName()))
- {
- return true;
- }
- }
-
- return false;
- }
-
- /**
- * Adds the given MBean to the given domain node.
- * sample ObjectNames -
- * org.apache.qpid:type=VirtualHost.VirtualHostManager,VirtualHost=localhost
- * org.apache.qpid:type=VirtualHost.Queue,VirtualHost=test,name=ping_1
- * @param parent parent tree node to add the mbean to
- * @param mbean mbean to add
- */
- private void addManagedBean(TreeObject parent, ManagedBean mbean)
- {
- String name = mbean.getName();
- // Split the mbean type into array of Strings, to create hierarchy
- // eg. type=VirtualHost.VirtualHostManager,VirtualHost=localhost will be:
- // localhost->VirtualHostManager
- // eg. type=org.apache.qpid:type=VirtualHost.Queue,VirtualHost=test,name=ping will be:
- // test->Queue->ping
- String[] types = mbean.getType().split("\\.");
- TreeObject typeNode = null;
- TreeObject parentNode = parent;
-
- // Run this loop till all nodes(hierarchy) for this mbean are created. This loop only creates
- // all the required parent nodes for the mbean
- for (int i = 0; i < types.length; i++)
- {
- String type = types[i];
-
- if(types.length == 1 && _serverTopLevelMBeans.contains(type))
- {
- //This mbean is not to be contained in a type hierarchy
- //Just add it as a child of the server node.
- break;
- }
-
- String valueOftype = mbean.getProperty(type);
- // If value is not null, then there will be a parent node for this mbean
- // eg. for type=VirtualHost the value is "test"
- typeNode = getMBeanTypeNode(parentNode, type);
-
- // create the type node if not already created
- if (typeNode == null)
- {
- // If the ObjectName doesn't have name property, that means there will be only one instance
- // of this mbean for given "type". So there will be no type node created for this mbean.
- if ((name == null) && (i == (types.length - 1)))
- {
- break;
- }
-
- // create a node for "type"
- typeNode = createTypeNode(parentNode, type);
- if (!type.equals(VIRTUAL_HOST))
- {
- typeNode.setVirtualHost(mbean.getVirtualHostName());
- }
- }
-
- // now type node create becomes the parent node for next node in hierarchy
- parentNode = typeNode;
-
- /*
- * Now create instances node for this type if value exists.
- */
- if (valueOftype == null)
- {
- // No instance node will be created when value is null (eg type=Queue)
- break;
- }
-
- // For different virtual hosts, the nodes with given value will be created.
- // eg type=VirtualHost, value=test
- typeNode = getMBeanTypeNode(parentNode, valueOftype);
- if (typeNode == null)
- {
- typeNode = createTypeInstanceNode(parentNode, valueOftype);
- typeNode.setVirtualHost(mbean.getVirtualHostName());
-
- // Create default nodes for VHost instances
- if (type.equals(VIRTUAL_HOST))
- {
- addDefaultNodes(typeNode);
- }
- }
-
- parentNode = typeNode;
- }
-
- if (typeNode == null)
- {
- typeNode = parentNode;
- }
-
- // Check if an MBean is already added
- if (doesMBeanNodeAlreadyExist(typeNode, name))
- {
- return;
- }
-
- // Add the mbean node now
- TreeObject mbeanNode = new TreeObject(mbean);
- mbeanNode.setVirtualHost(mbean.getVirtualHostName());
- mbeanNode.setParent(typeNode);
-
- // Add the mbean to the config file
- if (mbean.isQueue() || mbean.isExchange() || mbean.isConnection())
- {
- addItemInConfigFile(mbeanNode);
- }
- }
-
- private TreeObject createTypeNode(TreeObject parent, String name)
- {
- TreeObject typeNode = new TreeObject(name, NODE_TYPE_MBEANTYPE);
- typeNode.setParent(parent);
-
- return typeNode;
- }
-
- private TreeObject createTypeInstanceNode(TreeObject parent, String name)
- {
- TreeObject typeNode = new TreeObject(name, NODE_TYPE_TYPEINSTANCE);
- typeNode.setParent(parent);
-
- return typeNode;
- }
-
- /**
- * Removes all the child nodes of the given parent node. Used when closing a server.
- * @param parent
- */
- private void removeManagedObject(TreeObject parent)
- {
- if(parent == null)
- {
- return;
- }
-
- List<TreeObject> list = parent.getChildren();
- for (TreeObject child : list)
- {
- removeManagedObject(child);
- }
-
- list.clear();
- }
-
- /**
- * Removes the mbean from the tree
- * @param parent
- * @param mbean
- */
- private void removeManagedObject(TreeObject parent, ManagedBean mbean, boolean removeFromConfigFile)
- {
- List<TreeObject> list = parent.getChildren();
- TreeObject objectToRemove = null;
- for (TreeObject child : list)
- {
- if (MBEAN.equals(child.getType()))
- {
- String name = (mbean.getName() != null) ? mbean.getName() : mbean.getType();
- if (child.getName().equals(name))
- {
- objectToRemove = child;
-
- break;
- }
- }
- else
- {
- removeManagedObject(child, mbean, removeFromConfigFile);
- }
- }
-
- if (objectToRemove != null)
- {
- list.remove(objectToRemove);
- if(removeFromConfigFile)
- {
- removeItemFromConfigFile(objectToRemove);
- }
- }
-
- }
-
- /**
- * Closes the Qpid server connection
- */
- public void disconnect() throws Exception
- {
- TreeObject selectedNode = getSelectedServerNode();
- ManagedServer managedServer = (ManagedServer) selectedNode.getManagedObject();
- disconnect(managedServer);
- }
-
- private void disconnect(ManagedServer managedServer) throws Exception
- {
- if (!_managedServerMap.containsKey(managedServer))
- {
- return;
- }
-
- // Close server connection
- ServerRegistry serverRegistry = ApplicationRegistry.getServerRegistry(managedServer);
- if (serverRegistry == null) // server connection is already closed
- {
- return;
- }
-
- // Add server to the closed server list and the worker thread will remove the server from required places.
- ApplicationRegistry.serverConnectionClosed(managedServer);
-
- //close the connection
- serverRegistry.closeServerConnection();
- }
-
- /**
- * Connects the selected server node
- * @throws Exception
- */
- public void reconnect(String user, String password) throws Exception
- {
- TreeObject selectedNode = getSelectedServerNode();
- ManagedServer managedServer = (ManagedServer) selectedNode.getManagedObject();
- if (_managedServerMap.containsKey(managedServer))
- {
- throw new InfoRequiredException("Server " + managedServer.getName() + " is already connected");
- }
-
- managedServer.setUser(user);
- managedServer.setPassword(password);
- createJMXServerConnection(managedServer);
-
- // put the server in the managed server map
- _managedServerMap.put(managedServer, selectedNode);
-
- try
- {
- // populate the server tree now
- populateServer(selectedNode);
- }
- catch (SecurityException ex)
- {
- disconnect(managedServer);
- throw ex;
- }
-
-
- // Add the Queue/Exchanges/Connections from config file into the navigation tree
- addConfiguredItems(managedServer);
-
- expandInitialMBeanView(selectedNode);
-
- //(re)select the server node now that it is connected to force a selectionEvent
- _treeViewer.setSelection(new StructuredSelection(selectedNode));
- _treeViewer.refresh();
- }
-
- private void expandInitialMBeanView(TreeObject serverNode)
- {
- if (serverNode.getChildren().size() == 0 )
- {
- return;
- }
- else
- {
- _treeViewer.setExpandedState(serverNode , true);
- }
-
- List<TreeObject> children = serverNode.getChildren();
- for (TreeObject child : children)
- {
- if (child.getChildren().size() > 0)
- {
- _treeViewer.setExpandedState(child, true);
- }
- }
- }
-
- /**
- * Adds the items(queues/exchanges/connectins) from config file to the server tree
- * @param server
- */
- private void addConfiguredItems(ManagedServer server)
- {
- ServerRegistry serverRegistry = ApplicationRegistry.getServerRegistry(server);
- List<String> list = serverRegistry.getVirtualHosts();
- for (String virtualHost : list)
- {
- // Add Queues
- String itemKey = server.getName() + "." + virtualHost + "." + INI_QUEUES;
- List<String> items = getConfiguredItemsFromFile(itemKey);
- List<ManagedBean> mbeans = serverRegistry.getQueues(virtualHost);
- addConfiguredItems(items, mbeans);
-
- // Add Exchanges
- itemKey = server.getName() + "." + virtualHost + "." + INI_EXCHANGES;
- items = getConfiguredItemsFromFile(itemKey);
- mbeans = serverRegistry.getExchanges(virtualHost);
- addConfiguredItems(items, mbeans);
-
- // Add Connections
- itemKey = server.getName() + "." + virtualHost + "." + INI_CONNECTIONS;
- items = getConfiguredItemsFromFile(itemKey);
- mbeans = serverRegistry.getConnections(virtualHost);
- addConfiguredItems(items, mbeans);
- }
- }
-
- /**
- * Gets the mbeans corresponding to the items and adds those to the navigation tree
- * @param items
- * @param mbeans
- */
- private void addConfiguredItems(List<String> items, List<ManagedBean> mbeans)
- {
- if ((items == null) || (items.isEmpty() || (mbeans == null)) || mbeans.isEmpty())
- {
- return;
- }
-
- for (String item : items)
- {
- for (ManagedBean mbean : mbeans)
- {
- if (item.equals(mbean.getName()))
- {
- addManagedBean(mbean);
-
- break;
- }
- }
- }
- }
-
- /**
- * Closes the Qpid server connection if not already closed and removes the server node from the navigation view and
- * also from the ini file stored in the system.
- * @throws Exception
- */
- public void removeServer() throws Exception
- {
- disconnect();
-
- // Remove from the Tree
- String serverNodeName = getSelectedServerNode().getName();
- List<TreeObject> list = _serversRootNode.getChildren();
- TreeObject objectToRemove = null;
- for (TreeObject child : list)
- {
- if (child.getName().equals(serverNodeName))
- {
- objectToRemove = child;
-
- break;
- }
- }
-
- if (objectToRemove != null)
- {
- list.remove(objectToRemove);
- }
-
- _treeViewer.refresh();
-
- // Remove from the ini file
- removeServerFromConfigFile(serverNodeName);
- }
-
- private void removeServerFromConfigFile(String serverNodeName)
- {
- List<String> serversList = getServerListFromFile();
- serversList.remove(serverNodeName);
-
- String value = "";
- for (String item : serversList)
- {
- value += item + ",";
- }
-
- value = (value.lastIndexOf(",") != -1) ? value.substring(0, value.lastIndexOf(",")) : value;
-
- _preferences.putValue(INI_SERVERS, value);
-
- try
- {
- _preferences.save();
- }
- catch (IOException ex)
- {
- System.err.println("Error in updating the config file " + INI_FILENAME);
- System.out.println(ex);
- }
- }
-
- /**
- * @return the server addresses from the ini file
- * @throws Exception
- */
- private List<String> getServerListFromFile()
- {
- return getConfiguredItemsFromFile(INI_SERVERS);
- }
-
- /**
- * Returns the list of items from the config file.
- * sample ini file:
- * Servers=localhost:8999,127.0.0.1:8999
- * localhost.virtualhost1.Queues=queue1,queue2
- * localhost.virtualhost1.Exchanges=exchange1,exchange2
- * localhost.virtualhost2.Connections=conn1
- * @param key
- * @return
- */
- private List<String> getConfiguredItemsFromFile(String key)
- {
- List<String> list = new ArrayList<String>();
- String items = _preferences.getString(key);
- if (items.length() != 0)
- {
- String[] array = items.split(",");
- for (String item : array)
- {
- list.add(item);
- }
- }
-
- return list;
- }
-
- public TreeObject getSelectedServerNode() throws Exception
- {
- IStructuredSelection ss = (IStructuredSelection) _treeViewer.getSelection();
- TreeObject selectedNode = (TreeObject) ss.getFirstElement();
- if (ss.isEmpty() || (selectedNode == null) || (!selectedNode.getType().equals(NODE_TYPE_SERVER)))
- {
- throw new InfoRequiredException("Please select the server");
- }
-
- return selectedNode;
- }
-
- /**
- * This is a callback that will allow us to create the viewer and initialize
- * it.
- */
- public void createPartControl(Composite parent)
- {
- Composite composite = new Composite(parent, SWT.NONE);
- GridLayout gridLayout = new GridLayout();
- gridLayout.marginHeight = 2;
- gridLayout.marginWidth = 2;
- gridLayout.horizontalSpacing = 0;
- gridLayout.verticalSpacing = 2;
- composite.setLayout(gridLayout);
-
- createTreeViewer(composite);
- _serversRootNode = new TreeObject(NAVIGATION_ROOT, "ROOT");
-
- _treeViewer.setInput(_serversRootNode);
- // set viewer as selection event provider for MBeanView
- getSite().setSelectionProvider(_treeViewer);
-
- // Start worker thread to refresh tree for added or removed objects
- (new Thread(new Worker())).start();
-
- createConfigFile();
- _preferences = new PreferenceStore(INI_FILENAME);
-
- try
- {
- _preferences.load();
- }
- catch (IOException ex)
- {
- System.out.println(ex);
- }
-
- // load the list of servers already added from file
- List<String> serversList = getServerListFromFile();
- if (serversList != null)
- {
- for (String serverAddress : serversList)
- {
- String[] server = serverAddress.split(":");
- ManagedServer managedServer = new ManagedServer(server[0], Integer.parseInt(server[1]), "org.apache.qpid");
- TreeObject serverNode = new TreeObject(serverAddress, NODE_TYPE_SERVER);
- serverNode.setManagedObject(managedServer);
- _serversRootNode.addChild(serverNode);
- }
- }
-
- _treeViewer.refresh();
-
- }
-
- /**
- * Passing the focus request to the viewer's control.
- */
- public void setFocus()
- { }
-
- public void refresh()
- {
- _treeViewer.refresh();
- }
-
- /**
- * Content provider class for the tree viewer
- */
- private static class ContentProviderImpl implements ITreeContentProvider
- {
- public Object[] getElements(Object parent)
- {
- return getChildren(parent);
- }
-
- public Object[] getChildren(final Object parentElement)
- {
- final TreeObject node = (TreeObject) parentElement;
-
- return node.getChildren().toArray(new TreeObject[0]);
- }
-
- public Object getParent(final Object element)
- {
- final TreeObject node = (TreeObject) element;
-
- return node.getParent();
- }
-
- public boolean hasChildren(final Object element)
- {
- final TreeObject node = (TreeObject) element;
-
- return !node.getChildren().isEmpty();
- }
-
- public void inputChanged(final Viewer viewer, final Object oldInput, final Object newInput)
- {
- // Do nothing
- }
-
- public void dispose()
- {
- // Do nothing
- }
- }
-
- /**
- * Label provider class for the tree viewer
- */
- private class LabelProviderImpl extends LabelProvider implements IFontProvider
- {
- public Image getImage(Object element)
- {
- TreeObject node = (TreeObject) element;
- if (node.getType().equals(NOTIFICATIONS))
- {
- return ApplicationRegistry.getImage(NOTIFICATION_IMAGE);
- }
- else if (!node.getType().equals(MBEAN))
- {
- if (_treeViewer.getExpandedState(node))
- {
- return ApplicationRegistry.getImage(OPEN_FOLDER_IMAGE);
- }
- else
- {
- return ApplicationRegistry.getImage(CLOSED_FOLDER_IMAGE);
- }
-
- }
- else
- {
- ManagedObject obj = node.getManagedObject();
- if(obj instanceof ManagedBean)
- {
- ManagedBean mbean = (ManagedBean) obj;
- String mbeanType = mbean.getType();
-
- if(mbeanType.equals(LoggingManagement.TYPE))
- {
- return ApplicationRegistry.getImage(LOGGING_MANAGEMENT_IMAGE);
- }
- else if(mbeanType.equals(UserManagement.TYPE))
- {
- return ApplicationRegistry.getImage(USER_MANAGEMENT_IMAGE);
- }
- else if(mbeanType.equals(ConfigurationManagement.TYPE))
- {
- return ApplicationRegistry.getImage(CONFIGURATION_MANAGEMENT_IMAGE);
- }
- else if(mbeanType.equals(ServerInformation.TYPE))
- {
- return ApplicationRegistry.getImage(SERVER_INFO_IMAGE);
- }
- else if(mbeanType.equals("VirtualHost.VirtualHostManager"))
- {
- return ApplicationRegistry.getImage(VHOST_MANAGER_IMAGE);
- }
- else
- {
- return ApplicationRegistry.getImage(MBEAN_IMAGE);
- }
-
- }
- else
- {
- return ApplicationRegistry.getImage(MBEAN_IMAGE);
- }
- }
- }
-
- public String getText(Object element)
- {
- TreeObject node = (TreeObject) element;
- if (node.getType().equals(NODE_TYPE_MBEANTYPE))
- {
- return node.getName() + "s";
- }
- else
- {
- return node.getName();
- }
- }
-
- public Font getFont(Object element)
- {
- TreeObject node = (TreeObject) element;
- if (node.getType().equals(NODE_TYPE_SERVER))
- {
- if (node.getChildren().isEmpty())
- {
- return ApplicationRegistry.getFont(FONT_NORMAL);
- }
- else
- {
- return ApplicationRegistry.getFont(FONT_BOLD);
- }
- }
-
- return ApplicationRegistry.getFont(FONT_NORMAL);
- }
- } // End of LabelProviderImpl
-
- private static class ViewerSorterImpl extends ViewerSorter
- {
- public int category(Object element)
- {
- TreeObject node = (TreeObject) element;
- if (node.getType().equals(MBEAN))
- {
- return 1;
- }
- if (node.getType().equals(NOTIFICATIONS))
- {
- return 2;
- }
- return 3;
- }
- }
-
- /**
- * Worker thread, which keeps looking for new ManagedObjects to be added and
- * unregistered objects to be removed from the tree.
- * @author Bhupendra Bhardwaj
- */
- private class Worker implements Runnable
- {
- public void run()
- {
- while (true)
- {
- if (!_managedServerMap.isEmpty())
- {
- refreshRemovedObjects();
- refreshClosedServerConnections();
- }
-
- try
- {
- Thread.sleep(2000);
- }
- catch (InterruptedException ex)
- {
- //ignore
- }
-
- } // end of while loop
- } // end of run method.
- } // end of Worker class
-
- /**
- * Adds the mbean to the navigation tree
- * @param mbean mbean to add to the tree
- */
- public void addManagedBean(ManagedBean mbean)
- {
- TreeObject treeServerObject = _managedServerMap.get(mbean.getServer());
- addManagedBean(treeServerObject, mbean);
- _treeViewer.refresh();
- }
-
- private void refreshRemovedObjects()
- {
- for (ManagedServer server : _managedServerMap.keySet())
- {
- final ServerRegistry serverRegistry = ApplicationRegistry.getServerRegistry(server);
- if (serverRegistry == null) // server connection is closed
- {
- continue;
- }
-
- final List<ManagedBean> removalList = serverRegistry.getObjectsToBeRemoved();
- if (removalList != null)
- {
- Display display = getSite().getShell().getDisplay();
- display.syncExec(new Runnable()
- {
- public void run()
- {
- IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- final MBeanView view = (MBeanView)window.getActivePage().findView(MBeanView.ID);
-
- for (ManagedBean mbean : removalList)
- {
- TreeObject treeServerObject = _managedServerMap.get(mbean.getServer());
-
- if(view != null)
- {
- //notify the MBeanView in case the unregistered mbean is being viewed
- view.mbeanUnregistered(mbean);
- }
-
- removeManagedObject(treeServerObject, mbean, false);
- }
-
- _treeViewer.refresh();
- }
- });
- }
- }
- }
-
- /**
- * Gets the list of closed server connection from the ApplicationRegistry and then removes
- * the closed server nodes from the navigation view
- */
- private void refreshClosedServerConnections()
- {
- final List<ManagedServer> closedServers = ApplicationRegistry.getClosedServers();
- if (closedServers != null)
- {
- Display display = getSite().getShell().getDisplay();
- display.syncExec(new Runnable()
- {
- public void run()
- {
- for (ManagedServer server : closedServers)
- {
- if(server == null)
- {
- continue;
- }
-
- TreeObject node = _managedServerMap.get(server);
- if(node ==null)
- {
- continue;
- }
-
- removeManagedObject(node);
- _managedServerMap.remove(server);
- ApplicationRegistry.removeServer(server);
- }
-
- _treeViewer.refresh();
- }
- });
- }
- }
-
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/NotificationsTabControl.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/NotificationsTabControl.java
deleted file mode 100644
index ea49a5c006..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/NotificationsTabControl.java
+++ /dev/null
@@ -1,388 +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.management.ui.views;
-
-import static org.apache.qpid.management.ui.Constants.BUTTON_CLEAR;
-import static org.apache.qpid.management.ui.Constants.DESCRIPTION;
-import static org.apache.qpid.management.ui.Constants.FONT_BOLD;
-import static org.apache.qpid.management.ui.Constants.FONT_BUTTON;
-import static org.apache.qpid.management.ui.Constants.FONT_ITALIC;
-import static org.apache.qpid.management.ui.Constants.SUBSCRIBE_BUTTON;
-import static org.apache.qpid.management.ui.Constants.UNSUBSCRIBE_BUTTON;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.qpid.management.ui.ApplicationRegistry;
-import org.apache.qpid.management.ui.ManagedBean;
-import org.apache.qpid.management.ui.ServerRegistry;
-import org.apache.qpid.management.ui.jmx.MBeanUtility;
-import org.apache.qpid.management.ui.model.NotificationInfoModel;
-import org.apache.qpid.management.ui.model.NotificationObject;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.FormAttachment;
-import org.eclipse.swt.layout.FormData;
-import org.eclipse.swt.layout.FormLayout;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.TabFolder;
-
-/**
- * Creates control composite for Notifications tab
- * @author Bhupendra Bhardwaj
- */
-public class NotificationsTabControl extends VHNotificationsTabControl
-{
- private static final String SELECT_NOTIFICATIONNAME = "Select Notification";
- private static final String SELECT_NOTIFICATIONTYPE = "Select Type";
- private SelectionListener selectionListener;
- private SelectionListener comboListener;
-
- private Combo _notificationNameCombo;
- private Combo _typesCombo;
- private Label _descriptionLabel;
- private Button _subscribeButton;
- private Button _unsubscribeButton;
-
- public NotificationsTabControl(TabFolder tabFolder, ManagedBean mbean)
- {
- super(tabFolder);
- _mbean = mbean;
-
- populateNotificationInfo();
- }
-
- protected void createWidgets()
- {
- selectionListener = new SelectionListenerImpl();
- comboListener = new ComboSelectionListener();
- createNotificationInfoComposite();
- addButtons();
- createTableViewer();
- }
-
- /**
- * Creates composite and populates for displaying Notification Information (name, type, description)
- * and creates buttons for subscribing or unsubscribing for notifications
- */
- private void createNotificationInfoComposite()
- {
- Composite composite = _toolkit.createComposite(_form.getBody(), SWT.NONE);
- composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- composite.setLayout(new FormLayout());
-
- Label label = _toolkit.createLabel(composite, "Select the notification to subscribe or unsubscribe");
- label.setFont(ApplicationRegistry.getFont(FONT_BOLD));
- FormData formData = new FormData();
- formData.top = new FormAttachment(0, 10);
- formData.left = new FormAttachment(0, 10);
- label.setLayoutData(formData);
-
- _notificationNameCombo = new Combo(composite, SWT.READ_ONLY | SWT.DROP_DOWN);
- formData = new FormData();
- formData.top = new FormAttachment(label, 10);
- formData.left = new FormAttachment(0, 10);
- formData.right = new FormAttachment(40);
- _notificationNameCombo.setLayoutData(formData);
- _notificationNameCombo.addSelectionListener(comboListener);
-
- _typesCombo = new Combo(composite, SWT.READ_ONLY | SWT.DROP_DOWN);
- formData = new FormData();
- formData.top = new FormAttachment(label, 10);
- formData.left = new FormAttachment(_notificationNameCombo, 5);
- formData.right = new FormAttachment(65);
- _typesCombo.setLayoutData(formData);
- _typesCombo.addSelectionListener(comboListener);
-
- _subscribeButton = new Button(composite, SWT.PUSH | SWT.CENTER);
- _subscribeButton.setFont(ApplicationRegistry.getFont(FONT_BUTTON));
- _subscribeButton.setText(SUBSCRIBE_BUTTON);
- formData = new FormData();
- formData.top = new FormAttachment(label, 10);
- formData.left = new FormAttachment(65, 10);
- formData.width = 80;
- _subscribeButton.setLayoutData(formData);
- _subscribeButton.addSelectionListener(selectionListener);
-
- _unsubscribeButton = new Button(composite, SWT.PUSH | SWT.CENTER);
- _unsubscribeButton.setFont(ApplicationRegistry.getFont(FONT_BUTTON));
- _unsubscribeButton.setText(UNSUBSCRIBE_BUTTON);
- formData = new FormData();
- formData.top = new FormAttachment(label, 10);
- formData.left = new FormAttachment(_subscribeButton, 10);
- formData.width = 80;
- _unsubscribeButton.setLayoutData(formData);
- _unsubscribeButton.addSelectionListener(selectionListener);
-
- Label fixedLabel = _toolkit.createLabel(composite, "");
- formData = new FormData();
- formData.top = new FormAttachment(_notificationNameCombo, 5);
- formData.left = new FormAttachment(0, 10);
- fixedLabel.setLayoutData(formData);
- fixedLabel.setText(DESCRIPTION + " : ");
- fixedLabel.setFont(ApplicationRegistry.getFont(FONT_BOLD));
-
- _descriptionLabel = _toolkit.createLabel(composite, "");
- formData = new FormData();
- formData.top = new FormAttachment(_notificationNameCombo, 5);
- formData.left = new FormAttachment(fixedLabel, 10);
- formData.right = new FormAttachment(100);
- _descriptionLabel.setLayoutData(formData);
- _descriptionLabel.setText(" ");
- _descriptionLabel.setFont(ApplicationRegistry.getFont(FONT_ITALIC));
- }
-
- /**
- * Creates clear button
- */
- protected void addButtons()
- {
- Composite composite = _toolkit.createComposite(_form.getBody(), SWT.NONE);
- composite.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false));
- composite.setLayout(new GridLayout(2,false));
-
- // Add Clear Button
- _clearButton = _toolkit.createButton(composite, BUTTON_CLEAR, SWT.PUSH | SWT.CENTER);
- _clearButton.setFont(ApplicationRegistry.getFont(FONT_BUTTON));
- GridData gridData = new GridData(SWT.LEAD, SWT.TOP, true, false);
- gridData.widthHint = 80;
- _clearButton.setLayoutData(gridData);
- _clearButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- if (_mbean == null)
- {
- return;
- }
-
- ServerRegistry serverRegistry = ApplicationRegistry.getServerRegistry(MBeanView.getServer());
- IStructuredSelection ss = (IStructuredSelection)_tableViewer.getSelection();
- if(!ss.isEmpty())
- {
- //clear selected Notifications
- serverRegistry.clearNotifications(_mbean, ss.toList());
- }
- else if(_notifications != null)
- {
- //clear all the notifications, if there are any
-
- //check the user is certain of this clear-all operation
- int response = ViewUtility.popupOkCancelConfirmationMessage(
- "Clear Notifications", "Clear all Notifications for this MBean?");
- if(response != SWT.OK)
- {
- return;
- }
-
- synchronized(this)
- {
- List<NotificationObject> newList = new ArrayList<NotificationObject>();
- newList.addAll(_notifications);
- serverRegistry.clearNotifications(_mbean, newList);
- }
- }
-
- refresh();
- }
- });
- //add description
- Label desc = _toolkit.createLabel(composite,"Clears the selected Notifications, or all if none are selected");
- desc.setLayoutData(new GridData(SWT.LEFT,SWT.CENTER, false, false));
- }
-
- @Override
- public void refresh(ManagedBean mbean)
- {
- refresh();
- }
-
- /**
- * Fills the notification information widgets for selected mbean
- */
- private void populateNotificationInfo()
- {
- _notificationNameCombo.removeAll();
- NotificationInfoModel[] items = MBeanUtility.getNotificationInfo(_mbean);
- if (items.length > 1)
- {
- _notificationNameCombo.add(SELECT_NOTIFICATIONNAME);
- }
-
- for (int i = 0; i < items.length; i++)
- {
- _notificationNameCombo.add(items[i].getName());
- _notificationNameCombo.setData(items[i].getName(), items[i]);
- }
- _notificationNameCombo.select(0);
-
- _typesCombo.removeAll();
- _typesCombo.add("Select Type", 0);
- _typesCombo.select(0);
- _typesCombo.setEnabled(false);
-
- populateNotificationType(_notificationNameCombo.getItem(0));
- checkForEnablingButtons();
- }
-
- /**
- * Checks and the enabing/disabling of buttons
- */
- private void checkForEnablingButtons()
- {
- int nameIndex = _notificationNameCombo.getSelectionIndex();
- int itemCount = _notificationNameCombo.getItems().length;
- if ((itemCount > 1) && (nameIndex == 0))
- {
- _subscribeButton.setEnabled(false);
- _unsubscribeButton.setEnabled(false);
- _descriptionLabel.setText("");
- return;
- }
-
- int typeIndex = _typesCombo.getSelectionIndex();
- itemCount = _typesCombo.getItems().length;
- if ((itemCount > 1) && (typeIndex == 0))
- {
- _subscribeButton.setEnabled(false);
- _unsubscribeButton.setEnabled(false);
- return;
- }
-
- String type = _typesCombo.getItem(typeIndex);
- String name = _notificationNameCombo.getItem(nameIndex);
- ServerRegistry serverRegistry = ApplicationRegistry.getServerRegistry(_mbean);
-
- if (serverRegistry.hasSubscribedForNotifications(_mbean, name, type))
- {
- _subscribeButton.setEnabled(false);
- _unsubscribeButton.setEnabled(true);
- }
- else
- {
- _subscribeButton.setEnabled(true);
- _unsubscribeButton.setEnabled(false);
- }
- }
-
- /**
- * Selection listener for subscribing or unsubscribing the notifications
- */
- private class SelectionListenerImpl extends SelectionAdapter
- {
- public void widgetSelected(SelectionEvent e)
- {
- if (_mbean == null)
- return;
-
- Button source = (Button)e.getSource();
- String type = _typesCombo.getItem(_typesCombo.getSelectionIndex());
- String name = _notificationNameCombo.getItem(_notificationNameCombo.getSelectionIndex());
- if (source == _unsubscribeButton)
- {
- try
- {
- MBeanUtility.removeNotificationListener(_mbean, name, type);
- }
- catch(Exception ex)
- {
- MBeanUtility.handleException(ex);
- }
- }
- else if (source == _subscribeButton)
- {
- try
- {
- MBeanUtility.createNotificationlistener(_mbean, name, type);
- }
- catch(Exception ex)
- {
- MBeanUtility.handleException(ex);
- }
- }
- checkForEnablingButtons();
- }
- }
-
- /**
- * Selection listener class for the Notification Name. The notification type and description will be
- * displayed accordingly
- */
- private class ComboSelectionListener extends SelectionAdapter
- {
- public void widgetSelected(SelectionEvent e)
- {
- if (_mbean == null)
- return;
-
- Combo combo = (Combo)e.getSource();
- if (combo == _notificationNameCombo)
- {
- String selectedItem = combo.getItem(combo.getSelectionIndex());
- populateNotificationType(selectedItem);
- }
- checkForEnablingButtons();
- }
- }
-
- private void populateNotificationType(String notificationName)
- {
- NotificationInfoModel data = (NotificationInfoModel)_notificationNameCombo.getData(notificationName);
- if (data == null)
- {
- _descriptionLabel.setText("");
- _typesCombo.select(0);
- _typesCombo.setEnabled(false);
- return;
- }
- _descriptionLabel.setText(data.getDescription());
- _typesCombo.removeAll();
- _typesCombo.setItems(data.getTypes());
- if (_typesCombo.getItemCount() > 1)
- {
- _typesCombo.add(SELECT_NOTIFICATIONTYPE, 0);
- }
- _typesCombo.select(0);
- _typesCombo.setEnabled(true);
- }
-
- /**
- * Updates the table with new notifications received from mbean server for the selected mbean
- */
- protected void updateTableViewer()
- {
- ServerRegistry serverRegistry = ApplicationRegistry.getServerRegistry(_mbean);
- List<NotificationObject> newList = serverRegistry.getNotifications(_mbean);
- synchronized(this)
- {
- _notifications = newList;
- _tableViewer.setInput(_notifications);
- }
- }
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/NumberVerifyListener.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/NumberVerifyListener.java
deleted file mode 100644
index 1774209dae..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/NumberVerifyListener.java
+++ /dev/null
@@ -1,46 +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.management.ui.views;
-
-import org.eclipse.swt.events.VerifyEvent;
-import org.eclipse.swt.events.VerifyListener;
-
-/**
- * Implementation of VeryfyListener for numeric values
- * @author Bhupendra Bhardwaj
- */
-public class NumberVerifyListener implements VerifyListener
-{
- public void verifyText(VerifyEvent event)
- {
- String string = event.text;
- char [] chars = new char [string.length ()];
- string.getChars (0, chars.length, chars, 0);
- for (int i=0; i<chars.length; i++)
- {
- if (!('0' <= chars [i] && chars [i] <= '9'))
- {
- event.doit = false;
- return;
- }
- }
- }
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/OperationTabControl.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/OperationTabControl.java
deleted file mode 100644
index d0b70f4340..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/OperationTabControl.java
+++ /dev/null
@@ -1,920 +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.management.ui.views;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map.Entry;
-
-import javax.management.openmbean.CompositeData;
-import javax.management.openmbean.TabularDataSupport;
-
-import static org.apache.qpid.management.ui.Constants.*;
-
-import org.apache.qpid.management.ui.ApplicationRegistry;
-import org.apache.qpid.management.ui.ManagedBean;
-import org.apache.qpid.management.ui.jmx.MBeanUtility;
-import org.apache.qpid.management.ui.model.OperationData;
-import org.apache.qpid.management.ui.model.ParameterData;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.ScrolledComposite;
-import org.eclipse.swt.events.KeyAdapter;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.events.KeyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.events.VerifyEvent;
-import org.eclipse.swt.events.VerifyListener;
-import org.eclipse.swt.layout.FormAttachment;
-import org.eclipse.swt.layout.FormData;
-import org.eclipse.swt.layout.FormLayout;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.TabFolder;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.forms.widgets.Form;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-
-
-/**
- * Control class for the MBean operations tab. It creates the required widgets
- * for the selected MBean.
- */
-public class OperationTabControl extends TabControl
-{
- private static final int heightForAParameter = 30;
- private static final int labelWidth = 30;
- private static final int valueWidth = labelWidth + 25;
-
- private FormToolkit _toolkit;
- private Form _form;
- private OperationData _opData;
-
- private SelectionListener operationExecutionListener = new OperationExecutionListener();
- private SelectionListener refreshListener = new RefreshListener();
- private SelectionListener parameterSelectionListener = new ParameterSelectionListener();
- private SelectionListener booleanSelectionListener = new BooleanSelectionListener();
- private VerifyListener verifyListener = new VerifyListenerImpl();
- private KeyListener keyListener = new KeyListenerImpl();
- private KeyListener headerBindingListener = new HeaderBindingKeyListener();
-
- private Composite _headerComposite = null;
- private Composite _paramsComposite = null;
- private Composite _resultsComposite = null;
- private Button _executionButton = null;
-
- // for customized method in header exchange
- private HashMap<Text, Text> headerBindingHashMap = null;
- private String _virtualHostName = null;
-
- public OperationTabControl(TabFolder tabFolder, OperationData opData)
- {
- super(tabFolder);
- _toolkit = new FormToolkit(_tabFolder.getDisplay());
- _form = _toolkit.createForm(_tabFolder);
- _form.getBody().setLayout(new GridLayout());
- _opData = opData;
- createComposites();
- setHeader();
- }
-
- /**
- * Form area is devided in four parts:
- * Header composite - displays operaiton information
- * Patameters composite - displays parameters if there
- * Button - operation execution button
- * Results composite - displays results for operations, which have
- * no parameters but have some return value
- */
- private void createComposites()
- {
- //
- _headerComposite = _toolkit.createComposite(_form.getBody(), SWT.NONE);
- _headerComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
-
- List<ParameterData> params = _opData.getParameters();
- if (params != null && !params.isEmpty())
- {
- _paramsComposite = _toolkit.createComposite(_form.getBody(), SWT.NONE);
- _paramsComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- }
- _executionButton = _toolkit.createButton(_form.getBody(), BUTTON_EXECUTE, SWT.PUSH | SWT.CENTER);
- _executionButton.setFont(ApplicationRegistry.getFont(FONT_BUTTON));
- GridData layoutData = new GridData(SWT.CENTER, SWT.TOP, true, false);
- layoutData.verticalIndent = 20;
- _executionButton.setLayoutData(layoutData);
-
- _resultsComposite = _toolkit.createComposite(_form.getBody(), SWT.NONE);
- layoutData = new GridData(SWT.FILL, SWT.FILL, true, true);
- layoutData.verticalIndent = 20;
- _resultsComposite.setLayoutData(layoutData);
- _resultsComposite.setLayout(new GridLayout());
- }
-
- /**
- * @see TabControl#getControl()
- */
- public Control getControl()
- {
- return _form;
- }
-
- @Override
- public void refresh(ManagedBean mbean)
- {
- _mbean = mbean;
- _virtualHostName = _mbean.getVirtualHostName();
-
- // Setting the form to be invisible. Just in case the mbean server connection
- // is done and it takes time in getting the response, then the ui should be blank
- // instead of having half the widgets displayed.
- _form.setVisible(false);
-
- ViewUtility.disposeChildren(_paramsComposite);
- createParameterWidgets();
-
- // Set button text and add appropriate listener to button.
- // If there are no parameters and it is info operation, then operation gets executed
- // and result is displayed
- List<ParameterData> params = _opData.getParameters();
- if (params != null && !params.isEmpty())
- {
- setButton(BUTTON_EXECUTE);
- }
- else if (_opData.getImpact() == OPERATION_IMPACT_ACTION)
- {
- setButton(BUTTON_EXECUTE);
- }
- else if (_opData.getImpact() == OPERATION_IMPACT_INFO)
- {
- setButton(BUTTON_REFRESH);
- executeAndShowResults();
- }
-
- _form.setVisible(true);
- layout();
- }
-
- public void layout()
- {
- _form.layout(true);
- _form.getBody().layout(true, true);
- }
-
- /**
- * populates the header composite, containing the operation name and description.
- */
- private void setHeader()
- {
- _form.setText(ViewUtility.getDisplayText(_opData.getName()));
- _headerComposite.setLayout(new GridLayout(2, false));
- //operation description
- Label label = _toolkit.createLabel(_headerComposite, DESCRIPTION + " : ");
- label.setFont(ApplicationRegistry.getFont(FONT_BOLD));
- label.setLayoutData(new GridData(SWT.LEAD, SWT.TOP, false, false));
-
- label = _toolkit.createLabel(_headerComposite, _opData.getDescription());
- label.setFont(ApplicationRegistry.getFont(FONT_NORMAL));
- label.setLayoutData(new GridData(SWT.LEAD, SWT.TOP, true, false));
-
- _headerComposite.layout();
- }
-
- /**
- * Creates the widgets for operation parameters if there are any
- */
- private void createParameterWidgets()
- {
- List<ParameterData> params = _opData.getParameters();
- if (params == null || params.isEmpty())
- {
- return;
- }
-
- // Customised parameter widgets
- if (_mbean.isExchange() &&
- HEADERS_EXCHANGE.equals(_mbean.getProperty(EXCHANGE_TYPE)) &&
- _opData.getName().equalsIgnoreCase(OPERATION_CREATE_BINDING))
- {
- customCreateNewBinding();
- return;
- }
- // end of Customised parameter widgets
-
- _paramsComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- _paramsComposite.setLayout(new FormLayout());
- int parameterPositionOffset = 0;
- for (ParameterData param : params)
- {
- boolean valueInCombo = false;
- Label label = _toolkit.createLabel(_paramsComposite, ViewUtility.getDisplayText(param.getName()));
- FormData formData = new FormData();
- if (params.indexOf(param) == 0)
- {
- parameterPositionOffset = 0;
- }
- else
- {
- parameterPositionOffset += heightForAParameter;
- }
- formData.top = new FormAttachment(0, parameterPositionOffset + 2);
- formData.right = new FormAttachment(labelWidth);
- label.setLayoutData(formData);
- label.setToolTipText(param.getDescription());
-
- formData = new FormData();
- formData.top = new FormAttachment(0, parameterPositionOffset);
- formData.left = new FormAttachment(label, 5);
- formData.right = new FormAttachment(valueWidth);
- // this will contain the list of items, if the list is to be made available to choose from
- // e.g. the list of exchanges
- String[] items = null;
- if (param.getName().equals(QUEUE))
- {
- List<String> qList = ApplicationRegistry.getServerRegistry(_mbean).getQueueNames(_virtualHostName);
- // Customization for AMQQueueMBean method OPERATION_MOVE_MESSAGES
- if (_opData.getName().equals(OPERATION_MOVE_MESSAGES))
- {
- qList.remove(_mbean.getName());
- }
- // End of Customization
- items = qList.toArray(new String[0]);
- }
- else if (param.getName().equals(EXCHANGE))
- {
- items = ApplicationRegistry.getServerRegistry(_mbean).getExchangeNames(_virtualHostName);
- }
- else if (param.getName().equals(EXCHANGE_TYPE))
- {
- items = DEFAULT_EXCHANGE_TYPE_VALUES.toArray(new String[DEFAULT_EXCHANGE_TYPE_VALUES.size()]);
- }
- else if (isUserListParameter(param))
- {
- List<String> list = ApplicationRegistry.getServerRegistry(_mbean).getUsernames();
- if (list != null && !list.isEmpty())
- {
- items = list.toArray(new String[0]);
- }
- }
-
- if (items != null)
- {
- org.eclipse.swt.widgets.List _list = new org.eclipse.swt.widgets.List(_paramsComposite, SWT.BORDER | SWT.V_SCROLL);
- int listSize = _form.getClientArea().height * 2 / 3;
- int itemsHeight = items.length * (_list.getItemHeight() + 2);
- // Set a min height for the list widget (set it to min 4 items)
- if (items.length < 4)
- {
- itemsHeight = 4 * (_list.getItemHeight() + 2);
- }
-
- listSize = (listSize > itemsHeight) ? itemsHeight : listSize;
- parameterPositionOffset = parameterPositionOffset + listSize;
- formData.bottom = new FormAttachment(0, parameterPositionOffset);
- _list.setLayoutData(formData);
- _list.setData(param);
- _list.setItems(items);
- _list.addSelectionListener(parameterSelectionListener);
- valueInCombo = true;
- }
- else if (param.isBoolean())
- {
- Button booleanButton = _toolkit.createButton(_paramsComposite, "", SWT.CHECK);
- booleanButton.setLayoutData(formData);
- booleanButton.setData(param);
- booleanButton.addSelectionListener(booleanSelectionListener);
- valueInCombo = true;
- }
- else
- {
- int style = SWT.NONE;
- if (PASSWORD.equalsIgnoreCase(param.getName()))
- {
- style = SWT.PASSWORD;
- }
- Text text = _toolkit.createText(_paramsComposite, "", style);
- formData = new FormData();
- formData.top = new FormAttachment(0, parameterPositionOffset);
- formData.left = new FormAttachment(label, 5);
- formData.right = new FormAttachment(valueWidth);
- text.setLayoutData(formData);
- // Listener to assign value to the parameter
- text.addKeyListener(keyListener);
- // Listener to verify if the entered key is valid
- text.addVerifyListener(verifyListener);
- text.setData(param);
- }
-
- // display the parameter data type next to the text field
- if (valueInCombo)
- {
- label = _toolkit.createLabel(_paramsComposite, "");
- }
- else if (PASSWORD.equalsIgnoreCase(param.getName()))
- {
- label = _toolkit.createLabel(_paramsComposite, "(String)");
- }
- else
- {
- String str = param.getType();
-
- if (param.getType().lastIndexOf(".") != -1)
- str = param.getType().substring(1 + param.getType().lastIndexOf("."));
-
- label = _toolkit.createLabel(_paramsComposite, "(" + str + ")");
- }
- formData = new FormData();
- formData.top = new FormAttachment(0, parameterPositionOffset);
- formData.left = new FormAttachment(valueWidth, 5);
- label.setLayoutData(formData);
- }
- }
-
- private boolean isUserListParameter(ParameterData param)
- {
- if (_mbean.isAdmin() && param.getName().equals(OPERATION_PARAM_USERNAME)
- && !_opData.getName().equals(OPERATION_CREATEUSER))
- {
- return true;
- }
-
- return false;
- }
-
- /**
- * Creates customized dispaly for a method "CreateNewBinding" for Headers exchange
- *
- */
- private void customCreateNewBinding()
- {
- headerBindingHashMap = new HashMap<Text, Text>();
-
- _paramsComposite.setLayout(new GridLayout());
- _paramsComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true));
- final ScrolledComposite scrolledComposite = new ScrolledComposite(_paramsComposite, SWT.BORDER | SWT.V_SCROLL);
- scrolledComposite.setExpandHorizontal(true);
- scrolledComposite.setExpandVertical(true);
- GridData layoutData = new GridData(SWT.FILL, SWT.TOP, true, true);
- scrolledComposite.setLayoutData(layoutData);
- scrolledComposite.setLayout(new GridLayout());
-
- final Composite composite = _toolkit.createComposite(scrolledComposite, SWT.NONE);
- scrolledComposite.setContent(composite);
- layoutData = new GridData(SWT.FILL, SWT.FILL, true, true);
- layoutData.verticalIndent = 20;
- composite.setLayoutData(layoutData);
- composite.setLayout(new FormLayout());
-
- List<ParameterData> params = _opData.getParameters();
- ParameterData param = params.get(0);
- // Queue selection widget
- Label label = _toolkit.createLabel(composite, ViewUtility.getDisplayText(param.getName()));
- FormData formData = new FormData();
- formData.top = new FormAttachment(0, 2);
- formData.right = new FormAttachment(labelWidth);
- label.setLayoutData(formData);
- label.setToolTipText(param.getDescription());
-
- formData = new FormData();
- formData.top = new FormAttachment(0);
- formData.left = new FormAttachment(label, 5);
- formData.right = new FormAttachment(valueWidth);
-
- Combo combo = new Combo(composite, SWT.READ_ONLY | SWT.DROP_DOWN);
- List<String> qList = ApplicationRegistry.getServerRegistry(_mbean).getQueueNames(_virtualHostName);
- combo.setItems(qList.toArray(new String[0]));
- combo.add("Select Queue", 0);
- combo.select(0);
- combo.setLayoutData(formData);
- combo.setData(param);
- combo.addSelectionListener(parameterSelectionListener);
-
- // Binding creation widgets
- createARowForCreatingHeadersBinding(composite, 1);
- createARowForCreatingHeadersBinding(composite, 2);
- createARowForCreatingHeadersBinding(composite, 3);
- createARowForCreatingHeadersBinding(composite, 4);
- createARowForCreatingHeadersBinding(composite, 5);
- createARowForCreatingHeadersBinding(composite, 6);
- createARowForCreatingHeadersBinding(composite, 7);
- createARowForCreatingHeadersBinding(composite, 8);
-
- final Button addMoreButton = _toolkit.createButton(composite, "Add More", SWT.PUSH);
- formData = new FormData();
- formData.top = new FormAttachment(0, heightForAParameter);
- formData.left = new FormAttachment(70, 5);
- addMoreButton.setLayoutData(formData);
- addMoreButton.setData("rowCount", 8);
- addMoreButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- int count = Integer.parseInt(addMoreButton.getData("rowCount").toString());
- createARowForCreatingHeadersBinding(composite, ++count);
- addMoreButton.setData("rowCount", count);
- scrolledComposite.setMinSize(composite.computeSize(SWT.DEFAULT, SWT.DEFAULT));
- composite.layout();
- _form.layout();
- }
- });
-
- scrolledComposite.setMinSize(composite.computeSize(SWT.DEFAULT, SWT.DEFAULT));
- composite.layout();
- }
-
- /**
- * Adds a row for adding a binding for Headers Exchange. Used by the method, which creates the customized
- * layout and widgest for Header's exchange method createNewBinding.
- * @param parent composite
- * @param rowCount - row number
- */
- private void createARowForCreatingHeadersBinding(Composite parent, int rowCount)
- {
- Label key = _toolkit.createLabel(parent, "Name");
- FormData formData = new FormData();
- formData.top = new FormAttachment(0, rowCount * heightForAParameter + 2);
- formData.right = new FormAttachment(15);
- key.setLayoutData(formData);
-
- Text keyText = _toolkit.createText(parent, "", SWT.NONE);
- formData = new FormData();
- formData.top = new FormAttachment(0, rowCount * heightForAParameter);
- formData.left = new FormAttachment(key, 5);
- formData.right = new FormAttachment(40);
- keyText.setLayoutData(formData);
- keyText.addKeyListener(headerBindingListener);
-
- Label value = _toolkit.createLabel(parent, "Value");
- formData = new FormData();
- formData.top = new FormAttachment(0, rowCount * heightForAParameter + 2);
- formData.right = new FormAttachment(45);
- value.setLayoutData(formData);
-
- Text valueText = _toolkit.createText(parent, "", SWT.NONE);
- formData = new FormData();
- formData.top = new FormAttachment(0, rowCount * heightForAParameter);
- formData.left = new FormAttachment(value, 5);
- formData.right = new FormAttachment(70);
- valueText.setLayoutData(formData);
- valueText.addKeyListener(headerBindingListener);
-
- // Add these to the map, to retrieve the values while setting the parameter value
- headerBindingHashMap.put(keyText, valueText);
- }
-
- /**
- * Sets text and listener for the operation execution button
- * @param text
- */
- private void setButton(String text)
- {
- _executionButton.setText(text);
- _executionButton.removeSelectionListener(refreshListener);
- _executionButton.removeSelectionListener(operationExecutionListener);
-
- if (BUTTON_EXECUTE.equals(text))
- {
- _executionButton.addSelectionListener(operationExecutionListener);
- }
- else
- {
- _executionButton.addSelectionListener(refreshListener);
- }
- }
-
- /**
- * displays the operation result in a pop-up window
- * @param result
- */
- private void populateResults(Object result)
- {
- Display display = Display.getCurrent();
- int width = 610;
- int height = 400;
- Shell shell = ViewUtility.createPopupShell(RESULT, width, height);
- shell.setImage(ApplicationRegistry.getImage(CONSOLE_IMAGE));
- ViewUtility.populateCompositeWithData(_toolkit, shell, result);
-
- shell.open();
- while (!shell.isDisposed()) {
- if (!display.readAndDispatch()) {
- display.sleep();
- }
- }
- shell.dispose();
- }
-
- /**
- * Clears the parameter values of the operation
- */
- private void clearParameters()
- {
- List<ParameterData> params = _opData.getParameters();
- if (params != null && !params.isEmpty())
- {
- for (ParameterData param : params)
- {
- param.setDefaultValue();
- }
- }
- }
-
- /**
- * Clears the values entered by the user from parameter value widgets
- * @param control
- */
- private void clearParameterValues(Composite control)
- {
- if (control == null || (control.isDisposed()))
- return;
-
- Control[] controls = control.getChildren();
- if (controls == null || controls.length == 0)
- return;
-
- for (int i = 0; i < controls.length; i++)
- {
- if (controls[i] instanceof Combo)
- ((Combo)controls[i]).select(0);
- if (controls[i] instanceof org.eclipse.swt.widgets.List)
- ((org.eclipse.swt.widgets.List)controls[i]).deselectAll();
- else if (controls[i] instanceof Text)
- ((Text)controls[i]).setText("");
- else if (controls[i] instanceof Button)
- ((Button)controls[i]).setSelection(false);
- else if (controls[i] instanceof Composite)
- clearParameterValues((Composite)controls[i]);
- }
- }
-
- /**
- * Listener class for operation execution events
- */
- private class OperationExecutionListener extends SelectionAdapter
- {
- public void widgetSelected(SelectionEvent e)
- {
- List<ParameterData> params = _opData.getParameters();
- if (params != null && !params.isEmpty())
- {
- for (ParameterData param : params)
- {
- if (param.getValue() == null || param.getValue().toString().length() == 0)
- {
- // Customized check, because for this parameter null is allowed
- if (param.getName().equals(ATTRIBUTE_QUEUE_OWNER) &&
- _opData.getName().equals(OPERATION_CREATE_QUEUE))
- {
- continue;
- }
- // End of custom code
-
- ViewUtility.popupInfoMessage(_form.getText(), "Please select the " + ViewUtility.getDisplayText(param.getName()));
- return;
- }
-
- //Custom handling for the PASSWORD field
- if (param.getName().equalsIgnoreCase(PASSWORD))
- {
- //Convert the String value to a character array if that is what is required.
- if (param.getType().equals("[C"))
- {
- // Retreive the mBean type and version.
- // If we have a version 1 UserManagement class mbean then it expects the password
- // to be sent as the hashed version.
- if (_mbean.getType().equals("UserManagement") && _mbean.getVersion() == 1)
- {
- try
- {
- param.setValue(ViewUtility.getHash((String) param.getValue()));
- }
- catch (Exception hashException)
- {
- ViewUtility.popupErrorMessage(_form.getText(),
- "Unable to calculate hash for Password:"
- + hashException.getMessage());
- return;
- }
- }
- else
- {
- param.setValue(((String) param.getValue()).toCharArray());
- }
- }
- }
- // end of customization
-
- }
- }
-
- if (_opData.getImpact() == OPERATION_IMPACT_ACTION)
- {
- String bean = _mbean.getName() == null ? _mbean.getType() : _mbean.getName();
- int response = ViewUtility.popupConfirmationMessage(bean, "Do you want to " + _form.getText()+ " ?");
- if (response == SWT.YES)
- {
- executeAndShowResults();
- }
- }
- else
- {
- executeAndShowResults();
- }
-
- if (_mbean.isAdmin() && _opData.getName().equals(OPERATION_DELETEUSER))
- {
- refresh(_mbean);
- }
- else
- {
- clearParameters();
- clearParameterValues(_paramsComposite);
- }
- }
- }
-
- // Listener for the "Refresh" execution button
- private class RefreshListener extends SelectionAdapter
- {
- public void widgetSelected(SelectionEvent e)
- {
- executeAndShowResults();
- }
- }
-
- /**
- * Executres the operation, gets the result from server and displays to the user
- */
- private void executeAndShowResults()
- {
- Object result = null;
- try
- {
- result = MBeanUtility.execute(_mbean, _opData);
- }
- catch(Exception ex)
- {
- MBeanUtility.handleException(_mbean, ex);
- return;
- }
-
- // Custom code for Admin mbean operation
- /* These custome codes here are to make the GUI look more user friendly.
- * Here we are adding the users to a list, which will be used to list username to be selected on
- * pages like "delete user", "set password" instead of typing the username
- */
- if (_mbean.isAdmin())
- {
- if (_opData.getName().equals(OPERATION_VIEWUSERS))
- {
- ApplicationRegistry.getServerRegistry(_mbean).setUserList(extractUserList(result));
- }
- else if (_opData.getName().equals(OPERATION_DELETEUSER))
- {
- List<String> list = ApplicationRegistry.getServerRegistry(_mbean).getUsernames();
- Object userName = _opData.getParameterValue(OPERATION_PARAM_USERNAME);
- if ((list != null) && !list.isEmpty() && (userName != null))
- {
- list.remove(userName);
- ApplicationRegistry.getServerRegistry(_mbean).setUserList(list);
- }
- }
- else if (_opData.getName().equals(OPERATION_CREATEUSER))
- {
- List<String> list = ApplicationRegistry.getServerRegistry(_mbean).getUsernames();
- Object userName = _opData.getParameterValue(OPERATION_PARAM_USERNAME);
- if ((list != null) && !list.isEmpty() && (userName != null))
- {
- list.add(userName.toString());
- ApplicationRegistry.getServerRegistry(_mbean).setUserList(list);
- }
- }
- }
- // end of custom code
-
- // Some mbeans have only "type" and no "name".
- String title = _mbean.getType();
- if (_mbean.getName() != null && _mbean.getName().length() != 0)
- {
- title = _mbean.getName();
- }
-
- if (_opData.isReturnTypeVoid())
- {
- ViewUtility.popupInfoMessage(title, OPERATION_SUCCESSFUL);
- }
- else if (_opData.isReturnTypeBoolean())
- {
- boolean success = Boolean.parseBoolean(result.toString());
- String message = success ? OPERATION_SUCCESSFUL : OPERATION_UNSUCCESSFUL;
- if(success)
- {
- ViewUtility.popupInfoMessage(title, message);
- }
- else
- {
- ViewUtility.popupErrorMessage(title, message);
- }
- }
- else if (_opData.getParameters() != null && !_opData.getParameters().isEmpty())
- {
- populateResults(result);
- }
- else
- {
- ViewUtility.disposeChildren(_resultsComposite);
- ViewUtility.populateCompositeWithData(_toolkit, _resultsComposite, result);
- _resultsComposite.layout();
- _form.layout();
- }
-
- }
-
- private List<String> extractUserList(Object result)
- {
- if (!(result instanceof TabularDataSupport))
- {
- return null;
- }
-
- TabularDataSupport tabularData = (TabularDataSupport)result;
- Collection<Object> records = tabularData.values();
- List<String> list = new ArrayList<String>();
- for (Object o : records)
- {
- CompositeData data = (CompositeData) o;
- if (data.containsKey(USERNAME))
- {
- list.add(data.get(USERNAME).toString());
- }
- }
-
- return list;
- }
-
- /**
- * Listener class for the operation parameters widget
- */
- private static class ParameterSelectionListener extends SelectionAdapter
- {
- public void widgetSelected(SelectionEvent e)
- {
- ParameterData parameter = (ParameterData)e.widget.getData();
- parameter.setValue(null);
- if (e.widget instanceof Combo)
- {
- Combo combo = (Combo)e.widget;
- if (combo.getSelectionIndex() > 0)
- {
- String item = combo.getItem(combo.getSelectionIndex());
- parameter.setValueFromString(item);
- }
- }
- else if (e.widget instanceof org.eclipse.swt.widgets.List)
- {
- org.eclipse.swt.widgets.List list = (org.eclipse.swt.widgets.List)e.widget;
- String[] selectedItems = list.getSelection();
- if (selectedItems.length > 0)
- {
- parameter.setValueFromString(selectedItems[0]);
- }
- }
- }
- }
-
- /**
- * Listener class for boolean parameter widgets
- */
- private static class BooleanSelectionListener extends SelectionAdapter
- {
- public void widgetSelected(SelectionEvent e)
- {
- ParameterData parameter = (ParameterData)(e.widget.getData());
- if (e.widget instanceof Button)
- {
- Button button = (Button)e.widget;
- parameter.setValue(button.getSelection());
- }
- else if (e.widget instanceof Combo)
- {
- Combo combo = (Combo)e.widget;
- String item = combo.getItem(combo.getSelectionIndex());
- parameter.setValueFromString(item);
- }
- }
- }
-
- /**
- * Listener class for the operation parameter value widget (Text field)
- */
- private static class KeyListenerImpl extends KeyAdapter
- {
- public void keyReleased(KeyEvent e)
- {
- if (!(e.widget instanceof Text))
- return;
-
- Text text = (Text)e.widget;
- // Get the parameters widget and assign the text to the parameter
- String strValue = text.getText();
- ParameterData parameter = (ParameterData)text.getData();
- try
- {
- parameter.setValueFromString(strValue);
- }
- catch(Exception ex)
- {
- // Exception occured in setting parameter value.
- // ignore it. The value will not be assigned to the parameter
- }
- }
- }
-
- /**
- * Listener class for HeaderExchange's new binding widgets. Used when the new bindings are
- * being created for Header's Exchange
- */
- private class HeaderBindingKeyListener extends KeyAdapter
- {
- public void keyReleased(KeyEvent e)
- {
- ParameterData param = _opData.getParameters().get(1);
- StringBuffer paramValue = new StringBuffer();
- for (Entry<Text, Text> entry : headerBindingHashMap.entrySet())
- {
-
- Text nameText = entry.getKey();
- String name = nameText.getText();
- Text valueText = entry.getValue();
- String value = valueText.getText();
- if ((name != null) && (name.length() != 0) && (value != null) && (value.length() != 0))
- {
- if (paramValue.length() != 0)
- {
- paramValue.append(",");
- }
- paramValue.append(name + "=" + value);
- }
- }
-
- param.setValue(paramValue.toString());
- }
- }
-
- /**
- * Listener class for verifying the user input with parameter type
- */
- private static class VerifyListenerImpl implements VerifyListener
- {
- public void verifyText(VerifyEvent event)
- {
- ParameterData parameter = (ParameterData)event.widget.getData();
- String text = event.text;
- char [] chars = new char [text.length ()];
- text.getChars(0, chars.length, chars, 0);
- String type = parameter.getType();
- if (type.equals("int") || type.equals("java.lang.Integer") ||
- type.equals("long") || type.equals("java.lang.Long"))
- {
- for (int i=0; i<chars.length; i++)
- {
- if (!('0' <= chars [i] && chars [i] <= '9'))
- {
- event.doit = false;
- return;
- }
- }
-
- }
- }
- }
-
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/TabControl.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/TabControl.java
deleted file mode 100644
index 156543d603..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/TabControl.java
+++ /dev/null
@@ -1,103 +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.management.ui.views;
-
-import java.util.ArrayList;
-
-import org.apache.qpid.management.ui.ManagedBean;
-import org.apache.qpid.management.ui.model.OperationData;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.TabFolder;
-
-/**
- * Abstract class for all the control classes of tabs.
- * @author Bhupendra Bhardwaj
- */
-public abstract class TabControl
-{
- public static final String CONTROLLER = "controller";
- protected ManagedBean _mbean = null;
- protected TabFolder _tabFolder = null;
-
- private static java.util.List<String> simpleTypes = new ArrayList<String>();
-
- static
- {
- simpleTypes.add("java.math.BigDecimal");
- simpleTypes.add("java.math.BigInteger");
- simpleTypes.add("java.lang.Boolean");
- simpleTypes.add("java.lang.Byte");
- simpleTypes.add("java.lang.Character");
- simpleTypes.add("java.util.Date");
- simpleTypes.add("java.lang.Double");
- simpleTypes.add("java.lang.Float");
- simpleTypes.add("java.lang.Integer");
- simpleTypes.add("java.lang.Long");
- simpleTypes.add("javax.management.ObjectName");
- simpleTypes.add("java.lang.Short");
- simpleTypes.add("java.lang.String");
- simpleTypes.add("boolean");
- }
-
- public TabControl(TabFolder tabFolder)
- {
- _tabFolder = tabFolder;
- }
-
- /**
- * @return controller composite for the tab
- */
- public Control getControl()
- {
- return null;
- }
-
- public void refresh(ManagedBean mbean)
- {
- if (mbean == null)
- {
- refresh();
- }
- }
-
- public void refresh()
- {
-
- }
-
- public void refresh(ManagedBean mbean, OperationData opData)
- {
-
- }
-
- /**
- * Sets focus on a widget
- */
- public void setFocus()
- {
-
- }
-
- public boolean isSimpleType(Object data)
- {
- return simpleTypes.contains(data.getClass().getName());
- }
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/TreeObject.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/TreeObject.java
deleted file mode 100644
index 9545ed9876..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/TreeObject.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.management.ui.views;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.qpid.management.ui.Constants;
-import org.apache.qpid.management.ui.ManagedBean;
-import org.apache.qpid.management.ui.ManagedObject;
-
-public class TreeObject
-{
- private String _name;
- private String _type;
- private String _virtualHost;
- private TreeObject _parent;
- private List<TreeObject> _children = new ArrayList<TreeObject>();
- private ManagedObject _object;
-
- public TreeObject(String name, String type)
- {
- this._name = name;
- this._type = type;
- }
-
- public TreeObject(ManagedObject obj)
- {
- _name = obj.getName();
- if (_name == null && (obj instanceof ManagedBean))
- {
- String[] types = ((ManagedBean)obj).getType().split("\\.");
- _name = types[types.length - 1];
- }
- this._type = Constants.MBEAN;
- this._object = obj;
- }
-
- public void addChild(TreeObject child)
- {
- _children.add(child);
- }
-
- public void addChildren(List<TreeObject> subList)
- {
- _children.addAll(subList);
- }
-
- public List<TreeObject> getChildren()
- {
- return _children;
- }
-
- public void setChildren(List<TreeObject> children)
- {
- this._children = children;
- }
-
- public void setName(String value)
- {
- _name = value;
- }
-
- public String getName()
- {
- return _name;
- }
- public String getType()
- {
- return _type;
- }
-
- public String getVirtualHost()
- {
- // To make it work with the broker with no virtual host implementation
- return _virtualHost == null ? Constants.DEFAULT_VH : _virtualHost;
- }
-
- public void setVirtualHost(String vHost)
- {
- _virtualHost = vHost;
- }
-
- public ManagedObject getManagedObject()
- {
- return _object;
- }
-
- public void setManagedObject(ManagedObject obj)
- {
- this._object = obj;
- }
-
- public TreeObject getParent()
- {
- return _parent;
- }
-
- public void setParent(TreeObject parent)
- {
- this._parent = parent;
-
- if (parent != null)
- {
- parent.addChild(this);
- }
- }
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/VHNotificationsTabControl.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/VHNotificationsTabControl.java
deleted file mode 100644
index d23355501f..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/VHNotificationsTabControl.java
+++ /dev/null
@@ -1,484 +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.management.ui.views;
-
-import static org.apache.qpid.management.ui.Constants.BUTTON_CLEAR;
-import static org.apache.qpid.management.ui.Constants.CONSOLE_IMAGE;
-import static org.apache.qpid.management.ui.Constants.FONT_BUTTON;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.qpid.management.ui.ApplicationRegistry;
-import org.apache.qpid.management.ui.ServerRegistry;
-import org.apache.qpid.management.ui.model.NotificationObject;
-import org.eclipse.jface.viewers.DoubleClickEvent;
-import org.eclipse.jface.viewers.IDoubleClickListener;
-import org.eclipse.jface.viewers.ILabelProviderListener;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITableLabelProvider;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.TabFolder;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.TableColumn;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.forms.widgets.Form;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-
-public class VHNotificationsTabControl extends TabControl
-{
- protected FormToolkit _toolkit;
- protected Form _form;
- protected Table _table = null;
- protected TableViewer _tableViewer = null;
-
- protected Thread _worker = null;
- protected boolean _workerRunning = false;
-
- protected List<NotificationObject> _notifications = null;
-
- private static final String COLUMN_OBJ = "Object Name";
- private static final String COLUMN_SEQ = "Sequence No";
- private static final String COLUMN_TIME = "TimeStamp";
- private static final String COLUMN_TYPE = "Type";
- private static final String COLUMN_MSG = "Notification Message";
- private static final String[] TABLE_TITLES = new String [] {
- COLUMN_OBJ,
- COLUMN_SEQ,
- COLUMN_TIME,
- COLUMN_TYPE,
- COLUMN_MSG
- };
-
- protected Button _clearButton = null;
-
- public VHNotificationsTabControl(TabFolder tabFolder)
- {
- super(tabFolder);
- _toolkit = new FormToolkit(_tabFolder.getDisplay());
- _form = _toolkit.createForm(_tabFolder);
- GridLayout gridLayout = new GridLayout();
- gridLayout.marginWidth = 0;
- gridLayout.marginHeight = 0;
- _form.getBody().setLayout(gridLayout);
-
- createWidgets();
- }
-
- protected void createWidgets()
- {
- addButtons();
- createTableViewer();
- }
-
- /**
- * @see TabControl#getControl()
- */
- public Control getControl()
- {
- return _form;
- }
-
- /**
- * Creates clear buttin and refresh button
- */
- protected void addButtons()
- {
- Composite composite = _toolkit.createComposite(_form.getBody(), SWT.NONE);
- composite.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false));
- composite.setLayout(new GridLayout(2,false));
-
- // Add Clear Button
- _clearButton = _toolkit.createButton(composite, BUTTON_CLEAR, SWT.PUSH | SWT.CENTER);
- _clearButton.setFont(ApplicationRegistry.getFont(FONT_BUTTON));
- GridData gridData = new GridData(SWT.LEAD, SWT.TOP, true, false);
- gridData.widthHint = 80;
- _clearButton.setLayoutData(gridData);
- _clearButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- ServerRegistry serverRegistry = ApplicationRegistry.getServerRegistry(MBeanView.getServer());
- IStructuredSelection ss = (IStructuredSelection)_tableViewer.getSelection();
- if(!ss.isEmpty())
- {
- //clear selected Notifications
- serverRegistry.clearNotifications(null, ss.toList());
- }
- else if(_notifications != null)
- {
- //clear all the notifications, if there are any
-
- //check the user is certain of this clear-all operation
- int response = ViewUtility.popupOkCancelConfirmationMessage(
- "Clear Notifications", "Clear all Notifications for this VirtualHost?");
- if(response != SWT.OK)
- {
- return;
- }
-
- synchronized(this)
- {
- serverRegistry.clearNotifications(null, _notifications);
- }
- }
-
- refresh();
- }
- });
- //add description
- Label desc = _toolkit.createLabel(composite,"Clears the selected Notifications, or all if none are selected");
- desc.setLayoutData(new GridData(SWT.LEFT,SWT.CENTER, false, false));
- }
-
- /**
- * Creates table to display notifications
- */
- private void createTable()
- {
- _table = _toolkit.createTable(_form.getBody(), SWT.MULTI | SWT.FULL_SELECTION);
- _table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
-
- TableColumn column = new TableColumn(_table, SWT.NONE);
- column.setText(TABLE_TITLES[0]);
- column.setWidth(100);
-
- column = new TableColumn(_table, SWT.NONE);
- column.setText(TABLE_TITLES[1]);
- column.setWidth(100);
-
- column = new TableColumn(_table, SWT.NONE);
- column.setText(TABLE_TITLES[2]);
- column.setWidth(130);
-
- column = new TableColumn(_table, SWT.NONE);
- column.setText(TABLE_TITLES[3]);
- column.setWidth(100);
-
- column = new TableColumn(_table, SWT.NONE);
- column.setText(TABLE_TITLES[4]);
- column.setWidth(500);
-
- _table.setHeaderVisible(true);
- _table.setLinesVisible(true);
- }
-
- /**
- * Creates JFace viewer for the notifications table
- */
- protected void createTableViewer()
- {
- createTable();
- _tableViewer = new TableViewer(_table);
- _tableViewer.setUseHashlookup(true);
- _tableViewer.setContentProvider(new ContentProviderImpl());
- _tableViewer.setLabelProvider(new LabelProviderImpl());
- _tableViewer.setColumnProperties(TABLE_TITLES);
-
- addTableListeners();
- }
-
- /**
- * Adds listeners to the viewer for displaying notification details
- */
- protected void addTableListeners()
- {
- _tableViewer.addDoubleClickListener(new IDoubleClickListener()
- {
- Display display = null;
- Shell shell = null;
- public void doubleClick(DoubleClickEvent event)
- {
- display = Display.getCurrent();
- shell = new Shell(display, SWT.BORDER | SWT.CLOSE | SWT.MIN | SWT.MAX | SWT.RESIZE);
- shell.setText("Notification");
- shell.setImage(ApplicationRegistry.getImage(CONSOLE_IMAGE));
-
- int x = display.getBounds().width;
- int y = display.getBounds().height;
- shell.setBounds(x/4, y/4, x/2, y/3);
- StructuredSelection selection = (StructuredSelection)event.getSelection();
- createPopupContents((NotificationObject)selection.getFirstElement());
- shell.open();
- while (!shell.isDisposed()) {
- if (!display.readAndDispatch()) {
- display.sleep();
- }
- }
-
- //If you create it, you dispose it.
- shell.dispose();
- }
-
- private void createPopupContents(NotificationObject obj)
- {
- shell.setLayout(new GridLayout());
-
- Composite parent = _toolkit.createComposite(shell, SWT.NONE);
- parent.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- GridLayout layout = new GridLayout(4, true);
- parent.setLayout(layout);
-
- // Object name record
- Label key = _toolkit.createLabel(parent, COLUMN_OBJ, SWT.TRAIL);
- GridData layoutData = new GridData(SWT.TRAIL, SWT.TOP, false, false,1,1);
- key.setLayoutData(layoutData);
- Text value = _toolkit.createText(parent, obj.getSourceName(), SWT.BEGINNING | SWT.BORDER |SWT.READ_ONLY);
- value.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false,3,1));
-
- // Sequence no record
- key = _toolkit.createLabel(parent, COLUMN_SEQ, SWT.TRAIL);
- layoutData = new GridData(SWT.TRAIL, SWT.TOP, false, false,1,1);
- key.setLayoutData(layoutData);
- value = _toolkit.createText(parent, ""+obj.getSequenceNo(), SWT.BEGINNING | SWT.BORDER |SWT.READ_ONLY);
- value.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false,3,1));
-
- // Time row
- key = _toolkit.createLabel(parent, COLUMN_TIME, SWT.TRAIL);
- key.setLayoutData(new GridData(SWT.TRAIL, SWT.TOP, true, false,1,1));
- value = _toolkit.createText(parent, obj.getTimeStamp(), SWT.BEGINNING | SWT.BORDER | SWT.READ_ONLY);
- value.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false,3,1));
-
- key = _toolkit.createLabel(parent, COLUMN_TYPE, SWT.TRAIL);
- key.setLayoutData(new GridData(SWT.TRAIL, SWT.TOP, true, false,1,1));
- value = _toolkit.createText(parent, obj.getType(), SWT.BEGINNING | SWT.BORDER | SWT.READ_ONLY);
- value.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false,3,1));
-
- key = _toolkit.createLabel(parent, COLUMN_MSG, SWT.TRAIL);
- key.setLayoutData(new GridData(SWT.TRAIL, SWT.TOP, true, false,1,1));
- value = _toolkit.createText(parent, obj.getMessage(), SWT.MULTI | SWT.WRAP| SWT.BORDER | SWT.V_SCROLL | SWT.READ_ONLY);
- GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true, 3, 1);
- gridData.heightHint = 100;
- value.setLayoutData(gridData);
- }
- });
- }
-
- public void refresh()
- {
- if(_workerRunning)
- {
- //perform an single immediate-update
- updateTableViewer();
- }
- else
- {
- //start a worker to do the update and keep going as required
- _workerRunning = true;
- _worker = new Thread(new Worker());
- _worker.start();
- }
-
- _form.layout(true);
- _form.getBody().layout(true, true);
- }
-
- /**
- * Content provider class for the table viewer
- */
- protected class ContentProviderImpl implements IStructuredContentProvider, INotificationViewer
- {
- public void inputChanged(Viewer v, Object oldInput, Object newInput)
- {
-
- }
- public void dispose()
- {
-
- }
- public Object[] getElements(Object parent)
- {
- synchronized(VHNotificationsTabControl.this)
- {
- return _notifications.toArray(new NotificationObject[0]);
- }
- }
- public void addNotification(NotificationObject notification)
- {
- _tableViewer.add(notification);
- }
-
- public void addNotification(List<NotificationObject> notificationList)
- {
- _tableViewer.add(notificationList.toArray(new NotificationObject[0]));
- }
- }
-
- /**
- * Label provider for the table viewer
- */
- protected static class LabelProviderImpl implements ITableLabelProvider
- {
- List<ILabelProviderListener> listeners = new ArrayList<ILabelProviderListener>();
- public void addListener(ILabelProviderListener listener)
- {
- listeners.add(listener);
- }
-
- public void dispose(){
-
- }
-
- public Image getColumnImage(Object element, int columnIndex)
- {
- return null;
- }
-
- public String getColumnText(Object element, int columnIndex)
- {
- String result = null;
- NotificationObject t = (NotificationObject)element;
- switch(columnIndex)
- {
- case 0 :
- result = t.getSourceName();
- break;
- case 1 :
- result = String.valueOf(t.getSequenceNo());
- break;
- case 2 :
- result = String.valueOf(t.getTimeStamp());
- break;
- case 3 :
- result = t.getType();
- break;
- case 4 :
- result = t.getMessage();
- break;
- default :
- result = "";
- }
-
- return result;
- }
-
- public boolean isLabelProperty(Object element, String property)
- {
- return false;
- }
-
- public void removeListener(ILabelProviderListener listener)
- {
- listeners.remove(listener);
- }
- } // end of LabelProviderImpl
-
-
- protected void setWorkerRunning(boolean running)
- {
- _workerRunning = running;
- }
-
- /**
- * Worker class which keeps looking if there are new notifications coming from server for the selected mbean
- */
- private class Worker implements Runnable
- {
- private boolean keepGoing = true;
-
- public void run()
- {
- final Display display = _tabFolder.getDisplay();
-
- while(keepGoing)
- {
- if (display == null || display.isDisposed())
- {
- setWorkerRunning(false);
- break; //stop the thread
- }
-
- display.syncExec(new Runnable()
- {
- public void run()
- {
- if (_form == null || _form.isDisposed())
- {
- setWorkerRunning(false);
- keepGoing = false; //exit the loop and stop the thread
- }
- else
- {
- keepGoing = _form.isVisible();
- setWorkerRunning(keepGoing);
- }
-
- if (keepGoing)
- {
- updateTableViewer();
- }
- }
- });
-
- if (keepGoing)
- {
- sleep();
- }
- }
- }
-
- private void sleep()
- {
- try
- {
- Thread.sleep(2000);
- }
- catch(Exception ex)
- {
-
- }
- }
- }
-
- /**
- * Updates the table with new notifications received from mbean server for all mbeans in this virtual host
- */
- protected void updateTableViewer()
- {
- String virtualhost = MBeanView.getVirtualHost();
-
- ServerRegistry serverRegistry = ApplicationRegistry.getServerRegistry(MBeanView.getServer());
- List<NotificationObject> newList = serverRegistry.getNotifications(virtualhost);
-
- synchronized(this)
- {
- _notifications = newList;
- _tableViewer.setInput(_notifications);
- }
- }
-
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/ViewUtility.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/ViewUtility.java
deleted file mode 100644
index 8e4bea39e9..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/ViewUtility.java
+++ /dev/null
@@ -1,1032 +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.management.ui.views;
-
-import java.io.UnsupportedEncodingException;
-import java.nio.charset.Charset;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import javax.management.openmbean.ArrayType;
-import javax.management.openmbean.CompositeData;
-import javax.management.openmbean.CompositeDataSupport;
-import javax.management.openmbean.CompositeType;
-import javax.management.openmbean.OpenType;
-import javax.management.openmbean.TabularDataSupport;
-import javax.management.openmbean.TabularType;
-
-import org.apache.commons.codec.binary.Hex;
-import org.apache.qpid.management.ui.ApplicationRegistry;
-import static org.apache.qpid.management.ui.Constants.FAILURE_IMAGE;
-import static org.apache.qpid.management.ui.Constants.SUCCESS_IMAGE;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ControlAdapter;
-import org.eclipse.swt.events.ControlEvent;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Event;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Listener;
-import org.eclipse.swt.widgets.MessageBox;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.ScrollBar;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-
-/**
- * Utility Class for displaying OpenMbean data types by creating required SWT widgets
- */
-public class ViewUtility
-{
- public static final String OP_NAME = "operation_name";
- public static final String OP_PARAMS = "parameters";
- public static final String PARAMS_TEXT = "text";
-
- public static final String FIRST = "First";
- public static final String LAST = "Last";
- public static final String NEXT = "Next";
- public static final String PREV = "Previous";
- public static final String INDEX = "Index";
-
- private static final Comparator tabularDataComparator = new TabularDataComparator();
-
- private static MBeanView _mbeanView = null;
-
- private static List<String> SUPPORTED_ARRAY_DATATYPES = new ArrayList<String>();
- static
- {
- SUPPORTED_ARRAY_DATATYPES.add("java.lang.String");
- SUPPORTED_ARRAY_DATATYPES.add("java.lang.Boolean");
- SUPPORTED_ARRAY_DATATYPES.add("java.lang.Character");
- SUPPORTED_ARRAY_DATATYPES.add("java.lang.Integer");
- SUPPORTED_ARRAY_DATATYPES.add("java.lang.Long");
- SUPPORTED_ARRAY_DATATYPES.add("java.lang.Double");
- SUPPORTED_ARRAY_DATATYPES.add("java.util.Date");
- }
-
- private static final int DEFAULT_CONTENT_SIZE = 198;
- static Button _firstButton, _nextButton, _previousButton, _lastButton;
- static Text _hexNumTextToEnd, _hexNumTextToStart;
-
- /**
- * Populates the composite with given openmbean data type (TabularType or CompositeType)
- * @param toolkit
- * @param parent composite
- * @param data open mbean data type(either composite type or tabular data type)
- */
- public static void populateCompositeWithData(FormToolkit toolkit, Composite parent, Object data)
- {
- if (data instanceof TabularDataSupport)
- {
- ViewUtility.createTabularDataHolder(toolkit, parent, (TabularDataSupport)data);
- }
- else if (data instanceof CompositeDataSupport)
- {
- ViewUtility.populateCompositeWithCompositeData(toolkit, parent, (CompositeDataSupport)data);
- }
- }
-
- @SuppressWarnings("unchecked")
- private static void createTabularDataHolder(FormToolkit toolkit, Composite parent, TabularDataSupport tabularData)
- {
- Composite composite = toolkit.createComposite(parent, SWT.BORDER);
- GridLayout layout = new GridLayout(4, true);
- layout.horizontalSpacing = 0;
- layout.marginWidth = 0;
- layout.marginHeight = 10;
- layout.verticalSpacing = 10;
- composite.setLayout(layout);
- composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
-
- Set entrySet = tabularData.entrySet();
- ArrayList<Map.Entry> list = new ArrayList<Map.Entry>(entrySet);
- if (list.size() == 0)
- {
- Text text = toolkit.createText(composite, " No records ", SWT.CENTER | SWT.SINGLE | SWT.READ_ONLY);
- GridData layoutData = new GridData(SWT.FILL, SWT.FILL, true, true, 4, 1);
- text.setLayoutData(layoutData);
- return;
- }
-
- Collections.sort(list, tabularDataComparator);
-
- // Attach the tabular record to be retrieved and shown later when record is traversed
- // using first/next/previous/last buttons
- composite.setData(list);
-
- // Create button and the composite for CompositeData
- Composite compositeDataHolder = createCompositeDataHolder(toolkit, composite,
- tabularData.getTabularType().getRowType());
-
- // display the first record
- CompositeData data = (CompositeData)(list.get(0)).getValue();
- composite.setData(INDEX, 0);
- populateCompositeWithCompositeData(toolkit, compositeDataHolder, data);
- enableOrDisableTraversalButtons(composite);
- }
-
- private static void enableOrDisableTraversalButtons(Composite composite)
- {
- int index = (Integer)composite.getData(INDEX);
- int size = ((List)composite.getData()).size();
-
- ((Button)composite.getData(FIRST)).setEnabled(true);
- ((Button)composite.getData(PREV)).setEnabled(true);
- ((Button)composite.getData(NEXT)).setEnabled(true);
- ((Button)composite.getData(LAST)).setEnabled(true);
-
- if (index == 0)
- {
- ((Button)composite.getData(FIRST)).setEnabled(false);
- ((Button)composite.getData(PREV)).setEnabled(false);
- }
- if (index == size -1)
- {
- ((Button)composite.getData(NEXT)).setEnabled(false);
- ((Button)composite.getData(LAST)).setEnabled(false);
- }
- }
-
- /**
- * Sets up the given composite for holding a CompositeData. Create traversal buttons, label etc and
- * creates a child Composite, which should be populated with the CompositeData
- * @param toolkit
- * @param dataHolder
- * @param compositeType
- * @return
- */
- private static Composite createCompositeDataHolder(final FormToolkit toolkit, final Composite dataHolder, CompositeType compositeType)
- {
- String desc = compositeType.getDescription();
- Label description = toolkit.createLabel(dataHolder, desc, SWT.CENTER);
- description.setLayoutData(new GridData(SWT.CENTER, SWT.TOP, true, false, 4, 1));
- // TODO nameLabel.setFont(font);
- description.setText(desc);
-
- // Add traversal buttons
- final Button firstRecordButton = toolkit.createButton(dataHolder, FIRST, SWT.PUSH);
- GridData layoutData = new GridData (GridData.HORIZONTAL_ALIGN_END);
- layoutData.widthHint = 80;
- firstRecordButton.setLayoutData(layoutData);
-
- final Button previousRecordButton = toolkit.createButton(dataHolder, PREV, SWT.PUSH);
- layoutData = new GridData (GridData.HORIZONTAL_ALIGN_END);
- layoutData.widthHint = 80;
- previousRecordButton.setLayoutData(layoutData);
-
- final Button nextRecordButton = toolkit.createButton(dataHolder, NEXT, SWT.PUSH);
- layoutData = new GridData (GridData.HORIZONTAL_ALIGN_BEGINNING);
- layoutData.widthHint = 80;
- nextRecordButton.setLayoutData(layoutData);
-
- final Button lastRecordButton = toolkit.createButton(dataHolder, LAST, SWT.PUSH);
- layoutData = new GridData (GridData.HORIZONTAL_ALIGN_BEGINNING);
- layoutData.widthHint = 80;
- lastRecordButton.setLayoutData(layoutData);
-
- // Now create the composite, which will hold the CompositeData
- final Composite composite = toolkit.createComposite(dataHolder, SWT.NONE);
- GridLayout layout = new GridLayout();
- layout.horizontalSpacing = layout.verticalSpacing = 0;
- layout.marginHeight = layout.marginWidth = 0;
- composite.setLayout(layout);
- composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 4, 1));
-
- // Add button references. These references will be used when buttons
- // are to enabled or disabled based of record index. e.g. for first record
- // First and Previous buttons will be disabled.
- dataHolder.setData(FIRST, firstRecordButton);
- dataHolder.setData(NEXT, nextRecordButton);
- dataHolder.setData(PREV, previousRecordButton);
- dataHolder.setData(LAST, lastRecordButton);
-
- // Listener for the traversal buttons. When a button is clicked the respective
- // CompositeData will be populated in the composite
- SelectionListener listener = new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- if (!(e.widget instanceof Button))
- return;
-
- Button traverseButton =(Button)e.widget;
- // Get the CompositeData respective to the button selected
- CompositeData data = getCompositeData(dataHolder, traverseButton.getText());
- populateCompositeWithCompositeData(toolkit, composite, data);
- enableOrDisableTraversalButtons(dataHolder);
- }
- };
-
- firstRecordButton.addSelectionListener(listener);
- nextRecordButton.addSelectionListener(listener);
- previousRecordButton.addSelectionListener(listener);
- lastRecordButton.addSelectionListener(listener);
-
- return composite;
- }
-
- /**
- * The CompositeData is set as data with the Composite and using the index, this method will
- * return the corresponding CompositeData
- * @param compositeHolder
- * @param dataIndex
- * @return the CompositeData respective to the index
- */
- private static CompositeData getCompositeData(Composite compositeHolder, String dataIndex)
- {
- List objectData = (List)compositeHolder.getData();
- if (objectData == null || objectData.isEmpty())
- {
- // TODO
- }
-
- // Get the index of record to be shown.
- int index = 0;
- if (compositeHolder.getData(INDEX) != null)
- {
- index = (Integer)compositeHolder.getData(INDEX);
- }
-
- if (FIRST.equals(dataIndex))
- {
- index = 0;
- }
- else if (NEXT.equals(dataIndex))
- {
- index = index + 1;
- }
- else if (PREV.equals(dataIndex))
- {
- index = (index != 0) ? (index = index - 1) : index;
- }
- else if (LAST.equals(dataIndex))
- {
- index = objectData.size() -1;
- }
-
- // Set the index being shown.
- compositeHolder.setData(INDEX, index);
-
- return (CompositeData)((Map.Entry)objectData.get(index)).getValue();
- }
-
- /**
- * Populates the given composite with the CompositeData. Creates required widgets to hold the data types
- * @param toolkit
- * @param parent
- * @param data CompositeData
- */
- @SuppressWarnings("unchecked")
- private static void populateCompositeWithCompositeData(FormToolkit toolkit, Composite parent, CompositeData data)
- {
- Control[] oldControls = parent.getChildren();
- for (int i = 0; i < oldControls.length; i++)
- {
- oldControls[i].dispose();
- }
-
- Composite compositeHolder = toolkit.createComposite(parent, SWT.NONE);
- GridLayout layout = new GridLayout(4, false);
- layout.horizontalSpacing = 10;
- compositeHolder.setLayout(layout);
- compositeHolder.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
-
-
- // ItemNames in composite data
- List<String> itemNames = new ArrayList<String>(data.getCompositeType().keySet());
-
- for (String itemName : itemNames)
- {
- OpenType itemType = data.getCompositeType().getType(itemName);
- Label keyLabel = toolkit.createLabel(compositeHolder, itemName, SWT.TRAIL);
- GridData layoutData = new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1);
- layoutData.minimumWidth = 70;
- keyLabel.setLayoutData(layoutData);
-
- if (itemType.isArray())
- {
- OpenType type = ((ArrayType)itemType).getElementOpenType();
- // If Byte array and mimetype is text, convert to text string
- if (type.getClassName().equals(Byte.class.getName()))
- {
- String mimeType = null;
- String encoding = null;
- if (data.containsKey("MimeType"))
- {
- mimeType = (String)data.get("MimeType");
- }
- if (data.containsKey("Encoding"))
- {
- encoding = (String)data.get("Encoding");
- }
-
- if (encoding == null || encoding.length() == 0)
- {
- encoding = Charset.defaultCharset().name();
- }
-
- if ("text/plain".equals(mimeType))
- {
- convertByteArray(toolkit, compositeHolder, data, itemName, encoding);
- }
- else
- {
- handleBinaryMessageContent(toolkit, compositeHolder, data, itemName, encoding);
- }
- }
- // If array of any other supported type, show as a list of String array
- else if (SUPPORTED_ARRAY_DATATYPES.contains(type.getClassName()))
- {
- convertArrayItemForDisplay(compositeHolder, data, itemName);
- }
- else
- {
- setNotSupportedDataType(toolkit, compositeHolder);
- }
- }
- else if (itemType instanceof TabularType)
- {
- Composite composite = toolkit.createComposite(compositeHolder, SWT.NONE);
- composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false, 3, 1));
- layout = new GridLayout();
- layout.marginHeight = 0;
- layout.marginWidth = 0;
- composite.setLayout(layout);
- createTabularDataHolder(toolkit, composite, (TabularDataSupport)data.get(itemName));
- }
- else
- {
- Text valueText = toolkit.createText(compositeHolder, String.valueOf(data.get(itemName)), SWT.READ_ONLY | SWT.BORDER);
- valueText.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false, 3, 1));
- }
- }
-
- // layout the composite after creating new widgets.
- parent.layout();
- } //end of method
-
-
- private static void convertByteArray(FormToolkit toolkit, Composite compositeHolder, CompositeData data, String itemName, String encoding)
- {
- Byte[] arrayItems = (Byte[])data.get(itemName);
- byte[] byteArray = new byte[arrayItems.length];
-
- for (int i = 0; i < arrayItems.length; i++)
- {
- byteArray[i] = arrayItems[i];
- }
- try
- {
- String textMessage = new String(byteArray, encoding);
-
- Text valueText = toolkit.createText(compositeHolder, textMessage, SWT.READ_ONLY | SWT.BORDER |
- SWT.MULTI | SWT.WRAP | SWT.V_SCROLL);
- GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true, 3, 1);
- gridData.heightHint = 300;
- valueText.setLayoutData(gridData);
- }
- catch(Exception ex)
- {
- ex.printStackTrace();
- }
- }
-
- private static Shell getShell()
- {
- Shell shell = Display.getCurrent().getActiveShell();
-
- // Under linux GTK getActiveShell returns null so we need to make a new shell for display.
- // Under windows this is fine.
- if (shell == null)
- {
- // This occurs under linux gtk
- shell = new Shell(Display.getCurrent(), SWT.BORDER | SWT.CLOSE | SWT.MIN | SWT.MAX);
- }
-
- return shell;
- }
-
- private static int showBox(String title, String message, int icon)
- {
- MessageBox messageBox = new MessageBox(getShell(), icon);
- messageBox.setMessage(message);
- messageBox.setText(title);
-
- return messageBox.open();
- }
-
- /**
- * Creates widgets for object messages and populates the content in hexadecimal format.
- * @param toolkit
- * @param compositeHolder
- * @param data
- * @param itemName
- * @param encoding
- */
- private static void handleBinaryMessageContent(FormToolkit toolkit, Composite compositeHolder, CompositeData data, String itemName, String encoding)
- {
- final String thisEncoding = encoding;
- final Byte[] arrayItems = (Byte[]) data.get(itemName);
- final byte[] byteArray = new byte[arrayItems.length];
-
- for (int i = 0; i < arrayItems.length; i++)
- {
- byteArray[i] = arrayItems[i];
- }
-
- try
- {
- //create a new composite to contain the widgets required to display object messages.
- final Composite localComposite = toolkit.createComposite(compositeHolder, SWT.NONE);
- localComposite.setData("currentBytePos", 0);
- localComposite.setData("startingBytePos", 0);
- GridLayout layout = new GridLayout(2, true);
- layout.marginWidth = 0;
- layout.marginHeight = 0;
- localComposite.setLayout(layout);
- localComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 3, 1));
-
- int startContentSize = DEFAULT_CONTENT_SIZE;
-
- if (byteArray.length < DEFAULT_CONTENT_SIZE)
- {
- startContentSize = byteArray.length;
- }
-
- //create a text to display the hexadecimal views of object messages, it takes more space than ascii view as
- //a hex uses 2 chars and 1 space, while ascii only uses 1 char and 1 space.
- final Text hexText = toolkit.createText(localComposite,
- displayByteFormat(localComposite, byteArray, startContentSize * 2, thisEncoding, "<<", true),
- SWT.READ_ONLY | SWT.MULTI | SWT.WRAP | SWT.V_SCROLL | SWT.BORDER);
- GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
- gridData.widthHint = 144; //set to 222 if not using any fonts
- gridData.heightHint = 200;
- hexText.setLayoutData(gridData);
-
- final Text asciiText = toolkit.createText(localComposite,
- displayByteFormat(localComposite, byteArray, startContentSize * 2, thisEncoding, "<<", false),
- SWT.READ_ONLY | SWT.MULTI | SWT.WRAP | SWT.V_SCROLL | SWT.BORDER);
-
-
- gridData = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
- gridData.widthHint = 52;//set to 98 if not using any fonts
- gridData.heightHint = 200;
- asciiText.setLayoutData(gridData);
-
- //use a monospaced font for a better layout
- Font font = new Font(compositeHolder.getDisplay(), "Courier", 10, SWT.NORMAL);
- hexText.setFont(font);
- asciiText.setFont(font);
-
- final ScrollBar hexScrollBar = hexText.getVerticalBar();
- final ScrollBar asciiScrollBar = asciiText.getVerticalBar();
-
- //create a sub composite to contain all the buttons
- final Composite buttonComposite = toolkit.createComposite(localComposite, SWT.NONE);
- layout = new GridLayout(7, false);
- layout.marginWidth = 0;
- buttonComposite.setLayout(layout);
- buttonComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false, 2, 1));
-
- _firstButton = toolkit.createButton(buttonComposite, "<<", SWT.PUSH);
- GridData layoutData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
- layoutData.widthHint = 40;
- _firstButton.setLayoutData(layoutData);
- _firstButton.setToolTipText("See the first n bytes");
-
- _previousButton = toolkit.createButton(buttonComposite, "<", SWT.PUSH);
- layoutData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
- layoutData.widthHint = 40;
- _previousButton.setLayoutData(layoutData);
- _previousButton.setToolTipText("See the previous n bytes");
- _previousButton.setEnabled(false);
-
- _hexNumTextToStart = toolkit.createText(buttonComposite, "0");
- layoutData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
- layoutData.widthHint = 40;
- _hexNumTextToStart.setLayoutData(layoutData);
- _hexNumTextToStart.setEditable(false);
-
- final Text hexNumText = toolkit.createText(buttonComposite, "" + startContentSize);
- layoutData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
- layoutData.widthHint = 40;
- hexNumText.setLayoutData(layoutData);
-
- _hexNumTextToEnd = toolkit.createText(buttonComposite, "" + (byteArray.length - startContentSize));
- layoutData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
- layoutData.widthHint = 40;
- _hexNumTextToEnd.setLayoutData(layoutData);
- _hexNumTextToEnd.setEditable(false);
-
- _nextButton = toolkit.createButton(buttonComposite, ">", SWT.PUSH);
- layoutData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
- layoutData.widthHint = 40;
- _nextButton.setLayoutData(layoutData);
- _nextButton.setToolTipText("See the next n bytes");
- _nextButton.setEnabled(true);
-
- _lastButton = toolkit.createButton(buttonComposite, ">>", SWT.PUSH);
- layoutData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
- layoutData.widthHint = 40;
- _lastButton.setToolTipText("See the last n bytes");
- _lastButton.setLayoutData(layoutData);
-
- SelectionListener listener = new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- if (e.widget instanceof Button)
- {
- String numOfBytes = hexNumText.getText();
- try
- {
- int n = Integer.parseInt(numOfBytes);
-
- //Reset range display if user requests a large value
- if (n > byteArray.length)
- {
- n = (byteArray.length > DEFAULT_CONTENT_SIZE) ? DEFAULT_CONTENT_SIZE : byteArray.length;
- hexNumText.setText("" + n);
- }
-
- //rest if the user requests 0
- if (n < 1)
- {
- n = DEFAULT_CONTENT_SIZE;
- hexNumText.setText("" + n);
- }
-
- Button button = (Button) e.widget;
- hexText.setText(displayByteFormat(localComposite, byteArray, n * 2, thisEncoding,
- button.getText(), true));
- asciiText.setText(displayByteFormat(localComposite, byteArray, n * 2, thisEncoding,
- button.getText(), false));
- }
- catch (NumberFormatException exp)
- {
- popupErrorMessage("Error", "Please input the number of bytes you wish to look at");
- }
- }
- if (e.widget instanceof ScrollBar)
- {
- //synchronize the movements of the two scrollbars
- ScrollBar sb = (ScrollBar) e.widget;
- if (sb.getParent().equals(hexText))
- {
- asciiScrollBar.setIncrement(sb.getIncrement());
- asciiScrollBar.setSelection(sb.getSelection());
- }
- else if (sb.getParent().equals(asciiText))
- {
- hexScrollBar.setSelection(sb.getSelection());
- hexScrollBar.setIncrement(sb.getIncrement());
- }
- }
- }
- };
- localComposite.addControlListener(new ControlAdapter()
- {
- public void controlResized(ControlEvent e)
- {
- //if the control is resized, set different parameters to make a single line displays the same contents.
- if (((GridLayout) localComposite.getLayout()).makeColumnsEqualWidth)
- {
- ((GridLayout) localComposite.getLayout()).makeColumnsEqualWidth = false;
- ((GridLayout) localComposite.getLayout()).numColumns = 2;
- ((GridData) hexText.getLayoutData()).horizontalSpan = 1;
- ((GridData) hexText.getLayoutData()).widthHint = 144;
- ((GridData) asciiText.getLayoutData()).horizontalSpan = 1;
- ((GridData) asciiText.getLayoutData()).widthHint = 52;
- ((GridData) buttonComposite.getLayoutData()).horizontalSpan = 2;
- }
- else
- {
- ((GridLayout) localComposite.getLayout()).makeColumnsEqualWidth = true;
- ((GridLayout) localComposite.getLayout()).numColumns = 42; //set to 47 if not using any fonts
- ((GridData) hexText.getLayoutData()).horizontalSpan = 25; // set to 30 if not using any fonts
- ((GridData) asciiText.getLayoutData()).horizontalSpan = 17; // set to 17 if not using any fonts
- ((GridData) buttonComposite.getLayoutData()).horizontalSpan = 42;
- }
- }
- });
-
- _firstButton.addSelectionListener(listener);
- _previousButton.addSelectionListener(listener);
- _nextButton.addSelectionListener(listener);
- _lastButton.addSelectionListener(listener);
- hexScrollBar.addSelectionListener(listener);
- asciiScrollBar.addSelectionListener(listener);
- //f.dispose();
- }
- catch (Exception ex)
- {
- ex.printStackTrace();
- }
- }
-
- /**
- * Format object messages to have a hexadecimal view and a ascii view.
- * @param numOfBytes
- * @param encoding
- * @return
- */
- private static String displayByteFormat(Composite localComposite, byte[] byteArray, int numOfBytes,
- String encoding, String direction, boolean isHex)
- {
- final Hex hexeconder = new Hex();
- final byte[] encoded = hexeconder.encode(byteArray);
-
- int hexLength = byteArray.length * 2;
- StringBuilder sb = new StringBuilder();
- int currentBytePos = (Integer) localComposite.getData("currentBytePos");
- int startingBytePos = (Integer) localComposite.getData("startingBytePos");
-
- int strLength = 0;
- int offset = 0;
- String encStr;
- if (isHex)
- {
- if (direction.equals("<<"))
- {
- strLength = (numOfBytes > hexLength) ? hexLength : numOfBytes;
- offset = 0;
- }
- else if (direction.equals("<"))
- {
- strLength = (startingBytePos - numOfBytes < 0) ? startingBytePos : numOfBytes;
- offset = (startingBytePos - numOfBytes < 0) ? 0 : startingBytePos - numOfBytes;
- }
- else if (direction.equals(">"))
- {
- strLength = (numOfBytes > (hexLength - currentBytePos)) ? hexLength - currentBytePos : numOfBytes;
- offset = currentBytePos;
- }
- else if (direction.equals(">>"))
- {
- strLength = (numOfBytes > hexLength) ? hexLength : numOfBytes;
- offset = (hexLength - numOfBytes > 0) ? hexLength - numOfBytes : 0;
- }
- else
- {
- strLength = hexLength;
- offset = 0;
- }
- localComposite.setData("strLength", strLength);
- localComposite.setData("currentBytePos", offset + strLength);
- localComposite.setData("startingBytePos", offset);
-
- if (_lastButton != null && !_lastButton.isDisposed())
- {
- //Set button state
- _previousButton.setEnabled(offset != 0);
- _nextButton.setEnabled(offset + strLength != hexLength);
-
- //set the text fields
- _hexNumTextToStart.setText("" + offset / 2);
- _hexNumTextToEnd.setText("" + (hexLength - (offset + strLength)) / 2);
- }
- }
-
- try
- {
- if (isHex)
- {
- encStr = new String(encoded, offset, strLength, encoding);
- for (int c = 0; c < strLength; c++)
- {
- sb.append(encStr.charAt(c));
- if (c % 2 == 1)
- {
- sb.append(" ");
- }
- }
- return sb.toString().toUpperCase();
- }
- else
- {
- strLength = (Integer) localComposite.getData("strLength");
- sb = new StringBuilder();
- encStr = new String(byteArray, startingBytePos / 2, strLength / 2, encoding);
- for (int c = 0; c < encStr.length(); c++)
- {
- char ch = encStr.charAt(c);
- if (ch > 31 && ch < 127)
- {
- sb.append(ch);
- }
- else
- {
- sb.append("?");
- }
-
- sb.append(" ");
- }
- }
- }
- catch (UnsupportedEncodingException e)
- {
- e.printStackTrace();
- }
- return sb.toString();
- }
-
- public static int popupInfoMessage(String title, String message)
- {
- return showBox(title, message, SWT.ICON_INFORMATION | SWT.OK);
- }
-
- public static int popupErrorMessage(String title, String message)
- {
- return showBox(title, message, SWT.ICON_ERROR | SWT.OK);
- }
-
- public static int popupConfirmationMessage(String title, String message)
- {
- return showBox(title, message,SWT.ICON_QUESTION | SWT.YES | SWT.NO);
- }
-
- public static int popupOkCancelConfirmationMessage(String title, String message)
- {
- return showBox(title, message,SWT.ICON_QUESTION | SWT.OK | SWT.CANCEL);
- }
-
-
- public static Shell createPopupShell(String title, int width, int height)
- {
- Display display = Display.getCurrent();
- final Shell shell = new Shell(display, SWT.BORDER | SWT.CLOSE | SWT.MIN |SWT.MAX);
- shell.setText(title);
- shell.setLayout(new GridLayout());
- int x = display.getBounds().width;
- int y = display.getBounds().height;
- shell.setBounds(x/4, y/4, width, height);
-
- shell.addListener(SWT.Traverse, new Listener () {
- public void handleEvent (Event event) {
- switch (event.detail) {
- case SWT.TRAVERSE_ESCAPE:
- shell.close ();
- event.detail = SWT.TRAVERSE_NONE;
- event.doit = false;
- break;
- }
- }
- });
-
- return shell;
- }
-
- public static Shell createModalDialogShell(Shell parent, String title)
- {
- final Shell shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);
- shell.setText(title);
- shell.setLayout(new GridLayout());
-
- shell.addListener(SWT.Traverse, new Listener () {
- public void handleEvent (Event event) {
- switch (event.detail) {
- case SWT.TRAVERSE_ESCAPE:
- shell.close ();
- event.detail = SWT.TRAVERSE_NONE;
- event.doit = false;
- break;
- }
- }
- });
-
- return shell;
- }
-
- /**
- * Creates a List widget for displaying array of strings
- * @param compositeHolder
- * @param data - containing the array item value
- * @param itemName - item name
- */
- private static void convertArrayItemForDisplay(Composite compositeHolder, CompositeData data, String itemName)
- {
- Object[] arrayItems = (Object[])data.get(itemName);
- String[] items = new String[arrayItems.length];
- for (int i = 0; i < arrayItems.length; i++)
- {
- items[i] = String.valueOf(arrayItems[i]);
- }
- org.eclipse.swt.widgets.List list = new org.eclipse.swt.widgets.List(compositeHolder,
- SWT.MULTI | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.READ_ONLY);
- list.setItems(items);
- //list.setBackground(compositeHolder.getBackground());
- list.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 3, 1));
- }
-
- private static void setNotSupportedDataType(FormToolkit toolkit, Composite compositeHolder)
- {
- Text valueText = toolkit.createText(compositeHolder, "--- Content can not be displayed ---", SWT.READ_ONLY);
- valueText.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false, 3, 1));
- }
-
- /**
- * Converts the input string to displayable format by converting some character case or inserting space
- * @param input
- * @return formatted string
- */
- public static String getDisplayText(String input)
- {
- StringBuffer result = new StringBuffer(input);
- if (Character.isLowerCase(result.charAt(0)))
- {
- result.setCharAt(0, Character.toUpperCase(result.charAt(0)));
- }
- for (int i = 1; i < input.length(); i++)
- {
- if (Character.isUpperCase(result.charAt(i)) && !Character.isWhitespace(result.charAt(i - 1))
- && Character.isLowerCase(result.charAt(i - 1)))
- {
- result.insert(i, " ");
- i++;
- }
- else if (Character.isLowerCase(result.charAt(i)) && Character.isWhitespace(result.charAt(i - 1)))
- {
- result.setCharAt(i, Character.toUpperCase(result.charAt(i)));
- }
-
- }
-
- return result.toString();
- }
-
- /**
- * Disposes the children of given Composite if not null and not already disposed
- * @param parent composite
- */
- public static void disposeChildren(Composite parent)
- {
- if (parent == null || parent.isDisposed())
- return;
-
- Control[] oldControls = parent.getChildren();
- for (int i = 0; i < oldControls.length; i++)
- {
- oldControls[i].dispose();
- }
- }
-
- public static char[] getHash(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException
- {
- byte[] data = text.getBytes("utf-8");
-
- MessageDigest md = MessageDigest.getInstance("MD5");
-
- for (byte b : data)
- {
- md.update(b);
- }
-
- byte[] digest = md.digest();
-
- char[] hash = new char[digest.length ];
-
- int index = 0;
- for (byte b : digest)
- {
- hash[index++] = (char) b;
- }
-
- return hash;
- }
-
- private static class TabularDataComparator implements java.util.Comparator<Map.Entry>
- {
- public int compare(Map.Entry data1, Map.Entry data2)
- {
- if (data1.getKey() instanceof List)
- {
- Object obj1 = ((List)data1.getKey()).get(0);
- Object obj2 = ((List)data2.getKey()).get(0);
- String str1 = obj1.toString();
- String str2 = obj2.toString();
- if (obj1 instanceof String)
- {
- return str1.compareTo(str2);
- }
-
- try
- {
- return Long.valueOf(str1).compareTo(Long.valueOf(str2));
- }
- catch (Exception ex)
- {
- return -1;
- }
- }
-
- return -1;
- }
- }
-
- public static void setMBeanView(MBeanView mbeanView)
- {
- _mbeanView = mbeanView;
- }
-
- /**
- * Report feedback for the operation
- * @param result true if success, false if unsuccessful, null if invoked but void result type.
- * @param successMessage
- * @param failureMessage
- */
- public static void operationResultFeedback(Boolean result, String successMessage, String failureMessage)
- {
- Image icon;
-
- if(_mbeanView != null)
- {
- if(result == null)
- {
- icon = ApplicationRegistry.getImage(SUCCESS_IMAGE);
- _mbeanView.populateStatusBar(icon, successMessage);
- }
- else if(result)
- {
- icon = ApplicationRegistry.getImage(SUCCESS_IMAGE);
- _mbeanView.populateStatusBar(icon, successMessage);
- }
- else
- {
- icon = ApplicationRegistry.getImage(FAILURE_IMAGE);
- _mbeanView.populateStatusBar(icon, failureMessage);
- popupErrorMessage("Operation Failed", failureMessage);
- }
- }
- }
-
- public static void operationFailedStatusBarMessage(String failureMessage)
- {
- Image icon = ApplicationRegistry.getImage(FAILURE_IMAGE);
-
- if(_mbeanView != null)
- {
- _mbeanView.populateStatusBar(icon, failureMessage);
- }
- }
-
- public static void clearStatusBar()
- {
- if(_mbeanView != null)
- {
- _mbeanView.clearStatusBar();
- }
- }
-
- public static void centerChildInParentShell(Shell parent, Shell child)
- {
- //get current parent shell size and location
- int parentLocX = parent.getBounds().x;
- int parentLocY = parent.getBounds().y;
- int parentWidth = parent.getBounds().width;
- int parentHeight = parent.getBounds().height;
-
- //get current child size
- int childWidth = child.getSize().x;
- int childHeight = child.getSize().y;
-
- //centre the child within/over the parent
- child.setBounds((parentWidth - childWidth)/2 + parentLocX,
- (parentHeight - childHeight)/2 + parentLocY,
- childWidth, childHeight);
- }
-
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/connection/ConnectionOperationsTabControl.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/connection/ConnectionOperationsTabControl.java
deleted file mode 100644
index 35171773ad..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/connection/ConnectionOperationsTabControl.java
+++ /dev/null
@@ -1,545 +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.management.ui.views.connection;
-
-import static org.apache.qpid.management.common.mbeans.ManagedConnection.CHAN_ID;
-import static org.apache.qpid.management.common.mbeans.ManagedConnection.DEFAULT_QUEUE;
-import static org.apache.qpid.management.common.mbeans.ManagedConnection.FLOW_BLOCKED;
-import static org.apache.qpid.management.common.mbeans.ManagedConnection.TRANSACTIONAL;
-import static org.apache.qpid.management.common.mbeans.ManagedConnection.UNACKED_COUNT;
-
-import java.util.Collection;
-
-import javax.management.MBeanServerConnection;
-import javax.management.MBeanServerInvocationHandler;
-import javax.management.openmbean.CompositeData;
-import javax.management.openmbean.CompositeDataSupport;
-import javax.management.openmbean.TabularDataSupport;
-
-import org.apache.qpid.management.ui.ApiVersion;
-import org.apache.qpid.management.ui.ApplicationRegistry;
-import org.apache.qpid.management.ui.ManagedBean;
-import org.apache.qpid.management.ui.ServerRegistry;
-import org.apache.qpid.management.common.mbeans.ManagedConnection;
-import org.apache.qpid.management.ui.jmx.JMXManagedObject;
-import org.apache.qpid.management.ui.jmx.MBeanUtility;
-import org.apache.qpid.management.ui.views.MBeanView;
-import org.apache.qpid.management.ui.views.TabControl;
-import org.apache.qpid.management.ui.views.ViewUtility;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.ITableLabelProvider;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerSorter;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.MouseEvent;
-import org.eclipse.swt.events.MouseListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.swt.widgets.TabFolder;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.TableColumn;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.forms.widgets.Form;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-
-
-/**
- * Control class for the Connection mbean Operations tab.
- */
-public class ConnectionOperationsTabControl extends TabControl
-{
- private FormToolkit _toolkit;
- private Form _form;
- private Table _table = null;
- private TableViewer _tableViewer = null;
- private Composite _paramsComposite = null;
-
- private TabularDataSupport _channels = null;
- private ManagedConnection _cmb;
- private ApiVersion _ApiVersion;
-
- public ConnectionOperationsTabControl(TabFolder tabFolder, JMXManagedObject mbean, MBeanServerConnection mbsc)
- {
- super(tabFolder);
- _mbean = mbean;
- _ApiVersion = ApplicationRegistry.getServerRegistry(mbean).getManagementApiVersion();
- _cmb = (ManagedConnection) MBeanServerInvocationHandler.newProxyInstance(mbsc,
- mbean.getObjectName(), ManagedConnection.class, false);
- _toolkit = new FormToolkit(_tabFolder.getDisplay());
- _form = _toolkit.createForm(_tabFolder);
- _form.getBody().setLayout(new GridLayout());
- createComposites();
- createWidgets();
- }
-
- private void createComposites()
- {
- _paramsComposite = _toolkit.createComposite(_form.getBody(), SWT.NONE);
- _paramsComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- _paramsComposite.setLayout(new GridLayout());
- }
-
- /**
- * @see TabControl#getControl()
- */
- public Control getControl()
- {
- return _form;
- }
-
- /**
- * @see TabControl#setFocus()
- */
- public void setFocus()
- {
- _table.setFocus();
- }
-
- @Override
- public void refresh(ManagedBean mbean)
- {
- _channels = null;
- try
- {
- //gather a list of all channels on the connection for display and selection
- _channels = (TabularDataSupport) _cmb.channels();
- }
- catch (Exception e)
- {
- MBeanUtility.handleException(mbean,e);
- }
-
- _tableViewer.setInput(_channels);
-
- layout();
- }
-
- public void layout()
- {
- _form.layout(true);
- _form.getBody().layout(true, true);
- }
-
- private void createWidgets()
- {
- Group viewChannelsGroup = new Group(_paramsComposite, SWT.SHADOW_NONE);
- viewChannelsGroup.setBackground(_paramsComposite.getBackground());
- viewChannelsGroup.setText("Channels");
- viewChannelsGroup.setLayout(new GridLayout());
- GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
- gridData.heightHint = 250;
- gridData.minimumHeight = 250;
-
- viewChannelsGroup.setLayoutData(gridData);
-
- _table = new Table (viewChannelsGroup, SWT.SINGLE | SWT.SCROLL_LINE | SWT.BORDER | SWT.FULL_SELECTION);
- _table.setLinesVisible (true);
- _table.setHeaderVisible (true);
- GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
- _table.setLayoutData(data);
-
- _tableViewer = new TableViewer(_table);
- final TableSorter tableSorter = new TableSorter();
-
- String[] titles;
- if(_ApiVersion.greaterThanOrEqualTo(1, 5))
- {
- titles = new String[]{"Id", "Transactional", "Num Unacked Msg", "Default Queue", "Flow Blocked"};
- }
- else
- {
- titles = new String[]{"Id", "Transactional", "Num Unacked Msg", "Default Queue"};
- }
- int[] bounds = { 50, 110, 145, 200, 110 };
- for (int i = 0; i < titles.length; i++)
- {
- final int index = i;
- final TableColumn column = new TableColumn (_table, SWT.NONE);
-
- column.setText(titles[i]);
- column.setWidth(bounds[i]);
- column.setResizable(true);
-
- //Setting the right sorter
- column.addSelectionListener(new SelectionAdapter()
- {
- @Override
- public void widgetSelected(SelectionEvent e)
- {
- tableSorter.setColumn(index);
- final TableViewer viewer = _tableViewer;
- int dir = viewer .getTable().getSortDirection();
- if (viewer.getTable().getSortColumn() == column)
- {
- dir = dir == SWT.UP ? SWT.DOWN : SWT.UP;
- }
- else
- {
- dir = SWT.UP;
- }
- viewer.getTable().setSortDirection(dir);
- viewer.getTable().setSortColumn(column);
- viewer.refresh();
- }
- });
-
- }
-
- _tableViewer.setContentProvider(new ContentProviderImpl());
- _tableViewer.setLabelProvider(new LabelProviderImpl());
- _tableViewer.setSorter(tableSorter);
- _table.setSortColumn(_table.getColumn(0));
- _table.setSortDirection(SWT.UP);
-
- Composite buttonsComposite = _toolkit.createComposite(viewChannelsGroup);
- gridData = new GridData(SWT.RIGHT, SWT.BOTTOM, false, false);
- buttonsComposite.setLayoutData(gridData);
- buttonsComposite.setLayout(new GridLayout(2,false));
-
- final Button commitButton = _toolkit.createButton(buttonsComposite, "Commit Transactions", SWT.PUSH);
- commitButton.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
- commitButton.setEnabled(false);
- commitButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- int selectionIndex = _table.getSelectionIndex();
-
- if (selectionIndex != -1)
- {
- final CompositeData selectedChannel = (CompositeData)_table.getItem(selectionIndex).getData();
- Integer id = (Integer) selectedChannel.get(CHAN_ID);
-
- int response = ViewUtility.popupOkCancelConfirmationMessage("Commit Transactions",
- "Commit transactions for channel:" + id + " ?");
-
- if (response == SWT.OK)
- {
- try
- {
- _cmb.commitTransactions(id);
- ViewUtility.operationResultFeedback(null, "Commited transactions", null);
- }
- catch (Exception e1)
- {
- ViewUtility.operationFailedStatusBarMessage("Error commiting transactions");
- MBeanUtility.handleException(_mbean, e1);
- }
-
- refresh(_mbean);;
- }
- }
- }
- });
-
- final Button rollbackButton = _toolkit.createButton(buttonsComposite, "Rollback Transactions", SWT.PUSH);
- rollbackButton.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
- rollbackButton.setEnabled(false);
- rollbackButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- int selectionIndex = _table.getSelectionIndex();
-
- if (selectionIndex != -1)
- {
- final CompositeData selectedChannel = (CompositeData)_table.getItem(selectionIndex).getData();
- Integer id = (Integer) selectedChannel.get(CHAN_ID);
-
- int response = ViewUtility.popupOkCancelConfirmationMessage("Rollback Transactions",
- "Rollback transactions for channel:" + id + " ?");
-
- if (response == SWT.OK)
- {
- try
- {
- _cmb.rollbackTransactions(id);
- ViewUtility.operationResultFeedback(null, "Rolled back transactions", null);
- }
- catch (Exception e1)
- {
- ViewUtility.operationFailedStatusBarMessage("Error rolling back transactions");
- MBeanUtility.handleException(_mbean, e1);
- }
-
- refresh(_mbean);;
- }
- }
-
- }
- });
-
- //listener for double clicking to open the selection mbean
- _table.addMouseListener(new MouseListener()
- {
- // MouseListener implementation
- public void mouseDoubleClick(MouseEvent event)
- {
- openMBean(_table);
- }
-
- public void mouseDown(MouseEvent e){}
- public void mouseUp(MouseEvent e){}
- });
-
- _tableViewer.addSelectionChangedListener(new ISelectionChangedListener(){
- public void selectionChanged(SelectionChangedEvent evt)
- {
- int selectionIndex = _table.getSelectionIndex();
-
- if (selectionIndex != -1)
- {
- final CompositeData selectedChannel = (CompositeData)_table.getItem(selectionIndex).getData();
- Boolean transactional = (Boolean) selectedChannel.get(TRANSACTIONAL);
-
- if(transactional)
- {
- rollbackButton.setEnabled(true);
- commitButton.setEnabled(true);
- }
- else
- {
- rollbackButton.setEnabled(false);
- commitButton.setEnabled(false);
- }
- }
- else
- {
- rollbackButton.setEnabled(false);
- commitButton.setEnabled(true);
- }
- }
- });
-
- Composite opsComposite = _toolkit.createComposite(_paramsComposite);
- gridData = new GridData(SWT.LEFT, SWT.FILL, false, true);
- opsComposite.setLayoutData(gridData);
- opsComposite.setLayout(new GridLayout(3,false));
-
- Group closeConnectionGroup = new Group(opsComposite, SWT.SHADOW_NONE);
- closeConnectionGroup.setBackground(opsComposite.getBackground());
- closeConnectionGroup.setText("Close Connection");
- gridData = new GridData(SWT.LEFT, SWT.TOP, true, false);
- closeConnectionGroup.setLayoutData(gridData);
- closeConnectionGroup.setLayout(new GridLayout());
-
- final Button closeConnectionButton = _toolkit.createButton(closeConnectionGroup, "Close Connection", SWT.PUSH);
- closeConnectionButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- int response = ViewUtility.popupOkCancelConfirmationMessage("Close Connection",
- "Are you sure you wish to close the Connection?");
-
- if (response == SWT.OK)
- {
- try
- {
- _cmb.closeConnection();
- }
- catch (Exception e1)
- {
- MBeanUtility.handleException(_mbean, e1);
- }
- }
- }
- });
- }
-
-
- /**
- * Content Provider class for the table viewer
- */
- private static class ContentProviderImpl implements IStructuredContentProvider
- {
-
- public void inputChanged(Viewer v, Object oldInput, Object newInput)
- {
-
- }
-
- public void dispose()
- {
-
- }
-
- public Object[] getElements(Object parent)
- {
- Collection<Object> rowCollection = ((TabularDataSupport) parent).values();
-
- return rowCollection.toArray();
- }
- }
-
- /**
- * Label Provider class for the table viewer
- */
- private static class LabelProviderImpl extends LabelProvider implements ITableLabelProvider
- {
- public String getColumnText(Object element, int columnIndex)
- {
- switch (columnIndex)
- {
- case 0 : // id column
- return String.valueOf(((CompositeDataSupport) element).get(CHAN_ID));
- case 1 : // transactional column
- return String.valueOf(((CompositeDataSupport) element).get(TRANSACTIONAL));
- case 2 : // num unacked msgs column
- return String.valueOf(((CompositeDataSupport) element).get(UNACKED_COUNT));
- case 3 : // default queue column
- return String.valueOf(((CompositeDataSupport) element).get(DEFAULT_QUEUE));
- case 4 : // flow blocked column
- return String.valueOf(((CompositeDataSupport) element).get(FLOW_BLOCKED));
- default :
- return "-";
- }
- }
-
- public Image getColumnImage(Object element, int columnIndex)
- {
- return null;
- }
-
- }
-
- /**
- * Sorter class for the table viewer.
- *
- */
- public static class TableSorter extends ViewerSorter
- {
- private int column;
- private static final int ASCENDING = 0;
- private static final int DESCENDING = 1;
-
- private int direction = DESCENDING;
-
- public TableSorter()
- {
- this.column = 0;
- direction = ASCENDING;
- }
-
- public void setColumn(int column)
- {
- if (column == this.column)
- {
- // Same column as last sort; toggle the direction
- direction = 1 - direction;
- }
- else
- {
- // New column; do an ascending sort
- this.column = column;
- direction = ASCENDING;
- }
- }
-
- @Override
- public int compare(Viewer viewer, Object e1, Object e2)
- {
- CompositeData chan1 = (CompositeData) e1;
- CompositeData chan2 = (CompositeData) e2;
-
- int comparison = 0;
- switch(column)
- {
- case 0:
- comparison = ((Integer) chan1.get(CHAN_ID)).compareTo((Integer)chan2.get(CHAN_ID));
- break;
- case 1:
- comparison = String.valueOf(chan1.get(TRANSACTIONAL)).compareTo(
- String.valueOf(chan2.get(TRANSACTIONAL)));
- break;
- case 2:
- comparison = ((Long) chan1.get(UNACKED_COUNT)).compareTo((Long)chan2.get(UNACKED_COUNT));
- break;
- case 3:
- comparison = String.valueOf(chan1.get(DEFAULT_QUEUE)).compareTo(
- String.valueOf(chan2.get(DEFAULT_QUEUE)));
- break;
- case 4:
- comparison = String.valueOf(chan1.get(FLOW_BLOCKED)).compareTo(
- String.valueOf(chan2.get(FLOW_BLOCKED)));
- break;
- default:
- comparison = 0;
- }
- // If descending order, flip the direction
- if(direction == DESCENDING)
- {
- comparison = -comparison;
- }
- return comparison;
- }
- }
-
- private void openMBean(Table table)
- {
- int selectionIndex = table.getSelectionIndex();
-
- if (selectionIndex == -1)
- {
- return;
- }
-
- CompositeData channelResult = (CompositeData) table.getItem(selectionIndex).getData();
- String queueName = (String) channelResult.get(DEFAULT_QUEUE);
-
- if(queueName == null)
- {
- return;
- }
-
- ServerRegistry serverRegistry = ApplicationRegistry.getServerRegistry(_mbean);
- ManagedBean selectedMBean = serverRegistry.getQueue(queueName, _mbean.getVirtualHostName());
-
- if(selectedMBean == null)
- {
- ViewUtility.popupErrorMessage("Error", "Unable to retrieve the selected MBean to open it");
- return;
- }
-
- IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- MBeanView view = (MBeanView) window.getActivePage().findView(MBeanView.ID);
- try
- {
- view.openMBean(selectedMBean);
- }
- catch (Exception ex)
- {
- MBeanUtility.handleException(selectedMBean, ex);
- }
- }
-
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/exchange/ExchangeOperationsTabControl.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/exchange/ExchangeOperationsTabControl.java
deleted file mode 100644
index b51cb85427..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/exchange/ExchangeOperationsTabControl.java
+++ /dev/null
@@ -1,722 +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.management.ui.views.exchange;
-
-import static org.apache.qpid.management.common.mbeans.ManagedExchange.BINDING_KEY;
-import static org.apache.qpid.management.common.mbeans.ManagedExchange.QUEUE_NAMES;
-import static org.apache.qpid.management.ui.Constants.EXCHANGE_TYPE;
-import static org.apache.qpid.management.ui.Constants.DIRECT_EXCHANGE;
-import static org.apache.qpid.management.ui.Constants.FANOUT_EXCHANGE;
-import static org.apache.qpid.management.ui.Constants.TOPIC_EXCHANGE;
-
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-
-import javax.management.MBeanServerConnection;
-import javax.management.MBeanServerInvocationHandler;
-import javax.management.openmbean.CompositeData;
-import javax.management.openmbean.CompositeDataSupport;
-import javax.management.openmbean.TabularDataSupport;
-
-import org.apache.qpid.management.ui.ApiVersion;
-import org.apache.qpid.management.ui.ApplicationRegistry;
-import org.apache.qpid.management.ui.ManagedBean;
-import org.apache.qpid.management.ui.ServerRegistry;
-import org.apache.qpid.management.common.mbeans.ManagedExchange;
-import org.apache.qpid.management.ui.jmx.JMXManagedObject;
-import org.apache.qpid.management.ui.jmx.MBeanUtility;
-import org.apache.qpid.management.ui.views.MBeanView;
-import org.apache.qpid.management.ui.views.TabControl;
-import org.apache.qpid.management.ui.views.ViewUtility;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.ITableLabelProvider;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerSorter;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.MouseEvent;
-import org.eclipse.swt.events.MouseListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.TabFolder;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.TableColumn;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.ScrolledForm;
-
-
-/**
- * Control class for the Exchange mbean Operations tab.
- */
-public class ExchangeOperationsTabControl extends TabControl
-{
- private FormToolkit _toolkit;
- private ScrolledForm _form;
- private Table _keysTable = null;
- private TableViewer _keysTableViewer = null;
- private Table _queuesTable = null;
- private TableViewer _queuesTableViewer = null;
- private Composite _paramsComposite = null;
-
- private TabularDataSupport _bindings = null;
- private ManagedExchange _emb;
- private ApiVersion _ApiVersion;
-
- public ExchangeOperationsTabControl(TabFolder tabFolder, JMXManagedObject mbean, MBeanServerConnection mbsc)
- {
- super(tabFolder);
- _mbean = mbean;
- _ApiVersion = ApplicationRegistry.getServerRegistry(mbean).getManagementApiVersion();
- _emb = (ManagedExchange) MBeanServerInvocationHandler.newProxyInstance(mbsc,
- mbean.getObjectName(), ManagedExchange.class, false);
- _toolkit = new FormToolkit(_tabFolder.getDisplay());
- _form = _toolkit.createScrolledForm(_tabFolder);
- _form.getBody().setLayout(new GridLayout());
- createComposites();
- createWidgets();
- }
-
- private void createComposites()
- {
- _paramsComposite = _toolkit.createComposite(_form.getBody(), SWT.NONE);
- _paramsComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- _paramsComposite.setLayout(new GridLayout());
- }
-
- /**
- * @see TabControl#getControl()
- */
- public Control getControl()
- {
- return _form;
- }
-
- /**
- * @see TabControl#setFocus()
- */
- public void setFocus()
- {
- _keysTable.setFocus();
- }
-
- @Override
- public void refresh(ManagedBean mbean)
- {
- _bindings = null;
- try
- {
- //gather a list of all keys and queues for display and selection
- _bindings = (TabularDataSupport) _emb.bindings();
- }
- catch (Exception e)
- {
- MBeanUtility.handleException(_mbean,e);
- }
-
- _keysTableViewer.setInput(_bindings);
-
- //if we have a Qpid JMX API 1.3+ server
- if(_ApiVersion.greaterThanOrEqualTo(1, 3))
- {
- //if it is a fanout exchange
- if(isFanoutExchange())
- {
- //if there are any queue bindings, there is a single wildcard binding key
- //auto-select it to show all the queues bound to the exchange
- if (_keysTable.getItemCount() == 1)
- {
- _keysTable.setSelection(0);
- updateQueuesTable();
- }
- }
- }
-
- layout();
- }
-
- public void layout()
- {
- _form.layout(true);
- _form.getBody().layout(true, true);
- }
-
- private void createWidgets()
- {
- Group bindingsGroup = new Group(_paramsComposite, SWT.SHADOW_NONE);
- bindingsGroup.setBackground(_paramsComposite.getBackground());
- bindingsGroup.setText("Bindings");
- bindingsGroup.setLayout(new GridLayout(2,false));
- GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
- bindingsGroup.setLayoutData(gridData);
-
- Composite tablesComposite = _toolkit.createComposite(bindingsGroup);
- gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
- gridData.minimumHeight = 250;
- gridData.heightHint = 250;
- tablesComposite.setLayoutData(gridData);
- tablesComposite.setLayout(new GridLayout(2,false));
-
- _keysTable = new Table (tablesComposite, SWT.SINGLE | SWT.SCROLL_LINE | SWT.BORDER | SWT.FULL_SELECTION);
- _keysTable.setLinesVisible(true);
- _keysTable.setHeaderVisible(true);
- GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
- _keysTable.setLayoutData(data);
-
- _keysTableViewer = new TableViewer(_keysTable);
- final TableSorter tableSorter = new TableSorter(BINDING_KEY);
-
- String[] titles = {"Binding Key"};
- int[] bounds = {200};
- for (int i = 0; i < titles.length; i++)
- {
- final int index = i;
- final TableColumn column = new TableColumn (_keysTable, SWT.NONE);
-
- column.setText(titles[i]);
- column.setWidth(bounds[i]);
- column.setResizable(true);
-
- //Setting the right sorter
- column.addSelectionListener(new SelectionAdapter()
- {
- @Override
- public void widgetSelected(SelectionEvent e)
- {
- tableSorter.setColumn(index);
- final TableViewer viewer = _keysTableViewer;
- int dir = viewer .getTable().getSortDirection();
- if (viewer.getTable().getSortColumn() == column)
- {
- dir = dir == SWT.UP ? SWT.DOWN : SWT.UP;
- }
- else
- {
- dir = SWT.UP;
- }
- viewer.getTable().setSortDirection(dir);
- viewer.getTable().setSortColumn(column);
- viewer.refresh();
- }
- });
-
- }
-
- _keysTableViewer.setContentProvider(new ContentProviderImpl(BINDING_KEY));
- _keysTableViewer.setLabelProvider(new LabelProviderImpl(BINDING_KEY));
- _keysTableViewer.setSorter(tableSorter);
- _keysTable.setSortColumn(_keysTable.getColumn(0));
- _keysTable.setSortDirection(SWT.UP);
-
-
- _queuesTable = new Table (tablesComposite, SWT.SINGLE | SWT.SCROLL_LINE | SWT.BORDER | SWT.FULL_SELECTION);
- _queuesTable.setLinesVisible (true);
- _queuesTable.setHeaderVisible (true);
- data = new GridData(SWT.FILL, SWT.FILL, true, true);
- _queuesTable.setLayoutData(data);
-
- _queuesTableViewer = new TableViewer(_queuesTable);
- final TableSorter queuesTableSorter = new TableSorter(QUEUE_NAMES);
-
- titles = new String[]{"Queue Names"};
- bounds = new int[]{225};
- for (int i = 0; i < titles.length; i++)
- {
- final int index = i;
- final TableColumn column = new TableColumn (_queuesTable, SWT.NONE);
-
- column.setText(titles[i]);
- column.setWidth(bounds[i]);
- column.setResizable(true);
-
- //Setting the right sorter
- column.addSelectionListener(new SelectionAdapter()
- {
- @Override
- public void widgetSelected(SelectionEvent e)
- {
- queuesTableSorter.setColumn(index);
- final TableViewer viewer = _queuesTableViewer;
- int dir = viewer .getTable().getSortDirection();
- if (viewer.getTable().getSortColumn() == column)
- {
- dir = dir == SWT.UP ? SWT.DOWN : SWT.UP;
- }
- else
- {
- dir = SWT.UP;
- }
- viewer.getTable().setSortDirection(dir);
- viewer.getTable().setSortColumn(column);
- viewer.refresh();
- }
- });
-
- }
-
- _queuesTableViewer.setContentProvider(new ContentProviderImpl(QUEUE_NAMES));
- _queuesTableViewer.setLabelProvider(new LabelProviderImpl(QUEUE_NAMES));
- _queuesTableViewer.setSorter(queuesTableSorter);
- _queuesTable.setSortColumn(_queuesTable.getColumn(0));
- _queuesTable.setSortDirection(SWT.UP);
- _queuesTableViewer.setInput(new String[]{"Select a binding key to view queues"});
-
- //listener for double clicking to open the selection mbean
- _queuesTable.addMouseListener(new MouseListener()
- {
- // MouseListener implementation
- public void mouseDoubleClick(MouseEvent event)
- {
- openMBean(_queuesTable);
- }
-
- public void mouseDown(MouseEvent e){}
- public void mouseUp(MouseEvent e){}
- });
-
- _keysTableViewer.addSelectionChangedListener(new ISelectionChangedListener(){
- public void selectionChanged(SelectionChangedEvent evt)
- {
- updateQueuesTable();
- }
- });
-
- //Side Buttons
- Composite buttonsComposite = _toolkit.createComposite(bindingsGroup);
- gridData = new GridData(SWT.FILL, SWT.FILL, false, true);
- buttonsComposite.setLayoutData(gridData);
- buttonsComposite.setLayout(new GridLayout());
-
- final Button createBindingButton = _toolkit.createButton(buttonsComposite, "Create ...", SWT.PUSH);
- createBindingButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- createNewBinding(createBindingButton.getShell());
- }
- });
-
- if(_ApiVersion.greaterThanOrEqualTo(1, 9)
- && (isDirectExchange() ||isTopicExchange()))
- {
- final Button removeBindingButton = _toolkit.createButton(buttonsComposite, "Delete ...", SWT.PUSH);
- removeBindingButton.setEnabled(false);
- removeBindingButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- removeBinding(removeBindingButton.getShell());
- }
- });
-
- _queuesTableViewer.addSelectionChangedListener(new ISelectionChangedListener(){
- public void selectionChanged(SelectionChangedEvent evt)
- {
- int selectionIndex = _queuesTable.getSelectionIndex();
-
- if (selectionIndex != -1)
- {
- removeBindingButton.setEnabled(true);
- }
- else
- {
- removeBindingButton.setEnabled(false);
- }
- }
- });
- }
- }
-
- private void updateQueuesTable()
- {
- int selectionIndex = _keysTable.getSelectionIndex();
-
- if (selectionIndex != -1)
- {
- final CompositeData selectedMsg = (CompositeData)_keysTable.getItem(selectionIndex).getData();
-
- String[] queues = (String[]) selectedMsg.get(QUEUE_NAMES);
- _queuesTableViewer.setInput(queues);
- }
- else
- {
- _queuesTableViewer.setInput(new String[]{"Select a binding key to view queues"});
- }
- }
-
- private boolean isFanoutExchange()
- {
- return _mbean.getProperty(EXCHANGE_TYPE).equalsIgnoreCase(FANOUT_EXCHANGE);
- }
-
- private boolean isDirectExchange()
- {
- return _mbean.getProperty(EXCHANGE_TYPE).equalsIgnoreCase(DIRECT_EXCHANGE);
- }
-
- private boolean isTopicExchange()
- {
- return _mbean.getProperty(EXCHANGE_TYPE).equalsIgnoreCase(TOPIC_EXCHANGE);
- }
-
- /**
- * Content Provider class for the table viewer
- */
- private static class ContentProviderImpl implements IStructuredContentProvider
- {
- String type;
-
- public ContentProviderImpl(String type)
- {
- this.type = type;
- }
-
- public void inputChanged(Viewer v, Object oldInput, Object newInput)
- {
-
- }
-
- public void dispose()
- {
-
- }
-
- public Object[] getElements(Object parent)
- {
- if(type.equals(BINDING_KEY))
- {
- Collection<Object> rowCollection = ((TabularDataSupport) parent).values();
-
- return rowCollection.toArray();
- }
- else
- {
- //we have the list of queues, return directly
- return (String[]) parent;
- }
- }
- }
-
- /**
- * Label Provider class for the routing key table viewer
- */
- private static class LabelProviderImpl extends LabelProvider implements ITableLabelProvider
- {
- String type;
-
- public LabelProviderImpl(String type)
- {
- this.type = type;
- }
-
- public String getColumnText(Object element, int columnIndex)
- {
- if(type.equals(BINDING_KEY)) //binding num and queue name table
- {
- switch (columnIndex)
- {
- case 0 : // key column
- return String.valueOf(((CompositeDataSupport) element).get(BINDING_KEY));
- default :
- return "";
- }
- }
- else //binding key-value pair table
- {
- switch (columnIndex)
- {
- case 0 : //queue name column
- return String.valueOf(element);
- default :
- return "";
- }
- }
- }
-
- public Image getColumnImage(Object element, int columnIndex)
- {
- return null;
- }
- }
-
- /**
- * Sorter class for the table viewer.
- *
- */
- public static class TableSorter extends ViewerSorter
- {
- private int column;
- private static final int ASCENDING = 0;
- private static final int DESCENDING = 1;
-
- private int direction = DESCENDING;
-
- private String type;
-
- public TableSorter(String type)
- {
- this.type = type;
- this.column = 0;
- direction = ASCENDING;
- }
-
- public void setColumn(int column)
- {
- if (column == this.column)
- {
- // Same column as last sort; toggle the direction
- direction = 1 - direction;
- }
- else
- {
- // New column; do an ascending sort
- this.column = column;
- direction = ASCENDING;
- }
- }
-
- @Override
- public int compare(Viewer viewer, Object e1, Object e2)
- {
- int comparison = 0;
-
- if(type.equals(BINDING_KEY))//binding num and queue name table
- {
- CompositeData binding1 = (CompositeData) e1;
- CompositeData binding2 = (CompositeData) e2;
-
- switch(column)
- {
- case 0:
- comparison = ((String) binding1.get(BINDING_KEY)).compareTo((String) binding2.get(BINDING_KEY));
- break;
- default:
- comparison = 0;
- }
- }
- else //binding key-value pair table
- {
- switch(column)
- {
- case 0:
- comparison = ((String)e1).compareTo((String) e2);
- break;
- default:
- comparison = 0;
- }
- }
-
-
- // If descending order, flip the direction
- if(direction == DESCENDING)
- {
- comparison = -comparison;
- }
- return comparison;
- }
- }
-
- private void createNewBinding(Shell parent)
- {
- final Shell shell = ViewUtility.createModalDialogShell(parent, "Create New Binding");
-
- Composite destinationComposite = _toolkit.createComposite(shell, SWT.NONE);
- destinationComposite.setBackground(shell.getBackground());
- destinationComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- destinationComposite.setLayout(new GridLayout(2,false));
-
- _toolkit.createLabel(destinationComposite,"Queue:").setBackground(shell.getBackground());
- final Combo destinationCombo = new Combo(destinationComposite,SWT.NONE | SWT.READ_ONLY);
- destinationCombo.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
-
- Composite bindingComposite = _toolkit.createComposite(shell, SWT.NONE);
- bindingComposite.setBackground(shell.getBackground());
- bindingComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- bindingComposite.setLayout(new GridLayout(2,false));
-
- _toolkit.createLabel(bindingComposite,"Binding:").setBackground(shell.getBackground());
- final Text bindingText = new Text(bindingComposite, SWT.BORDER);
- bindingText.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- if(isFanoutExchange())
- {
- bindingText.setText("*");
- }
-
- Composite okCancelButtonsComp = _toolkit.createComposite(shell);
- okCancelButtonsComp.setBackground(shell.getBackground());
- okCancelButtonsComp.setLayoutData(new GridData(SWT.RIGHT, SWT.FILL, true, true));
- okCancelButtonsComp.setLayout(new GridLayout(2,false));
-
- Button okButton = _toolkit.createButton(okCancelButtonsComp, "OK", SWT.PUSH);
- okButton.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, false));
- Button cancelButton = _toolkit.createButton(okCancelButtonsComp, "Cancel", SWT.PUSH);
- cancelButton.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, false));
-
- List<String> queueList = ApplicationRegistry.getServerRegistry(_mbean).getQueueNames(_mbean.getVirtualHostName());
-
- if(queueList.size() == 0)
- {
- destinationCombo.setItems(new String[]{"No queues available"});
- okButton.setEnabled(false);
- }
- else
- {
- Collections.sort(queueList);
- destinationCombo.setItems(queueList.toArray(new String[0]));
- }
- destinationCombo.select(0);
-
- okButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- String binding = bindingText.getText();
-
- if (!isFanoutExchange() && (binding == null || binding.length() == 0))
- {
- ViewUtility.popupErrorMessage("Create New Binding", "Please enter a valid binding");
- return;
- }
-
- String destQueue = destinationCombo.getItem(destinationCombo.getSelectionIndex()).toString();
-
- shell.dispose();
-
- try
- {
- _emb.createNewBinding(destQueue, binding);
- ViewUtility.operationResultFeedback(null, "Created new Binding", null);
- }
- catch (Exception e4)
- {
- ViewUtility.operationFailedStatusBarMessage("Error creating new Binding");
- MBeanUtility.handleException(_mbean, e4);
- }
-
- refresh(_mbean);
- }
- });
-
- cancelButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- shell.dispose();
- }
- });
-
- shell.setDefaultButton(okButton);
- shell.pack();
- ViewUtility.centerChildInParentShell(parent, shell);
-
- shell.open();
- }
-
- private void removeBinding(Shell parent)
- {
- int selectionIndex = _keysTable.getSelectionIndex();
- if (selectionIndex == -1)
- {
- return;
- }
-
- final CompositeData selectedBindingRecord = (CompositeData)_keysTable.getItem(selectionIndex).getData();
-
- final String bindingKey = (String) selectedBindingRecord.get(BINDING_KEY);
-
- selectionIndex = _queuesTable.getSelectionIndex();
- if (selectionIndex == -1)
- {
- return;
- }
-
- final String queueName = (String)_queuesTable.getItem(selectionIndex).getData();
-
-
- int response = ViewUtility.popupOkCancelConfirmationMessage("Delete Binding",
- "Delete the following binding?\n\n" +
- "Binding Key: " + bindingKey + "\n" +
- "Queue: " + queueName + "\n" +
- "Exchange: " + _mbean.getName());
-
- if (response == SWT.OK)
- {
- try
- {
- _emb.removeBinding(queueName, bindingKey);
- ViewUtility.operationResultFeedback(null, "Removed Binding", null);
- }
- catch (Exception e)
- {
- ViewUtility.operationFailedStatusBarMessage("Error removing Binding");
- MBeanUtility.handleException(_mbean, e);
- }
-
- refresh(_mbean);
- }
- }
-
- private void openMBean(Table table)
- {
- int selectionIndex = table.getSelectionIndex();
-
- if (selectionIndex == -1)
- {
- return;
- }
-
- String queueName = (String) table.getItem(selectionIndex).getData();
- ServerRegistry serverRegistry = ApplicationRegistry.getServerRegistry(_mbean);
- ManagedBean selectedMBean = serverRegistry.getQueue(queueName, _mbean.getVirtualHostName());
-
- if(selectedMBean == null)
- {
- ViewUtility.popupErrorMessage("Error", "Unable to retrieve the selected MBean to open it");
- return;
- }
-
- IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- MBeanView view = (MBeanView) window.getActivePage().findView(MBeanView.ID);
- try
- {
- view.openMBean(selectedMBean);
- }
- catch (Exception ex)
- {
- MBeanUtility.handleException(selectedMBean, ex);
- }
- }
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/exchange/HeadersExchangeOperationsTabControl.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/exchange/HeadersExchangeOperationsTabControl.java
deleted file mode 100644
index e22898fb93..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/exchange/HeadersExchangeOperationsTabControl.java
+++ /dev/null
@@ -1,711 +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.management.ui.views.exchange;
-
-import static org.apache.qpid.management.common.mbeans.ManagedExchange.HDR_BINDING_NUMBER;
-import static org.apache.qpid.management.common.mbeans.ManagedExchange.HDR_QUEUE_BINDINGS;
-import static org.apache.qpid.management.common.mbeans.ManagedExchange.HDR_QUEUE_NAME;
-
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-
-import javax.management.MBeanServerConnection;
-import javax.management.MBeanServerInvocationHandler;
-import javax.management.openmbean.CompositeData;
-import javax.management.openmbean.CompositeDataSupport;
-import javax.management.openmbean.TabularDataSupport;
-
-import org.apache.qpid.management.ui.ApplicationRegistry;
-import org.apache.qpid.management.ui.ManagedBean;
-import org.apache.qpid.management.ui.ServerRegistry;
-import org.apache.qpid.management.common.mbeans.ManagedExchange;
-import org.apache.qpid.management.ui.jmx.JMXManagedObject;
-import org.apache.qpid.management.ui.jmx.MBeanUtility;
-import org.apache.qpid.management.ui.views.MBeanView;
-import org.apache.qpid.management.ui.views.TabControl;
-import org.apache.qpid.management.ui.views.ViewUtility;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.ITableLabelProvider;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerSorter;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.ScrolledComposite;
-import org.eclipse.swt.events.MouseEvent;
-import org.eclipse.swt.events.MouseListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.TabFolder;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.TableColumn;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.ScrolledForm;
-
-
-/**
- * Control class for the Headers Exchange mbean Operations tab.
- */
-public class HeadersExchangeOperationsTabControl extends TabControl
-{
- private FormToolkit _toolkit;
- private ScrolledForm _form;
- private Table _bindingNumberTable = null;
- private TableViewer _bindingNumberTableViewer = null;
- private Table _headersTable = null;
- private TableViewer _headersTableViewer = null;
- private Composite _paramsComposite = null;
-
- private TabularDataSupport _bindings = null;
- private ManagedExchange _emb;
-
- public HeadersExchangeOperationsTabControl(TabFolder tabFolder, JMXManagedObject mbean, MBeanServerConnection mbsc)
- {
- super(tabFolder);
- _mbean = mbean;
- _emb = (ManagedExchange) MBeanServerInvocationHandler.newProxyInstance(mbsc,
- mbean.getObjectName(), ManagedExchange.class, false);
- _toolkit = new FormToolkit(_tabFolder.getDisplay());
- _form = _toolkit.createScrolledForm(_tabFolder);
- _form.getBody().setLayout(new GridLayout());
- createComposites();
- createWidgets();
- }
-
- private void createComposites()
- {
- _paramsComposite = _toolkit.createComposite(_form.getBody(), SWT.NONE);
- _paramsComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- _paramsComposite.setLayout(new GridLayout());
- }
-
- /**
- * @see TabControl#getControl()
- */
- public Control getControl()
- {
- return _form;
- }
-
- /**
- * @see TabControl#setFocus()
- */
- public void setFocus()
- {
- _bindingNumberTable.setFocus();
- }
-
- @Override
- public void refresh(ManagedBean mbean)
- {
-
- _bindings = null;
- try
- {
- //gather a list of all keys and queues for display and selection
- _bindings = (TabularDataSupport) _emb.bindings();
- }
- catch (Exception e)
- {
- MBeanUtility.handleException(_mbean,e);
- }
-
- _bindingNumberTableViewer.setInput(_bindings);
-
- layout();
- }
-
- public void layout()
- {
- _form.layout(true);
- _form.getBody().layout(true, true);
- }
-
- private void createWidgets()
- {
- Group bindingsGroup = new Group(_paramsComposite, SWT.SHADOW_NONE);
- bindingsGroup.setBackground(_paramsComposite.getBackground());
- bindingsGroup.setText("Bindings");
- bindingsGroup.setLayout(new GridLayout(2,false));
- GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
- bindingsGroup.setLayoutData(gridData);
-
- Composite tablesComposite = _toolkit.createComposite(bindingsGroup);
- gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
- gridData.minimumHeight = 250;
- gridData.heightHint = 250;
- tablesComposite.setLayoutData(gridData);
- tablesComposite.setLayout(new GridLayout(2,false));
-
- //table of bindings for the exchange
- _bindingNumberTable = new Table (tablesComposite, SWT.SINGLE | SWT.SCROLL_LINE | SWT.BORDER | SWT.FULL_SELECTION);
- _bindingNumberTable.setLinesVisible(true);
- _bindingNumberTable.setHeaderVisible(true);
- GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
- data.minimumHeight = 300;
- data.heightHint = 300;
- _bindingNumberTable.setLayoutData(data);
-
- _bindingNumberTableViewer = new TableViewer(_bindingNumberTable);
- final TableSorter tableSorter = new TableSorter(HDR_BINDING_NUMBER);
-
- String[] titles = {"Binding Number", "Queue Name"};
- int[] bounds = {135, 175};
- for (int i = 0; i < titles.length; i++)
- {
- final int index = i;
- final TableColumn column = new TableColumn (_bindingNumberTable, SWT.NONE);
-
- column.setText(titles[i]);
- column.setWidth(bounds[i]);
- column.setResizable(true);
-
- //Setting the right sorter
- column.addSelectionListener(new SelectionAdapter()
- {
- @Override
- public void widgetSelected(SelectionEvent e)
- {
- tableSorter.setColumn(index);
- final TableViewer viewer = _bindingNumberTableViewer;
- int dir = viewer .getTable().getSortDirection();
- if (viewer.getTable().getSortColumn() == column)
- {
- dir = dir == SWT.UP ? SWT.DOWN : SWT.UP;
- }
- else
- {
- dir = SWT.UP;
- }
- viewer.getTable().setSortDirection(dir);
- viewer.getTable().setSortColumn(column);
- viewer.refresh();
- }
- });
-
- }
-
- _bindingNumberTableViewer.setContentProvider(new ContentProviderImpl(HDR_BINDING_NUMBER));
- _bindingNumberTableViewer.setLabelProvider(new LabelProviderImpl(HDR_BINDING_NUMBER));
- _bindingNumberTableViewer.setSorter(tableSorter);
- _bindingNumberTable.setSortColumn(_bindingNumberTable.getColumn(0));
- _bindingNumberTable.setSortDirection(SWT.UP);
-
- //table of header bindings
- _headersTable = new Table (tablesComposite, SWT.SINGLE | SWT.SCROLL_LINE | SWT.BORDER | SWT.FULL_SELECTION);
- _headersTable.setLinesVisible (true);
- _headersTable.setHeaderVisible (true);
- data = new GridData(SWT.FILL, SWT.FILL, true, true);
- data.minimumHeight = 300;
- data.heightHint = 300;
- _headersTable.setLayoutData(data);
-
- _headersTableViewer = new TableViewer(_headersTable);
- final TableSorter queuesTableSorter = new TableSorter(HDR_QUEUE_BINDINGS);
-
- titles = new String[]{"Header Bindings"};
- bounds = new int[]{225};
- for (int i = 0; i < titles.length; i++)
- {
- final int index = i;
- final TableColumn column = new TableColumn (_headersTable, SWT.NONE);
-
- column.setText(titles[i]);
- column.setWidth(bounds[i]);
- column.setResizable(true);
-
- //Setting the right sorter
- column.addSelectionListener(new SelectionAdapter()
- {
- @Override
- public void widgetSelected(SelectionEvent e)
- {
- queuesTableSorter.setColumn(index);
- final TableViewer viewer = _headersTableViewer;
- int dir = viewer .getTable().getSortDirection();
- if (viewer.getTable().getSortColumn() == column)
- {
- dir = dir == SWT.UP ? SWT.DOWN : SWT.UP;
- }
- else
- {
- dir = SWT.UP;
- }
- viewer.getTable().setSortDirection(dir);
- viewer.getTable().setSortColumn(column);
- viewer.refresh();
- }
- });
-
- }
-
- _headersTableViewer.setContentProvider(new ContentProviderImpl(HDR_QUEUE_BINDINGS));
- _headersTableViewer.setLabelProvider(new LabelProviderImpl(HDR_QUEUE_BINDINGS));
- _headersTableViewer.setSorter(queuesTableSorter);
- _headersTable.setSortColumn(_headersTable.getColumn(0));
- _headersTable.setSortDirection(SWT.UP);
- _headersTableViewer.setInput(new String[]{"Select a binding to view key-value pairs"});
-
- _bindingNumberTableViewer.addSelectionChangedListener(new ISelectionChangedListener(){
- public void selectionChanged(SelectionChangedEvent evt)
- {
- int selectionIndex = _bindingNumberTable.getSelectionIndex();
-
- if (selectionIndex != -1)
- {
- final CompositeData selectedMsg = (CompositeData)_bindingNumberTable.getItem(selectionIndex).getData();
-
- String[] bindings = (String[]) selectedMsg.get(HDR_QUEUE_BINDINGS);
- _headersTableViewer.setInput(bindings);
- }
- else
- {
- _headersTableViewer.setInput(new String[]{"Select a binding to view key-value pairs"});
- }
- }
- });
-
- //listener for double clicking to open the selection mbean
- _bindingNumberTable.addMouseListener(new MouseListener()
- {
- // MouseListener implementation
- public void mouseDoubleClick(MouseEvent event)
- {
- openMBean(_bindingNumberTable);
- }
-
- public void mouseDown(MouseEvent e){}
- public void mouseUp(MouseEvent e){}
- });
-
- //Side Buttons
- Composite buttonsComposite = _toolkit.createComposite(bindingsGroup);
- gridData = new GridData(SWT.FILL, SWT.FILL, false, true);
- buttonsComposite.setLayoutData(gridData);
- buttonsComposite.setLayout(new GridLayout());
-
- final Button createBindingButton = _toolkit.createButton(buttonsComposite, "Create ...", SWT.PUSH);
- createBindingButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- createNewBinding(createBindingButton.getShell());
- }
- });
-
- }
-
-
- /**
- * Content Provider class for the table viewer
- */
- private static class ContentProviderImpl implements IStructuredContentProvider
- {
- String type;
-
- public ContentProviderImpl(String type)
- {
- this.type = type;
- }
-
- public void inputChanged(Viewer v, Object oldInput, Object newInput)
- {
-
- }
-
- public void dispose()
- {
-
- }
-
- public Object[] getElements(Object parent)
- {
- if(type.equals(HDR_BINDING_NUMBER))
- {
- Collection<Object> rowCollection = ((TabularDataSupport) parent).values();
-
- return rowCollection.toArray();
- }
- else
- {
- //we have the list of bindings, return directly
- return (String[]) parent;
- }
- }
- }
-
- /**
- * Label Provider class for the routing key table viewer
- */
- private static class LabelProviderImpl extends LabelProvider implements ITableLabelProvider
- {
- String type;
-
- public LabelProviderImpl(String type)
- {
- this.type = type;
- }
-
- public String getColumnText(Object element, int columnIndex)
- {
- if(type.equals(HDR_BINDING_NUMBER)) //binding num and queue name table
- {
- switch (columnIndex)
- {
- case 0 : // binding number column
- return String.valueOf(((CompositeDataSupport) element).get(HDR_BINDING_NUMBER));
- case 1 : // queue name column
- return (String) ((CompositeDataSupport) element).get(HDR_QUEUE_NAME);
- default :
- return "";
- }
- }
- else //binding key-value pair table
- {
- switch (columnIndex)
- {
- case 0 : //header binding column
- return String.valueOf(element);
- default :
- return "";
- }
- }
- }
-
- public Image getColumnImage(Object element, int columnIndex)
- {
- return null;
- }
- }
-
- /**
- * Sorter class for the table viewer.
- *
- */
- public static class TableSorter extends ViewerSorter
- {
- private int column;
- private static final int ASCENDING = 0;
- private static final int DESCENDING = 1;
-
- private int direction = DESCENDING;
-
- private String type;
-
- public TableSorter(String type)
- {
- this.type = type;
- this.column = 0;
- direction = ASCENDING;
- }
-
- public void setColumn(int column)
- {
- if (column == this.column)
- {
- // Same column as last sort; toggle the direction
- direction = 1 - direction;
- }
- else
- {
- // New column; do an ascending sort
- this.column = column;
- direction = ASCENDING;
- }
- }
-
- @Override
- public int compare(Viewer viewer, Object e1, Object e2)
- {
- int comparison = 0;
-
- if(type.equals(HDR_BINDING_NUMBER)) //binding num and queue name table
- {
- CompositeData binding1 = (CompositeData) e1;
- CompositeData binding2 = (CompositeData) e2;
-
- switch(column)
- {
- case 0: // binding number column
- comparison = ((Integer) binding1.get(HDR_BINDING_NUMBER)).compareTo((Integer) binding2.get(HDR_BINDING_NUMBER));
- break;
- case 1: // queue name column
- comparison = ((String) binding1.get(HDR_QUEUE_NAME)).compareTo((String) binding2.get(HDR_QUEUE_NAME));
- break;
- default:
- comparison = 0;
- }
- }
- else //binding key-value pair table
- {
- switch(column)
- {
- case 0: //header binding column
- comparison = ((String)e1).compareTo((String) e2);
- break;
- default:
- comparison = 0;
- }
- }
-
- // If descending order, flip the direction
- if(direction == DESCENDING)
- {
- comparison = -comparison;
- }
- return comparison;
- }
- }
-
- private void createNewBinding(Shell parent)
- {
- final Shell shell = ViewUtility.createModalDialogShell(parent, "Create New Binding");
-
- Composite queueNameComposite = _toolkit.createComposite(shell, SWT.NONE);
- queueNameComposite.setBackground(shell.getBackground());
- GridData layoutData = new GridData(SWT.CENTER, SWT.TOP, true, false);
- layoutData.minimumWidth = 300;
- queueNameComposite.setLayoutData(layoutData);
- queueNameComposite.setLayout(new GridLayout(2,false));
-
- _toolkit.createLabel(queueNameComposite,"Queue:").setBackground(shell.getBackground());
- final Combo destinationCombo = new Combo(queueNameComposite,SWT.NONE | SWT.READ_ONLY);
- destinationCombo.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
-
- final ScrolledComposite scrolledComposite = new ScrolledComposite(shell, SWT.V_SCROLL);
- scrolledComposite.setExpandHorizontal(true);
- scrolledComposite.setLayout(new GridLayout());
- scrolledComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- scrolledComposite.setBackground(shell.getBackground());
-
- final Composite bindingComposite = _toolkit.createComposite(scrolledComposite, SWT.NONE);
- bindingComposite.setBackground(scrolledComposite.getBackground());
- bindingComposite.setLayout(new GridLayout(2,true));
- layoutData = new GridData(SWT.FILL, SWT.TOP, true, false);
- bindingComposite.setLayoutData(layoutData);
- scrolledComposite.setContent(bindingComposite);
-
- Composite addMoreButtonComp = _toolkit.createComposite(shell);
- addMoreButtonComp.setBackground(shell.getBackground());
- addMoreButtonComp.setLayoutData(new GridData(SWT.RIGHT, SWT.FILL, true, true));
- addMoreButtonComp.setLayout(new GridLayout());
-
- final Button addMoreButton = _toolkit.createButton(addMoreButtonComp, "Add additional field", SWT.PUSH);
-
- Composite okCancelButtonsComp = _toolkit.createComposite(shell);
- okCancelButtonsComp.setBackground(shell.getBackground());
- okCancelButtonsComp.setLayoutData(new GridData(SWT.RIGHT, SWT.FILL, true, true));
- okCancelButtonsComp.setLayout(new GridLayout(2,false));
-
- Button okButton = _toolkit.createButton(okCancelButtonsComp, "OK", SWT.PUSH);
- okButton.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, false));
- Button cancelButton = _toolkit.createButton(okCancelButtonsComp, "Cancel", SWT.PUSH);
- cancelButton.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, false));
-
- List<String> queueList = ApplicationRegistry.getServerRegistry(_mbean).getQueueNames(_mbean.getVirtualHostName());
-
- if(queueList.size() == 0)
- {
- destinationCombo.setItems(new String[]{"No queues available"});
- okButton.setEnabled(false);
- }
- else
- {
- Collections.sort(queueList);
- destinationCombo.setItems(queueList.toArray(new String[0]));
- }
- destinationCombo.select(0);
-
- final HashMap<Text, Text> headerBindingHashMap = new HashMap<Text, Text>();
-
- //add headings
- Label keyLabel = _toolkit.createLabel(bindingComposite,"Key:");
- keyLabel.setBackground(bindingComposite.getBackground());
- keyLabel.setLayoutData(new GridData(SWT.CENTER, SWT.TOP, true, false));
-
- Label valueLabel = _toolkit.createLabel(bindingComposite,"Value:");
- valueLabel.setBackground(bindingComposite.getBackground());
- valueLabel.setLayoutData(new GridData(SWT.CENTER, SWT.TOP, true, false));
-
- //add the x-match key by default and offer a comobo to select its value
- final Text xmatchKeyText = new Text(bindingComposite, SWT.BORDER);
- xmatchKeyText.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- xmatchKeyText.setText("x-match");
- xmatchKeyText.setEditable(false);
-
- final Combo xmatchValueCombo = new Combo(bindingComposite,SWT.NONE | SWT.READ_ONLY);
- xmatchValueCombo.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- xmatchValueCombo.setItems(new String[]{"any", "all"});
- xmatchValueCombo.select(0);
-
- //make some empty key-value fields
- for(int i=0; i < 4; i++)
- {
- Text keyText = new Text(bindingComposite, SWT.BORDER);
- Text valueText = new Text(bindingComposite, SWT.BORDER);
- keyText.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- valueText.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
-
- headerBindingHashMap.put(keyText, valueText);
- }
- bindingComposite.setSize(bindingComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT));
-
- //allow adding more fields for additional key-value pairs
- addMoreButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- Text keyText = new Text(bindingComposite, SWT.BORDER);
- Text valueText = new Text(bindingComposite, SWT.BORDER);
- keyText.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- valueText.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
-
- headerBindingHashMap.put(keyText, valueText);
-
- bindingComposite.setSize(bindingComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT));
- bindingComposite.layout(true);
- scrolledComposite.layout(true);
- }
- });
-
- okButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- String xMatchString = xmatchValueCombo.getText();
-
- String destQueue = destinationCombo.getItem(destinationCombo.getSelectionIndex()).toString();
-
- StringBuffer bindingValue = new StringBuffer();
-
- //insert the x-match key-value pair
- if (xMatchString.equalsIgnoreCase("any"))
- {
- bindingValue.append("x-match=any");
- }
- else
- {
- bindingValue.append("x-match=all");
- }
-
- //insert the other key-value pairs
- for (Text keyText : headerBindingHashMap.keySet())
- {
-
- String key = keyText.getText();
- if(key == null || key.length() == 0)
- {
- continue;
- }
-
- Text valueText = headerBindingHashMap.get(keyText);
- String value = valueText.getText();
-
- bindingValue.append(",");
- bindingValue.append(key + "=");
- //empty values are permitted, signalling only key-presence is required
- if(value != null && value.length() > 0)
- {
- bindingValue.append(value);
- }
- }
-
- shell.dispose();
-
- try
- {
- _emb.createNewBinding(destQueue, bindingValue.toString());
- ViewUtility.operationResultFeedback(null, "Created new Binding", null);
- }
- catch (Exception e4)
- {
- ViewUtility.operationFailedStatusBarMessage("Error creating new Binding");
- MBeanUtility.handleException(_mbean, e4);
- }
-
- refresh(_mbean);
- }
- });
-
- cancelButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- shell.dispose();
- }
- });
-
- shell.setDefaultButton(okButton);
- shell.pack();
- ViewUtility.centerChildInParentShell(parent, shell);
-
- shell.open();
- }
-
- private void openMBean(Table table)
- {
- int selectionIndex = table.getSelectionIndex();
-
- if (selectionIndex == -1)
- {
- return;
- }
-
- CompositeData bindingResult = (CompositeData) table.getItem(selectionIndex).getData();
- String queueName = (String) bindingResult.get(HDR_QUEUE_NAME);
- ServerRegistry serverRegistry = ApplicationRegistry.getServerRegistry(_mbean);
- ManagedBean selectedMBean = serverRegistry.getQueue(queueName, _mbean.getVirtualHostName());
-
- if(selectedMBean == null)
- {
- ViewUtility.popupErrorMessage("Error", "Unable to retrieve the selected MBean to open it");
- return;
- }
-
- IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- MBeanView view = (MBeanView) window.getActivePage().findView(MBeanView.ID);
- try
- {
- view.openMBean(selectedMBean);
- }
- catch (Exception ex)
- {
- MBeanUtility.handleException(selectedMBean, ex);
- }
- }
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/logging/ConfigurationFileTabControl.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/logging/ConfigurationFileTabControl.java
deleted file mode 100644
index 1ae48f5c6c..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/logging/ConfigurationFileTabControl.java
+++ /dev/null
@@ -1,591 +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.management.ui.views.logging;
-
-import static org.apache.qpid.management.common.mbeans.LoggingManagement.LOGGER_LEVEL;
-import static org.apache.qpid.management.common.mbeans.LoggingManagement.LOGGER_NAME;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-
-import javax.management.MBeanServerConnection;
-import javax.management.MBeanServerInvocationHandler;
-import javax.management.openmbean.CompositeData;
-import javax.management.openmbean.TabularDataSupport;
-
-import static org.apache.qpid.management.ui.Constants.FONT_BOLD;
-
-import org.apache.qpid.management.ui.ApiVersion;
-import org.apache.qpid.management.ui.ApplicationRegistry;
-import org.apache.qpid.management.ui.ManagedBean;
-import org.apache.qpid.management.common.mbeans.LoggingManagement;
-import org.apache.qpid.management.ui.jmx.JMXManagedObject;
-import org.apache.qpid.management.ui.jmx.MBeanUtility;
-import org.apache.qpid.management.ui.views.TabControl;
-import org.apache.qpid.management.ui.views.ViewUtility;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.TableViewerColumn;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.MouseEvent;
-import org.eclipse.swt.events.MouseListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.TabFolder;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.TableColumn;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.ScrolledForm;
-
-
-/**
- * Control class for the LoggingManagement mbean ConfigFile Options tab.
- */
-public class ConfigurationFileTabControl extends TabControl
-{
- private FormToolkit _toolkit;
- private ScrolledForm _form;
- private Table _table = null;
- private TableViewer _tableViewer = null;
- private Composite _headerComposite = null;
- private Composite _paramsComposite = null;
-
- private Label _configFileRootLoggerLevelLabel = null;
- private Label _logWatchIntervalLabel = null;
- private String[] _availableLoggerLevels;
- private TabularDataSupport _configFileLoggerLevels = null;
- private LoggingManagement _lmmb;
- private ApiVersion _ApiVersion;
-
- public ConfigurationFileTabControl(TabFolder tabFolder, JMXManagedObject mbean, MBeanServerConnection mbsc)
- {
- super(tabFolder);
- _mbean = mbean;
- _lmmb = (LoggingManagement)
- MBeanServerInvocationHandler.newProxyInstance(mbsc, mbean.getObjectName(),
- LoggingManagement.class, false);
- _ApiVersion = ApplicationRegistry.getServerRegistry(mbean).getManagementApiVersion();
- _toolkit = new FormToolkit(_tabFolder.getDisplay());
- _form = _toolkit.createScrolledForm(_tabFolder);
- _form.getBody().setLayout(new GridLayout());
- createComposites();
- createWidgets();
- }
-
- private void createComposites()
- {
-
- _headerComposite = _toolkit.createComposite(_form.getBody(), SWT.NONE);
- _headerComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- _headerComposite.setLayout(new GridLayout());
-
- _paramsComposite = _toolkit.createComposite(_form.getBody(), SWT.NONE);
- _paramsComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- _paramsComposite.setLayout(new GridLayout());
- }
-
- /**
- * @see TabControl#getControl()
- */
- public Control getControl()
- {
- return _form;
- }
-
- /**
- * @see TabControl#setFocus()
- */
- public void setFocus()
- {
- _table.setFocus();
- }
-
- @Override
- public void refresh(ManagedBean mbean)
- {
- String configFileRootLoggerLevel = "-";
- try
- {
- configFileRootLoggerLevel = _lmmb.getConfigFileRootLoggerLevel();
- }
- catch (Exception e1)
- {
- MBeanUtility.handleException(_mbean, e1);
- }
-
- int log4jLogWatchInterval = -1;
- try
- {
- log4jLogWatchInterval = _lmmb.getLog4jLogWatchInterval();
- }
- catch (Exception e2)
- {
- MBeanUtility.handleException(_mbean, e2);
- }
-
- _configFileLoggerLevels = null;
- try
- {
- _configFileLoggerLevels = (TabularDataSupport) _lmmb.viewConfigFileLoggerLevels();
- }
- catch (Exception e3)
- {
- MBeanUtility.handleException(_mbean, e3);
- }
-
- _configFileRootLoggerLevelLabel.setText(String.valueOf(configFileRootLoggerLevel));
- if (log4jLogWatchInterval == 0)
- {
- _logWatchIntervalLabel.setText("Disabled (0 sec)");
- }
- else
- {
- _logWatchIntervalLabel.setText(String.valueOf(log4jLogWatchInterval) + " seconds");
- }
- _tableViewer.setInput(_configFileLoggerLevels);
-
- layout();
- }
-
- public void layout()
- {
- _form.layout(true);
- _form.getBody().layout(true, true);
- }
-
- private void createWidgets()
- {
- try
- {
- _availableLoggerLevels = _lmmb.getAvailableLoggerLevels();
- }
- catch(Exception e)
- {
- _availableLoggerLevels = new String[]{"ALL","TRACE","DEBUG","INFO","WARN","ERROR","FATAL","OFF"};
- }
-
- Label noteLabel = _toolkit.createLabel(_headerComposite,
- "NOTE: These options modify the configuration file. " +
- "Changes only take effect automatically if LogWatch is enabled.");
- Label noteLabel2 = _toolkit.createLabel(_headerComposite,
- "A child Logger set to a non-inherited Level in the Runtime tab " +
- "will retain that value after the file is reloaded.");
- GridData gridData = new GridData(SWT.FILL, SWT.FILL, false, true);
- noteLabel.setLayoutData(gridData);
- gridData = new GridData(SWT.FILL, SWT.FILL, false, true);
- noteLabel2.setLayoutData(gridData);
-
- Group configFileLoggerLevelsGroup = new Group(_paramsComposite, SWT.SHADOW_NONE);
- configFileLoggerLevelsGroup.setBackground(_paramsComposite.getBackground());
- configFileLoggerLevelsGroup.setText("Configuration File Logger Levels");
- configFileLoggerLevelsGroup.setLayout(new GridLayout());
- gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
- configFileLoggerLevelsGroup.setLayoutData(gridData);
-
- Composite tableComposite = _toolkit.createComposite(configFileLoggerLevelsGroup);
- gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
- gridData.heightHint = 250;
- gridData.minimumHeight = 250;
- tableComposite.setLayoutData(gridData);
- GridLayout gridLayout = new GridLayout();
-
- tableComposite.setLayout(gridLayout);
-
- _table = new Table (tableComposite, SWT.MULTI | SWT.SCROLL_LINE | SWT.BORDER | SWT.FULL_SELECTION);
- _table.setLinesVisible (true);
- _table.setHeaderVisible (true);
- GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
- _table.setLayoutData(data);
-
- _tableViewer = new TableViewer(_table);
- final LoggingTableSorter tableSorter = new LoggingTableSorter();
-
- String[] titles = { LOGGER_NAME, LOGGER_LEVEL };
- int[] bounds = { 600, 75 };
- for (int i = 0; i < titles.length; i++)
- {
- final int index = i;
- final TableViewerColumn viewerColumn = new TableViewerColumn(_tableViewer, SWT.NONE);
- final TableColumn column = viewerColumn.getColumn();
-
- column.setText(titles[i]);
- column.setWidth(bounds[i]);
- column.setResizable(true);
-
- //Setting the right sorter
- column.addSelectionListener(new SelectionAdapter()
- {
- @Override
- public void widgetSelected(SelectionEvent e)
- {
- tableSorter.setColumn(index);
- final TableViewer viewer = _tableViewer;
- int dir = viewer .getTable().getSortDirection();
- if (viewer.getTable().getSortColumn() == column)
- {
- dir = dir == SWT.UP ? SWT.DOWN : SWT.UP;
- }
- else
- {
- dir = SWT.UP;
- }
- viewer.getTable().setSortDirection(dir);
- viewer.getTable().setSortColumn(column);
- viewer.refresh();
- }
- });
-
- }
-
- _tableViewer.setContentProvider(new LoggingTableContentProvider());
- _tableViewer.setLabelProvider(new LoggingTableLabelProvider());
- _tableViewer.setSorter(tableSorter);
- _table.setSortColumn(_table.getColumn(0));
- _table.setSortDirection(SWT.UP);
- _table.addMouseListener(new MouseListener()
- {
- public void mouseDoubleClick(MouseEvent event)
- {
- editLoggerLevel(_table.getShell());
- }
-
- public void mouseDown(MouseEvent e){}
- public void mouseUp(MouseEvent e){}
- });
-
- final Button logLevelEditButton = _toolkit.createButton(configFileLoggerLevelsGroup, "Edit Selected Logger(s)...", SWT.PUSH);
- logLevelEditButton.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
- logLevelEditButton.setEnabled(false);
- logLevelEditButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- editLoggerLevel(logLevelEditButton.getShell());
- }
- });
-
- _tableViewer.addSelectionChangedListener(new ISelectionChangedListener(){
- public void selectionChanged(SelectionChangedEvent evt)
- {
- int selectionIndex = _table.getSelectionIndex();
-
- if(selectionIndex != -1)
- {
- logLevelEditButton.setEnabled(true);
- }
- else
- {
- logLevelEditButton.setEnabled(false);
- }
- }
- });
-
-
- Composite attributesComposite = _toolkit.createComposite(_paramsComposite);
- gridData = new GridData(SWT.LEFT, SWT.FILL, false, true);
- attributesComposite.setLayoutData(gridData);
- gridLayout = new GridLayout(3,false);
- attributesComposite.setLayout(gridLayout);
-
- Group configFileRootLoggerLevelGroup = new Group(attributesComposite, SWT.SHADOW_NONE);
- configFileRootLoggerLevelGroup.setBackground(attributesComposite.getBackground());
- configFileRootLoggerLevelGroup.setText("Config File RootLogger Level");
- gridData = new GridData(SWT.LEFT, SWT.TOP, true, false);
- configFileRootLoggerLevelGroup.setLayoutData(gridData);
- configFileRootLoggerLevelGroup.setLayout(new GridLayout(2,false));
-
- _configFileRootLoggerLevelLabel = _toolkit.createLabel(configFileRootLoggerLevelGroup, "-");
- _configFileRootLoggerLevelLabel.setFont(ApplicationRegistry.getFont(FONT_BOLD));
- _configFileRootLoggerLevelLabel.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false));
-
- final Button configFileRootLoggerLevelButton = _toolkit.createButton(configFileRootLoggerLevelGroup, "Edit ...", SWT.PUSH);
- configFileRootLoggerLevelButton.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, true, false));
- configFileRootLoggerLevelButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- editRootLoggerLevel(configFileRootLoggerLevelButton.getShell());
- }
- });
-
-
- Group logWatchIntervalGroup = new Group(attributesComposite, SWT.SHADOW_NONE);
- logWatchIntervalGroup.setBackground(attributesComposite.getBackground());
- logWatchIntervalGroup.setText("LogWatch Interval");
- gridData = new GridData(SWT.LEFT, SWT.FILL, true, false);
- logWatchIntervalGroup.setLayoutData(gridData);
- logWatchIntervalGroup.setLayout(new GridLayout());
-
- _logWatchIntervalLabel = _toolkit.createLabel(logWatchIntervalGroup, "-");
- _logWatchIntervalLabel.setFont(ApplicationRegistry.getFont(FONT_BOLD));
- _logWatchIntervalLabel.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, true));
-
- if(_ApiVersion.greaterThanOrEqualTo(1, 4))
- {
- Group reloadConfigFileGroup = new Group(attributesComposite, SWT.SHADOW_NONE);
- reloadConfigFileGroup.setBackground(attributesComposite.getBackground());
- reloadConfigFileGroup.setText("Reload Configuration File");
- gridData = new GridData(SWT.LEFT, SWT.TOP, true, false);
- reloadConfigFileGroup.setLayoutData(gridData);
- reloadConfigFileGroup.setLayout(new GridLayout());
-
- final Button reloadConfigFileButton = _toolkit.createButton(reloadConfigFileGroup, "Reload Config File", SWT.PUSH);
- reloadConfigFileButton.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false));
- reloadConfigFileButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- int response = ViewUtility.popupOkCancelConfirmationMessage("Reload",
- "Reload Logging Configuration File?");
- if (response == SWT.OK)
- {
- try
- {
- _lmmb.reloadConfigFile();
- ViewUtility.operationResultFeedback(null, "Reloaded Logging Configuration File", null);
-
- }
- catch (Exception ex)
- {
- ViewUtility.operationFailedStatusBarMessage("Error Reloading Logging Configuration File");
- MBeanUtility.handleException(_mbean, ex);
- }
-
- refresh(_mbean);;
- }
- }
- });
- }
- }
-
-
-
- private void editLoggerLevel(Shell parent)
- {
- int selectionIndex = _table.getSelectionIndex();
-
- if (selectionIndex != -1)
- {
- int[] selectedIndices = _table.getSelectionIndices();
-
- final ArrayList<String> selectedLoggers = new ArrayList<String>();
-
- for(int index = 0; index < selectedIndices.length ; index++)
- {
- CompositeData selectedLogger = (CompositeData)_table.getItem(selectedIndices[index]).getData();
- String user = (String) selectedLogger.get(LOGGER_NAME);
- selectedLoggers.add(user);
- }
-
- final Shell shell = ViewUtility.createModalDialogShell(parent, "Set Config File Logger Level(s)");
-
- _toolkit.createLabel(shell, "Logger(s): ").setBackground(shell.getBackground());
-
- final Text headerText = new Text(shell, SWT.WRAP | SWT.V_SCROLL | SWT.BORDER );
- headerText.setEditable(false);
- GridData data = new GridData(SWT.FILL, SWT.FILL, false, false);
- data.minimumHeight = 125;
- data.heightHint = 125;
- data.minimumWidth = 575;
- data.widthHint = 575;
- headerText.setLayoutData(data);
-
- String lineSeperator = System.getProperty("line.separator");
- for(String loggerName : selectedLoggers)
- {
- headerText.append(loggerName + lineSeperator);
- }
- headerText.setSelection(0);
-
- Composite levelComp = _toolkit.createComposite(shell);
- levelComp.setBackground(shell.getBackground());
- levelComp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- levelComp.setLayout(new GridLayout(2,false));
-
- _toolkit.createLabel(levelComp,"Level: ").setBackground(levelComp.getBackground());
- final Combo levelCombo = new Combo (levelComp, SWT.READ_ONLY );
- levelCombo.setItems(_availableLoggerLevels);
- levelCombo.select(0);
-
- Composite okCancelButtonsComp = _toolkit.createComposite(shell);
- okCancelButtonsComp.setBackground(shell.getBackground());
- okCancelButtonsComp.setLayoutData(new GridData(SWT.RIGHT, SWT.FILL, true, true));
- okCancelButtonsComp.setLayout(new GridLayout(2,false));
-
- Button okButton = _toolkit.createButton(okCancelButtonsComp, "OK", SWT.PUSH);
- okButton.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, false));
- Button cancelButton = _toolkit.createButton(okCancelButtonsComp, "Cancel", SWT.PUSH);
- cancelButton.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, false));
-
- okButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- String level = levelCombo.getItem(levelCombo.getSelectionIndex()).toString();
-
- shell.close();
-
- try
- {
- HashMap<String,Boolean> results = new HashMap<String,Boolean>();
-
- //perform the updates, save the results.
- for(String logger : selectedLoggers)
- {
- boolean result = _lmmb.setConfigFileLoggerLevel(logger, level);
- results.put(logger, result);
- }
-
- //categorise the overall result
- boolean overallResult = true;
- for(boolean result : results.values())
- {
- if (!result)
- {
- overallResult = false;
- }
- }
-
- //output the result to status bar if all succeed, and dialogue if not
- if(overallResult)
- {
- ViewUtility.operationResultFeedback(overallResult, "Updated ConfigFile Logger Level(s)", null);
- }
- else
- {
- String failedToSetLevelOfLoggers = "";
- for(String logger : results.keySet())
- {
- if(!results.get(logger))
- {
- failedToSetLevelOfLoggers = failedToSetLevelOfLoggers.concat(logger + ", ");
- }
- }
-
- //cut off last ", "
- int lastIndex = failedToSetLevelOfLoggers.lastIndexOf(',');
- if (lastIndex != -1)
- {
- failedToSetLevelOfLoggers = failedToSetLevelOfLoggers.substring(0, lastIndex);
- }
-
- ViewUtility.operationResultFeedback(overallResult, null,
- "Failed to update ConfigFile Logger Level(s): "
- + failedToSetLevelOfLoggers);
- }
- }
- catch(Exception e4)
- {
- ViewUtility.operationFailedStatusBarMessage("Error updating Config File Logger Level(s)");
- MBeanUtility.handleException(_mbean, e4);
- }
-
- refresh(_mbean);
- }
- });
-
- cancelButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- shell.dispose();
- }
- });
-
- shell.setDefaultButton(okButton);
- shell.pack();
- ViewUtility.centerChildInParentShell(parent, shell);
-
- shell.open();
- }
- }
-
- private void editRootLoggerLevel(Shell parent)
- {
- final Shell shell = ViewUtility.createModalDialogShell(parent, "ConfigFile RootLogger Level");
-
- Composite levelComp = _toolkit.createComposite(shell);
- levelComp.setBackground(shell.getBackground());
- levelComp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- levelComp.setLayout(new GridLayout(2,false));
-
- _toolkit.createLabel(levelComp,"RootLogger level: ").setBackground(levelComp.getBackground());
- final Combo levelCombo = new Combo (levelComp, SWT.READ_ONLY );
- levelCombo.setItems(_availableLoggerLevels);
- levelCombo.select(0);
-
- Composite okCancelButtonsComp = _toolkit.createComposite(shell);
- okCancelButtonsComp.setBackground(shell.getBackground());
- okCancelButtonsComp.setLayoutData(new GridData(SWT.RIGHT, SWT.FILL, true, true));
- okCancelButtonsComp.setLayout(new GridLayout(2,false));
-
- Button okButton = _toolkit.createButton(okCancelButtonsComp, "OK", SWT.PUSH);
- okButton.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, false));
- Button cancelButton = _toolkit.createButton(okCancelButtonsComp, "Cancel", SWT.PUSH);
- cancelButton.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, false));
-
- okButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- String selection = levelCombo.getItem(levelCombo.getSelectionIndex()).toString();
- shell.dispose();
- try
- {
- boolean result = _lmmb.setConfigFileRootLoggerLevel(selection);
- ViewUtility.operationResultFeedback(result,
- "Updated ConfigFile RootLogger Level", "Failed to update ConfigFile RootLogger Level");
- }
- catch (Exception e5)
- {
- ViewUtility.operationFailedStatusBarMessage("Error updating ConfigFile RootLogger Level");
- MBeanUtility.handleException(_mbean, e5);
- }
- refresh(_mbean);
- }
- });
-
- cancelButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- shell.dispose();
- }
- });
-
- shell.setDefaultButton(okButton);
- shell.pack();
- ViewUtility.centerChildInParentShell(parent, shell);
-
- shell.open();
- }
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/logging/LoggingTableContentProvider.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/logging/LoggingTableContentProvider.java
deleted file mode 100644
index 6ef3ab70a7..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/logging/LoggingTableContentProvider.java
+++ /dev/null
@@ -1,52 +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.management.ui.views.logging;
-
-import java.util.Collection;
-
-import javax.management.openmbean.TabularDataSupport;
-
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.Viewer;
-
-/**
- * Content Provider class for theLogging Management table viewers
- */
-public class LoggingTableContentProvider implements IStructuredContentProvider
-{
-
- public void inputChanged(Viewer v, Object oldInput, Object newInput)
- {
-
- }
-
- public void dispose()
- {
-
- }
-
- public Object[] getElements(Object parent)
- {
- Collection<Object> rowCollection = ((TabularDataSupport) parent).values();
-
- return rowCollection.toArray();
- }
-} \ No newline at end of file
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/logging/LoggingTableLabelProvider.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/logging/LoggingTableLabelProvider.java
deleted file mode 100644
index 3156e3f1c4..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/logging/LoggingTableLabelProvider.java
+++ /dev/null
@@ -1,59 +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.management.ui.views.logging;
-
-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.openmbean.CompositeDataSupport;
-
-import org.eclipse.jface.viewers.ITableLabelProvider;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.swt.graphics.Image;
-
-/**
- * Label Provider class for the LoggingManagement table viewers
- */
-public class LoggingTableLabelProvider extends LabelProvider implements ITableLabelProvider
-{
- @Override
- public String getColumnText(Object element, int columnIndex)
- {
- switch (columnIndex)
- {
- case 0 : // logger name column
- return (String) ((CompositeDataSupport) element).get(LOGGER_NAME);
- case 1 : // logger level column
- return (String) ((CompositeDataSupport) element).get(LOGGER_LEVEL);
- default :
- return "-";
- }
- }
-
- @Override
- public Image getColumnImage(Object element, int columnIndex)
- {
- return null;
- }
-
-
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/logging/LoggingTableSorter.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/logging/LoggingTableSorter.java
deleted file mode 100644
index 99d22f2cb8..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/logging/LoggingTableSorter.java
+++ /dev/null
@@ -1,90 +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.management.ui.views.logging;
-
-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.openmbean.CompositeData;
-
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerSorter;
-
-/**
- * Sorter class for the Logging Management table viewers.
- */
-public class LoggingTableSorter extends ViewerSorter
-{
- private static final int ASCENDING = 0;
- private static final int DESCENDING = 1;
-
- private int column;
- private int direction;
-
- public LoggingTableSorter()
- {
- this.column = 0;
- direction = ASCENDING;
- }
-
- public void setColumn(int column)
- {
- if (column == this.column)
- {
- // Same column as last sort; toggle the direction
- direction = 1 - direction;
- }
- else
- {
- // New column; do an ascending sort
- this.column = column;
- direction = ASCENDING;
- }
- }
-
- @Override
- public int compare(Viewer viewer, Object e1, Object e2)
- {
- CompositeData logger1 = (CompositeData) e1;
- CompositeData logger2 = (CompositeData) e2;
-
- int comparison = 0;
- switch(column)
- {
- case 0:
- comparison = String.valueOf(logger1.get(LOGGER_NAME)).compareTo(
- String.valueOf(logger2.get(LOGGER_NAME)));
- break;
- case 1:
- comparison = String.valueOf(logger1.get(LOGGER_LEVEL)).compareTo(
- String.valueOf(logger2.get(LOGGER_LEVEL)));
- break;
- default:
- comparison = 0;
- }
- // If descending order, flip the direction
- if (direction == DESCENDING)
- {
- comparison = -comparison;
- }
- return comparison;
- }
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/logging/RuntimeTabControl.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/logging/RuntimeTabControl.java
deleted file mode 100644
index 1ae97cfcb6..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/logging/RuntimeTabControl.java
+++ /dev/null
@@ -1,595 +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.management.ui.views.logging;
-
-import static org.apache.qpid.management.common.mbeans.LoggingManagement.LOGGER_LEVEL;
-import static org.apache.qpid.management.common.mbeans.LoggingManagement.LOGGER_NAME;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-
-import javax.management.MBeanServerConnection;
-import javax.management.MBeanServerInvocationHandler;
-import javax.management.openmbean.CompositeData;
-import javax.management.openmbean.CompositeDataSupport;
-import javax.management.openmbean.TabularDataSupport;
-
-import static org.apache.qpid.management.ui.Constants.FONT_BOLD;
-
-import org.apache.qpid.management.common.mbeans.LoggingManagement;
-import org.apache.qpid.management.ui.ApplicationRegistry;
-import org.apache.qpid.management.ui.ManagedBean;
-import org.apache.qpid.management.ui.jmx.JMXManagedObject;
-import org.apache.qpid.management.ui.jmx.MBeanUtility;
-import org.apache.qpid.management.ui.views.TabControl;
-import org.apache.qpid.management.ui.views.ViewUtility;
-import org.eclipse.jface.viewers.IColorProvider;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.ITableLabelProvider;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.TableViewerColumn;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.MouseEvent;
-import org.eclipse.swt.events.MouseListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.TabFolder;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.TableColumn;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.ScrolledForm;
-
-
-/**
- * Control class for the LoggingManagement mbean Runtime Options tab.
- */
-public class RuntimeTabControl extends TabControl
-{
- private FormToolkit _toolkit;
- private ScrolledForm _form;
- private Table _table = null;
- private TableViewer _tableViewer = null;
- private Composite _headerComposite = null;
- private Composite _paramsComposite = null;
-
- private Label _runtimeRootLoggerLevelLabel = null;
- private String[] _availableLoggerLevels;
- private TabularDataSupport _runtimeLoggerLevels = null;
- private ArrayList<String> _configFileLoggerNames = new ArrayList<String>();
- private LoggingManagement _lmmb;
-
- public RuntimeTabControl(TabFolder tabFolder, JMXManagedObject mbean, MBeanServerConnection mbsc)
- {
- super(tabFolder);
- _mbean = mbean;
- _lmmb = (LoggingManagement)
- MBeanServerInvocationHandler.newProxyInstance(mbsc, mbean.getObjectName(),
- LoggingManagement.class, false);
- _toolkit = new FormToolkit(_tabFolder.getDisplay());
- _form = _toolkit.createScrolledForm(_tabFolder);
- _form.getBody().setLayout(new GridLayout());
- createComposites();
- createWidgets();
- }
-
- private void createComposites()
- {
-
- _headerComposite = _toolkit.createComposite(_form.getBody(), SWT.NONE);
- _headerComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- _headerComposite.setLayout(new GridLayout());
-
- _paramsComposite = _toolkit.createComposite(_form.getBody(), SWT.NONE);
- _paramsComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- _paramsComposite.setLayout(new GridLayout());
- }
-
- /**
- * @see TabControl#getControl()
- */
- public Control getControl()
- {
- return _form;
- }
-
- /**
- * @see TabControl#setFocus()
- */
- public void setFocus()
- {
- _table.setFocus();
- }
-
- @Override
- public void refresh(ManagedBean mbean)
- {
- String runtimeRootLoggerLevel = "-";
- try
- {
- runtimeRootLoggerLevel = _lmmb.getRuntimeRootLoggerLevel();
- }
- catch(Exception e1)
- {
- MBeanUtility.handleException(_mbean, e1);
- }
-
- _runtimeLoggerLevels = null;
- try
- {
- _runtimeLoggerLevels = (TabularDataSupport) _lmmb.viewEffectiveRuntimeLoggerLevels();
- }
- catch(Exception e2)
- {
- MBeanUtility.handleException(_mbean, e2);
- }
-
-
- try
- {
- TabularDataSupport confLoggers = (TabularDataSupport) _lmmb.viewConfigFileLoggerLevels();
- ArrayList<String> confLoggerNames = new ArrayList<String>();
-
- for(Object obj : confLoggers.values())
- {
- CompositeData comp = (CompositeData) obj;
- confLoggerNames.add((String) comp.get(LOGGER_NAME));
- }
-
- _configFileLoggerNames = confLoggerNames;
- }
- catch(Exception e2)
- {
- //dont signal the failure, just dont highlight the config file loggers, empty the existing list.
- _configFileLoggerNames.clear();
- }
-
- _runtimeRootLoggerLevelLabel.setText(String.valueOf(runtimeRootLoggerLevel));
- _tableViewer.setInput(_runtimeLoggerLevels);
-
- layout();
- }
-
- public void layout()
- {
- _form.layout(true);
- _form.getBody().layout(true, true);
- }
-
- private void createWidgets()
- {
- try
- {
- _availableLoggerLevels = _lmmb.getAvailableLoggerLevels();
- }
- catch(Exception e)
- {
- _availableLoggerLevels = new String[]{"ALL","TRACE","DEBUG","INFO","WARN","ERROR","FATAL","OFF"};
- }
-
- Label noteLabel = _toolkit.createLabel(_headerComposite,
- "NOTE: These options modify only the live runtime settings. " +
- "Non-default values will be lost following broker restart.");
- Label noteLabel2 = _toolkit.createLabel(_headerComposite,
- "Loggers currently defined in the configuration file are " +
- "highlighted. The other Loggers inherit a Level by default.");
- GridData gridData = new GridData(SWT.FILL, SWT.FILL, false, true);
- noteLabel.setLayoutData(gridData);
- gridData = new GridData(SWT.FILL, SWT.FILL, false, true);
- noteLabel2.setLayoutData(gridData);
-
- Group effectiveRuntimeLoggerLevelsGroup = new Group(_paramsComposite, SWT.SHADOW_NONE);
- effectiveRuntimeLoggerLevelsGroup.setBackground(_paramsComposite.getBackground());
- effectiveRuntimeLoggerLevelsGroup.setText("Effective Runtime Logger Levels");
- effectiveRuntimeLoggerLevelsGroup.setLayout(new GridLayout());
- gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
- effectiveRuntimeLoggerLevelsGroup.setLayoutData(gridData);
-
- Composite tableComposite = _toolkit.createComposite(effectiveRuntimeLoggerLevelsGroup);
- gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
- gridData.heightHint = 250;
- gridData.minimumHeight = 250;
- tableComposite.setLayoutData(gridData);
- GridLayout gridLayout = new GridLayout();
- tableComposite.setLayout(gridLayout);
-
- _table = new Table (tableComposite, SWT.MULTI | SWT.SCROLL_LINE | SWT.BORDER | SWT.FULL_SELECTION);
- _table.setLinesVisible (true);
- _table.setHeaderVisible (true);
- GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
- _table.setLayoutData(data);
-
- _tableViewer = new TableViewer(_table);
- final LoggingTableSorter tableSorter = new LoggingTableSorter();
-
- String[] titles = { LOGGER_NAME, LOGGER_LEVEL };
- int[] bounds = { 600, 75 };
- for (int i = 0; i < titles.length; i++)
- {
- final int index = i;
- final TableViewerColumn viewerColumn = new TableViewerColumn(_tableViewer, SWT.NONE);
- final TableColumn column = viewerColumn.getColumn();
-
- column.setText(titles[i]);
- column.setWidth(bounds[i]);
- column.setResizable(true);
-
- //Setting the right sorter
- column.addSelectionListener(new SelectionAdapter()
- {
- @Override
- public void widgetSelected(SelectionEvent e)
- {
- tableSorter.setColumn(index);
- final TableViewer viewer = _tableViewer;
- int dir = viewer.getTable().getSortDirection();
- if (viewer.getTable().getSortColumn() == column)
- {
- dir = (dir == SWT.UP ? SWT.DOWN : SWT.UP);
- }
- else
- {
- dir = SWT.UP;
- }
- viewer.getTable().setSortDirection(dir);
- viewer.getTable().setSortColumn(column);
- viewer.refresh();
- }
- });
-
- }
-
- _tableViewer.setContentProvider(new LoggingTableContentProvider());
- _tableViewer.setLabelProvider(new RuntimeLoggingTableLabelProvider());
- _tableViewer.setSorter(tableSorter);
- _table.setSortColumn(_table.getColumn(0));
- _table.setSortDirection(SWT.UP);
- _table.addMouseListener(new MouseListener()
- {
- public void mouseDoubleClick(MouseEvent event)
- {
- editLoggerLevel(_table.getShell());
- }
-
- public void mouseDown(MouseEvent e){}
- public void mouseUp(MouseEvent e){}
- });
-
- final Button logLevelEditButton = _toolkit.createButton(effectiveRuntimeLoggerLevelsGroup, "Edit Selected Logger(s)...", SWT.PUSH);
- logLevelEditButton.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
- logLevelEditButton.setEnabled(false);
- logLevelEditButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- editLoggerLevel(logLevelEditButton.getShell());
- }
- });
-
- _tableViewer.addSelectionChangedListener(new ISelectionChangedListener(){
- public void selectionChanged(SelectionChangedEvent evt)
- {
- int selectionIndex = _table.getSelectionIndex();
-
- if (selectionIndex != -1)
- {
- logLevelEditButton.setEnabled(true);
- }
- else
- {
- logLevelEditButton.setEnabled(false);
- }
- }
- });
-
- Composite attributesComposite = _toolkit.createComposite(_paramsComposite);
- gridData = new GridData(SWT.FILL, SWT.FILL, false, true);
- attributesComposite.setLayoutData(gridData);
- gridLayout = new GridLayout(3,false);
- attributesComposite.setLayout(gridLayout);
-
- Group runtimeRootLoggerGroup = new Group(attributesComposite, SWT.SHADOW_NONE);
- runtimeRootLoggerGroup.setBackground(attributesComposite.getBackground());
- runtimeRootLoggerGroup.setText("Runtime RootLogger Level");
- gridData = new GridData(SWT.LEFT, SWT.TOP, true, false);
- runtimeRootLoggerGroup.setLayoutData(gridData);
- runtimeRootLoggerGroup.setLayout(new GridLayout(2,false));
-
- _runtimeRootLoggerLevelLabel = _toolkit.createLabel(runtimeRootLoggerGroup, "-");
- _runtimeRootLoggerLevelLabel.setFont(ApplicationRegistry.getFont(FONT_BOLD));
- _runtimeRootLoggerLevelLabel.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false));
-
- final Button runtimeRootLoggerLevelButton = _toolkit.createButton(runtimeRootLoggerGroup, "Edit ...", SWT.PUSH);
- runtimeRootLoggerLevelButton.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, true, false));
- runtimeRootLoggerLevelButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- editRootLoggerLevel(runtimeRootLoggerLevelButton.getShell());
- }
- });
- }
-
- private void editLoggerLevel(Shell parent)
- {
- int selectionIndex = _table.getSelectionIndex();
-
- if (selectionIndex != -1)
- {
- int[] selectedIndices = _table.getSelectionIndices();
-
- final ArrayList<String> selectedLoggers = new ArrayList<String>();
-
- for(int index = 0; index < selectedIndices.length ; index++)
- {
- CompositeData selectedLogger = (CompositeData)_table.getItem(selectedIndices[index]).getData();
- String user = (String) selectedLogger.get(LOGGER_NAME);
- selectedLoggers.add(user);
- }
-
- final Shell shell = ViewUtility.createModalDialogShell(parent, "Set Runtime Logger Level(s)");
-
- _toolkit.createLabel(shell, "Logger(s): ").setBackground(shell.getBackground());
-
- final Text headerText = new Text(shell, SWT.WRAP | SWT.V_SCROLL | SWT.BORDER );
- headerText.setEditable(false);
- GridData data = new GridData(SWT.FILL, SWT.FILL, false, false);
- data.minimumHeight = 125;
- data.heightHint = 125;
- data.minimumWidth = 575;
- data.widthHint = 575;
- headerText.setLayoutData(data);
-
- String lineSeperator = System.getProperty("line.separator");
- for(String loggerName : selectedLoggers)
- {
- headerText.append(loggerName + lineSeperator);
- }
- headerText.setSelection(0);
-
- Composite levelComp = _toolkit.createComposite(shell);
- levelComp.setBackground(shell.getBackground());
- levelComp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- levelComp.setLayout(new GridLayout(2,false));
-
- _toolkit.createLabel(levelComp,"Level: ").setBackground(levelComp.getBackground());
- final Combo levelCombo = new Combo (levelComp, SWT.READ_ONLY );
- levelCombo.setItems(_availableLoggerLevels);
- levelCombo.select(0);
-
- Composite okCancelButtonsComp = _toolkit.createComposite(shell);
- okCancelButtonsComp.setBackground(shell.getBackground());
- okCancelButtonsComp.setLayoutData(new GridData(SWT.RIGHT, SWT.FILL, true, true));
- okCancelButtonsComp.setLayout(new GridLayout(2,false));
-
- Button okButton = _toolkit.createButton(okCancelButtonsComp, "OK", SWT.PUSH);
- okButton.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, false));
- Button cancelButton = _toolkit.createButton(okCancelButtonsComp, "Cancel", SWT.PUSH);
- cancelButton.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, false));
-
- okButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- String level = levelCombo.getItem(levelCombo.getSelectionIndex()).toString();
-
- shell.close();
-
- try
- {
- HashMap<String,Boolean> results = new HashMap<String,Boolean>();
-
- //perform the updates, save the results.
- for(String logger : selectedLoggers)
- {
- boolean result = _lmmb.setRuntimeLoggerLevel(logger, level);
- results.put(logger, result);
- }
-
- //categorise the overall result
- boolean overallResult = true;
- for(boolean result : results.values())
- {
- if (!result)
- {
- overallResult = false;
- }
- }
-
- //output the result to status bar if all succeed, and dialogue if not
- if(overallResult)
- {
- ViewUtility.operationResultFeedback(overallResult, "Updated Runtime Logger Level(s)", null);
- }
- else
- {
- String failedToSetLevelOfLoggers = "";
- for(String logger : results.keySet())
- {
- if(!results.get(logger))
- {
- failedToSetLevelOfLoggers = failedToSetLevelOfLoggers.concat(logger + ", ");
- }
- }
-
- //cut off last ", "
- int lastIndex = failedToSetLevelOfLoggers.lastIndexOf(',');
- if (lastIndex != -1)
- {
- failedToSetLevelOfLoggers = failedToSetLevelOfLoggers.substring(0, lastIndex);
- }
-
- ViewUtility.operationResultFeedback(overallResult, null,
- "Failed to update Runtime Logger Level(s): "
- + failedToSetLevelOfLoggers);
- }
- }
- catch(Exception e3)
- {
- ViewUtility.operationFailedStatusBarMessage("Error updating Runtime Logger Level(s)");
- MBeanUtility.handleException(_mbean, e3);
- }
-
- refresh(_mbean);
- }
- });
-
- cancelButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- shell.dispose();
- }
- });
-
- shell.setDefaultButton(okButton);
- shell.pack();
- ViewUtility.centerChildInParentShell(parent, shell);
-
- shell.open();
- }
- }
-
- private void editRootLoggerLevel(Shell parent)
- {
- final Shell shell = ViewUtility.createModalDialogShell(parent, "Runtime RootLogger Level");
-
- Composite levelComp = _toolkit.createComposite(shell);
- levelComp.setBackground(shell.getBackground());
- levelComp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- levelComp.setLayout(new GridLayout(2,false));
-
- _toolkit.createLabel(levelComp,"RootLogger level: ").setBackground(levelComp.getBackground());
- final Combo levelCombo = new Combo (levelComp, SWT.READ_ONLY );
- levelCombo.setItems(_availableLoggerLevels);
- levelCombo.select(0);
-
- Composite okCancelButtonsComp = _toolkit.createComposite(shell);
- okCancelButtonsComp.setBackground(shell.getBackground());
- okCancelButtonsComp.setLayoutData(new GridData(SWT.RIGHT, SWT.FILL, true, true));
- okCancelButtonsComp.setLayout(new GridLayout(2,false));
-
- Button okButton = _toolkit.createButton(okCancelButtonsComp, "OK", SWT.PUSH);
- okButton.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, false));
- Button cancelButton = _toolkit.createButton(okCancelButtonsComp, "Cancel", SWT.PUSH);
- cancelButton.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, false));
-
- okButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- String selection = levelCombo.getItem(levelCombo.getSelectionIndex()).toString();
- shell.dispose();
-
- try
- {
- boolean result = _lmmb.setRuntimeRootLoggerLevel(selection);
- ViewUtility.operationResultFeedback(result,
- "Updated Runtime RootLogger Level", "Failed to update Runtime Logger Level");
- }
- catch(Exception e4)
- {
- ViewUtility.operationFailedStatusBarMessage("Error updating Runtime Logger Level");
- MBeanUtility.handleException(_mbean, e4);
- }
-
- refresh(_mbean);
- }
- });
-
- cancelButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- shell.dispose();
- }
- });
-
- shell.setDefaultButton(okButton);
- shell.pack();
- ViewUtility.centerChildInParentShell(parent, shell);
-
- shell.open();
- }
-
- /**
- * Label Provider class for the RuntimeLoggers table viewer
- */
- public class RuntimeLoggingTableLabelProvider extends LabelProvider implements ITableLabelProvider, IColorProvider
- {
-
- @Override
- public String getColumnText(Object element, int columnIndex)
- {
- switch (columnIndex)
- {
- case 0 : // logger name column
- return (String) ((CompositeDataSupport) element).get(LOGGER_NAME);
- case 1 : // logger level column
- return (String) ((CompositeDataSupport) element).get(LOGGER_LEVEL);
- default :
- return "-";
- }
- }
-
- @Override
- public Image getColumnImage(Object element, int columnIndex)
- {
- return null;
- }
-
- @Override
- public Color getBackground(Object element)
- {
- return null;
- }
-
- @Override
- public Color getForeground(Object element)
- {
- String loggerName = (String) ((CompositeData) element).get(LOGGER_NAME);
- if(_configFileLoggerNames.contains(loggerName))
- {
- return Display.getCurrent().getSystemColor(SWT.COLOR_BLUE);
- }
- else
- {
- return null;
- }
- }
-
-
- }
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/queue/QueueOperationsTabControl.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/queue/QueueOperationsTabControl.java
deleted file mode 100644
index ee6bd3522b..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/queue/QueueOperationsTabControl.java
+++ /dev/null
@@ -1,1111 +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.management.ui.views.queue;
-
-import static org.apache.qpid.management.common.mbeans.ManagedQueue.MSG_AMQ_ID;
-import static org.apache.qpid.management.common.mbeans.ManagedQueue.MSG_HEADER;
-import static org.apache.qpid.management.common.mbeans.ManagedQueue.MSG_QUEUE_POS;
-import static org.apache.qpid.management.common.mbeans.ManagedQueue.MSG_REDELIVERED;
-import static org.apache.qpid.management.common.mbeans.ManagedQueue.MSG_SIZE;
-import static org.apache.qpid.management.ui.Constants.CONSOLE_IMAGE;
-import static org.apache.qpid.management.ui.Constants.RESULT;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-import java.util.SortedSet;
-import java.util.TreeSet;
-
-import javax.management.MBeanServerConnection;
-import javax.management.MBeanServerInvocationHandler;
-import javax.management.openmbean.CompositeData;
-import javax.management.openmbean.CompositeDataSupport;
-import javax.management.openmbean.TabularDataSupport;
-
-import org.apache.qpid.management.ui.ApiVersion;
-import org.apache.qpid.management.ui.ApplicationRegistry;
-import org.apache.qpid.management.ui.ManagedBean;
-import org.apache.qpid.management.common.mbeans.ManagedQueue;
-import org.apache.qpid.management.ui.jmx.JMXManagedObject;
-import org.apache.qpid.management.ui.jmx.MBeanUtility;
-import org.apache.qpid.management.ui.views.NumberVerifyListener;
-import org.apache.qpid.management.ui.views.TabControl;
-import org.apache.qpid.management.ui.views.ViewUtility;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.ITableLabelProvider;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerSorter;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.KeyAdapter;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.events.MouseEvent;
-import org.eclipse.swt.events.MouseListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.TabFolder;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.TableColumn;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.ScrolledForm;
-
-
-/**
- * Control class for the Queue mbean Operations tab.
- */
-public class QueueOperationsTabControl extends TabControl
-{
- private FormToolkit _toolkit;
- private ScrolledForm _form;
- private Table _table = null;
- private TableViewer _tableViewer = null;
- private Composite _paramsComposite = null;
-
- private ApiVersion _ApiVersion;
-
- private Text _fromMsgText;
- private Text _toMsgText;
- private static final String FROM_DEFAULT = "1";
- private static final String TO_DEFAULT = "50";
- private long _interval = 50; //(to-from)+1
- private Long _fromMsg = new Long(FROM_DEFAULT);
- private Long _toMsg = new Long(TO_DEFAULT);
-
- private TabularDataSupport _messages = null;
- private ManagedQueue _qmb;
-
- private Button _previousButton;
- private Button _nextButton;
-
- public QueueOperationsTabControl(TabFolder tabFolder, JMXManagedObject mbean, MBeanServerConnection mbsc)
- {
- super(tabFolder);
- _mbean = mbean;
- _ApiVersion = ApplicationRegistry.getServerRegistry(mbean).getManagementApiVersion();
- _qmb = (ManagedQueue) MBeanServerInvocationHandler.newProxyInstance(mbsc,
- mbean.getObjectName(), ManagedQueue.class, false);
- _toolkit = new FormToolkit(_tabFolder.getDisplay());
- _form = _toolkit.createScrolledForm(_tabFolder);
- _form.getBody().setLayout(new GridLayout());
- createComposites();
- createWidgets();
- }
-
- private void createComposites()
- {
- _paramsComposite = _toolkit.createComposite(_form.getBody(), SWT.NONE);
- _paramsComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- _paramsComposite.setLayout(new GridLayout());
- }
-
- /**
- * @see TabControl#getControl()
- */
- public Control getControl()
- {
- return _form;
- }
-
- /**
- * @see TabControl#setFocus()
- */
- public void setFocus()
- {
- _table.setFocus();
- }
-
- @Override
- public void refresh(ManagedBean mbean)
- {
- _messages = null;
- try
- {
- if(_ApiVersion.greaterThanOrEqualTo(1, 3))
- { //broker supports Qpid JMX API 1.3 and takes Long values
-
- //gather a list of all messages on the queue for display and selection
- _messages = (TabularDataSupport) _qmb.viewMessages(_fromMsg,_toMsg);
- }
- else
- { //broker supports Qpid JMX API 1.2 or below and takes int values
-
- if(_toMsg > Integer.MAX_VALUE || _toMsg > Integer.MAX_VALUE)
- {
- ViewUtility.popupErrorMessage("Error", "This broker only supports viewing up to message " + Integer.MAX_VALUE);
- _tableViewer.setInput(null);
- return;
- }
-
- //gather a list of all messages on the queue for display and selection
- _messages = (TabularDataSupport) _qmb.viewMessages(_fromMsg.intValue(), _toMsg.intValue());
- }
- }
- catch (Exception e)
- {
- MBeanUtility.handleException(mbean,e);
- }
-
- _tableViewer.setInput(_messages);
-
- layout();
- }
-
- public void layout()
- {
- _form.layout(true);
- _form.getBody().layout(true, true);
- }
-
- private void createWidgets()
- {
- Group messagesGroup = new Group(_paramsComposite, SWT.SHADOW_NONE | SWT.SCROLL_LINE);
- messagesGroup.setBackground(_paramsComposite.getBackground());
- messagesGroup.setText("Messages");
- messagesGroup.setLayout(new GridLayout());
- GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
- messagesGroup.setLayoutData(gridData);
-
- //from and to fields for selecting the viewing range
- Composite viewMessageRangeComposite = _toolkit.createComposite(messagesGroup);
- gridData = new GridData(SWT.LEFT, SWT.FILL, false, false);
- viewMessageRangeComposite.setLayoutData(gridData);
- viewMessageRangeComposite.setLayout(new GridLayout(8,false));
-
- _toolkit.createLabel(viewMessageRangeComposite, "Queue pos: ");
- _fromMsgText = new Text(viewMessageRangeComposite, SWT.BORDER);
- _fromMsgText.setText(FROM_DEFAULT);
- gridData = new GridData(SWT.LEFT, SWT.FILL, false, false);
- gridData.widthHint = 75;
- _fromMsgText.setLayoutData(gridData);
- _fromMsgText.addVerifyListener(new NumberVerifyListener());
- _fromMsgText.addKeyListener(new KeyAdapter()
- {
- public void keyPressed(KeyEvent event)
- {
- if (event.character == SWT.CR)
- {
- updateMessageInterval();
- }
- }
- });
-
- _toolkit.createLabel(viewMessageRangeComposite, "to");
-
- _toMsgText = new Text(viewMessageRangeComposite, SWT.BORDER);
- _toMsgText.setText(TO_DEFAULT);
- gridData = new GridData(SWT.LEFT, SWT.FILL, false, false);
- gridData.widthHint = 75;
- _toMsgText.setLayoutData(gridData);
- _toMsgText.addVerifyListener(new NumberVerifyListener());
- _toMsgText.addKeyListener(new KeyAdapter()
- {
- public void keyPressed(KeyEvent event)
- {
- if (event.character == SWT.CR)
- {
- updateMessageInterval();
- }
- }
- });
-
- final Button setButton = _toolkit.createButton(viewMessageRangeComposite, "Set", SWT.PUSH);
- setButton.setLayoutData(new GridData(SWT.LEFT, SWT.FILL, false, false));
- setButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- updateMessageInterval();
- }
- });
-
- _toolkit.createLabel(viewMessageRangeComposite, " "); //spacer
-
- _previousButton = _toolkit.createButton(viewMessageRangeComposite, "< Prev " + _interval, SWT.PUSH);
- _previousButton.setLayoutData(new GridData(SWT.LEFT, SWT.FILL, false, false));
- _previousButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- //make 'to' be 'from - 1' unless from is 1 (ie there are no previous messages)
- if(_fromMsg > 1)
- {
- _toMsg = _fromMsg - 1;
- _toMsgText.setText(_toMsg.toString());
- }
-
- //make 'from' be 'from - INTERVAL', or make it 1 if that would make it 0 or less
- _fromMsg = (_fromMsg - _interval < 1) ? 1 : _fromMsg - _interval;
- _fromMsgText.setText(_fromMsg.toString());
-
- refresh(_mbean);
- }
- });
-
- _nextButton = _toolkit.createButton(viewMessageRangeComposite, "Next " + _interval + " >", SWT.PUSH);
- _nextButton.setLayoutData(new GridData(SWT.LEFT, SWT.FILL, false, false));
- _nextButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- //make 'from' be 'to + 1' unless 'to' is already Long.MAX_VALUE
- if(_toMsg != Long.MAX_VALUE)
- {
- _fromMsg = _toMsg + 1;
- _fromMsgText.setText(_fromMsg.toString());
- }
-
- //make 'to' be 'to + INTERVAL', or make it Long.MAX_VALUE if that would too large
- _toMsg = (Long.MAX_VALUE - _toMsg > _interval) ? _toMsg + _interval : Long.MAX_VALUE;
- _toMsgText.setText(_toMsg.toString());
-
- refresh(_mbean);
- }
- });
-
- //message table
- Composite tableAndButtonsComposite = _toolkit.createComposite(messagesGroup);
- gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
- gridData.minimumHeight = 180;
- gridData.heightHint = 180;
- tableAndButtonsComposite.setLayoutData(gridData);
- tableAndButtonsComposite.setLayout(new GridLayout(2,false));
-
- _table = new Table (tableAndButtonsComposite, SWT.MULTI | SWT.SCROLL_LINE | SWT.BORDER | SWT.FULL_SELECTION);
- _table.setLinesVisible (true);
- _table.setHeaderVisible (true);
- GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
- _table.setLayoutData(data);
-
- _tableViewer = new TableViewer(_table);
- final TableSorter tableSorter = new TableSorter();
-
- String[] titles = {"AMQ ID", "Size(bytes)"};
- if(_ApiVersion.greaterThanOrEqualTo(1, 3))
- {
- //if server management API is >= 1.3, show message's queue position
- titles = new String[]{"AMQ ID", "Size(bytes)", "Queue Position"};
- }
-
- int[] bounds = { 175, 175, 140 };
- for (int i = 0; i < titles.length; i++)
- {
- final int index = i;
- final TableColumn column = new TableColumn (_table, SWT.NONE);
-
- column.setText(titles[i]);
- column.setWidth(bounds[i]);
- column.setResizable(true);
-
- //Setting the right sorter
- column.addSelectionListener(new SelectionAdapter()
- {
- @Override
- public void widgetSelected(SelectionEvent e)
- {
- tableSorter.setColumn(index);
- final TableViewer viewer = _tableViewer;
- int dir = viewer .getTable().getSortDirection();
- if (viewer.getTable().getSortColumn() == column)
- {
- dir = dir == SWT.UP ? SWT.DOWN : SWT.UP;
- }
- else
- {
- dir = SWT.UP;
- }
- viewer.getTable().setSortDirection(dir);
- viewer.getTable().setSortColumn(column);
- viewer.refresh();
- }
- });
-
- }
-
- _tableViewer.setContentProvider(new ContentProviderImpl());
- _tableViewer.setLabelProvider(new LabelProviderImpl());
- _tableViewer.setSorter(tableSorter);
- _table.setSortColumn(_table.getColumn(0));
- _table.setSortDirection(SWT.UP);
-
- //Side Buttons
- Composite buttonsComposite = _toolkit.createComposite(tableAndButtonsComposite);
- gridData = new GridData(SWT.FILL, SWT.FILL, false, true);
- buttonsComposite.setLayoutData(gridData);
- buttonsComposite.setLayout(new GridLayout());
-
- final Button viewSelectedMsgButton = _toolkit.createButton(buttonsComposite, "View Message Content ...", SWT.PUSH);
- viewSelectedMsgButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false));
- viewSelectedMsgButton.setEnabled(false);
- viewSelectedMsgButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- if (_table.getSelectionIndex() == -1)
- {
- return;
- }
-
- viewMessageContent();
- }
- });
-
- if(_ApiVersion.lessThan(1, 3)) //if the server predates Qpid JMX API 1.3
- {
- final Button deleteFirstMessageButton = _toolkit.createButton(buttonsComposite, "Delete 1st Unacquired Msg", SWT.PUSH);
- deleteFirstMessageButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false));
- deleteFirstMessageButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent se)
- {
- int response = ViewUtility.popupOkCancelConfirmationMessage("Delete 1st unacquired message",
- "Delete 1st unacquired message on the queue?\n\n"
- + "NOTE: Any ongoing consumer activity may mean this is "
- + "not the first message listed in the table.");
- if (response == SWT.OK)
- {
- try
- {
- _qmb.deleteMessageFromTop();
- ViewUtility.operationResultFeedback(null, "Deleted 1st unacquired message on the queue", null);
- }
- catch (Exception e)
- {
- ViewUtility.operationFailedStatusBarMessage("Error deleting 1st unacquired message on queue");
- MBeanUtility.handleException(_mbean, e);
- }
-
- refresh(_mbean);;
- }
- }
- });
- }
-
- final Button moveMessagesButton;
- if(_ApiVersion.greaterThanOrEqualTo(1, 3))
- {
- //If the server supports Qpid JMX API 1.3, show the move message button.
- //This is being disabled for earlier brokers due to bugs affecting the result appearance
- //and impacting on the ability of the source queues to deliver further messages.
-
- moveMessagesButton = _toolkit.createButton(buttonsComposite, "Move Message(s) ...", SWT.PUSH);
-
- moveMessagesButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false));
- moveMessagesButton.setEnabled(false);
- moveMessagesButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- if (_table.getSelectionIndex() == -1)
- {
- return;
- }
-
- moveOrCopyMessages(moveMessagesButton.getShell(), QueueOperations.MOVE);
- }
- });
- }
- else
- {
- moveMessagesButton = null;
- }
-
- final Button copyMessagesButton;
- if(_ApiVersion.greaterThanOrEqualTo(1, 3))//if the server supports Qpid JMX API 1.3
- {
- copyMessagesButton= _toolkit.createButton(buttonsComposite, "Copy Message(s) ...", SWT.PUSH);
- copyMessagesButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false));
- copyMessagesButton.setEnabled(false);
- copyMessagesButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- if (_table.getSelectionIndex() == -1)
- {
- return;
- }
-
- moveOrCopyMessages(copyMessagesButton.getShell(), QueueOperations.COPY);
- }
- });
- }
- else
- {
- copyMessagesButton = null;
- }
-
- final Button deleteMessagesButton;
- if(_ApiVersion.greaterThanOrEqualTo(1, 3))//if the server supports Qpid JMX API 1.3
- {
- deleteMessagesButton = _toolkit.createButton(buttonsComposite, "Delete Message(s) ...", SWT.PUSH);
- deleteMessagesButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false));
- deleteMessagesButton.setEnabled(false);
- deleteMessagesButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- if (_table.getSelectionIndex() == -1)
- {
- return;
- }
-
- deleteMessages(deleteMessagesButton.getShell());
- }
- });
- }
- else
- {
- deleteMessagesButton = null;
- }
-
- final Button clearQueueButton = _toolkit.createButton(buttonsComposite, "Clear Queue", SWT.PUSH);
- clearQueueButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false));
- clearQueueButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- int response = ViewUtility.popupOkCancelConfirmationMessage("Clear Queue",
- "Clear queue ?");
- if (response == SWT.OK)
- {
- try
- {
- if(_ApiVersion.greaterThanOrEqualTo(1, 3))
- {
- //Qpid JMX API 1.3+, returns the number of messages deleted
- Long numDeleted = _qmb.clearQueue();
- String message = "Queue cleared of " + numDeleted +
- " non-acquired message" + (numDeleted == 1 ? "": "s");
-
- ViewUtility.operationResultFeedback(null, message, null);
- }
- else
- {
- //Qpid JMX API 1.2 or below, void return
- _qmb.clearQueue();
- ViewUtility.operationResultFeedback(null, "Queue cleared of non-acquired messages", null);
- }
- }
- catch (Exception e2)
- {
- ViewUtility.operationFailedStatusBarMessage("Error clearing Queue");
- MBeanUtility.handleException(_mbean, e2);
- }
-
- refresh(_mbean);;
- }
- }
- });
-
- _toolkit.createLabel(messagesGroup, "Message Header: ");
-
- //Redelivered status and header
- Composite headerEtcComposite = _toolkit.createComposite(messagesGroup);
- gridData = new GridData(SWT.FILL, SWT.FILL, true, false);
- headerEtcComposite.setLayoutData(gridData);
- headerEtcComposite.setLayout(new GridLayout());
-
- final Text headerText = new Text(headerEtcComposite, SWT.WRAP | SWT.BORDER | SWT.V_SCROLL);
- headerText.setText("Select a message to view its header.");
- headerText.setEditable(false);
- data = new GridData(SWT.LEFT, SWT.TOP, false, false);
- data.minimumHeight = 210;
- data.heightHint = 210;
- data.minimumWidth = 500;
- data.widthHint = 500;
- headerText.setLayoutData(data);
-
- Composite redeliveryComposite = _toolkit.createComposite(headerEtcComposite);
- redeliveryComposite.setLayout(new GridLayout(2,false));
- data = new GridData(SWT.LEFT, SWT.FILL, false, false);
- data.minimumWidth = 150;
- data.widthHint = 150;
- redeliveryComposite.setLayoutData(data);
-
- _toolkit.createLabel(redeliveryComposite, "Redelivered: ");
- final Text redeliveredText = new Text(redeliveryComposite, SWT.BORDER);
- redeliveredText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
- redeliveredText.setText("-");
- redeliveredText.setEditable(false);
-
- //listener for double clicking to view message content
- _table.addMouseListener(new MouseListener()
- {
- // MouseListener implementation
- public void mouseDoubleClick(MouseEvent event)
- {
- viewMessageContent();
- }
-
- public void mouseDown(MouseEvent e){}
- public void mouseUp(MouseEvent e){}
- });
-
- //selection listener to enable and disable buttons, update header and redelivered info
- _tableViewer.addSelectionChangedListener(new ISelectionChangedListener(){
- public void selectionChanged(SelectionChangedEvent evt)
- {
- int selectionIndex = _table.getSelectionIndex();
-
- if (selectionIndex == -1)
- {
- headerText.setText("Select a message to view its header.");
- redeliveredText.setText("-");
- viewSelectedMsgButton.setEnabled(false);
- if(moveMessagesButton != null)
- {
- moveMessagesButton.setEnabled(false);
- }
- if(copyMessagesButton != null)
- {
- copyMessagesButton.setEnabled(false);
- }
- if(deleteMessagesButton != null)
- {
- deleteMessagesButton.setEnabled(false);
- }
-
- return;
- }
- else
- {
- if(moveMessagesButton != null)
- {
- moveMessagesButton.setEnabled(true);
- }
- if(copyMessagesButton != null)
- {
- copyMessagesButton.setEnabled(true);
- }
- if(deleteMessagesButton != null)
- {
- deleteMessagesButton.setEnabled(true);
- }
-
- final CompositeData selectedMsg = (CompositeData)_table.getItem(selectionIndex).getData();
- Boolean redelivered = (Boolean) selectedMsg.get(MSG_REDELIVERED);
- redeliveredText.setText(redelivered.toString());
-
- String[] msgHeader = (String[]) selectedMsg.get(MSG_HEADER);
- headerText.setText("");
- String lineSeperator = System.getProperty("line.separator");
- int size = msgHeader.length;
- for(int i=0; i < size; i++)
- {
- headerText.append(msgHeader[i]);
- if(!(i == size - 1))
- {
- headerText.append(lineSeperator);
- }
- }
- headerText.setSelection(0);
- }
-
- if (_table.getSelectionCount() > 1)
- {
- viewSelectedMsgButton.setEnabled(false);
- }
- else
- {
- viewSelectedMsgButton.setEnabled(true);
- }
-
- }
- });
-
- }
-
- /**
- * Content Provider class for the table viewer
- */
- private static class ContentProviderImpl implements IStructuredContentProvider
- {
-
- public void inputChanged(Viewer v, Object oldInput, Object newInput)
- {
-
- }
-
- public void dispose()
- {
-
- }
-
- public Object[] getElements(Object parent)
- {
- Collection<Object> rowCollection = ((TabularDataSupport) parent).values();
-
- return rowCollection.toArray();
- }
- }
-
- /**
- * Label Provider class for the table viewer
- */
- private static class LabelProviderImpl extends LabelProvider implements ITableLabelProvider
- {
- public String getColumnText(Object element, int columnIndex)
- {
- switch (columnIndex)
- {
- case 0 : // msg id column
- return String.valueOf(((CompositeDataSupport) element).get(MSG_AMQ_ID));
- case 1 : // msg size column
- return String.valueOf(((CompositeDataSupport) element).get(MSG_SIZE));
- case 2 : // msg position in queue
- return String.valueOf(((CompositeDataSupport) element).get(MSG_QUEUE_POS));
- default :
- return "-";
- }
- }
-
- public Image getColumnImage(Object element, int columnIndex)
- {
- return null;
- }
-
- }
-
- /**
- * Sorter class for the table viewer.
- *
- */
- public static class TableSorter extends ViewerSorter
- {
- private int column;
- private static final int ASCENDING = 0;
- private static final int DESCENDING = 1;
-
- private int direction = DESCENDING;
-
- public TableSorter()
- {
- this.column = 0;
- direction = ASCENDING;
- }
-
- public void setColumn(int column)
- {
- if (column == this.column)
- {
- // Same column as last sort; toggle the direction
- direction = 1 - direction;
- }
- else
- {
- // New column; do an ascending sort
- this.column = column;
- direction = ASCENDING;
- }
- }
-
- @Override
- public int compare(Viewer viewer, Object e1, Object e2)
- {
- CompositeData msg1 = (CompositeData) e1;
- CompositeData msg2 = (CompositeData) e2;
-
- int comparison = 0;
- switch(column)
- {
- case 0:
- comparison = ((Long) msg1.get(MSG_AMQ_ID)).compareTo((Long)msg2.get(MSG_AMQ_ID));
- break;
- case 1:
- comparison = ((Long) msg1.get(MSG_SIZE)).compareTo((Long)msg2.get(MSG_SIZE));
- break;
- case 2:
- comparison = ((Long) msg1.get(MSG_QUEUE_POS)).compareTo((Long)msg2.get(MSG_QUEUE_POS));
- break;
- default:
- comparison = 0;
- }
- // If descending order, flip the direction
- if(direction == DESCENDING)
- {
- comparison = -comparison;
- }
- return comparison;
- }
- }
-
- private void updateMessageInterval()
- {
- Long from;
- try
- {
- from = Long.valueOf(_fromMsgText.getText());
- }
- catch(Exception e1)
- {
- ViewUtility.popupErrorMessage("Invalid Value", "Please enter a valid 'from' number");
- return;
- }
-
- Long to;
- try
- {
- to = Long.valueOf(_toMsgText.getText());
- }
- catch(Exception e1)
- {
- ViewUtility.popupErrorMessage("Invalid Value", "Please enter a valid 'to' number");
- return;
- }
-
- _fromMsg = from;
- _toMsg = to;
-
- _interval = (to - from) + 1;
- _previousButton.setText("< Prev " + _interval);
- _nextButton.setText("Next " + _interval + " >");
-
- refresh(_mbean);
- }
-
- private void viewMessageContent()
- {
- int selectionIndex = _table.getSelectionIndex();
-
- if (selectionIndex != -1)
- {
- try
- {
- final CompositeData selectedMsg = (CompositeData)_table.getItem(selectionIndex).getData();
- Long msgId = (Long) selectedMsg.get(MSG_AMQ_ID);
-
- Object result = _qmb.viewMessageContent(msgId);
-
- populateResults(result);
- }
- catch (Exception e3)
- {
- MBeanUtility.handleException(_mbean, e3);
- }
- }
- }
-
- private void populateResults(Object result)
- {
- Display display = Display.getCurrent();
- int width = 610;
- int height = 400;
- Shell shell = ViewUtility.createPopupShell(RESULT, width, height);
- shell.setImage(ApplicationRegistry.getImage(CONSOLE_IMAGE));
- ViewUtility.populateCompositeWithData(_toolkit, shell, result);
-
- shell.open();
- while (!shell.isDisposed())
- {
- if (!display.readAndDispatch())
- {
- display.sleep();
- }
- }
- shell.dispose();
- }
-
- private void moveOrCopyMessages(final Shell parent, final QueueOperations op)
- {
- final ArrayList<Long> rangeStarts = new ArrayList<Long>();
- final ArrayList<Long> rangeEnds = new ArrayList<Long>();
-
- gatherSelectedAMQMsgIDRanges(rangeStarts,rangeEnds);
- String rangeString = getRangesString(rangeStarts,rangeEnds);
-
- String windowTitle;
- String dialogueMessage;
- final String feedBackMessage;
- final String failureFeedBackMessage;
-
- if(op.equals(QueueOperations.MOVE))
- {
- windowTitle = "Move Messages";
- dialogueMessage = "Move message(s) with AMQ ID:";
- feedBackMessage = "Messages moved";
- failureFeedBackMessage = "Error moving messages";
- }
- else
- {
- windowTitle = "Copy Messages";
- dialogueMessage = "Copy message(s) with AMQ ID:";
- feedBackMessage = "Messages copied";
- failureFeedBackMessage = "Error copying messages";
- }
-
- final Shell shell = ViewUtility.createModalDialogShell(parent, windowTitle);
-
- Composite idComposite = _toolkit.createComposite(shell, SWT.NONE);
- idComposite.setBackground(shell.getBackground());
- idComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- idComposite.setLayout(new GridLayout());
-
- _toolkit.createLabel(idComposite,dialogueMessage).setBackground(shell.getBackground());
- _toolkit.createLabel(idComposite,rangeString).setBackground(shell.getBackground());
-
- Composite destinationComposite = _toolkit.createComposite(shell, SWT.NONE);
- destinationComposite.setBackground(shell.getBackground());
- destinationComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- destinationComposite.setLayout(new GridLayout(2,false));
-
- _toolkit.createLabel(destinationComposite,"To Queue:").setBackground(shell.getBackground());
- final Combo destinationCombo = new Combo(destinationComposite,SWT.NONE | SWT.READ_ONLY);
- destinationCombo.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
-
- Composite okCancelButtonsComp = _toolkit.createComposite(shell);
- okCancelButtonsComp.setBackground(shell.getBackground());
- okCancelButtonsComp.setLayoutData(new GridData(SWT.RIGHT, SWT.FILL, true, true));
- okCancelButtonsComp.setLayout(new GridLayout(2,false));
-
- Button okButton = _toolkit.createButton(okCancelButtonsComp, "OK", SWT.PUSH);
- okButton.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, false));
- Button cancelButton = _toolkit.createButton(okCancelButtonsComp, "Cancel", SWT.PUSH);
- cancelButton.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, false));
-
- List<String> queueList = ApplicationRegistry.getServerRegistry(_mbean).getQueueNames(_mbean.getVirtualHostName());
- queueList.remove(_mbean.getName());
-
- if(queueList.size() == 0)
- {
- destinationCombo.setItems(new String[]{"No other queues available"});
- okButton.setEnabled(false);
- }
- else
- {
- Collections.sort(queueList);
- destinationCombo.setItems(queueList.toArray(new String[0]));
- }
- destinationCombo.select(0);
-
- okButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- String destQueue = destinationCombo.getItem(destinationCombo.getSelectionIndex()).toString();
- shell.dispose();
-
- try
- {
- for(int i=0 ; i < rangeStarts.size() ; i++)
- {
- Long from = rangeStarts.get(i);
- Long to = rangeEnds.get(i);
-
- switch(op)
- {
- case COPY:
- _qmb.copyMessages(Long.valueOf(from), Long.valueOf(to), destQueue);
- break;
- case MOVE:
- _qmb.moveMessages(Long.valueOf(from), Long.valueOf(to), destQueue);
- break;
- }
- }
-
- ViewUtility.operationResultFeedback(null, feedBackMessage, null);
- }
- catch (Exception e4)
- {
- ViewUtility.operationFailedStatusBarMessage(failureFeedBackMessage);
- MBeanUtility.handleException(_mbean, e4);
- }
-
- refresh(_mbean);
- }
- });
-
- cancelButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- shell.dispose();
- }
- });
-
- shell.setDefaultButton(okButton);
- shell.pack();
- ViewUtility.centerChildInParentShell(parent, shell);
-
- shell.open();
- }
-
- private void deleteMessages(final Shell parent)
- {
- final ArrayList<Long> rangeStarts = new ArrayList<Long>();
- final ArrayList<Long> rangeEnds = new ArrayList<Long>();
-
- gatherSelectedAMQMsgIDRanges(rangeStarts,rangeEnds);
- String rangeString = getRangesString(rangeStarts,rangeEnds);
-
- final Shell shell = ViewUtility.createModalDialogShell(parent, "Delete Messages");
-
- Composite idComposite = _toolkit.createComposite(shell, SWT.NONE);
- idComposite.setBackground(shell.getBackground());
- idComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- idComposite.setLayout(new GridLayout());
-
- _toolkit.createLabel(idComposite,"Delete message(s) with AMQ ID:").setBackground(shell.getBackground());
- _toolkit.createLabel(idComposite,rangeString).setBackground(shell.getBackground());
-
- Composite okCancelButtonsComp = _toolkit.createComposite(shell);
- okCancelButtonsComp.setBackground(shell.getBackground());
- okCancelButtonsComp.setLayoutData(new GridData(SWT.RIGHT, SWT.FILL, true, true));
- okCancelButtonsComp.setLayout(new GridLayout(2,false));
-
- Button okButton = _toolkit.createButton(okCancelButtonsComp, "OK", SWT.PUSH);
- okButton.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, false));
- Button cancelButton = _toolkit.createButton(okCancelButtonsComp, "Cancel", SWT.PUSH);
- cancelButton.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, false));
-
- okButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- shell.dispose();
-
- try
- {
- for(int i=0 ; i < rangeStarts.size() ; i++)
- {
- Long from = rangeStarts.get(i);
- Long to = rangeEnds.get(i);
-
- _qmb.deleteMessages(Long.valueOf(from), Long.valueOf(to));
- }
-
- ViewUtility.operationResultFeedback(null, "Messages deleted", null);
- }
- catch (Exception e4)
- {
- ViewUtility.operationFailedStatusBarMessage("Error deleting messages");
- MBeanUtility.handleException(_mbean, e4);
- }
-
- refresh(_mbean);
- }
- });
-
- cancelButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- shell.dispose();
- }
- });
-
- shell.setDefaultButton(okButton);
- shell.pack();
- ViewUtility.centerChildInParentShell(parent, shell);
-
- shell.open();
- }
-
- private void gatherSelectedAMQMsgIDRanges(ArrayList<Long> starts, ArrayList<Long> ends)
- {
- SortedSet<Long> amqIDs = new TreeSet<Long>();
-
- for(Integer i : _table.getSelectionIndices())
- {
- CompositeData selectedMsg = (CompositeData)_table.getItem(i).getData();
- amqIDs.add((Long)selectedMsg.get(MSG_AMQ_ID));
- }
-
- //initialise the first range
- Long start = amqIDs.first();
- Long end = amqIDs.first();
-
- for(Long id : amqIDs)
- {
- if(id == amqIDs.first())
- {
- //skip first check, already initialised range
- continue;
- }
-
- if(id == end +1)
- {
- //part of previous range, append
- end = id;
- }
- else
- {
- //not in previous range, record existing start and end msg id values
- starts.add(start);
- ends.add(end);
-
- //begin new range with this msg id
- start = id;
- end = id;
- }
- }
-
- //record the last range created
- starts.add(start);
- ends.add(end);
- }
-
- private String getRangesString(ArrayList<Long> starts, ArrayList<Long> ends)
- {
- String idRangesString = "";
-
- for(int i=0 ; i < starts.size() ; i++)
- {
- long start = starts.get(i);
- long end = ends.get(i);
-
- if(i != 0)
- {
- idRangesString = idRangesString.concat(", ");
- }
-
- if(start == end)
- {
- idRangesString = idRangesString.concat(String.valueOf(starts.get(i)));
- }
- else
- {
- idRangesString = idRangesString.concat(starts.get(i) + "-" + ends.get(i));
- }
- }
-
- return idRangesString.concat(".");
- }
-
- private enum QueueOperations
- {
- MOVE,
- COPY;
- }
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/type/ConnectionTypeTabControl.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/type/ConnectionTypeTabControl.java
deleted file mode 100644
index f1f7b07b6f..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/type/ConnectionTypeTabControl.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.management.ui.views.type;
-
-import java.util.List;
-
-import static org.apache.qpid.management.ui.Constants.CONNECTION;
-
-import org.apache.qpid.management.ui.ManagedBean;
-import org.apache.qpid.management.ui.ManagedServer;
-import org.eclipse.swt.widgets.TabFolder;
-
-/**
- * Controller class, which takes care of displaying appropriate information and widgets for Connections.
- * This allows user to select Connections and add those to the navigation view
- */
-
-public class ConnectionTypeTabControl extends MBeanTypeTabControl
-{
-
- public ConnectionTypeTabControl(TabFolder tabFolder, ManagedServer server, String virtualHost)
- {
- super(tabFolder, server, virtualHost, CONNECTION);
- }
-
- @Override
- protected List<ManagedBean> getMbeans()
- {
- return _serverRegistry.getConnections(_virtualHost);
- }
-
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/type/ExchangeTypeTabControl.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/type/ExchangeTypeTabControl.java
deleted file mode 100644
index 5d587c7158..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/type/ExchangeTypeTabControl.java
+++ /dev/null
@@ -1,45 +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.management.ui.views.type;
-
-import java.util.List;
-
-import static org.apache.qpid.management.ui.Constants.EXCHANGE;
-
-import org.apache.qpid.management.ui.ManagedBean;
-import org.apache.qpid.management.ui.ManagedServer;
-import org.eclipse.swt.widgets.TabFolder;
-
-public class ExchangeTypeTabControl extends MBeanTypeTabControl
-{
-
- public ExchangeTypeTabControl(TabFolder tabFolder, ManagedServer server, String virtualHost)
- {
- super(tabFolder, server, virtualHost, EXCHANGE);
- }
-
- @Override
- protected List<ManagedBean> getMbeans()
- {
- return _serverRegistry.getExchanges(_virtualHost);
- }
-
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/type/MBeanTypeTabControl.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/type/MBeanTypeTabControl.java
deleted file mode 100644
index a4574b8d22..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/type/MBeanTypeTabControl.java
+++ /dev/null
@@ -1,456 +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.management.ui.views.type;
-
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.qpid.management.ui.ApiVersion;
-import org.apache.qpid.management.ui.ApplicationRegistry;
-import org.apache.qpid.management.ui.ManagedBean;
-import org.apache.qpid.management.ui.ManagedServer;
-import org.apache.qpid.management.ui.jmx.JMXManagedObject;
-import org.apache.qpid.management.ui.jmx.JMXServerRegistry;
-import org.apache.qpid.management.ui.jmx.MBeanUtility;
-import org.apache.qpid.management.ui.views.MBeanView;
-import org.apache.qpid.management.ui.views.NavigationView;
-import org.apache.qpid.management.ui.views.TabControl;
-
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.ITableLabelProvider;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.TableViewerColumn;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerSorter;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.MouseEvent;
-import org.eclipse.swt.events.MouseListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.TabFolder;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.TableColumn;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.forms.widgets.Form;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-
-public abstract class MBeanTypeTabControl extends TabControl
-{
- protected FormToolkit _toolkit;
- protected Form _form;
- protected Table _table = null;
- protected TableViewer _tableViewer = null;
-
- protected List<ManagedBean> _mbeans = null;
- protected String _type;
- protected ApiVersion _ApiVersion;
- protected JMXManagedObject _vhostMbean;
- protected String _virtualHost;
- protected JMXServerRegistry _serverRegistry;
- protected Composite _tableComposite;
- protected Button _favouritesButton;
- protected Button _openButton;
-
- public MBeanTypeTabControl(TabFolder tabFolder, ManagedServer server, String virtualHost, String type)
- {
- super(tabFolder);
- _virtualHost = virtualHost;
- _serverRegistry = (JMXServerRegistry) ApplicationRegistry.getServerRegistry(server);
- _ApiVersion = _serverRegistry.getManagementApiVersion();
- _vhostMbean = (JMXManagedObject) _serverRegistry.getVirtualHostManagerMBean(_virtualHost);
- _type = type;
- _toolkit = new FormToolkit(_tabFolder.getDisplay());
- _form = _toolkit.createForm(_tabFolder);
- _form.getBody().setLayout(new GridLayout());
- init();
- createWidgets();
- }
-
- protected void init()
- {
-
- }
-
- /**
- * @see TabControl#getControl()
- */
- public Control getControl()
- {
- return _form;
- }
-
- /**
- * @see TabControl#setFocus()
- */
- public void setFocus()
- {
- _table.setFocus();
- }
-
- public void refresh()
- {
- refresh(null);
- }
-
-
- @Override
- public void refresh(ManagedBean mbean)
- {
- _mbeans = getMbeans();
-
- _tableViewer.setInput(_mbeans);
-
- layout();
- }
-
- public void layout()
- {
- _form.layout(true);
- _form.getBody().layout(true, true);
- }
-
- protected abstract List<ManagedBean> getMbeans();
-
- protected void createTable()
- {
- _table = new Table (_tableComposite, SWT.MULTI | SWT.SCROLL_LINE | SWT.BORDER | SWT.FULL_SELECTION);
- _table.setLinesVisible (true);
- _table.setHeaderVisible (true);
- GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
- _table.setLayoutData(data);
-
- _tableViewer = new TableViewer(_table);
- final TableSorter tableSorter = new TableSorter();
-
- String[] titles = { "Name"};
- int[] bounds = { 310};
- for (int i = 0; i < titles.length; i++)
- {
- final int index = i;
- final TableViewerColumn viewerColumn = new TableViewerColumn(_tableViewer, SWT.NONE);
- final TableColumn column = viewerColumn.getColumn();
-
- column.setText(titles[i]);
- column.setWidth(bounds[i]);
- column.setResizable(true);
-
- //Setting the right sorter
- column.addSelectionListener(new SelectionAdapter()
- {
- @Override
- public void widgetSelected(SelectionEvent e)
- {
- tableSorter.setColumn(index);
- final TableViewer viewer = _tableViewer;
- int dir = viewer .getTable().getSortDirection();
- if (viewer.getTable().getSortColumn() == column)
- {
- dir = dir == SWT.UP ? SWT.DOWN : SWT.UP;
- }
- else
- {
- dir = SWT.UP;
- }
- viewer.getTable().setSortDirection(dir);
- viewer.getTable().setSortColumn(column);
- viewer.refresh();
- }
- });
-
- }
-
- _tableViewer.setContentProvider(new ContentProviderImpl());
- _tableViewer.setLabelProvider(new LabelProviderImpl());
- _tableViewer.setSorter(tableSorter);
- _table.setSortColumn(_table.getColumn(0));
- _table.setSortDirection(SWT.UP);
-
- addTableListeners();
- }
-
- protected void addTableListeners()
- {
- _favouritesButton.setEnabled(false);
- _openButton.setEnabled(false);
-
- _tableViewer.addSelectionChangedListener(new ISelectionChangedListener(){
- public void selectionChanged(SelectionChangedEvent evt)
- {
- int selectionIndex = _table.getSelectionIndex();
-
- if (selectionIndex == -1)
- {
- _favouritesButton.setEnabled(false);
- _openButton.setEnabled(false);
- return;
- }
- else
- {
- _favouritesButton.setEnabled(true);
- }
-
- if(_table.getSelectionCount() > 1)
- {
- _openButton.setEnabled(false);
- }
- else
- {
- _openButton.setEnabled(true);
- }
- }
- });
-
- _table.addMouseListener(new MouseListener()
- {
- // MouseListener implementation
- public void mouseDoubleClick(MouseEvent event)
- {
- openMBean();
- }
-
- public void mouseDown(MouseEvent e){}
- public void mouseUp(MouseEvent e){}
- });
- }
-
-
- private void createWidgets()
- {
- Composite mainComposite = _toolkit.createComposite(_form.getBody(), SWT.NONE);
- mainComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- mainComposite.setLayout(new GridLayout());
-
- Composite buttonComposite = _toolkit.createComposite(mainComposite, SWT.NONE);
- GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, false);
- buttonComposite.setLayoutData(gridData);
- buttonComposite.setLayout(new GridLayout(2,true));
-
- _favouritesButton = _toolkit.createButton(buttonComposite,
- "<-- Add " + _type + "(s) to favourites", SWT.PUSH);
- gridData = new GridData(SWT.LEFT, SWT.CENTER, true, false);
- _favouritesButton.setLayoutData(gridData);
- _favouritesButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- addMBeanToFavourites();
- }
- });
-
- _openButton = _toolkit.createButton(buttonComposite, "Open selected " + _type, SWT.PUSH);
- gridData = new GridData(SWT.RIGHT, SWT.CENTER, true, false);
- _openButton.setLayoutData(gridData);
- _openButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- openMBean();
- }
- });
-
- _tableComposite = _toolkit.createComposite(mainComposite);
- gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
- _tableComposite.setLayoutData(gridData);
- _tableComposite.setLayout(new GridLayout(1,false));
-
- createTable();
-
- createLowerAreaButton(mainComposite);
- }
-
- protected void createLowerAreaButton(Composite parent)
- {
-
- }
-
- /**
- * Content Provider class for the table viewer
- */
- private static class ContentProviderImpl implements IStructuredContentProvider
- {
-
- public void inputChanged(Viewer v, Object oldInput, Object newInput)
- {
-
- }
-
- public void dispose()
- {
-
- }
-
- @SuppressWarnings("unchecked")
- public Object[] getElements(Object parent)
- {
- return ((List<ManagedBean>) parent).toArray();
- }
- }
-
- /**
- * Label Provider class for the table viewer
- */
- private static class LabelProviderImpl extends LabelProvider implements ITableLabelProvider
- {
- public String getColumnText(Object element, int columnIndex)
- {
- switch (columnIndex)
- {
- case 0 : // name column
- return ((ManagedBean) element).getName();
- default:
- return "-";
- }
- }
-
- public Image getColumnImage(Object element, int columnIndex)
- {
- return null;
- }
-
- }
-
- /**
- * Sorter class for the table viewer.
- *
- */
- private static class TableSorter extends ViewerSorter
- {
- private int column;
- private static final int ASCENDING = 0;
- private static final int DESCENDING = 1;
-
- private int direction;
-
- public TableSorter()
- {
- this.column = 0;
- direction = ASCENDING;
- }
-
- public void setColumn(int column)
- {
- if(column == this.column)
- {
- // Same column as last sort; toggle the direction
- direction = 1 - direction;
- }
- else
- {
- // New column; do an ascending sort
- this.column = column;
- direction = ASCENDING;
- }
- }
-
- @Override
- public int compare(Viewer viewer, Object e1, Object e2)
- {
- ManagedBean mbean1 = (ManagedBean) e1;
- ManagedBean mbean2 = (ManagedBean) e2;
-
- int comparison = 0;
- switch(column)
- {
- case 0:
- comparison = mbean1.getName().compareTo(mbean2.getName());
- break;
- default:
- comparison = 0;
- }
- // If descending order, flip the direction
- if(direction == DESCENDING)
- {
- comparison = -comparison;
- }
- return comparison;
- }
- }
-
- protected void addMBeanToFavourites()
- {
- int selectionIndex = _table.getSelectionIndex();
-
- if (selectionIndex == -1)
- {
- return;
- }
-
- int[] selectedIndices = _table.getSelectionIndices();
-
- ArrayList<ManagedBean> selectedMBeans = new ArrayList<ManagedBean>();
-
- for(int index = 0; index < selectedIndices.length ; index++)
- {
- ManagedBean selectedMBean = (ManagedBean)_table.getItem(selectedIndices[index]).getData();
- selectedMBeans.add(selectedMBean);
- }
-
- IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- NavigationView view = (NavigationView)window.getActivePage().findView(NavigationView.ID);
-
- ManagedBean bean = null;
- try
- {
- for(ManagedBean mbean: selectedMBeans)
- {
- view.addManagedBean(mbean);
- }
- }
- catch (Exception ex)
- {
- MBeanUtility.handleException(bean, ex);
- }
- }
-
- protected void openMBean()
- {
- int selectionIndex = _table.getSelectionIndex();
-
- if (selectionIndex == -1)
- {
- return;
- }
-
- final ManagedBean selectedMBean = (ManagedBean)_table.getItem(selectionIndex).getData();
-
- IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- MBeanView view = (MBeanView) window.getActivePage().findView(MBeanView.ID);
- try
- {
- view.openMBean(selectedMBean);
- }
- catch (Exception ex)
- {
- MBeanUtility.handleException(selectedMBean, ex);
- }
- }
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/type/QueueTypeTabControl.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/type/QueueTypeTabControl.java
deleted file mode 100644
index 406ef08326..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/type/QueueTypeTabControl.java
+++ /dev/null
@@ -1,786 +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.management.ui.views.type;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.Semaphore;
-
-import javax.management.MBeanServerConnection;
-import javax.management.MBeanServerInvocationHandler;
-
-import static org.apache.qpid.management.ui.ApplicationRegistry.DATA_DIR;
-import static org.apache.qpid.management.ui.Constants.QUEUE;
-import static org.apache.qpid.management.common.mbeans.ManagedQueue.ATTR_NAME;
-import static org.apache.qpid.management.common.mbeans.ManagedQueue.ATTR_ACTIVE_CONSUMER_COUNT;
-import static org.apache.qpid.management.common.mbeans.ManagedQueue.ATTR_AUTODELETE;
-import static org.apache.qpid.management.common.mbeans.ManagedQueue.ATTR_CONSUMER_COUNT;
-import static org.apache.qpid.management.common.mbeans.ManagedQueue.ATTR_DURABLE;
-import static org.apache.qpid.management.common.mbeans.ManagedQueue.ATTR_MAX_MSG_AGE;
-import static org.apache.qpid.management.common.mbeans.ManagedQueue.ATTR_MAX_MSG_COUNT;
-import static org.apache.qpid.management.common.mbeans.ManagedQueue.ATTR_MAX_MSG_SIZE;
-import static org.apache.qpid.management.common.mbeans.ManagedQueue.ATTR_MAX_QUEUE_DEPTH;
-import static org.apache.qpid.management.common.mbeans.ManagedQueue.ATTR_MSG_COUNT;
-import static org.apache.qpid.management.common.mbeans.ManagedQueue.ATTR_OWNER;
-import static org.apache.qpid.management.common.mbeans.ManagedQueue.ATTR_QUEUE_DEPTH;
-import static org.apache.qpid.management.common.mbeans.ManagedQueue.ATTR_RCVD_MSG_COUNT;
-
-import org.apache.qpid.management.common.mbeans.ManagedBroker;
-import org.apache.qpid.management.common.mbeans.ManagedQueue;
-import org.apache.qpid.management.ui.ApplicationRegistry;
-import org.apache.qpid.management.ui.ManagedBean;
-import org.apache.qpid.management.ui.ManagedServer;
-import org.apache.qpid.management.ui.jmx.MBeanUtility;
-import org.apache.qpid.management.ui.views.MBeanView;
-import org.apache.qpid.management.ui.views.NavigationView;
-import org.apache.qpid.management.ui.views.ViewUtility;
-import org.eclipse.jface.preference.PreferenceStore;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.ITableLabelProvider;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.TableViewerColumn;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerSorter;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.TabFolder;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.TableColumn;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PlatformUI;
-
-public class QueueTypeTabControl extends MBeanTypeTabControl
-{
- private MBeanServerConnection _mbsc;
- private ManagedBroker _vhmb;
-
- private List<String> _selectedAttributes;
- private PreferenceStore _preferences;
- private Semaphore _tableViewerSemaphore = new Semaphore(1);
-
- private static final String APP_DIR = ApplicationRegistry.DATA_DIR;
- private static final String INI_FILENAME = APP_DIR + File.separator + "qpidmc_queue_attributes.ini";
- private static final String INI_QUEUE_ATTRIBUES = "QueueAttributesSelection";
-
- private static final ArrayList<String> FALLBACK_ATTRIBUTES_LIST = new ArrayList<String>();
- static
- {
- FALLBACK_ATTRIBUTES_LIST.add(ATTR_NAME);
- FALLBACK_ATTRIBUTES_LIST.add(ATTR_ACTIVE_CONSUMER_COUNT);
- FALLBACK_ATTRIBUTES_LIST.add(ATTR_AUTODELETE);
- FALLBACK_ATTRIBUTES_LIST.add(ATTR_CONSUMER_COUNT);
- FALLBACK_ATTRIBUTES_LIST.add(ATTR_DURABLE);
- FALLBACK_ATTRIBUTES_LIST.add(ATTR_MAX_MSG_AGE);
- FALLBACK_ATTRIBUTES_LIST.add(ATTR_MAX_MSG_COUNT);
- FALLBACK_ATTRIBUTES_LIST.add(ATTR_MAX_MSG_SIZE);
- FALLBACK_ATTRIBUTES_LIST.add(ATTR_MAX_QUEUE_DEPTH);
- FALLBACK_ATTRIBUTES_LIST.add(ATTR_MSG_COUNT);
- FALLBACK_ATTRIBUTES_LIST.add(ATTR_OWNER);
- FALLBACK_ATTRIBUTES_LIST.add(ATTR_QUEUE_DEPTH);
- FALLBACK_ATTRIBUTES_LIST.add(ATTR_RCVD_MSG_COUNT);
- }
-
- private static final Map<String, Integer> DEFAULT_COLUMN_WIDTHS = new HashMap<String,Integer>();
- static
- {
- DEFAULT_COLUMN_WIDTHS.put(ATTR_NAME, 215);
- DEFAULT_COLUMN_WIDTHS.put(ATTR_OWNER,125);
- DEFAULT_COLUMN_WIDTHS.put(ATTR_QUEUE_DEPTH,125);
- }
-
- public QueueTypeTabControl(TabFolder tabFolder, ManagedServer server, String virtualHost)
- {
- super(tabFolder,server,virtualHost,QUEUE);
- _mbsc = (MBeanServerConnection) _serverRegistry.getServerConnection();
-
- //create a proxy for the VirtualHostManager mbean to use in retrieving the attribute names/values
- _vhmb = MBeanServerInvocationHandler.newProxyInstance(_mbsc,
- _vhostMbean.getObjectName(), ManagedBroker.class, false);
-
- }
-
- @Override
- protected void init()
- {
- createIniFileIfNecessary();
- loadAttributePreferences();
- }
-
- /**
- * Create the ini file if it doesn't already exist.
- */
- public static void createIniFileIfNecessary()
- {
- File dir = new File(DATA_DIR);
- if (!dir.exists())
- {
- if(!dir.mkdir())
- {
- System.err.println("Could not create application data directory " + DATA_DIR);
- ViewUtility.popupErrorMessage("Error", "Fatal Error: Unable to create the application data directory: " + DATA_DIR);
- System.exit(1);
- }
- }
-
- File file = new File(INI_FILENAME);
- try
- {
- if (!file.exists())
- {
- file.createNewFile();
- }
- }
- catch (IOException ex)
- {
- System.err.println("Error creating the configuration file " + INI_FILENAME);
- ViewUtility.popupErrorMessage("Error", "Fatal Error: Unable to create the configuration file: " + INI_FILENAME);
- System.exit(1);
- }
- }
-
- private void loadAttributePreferences()
- {
- _preferences = new PreferenceStore(INI_FILENAME);
- List<String> attributesList = new ArrayList<String>();
-
- //ensure the name is present, and first
- attributesList.add(ManagedQueue.ATTR_NAME);
-
- //add any others from the file
- try
- {
- _preferences.load();
-
- String selectedAttributes = _preferences.getString(INI_QUEUE_ATTRIBUES);
- if (selectedAttributes.length() != 0)
- {
- String[] attributes = selectedAttributes.split(",");
- for (String attr : attributes)
- {
- if(attr.equals(ManagedQueue.ATTR_NAME))
- {
- //the Name attribute is already present
- continue;
- }
-
- attributesList.add(attr);
- }
- }
- }
- catch (IOException e)
- {
- ViewUtility.popupErrorMessage("Error", "Unable to load previous attribute selections, defaulting to Name only");
- System.err.println(e);
- }
-
- _selectedAttributes = attributesList;
- }
-
- private void saveAttributePreferences()
- {
- String chosenAttributes = new String();
-
- for(String attr : _selectedAttributes)
- {
- chosenAttributes = chosenAttributes.concat(attr) + ",";
- }
- //cut off last ","
- int lastIndex = chosenAttributes.lastIndexOf(',');
- if (lastIndex != -1)
- {
- chosenAttributes = chosenAttributes.substring(0,lastIndex);
- }
-
- _preferences.putValue(INI_QUEUE_ATTRIBUES, chosenAttributes);
-
- try
- {
- _preferences.save();
- }
- catch (IOException e)
- {
- ViewUtility.popupErrorMessage("Error", "Unable to save the attribute selection, choices will be lost at shutdown");
- System.err.println(e);
- }
- }
-
- @Override
- public void refresh(ManagedBean mbean)
- {
- //Try locking. If we cant aquire the lock, dont bother getting new values.
- //Either the attributes are being changed and these values would be out of date,
- //or another thread is still in the process of refreshing
- if(_tableViewerSemaphore.tryAcquire())
- {
- try
- {
- List<List<Object>> values = null;
-
- if(_ApiVersion.greaterThanOrEqualTo(1, 3))
- {
- //Qpid JMX API 1.3+, use this virtualhosts VirtualHostManager MBean
- //to retrieve the attributes values requested for all queues at once
- try
- {
- values = _vhmb.retrieveQueueAttributeValues(_selectedAttributes.toArray(new String[0]));
- }
- catch(Exception e)
- {
- MBeanUtility.handleException(_vhostMbean, e);
- }
- }
- else
- {
- //Qpid JMX API 1.2 or below, use the local ManagedBeans and look
- //up the attribute values for each queue individually
- _mbeans = getMbeans();
- values = MBeanUtility.getQueueAttributes(_mbeans, _selectedAttributes.toArray(new String[0]));
- }
-
- _tableViewer.setInput(values);
- layout();
- }
- finally
- {
- _tableViewerSemaphore.release();
- }
- }
-
- }
-
- @Override
- protected List<ManagedBean> getMbeans()
- {
- return _serverRegistry.getQueues(_virtualHost);
- }
-
- private void clearTableComposite()
- {
- ViewUtility.disposeChildren(_tableComposite);
- }
-
- @Override
- protected void createTable()
- {
- _table = new Table (_tableComposite, SWT.MULTI | SWT.SCROLL_LINE | SWT.BORDER | SWT.FULL_SELECTION);
- _table.setLinesVisible (true);
- _table.setHeaderVisible (true);
- GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
- _table.setLayoutData(data);
-
- _tableViewer = new TableViewer(_table);
-
- final QueueTableSorter tableSorter = new QueueTableSorter();
-
- for (int i = 0; i < _selectedAttributes.size(); i++)
- {
- final int index = i;
- final TableViewerColumn viewerColumn = new TableViewerColumn(_tableViewer, SWT.NONE);
- final TableColumn column = viewerColumn.getColumn();
-
- String attrName = _selectedAttributes.get(i);
- column.setMoveable(true);
- column.setText(attrName);
- column.pack();
- if(DEFAULT_COLUMN_WIDTHS.containsKey(attrName))
- {
- //retrieve the desired default width
- column.setWidth(DEFAULT_COLUMN_WIDTHS.get(attrName));
- }
- else
- {
- //add padding for sort direction indicator
- column.setWidth(column.getWidth() + 15);
- }
- column.setResizable(true);
-
- //Setting the right sorter
- column.addSelectionListener(new SelectionAdapter()
- {
- @Override
- public void widgetSelected(SelectionEvent e)
- {
- tableSorter.setColumn(index);
- final TableViewer viewer = _tableViewer;
- int dir = viewer .getTable().getSortDirection();
- if (viewer.getTable().getSortColumn() == column)
- {
- dir = dir == SWT.UP ? SWT.DOWN : SWT.UP;
- }
- else
- {
- dir = SWT.UP;
- }
- viewer.getTable().setSortDirection(dir);
- viewer.getTable().setSortColumn(column);
- viewer.refresh();
- }
- });
-
- }
-
- _tableViewer.setContentProvider(new QueueContentProviderImpl());
- _tableViewer.setLabelProvider(new QueueLabelProviderImpl());
-
- _tableViewer.setUseHashlookup(true);
- _tableViewer.setSorter(tableSorter);
- _table.setSortColumn(_table.getColumn(0));
- _table.setSortDirection(SWT.UP);
-
- addTableListeners();
- }
-
- protected void createLowerAreaButton(Composite parent)
- {
- Composite lowerButtonComposite = _toolkit.createComposite(parent, SWT.NONE);
- GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, false);
- lowerButtonComposite.setLayoutData(gridData);
- lowerButtonComposite.setLayout(new GridLayout());
-
- final Button attributesButton = _toolkit.createButton(lowerButtonComposite, "Select Attributes ...", SWT.PUSH);
- gridData = new GridData(SWT.RIGHT, SWT.CENTER, true, false);
- attributesButton.setLayoutData(gridData);
- attributesButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- chooseAttributes(attributesButton.getShell());
- }
- });
- }
-
- private void chooseAttributes(final Shell parent)
- {
-
- List<String> availableAttributes;
- if(_ApiVersion.greaterThanOrEqualTo(1, 3))
- {
- //Qpid JMX API 1.3+, request the current queue attributes names from the broker
- try
- {
- availableAttributes = _vhmb.retrieveQueueAttributeNames();
- }
- catch (IOException e)
- {
- availableAttributes = new ArrayList<String>(FALLBACK_ATTRIBUTES_LIST);
- }
- }
- else
- {
- //Qpid JMX API 1.2 or below, use the falllback list of names.
- availableAttributes = new ArrayList<String>(FALLBACK_ATTRIBUTES_LIST);
- }
-
-
- final List<String> chosenAttributes = new ArrayList<String>();
-
- final Shell shell = ViewUtility.createModalDialogShell(parent, "Select Attributes");
-
- Composite attributesComposite = _toolkit.createComposite(shell, SWT.NONE);
- attributesComposite.setBackground(shell.getBackground());
- attributesComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- attributesComposite.setLayout(new GridLayout(2,false));
-
- //add a selected-but-disabled check box for the Name attribute (its a mandatory attribute)
- final Button nameCheckbox = new Button(attributesComposite, SWT.CHECK);
- nameCheckbox.setText(ManagedQueue.ATTR_NAME);
- nameCheckbox.setSelection(true);
- nameCheckbox.setEnabled(false);
-
- for(String attr : availableAttributes)
- {
- if(attr.equals(ManagedQueue.ATTR_NAME))
- {
- //Name attribute is mandatory and gets added to the front of the list later
- continue;
- }
-
- final Button attrButton = new Button(attributesComposite, SWT.CHECK);
- attrButton.setText(attr);
-
- //if it was checked before, select it again now
- if(_selectedAttributes.contains(attr))
- {
- attrButton.setSelection(true);
- chosenAttributes.add(attr);
- }
-
- //add a selection listener to update the selected attribute list
- attrButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- if(attrButton.getSelection())
- {
- chosenAttributes.add(attrButton.getText());
- }
- else
- {
- chosenAttributes.remove(attrButton.getText());
- }
- }
- });
- }
-
- Composite okCancelButtonsComp = _toolkit.createComposite(shell);
- okCancelButtonsComp.setBackground(shell.getBackground());
- okCancelButtonsComp.setLayoutData(new GridData(SWT.RIGHT, SWT.FILL, true, true));
- okCancelButtonsComp.setLayout(new GridLayout(2,false));
-
- Button okButton = _toolkit.createButton(okCancelButtonsComp, "OK", SWT.PUSH);
- okButton.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, false));
- Button cancelButton = _toolkit.createButton(okCancelButtonsComp, "Cancel", SWT.PUSH);
- cancelButton.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, false));
-
- okButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- shell.dispose();
-
- //The Name attribute is mandatory, add it now, also
- //ensuring it is left-most by placing it first in the list
- List<String> newSelection = new ArrayList<String>();
- newSelection.add(ManagedQueue.ATTR_NAME);
-
- //now add all remaining choices in alphabetical order
- Collections.sort(chosenAttributes);
- newSelection.addAll(chosenAttributes);
-
- _tableViewerSemaphore.acquireUninterruptibly();
- try
- {
- _selectedAttributes = newSelection;
-
- clearTableComposite();
- createTable();
- saveAttributePreferences();
- }
- finally
- {
- _tableViewerSemaphore.release();
- }
-
- refresh(_mbean);
- }
- });
-
- cancelButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- shell.dispose();
- }
- });
-
- shell.setDefaultButton(okButton);
- shell.pack();
- ViewUtility.centerChildInParentShell(parent, shell);
-
- shell.open();
- }
-
- private String getQueueDepthString(Long value)
- {
- if(value == null)
- {
- return "-";
- }
-
- if (_ApiVersion.greaterThanOrEqualTo(1,2))
- {
- //Qpid JMX API 1.2 or above, returns Bytes
- return convertLongBytesToText(value);
- }
- else
- {
- //Qpid JMX API 1.1 or below, returns KB
- double mb = 1024.0;
-
- if(value > mb) //MB
- {
- return String.format("%.3f", (Double)(value / mb)) + " MB";
- }
- else //KB
- {
- return value + " KB";
- }
- }
- }
-
- private String convertLongBytesToText(Long value)
- {
- if(value == null)
- {
- return "-";
- }
-
- double mb = 1024.0 * 1024.0;
- double kb = 1024.0;
-
- if(value >= mb) //MB
- {
- return String.format("%.3f", (Double)((double)value / mb)) + " MB";
- }
- else if (value >= kb) //KB
- {
- return String.format("%.3f", (Double)((double)value / kb)) + " KB";
- }
- else //Bytes
- {
- return value + " Bytes";
- }
- }
-
- /**
- * sorter class for the table viewer.
- *
- */
- private static class QueueTableSorter extends ViewerSorter
- {
- protected int column;
- protected static final int ASCENDING = 0;
- protected static final int DESCENDING = 1;
-
- protected int direction;
-
- public QueueTableSorter()
- {
- this.column = 0;
- direction = ASCENDING;
- }
-
- public void setColumn(int column)
- {
- if(column == this.column)
- {
- // Same column as last sort; toggle the direction
- direction = 1 - direction;
- }
- else
- {
- // New column; do an ascending sort
- this.column = column;
- direction = ASCENDING;
- }
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public int compare(Viewer viewer, Object e1, Object e2)
- {
- List<Object> queue1 = (List<Object>) e1;
- List<Object> queue2 = (List<Object>) e2;
-
- int comparison = 0;
- switch(column)
- {
- default:
- if(queue1.get(column) instanceof Comparable)
- {
- comparison = ((Comparable)queue1.get(column)).compareTo((Comparable) queue2.get(column));
- }
- }
- // If descending order, flip the direction
- if(direction == DESCENDING)
- {
- comparison = -comparison;
- }
- return comparison;
- }
- }
-
- /**
- * Content Provider class for the table viewer for Qpid JMX API 1.3 and above.
- */
- private static class QueueContentProviderImpl implements IStructuredContentProvider
- {
-
- public void inputChanged(Viewer v, Object oldInput, Object newInput)
- {
-
- }
-
- public void dispose()
- {
-
- }
-
- @SuppressWarnings("unchecked")
- public Object[] getElements(Object parent)
- {
- return ((List<List<Object>>) parent).toArray();
- }
- }
-
- /**
- * Label Provider class for the table viewer for for Qpid JMX API 1.3 and above.
- */
- private class QueueLabelProviderImpl extends LabelProvider implements ITableLabelProvider
- {
- @SuppressWarnings("unchecked")
- public String getColumnText(Object element, int columnIndex)
- {
- List<Object> attributes = (List<Object>) element;
-
- switch (columnIndex)
- {
- default :
- String attrName = _selectedAttributes.get(columnIndex);
-
- if(ATTR_QUEUE_DEPTH.equals(attrName))
- {
- return getQueueDepthString((Long) attributes.get(columnIndex));
- }
- else if(ATTR_MAX_QUEUE_DEPTH.equals(attrName) || ATTR_MAX_MSG_SIZE.equals(attrName))
- {
- Number val = (Number)attributes.get(columnIndex);
- return convertLongBytesToText(val.longValue());
- }
- else if(ATTR_MAX_MSG_AGE.equals(attrName))
- {
- return String.valueOf(attributes.get(columnIndex) + "ms");
- }
-
- return String.valueOf(attributes.get(columnIndex));
- }
- }
-
- public Image getColumnImage(Object element, int columnIndex)
- {
- return null;
- }
- }
-
- @SuppressWarnings("unchecked")
- @Override
- protected void addMBeanToFavourites()
- {
- int selectionIndex = _table.getSelectionIndex();
-
- if (selectionIndex == -1)
- {
- return;
- }
-
- int[] selectedIndices = _table.getSelectionIndices();
-
- ArrayList<ManagedBean> selectedMBeans = new ArrayList<ManagedBean>();
-
- boolean allSucceded = true;
- //the entries are created from an List<Object> with the attribute values (name first)
- for(int index = 0; index < selectedIndices.length ; index++)
- {
- List<Object> queueEntry = (List<Object>) _table.getItem(selectedIndices[index]).getData();
- String queueName = (String) queueEntry.get(0);
-
- ManagedBean queueMBean = _serverRegistry.getQueue(queueName, _virtualHost);
-
- //check queue had not already been unregistered before trying to add it
- if(queueMBean != null)
- {
- selectedMBeans.add(queueMBean);
- }
- else
- {
- allSucceded = false;
- }
- }
-
- if(allSucceded)
- {
- //ensure the status bar is cleared of any previous failures added by the below
- ViewUtility.clearStatusBar();
- }
- else
- {
- ViewUtility.operationFailedStatusBarMessage("A selected queue could not be added as it was no longer registered");
- refresh();
- }
-
-
- IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- NavigationView view = (NavigationView)window.getActivePage().findView(NavigationView.ID);
-
- ManagedBean bean = null;
- try
- {
- for(ManagedBean mbean: selectedMBeans)
- {
- bean = mbean;
- view.addManagedBean(mbean);
- }
- }
- catch (Exception ex)
- {
- MBeanUtility.handleException(bean, ex);
- }
- }
-
- @SuppressWarnings("unchecked")
- @Override
- protected void openMBean()
- {
- int selectionIndex = _table.getSelectionIndex();
-
- if (selectionIndex == -1)
- {
- return;
- }
-
- ManagedBean selectedMBean;
-
- //the entries are created from an List<Object> with the attribute values (name first)
- List<Object> queueEntry = (List<Object>) _table.getItem(selectionIndex).getData();
- String queueName = (String) queueEntry.get(0);
- selectedMBean = _serverRegistry.getQueue(queueName, _virtualHost);
-
- if(selectedMBean == null)
- {
- ViewUtility.popupErrorMessage("Error", "Unable to retrieve the selected MBean to open it");
- return;
- }
-
- IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- MBeanView view = (MBeanView) window.getActivePage().findView(MBeanView.ID);
- try
- {
- view.openMBean(selectedMBean);
- }
- catch (Exception ex)
- {
- MBeanUtility.handleException(selectedMBean, ex);
- }
- }
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/users/UserManagementTabControl.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/users/UserManagementTabControl.java
deleted file mode 100644
index fdcc25d337..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/users/UserManagementTabControl.java
+++ /dev/null
@@ -1,925 +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.management.ui.views.users;
-
-import static org.apache.qpid.management.common.mbeans.UserManagement.RIGHTS_ADMIN;
-import static org.apache.qpid.management.common.mbeans.UserManagement.RIGHTS_READ_ONLY;
-import static org.apache.qpid.management.common.mbeans.UserManagement.RIGHTS_READ_WRITE;
-import static org.apache.qpid.management.common.mbeans.UserManagement.USERNAME;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-
-import javax.management.MBeanServerConnection;
-import javax.management.MBeanServerInvocationHandler;
-import javax.management.openmbean.CompositeData;
-import javax.management.openmbean.TabularDataSupport;
-
-import org.apache.qpid.management.ui.ApiVersion;
-import org.apache.qpid.management.ui.ApplicationRegistry;
-import org.apache.qpid.management.ui.ManagedBean;
-import org.apache.qpid.management.common.mbeans.UserManagement;
-import org.apache.qpid.management.ui.jmx.JMXManagedObject;
-import org.apache.qpid.management.ui.jmx.MBeanUtility;
-import org.apache.qpid.management.ui.views.TabControl;
-import org.apache.qpid.management.ui.views.ViewUtility;
-import org.eclipse.jface.dialogs.InputDialog;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.ITableLabelProvider;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.TableViewerColumn;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerSorter;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.TabFolder;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.TableColumn;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.ScrolledForm;
-
-
-/**
- * Control class for the UserManagement mbean.
- */
-public class UserManagementTabControl extends TabControl
-{
- private FormToolkit _toolkit;
- private ScrolledForm _form;
- private Table _table = null;
- private TableViewer _tableViewer = null;
-
- private TabularDataSupport _userDetails = null;
- private UserManagement _ummb;
- private ApiVersion _ApiVersion;
-
- public UserManagementTabControl(TabFolder tabFolder, JMXManagedObject mbean, MBeanServerConnection mbsc)
- {
- super(tabFolder);
- _mbean = mbean;
- _ApiVersion = ApplicationRegistry.getServerRegistry(mbean).getManagementApiVersion();
- _ummb = (UserManagement)
- MBeanServerInvocationHandler.newProxyInstance(mbsc, mbean.getObjectName(),
- UserManagement.class, false);
- _toolkit = new FormToolkit(_tabFolder.getDisplay());
- _form = _toolkit.createScrolledForm(_tabFolder);
- _form.getBody().setLayout(new GridLayout());
- createWidgets();
- }
-
- /**
- * @see TabControl#getControl()
- */
- public Control getControl()
- {
- return _form;
- }
-
- /**
- * @see TabControl#setFocus()
- */
- public void setFocus()
- {
- _table.setFocus();
- }
-
- @Override
- public void refresh(ManagedBean mbean)
- {
- _userDetails = null;
- try
- {
- _userDetails = (TabularDataSupport) _ummb.viewUsers();
- }
- catch(Exception e)
- {
- MBeanUtility.handleException(_mbean, e);
-
- }
-
- _tableViewer.setInput(_userDetails);
-
- layout();
- }
-
- public void layout()
- {
- _form.layout(true);
- _form.getBody().layout(true, true);
- }
-
- private void createWidgets()
- {
- Composite paramsComposite = _toolkit.createComposite(_form.getBody(), SWT.NONE);
- paramsComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- paramsComposite.setLayout(new GridLayout());
-
- Group viewUsersGroup = new Group(paramsComposite, SWT.SHADOW_NONE);
- viewUsersGroup.setBackground(paramsComposite.getBackground());
- viewUsersGroup.setText("Users");
- viewUsersGroup.setLayout(new GridLayout(2,false));
- viewUsersGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
-
- Composite tableComposite = _toolkit.createComposite(viewUsersGroup);
- GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
- gridData.heightHint = 250;
- gridData.minimumHeight = 250;
- tableComposite.setLayoutData(gridData);
- tableComposite.setLayout(new GridLayout(2,false));
-
- _table = new Table (tableComposite, SWT.MULTI | SWT.SCROLL_LINE | SWT.BORDER | SWT.FULL_SELECTION);
- _table.setLinesVisible (true);
- _table.setHeaderVisible (true);
- gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
- _table.setLayoutData(gridData);
-
- _tableViewer = new TableViewer(_table);
- final TableSorter tableSorter = new TableSorter();
-
- String[] titles = { "Username", "JMX Management Rights" };
- int[] bounds = { 310, 200 };
- for (int i = 0; i < titles.length; i++)
- {
- final int index = i;
- final TableViewerColumn viewerColumn = new TableViewerColumn(_tableViewer, SWT.NONE);
- final TableColumn column = viewerColumn.getColumn();
-
- column.setText(titles[i]);
- column.setWidth(bounds[i]);
- column.setResizable(true);
-
- //Setting the right sorter
- column.addSelectionListener(new SelectionAdapter()
- {
- @Override
- public void widgetSelected(SelectionEvent e)
- {
- tableSorter.setColumn(index);
- final TableViewer viewer = _tableViewer;
- int dir = viewer .getTable().getSortDirection();
- if (viewer.getTable().getSortColumn() == column)
- {
- dir = dir == SWT.UP ? SWT.DOWN : SWT.UP;
- }
- else
- {
- dir = SWT.UP;
- }
- viewer.getTable().setSortDirection(dir);
- viewer.getTable().setSortColumn(column);
- viewer.refresh();
- }
- });
-
- }
-
- _tableViewer.setContentProvider(new ContentProviderImpl());
- _tableViewer.setLabelProvider(new LabelProviderImpl());
- _tableViewer.setSorter(tableSorter);
- _table.setSortColumn(_table.getColumn(0));
- _table.setSortDirection(SWT.UP);
-
- Composite buttonsComposite = _toolkit.createComposite(tableComposite);
- gridData = new GridData(SWT.FILL, SWT.TOP, false, false);
- gridData.heightHint = 165;
- buttonsComposite.setLayoutData(gridData);
- buttonsComposite.setLayout(new GridLayout());
-
- final Button addUserButton = _toolkit.createButton(buttonsComposite, "Add New User ...", SWT.PUSH);
- gridData = new GridData(SWT.CENTER, SWT.TOP, false, true);
- gridData.widthHint = 125;
- addUserButton.setLayoutData(gridData);
- addUserButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- addUser(addUserButton.getShell());
- }
- });
-
- final Button deleteUsersButton = _toolkit.createButton(buttonsComposite, "Delete User(s)", SWT.PUSH);
- gridData = new GridData(SWT.CENTER, SWT.BOTTOM, false, false);
- gridData.widthHint = 125;
- deleteUsersButton.setLayoutData(gridData);
- deleteUsersButton.setEnabled(false);
- deleteUsersButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- int selectionIndex = _table.getSelectionIndex();
-
- if (selectionIndex != -1)
- {
- deleteUsers();
- }
- }
- });
-
- final Button setPasswordButton = _toolkit.createButton(buttonsComposite, "Set Password ...", SWT.PUSH);
- gridData = new GridData(SWT.CENTER, SWT.BOTTOM, false, false);
- gridData.widthHint = 125;
- setPasswordButton.setLayoutData(gridData);
- setPasswordButton.setEnabled(false);
- setPasswordButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- int selectionIndex = _table.getSelectionIndex();
-
- if (selectionIndex != -1)
- {
- final CompositeData selectedLogger = (CompositeData)_table.getItem(
- selectionIndex).getData();
- String user = selectedLogger.get(USERNAME).toString();
- InputDialog id = new InputDialog(setPasswordButton.getShell(),"Set Password",
- "Please enter the new password for '" + user + "':",null,null){
- @Override
- protected Control createDialogArea(Composite parent)
- {
- Control control = super.createDialogArea(parent);
- //set the Text field echo char to '*' to mask the password
- getText().setEchoChar('*');
- //return the normal result
- return control;
- }
- };
-
- int returnValue;
- while((returnValue = id.open()) == InputDialog.OK)
- {
- if (id.getValue() == null || id.getValue().toString().length() == 0)
- {
- ViewUtility.popupErrorMessage("Set Password", "Please enter a valid password");
- }
- else
- {
- break;
- }
- }
-
- if (returnValue == InputDialog.OK)
- {
- char[] password = id.getValue().toCharArray();
-
- // Qpid JMX API 1.1 and below expects the password to be sent as a hashed value.
- if (_ApiVersion.lessThanOrEqualTo(1,1))
- {
- try
- {
- password = ViewUtility.getHash(id.getValue());
- }
- catch (Exception hashException)
- {
- ViewUtility.popupErrorMessage("Set Password",
- "Unable to calculate hash for Password:"
- + hashException.getMessage());
- return;
- }
- }
-
- try
- {
- boolean result = _ummb.setPassword(user, password);
- ViewUtility.operationResultFeedback(result, "Updated user password", "Failed to update user password");
- }
- catch(Exception e2)
- {
- ViewUtility.operationFailedStatusBarMessage("Error updating user password");
- MBeanUtility.handleException(_mbean, e2);
- }
- }
- }
- }
- });
-
- final Button setRightsButton = _toolkit.createButton(buttonsComposite, "Set Rights ...", SWT.PUSH);
- gridData = new GridData(SWT.CENTER, SWT.BOTTOM, false, false);
- gridData.widthHint = 125;
- setRightsButton.setLayoutData(gridData);
- setRightsButton.setEnabled(false);
- setRightsButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- int selectionIndex = _table.getSelectionIndex();
-
- if (selectionIndex != -1)
- {
- setRights(setRightsButton.getShell());
- }
- }
- });
-
- _tableViewer.addSelectionChangedListener(new ISelectionChangedListener(){
- public void selectionChanged(SelectionChangedEvent evt)
- {
- int selectionIndex = _table.getSelectionIndex();
-
- if (selectionIndex == -1)
- {
- deleteUsersButton.setEnabled(false);
- setRightsButton.setEnabled(false);
- setPasswordButton.setEnabled(false);
- return;
- }
- else
- {
- deleteUsersButton.setEnabled(true);
- setRightsButton.setEnabled(true);
- }
-
- if (_table.getSelectionCount() > 1)
- {
- setPasswordButton.setEnabled(false);
- }
- else
- {
- setPasswordButton.setEnabled(true);
- }
- }
- });
-
- Group miscGroup = new Group(paramsComposite, SWT.SHADOW_NONE);
- miscGroup.setBackground(paramsComposite.getBackground());
- miscGroup.setText("Misc");
- gridData = new GridData(SWT.LEFT, SWT.TOP, true, true);
- miscGroup.setLayoutData(gridData);
- miscGroup.setLayout(new GridLayout(2,false));
-
- final Button reloadUserDetails = _toolkit.createButton(miscGroup,
- "Reload User Details", SWT.PUSH);
- if(_ApiVersion.lessThan(1, 2))
- {
- //this only reloaded the JMX rights file before Qpid JMX API 1.2
- _toolkit.createLabel(miscGroup, " Loads the current management rights file from disk");
- }
- else
- {
- //since Qpid JMX API 1.2 it also reloads the password file
- _toolkit.createLabel(miscGroup, " Loads the current password and management rights files from disk");
- }
- reloadUserDetails.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- int response = ViewUtility.popupOkCancelConfirmationMessage("Reload User Data",
- "Do you want to reload user data ?");
- if (response == SWT.OK)
- {
- try
- {
- boolean result = _ummb.reloadData();
- ViewUtility.operationResultFeedback(result, "Reloaded user data", "Failed to reload user data");
- }
- catch(Exception e3)
- {
- ViewUtility.operationFailedStatusBarMessage("Error reloading user data");
- MBeanUtility.handleException(_mbean, e3);
- }
- refresh(_mbean);
- }
- }
- });
-
- }
-
-
- /**
- * Content Provider class for the table viewer
- */
- private static class ContentProviderImpl implements IStructuredContentProvider
- {
-
- public void inputChanged(Viewer v, Object oldInput, Object newInput)
- {
-
- }
-
- public void dispose()
- {
-
- }
-
- public Object[] getElements(Object parent)
- {
- Collection<Object> rowCollection = ((TabularDataSupport) parent).values();
-
- return rowCollection.toArray();
- }
- }
-
- /**
- * Label Provider class for the table viewer
- */
- private class LabelProviderImpl extends LabelProvider implements ITableLabelProvider
- {
- @Override
- public String getColumnText(Object element, int columnIndex)
- {
- switch (columnIndex)
- {
- case 0 : // username column
- return (String) ((CompositeData) element).get(USERNAME);
- case 1 : // rights column
- return classifyUserRights((CompositeData) element);
- default :
- return "-";
- }
- }
-
- @Override
- public Image getColumnImage(Object element, int columnIndex)
- {
- return null;
- }
-
- }
-
- /**
- * Sorter class for the table viewer.
- *
- */
- private class TableSorter extends ViewerSorter
- {
- private int column;
- private static final int ASCENDING = 0;
- private static final int DESCENDING = 1;
-
- private int direction;
-
- public TableSorter()
- {
- this.column = 0;
- direction = ASCENDING;
- }
-
- public void setColumn(int column)
- {
- if(column == this.column)
- {
- // Same column as last sort; toggle the direction
- direction = 1 - direction;
- }
- else
- {
- // New column; do an ascending sort
- this.column = column;
- direction = ASCENDING;
- }
- }
-
- @Override
- public int compare(Viewer viewer, Object e1, Object e2)
- {
- CompositeData user1 = (CompositeData) e1;
- CompositeData user2 = (CompositeData) e2;
-
- int comparison = 0;
- switch(column)
- {
- case 0:
- comparison = String.valueOf(user1.get(USERNAME)).compareTo(
- String.valueOf(user2.get(USERNAME)));
- break;
- case 1:
- comparison = classifyUserRights(user1).compareTo(classifyUserRights(user2));
- break;
- default:
- comparison = 0;
- }
- // If descending order, flip the direction
- if(direction == DESCENDING)
- {
- comparison = -comparison;
- }
- return comparison;
- }
- }
-
- private String classifyUserRights(CompositeData user)
- {
- Boolean read = (Boolean)user.get(RIGHTS_READ_ONLY);
- Boolean write = (Boolean)user.get(RIGHTS_READ_WRITE);
- Boolean admin = (Boolean)user.get(RIGHTS_ADMIN);
-
- if(admin)
- {
- return "Admin";
- }
- else if(write)
- {
- return "Read & Write";
- }
- else if(read)
- {
- return "Read Only";
- }
- else
- {
- return "No Access";
- }
- }
-
- private void setRights(final Shell parent)
- {
-
- int selectionIndex = _table.getSelectionIndex();
-
- if (selectionIndex == -1)
- {
- return;
- }
-
- int[] selectedIndices = _table.getSelectionIndices();
-
- final ArrayList<String> selectedUsers = new ArrayList<String>();
-
- for(int index = 0; index < selectedIndices.length ; index++)
- {
- CompositeData selectedUser = (CompositeData)_table.getItem(selectedIndices[index]).getData();
- String user = selectedUser.get(USERNAME).toString();
- selectedUsers.add(user);
- }
-
- String selectedUsersString = "";
- for(String user : selectedUsers)
- {
- selectedUsersString = selectedUsersString.concat(user + ", ");
- }
- //cut off last ", "
- int lastIndex = selectedUsersString.lastIndexOf(',');
- if (lastIndex != -1)
- {
- selectedUsersString = selectedUsersString.substring(0,lastIndex);
- }
-
-
-
- final Shell shell = ViewUtility.createModalDialogShell(parent, "Set Rights");
-
- Label overview = _toolkit.createLabel(shell,"Select rights for user(s): ");
- overview.setBackground(shell.getBackground());
- Label userNamesLabel= _toolkit.createLabel(shell,selectedUsersString);
- userNamesLabel.setBackground(shell.getBackground());
-
- Composite buttons = _toolkit.createComposite(shell, SWT.NONE);
- buttons.setBackground(shell.getBackground());
- buttons.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- buttons.setLayout(new GridLayout(4,false));
-
- final Button noneButton = new Button(buttons, SWT.RADIO);
- noneButton.setText("No Access");
- noneButton.setSelection(true);
- final Button readButton = new Button(buttons, SWT.RADIO);
- readButton.setText("Read Only");
- final Button writeButton = new Button(buttons, SWT.RADIO);
- writeButton.setText("Read + Write");
- final Button adminButton = new Button(buttons, SWT.RADIO);
- adminButton.setText("Admin");
-
- Composite okCancelButtonsComp = _toolkit.createComposite(shell);
- okCancelButtonsComp.setBackground(shell.getBackground());
- okCancelButtonsComp.setLayoutData(new GridData(SWT.RIGHT, SWT.FILL, true, true));
- okCancelButtonsComp.setLayout(new GridLayout(2,false));
-
- Button okButton = _toolkit.createButton(okCancelButtonsComp, "OK", SWT.PUSH);
- okButton.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, false));
- Button cancelButton = _toolkit.createButton(okCancelButtonsComp, "Cancel", SWT.PUSH);
- cancelButton.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, false));
-
- okButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- boolean read = readButton.getSelection();
- boolean write = writeButton.getSelection();
- boolean admin = adminButton.getSelection();
-
- shell.dispose();
-
- HashMap<String,Boolean> results = new HashMap<String,Boolean>();
- try
- {
- //perform the rights updates, save the results.
- for(String user : selectedUsers)
- {
- boolean result = _ummb.setRights(user,read,write,admin);
- results.put(user, result);
- }
-
- //categorise the overall result
- boolean overallResult = true;
- for(boolean result : results.values())
- {
- if (!result)
- {
- overallResult = false;
- }
- }
-
- //output the result to status bar if all success, and dialogue if not
- if(overallResult)
- {
- ViewUtility.operationResultFeedback(overallResult, "Updated user rights", null);
- }
- else
- {
- String failedToUpdateRightsUsers = "";
- for(String user : results.keySet())
- {
- if(!results.get(user))
- {
- failedToUpdateRightsUsers = failedToUpdateRightsUsers.concat(user + ", ");
- }
- }
-
- //cut off last ", "
- int lastIndex2 = failedToUpdateRightsUsers.lastIndexOf(',');
- if (lastIndex2 != -1)
- {
- failedToUpdateRightsUsers = failedToUpdateRightsUsers.substring(0, lastIndex2);
- }
-
- ViewUtility.operationResultFeedback(overallResult, null, "Failed to update user(s) rights: " + failedToUpdateRightsUsers);
- }
- }
- catch(Exception e4)
- {
- ViewUtility.operationFailedStatusBarMessage("Error updating user rights");
- MBeanUtility.handleException(_mbean, e4);
- }
- refresh(_mbean);
- }
- });
-
- cancelButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- shell.dispose();
- }
- });
-
- shell.setDefaultButton(okButton);
- shell.pack();
- ViewUtility.centerChildInParentShell(parent, shell);
-
- shell.open();
- }
-
- private void addUser(final Shell parent)
- {
- final Shell shell = ViewUtility.createModalDialogShell(parent, "Add New User");
-
- Composite usernameComposite = _toolkit.createComposite(shell, SWT.NONE);
- usernameComposite.setBackground(shell.getBackground());
- usernameComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- usernameComposite.setLayout(new GridLayout(2,false));
-
- _toolkit.createLabel(usernameComposite,"Username:").setBackground(shell.getBackground());
- final Text usernameText = new Text(usernameComposite, SWT.BORDER);
- usernameText.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
-
- Composite passwordComposite = _toolkit.createComposite(shell, SWT.NONE);
- passwordComposite.setBackground(shell.getBackground());
- passwordComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- passwordComposite.setLayout(new GridLayout(2,false));
-
- _toolkit.createLabel(passwordComposite,"Password:").setBackground(shell.getBackground());
- final Text passwordText = new Text(passwordComposite, SWT.BORDER | SWT.PASSWORD);
- passwordText.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
-
- Group buttonGroup = new Group(shell, SWT.NONE);
- buttonGroup.setText("JMX Management Rights");
- buttonGroup.setBackground(shell.getBackground());
- buttonGroup.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- buttonGroup.setLayout(new GridLayout(4,false));
-
- final Button noneButton = new Button(buttonGroup, SWT.RADIO);
- noneButton.setText("No Access");
- noneButton.setSelection(true);
- final Button readButton = new Button(buttonGroup, SWT.RADIO);
- readButton.setText("Read Only");
- final Button writeButton = new Button(buttonGroup, SWT.RADIO);
- writeButton.setText("Read + Write");
- final Button adminButton = new Button(buttonGroup, SWT.RADIO);
- adminButton.setText("Admin");
-
- Composite okCancelButtonsComp = _toolkit.createComposite(shell);
- okCancelButtonsComp.setBackground(shell.getBackground());
- okCancelButtonsComp.setLayoutData(new GridData(SWT.RIGHT, SWT.FILL, true, true));
- okCancelButtonsComp.setLayout(new GridLayout(2,false));
-
- Button okButton = _toolkit.createButton(okCancelButtonsComp, "OK", SWT.PUSH);
- okButton.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, false));
- Button cancelButton = _toolkit.createButton(okCancelButtonsComp, "Cancel", SWT.PUSH);
- cancelButton.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, false));
-
- okButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- String username = usernameText.getText();
- String password = passwordText.getText();
-
- if (username == null || username.length() == 0)
- {
- ViewUtility.popupErrorMessage("Add New User", "Please enter a valid username");
- return;
- }
-
- if (password == null || password.length() == 0)
- {
- ViewUtility.popupErrorMessage("Add New User", "Please enter a valid password");
- return;
- }
-
- char[] passwordChars = password.toCharArray();
-
- // Qpid JMX API 1.1 and below expects the password to be sent as a hashed value.
- if (_ApiVersion.lessThanOrEqualTo(1,1))
- {
- try
- {
- passwordChars = ViewUtility.getHash(password);
- }
- catch (Exception hashException)
- {
- ViewUtility.popupErrorMessage("Set Password",
- "Unable to calculate hash for Password:"
- + hashException.getMessage());
- return;
- }
- }
-
- boolean read = readButton.getSelection();
- boolean write = writeButton.getSelection();
- boolean admin = adminButton.getSelection();
-
- shell.dispose();
- try
- {
- boolean result = false;
- // If we have Qpid JMX API 1.7 or above, use newer createUser method with String based password.
- if (_ApiVersion.greaterThanOrEqualTo(1,7))
- {
- result = _ummb.createUser(username, password, read, write, admin);
- }
- else
- {
- result = _ummb.createUser(username, passwordChars, read, write, admin);
- }
-
- ViewUtility.operationResultFeedback(result, "Created user", "Failed to create user");
- }
- catch(Exception e5)
- {
- ViewUtility.operationFailedStatusBarMessage("Error creating user");
- MBeanUtility.handleException(_mbean, e5);
- }
-
- refresh(_mbean);
- }
- });
-
- cancelButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- shell.dispose();
- }
- });
-
- shell.setDefaultButton(okButton);
- shell.pack();
- ViewUtility.centerChildInParentShell(parent, shell);
-
- shell.open();
- }
-
- private void deleteUsers()
- {
- int selectionIndex = _table.getSelectionIndex();
- if (selectionIndex == -1)
- {
- return;
- }
-
- int[] selectedIndices = _table.getSelectionIndices();
-
- ArrayList<String> selectedUsers = new ArrayList<String>();
-
- for(int index = 0; index < selectedIndices.length ; index++)
- {
- CompositeData selectedUser = (CompositeData)_table.getItem(selectedIndices[index]).getData();
- String user = selectedUser.get(USERNAME).toString();
- selectedUsers.add(user);
- }
-
- String selectedUsersString = "";
- for(String user : selectedUsers)
- {
- selectedUsersString = selectedUsersString.concat(user + ", ");
- }
- //cut off last ", "
- int lastIndex = selectedUsersString.lastIndexOf(',');
- if (lastIndex != -1)
- {
- selectedUsersString = selectedUsersString.substring(0,lastIndex);
- }
-
- int response = ViewUtility.popupOkCancelConfirmationMessage(
- "User Management", "Delete user(s): " + selectedUsersString + " ?");
-
- if (response == SWT.OK)
- {
- HashMap<String,Boolean> results = new HashMap<String,Boolean>();
- try
- {
- //perform the deletes, save the results.
- for(String user : selectedUsers)
- {
- boolean result = _ummb.deleteUser(user);
- results.put(user, result);
- }
-
- //categorise the overall result
- boolean overallResult = true;
- for(boolean result : results.values())
- {
- if (!result)
- {
- overallResult = false;
- }
- }
-
- //output the result to status bar if all success, and dialogue if not
- if(overallResult)
- {
- ViewUtility.operationResultFeedback(overallResult, "Deleted user(s)", null);
- }
- else
- {
- String failedToDeleteUsers = "";
- for(String user : results.keySet())
- {
- if(!results.get(user))
- {
- failedToDeleteUsers = failedToDeleteUsers.concat(user + ", ");
- }
- }
-
- //cut off last ", "
- lastIndex = failedToDeleteUsers.lastIndexOf(',');
- if (lastIndex != -1)
- {
- failedToDeleteUsers = failedToDeleteUsers.substring(0, lastIndex);
- }
-
- ViewUtility.operationResultFeedback(overallResult, null, "Failed to delete user(s): " + failedToDeleteUsers);
- }
-
- }
- catch(Exception e1)
- {
- ViewUtility.operationFailedStatusBarMessage("Error deleting user(s)");
- MBeanUtility.handleException(_mbean, e1);
- }
-
- refresh(_mbean);;
- }
- }
-}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/vhost/VHostTabControl.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/vhost/VHostTabControl.java
deleted file mode 100644
index 0cbb1389d8..0000000000
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/vhost/VHostTabControl.java
+++ /dev/null
@@ -1,871 +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.management.ui.views.vhost;
-
-import static org.apache.qpid.management.ui.Constants.DEFAULT_EXCHANGE_TYPE_VALUES;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-import javax.management.MBeanServerConnection;
-import javax.management.MBeanServerInvocationHandler;
-
-import org.apache.qpid.management.ui.ApiVersion;
-import org.apache.qpid.management.ui.ApplicationRegistry;
-import org.apache.qpid.management.ui.ManagedBean;
-import org.apache.qpid.management.ui.ServerRegistry;
-import org.apache.qpid.management.common.mbeans.ManagedBroker;
-import org.apache.qpid.management.ui.jmx.JMXManagedObject;
-import org.apache.qpid.management.ui.jmx.MBeanUtility;
-import org.apache.qpid.management.ui.views.MBeanView;
-import org.apache.qpid.management.ui.views.TabControl;
-import org.apache.qpid.management.ui.views.ViewUtility;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.ITableLabelProvider;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerSorter;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.MouseEvent;
-import org.eclipse.swt.events.MouseListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.TabFolder;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.TableColumn;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.forms.widgets.Form;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-
-
-/**
- * Control class for the VirtualHostManager mbean operations tab.
- */
-public class VHostTabControl extends TabControl
-{
- private FormToolkit _toolkit;
- private Form _form;
- private Table _queueTable = null;
- private TableViewer _queueTableViewer = null;
- private Table _exchangeTable = null;
- private TableViewer _exchangeTableViewer = null;
-
- private Composite _paramsComposite = null;
-
- private ManagedBroker _vhmb;
- private ApiVersion _ApiVersion;
- private List<ManagedBean> _queues;
- private List<ManagedBean> _exchanges;
- private ServerRegistry _serverRegistry;
-
- public VHostTabControl(TabFolder tabFolder, JMXManagedObject mbean, MBeanServerConnection mbsc)
- {
- super(tabFolder);
- _mbean = mbean;
- _serverRegistry = ApplicationRegistry.getServerRegistry(mbean);
- _ApiVersion = _serverRegistry.getManagementApiVersion();
- _vhmb = (ManagedBroker) MBeanServerInvocationHandler.newProxyInstance(mbsc,
- mbean.getObjectName(), ManagedBroker.class, false);
- _toolkit = new FormToolkit(_tabFolder.getDisplay());
- _form = _toolkit.createForm(_tabFolder);
- _form.getBody().setLayout(new GridLayout());
- createComposites();
- createWidgets();
- }
-
- private void createComposites()
- {
- _paramsComposite = _toolkit.createComposite(_form.getBody(), SWT.NONE);
- _paramsComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- _paramsComposite.setLayout(new GridLayout(2, true));
- }
-
- /**
- * @see TabControl#getControl()
- */
- public Control getControl()
- {
- return _form;
- }
-
- /**
- * @see TabControl#setFocus()
- */
- public void setFocus()
- {
-
- }
-
- @Override
- public void refresh(ManagedBean mbean)
- {
- ServerRegistry serverRegistry = ApplicationRegistry.getServerRegistry(MBeanView.getServer());
- _queues = serverRegistry.getQueues(MBeanView.getVirtualHost());
- _exchanges = serverRegistry.getExchanges(MBeanView.getVirtualHost());
-
- _queueTableViewer.setInput(_queues);
- _exchangeTableViewer.setInput(_exchanges);
-
- layout();
- }
-
- public void layout()
- {
- _form.layout(true);
- _form.getBody().layout(true, true);
- }
-
- private void createWidgets()
- {
- Group queuesGroup = new Group(_paramsComposite, SWT.SHADOW_NONE);
- queuesGroup.setBackground(_paramsComposite.getBackground());
- queuesGroup.setText("Queues");
- queuesGroup.setLayout(new GridLayout(2,false));
- GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
- queuesGroup.setLayoutData(gridData);
-
- _queueTable = new Table (queuesGroup, SWT.MULTI | SWT.SCROLL_LINE | SWT.BORDER | SWT.FULL_SELECTION);
- _queueTable.setLinesVisible (true);
- _queueTable.setHeaderVisible (true);
- GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
- _queueTable.setLayoutData(data);
-
- _queueTableViewer = new TableViewer(_queueTable);
- final TableSorter tableSorter = new TableSorter();
-
- String[] titles = {"Name"};
- int[] bounds = { 250 };
- for (int i = 0; i < titles.length; i++)
- {
- final int index = i;
- final TableColumn column = new TableColumn (_queueTable, SWT.NONE);
-
- column.setText(titles[i]);
- column.setWidth(bounds[i]);
- column.setResizable(true);
-
- //Setting the right sorter
- column.addSelectionListener(new SelectionAdapter()
- {
- @Override
- public void widgetSelected(SelectionEvent e)
- {
- tableSorter.setColumn(index);
- final TableViewer viewer = _queueTableViewer;
- int dir = viewer .getTable().getSortDirection();
- if (viewer.getTable().getSortColumn() == column)
- {
- dir = dir == SWT.UP ? SWT.DOWN : SWT.UP;
- }
- else
- {
- dir = SWT.UP;
- }
- viewer.getTable().setSortDirection(dir);
- viewer.getTable().setSortColumn(column);
- viewer.refresh();
- }
- });
-
- }
-
- _queueTableViewer.setContentProvider(new ContentProviderImpl());
- _queueTableViewer.setLabelProvider(new LabelProviderImpl());
- _queueTableViewer.setSorter(tableSorter);
- _queueTable.setSortColumn(_queueTable.getColumn(0));
- _queueTable.setSortDirection(SWT.UP);
-
- Composite queuesRightComposite = _toolkit.createComposite(queuesGroup);
- gridData = new GridData(SWT.FILL, SWT.FILL, false, true);
- queuesRightComposite.setLayoutData(gridData);
- queuesRightComposite.setLayout(new GridLayout());
-
- final Button createQueueButton = _toolkit.createButton(queuesRightComposite, "Create ...", SWT.PUSH);
- createQueueButton.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false));
- createQueueButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- createQueue(createQueueButton.getShell());
- }
- });
-
- final Button deleteQueueButton = _toolkit.createButton(queuesRightComposite, "Delete", SWT.PUSH);
- deleteQueueButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
- deleteQueueButton.setEnabled(false);
- deleteQueueButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- deleteQueuesOrExchanges(deleteQueueButton.getShell(), VhostOperations.DELETE_QUEUE);
- }
- });
-
- _queueTableViewer.addSelectionChangedListener(new ISelectionChangedListener(){
- public void selectionChanged(SelectionChangedEvent evt)
- {
- int selectionIndex = _queueTable.getSelectionIndex();
-
- if (selectionIndex != -1)
- {
- deleteQueueButton.setEnabled(true);
- }
- else
- {
- deleteQueueButton.setEnabled(false);
- }
- }
- });
-
- //listener for double clicking to open the selection mbean
- _queueTable.addMouseListener(new MouseListener()
- {
- // MouseListener implementation
- public void mouseDoubleClick(MouseEvent event)
- {
- openMBean(_queueTable);
- }
-
- public void mouseDown(MouseEvent e){}
- public void mouseUp(MouseEvent e){}
- });
-
- Group exchangesGroup = new Group(_paramsComposite, SWT.SHADOW_NONE);
- exchangesGroup.setBackground(_paramsComposite.getBackground());
- exchangesGroup.setText("Exchanges");
- exchangesGroup.setLayout(new GridLayout(2,false));
- gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
- exchangesGroup.setLayoutData(gridData);
-
- _exchangeTable = new Table (exchangesGroup, SWT.MULTI | SWT.SCROLL_LINE | SWT.BORDER | SWT.FULL_SELECTION);
- _exchangeTable.setLinesVisible (true);
- _exchangeTable.setHeaderVisible (true);
- data = new GridData(SWT.FILL, SWT.FILL, true, true);
- _exchangeTable.setLayoutData(data);
-
- _exchangeTableViewer = new TableViewer(_exchangeTable);
- final TableSorter exchangeTableSorter = new TableSorter();
-
- for (int i = 0; i < titles.length; i++)
- {
- final int index = i;
- final TableColumn column = new TableColumn (_exchangeTable, SWT.NONE);
-
- column.setText(titles[i]);
- column.setWidth(bounds[i]);
- column.setResizable(true);
-
- //Setting the right sorter
- column.addSelectionListener(new SelectionAdapter()
- {
- @Override
- public void widgetSelected(SelectionEvent e)
- {
- exchangeTableSorter.setColumn(index);
- final TableViewer viewer = _exchangeTableViewer;
- int dir = viewer .getTable().getSortDirection();
- if (viewer.getTable().getSortColumn() == column)
- {
- dir = dir == SWT.UP ? SWT.DOWN : SWT.UP;
- }
- else
- {
- dir = SWT.UP;
- }
- viewer.getTable().setSortDirection(dir);
- viewer.getTable().setSortColumn(column);
- viewer.refresh();
- }
- });
-
- }
-
- _exchangeTableViewer.setContentProvider(new ContentProviderImpl());
- _exchangeTableViewer.setLabelProvider(new LabelProviderImpl());
- _exchangeTableViewer.setSorter(exchangeTableSorter);
- _exchangeTable.setSortColumn(_exchangeTable.getColumn(0));
- _exchangeTable.setSortDirection(SWT.UP);
-
- Composite exchangesRightComposite = _toolkit.createComposite(exchangesGroup);
- gridData = new GridData(SWT.FILL, SWT.FILL, false, true);
- exchangesRightComposite.setLayoutData(gridData);
- exchangesRightComposite.setLayout(new GridLayout());
-
- final Button createExchangeButton = _toolkit.createButton(exchangesRightComposite, "Create ...", SWT.PUSH);
- createExchangeButton.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false));
- createExchangeButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- createExchange(createQueueButton.getShell());
- }
- });
-
- final Button deleteExchangeButton = _toolkit.createButton(exchangesRightComposite, "Delete", SWT.PUSH);
- deleteExchangeButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
- deleteExchangeButton.setEnabled(false);
- deleteExchangeButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- deleteQueuesOrExchanges(deleteExchangeButton.getShell(), VhostOperations.DELETE_EXCHANGE);
- }
- });
-
- _exchangeTableViewer.addSelectionChangedListener(new ISelectionChangedListener(){
- public void selectionChanged(SelectionChangedEvent evt)
- {
- int selectionIndex = _exchangeTable.getSelectionIndex();
-
- if (selectionIndex != -1)
- {
- deleteExchangeButton.setEnabled(true);
- }
- else
- {
- deleteExchangeButton.setEnabled(false);
- }
- }
- });
-
- //listener for double clicking to open the selection mbean
- _exchangeTable.addMouseListener(new MouseListener()
- {
- // MouseListener implementation
- public void mouseDoubleClick(MouseEvent event)
- {
- openMBean(_exchangeTable);
- }
-
- public void mouseDown(MouseEvent e){}
- public void mouseUp(MouseEvent e){}
- });
- }
-
-
- /**
- * Content Provider class for the table viewer
- */
- private static class ContentProviderImpl implements IStructuredContentProvider
- {
-
- public void inputChanged(Viewer v, Object oldInput, Object newInput)
- {
-
- }
-
- public void dispose()
- {
-
- }
-
- @SuppressWarnings("unchecked")
- public Object[] getElements(Object parent)
- {
- return ((List<ManagedBean>) parent).toArray();
- }
- }
-
- /**
- * Label Provider class for the table viewer
- */
- private static class LabelProviderImpl extends LabelProvider implements ITableLabelProvider
- {
- @Override
- public String getColumnText(Object element, int columnIndex)
- {
- switch (columnIndex)
- {
- case 0 : // name column
- return ((ManagedBean) element).getName();
- default :
- return "-";
- }
- }
-
- @Override
- public Image getColumnImage(Object element, int columnIndex)
- {
- return null;
- }
-
- }
-
- /**
- * Sorter class for the table viewer.
- *
- */
- public static class TableSorter extends ViewerSorter
- {
- private int column;
- private static final int ASCENDING = 0;
- private static final int DESCENDING = 1;
-
- private int direction = DESCENDING;
-
- public TableSorter()
- {
- this.column = 0;
- direction = ASCENDING;
- }
-
- public void setColumn(int column)
- {
- if (column == this.column)
- {
- // Same column as last sort; toggle the direction
- direction = 1 - direction;
- }
- else
- {
- // New column; do an ascending sort
- this.column = column;
- direction = ASCENDING;
- }
- }
-
- @Override
- public int compare(Viewer viewer, Object e1, Object e2)
- {
- ManagedBean mbean1 = (ManagedBean ) e1;
- ManagedBean mbean2 = (ManagedBean ) e2;
-
- int comparison = 0;
- switch(column)
- {
- case 0:
- comparison = mbean1.getName().compareTo(mbean2.getName());
- break;
- default:
- comparison = 0;
- }
- // If descending order, flip the direction
- if(direction == DESCENDING)
- {
- comparison = -comparison;
- }
- return comparison;
- }
- }
-
- private void createQueue(final Shell parent)
- {
- final Shell shell = ViewUtility.createModalDialogShell(parent, "Create Queue");
-
- Composite nameComposite = _toolkit.createComposite(shell, SWT.NONE);
- nameComposite.setBackground(shell.getBackground());
- nameComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- nameComposite.setLayout(new GridLayout(2,false));
-
- _toolkit.createLabel(nameComposite,"Name:").setBackground(shell.getBackground());
- final Text nameText = new Text(nameComposite, SWT.BORDER);
- nameText.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
-
- Composite ownerComposite = _toolkit.createComposite(shell, SWT.NONE);
- ownerComposite.setBackground(shell.getBackground());
- ownerComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- ownerComposite.setLayout(new GridLayout(2,false));
-
- _toolkit.createLabel(ownerComposite,"Owner (optional):").setBackground(shell.getBackground());
- final Text ownerText = new Text(ownerComposite, SWT.BORDER);
- ownerText.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
-
- Composite durableComposite = _toolkit.createComposite(shell, SWT.NONE);
- durableComposite.setBackground(shell.getBackground());
- GridData gridData = new GridData(SWT.FILL, SWT.TOP, true, false);
- gridData.minimumWidth = 220;
- durableComposite.setLayoutData(gridData);
- durableComposite.setLayout(new GridLayout(2,false));
-
- _toolkit.createLabel(durableComposite,"Durable:").setBackground(shell.getBackground());
- final Button durableButton = new Button(durableComposite, SWT.CHECK);
- durableButton.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, true, false));
-
- Composite okCancelButtonsComp = _toolkit.createComposite(shell);
- okCancelButtonsComp.setBackground(shell.getBackground());
- okCancelButtonsComp.setLayoutData(new GridData(SWT.RIGHT, SWT.FILL, true, true));
- okCancelButtonsComp.setLayout(new GridLayout(2,false));
-
- Button okButton = _toolkit.createButton(okCancelButtonsComp, "OK", SWT.PUSH);
- okButton.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, false));
- Button cancelButton = _toolkit.createButton(okCancelButtonsComp, "Cancel", SWT.PUSH);
- cancelButton.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, false));
-
- okButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- String name = nameText.getText();
-
- if (name == null || name.length() == 0)
- {
- ViewUtility.popupErrorMessage("Create Queue", "Please enter a valid name");
- return;
- }
-
- String owner = ownerText.getText();
-
- if (owner != null && owner.length() == 0)
- {
- owner = null;
- }
-
- boolean durable = durableButton.getSelection();
-
- shell.dispose();
-
- try
- {
- _vhmb.createNewQueue(name, owner, durable);
-
- ViewUtility.operationResultFeedback(null, "Created Queue", null);
- try
- {
- //delay to allow mbean registration notification processing
- Thread.sleep(250);
- }
- catch(InterruptedException ie)
- {
- //ignore
- }
- }
- catch(Exception e5)
- {
- ViewUtility.operationFailedStatusBarMessage("Error creating Queue");
- MBeanUtility.handleException(_mbean, e5);
- }
-
- refresh(_mbean);
- }
- });
-
- cancelButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- shell.dispose();
- }
- });
-
- shell.setDefaultButton(okButton);
- shell.pack();
- ViewUtility.centerChildInParentShell(parent, shell);
-
- shell.open();
- }
-
- private void createExchange(final Shell parent)
- {
- final Shell shell = ViewUtility.createModalDialogShell(parent, "Create Exchange");
-
- Composite nameComposite = _toolkit.createComposite(shell, SWT.NONE);
- nameComposite.setBackground(shell.getBackground());
- nameComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- nameComposite.setLayout(new GridLayout(2,false));
-
- _toolkit.createLabel(nameComposite,"Name:").setBackground(shell.getBackground());
- final Text nameText = new Text(nameComposite, SWT.BORDER);
- nameText.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
-
- Composite typeComposite = _toolkit.createComposite(shell, SWT.NONE);
- typeComposite.setBackground(shell.getBackground());
- typeComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- typeComposite.setLayout(new GridLayout(2,false));
-
- String[] exchangeTypes;
- if(_ApiVersion.greaterThanOrEqualTo(1, 3))//if the server supports Qpid JMX API 1.3
- {//request the current exchange types from the broker
- try
- {
- exchangeTypes = _vhmb.getExchangeTypes();
- }
- catch (IOException e1)
- {
- exchangeTypes = DEFAULT_EXCHANGE_TYPE_VALUES.toArray(new String[DEFAULT_EXCHANGE_TYPE_VALUES.size()]);
- }
- }
- else //use the fallback defaults.
- {
- exchangeTypes = DEFAULT_EXCHANGE_TYPE_VALUES.toArray(new String[DEFAULT_EXCHANGE_TYPE_VALUES.size()]);
- }
-
- _toolkit.createLabel(typeComposite,"Type:").setBackground(shell.getBackground());
- final org.eclipse.swt.widgets.List typeList = new org.eclipse.swt.widgets.List(typeComposite, SWT.SINGLE | SWT.BORDER);
- typeList.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- typeList.setItems(exchangeTypes);
-
- Composite durableComposite = _toolkit.createComposite(shell, SWT.NONE);
- durableComposite.setBackground(shell.getBackground());
- GridData gridData = new GridData(SWT.FILL, SWT.TOP, true, false);
- gridData.minimumWidth = 220;
- durableComposite.setLayoutData(gridData);
- durableComposite.setLayout(new GridLayout(2,false));
-
- _toolkit.createLabel(durableComposite,"Durable:").setBackground(shell.getBackground());
- final Button durableButton = new Button(durableComposite, SWT.CHECK);
- durableButton.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, true, false));
-
-
- Composite okCancelButtonsComp = _toolkit.createComposite(shell);
- okCancelButtonsComp.setBackground(shell.getBackground());
- okCancelButtonsComp.setLayoutData(new GridData(SWT.RIGHT, SWT.FILL, true, true));
- okCancelButtonsComp.setLayout(new GridLayout(2,false));
-
- Button okButton = _toolkit.createButton(okCancelButtonsComp, "OK", SWT.PUSH);
- okButton.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, false));
- Button cancelButton = _toolkit.createButton(okCancelButtonsComp, "Cancel", SWT.PUSH);
- cancelButton.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, false));
-
- okButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- String name = nameText.getText();
-
- if (name == null || name.length() == 0)
- {
- ViewUtility.popupErrorMessage("Create Exchange", "Please enter a valid name");
- return;
- }
-
- int selectedTypeIndex = typeList.getSelectionIndex();
-
- if (selectedTypeIndex == -1)
- {
- ViewUtility.popupErrorMessage("Create Exchange", "Please select an Exchange type");
- return;
- }
-
- String type = typeList.getItem(selectedTypeIndex);
-
- boolean durable = durableButton.getSelection();
-
- shell.dispose();
-
- try
- {
- _vhmb.createNewExchange(name, type, durable);
-
- ViewUtility.operationResultFeedback(null, "Created Exchange", null);
- try
- {
- //delay to allow mbean registration notification processing
- Thread.sleep(250);
- }
- catch(InterruptedException ie)
- {
- //ignore
- }
- }
- catch(Exception e5)
- {
- ViewUtility.operationFailedStatusBarMessage("Error creating Exchange");
- MBeanUtility.handleException(_mbean, e5);
- }
-
- refresh(_mbean);
- }
- });
-
- cancelButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- shell.dispose();
- }
- });
-
- shell.setDefaultButton(okButton);
- shell.pack();
- ViewUtility.centerChildInParentShell(parent, shell);
-
- shell.open();
- }
-
- private void deleteQueuesOrExchanges(Shell parent, final VhostOperations op)
- {
- Table table;
- String windowTitle;
- String dialogueMessage;
- final String feedBackMessage;
- final String failureFeedBackMessage;
-
- if(op.equals(VhostOperations.DELETE_QUEUE))
- {
- table = _queueTable;
- windowTitle = "Delete Queue(s)";
- dialogueMessage = "Delete Queue(s): ";
- feedBackMessage = "Queue(s) deleted";
- failureFeedBackMessage = "Error deleting Queue(s)";
- }
- else
- {
- table = _exchangeTable;
- windowTitle = "Delete Exchange(s)";
- dialogueMessage = "Delete Exchange(s): ";
- feedBackMessage = "Exchange(s) deleted";
- failureFeedBackMessage = "Error deleting Exchange(s)";
- }
-
- int selectionIndex = table.getSelectionIndex();
- if (selectionIndex == -1)
- {
- return;
- }
-
- int[] selectedIndices = table.getSelectionIndices();
-
- final ArrayList<ManagedBean> selectedMBeans = new ArrayList<ManagedBean>();
-
- for(int index = 0; index < selectedIndices.length ; index++)
- {
- ManagedBean selectedMBean = (ManagedBean)table.getItem(selectedIndices[index]).getData();
- selectedMBeans.add(selectedMBean);
- }
-
-
- final Shell shell = ViewUtility.createModalDialogShell(parent, windowTitle);
-
- _toolkit.createLabel(shell, dialogueMessage).setBackground(shell.getBackground());
-
- final Text headerText = new Text(shell, SWT.WRAP | SWT.V_SCROLL | SWT.BORDER );
- headerText.setEditable(false);
- GridData data = new GridData(SWT.FILL, SWT.FILL, false, false);
- data.minimumHeight = 150;
- data.heightHint = 150;
- data.minimumWidth = 400;
- data.widthHint = 400;
- headerText.setLayoutData(data);
-
- String lineSeperator = System.getProperty("line.separator");
- for(ManagedBean mbean : selectedMBeans)
- {
- headerText.append(mbean.getName() + lineSeperator);
- }
- headerText.setSelection(0);
-
- Composite okCancelButtonsComp = _toolkit.createComposite(shell);
- okCancelButtonsComp.setBackground(shell.getBackground());
- okCancelButtonsComp.setLayoutData(new GridData(SWT.RIGHT, SWT.FILL, true, true));
- okCancelButtonsComp.setLayout(new GridLayout(2,false));
-
- Button okButton = _toolkit.createButton(okCancelButtonsComp, "OK", SWT.PUSH);
- okButton.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, false));
- Button cancelButton = _toolkit.createButton(okCancelButtonsComp, "Cancel", SWT.PUSH);
- cancelButton.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, false));
-
- okButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- shell.dispose();
-
- try
- {
- //perform the deletes
- for(ManagedBean mbean : selectedMBeans)
- {
- switch(op)
- {
- case DELETE_QUEUE:
- _vhmb.deleteQueue(mbean.getName());
- _serverRegistry.removeManagedObject(mbean);
- break;
- case DELETE_EXCHANGE:
- _vhmb.unregisterExchange(mbean.getName());
- break;
- }
- //remove the mbean from the server registry now instead of
- //waiting for an mbean Unregistration Notification to do it
- _serverRegistry.removeManagedObject(mbean);
- }
-
- ViewUtility.operationResultFeedback(null, feedBackMessage, null);
- }
- catch(Exception e1)
- {
- ViewUtility.operationFailedStatusBarMessage(failureFeedBackMessage);
- MBeanUtility.handleException(_mbean, e1);
- }
-
- refresh(_mbean);;
- }
- });
-
- cancelButton.addSelectionListener(new SelectionAdapter()
- {
- public void widgetSelected(SelectionEvent e)
- {
- shell.dispose();
- }
- });
-
- shell.setDefaultButton(okButton);
- shell.pack();
- ViewUtility.centerChildInParentShell(parent, shell);
-
- shell.open();
- }
-
- private enum VhostOperations
- {
- DELETE_QUEUE,
- DELETE_EXCHANGE;
- }
-
- private void openMBean(Table table)
- {
- int selectionIndex = table.getSelectionIndex();
-
- if (selectionIndex == -1)
- {
- return;
- }
-
- ManagedBean selectedMBean = (ManagedBean) table.getItem(selectionIndex).getData();
-
- IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- MBeanView view = (MBeanView) window.getActivePage().findView(MBeanView.ID);
- try
- {
- view.openMBean(selectedMBean);
- }
- catch (Exception ex)
- {
- MBeanUtility.handleException(selectedMBean, ex);
- }
- }
-}
diff --git a/java/management/eclipse-plugin/src/main/resources/.eclipseproduct b/java/management/eclipse-plugin/src/main/resources/.eclipseproduct
deleted file mode 100644
index 28ee27ca17..0000000000
--- a/java/management/eclipse-plugin/src/main/resources/.eclipseproduct
+++ /dev/null
@@ -1,23 +0,0 @@
-#Eclipse Product File
-#Fri Nov 03 14:47:54 GMT 2006
-#
-# 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.
-#
-version=1.0-incubating-M2-SNAPSHOT
-name=Qpid Management Console
-id=org.apache.qpid.manager.gui.product
diff --git a/java/management/eclipse-plugin/src/main/resources/jmxremote.sasl-plugin/MANIFEST.MF b/java/management/eclipse-plugin/src/main/resources/jmxremote.sasl-plugin/MANIFEST.MF
deleted file mode 100644
index 83c7c9f435..0000000000
--- a/java/management/eclipse-plugin/src/main/resources/jmxremote.sasl-plugin/MANIFEST.MF
+++ /dev/null
@@ -1,20 +0,0 @@
-Manifest-Version: 1.0
-Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt
-Bundle-ManifestVersion: 2
-Bundle-Name: jmx sasl Plug-in
-Bundle-SymbolicName: jmxremote.sasl
-Bundle-Version: 1.0.1
-Bundle-ClassPath: jmxremote_optional.jar
-Export-Package: com.sun.jmx.remote.generic,
- com.sun.jmx.remote.opt.internal,
- com.sun.jmx.remote.opt.security,
- com.sun.jmx.remote.opt.util,
- com.sun.jmx.remote.profile.sasl,
- com.sun.jmx.remote.profile.tls,
- com.sun.jmx.remote.protocol.jmxmp,
- com.sun.jmx.remote.socket,
- javax.management.remote.generic,
- javax.management.remote.jmxmp,
- javax.management.remote.message
-Bundle-Vendor:
-Bundle-Localization: plugin
diff --git a/java/management/eclipse-plugin/src/main/resources/linux-gtk-x86/Configuration/config.ini b/java/management/eclipse-plugin/src/main/resources/linux-gtk-x86/Configuration/config.ini
deleted file mode 100644
index dc15366740..0000000000
--- a/java/management/eclipse-plugin/src/main/resources/linux-gtk-x86/Configuration/config.ini
+++ /dev/null
@@ -1,49 +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.
-###############################################################################
-
-#Product Runtime Configuration File
-
-osgi.splashPath=platform:/base/plugins/org.apache.qpid.management.ui
-eclipse.product=org.apache.qpid.management.ui.product
-osgi.bundles.defaultStartLevel=4
-osgi.bundles=jmxremote.sasl, \
-qpid-management-common, \
-org.apache.qpid.management.ui, \
-com.ibm.icu, \
-org.eclipse.core.commands, \
-org.eclipse.core.contenttype, \
-org.eclipse.core.databinding, \
-org.eclipse.core.expressions, \
-org.eclipse.core.jobs, \
-org.eclipse.core.runtime@start, \
-org.eclipse.core.runtime.compatibility.registry, \
-org.eclipse.equinox.app,org.eclipse.equinox.common, \
-org.eclipse.equinox.preferences, \
-org.eclipse.equinox.registry, \
-org.eclipse.help, \
-org.eclipse.jface, \
-org.eclipse.jface.databinding, \
-org.eclipse.swt, \
-org.eclipse.swt.gtk.linux.x86, \
-org.eclipse.ui, \
-org.eclipse.ui.forms, \
-org.eclipse.ui.workbench, \
-org.eclipse.equinox.launcher, \
-org.eclipse.equinox.launcher.gtk.linux.x86, \
-org.apache.commons.codec
diff --git a/java/management/eclipse-plugin/src/main/resources/linux-gtk-x86/libcairo-swt.so b/java/management/eclipse-plugin/src/main/resources/linux-gtk-x86/libcairo-swt.so
deleted file mode 100644
index b66f95814e..0000000000
--- a/java/management/eclipse-plugin/src/main/resources/linux-gtk-x86/libcairo-swt.so
+++ /dev/null
Binary files differ
diff --git a/java/management/eclipse-plugin/src/main/resources/linux-gtk-x86/qpidmc b/java/management/eclipse-plugin/src/main/resources/linux-gtk-x86/qpidmc
deleted file mode 100644
index 0cc5c65455..0000000000
--- a/java/management/eclipse-plugin/src/main/resources/linux-gtk-x86/qpidmc
+++ /dev/null
Binary files differ
diff --git a/java/management/eclipse-plugin/src/main/resources/linux-gtk-x86/qpidmc.ini b/java/management/eclipse-plugin/src/main/resources/linux-gtk-x86/qpidmc.ini
deleted file mode 100644
index 19ceb6f717..0000000000
--- a/java/management/eclipse-plugin/src/main/resources/linux-gtk-x86/qpidmc.ini
+++ /dev/null
@@ -1,37 +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.
-###############################################################################
-
--vmargs
--Xms40m
--Xmx256m
--XX:MaxPermSize=256m
--Dosgi.requiredJavaVersion=1.5
--Declipse.consoleLog=true
-
-#===============================================
-# SSL trust store configuration options.
-#===============================================
-
-# Uncomment lines below to specify custom truststore for server SSL
-# certificate verification, eg when using self-signed server certs.
-#
-#-Djavax.net.ssl.trustStore=<path.to.truststore>
-#-Djavax.net.ssl.trustStorePassword=<truststore.password>
-
-
diff --git a/java/management/eclipse-plugin/src/main/resources/linux-gtk-x86_64/Configuration/config.ini b/java/management/eclipse-plugin/src/main/resources/linux-gtk-x86_64/Configuration/config.ini
deleted file mode 100644
index f437e830b5..0000000000
--- a/java/management/eclipse-plugin/src/main/resources/linux-gtk-x86_64/Configuration/config.ini
+++ /dev/null
@@ -1,49 +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.
-###############################################################################
-
-#Product Runtime Configuration File
-
-osgi.splashPath=platform:/base/plugins/org.apache.qpid.management.ui
-eclipse.product=org.apache.qpid.management.ui.product
-osgi.bundles.defaultStartLevel=4
-osgi.bundles=jmxremote.sasl, \
-qpid-management-common, \
-org.apache.qpid.management.ui, \
-com.ibm.icu, \
-org.eclipse.core.commands, \
-org.eclipse.core.contenttype, \
-org.eclipse.core.databinding, \
-org.eclipse.core.expressions, \
-org.eclipse.core.jobs, \
-org.eclipse.core.runtime@start, \
-org.eclipse.core.runtime.compatibility.registry, \
-org.eclipse.equinox.app,org.eclipse.equinox.common, \
-org.eclipse.equinox.preferences, \
-org.eclipse.equinox.registry, \
-org.eclipse.help, \
-org.eclipse.jface, \
-org.eclipse.jface.databinding, \
-org.eclipse.swt, \
-org.eclipse.swt.gtk.linux.x86_64, \
-org.eclipse.ui, \
-org.eclipse.ui.forms, \
-org.eclipse.ui.workbench, \
-org.eclipse.equinox.launcher, \
-org.eclipse.equinox.launcher.gtk.linux.x86_64, \
-org.apache.commons.codec
diff --git a/java/management/eclipse-plugin/src/main/resources/linux-gtk-x86_64/libcairo-swt.so b/java/management/eclipse-plugin/src/main/resources/linux-gtk-x86_64/libcairo-swt.so
deleted file mode 100644
index 5734427fb8..0000000000
--- a/java/management/eclipse-plugin/src/main/resources/linux-gtk-x86_64/libcairo-swt.so
+++ /dev/null
Binary files differ
diff --git a/java/management/eclipse-plugin/src/main/resources/linux-gtk-x86_64/qpidmc b/java/management/eclipse-plugin/src/main/resources/linux-gtk-x86_64/qpidmc
deleted file mode 100644
index ff1f3a7507..0000000000
--- a/java/management/eclipse-plugin/src/main/resources/linux-gtk-x86_64/qpidmc
+++ /dev/null
Binary files differ
diff --git a/java/management/eclipse-plugin/src/main/resources/linux-gtk-x86_64/qpidmc.ini b/java/management/eclipse-plugin/src/main/resources/linux-gtk-x86_64/qpidmc.ini
deleted file mode 100644
index 19ceb6f717..0000000000
--- a/java/management/eclipse-plugin/src/main/resources/linux-gtk-x86_64/qpidmc.ini
+++ /dev/null
@@ -1,37 +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.
-###############################################################################
-
--vmargs
--Xms40m
--Xmx256m
--XX:MaxPermSize=256m
--Dosgi.requiredJavaVersion=1.5
--Declipse.consoleLog=true
-
-#===============================================
-# SSL trust store configuration options.
-#===============================================
-
-# Uncomment lines below to specify custom truststore for server SSL
-# certificate verification, eg when using self-signed server certs.
-#
-#-Djavax.net.ssl.trustStore=<path.to.truststore>
-#-Djavax.net.ssl.trustStorePassword=<truststore.password>
-
-
diff --git a/java/management/eclipse-plugin/src/main/resources/macosx/Configuration/config.ini b/java/management/eclipse-plugin/src/main/resources/macosx/Configuration/config.ini
deleted file mode 100644
index 3ac3aa20f3..0000000000
--- a/java/management/eclipse-plugin/src/main/resources/macosx/Configuration/config.ini
+++ /dev/null
@@ -1,49 +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.
-###############################################################################
-
-#Product Runtime Configuration File
-
-osgi.splashPath=platform:/base/plugins/org.apache.qpid.management.ui
-eclipse.product=org.apache.qpid.management.ui.product
-osgi.bundles.defaultStartLevel=4
-osgi.bundles=jmxremote.sasl, \
-qpid-management-common, \
-org.apache.qpid.management.ui, \
-com.ibm.icu, \
-org.eclipse.core.commands, \
-org.eclipse.core.contenttype, \
-org.eclipse.core.databinding, \
-org.eclipse.core.expressions, \
-org.eclipse.core.jobs, \
-org.eclipse.core.runtime@start, \
-org.eclipse.core.runtime.compatibility.registry, \
-org.eclipse.equinox.app,org.eclipse.equinox.common, \
-org.eclipse.equinox.preferences, \
-org.eclipse.equinox.registry, \
-org.eclipse.help, \
-org.eclipse.jface, \
-org.eclipse.jface.databinding, \
-org.eclipse.swt, \
-org.eclipse.swt.carbon.macosx, \
-org.eclipse.ui, \
-org.eclipse.ui.forms, \
-org.eclipse.ui.workbench, \
-org.eclipse.equinox.launcher, \
-org.eclipse.equinox.launcher.carbon.macosx, \
-org.apache.commons.codec
diff --git a/java/management/eclipse-plugin/src/main/resources/macosx/Contents/Info.plist b/java/management/eclipse-plugin/src/main/resources/macosx/Contents/Info.plist
deleted file mode 100644
index c6482a9254..0000000000
--- a/java/management/eclipse-plugin/src/main/resources/macosx/Contents/Info.plist
+++ /dev/null
@@ -1,55 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
-<!--
- -
- - 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.
- -
- -->
-<plist version="1.0">
-<dict>
- <key>CFBundleExecutable</key>
- <string>qpidmc</string>
- <key>CFBundleGetInfoString</key>
- <string>Apache Qpid Management Console for Mac OS X</string>
- <key>CFBundleIconFile</key>
- <string>Console.icns</string>
- <key>CFBundleIdentifier</key>
- <string>org.apache.qpid.management.ui</string>
- <key>CFBundleInfoDictionaryVersion</key>
- <string>6.0</string>
- <key>CFBundleName</key>
- <string>Qpid Management Console</string>
- <key>CFBundlePackageType</key>
- <string>APPL</string>
- <key>CFBundleShortVersionString</key>
- <string>3.4</string>
- <key>CFBundleSignature</key>
- <string>????</string>
- <key>CFBundleVersion</key>
- <string>3.4</string>
- <key>Qpid Management Console</key>
- <array>
- <string>-consoleLog</string>
- <string>-showlocation</string>
- <!-- WARNING:
- If you try to add a single VM argument (-vmargs) here,
- *all* vmargs specified in qpidmc.ini will be ignored.
- We recommend to add all arguments in MacOS/qpidmc.ini -->
- </array>
-</dict>
-</plist>
diff --git a/java/management/eclipse-plugin/src/main/resources/macosx/Contents/MacOS/qpidmc b/java/management/eclipse-plugin/src/main/resources/macosx/Contents/MacOS/qpidmc
deleted file mode 100755
index 36247a08e4..0000000000
--- a/java/management/eclipse-plugin/src/main/resources/macosx/Contents/MacOS/qpidmc
+++ /dev/null
Binary files differ
diff --git a/java/management/eclipse-plugin/src/main/resources/macosx/Contents/MacOS/qpidmc.ini b/java/management/eclipse-plugin/src/main/resources/macosx/Contents/MacOS/qpidmc.ini
deleted file mode 100644
index 2a31b9b2c7..0000000000
--- a/java/management/eclipse-plugin/src/main/resources/macosx/Contents/MacOS/qpidmc.ini
+++ /dev/null
@@ -1,42 +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.
-###############################################################################
-
--startup
-../../plugins/org.eclipse.equinox.launcher_1.0.101.R34x_v20080819.jar
---launcher.library
-../../plugins/org.eclipse.equinox.launcher.carbon.macosx_1.0.101.R34x_v20080731
--vmargs
--XstartOnFirstThread
--Xms40m
--Xmx512m
--XX:MaxPermSize=256m
--Dosgi.requiredJavaVersion=1.5
--Declipse.consoleLog=true
--Dorg.eclipse.swt.internal.carbon.smallFonts
-
-#===============================================
-# SSL trust store configuration options.
-#===============================================
-
-# Uncomment lines below to specify custom truststore for server SSL
-# certificate verification, eg when using self-signed server certs.
-#
-#-Djavax.net.ssl.trustStore=<path.to.truststore>
-#-Djavax.net.ssl.trustStorePassword=<truststore.password>
-
diff --git a/java/management/eclipse-plugin/src/main/resources/macosx/Contents/Resources/Console.icns b/java/management/eclipse-plugin/src/main/resources/macosx/Contents/Resources/Console.icns
deleted file mode 100644
index 610976efab..0000000000
--- a/java/management/eclipse-plugin/src/main/resources/macosx/Contents/Resources/Console.icns
+++ /dev/null
Binary files differ
diff --git a/java/management/eclipse-plugin/src/main/resources/solaris-gtk-sparc/Configuration/config.ini b/java/management/eclipse-plugin/src/main/resources/solaris-gtk-sparc/Configuration/config.ini
deleted file mode 100644
index a99a8b3f7d..0000000000
--- a/java/management/eclipse-plugin/src/main/resources/solaris-gtk-sparc/Configuration/config.ini
+++ /dev/null
@@ -1,49 +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.
-###############################################################################
-
-#Product Runtime Configuration File
-
-osgi.splashPath=platform:/base/plugins/org.apache.qpid.management.ui
-eclipse.product=org.apache.qpid.management.ui.product
-osgi.bundles.defaultStartLevel=4
-osgi.bundles=jmxremote.sasl, \
-qpid-management-common, \
-org.apache.qpid.management.ui, \
-com.ibm.icu, \
-org.eclipse.core.commands, \
-org.eclipse.core.contenttype, \
-org.eclipse.core.databinding, \
-org.eclipse.core.expressions, \
-org.eclipse.core.jobs, \
-org.eclipse.core.runtime@start, \
-org.eclipse.core.runtime.compatibility.registry, \
-org.eclipse.equinox.app,org.eclipse.equinox.common, \
-org.eclipse.equinox.preferences, \
-org.eclipse.equinox.registry, \
-org.eclipse.help, \
-org.eclipse.jface, \
-org.eclipse.jface.databinding, \
-org.eclipse.swt, \
-org.eclipse.swt.gtk.solaris.sparc, \
-org.eclipse.ui, \
-org.eclipse.ui.forms, \
-org.eclipse.ui.workbench, \
-org.eclipse.equinox.launcher, \
-org.eclipse.equinox.launcher.gtk.solaris.sparc, \
-org.apache.commons.codec
diff --git a/java/management/eclipse-plugin/src/main/resources/solaris-gtk-sparc/Qpidmc.l.pm b/java/management/eclipse-plugin/src/main/resources/solaris-gtk-sparc/Qpidmc.l.pm
deleted file mode 100644
index 995d7c9bb0..0000000000
--- a/java/management/eclipse-plugin/src/main/resources/solaris-gtk-sparc/Qpidmc.l.pm
+++ /dev/null
@@ -1,311 +0,0 @@
-/* XPM */
-static char *ProductIcon48[] = {
-/* columns rows colors chars-per-pixel */
-"48 48 257 2",
-" c black",
-". c gray100",
-"X c #69695A5AE8E8",
-"o c #494949499191",
-"O c #CECE9292BFBF",
-"+ c #E7E7CACAE0E0",
-"@ c #C8C88C8CBBBB",
-"# c #C2C28A8ABABA",
-"$ c #EAEAD7D7E8E8",
-"% c #CFCFA9A9CCCC",
-"& c #D9D9BCBCD8D8",
-"* c #B6B68787B9B9",
-"= c #C3C39999C7C7",
-"- c #A7A77D7DB5B5",
-"; c #BDBDA3A3CDCD",
-": c #D8D8CACAE3E3",
-"> c #A8A88D8DC4C4",
-", c #92927575B2B2",
-"< c #87876C6CAAAA",
-"1 c #9A9A8383BABA",
-"2 c #7B7B6363A3A3",
-"3 c #666654549595",
-"4 c #73735F5FADAD",
-"5 c #626251519292",
-"6 c #7F7F7272A7A7",
-"7 c #6D6D5E5E9E9E",
-"8 c #64645454A9A9",
-"9 c #77776969B1B1",
-"0 c #49493E3E8282",
-"q c #7D7D7373B6B6",
-"w c #5B5B4E4EADAD",
-"e c #55554949BABA",
-"r c #56564949BABA",
-"t c #56564A4ABABA",
-"y c #56564949B9B9",
-"u c #55554949B8B8",
-"i c #4F4F4444ACAC",
-"p c #53534848B4B4",
-"a c #53534848B3B3",
-"s c #54544949B5B5",
-"d c #52524747B0B0",
-"f c #52524747AFAF",
-"g c #54544949B3B3",
-"h c #DEDEDCDCEEEE",
-"j c #3E3E36369898",
-"k c #43433B3B9F9F",
-"l c #33332C2C7777",
-"z c #42423A3A9C9C",
-"x c #4A4A4040A8A8",
-"c c #55554A4ABABA",
-"v c #55554A4AB9B9",
-"b c #54544949B7B7",
-"n c #52524848B1B1",
-"m c #51514747AEAE",
-"M c #4E4E4545A9A9",
-"N c #49494141A0A0",
-"B c #52524848AFAF",
-"V c #51514848AEAE",
-"C c #50504747ACAC",
-"Z c #4F4F4646AAAA",
-"A c #51514848ADAD",
-"S c #50504747ABAB",
-"D c #50504848ACAC",
-"F c #50504747A9A9",
-"G c #4E4E4646A7A7",
-"H c #4E4E4545A4A4",
-"J c #4D4D4545A4A4",
-"K c #4F4F4747A8A8",
-"L c #4E4E4646A5A5",
-"P c #4D4D4545A3A3",
-"I c #3B3B35357D7D",
-"U c #4E4E4646A3A3",
-"Y c #55554D4D9F9F",
-"T c #4A4A43438989",
-"R c #51514B4B9090",
-"E c #67676060A5A5",
-"W c #1D1D18186A6A",
-"Q c #272722227D7D",
-"! c #282823237D7D",
-"~ c #2B2B26268181",
-"^ c #33332C2C8989",
-"/ c #3B3B36368E8E",
-"( c #454540409797",
-") c #4D4D4646A4A4",
-"_ c #4C4C4545A1A1",
-"` c #4D4D4646A2A2",
-"' c #4B4B4545A0A0",
-"] c #4D4D4646A1A1",
-"[ c #4C4C45459F9F",
-"{ c #4B4B45459E9E",
-"} c #4A4A44449C9C",
-"| c #494944449898",
-" . c #484843439696",
-".. c #4A4A45459999",
-"X. c #4F4F4A4AA0A0",
-"o. c #68686363AAAA",
-"O. c #21211D1D7676",
-"+. c #242420207575",
-"@. c #2D2D2A2A7F7F",
-"#. c #2D2D2A2A7B7B",
-"$. c #3D3D39398F8F",
-"%. c #484844449696",
-"&. c #474743439393",
-"*. c #464643439191",
-"=. c #454542428E8E",
-"-. c #4D4D4A4A9C9C",
-";. c #57575454A3A3",
-":. c #5A5A58589797",
-">. c #5F5F5D5D9999",
-",. c #85858282C1C1",
-"<. c #95959292C9C9",
-"1. c #B8B8B6B6DCDC",
-"2. c #070705055353",
-"3. c #080807075555",
-"4. c #0A0A09095757",
-"5. c #0C0C0B0B5858",
-"6. c #0F0F0D0D5C5C",
-"7. c #10100F0F5C5C",
-"8. c #131311116464",
-"9. c #141413136060",
-"0. c #141413135F5F",
-"q. c #171715156767",
-"w. c #161615156262",
-"e. c #161615156161",
-"r. c #181817176464",
-"t. c #1A1A19196666",
-"y. c #1C1C1A1A6464",
-"u. c #1D1D1C1C6868",
-"i. c #1F1F1E1E6A6A",
-"p. c #222221216C6C",
-"a. c #242423236F6F",
-"s. c #272725257171",
-"d. c #272726267272",
-"f. c #272726267171",
-"g. c #292928287474",
-"h. c #2A2A29297474",
-"j. c #2C2C2B2B7777",
-"k. c #2F2F2E2E7C7C",
-"l. c #2E2E2D2D7979",
-"z. c #343433337E7E",
-"x. c #393937378686",
-"c. c #373736368181",
-"v. c #3A3A39398484",
-"b. c #3A3A39398383",
-"n. c #3D3D3B3B8686",
-"m. c #424241418C8C",
-"M. c #424241418B8B",
-"N. c #444442428B8B",
-"B. c #434341418989",
-"V. c #454544448E8E",
-"C. c #454544448D8D",
-"Z. c #424241418787",
-"A. c #434342428888",
-"S. c #444442428787",
-"D. c #424241418585",
-"F. c #414140408383",
-"G. c #484847479090",
-"H. c #434342428686",
-"J. c #4A4A49499393",
-"K. c #464645458A8A",
-"L. c #4D4D4C4C9595",
-"P. c #54545252A0A0",
-"I. c #50504F4F9898",
-"U. c #58585757A0A0",
-"Y. c #525250509393",
-"T. c #5B5B5959A2A2",
-"R. c #585857579F9F",
-"E. c #62626161A9A9",
-"W. c #64646363ACAC",
-"Q. c #6B6B6A6AB2B2",
-"!. c #6B6B6A6AB1B1",
-"~. c #75757474B8B8",
-"^. c #7F7F7D7DBDBD",
-"/. c #9C9C9B9BCFCF",
-"(. c #0B0B0B0B5858",
-"). c #0D0D0D0D5A5A",
-"_. c #111111115E5E",
-"`. c #131313136060",
-"'. c #212121216D6D",
-"]. c #242424246F6F",
-"[. c #2B2B2C2C7777",
-"{. c #2B2B2B2B7777",
-"}. c #2C2C2C2C7777",
-"|. c #2E2E2E2E7979",
-" X c #313131317C7C",
-".X c #313131317B7B",
-"XX c #343434347E7E",
-"oX c #3C3C3C3C8686",
-"OX c #3F3F3F3F8989",
-"+X c #414142428B8B",
-"@X c #424242428B8B",
-"#X c #474747479090",
-"$X c #414141418484",
-"%X c #404040408181",
-"&X c #4A4A4A4A9494",
-"*X c #4A4A4A4A9393",
-"=X c #4D4D4D4D9696",
-"-X c #4F4F4F4F9898",
-";X c #505050509898",
-":X c #525252529B9B",
-">X c #555555559E9E",
-",X c #555555559D9D",
-"<X c #57575858A0A0",
-"1X c #58585858A0A0",
-"2X c #575758589F9F",
-"3X c #575757579F9F",
-"4X c #5A5A5A5AA2A2",
-"5X c #5D5D5D5DA5A5",
-"6X c #5F5F5F5FA7A7",
-"7X c #61616262AAAA",
-"8X c #61616161A9A9",
-"9X c #61616262A9A9",
-"0X c #62626262AAAA",
-"qX c #64646464ACAC",
-"wX c #62626262A9A9",
-"eX c #64646464ABAB",
-"rX c #66666666AEAE",
-"tX c #66666666ADAD",
-"yX c #68686868B0B0",
-"uX c #69696969AFAF",
-"iX c #6D6D6D6DB4B4",
-"pX c #6F6F6F6FB5B5",
-"aX c #73737373BABA",
-"sX c #71717171B7B7",
-"dX c #76767676BCBC",
-"fX c #79797979BFBF",
-"gX c #77777777B9B9",
-"hX c #80808080C1C1",
-"jX c #8C8C8C8CC5C5",
-"kX c #90909090C9C9",
-"lX c #98989898CBCB",
-"zX c #A0A0A0A0CFCF",
-"xX c #A5A5A5A5D3D3",
-"cX c #ABABABABD6D6",
-"vX c #C4C4C4C4E3E3",
-"bX c #D1D1D1D1E9E9",
-"nX c #E5E5E5E5F3F3",
-"mX c #9F9FA0A0D1D1",
-"MX c #B6B6C5C5E5E5",
-"NX c #8E8EA6A6D6D6",
-"BX c #9090A7A7D7D7",
-"VX c #9191A9A9D7D7",
-"CX c #9595ABABD8D8",
-"ZX c #9999AFAFDADA",
-"AX c #9D9DB2B2DCDC",
-"SX c #A1A1B5B5DDDD",
-"DX c #A5A5B8B8DEDE",
-"FX c #A9A9BBBBE0E0",
-"GX c #ACACBDBDE1E1",
-"HX c #B0B0C1C1E3E3",
-"JX c #B4B4C4C4E4E4",
-"KX c #B8B8C7C7E5E5",
-"LX c #BBBBC9C9E6E6",
-"PX c #AEAEC0C0E2E2",
-"IX c #B2B2C3C3E3E3",
-"UX c gray100",
-"YX c None",
-/* pixels */
-"YXX X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X YX",
-"X %X%X%XF.F.F.F.$XD.Z.Z.Z.B.B.B.N.N.=.=.=.*.*.*.&.&. . .| ....} } { { _ _ P P H G G G K S S C o ",
-"X %X%X%X%XF.F.$XD.D.Z.Z.B.A.B.N.N.N.=.=.=.*.*.&.&.%.%.%.| | ..} { { [ _ _ ` U J L G K F Z S C o ",
-"X %X%X%X%XF.F.F.D.D.H.Z.Z.A.B.N.N.N.C.=.=.*.*.&.&. . .%.| | ..} } { [ [ _ P P H G G K F S S C o ",
-"X %XF.%XF.F.$XF.$XZ.Z.Z.B.A.K.Y.7 , - - 1 1 ^.^.~.aX~.q 9 6XY { } { ' _ ] P P H L G K F Z S C o ",
-"X %XF.F.F.F.F.D.D.Z.Z.Z.K.:.1 ; % ; <.hXfXfXdXaXaXsXpXiX!.yXrXo.;.X.[ _ _ ` H H G K K F S S C o ",
-"X F.F.F.F.F.D.D.D.Z.H.Y.1 & & 1.cXmX/.kXfXdXaXaXsXpXiXQ.yXtXeXE.6X5XP.X._ ` J L G G K F Z S C o ",
-"X D.$XF.$XD.D.Z.Z.S.>.% + : vX1.1.cXmX/.dXaXaXsXpXiXQ.uXrXqX8X6X5XT.R.P.X.P ) H G K K S S S m o ",
-"X D.$XD.D.D.D.D.S.6 & $ h bXvXvX1.xX/.kXfXaXsXpXiXQ.yXrXW.E.6X5X4XU.,X:XI.-.` L G G K F Z C C o ",
-"X D.D.D.D.D.Z.H.6 & $ h h h bXvX1.cXmXkX,.dXpXiXQ.yXtXqXwX6X5XT.U.,X:XI.=X*X..` G K K Z S S m o ",
-"X Z.D.Z.H.Z.Z.7 & $ h h nXh bXvX1.cXmXkX,.gXiXQ.uXrXW.E.6X5X4XU.,X:X-XL.J.#XV. .P G F S S C m o ",
-"X Z.Z.Z.H.Z.R % + : bXh h h bXvX1.cX/.kXhX~.Q.yXrXqX9X6X5X4X2X,X:X;X=X*X#XV.M.OX( K Z S S C m o ",
-"X Z.Z.Z.A.A.* & & vXvXbXbXbXvXvX1.xXlXjX^.pXuXrXeXwX6X5X4XU.,X:X-XL.*XG.V.@XOXoXb.( Z S C C V o ",
-"X B.B.B.A.2 % % 1.1.vXvXvXvXvX1.cXzX<.,.gXiXrXW.E.6X5X4XU.,X:XI.=X*X#XV.@XOXn.b.c.x.N S S C m o ",
-"X B.B.B.S.* % ; xX1.1.1.1.1.cXcXzXlXjX^.pXrXeX7X6X5X4XR.,X:X-XL.J.#XV.@XOXn.b.c.XX X$.S C C m o ",
-"X N.N.N.2 O = /.mXxXcXcXcXcXxXzXlXjXhX~.uXeXE.6X5X4XU.,X:X-XL.J.#XV.M.OXn.v.c.z. X|.k.N D V f o ",
-"X N.N.N.- @ > kX<././.mXzXzXlX<.jXhXgXuXeXE.6X5X4X1X,X:XI.L.*X#XV.m.OXn.b.c.z. Xl.j.g./ C m V o ",
-"X N.N.R @ # ,.,.jXkXkX<.kXkXjX,.^.~.uXwXE.6X5X4X1X,X:XI.=XJ.#XC.M.OXn.v.c.z..X|.j.g.d.#.M m B o ",
-"X =.M.< @ * fXfXhXhX,.,.,.hX^.gXpXuXqX9X6X5X4XU.,X:XI.L.*XG.V.+XOXn.b.c.z..X|.[.g.d.a.p.z V B o ",
-"X =.N.- @ NXNXBXBXBXVXCXCXCXCXZXZXZXZXAXAXSXSXSXDXDXDXFXFXFXGXPXPXHXHXIXJXMXMXMXKXKXLXLXLXB d o ",
-"X =.=.* @ 1 dXdXaXaXsXpXiX!.yXrXeXwX6X5X4X<X,X:XI.=X*XG.V.M.OXn.v.c.XX.X|.j.g.d.a.p.i.u.@.f d o ",
-"X *.=.# @ ^.dXaXaXsXpXiXQ.yXrXeXwX6X5XT.U.,X:X-XL.&XG.C.m.OXoXv.c.z..X|.j.g.f.a.p.i.u.t.+.d d o ",
-"X *.*.@ @ NXNXNXBXVXVXCXCXCXCXZXZXZXZXAXAXAXSXSXDXDXDXFXFXGXGXPXPXHXHXJXJXJXMXKXKXKXLXLXLXd n o ",
-"X &.*.@ @ dXaXsXpXiXQ.yXtXeXE.6X5X4XU.>X:XI.L.*XG.V.m.OXoXv.c.z. X|.j.g.d.a.'.i.u.t.r.w.9.d n o ",
-"X &.&.@ @ ~.sXpXiXQ.yXtXW.E.6X5X4X1X,X:XI.=X*X#XC.m.OXn.b.c.z. X|.[.g.f.a.p.i.u.t.r.w.9.0.n a o ",
-"X &.&.@ @ NXNXBXBXVXVXVXCXCXCXZXZXZXZXAXAXSXSXSXDXDXDXFXFXGXGXPXPXHXIXIXJXMXMXKXKXKXLXLXLXn n o ",
-"X %. .# @ q iXQ.yXrXW.0X6X5X4XU.>X:XI.L.*X#XV.@XOXn.b.c.XX.X|.{.g.f.].'.i.u.t.r.w.0._.7.W n a o ",
-"X %. .* # , Q.yXtXeX7X6X5X4XU.,X:X-XL.*X#XV.@XOXn.b.c.XX Xl.{.g.d.a.p.i.u.t.r.e.0._.7.).+.a a o ",
-"X | | - # NXNXNXBXVXVXCXCXCXCXZXZXZXAXAXAXAXSXSXDXDXDXFXFXGXGXPXPXHXHXIXJXMXMXMXKXKXLXLXLXa a o ",
-"X | | < # - rXeX9X6X5X4XU.,X:X-XL.*X#XC.@XOXoXb.c.z. X|.j.h.s.a.'.i.u.t.r.w.9._.7.).5.4.j a p o ",
-"X | } Y # * 9 8X6X5X4X3X,X:XI.=X*XG.V.@XOXn.v.c.XX X|.j.g.f.a.p.i.u.t.r.e.0._.7.).5.4.q.i g p o ",
-"X } } | - # , 6X5X4XR.,X:XI.=X*XG.V.m.OXoXb.c.XX X|.j.g.f.a.p.i.u.t.r.e.9._.7.).5.4.3.~ a s s o ",
-"X } } } 4 # - E 4XU.>X:X-X=XJ.#XV.M.OXoXb.c.XX X|.{.h.d.a.'.i.u.t.r.e.9._.7.).5.4.3.6.z p s s o ",
-"X { { } } - # < U.,X:XI.=X*XG.V.+XOXoXb.c.z. X|.}.g.d.a.'.i.u.t.r.w.0._.7.).5.4.3.2.! g p s s o ",
-"X [ { ' [ 4 * - E :X;XL.J.#XV.m.OXoXb.c.z..X|.j.h.f.a.'.i.u.t.r.w.9._.6.).(.4.3.2.8.k p s s s o ",
-"X [ [ ' _ [ , * , ;XL.J.#XV.@XOXoXv.c.z..X|.{.g.f.a.p.i.u.t.r.w.`._.7.).(.4.3.2.2.^ s p s s s o ",
-"X _ _ _ _ P ] - * 2 *X#XV.m.OXn.v.c.XX X|.j.h.f.a.p.i.u.t.r.w.`._.7.).(.4.3.2.2.Q p s s s b u o ",
-"X ` ` ` ` ` ` 8 - - 7 V.@XOXoXv.c.XX.X|.j.g.d.a.'.i.u.t.r.w.0._.7.).5.4.3.2.2.O.x p s s s u u o ",
-"X P P ) P U U ) 8 - - 7 OXn.v.c.XX X|.j.h.f.a.p.i.u.t.r.w.0._.7.).5.4.3.2.2.O.x s s s s b u u o ",
-"X L L ) H ) L L L 8 1 - 7 b.c.z. X|.j.h.f.a.'.i.u.t.r.w.0._.7.).5.4.3.2.2.Q x p s s s b b u e o ",
-"X L G L G G G G G G G , * 2 T .Xl.j.h.f.a.p.i.u.t.r.e.0._.7.).5.4.3.2.8.^ p p s s s s u u e e o ",
-"X G G G G G G G K K M M 4 , , 3 I g.d.a.p.i.u.t.r.e.`._.7.).5.4.3.7.! k p s p s s s u u u e v o ",
-"X K G K K K K K K Z Z M F F 4 , < 3 I p.i.u.t.r.w.9._.7.).5.4.W ~ z a p p s s b s u u u e e e o ",
-"X F Z F F F F Z Z F F S S S S S w 9 < 2 5 0 l p.e.9.y.a.l ^ j i a p p p s s b b b u e v y r e o ",
-"X S Z Z S Z S Z S S S S S C C C A m d V f m B m B d d n d a a a p s p s s b u u u u e v e r t o ",
-"X S S S S S S S S S S C C C m m A V V B B B d d d n n a a a p p s p s s b u u u e e e c t r t o ",
-"X C C C C C C C C m C A m A m f V f f B d d d n n n a a a a s s s s s u b u u u u v t t r t t o ",
-"YXo o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o YX"
-};
diff --git a/java/management/eclipse-plugin/src/main/resources/solaris-gtk-sparc/Qpidmc.m.pm b/java/management/eclipse-plugin/src/main/resources/solaris-gtk-sparc/Qpidmc.m.pm
deleted file mode 100644
index e64aa0cc06..0000000000
--- a/java/management/eclipse-plugin/src/main/resources/solaris-gtk-sparc/Qpidmc.m.pm
+++ /dev/null
@@ -1,295 +0,0 @@
-/* XPM */
-static char *ProductIcon32[] = {
-/* columns rows colors chars-per-pixel */
-"32 32 257 2",
-" c black",
-". c gray100",
-"X c #69695A5AE8E8",
-"o c #494949499191",
-"O c #E8E8CBCBE0E0",
-"+ c #DDDDB3B3D2D2",
-"@ c #F0F0DDDDEBEB",
-"# c #CDCD9191BEBE",
-"$ c #C8C88B8BBBBB",
-"% c #CACA9898C2C2",
-"& c #C3C38A8ABBBB",
-"* c #BABA8787B9B9",
-"= c #DCDCC4C4DEDE",
-"- c #C5C5A3A3CACA",
-"; c #ADAD8181B8B8",
-": c #A3A37A7AB5B5",
-"> c #E2E2D6D6E9E9",
-", c #B3B39A9AC4C4",
-"< c #EBEBE3E3F0F0",
-"1 c #C9C9B6B6D6D6",
-"2 c #96967676B8B8",
-"3 c #8C8C7171ABAB",
-"4 c #A4A49292BEBE",
-"5 c #7D7D6565A6A6",
-"6 c #83836D6DABAB",
-"7 c #9A9A8787C2C2",
-"8 c #7B7B6464B7B7",
-"9 c #5E5E50509191",
-"0 c #646457579A9A",
-"q c #85857B7BBEBE",
-"w c #7C7C7373B6B6",
-"e c #62625353D5D5",
-"r c #61615353D4D4",
-"t c #60605252D1D1",
-"y c #5F5F5252D0D0",
-"u c #5F5F5151CFCF",
-"i c #60605353D2D2",
-"p c #5F5F5252CFCF",
-"a c #5E5E5151CDCD",
-"s c #5C5C4F4FC7C7",
-"d c #5F5F5252CDCD",
-"f c #5E5E5151CBCB",
-"g c #5B5B4F4FC4C4",
-"h c #5A5A4E4EC1C1",
-"j c #71716969B0B0",
-"k c #48483E3EADAD",
-"l c #5D5D5151CDCD",
-"z c #5C5C5050C9C9",
-"x c #5D5D5151CBCB",
-"c c #5C5C5050C7C7",
-"v c #5B5B4F4FC6C6",
-"b c #5B5B5050C6C6",
-"n c #59594E4EC1C1",
-"m c #58584D4DBFBF",
-"M c #59594F4FC2C2",
-"N c #5A5A4F4FC2C2",
-"B c #58584D4DBCBC",
-"V c #57574D4DBCBC",
-"C c #59594E4EBEBE",
-"Z c #58584E4EBDBD",
-"A c #58584D4DBBBB",
-"S c #57574D4DBABA",
-"D c #56564D4DB9B9",
-"F c #56564C4CB6B6",
-"G c #55554C4CB6B6",
-"H c #54544B4BB4B4",
-"J c #54544B4BB1B1",
-"K c #53534B4BB1B1",
-"L c #52524A4AAEAE",
-"P c #51514949ACAC",
-"I c #51514949ABAB",
-"U c #474741418787",
-"Y c #32322C2C8F8F",
-"T c #2B2B25257777",
-"R c #36362F2F9696",
-"E c #2B2B26266E6E",
-"W c #4D4D4545ACAC",
-"Q c #55554D4DB8B8",
-"! c #54544C4CB4B4",
-"~ c #54544C4CB3B3",
-"^ c #51514A4AACAC",
-"/ c #51514A4AABAB",
-"( c #50504949A9A9",
-") c #4F4F4949A6A6",
-"_ c #4C4C4747A1A1",
-"` c #4E4E4848A3A3",
-"' c #4D4D4848A1A1",
-"] c #4B4B46469C9C",
-"[ c #4C4C47479E9E",
-"{ c #51514C4CA6A6",
-"} c #A9A9A6A6D5D5",
-"| c #1E1E1A1A6666",
-" . c #292925258181",
-".. c #3D3D39399292",
-"X. c #4A4A46469B9B",
-"o. c #53534E4EABAB",
-"O. c #494945459797",
-"+. c #4A4A46469999",
-"@. c #474744449494",
-"#. c #484845459494",
-"$. c #474744449292",
-"%. c #464643439090",
-"&. c #464642428D8D",
-"*. c #54545050A9A9",
-"=. c #474744448F8F",
-"-. c #4C4C49499999",
-";. c #57575454A6A6",
-":. c #5B5B5757AAAA",
-">. c #545451519B9B",
-",. c #5A5A57579C9C",
-"<. c #65656262A7A7",
-"1. c #68686666A2A2",
-"2. c #CACAC9C9E5E5",
-"3. c #050504045151",
-"4. c #080807075454",
-"5. c #0A0A09095858",
-"6. c #0C0C0A0A5858",
-"7. c #10100E0E6262",
-"8. c #0E0E0D0D5A5A",
-"9. c #121211115D5D",
-"0. c #131312125D5D",
-"q. c #161615156161",
-"w. c #171716166161",
-"e. c #1A1A19196565",
-"r. c #20201E1E7070",
-"t. c #1E1E1D1D6969",
-"y. c #2A2A29297676",
-"u. c #2F2F2D2D7676",
-"i. c #3A3A39398787",
-"p. c #3A3A39398383",
-"a. c #3F3F3E3E8888",
-"s. c #414140408989",
-"d. c #454543438D8D",
-"f. c #444442428B8B",
-"g. c #444443438C8C",
-"h. c #434342428A8A",
-"j. c #434341418888",
-"k. c #434342428989",
-"l. c #424241418787",
-"z. c #434342428787",
-"x. c #424241418585",
-"c. c #41413F3F8181",
-"v. c #414140408282",
-"b. c #484846468D8D",
-"n. c #494948489090",
-"m. c #4B4B4A4A9191",
-"M. c #4B4B49498E8E",
-"N. c #525251519A9A",
-"B. c #525251519999",
-"V. c #565654549A9A",
-"C. c #545453539494",
-"Z. c #60605F5FA7A7",
-"A. c #64646363ABAB",
-"S. c #5A5A59599797",
-"D. c #68686767ADAD",
-"F. c #6C6C6B6BB2B2",
-"G. c #5E5E5D5D9A9A",
-"H. c #76767575BABA",
-"J. c #78787777BBBB",
-"K. c #76767474B5B5",
-"L. c #7E7E7D7DBABA",
-"P. c #A5A5A4A4D2D2",
-"I. c #040404045252",
-"U. c #070707075454",
-"Y. c #070708085353",
-"T. c #080808085454",
-"R. c #0A0A0B0B5757",
-"E. c #0E0E0E0E5A5A",
-"W. c #111112125E5E",
-"Q. c #111111115E5E",
-"!. c #111111115D5D",
-"~. c #111112125D5D",
-"^. c #161616166868",
-"/. c #151516166161",
-"(. c #151515156161",
-"). c #19191A1A6565",
-"_. c #191919196565",
-"`. c #1A1A1A1A6464",
-"'. c #1D1D1E1E6969",
-"]. c #1E1E1E1E6969",
-"[. c #222222226D6D",
-"{. c #272727277171",
-"}. c #2B2B2C2C7676",
-"|. c #2B2B2B2B7676",
-" X c #2B2B2B2B7575",
-".X c #303030307A7A",
-"XX c #303030307979",
-"oX c #353535357F7F",
-"OX c #393939398383",
-"+X c #3A3A3A3A8383",
-"@X c #3F3F3F3F8787",
-"#X c #434343438C8C",
-"$X c #434344448C8C",
-"%X c #424242428686",
-"&X c #414141418484",
-"*X c #484848489191",
-"=X c #484849499090",
-"-X c #4D4D4D4D9696",
-";X c #515151519D9D",
-":X c #4D4D4D4D9595",
-">X c #515152529A9A",
-",X c #515152529999",
-"<X c #525252529A9A",
-"1X c #525252529999",
-"2X c #565657579E9E",
-"3X c #575757579D9D",
-"4X c #5B5B5B5BA2A2",
-"5X c #5F5F6060A6A6",
-"6X c #5F5F5F5FA6A6",
-"7X c #63636464AAAA",
-"8X c #64646464AAAA",
-"9X c #67676767AEAE",
-"0X c #67676868AEAE",
-"qX c #68686868AEAE",
-"wX c #6F6F6F6FB5B5",
-"eX c #6C6C6C6CB1B1",
-"rX c #73737373B8B8",
-"tX c #82828282BEBE",
-"yX c #86868686C2C2",
-"uX c #89898989C4C4",
-"iX c #98989898CBCB",
-"pX c #A0A0A0A0CFCF",
-"aX c #A9A9A9A9D5D5",
-"sX c #B0B0B0B0D8D8",
-"dX c #B8B8B8B8DDDD",
-"fX c #BDBDBDBDE0E0",
-"gX c #D9D9D9D9EDED",
-"hX c #90909191C6C6",
-"jX c #71718989BCBC",
-"kX c #73738B8BBFBF",
-"lX c #72728989BCBC",
-"zX c #79799090C3C3",
-"xX c #7E7E9595C7C7",
-"cX c #81819898CACA",
-"vX c #84849B9BCCCC",
-"bX c #8C8CA3A3D4D4",
-"nX c #71718A8ABCBC",
-"mX c #73738B8BBDBD",
-"MX c #75758D8DBFBF",
-"NX c #74748C8CBEBE",
-"BX c #76768E8EC0C0",
-"VX c #7C7C9494C6C6",
-"CX c #7B7B9393C4C4",
-"ZX c #7F7F9797C9C9",
-"AX c #82829A9ACBCB",
-"SX c #85859E9ECECE",
-"DX c #8888A0A0D1D1",
-"FX c #87879F9FD0D0",
-"GX c #8B8BA4A4D4D4",
-"HX c #8B8BA3A3D4D4",
-"JX c #8989A1A1D2D2",
-"KX c #8D8DA5A5D6D6",
-"LX c #8B8BA3A3D3D3",
-"PX c #8E8EA6A6D6D6",
-"IX c #8D8DA5A5D5D5",
-"UX c gray100",
-"YX c None",
-/* pixels */
-"YXX X X X X X X X X X X X X X X X X X X X X X X X X X X X X X YX",
-"X v.v.v.v.&Xl.z.k.&.d.%.$.@.O.+.] [ _ ` ) ( ^ L K ! G D V m m o ",
-"X c.c.c.v.&Xx.z.f.f.d.%.$.#.O.+.X.[ _ ` ) ( / L K H F D V C n o ",
-"X v.c.v.v.x.x.z.k.f.n.V.,.>.-.+.] [ _ ` ) ( ^ L K H G D V C h o ",
-"X &Xv.&Xx.x.l.j.M.1.4 - - , 7 q J.H.K.j :.*.P L K H F S B C n o ",
-"X x.&Xx.x.z.j.S., = = 1 } iXuXH.rXwXF.qX7XZ.;.o.J ! F S B m n o ",
-"X x.l.z.%Xz.G.1 @ > 2.dXaXiXuXrXwXF.qX8X5X4X2X;X{ H F S V C n o ",
-"X z.j.j.j.C.1 @ < gX2.fXaXpXuXwXeX9X7X5X4X2XN.:X*X_ D S Z m h o ",
-"X k.k.h.b., O > gXgX2.dXaXiXyXF.D.A.Z.4X3X1X:Xn.g.a._ V B m N o ",
-"X f.f.f.3 + = 2.2.2.fXsXpXhXtXD.8XZ.4X2X1X:X*X$X@Xp.i.W C n N o ",
-"X d.&.%.% + 1 dXdXdXsXP.iXyXK.8X5X4X2X>X:X*Xg.a.+XoX.X..m n N o ",
-"X %.=.5 % - P.} aXP.pXiXyXK.D.Z.4X3X1X-Xn.$X@X+XoX.X Xy.W h g o ",
-"X $.$.: # PXIXGXGXLXJXFXFXSXvXAXcXZXxXVXCXzXzXBXMXkXmXnXjXh g o ",
-"X #.@.* $ 7 yXuXyXtXL.K.D.6X4X2X1X:Xo g.a.OXoX.X|.{.[.t. .g v o ",
-"X O.#.$ $ q H.rXwXF.0XA.6X4X2X1X:Xo $Xa.p.oX.X|.{.[.'.`.r.g b o ",
-"X X.+.$ $ PXKXbXbXLXJXDXFXSXvXAXcXZXxXCXCXzXBXBXMXNXmXlXjXb c o ",
-"X ] ] $ $ H.wXF.0X7X6X4X2X<X:Xo #Xa.+XoX.X|.{.[.].)./.~.Q.c z o ",
-"X [ [ & & w F.qX7XZ.4X2X,X:Xo #Xa.+XoX.X}.{.[.'.e./.9.E.^.c z o ",
-"X ' _ * & PXKXbXHXLXJXDXSXSXvXAXcXZXxXVXCXzXzXBXMXNXkXjXjXz x o ",
-"X ` ` : & 2 8XZ.4X2XB.:X*Xg.@Xp.oX.X|.{.[.].).q.!.E.R.U.Y z f o ",
-"X ) ) 5 & ; <.4X2X>X:Xo #Xa.+XoXXX|.{.[.t._.q.~.E.R.4.5.k x a o ",
-"X ( ( I ; * 6 2X>X:X=X$X@X+XoX.X|.{.[.t.e./.W.E.R.Y.3. .z a a o ",
-"X I ^ / 8 * : 0 :X*X#X@X+XoX.X|.{.[.'._.(.~.E.R.T.3.7.k x a p o ",
-"X L L L ^ 2 * 3 m.$Xa.p.oX.X}.{.[.t.).(.~.E.6.T.3.I.R x a a y o ",
-"X J K K K K 2 * 5 s.OXoX.X}.{.[.'._.(.9.8.R.4.3.I.Y x l a p t o ",
-"X ~ H H ! ! ! 2 ; 5 U XX}.{.[.].e.(.W.E.R.U.3.7.R x l u u y t o ",
-"X G F G G G Q Q 8 : 3 9 u.[.]._./.Q.E.R.T.6. .k x a a u t t t o ",
-"X D S D S D S S S V 8 2 6 9 c.E w.0.| T Y k z z a a p t t i r o ",
-"X A V B V V V B B m m n n h h g g g c z z z l l d p y t i r r o ",
-"X m C C C C C C C n n n M N g g b c z z x a a a u y t t r r e o ",
-"X n n n n n h h h N N g g v b s z z z x a p p u t t r r r e e o ",
-"YXo o o o o o o o o o o o o o o o o o o o o o o o o o o o o o YX"
-};
diff --git a/java/management/eclipse-plugin/src/main/resources/solaris-gtk-sparc/Qpidmc.s.pm b/java/management/eclipse-plugin/src/main/resources/solaris-gtk-sparc/Qpidmc.s.pm
deleted file mode 100644
index e2b9379f3a..0000000000
--- a/java/management/eclipse-plugin/src/main/resources/solaris-gtk-sparc/Qpidmc.s.pm
+++ /dev/null
@@ -1,287 +0,0 @@
-/* XPM */
-static char *ProductIcon24[] = {
-/* columns rows colors chars-per-pixel */
-"24 24 257 2",
-" c black",
-". c gray100",
-"X c #69695A5AE8E8",
-"o c #494949499191",
-"O c #F1F1DFDFECEC",
-"+ c #D7D7ACACCDCD",
-"@ c #DFDFBBBBD6D6",
-"# c #E2E2C4C4DBDB",
-"$ c #CECE9C9CC4C4",
-"% c #C4C48B8BBABA",
-"& c #C2C28A8ABABA",
-"* c #C4C48E8EBCBC",
-"= c #BFBF8A8AB9B9",
-"- c #EBEBD9D9E9E9",
-"; c #BFBF8888B9B9",
-": c #D8D8B9B9D6D6",
-"> c #B9B98686B9B9",
-", c #B8B88989B9B9",
-"< c #BBBB9393BFBF",
-"1 c #A9A97B7BB2B2",
-"2 c #E4E4D4D4E7E7",
-"3 c #C6C6AFAFCECE",
-"4 c #A6A68080B6B6",
-"5 c #A2A27E7EB4B4",
-"6 c #9E9E7E7EB1B1",
-"7 c #ABAB9090BBBB",
-"8 c #B7B7A0A0C5C5",
-"9 c #9D9D7C7CB2B2",
-"0 c #AAAA8B8BBEBE",
-"q c #AAAA9090BCBC",
-"w c #8C8C6B6BABAB",
-"e c #90907070B1B1",
-"r c #C4C4B3B3D7D7",
-"t c #CDCDBFBFDDDD",
-"y c #EAEAE4E4F1F1",
-"u c #88886A6AADAD",
-"i c #9E9E8585C1C1",
-"p c #84846A6AAFAF",
-"a c #81816B6BAAAA",
-"s c #D7D7CFCFE6E6",
-"d c #81816969B1B1",
-"f c #78786363A5A5",
-"g c #6E6E5D5D9C9C",
-"h c #717160609D9D",
-"j c #83837474AAAA",
-"k c #6A6A5757A3A3",
-"l c #6E6E5E5EA0A0",
-"z c #5E5E50509292",
-"x c #88887B7BBCBC",
-"c c #68685858ABAB",
-"v c #5A5A4D4DA2A2",
-"b c #7D7D7373B4B4",
-"n c #5A5A4E4EA6A6",
-"m c #5F5F56569595",
-"M c #56564A4ABBBB",
-"N c #56564949B9B9",
-"B c #55554949B8B8",
-"V c #53534848B3B3",
-"C c #54544949B4B4",
-"Z c #52524747B0B0",
-"A c #52524747AFAF",
-"S c #5B5B53539393",
-"D c #3E3E36369797",
-"F c #49494040A6A6",
-"G c #48484040A5A5",
-"H c #55554A4ABABA",
-"J c #54544949B7B7",
-"K c #53534949B4B4",
-"L c #51514747AFAF",
-"P c #52524848B1B1",
-"I c #51514848B0B0",
-"U c #51514848AEAE",
-"Y c #51514747ADAD",
-"T c #51514848ADAD",
-"R c #4F4F4747ABAB",
-"E c #50504747ABAB",
-"W c #50504646A9A9",
-"Q c #4F4F4646A8A8",
-"! c #4E4E4646A7A7",
-"~ c #4E4E4545A4A4",
-"^ c #4D4D4545A4A4",
-"/ c #4E4E4646A5A5",
-"( c #4D4D4545A1A1",
-") c #3D3D36367E7E",
-"_ c #4B4B44449C9C",
-"` c #2A2A25257F7F",
-"' c #3E3E37379898",
-"] c #474740409C9C",
-"[ c #4D4D4646A4A4",
-"{ c #4C4C4545A2A2",
-"} c #4D4D4646A2A2",
-"| c #4D4D4646A1A1",
-" . c #4B4B45459F9F",
-".. c #4C4C45459F9F",
-"X. c #4C4C46469F9F",
-"o. c #4B4B45459D9D",
-"O. c #494943439898",
-"+. c #494944449A9A",
-"@. c #4A4A45459A9A",
-"#. c #494944449898",
-"$. c #484843439696",
-"%. c #494944449797",
-"&. c #484843439595",
-"*. c #51514C4CA1A1",
-"=. c #6B6B6767AEAE",
-"-. c #95959191C9C9",
-";. c #23231F1F7676",
-":. c #21211E1E7070",
-">. c #292925257F7F",
-",. c #252521217070",
-"<. c #242421216D6D",
-"1. c #2B2B27278080",
-"2. c #393935358C8C",
-"3. c #444440409494",
-"4. c #3B3B38388282",
-"5. c #474743439494",
-"6. c #484844449595",
-"7. c #474743439393",
-"8. c #474744449393",
-"9. c #464643439191",
-"0. c #454542428F8F",
-"q. c #4A4A47479898",
-"w. c #464643438F8F",
-"e. c #454542428D8D",
-"r. c #444441418B8B",
-"t. c #484844449191",
-"y. c #444441418989",
-"u. c #494946469090",
-"i. c #4C4C48489393",
-"p. c #51514E4E9E9E",
-"a. c #73737070B6B6",
-"s. c #77777474BBBB",
-"d. c #A0A09E9ED1D1",
-"f. c #D6D6D5D5EBEB",
-"g. c #0E0E0D0D5A5A",
-"h. c #11110F0F5E5E",
-"j. c #121211115E5E",
-"k. c #131312125F5F",
-"l. c #171716166363",
-"z. c #1D1D1B1B6868",
-"x. c #1D1D1C1C6868",
-"c. c #222221216E6E",
-"v. c #222221216D6D",
-"b. c #282827277474",
-"n. c #282827277373",
-"m. c #292928287373",
-"M. c #2F2F2E2E7979",
-"N. c #353534347F7F",
-"B. c #363635358181",
-"V. c #3C3C3B3B8585",
-"C. c #424241418C8C",
-"Z. c #424241418B8B",
-"A. c #444442428B8B",
-"S. c #434341418989",
-"D. c #434342428989",
-"F. c #424241418787",
-"G. c #414140408484",
-"H. c #474745458D8D",
-"J. c #434342428787",
-"K. c #424241418585",
-"L. c #414140408282",
-"P. c #494948489191",
-"I. c #4F4F4E4E9797",
-"U. c #59595757A6A6",
-"Y. c #5F5F5D5DA4A4",
-"T. c #6C6C6B6BB3B3",
-"R. c #7C7C7B7BB9B9",
-"E. c #A8A8A7A7D3D3",
-"W. c #0D0D0D0D5A5A",
-"Q. c #1F1F1F1F6C6C",
-"!. c #222222226E6E",
-"~. c #3B3B3B3B8585",
-"^. c #414141418C8C",
-"/. c #414141418B8B",
-"(. c #424242428B8B",
-"). c #484848489292",
-"_. c #404040408181",
-"`. c #4E4E4E4E9898",
-"'. c #555555559E9E",
-"]. c #555555559D9D",
-"[. c #5B5B5B5BA3A3",
-"{. c #5C5C5C5CA3A3",
-"}. c #61616161A9A9",
-"|. c #66666666AEAE",
-" X c #66666666ADAD",
-".X c #6B6B6B6BB2B2",
-"XX c #70707070B7B7",
-"oX c #6A6A6A6AADAD",
-"OX c #74747474BBBB",
-"+X c #89898989C2C2",
-"@X c #90909090C8C8",
-"#X c #8F8F8F8FC6C6",
-"$X c #92929292C6C6",
-"%X c #9F9F9F9FCFCF",
-"&X c #A5A5A5A5D2D2",
-"*X c #B5B5B5B5DBDB",
-"=X c #B8B8B8B8DEDE",
-"-X c #B7B7B7B7DCDC",
-";X c #BBBBBBBBDEDE",
-":X c #BDBDBDBDDFDF",
-">X c #C9C9C9C9E5E5",
-",X c #D1D1D1D1EAEA",
-"<X c #7C7C7D7DBABA",
-"1X c #89898A8AC7C7",
-"2X c #8F8F9090C7C7",
-"3X c #A3A3A4A4D3D3",
-"4X c #A2A2B5B5DEDE",
-"5X c #ADADBDBDE1E1",
-"6X c #B9B9C7C7E5E5",
-"7X c #BABAC8C8E6E6",
-"8X c #8E8EA6A6D6D6",
-"9X c #9090A7A7D7D7",
-"0X c #9191A9A9D7D7",
-"qX c #9292A9A9D8D8",
-"wX c #9494ABABD8D8",
-"eX c #9898AEAED9D9",
-"rX c #9B9BB0B0DADA",
-"tX c #9E9EB3B3DCDC",
-"yX c #A1A1B5B5DDDD",
-"uX c #A5A5B8B8DEDE",
-"iX c #A8A8BBBBE0E0",
-"pX c #ACACBEBEE1E1",
-"aX c #AFAFC0C0E3E3",
-"sX c #B3B3C3C3E4E4",
-"dX c #B2B2C2C2E3E3",
-"fX c #B5B5C5C5E5E5",
-"gX c #B8B8C7C7E6E6",
-"hX c #B6B6C5C5E4E4",
-"jX c #9797AEAED9D9",
-"kX c #A1A1B6B6DDDD",
-"lX c #A8A8BBBBDFDF",
-"zX c gray100",
-"xX c black",
-"cX c black",
-"vX c black",
-"bX c black",
-"nX c black",
-"mX c black",
-"MX c black",
-"NX c black",
-"BX c black",
-"VX c black",
-"CX c black",
-"ZX c black",
-"AX c black",
-"SX c black",
-"DX c black",
-"FX c black",
-"GX c black",
-"HX c black",
-"JX c black",
-"KX c black",
-"LX c black",
-"PX c black",
-"IX c black",
-"UX c black",
-"YX c None",
-/* pixels */
-"YXX X X X X X X X X X X X X X X X X X X X X X YX",
-"X _._.L.G.K.F.D.A.e.0.9.&.$.%.+._ ..{ ^ ! W E o ",
-"X L.L.L.G.F.F.D.r.e.0.9.7.&.O.@.o. .{ ~ ! Q E o ",
-"X L.G.G.K.F.S.y.r.e.w.9.5.$.+.@.o...( ~ ! W E o ",
-"X G.K.K.F.J.D.h 6 0 i x s.a.=.U.*...} ~ ! W E o ",
-"X K.F.F.F.S 7 : r d.1XOXXX.X|.}.[.p.| / ! W E o ",
-"X F.F.F.m 3 - s =X3X@XXXT. X}.[.].I.q.{ Q E T o ",
-"X S.D.H.8 O y ,X;X&X2X.X|.}.[.].I.P.C.3.Q E Y o ",
-"X A.r.j # 2 f.>X*X%X+X|.}.[.].I.P.^.~.B.] E Y o ",
-"X e.u.q @ t :X-XE.$X<X}.[.].`.P.Z.V.N.M.2.Y L o ",
-"X 0.i.< + 8X8XqXwXeXrXtX4XuXlXpXaXsXfXgX7XY A o ",
-"X 9.t.* $ -.#X+XR.oX{.'.`.P.(.~.N.M.m.c.Q.T Z o ",
-"X 8.7.; % 8X9X0XwXeXrXtXyXuXiXpXaXdXfXgX7XL Z o ",
-"X 6.&.1 & b X}.[.'.I.P./.~.N.M.n.!.x.l.:.I P o ",
-"X #.#.w = 8X9XqXwXjXrXtXkXuXiX5XaXsXhX6X7XP V o ",
-"X +.+.k > 5 Y.].I.)./.~.N.M.b.v.x.l.k.h.' V C o ",
-"X o.o.o.u , a I.).Z.V.N.M.n.c.z.l.j.W.` P V C o ",
-"X .. .X.v e 4 l ^.V.N.M.m.!.x.l.j.g.;.F V C J o ",
-"X ( | ( ( n p 9 g 4.M.n.c.x.l.j.h.>.G V K C J o ",
-"X ~ [ [ ^ / / c d f z ) <.z.,.1.D P V C C B B o ",
-"X ! Q ! Q Q Q Q W E E Y T A Z P V V K C J B B o ",
-"X Q W Q W R W E E T T T L Z P V V K J J J B N o ",
-"X R E E E E E Y Y U L Z P P P C V J J B B H M o ",
-"YXo o o o o o o o o o o o o o o o o o o o o o YX"
-};
diff --git a/java/management/eclipse-plugin/src/main/resources/solaris-gtk-sparc/Qpidmc.t.pm b/java/management/eclipse-plugin/src/main/resources/solaris-gtk-sparc/Qpidmc.t.pm
deleted file mode 100644
index 3f6b21f428..0000000000
--- a/java/management/eclipse-plugin/src/main/resources/solaris-gtk-sparc/Qpidmc.t.pm
+++ /dev/null
@@ -1,279 +0,0 @@
-/* XPM */
-static char *ProductIcon16[] = {
-/* columns rows colors chars-per-pixel */
-"16 16 257 2",
-" c black",
-". c gray100",
-"X c #E2E2C0C0D9D9",
-"o c #EDEDD9D9E8E8",
-"O c #D5D5ABABCDCD",
-"+ c #E2E2C3C3DCDC",
-"@ c #C5C58E8EBCBC",
-"# c #D4D4ABABCDCD",
-"$ c #CACA9F9FC6C6",
-"% c #D6D6B4B4D3D3",
-"& c #CACAA0A0C8C8",
-"* c #C6C69D9DC6C6",
-"= c #C5C59F9FC8C8",
-"- c #CCCCACACCECE",
-"; c #CCCCB0B0D3D3",
-": c #A6A68383B3B3",
-"> c #BABA9A9AC6C6",
-", c #B7B79A9AC2C2",
-"< c #E3E3D5D5E9E9",
-"1 c #B0B08E8EC0C0",
-"2 c #9F9F8080B8B8",
-"3 c #AFAF9898C1C1",
-"4 c #DBDBCFCFE5E5",
-"5 c #96967878B2B2",
-"6 c #9A9A7E7EBABA",
-"7 c #8E8E7878AFAF",
-"8 c #91917F7FBDBD",
-"9 c #D3D3CCCCE4E4",
-"0 c #535348488B8B",
-"q c #69695A5AE8E8",
-"w c #55554949B9B9",
-"e c #55554949B8B8",
-"r c #54544848B6B6",
-"t c #53534848B4B4",
-"y c #54544848B4B4",
-"u c #53534848B3B3",
-"i c #53534848B2B2",
-"p c #52524747AFAF",
-"a c #53534848B1B1",
-"s c #54544949B8B8",
-"d c #54544949B6B6",
-"f c #52524848B3B3",
-"g c #52524848B2B2",
-"h c #53534949B3B3",
-"j c #52524848B1B1",
-"k c #52524848B0B0",
-"l c #51514747AEAE",
-"z c #52524848AFAF",
-"x c #51514848AEAE",
-"c c #51514747ADAD",
-"v c #51514747ACAC",
-"b c #4F4F4646AAAA",
-"n c #51514848ADAD",
-"m c #50504747ABAB",
-"M c #50504747AAAA",
-"N c #4F4F4646A8A8",
-"B c #50504747A9A9",
-"V c #4E4E4646A7A7",
-"C c #4E4E4646A6A6",
-"Z c #4F4F4646A6A6",
-"A c #4F4F4747A7A7",
-"S c #4D4D4545A3A3",
-"D c #4D4D4545A2A2",
-"F c #4C4C45459E9E",
-"G c #74746E6EB3B3",
-"H c #2E2E29298383",
-"J c #383832329090",
-"K c #464640409999",
-"L c #4D4D4646A2A2",
-"P c #4E4E4747A3A3",
-"I c #4B4B45459F9F",
-"U c #4B4B45459E9E",
-"Y c #4C4C46469F9F",
-"T c #4A4A44449B9B",
-"R c #4A4A44449A9A",
-"E c #494943439797",
-"W c #494944449797",
-"Q c #484843439494",
-"! c #78787474B8B8",
-"~ c #272724247878",
-"^ c #2D2D2A2A7575",
-"/ c #484844449797",
-"( c #474743439393",
-") c #454542429090",
-"_ c #4B4B48489A9A",
-"` c #464643438F8F",
-"' c #464643438E8E",
-"] c #454542428C8C",
-"[ c #51514D4DA0A0",
-"{ c #5C5C5959A5A5",
-"} c #535350509090",
-"| c #C8C8C7C7E3E3",
-" . c #121211115D5D",
-".. c #1A1A19196565",
-"X. c #242422226D6D",
-"o. c #3F3F3E3E8888",
-"O. c #444442428D8D",
-"+. c #444442428989",
-"@. c #424241418787",
-"#. c #454543438A8A",
-"$. c #434342428888",
-"%. c #424241418686",
-"&. c #414140408484",
-"*. c #414140408383",
-"=. c #424240408383",
-"-. c #414140408282",
-";. c #474746468D8D",
-":. c #464644448989",
-">. c #525251519999",
-",. c #64646363AAAA",
-"<. c #61615F5FA2A2",
-"1. c #6E6E6C6CB2B2",
-"2. c #A5A5A4A4D3D3",
-"3. c #B0B0AFAFD6D6",
-"4. c #111112125D5D",
-"5. c #19191A1A6565",
-"6. c #1E1E1E1E6C6C",
-"7. c #222222226D6D",
-"8. c #2B2B2B2B7676",
-"9. c #2B2B2B2B7575",
-"0. c #2B2B2C2C7575",
-"q. c #343435357F7F",
-"w. c #343435357E7E",
-"e. c #353535357F7F",
-"r. c #3E3E3E3E8888",
-"t. c #3E3E3E3E8787",
-"y. c #414141418484",
-"u. c #404040408282",
-"i. c #484849499191",
-"p. c #494949499191",
-"a. c #484848489090",
-"s. c #484849499090",
-"d. c #404040408080",
-"f. c #525252529A9A",
-"g. c #525252529999",
-"h. c #5B5B5B5BA3A3",
-"j. c #5B5B5B5BA2A2",
-"k. c #64646464ABAB",
-"l. c #63636464AAAA",
-"z. c #6B6B6C6CB2B2",
-"x. c #72727373B9B9",
-"c. c #71717171A4A4",
-"v. c #78787878ABAB",
-"b. c #7F7F7F7FB1B1",
-"n. c #8C8C8C8CBEBE",
-"m. c #A5A5A5A5D2D2",
-"M. c #C9C9C9C9E5E5",
-"N. c #85858686B7B7",
-"B. c #91919292C4C4",
-"V. c #71718989BCBC",
-"C. c #73738B8BBEBE",
-"Z. c #75758D8DC0C0",
-"A. c #78789090C3C3",
-"S. c #7A7A9292C5C5",
-"D. c #71718A8ABDBD",
-"F. c #76768E8EC0C0",
-"G. c #78789090C2C2",
-"H. c #7B7B9393C5C5",
-"J. c #7D7D9595C7C7",
-"K. c #80809999CACA",
-"L. c #7E7E9696C7C7",
-"P. c #83839B9BCDCD",
-"I. c #83839B9BCCCC",
-"U. c #86869E9ECFCF",
-"Y. c #8888A1A1D1D1",
-"T. c #8A8AA2A2D3D3",
-"R. c #8989A1A1D1D1",
-"E. c #8B8BA3A3D3D3",
-"W. c gray100",
-"Q. c black",
-"!. c black",
-"~. c black",
-"^. c black",
-"/. c black",
-"(. c black",
-"). c black",
-"_. c black",
-"`. c black",
-"'. c black",
-"]. c black",
-"[. c black",
-"{. c black",
-"}. c black",
-"|. c black",
-" X c black",
-".X c black",
-"XX c black",
-"oX c black",
-"OX c black",
-"+X c black",
-"@X c black",
-"#X c black",
-"$X c black",
-"%X c black",
-"&X c black",
-"*X c black",
-"=X c black",
-"-X c black",
-";X c black",
-":X c black",
-">X c black",
-",X c black",
-"<X c black",
-"1X c black",
-"2X c black",
-"3X c black",
-"4X c black",
-"5X c black",
-"6X c black",
-"7X c black",
-"8X c black",
-"9X c black",
-"0X c black",
-"qX c black",
-"wX c black",
-"eX c black",
-"rX c black",
-"tX c black",
-"yX c black",
-"uX c black",
-"iX c black",
-"pX c black",
-"aX c black",
-"sX c black",
-"dX c black",
-"fX c black",
-"gX c black",
-"hX c black",
-"jX c black",
-"kX c black",
-"lX c black",
-"zX c black",
-"xX c black",
-"cX c black",
-"vX c black",
-"bX c black",
-"nX c black",
-"mX c black",
-"MX c black",
-"NX c black",
-"BX c black",
-"VX c black",
-"CX c black",
-"ZX c black",
-"AX c black",
-"SX c black",
-"DX c black",
-"FX c black",
-"GX c black",
-"HX c black",
-"JX c black",
-"KX c black",
-"LX c black",
-"PX c black",
-"IX c black",
-"UX c black",
-"YX c None",
-/* pixels */
-"YXq q q q q q q q q q q q q q YX",
-"q d.-.y.%.+.O.` ( E R U D C B p.",
-"q u.*.&.$.#.] ) Q W T F L V M p.",
-"q =.y.} , % ; 8 ! 1.{ [ S Z b p.",
-"q @.:.- o 4 2.x.z.,.j.>._ A m p.",
-"q +.: X < M.m.z.l.j.g.s.r.K v p.",
-"q ' $ + 9 | 3.B.n.N.b.v.c.<.n p.",
-"q ` O T.Y.U.P.K.L.S.G.F.C.D.l p.",
-"q ( # @ G k.h.g.i.t.e.9.7.6.z p.",
-"q / * E.R.U.I.K.J.H.A.Z.C.V.a p.",
-"q T 2 & 5 f.a.o.q.8.7...4.J u p.",
-"q I Y 1 = 7 ;.w.0.7.5. .H f y p.",
-"q L D P 6 > 3 0 ^ X.~ J i t d p.",
-"q C C V A N M m n p k g y r e p.",
-"q M b M m m c x p j h y d s w p.",
-"YXp.p.p.p.p.p.p.p.p.p.p.p.p.p.YX"
-};
diff --git a/java/management/eclipse-plugin/src/main/resources/solaris-gtk-sparc/qpidmc b/java/management/eclipse-plugin/src/main/resources/solaris-gtk-sparc/qpidmc
deleted file mode 100755
index b88ff49e8e..0000000000
--- a/java/management/eclipse-plugin/src/main/resources/solaris-gtk-sparc/qpidmc
+++ /dev/null
Binary files differ
diff --git a/java/management/eclipse-plugin/src/main/resources/solaris-gtk-sparc/qpidmc.ini b/java/management/eclipse-plugin/src/main/resources/solaris-gtk-sparc/qpidmc.ini
deleted file mode 100644
index cfa715e5a8..0000000000
--- a/java/management/eclipse-plugin/src/main/resources/solaris-gtk-sparc/qpidmc.ini
+++ /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.
-###############################################################################
--startup
-plugins/org.eclipse.equinox.launcher_1.0.101.R34x_v20080819.jar
---launcher.library
-plugins/org.eclipse.equinox.launcher.gtk.solaris.sparc_1.0.101.R34x_v20080731
--vmargs
--Xms40m
--Xmx256m
--XX:MaxPermSize=256m
--Dosgi.requiredJavaVersion=1.5
--Declipse.consoleLog=true
-
-#===============================================
-# SSL trust store configuration options.
-#===============================================
-
-# Uncomment lines below to specify custom truststore for server SSL
-# certificate verification, eg when using self-signed server certs.
-#
-#-Djavax.net.ssl.trustStore=<path.to.truststore>
-#-Djavax.net.ssl.trustStorePassword=<truststore.password>
-
-
diff --git a/java/management/eclipse-plugin/src/main/resources/win32-win32-x86/Configuration/config.ini b/java/management/eclipse-plugin/src/main/resources/win32-win32-x86/Configuration/config.ini
deleted file mode 100644
index a61bea2fa8..0000000000
--- a/java/management/eclipse-plugin/src/main/resources/win32-win32-x86/Configuration/config.ini
+++ /dev/null
@@ -1,49 +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.
-###############################################################################
-
-#Product Runtime Configuration File
-
-osgi.splashPath=platform:/base/plugins/org.apache.qpid.management.ui
-eclipse.product=org.apache.qpid.management.ui.product
-osgi.bundles.defaultStartLevel=4
-osgi.bundles=jmxremote.sasl, \
-qpid-management-common, \
-org.apache.qpid.management.ui, \
-com.ibm.icu, \
-org.eclipse.core.commands, \
-org.eclipse.core.contenttype, \
-org.eclipse.core.databinding, \
-org.eclipse.core.expressions, \
-org.eclipse.core.jobs, \
-org.eclipse.core.runtime@start, \
-org.eclipse.core.runtime.compatibility.registry, \
-org.eclipse.equinox.app,org.eclipse.equinox.common, \
-org.eclipse.equinox.preferences, \
-org.eclipse.equinox.registry, \
-org.eclipse.help, \
-org.eclipse.jface, \
-org.eclipse.jface.databinding, \
-org.eclipse.swt, \
-org.eclipse.swt.win32.win32.x86, \
-org.eclipse.ui, \
-org.eclipse.ui.forms, \
-org.eclipse.ui.workbench, \
-org.eclipse.equinox.launcher, \
-org.eclipse.equinox.launcher.win32.win32.x86, \
-org.apache.commons.codec
diff --git a/java/management/eclipse-plugin/src/main/resources/win32-win32-x86/qpidmc.exe b/java/management/eclipse-plugin/src/main/resources/win32-win32-x86/qpidmc.exe
deleted file mode 100644
index 3999884bfb..0000000000
--- a/java/management/eclipse-plugin/src/main/resources/win32-win32-x86/qpidmc.exe
+++ /dev/null
Binary files differ
diff --git a/java/management/eclipse-plugin/src/main/resources/win32-win32-x86/qpidmc.ini b/java/management/eclipse-plugin/src/main/resources/win32-win32-x86/qpidmc.ini
deleted file mode 100644
index 312580769e..0000000000
--- a/java/management/eclipse-plugin/src/main/resources/win32-win32-x86/qpidmc.ini
+++ /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.
-###############################################################################
-
--vmargs
--Xms40m
--Xmx256m
--XX:MaxPermSize=256m
--Dosgi.requiredJavaVersion=1.5
--Declipse.consoleLog=true
-
-#===============================================
-# SSL trust store configuration options.
-#===============================================
-
-# Uncomment lines below to specify custom truststore for server SSL
-# certificate verification, eg when using self-signed server certs.
-#
-#-Djavax.net.ssl.trustStore=<path.to.truststore>
-#-Djavax.net.ssl.trustStorePassword=<truststore.password>
-
diff --git a/java/management/eclipse-plugin/src/test/java/org/apache/qpid/management/ui/ApiVersionTest.java b/java/management/eclipse-plugin/src/test/java/org/apache/qpid/management/ui/ApiVersionTest.java
deleted file mode 100644
index b4f6aea57b..0000000000
--- a/java/management/eclipse-plugin/src/test/java/org/apache/qpid/management/ui/ApiVersionTest.java
+++ /dev/null
@@ -1,177 +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.management.ui;
-
-import junit.framework.TestCase;
-
-public class ApiVersionTest extends TestCase
-{
-
- public void testGetMajor()
- {
- ApiVersion ver = new ApiVersion(1,3);
- assertEquals(1, ver.getMajor());
- }
-
- public void testGetMinor()
- {
- ApiVersion ver = new ApiVersion(1,3);
- assertEquals(3, ver.getMinor());
- }
-
- public void testGreaterThanOrEqualTo()
- {
- ApiVersion ver = new ApiVersion(1,3);
-
- //equal
- assertTrue(ver.greaterThanOrEqualTo(1, 3));
- //same major, higher minor
- assertFalse(ver.greaterThanOrEqualTo(1, 4));
- //same major, lower minor
- assertTrue(ver.greaterThanOrEqualTo(1, 2));
-
- //higher major, lower minor
- assertFalse(ver.greaterThanOrEqualTo(2, 0));
- //higher major, same minor
- assertFalse(ver.greaterThanOrEqualTo(2, 3));
- //higher major, higher minor
- assertFalse(ver.greaterThanOrEqualTo(2, 4));
-
- //lower major, higher minor
- assertTrue(ver.greaterThanOrEqualTo(0, 9));
- //lower major, lower minor
- assertTrue(ver.greaterThanOrEqualTo(0, 2));
- //lower major, same minor
- assertTrue(ver.greaterThanOrEqualTo(0, 3));
- }
-
- public void testLessThanOrEqualTo()
- {
- ApiVersion ver = new ApiVersion(1,3);
-
- //equal
- assertTrue(ver.lessThanOrEqualTo(1, 3));
- //same major, higher minor
- assertTrue(ver.lessThanOrEqualTo(1, 4));
- //same major, lower minor
- assertFalse(ver.lessThanOrEqualTo(1, 2));
-
- //higher major, lower minor
- assertTrue(ver.lessThanOrEqualTo(2, 0));
- //higher major, same minor
- assertTrue(ver.lessThanOrEqualTo(2, 3));
- //higher major, higher minor
- assertTrue(ver.lessThanOrEqualTo(2, 4));
-
- //lower major, higher minor
- assertFalse(ver.lessThanOrEqualTo(0, 9));
- //lower major, lower minor
- assertFalse(ver.lessThanOrEqualTo(0, 2));
- //lower major, same minor
- assertFalse(ver.lessThanOrEqualTo(0, 3));
- }
-
- public void testGreaterThan()
- {
- ApiVersion ver = new ApiVersion(1,3);
-
- //equal
- assertFalse(ver.greaterThan(1, 3));
- //same major, higher minor
- assertFalse(ver.greaterThan(1, 4));
- //same major, lower minor
- assertTrue(ver.greaterThan(1, 2));
-
- //higher major, lower minor
- assertFalse(ver.greaterThan(2, 0));
- //higher major, same minor
- assertFalse(ver.greaterThan(2, 3));
- //higher major, higher minor
- assertFalse(ver.greaterThan(2, 4));
-
- //lower major, higher minor
- assertTrue(ver.greaterThan(0, 9));
- //lower major, lower minor
- assertTrue(ver.greaterThan(0, 2));
- //lower major, same minor
- assertTrue(ver.greaterThan(0, 3));
- }
-
- public void testLessThan()
- {
- ApiVersion ver = new ApiVersion(1,3);
-
- //equal
- assertFalse(ver.lessThan(1, 3));
- //same major, higher minor
- assertTrue(ver.lessThan(1, 4));
- //same major, lower minor
- assertFalse(ver.lessThan(1, 2));
-
- //higher major, lower minor
- assertTrue(ver.lessThan(2, 0));
- //higher major, same minor
- assertTrue(ver.lessThan(2, 3));
- //higher major, higher minor
- assertTrue(ver.lessThan(2, 4));
-
- //lower major, higher minor
- assertFalse(ver.lessThan(0, 9));
- //lower major, lower minor
- assertFalse(ver.lessThan(0, 2));
- //lower major, same minor
- assertFalse(ver.lessThan(0, 3));
- }
-
- public void testEqualsIntInt()
- {
- ApiVersion ver = new ApiVersion(1,3);
-
- //equal
- assertTrue(ver.equals(1, 3));
- //same major, higher minor
- assertFalse(ver.equals(1, 4));
- //same major, lower minor
- assertFalse(ver.equals(1, 2));
-
- //higher major, lower minor
- assertFalse(ver.equals(2, 0));
- //higher major, same minor
- assertFalse(ver.equals(2, 3));
- //higher major, higher minor
- assertFalse(ver.equals(2, 4));
-
- //lower major, higher minor
- assertFalse(ver.equals(0, 9));
- //lower major, lower minor
- assertFalse(ver.equals(0, 2));
- //lower major, same minor
- assertFalse(ver.equals(0, 3));
- }
-
- public void testToString()
- {
- ApiVersion ver = new ApiVersion(1,3);
-
- assertEquals("major=1,minor=3", ver.toString());
- }
-
-}
diff --git a/java/management/eclipse-plugin/src/test/java/org/apache/qpid/management/ui/ApplicationRegistryTest.java b/java/management/eclipse-plugin/src/test/java/org/apache/qpid/management/ui/ApplicationRegistryTest.java
deleted file mode 100644
index 1a56ab69b6..0000000000
--- a/java/management/eclipse-plugin/src/test/java/org/apache/qpid/management/ui/ApplicationRegistryTest.java
+++ /dev/null
@@ -1,43 +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.management.ui;
-
-import org.apache.qpid.management.common.mbeans.ServerInformation;
-
-import junit.framework.TestCase;
-
-public class ApplicationRegistryTest extends TestCase
-{
- public void testSupportedManagementApiVersion()
- {
- //ensure that the console supported API version is kept in sync with the broker
-
- assertEquals("The management console does not support the same major version of management API as the broker. " +
- "Make any required changes and update the supported value.",
- ServerInformation.QPID_JMX_API_MAJOR_VERSION,
- ApplicationRegistry.SUPPORTED_QPID_JMX_API_MAJOR_VERSION);
-
- assertEquals("The management console does not support the same minor version of management API as the broker. " +
- "Make any required changes and update the supported value.",
- ServerInformation.QPID_JMX_API_MINOR_VERSION,
- ApplicationRegistry.SUPPORTED_QPID_JMX_API_MINOR_VERSION);
- }
-}
diff --git a/java/management/eclipse-plugin/src/test/java/org/apache/qpid/management/ui/ManagementConsoleTest.java b/java/management/eclipse-plugin/src/test/java/org/apache/qpid/management/ui/ManagementConsoleTest.java
deleted file mode 100644
index 0f62fa8ab2..0000000000
--- a/java/management/eclipse-plugin/src/test/java/org/apache/qpid/management/ui/ManagementConsoleTest.java
+++ /dev/null
@@ -1,122 +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.management.ui;
-
-import junit.framework.TestCase;
-import org.apache.qpid.exchange.ExchangeDefaults;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.server.exchange.DirectExchange;
-import org.apache.qpid.server.management.AMQManagedObject;
-import org.apache.qpid.server.queue.AMQQueueMBean;
-import org.apache.qpid.server.queue.AMQQueue;
-import org.apache.qpid.server.queue.AMQQueueFactory;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-import org.apache.qpid.server.registry.IApplicationRegistry;
-import org.apache.qpid.server.util.InternalBrokerBaseCase;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-
-import javax.management.MBeanFeatureInfo;
-import javax.management.MBeanInfo;
-import java.util.ArrayList;
-import java.util.List;
-
-
-/**
- * Test class to test if any change in the broker JMX code is affesting the management console
- * There are some hardcoding of management feature names and parameter names to create a customized
- * look in the console.
- */
-public class ManagementConsoleTest extends InternalBrokerBaseCase
-{
- private VirtualHost _virtualHost;
-
- @Override
- public void setUp() throws Exception
- {
- super.setUp();
- IApplicationRegistry applicationRegistry = ApplicationRegistry.getInstance();
- _virtualHost = applicationRegistry.getVirtualHostRegistry().getVirtualHost("test");
- }
-
-
- /**
- * Test for AMQQueueMBean attribute and operation names, which are used in the management console
- * @throws Exception
- */
- public void testAMQQueueMBeanInfo() throws Exception
- {
- // If this test fails due to changes in the broker code,
- // then the constants in the Constants.java shoule be updated accordingly
- AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(new AMQShortString("testQueueForManagement"), false, null, false, false,
- _virtualHost, null);
- AMQManagedObject mbean = new AMQQueueMBean(queue);
- MBeanInfo mbeanInfo = mbean.getMBeanInfo();
-
- List<String> operationNames = getNamesList(mbeanInfo.getOperations());
- assertTrue(operationNames.contains(Constants.OPERATION_MOVE_MESSAGES));
-
- List<String> attributesList = getNamesList(mbeanInfo.getAttributes());
- assertTrue(attributesList.contains(Constants.ATTRIBUTE_QUEUE_CONSUMERCOUNT));
- assertTrue(attributesList.contains(Constants.ATTRIBUTE_QUEUE_DEPTH));
- }
-
- /**
- * Test for Exchange MBean attribute and operation names, which are used in the management console
- * @throws Exception
- */
- public void testExchangeMBeanInfo() throws Exception
- {
- // If this test fails due to changes in the broker code,
- // then the constants in the Constants.java shoule be updated accordingly
- DirectExchange exchange = new DirectExchange();
- exchange.initialise(_virtualHost, ExchangeDefaults.DIRECT_EXCHANGE_NAME, false, 0, true);
- AMQManagedObject mbean = (AMQManagedObject)exchange.getManagedObject();
- MBeanInfo mbeanInfo = mbean.getMBeanInfo();
-
- // Check for the Exchange Type property in the ObjectName
- assertNotNull(mbean.getObjectName().getKeyProperty(Constants.EXCHANGE_TYPE));
-
- // Check for operation names
- List<String> operationNames = getNamesList(mbeanInfo.getOperations());
- assertTrue(operationNames.contains(Constants.OPERATION_CREATE_BINDING));
- }
-
- /**
- * Test for VirtualHostManagerMBean features used in Management console for customizing the GUI
- * @throws Exception
- */
- public void testVirtualHostManagerMBeanInfo() throws Exception
- {
- AMQManagedObject mbean = (AMQManagedObject)_virtualHost.getManagedObject();
- assertTrue(mbean.getType().equals(Constants.VIRTUAL_HOST));
- }
-
- private List<String> getNamesList(MBeanFeatureInfo[] features)
- {
- List<String> names = new ArrayList<String>();
- for (MBeanFeatureInfo feature : features)
- {
- names.add(feature.getName());
- }
-
- return names;
- }
-}
diff --git a/java/management/example/build.xml b/java/management/example/build.xml
deleted file mode 100644
index 8bcd615282..0000000000
--- a/java/management/example/build.xml
+++ /dev/null
@@ -1,27 +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.
- -
- -->
-<project name="Management Examples" default="build">
-
- <property name="module.depends" value="management/common"/>
-
- <import file="../../module.xml"/>
-
-</project>
diff --git a/java/management/example/src/main/java/org/apache/qpid/example/jmxexample/AddQueue.java b/java/management/example/src/main/java/org/apache/qpid/example/jmxexample/AddQueue.java
deleted file mode 100644
index b858742c4e..0000000000
--- a/java/management/example/src/main/java/org/apache/qpid/example/jmxexample/AddQueue.java
+++ /dev/null
@@ -1,149 +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.example.jmxexample;
-
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-
-import javax.management.MBeanServerConnection;
-import javax.management.MBeanServerInvocationHandler;
-import javax.management.ObjectName;
-import javax.management.remote.JMXConnector;
-import javax.management.remote.JMXConnectorFactory;
-import javax.management.remote.JMXServiceURL;
-
-import org.apache.qpid.management.common.mbeans.ManagedBroker;
-import org.apache.qpid.management.common.mbeans.ManagedExchange;
-
-public class AddQueue
-{
-
- public static void main(String[] args)
- {
- //Example: add 'newqueue' to the 'test' virtualhost and bind to the 'amq.direct' exchange
- //TODO: take these parameters as arguments
-
- addQueue("test", "amq.direct", "newqueue");
- }
-
- private static JMXConnector getJMXConnection() throws Exception
- {
- //TODO: Take these parameters as main+method arguments
- String host = "localhost";
- int port = 8999;
- String username = "admin";
- String password = "admin";
-
- Map<String, Object> env = new HashMap<String, Object>();
- JMXServiceURL jmxUrl = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + host + ":" + port + "/jmxrmi");
-
- //Add user credential's to environment map for RMIConnector startup.
- env.put(JMXConnector.CREDENTIALS, new String[] {username,password});
-
- return JMXConnectorFactory.connect(jmxUrl, env);
- }
-
- public static boolean addQueue(String virHost, String exchName, String queueName) {
-
- JMXConnector jmxc = null;
- try
- {
- jmxc = getJMXConnection();
-
- MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
-
- ObjectName hostManagerObjectName = new ObjectName(
- "org.apache.qpid:" +
- "type=VirtualHost.VirtualHostManager," +
- "VirtualHost=" + virHost + ",*");
-
- Set<ObjectName> vhostManagers = mbsc.queryNames(hostManagerObjectName, null);
-
- if(vhostManagers.size() == 0)
- {
- //The vhostManager MBean wasnt found, cant procede
- return false;
- }
-
- ManagedBroker vhostManager = (ManagedBroker) MBeanServerInvocationHandler.newProxyInstance(
- mbsc, (ObjectName) vhostManagers.toArray()[0], ManagedBroker.class, false);
-
- ObjectName customExchangeObjectName = new ObjectName(
- "org.apache.qpid:" +
- "type=VirtualHost.Exchange," +
- "VirtualHost=" + virHost + "," +
- "name=" + exchName + "," +
- "ExchangeType=direct,*");
-
- Set<ObjectName> exchanges = mbsc.queryNames(customExchangeObjectName, null);
-
- if(exchanges.size() == 0)
- {
- //The exchange doesnt exist, cant procede.
- return false;
- }
-
- //create the MBean proxy
- ManagedExchange managedExchange = (ManagedExchange) MBeanServerInvocationHandler.newProxyInstance(
- mbsc, (ObjectName) exchanges.toArray()[0], ManagedExchange.class, false);
-
- try
- {
- //create the new durable queue and bind it.
- vhostManager.createNewQueue(queueName, null, true);
- managedExchange.createNewBinding(queueName,queueName);
- }
- catch (Exception e)
- {
- System.out.println("Could not add queue due to exception :" + e.getMessage());
- e.printStackTrace();
- return false;
- }
-
- return true;
-
- }
- catch (Exception e)
- {
- System.out.println("Could not add queue due to error :" + e.getMessage());
- e.printStackTrace();
- }
- finally
- {
- if(jmxc != null)
- {
- try
- {
- jmxc.close();
- }
- catch (IOException e)
- {
- //ignore
- }
- }
- }
-
- return false;
-
- }
-
-}
diff --git a/java/management/example/src/main/java/org/apache/qpid/example/jmxexample/DeleteMessagesFromTopOfTmp.java b/java/management/example/src/main/java/org/apache/qpid/example/jmxexample/DeleteMessagesFromTopOfTmp.java
deleted file mode 100644
index 5d529a8ff6..0000000000
--- a/java/management/example/src/main/java/org/apache/qpid/example/jmxexample/DeleteMessagesFromTopOfTmp.java
+++ /dev/null
@@ -1,119 +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.example.jmxexample;
-
-import java.util.Set;
-
-import javax.management.MBeanServerConnection;
-import javax.management.ObjectName;
-import javax.management.remote.JMXConnector;
-import javax.management.remote.JMXConnectorFactory;
-import javax.management.remote.JMXServiceURL;
-
-/**
- * Connects to a server and queries all info for tmp_* named queues, determines
- * their message count, and if this is above a given threshold deletes the
- * specified number of messages from the front of the queue
- */
-public class DeleteMessagesFromTopOfTmp
-{
- /**
- * Params:
- * 0: host, e.g. myserver.mydomain.com
- * 1: port, e.g. 8999
- * 2: Number of messages to delete, e.g. 1000
- * 3: Threshold MessageCount on queue required before deletion will be undertaken e.g. 5000
- */
- public static void main(String[] args) throws Exception
- {
- if (args.length < 4)
- {
- System.out.println("Usage: ");
- System.out.println("<host> <port> <numMsgsToDel> <minRequiredQueueMsgCount>");
- return;
- }
-
- String host = args[0];
- int port = Integer.parseInt(args[1]);
- int numToDel = Integer.parseInt(args[2]);
- int numRequired = Integer.parseInt(args[3]);
-
- deleteFromTop(host, port, numToDel, numRequired);
- }
-
- private static void deleteFromTop(String host, int port,
- int numMsgsToDel, int minRequiredQueueMsgCount) throws Exception
- {
- JMXConnector con = getJMXConnection(host, port);
- MBeanServerConnection mbsc = con.getMBeanServerConnection();
-
- // Gets all tmp_* queue MBean ObjectNames
- Set<ObjectName> names = mbsc.queryNames(
- new ObjectName("org.apache.qpid:type=VirtualHost.Queue,name=tmp_*,*"), null);
-
- // Traverse objects and delete specified number of message if the min msg count is breached
- for (ObjectName queueObjectName : names)
- {
- String queueName = queueObjectName.getKeyProperty("name");
- System.out.println("Checking message count on queue: " + queueName);
-
- long mc = (Integer) mbsc.getAttribute(queueObjectName, "MessageCount");
-
- if(mc >= minRequiredQueueMsgCount)
- {
- System.out.println("MessageCount (" + mc + ") is above the specified threshold ("
- + minRequiredQueueMsgCount + ")");
- System.out.println("Deleting first " + numMsgsToDel + " messages on queue: " + queueName);
-
- int i;
- for(i=0; i<numMsgsToDel; i++)
- {
- try
- {
- mbsc.invoke(queueObjectName,"deleteMessageFromTop",null,null);
- }
- catch(Exception e)
- {
- System.out.println("Exception whilst deleting message" + i +" from queue: " +e);
- break;
- }
- }
- }
- else
- {
- System.out.println("MessageCount (" + mc + ") is below the specified threshold ("
- + minRequiredQueueMsgCount + ")");
- System.out.println("Not deleting any messages on queue: " + queueName);
- }
- }
- }
-
- private static JMXConnector getJMXConnection(String host, int port) throws Exception
- {
- //Open JMX connection
- JMXServiceURL jmxUrl = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + host + ":" + port + "/jmxrmi");
- JMXConnector con = JMXConnectorFactory.connect(jmxUrl);
- return con;
- }
-}
-
-
-
diff --git a/java/management/example/src/main/java/org/apache/qpid/example/jmxexample/QueueInformation.java b/java/management/example/src/main/java/org/apache/qpid/example/jmxexample/QueueInformation.java
deleted file mode 100644
index 2b34e2da5d..0000000000
--- a/java/management/example/src/main/java/org/apache/qpid/example/jmxexample/QueueInformation.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.example.jmxexample;
-
-import javax.management.InstanceNotFoundException;
-import javax.management.IntrospectionException;
-import javax.management.MBeanAttributeInfo;
-import javax.management.MBeanInfo;
-import javax.management.MBeanServerConnection;
-import javax.management.MalformedObjectNameException;
-import javax.management.ObjectName;
-import javax.management.ReflectionException;
-import javax.management.remote.JMXConnector;
-import javax.management.remote.JMXConnectorFactory;
-import javax.management.remote.JMXServiceURL;
-import java.io.IOException;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * Connects to a server and queries all info for Queues
- * Includes _tmp queues thus covering queues underlying topic subscriptions
- */
-public class QueueInformation
-{
-
- private static long _previousTimePoint = 0l;
- private static Map<String, Long> _previousRMC = new HashMap<String, Long>();
- private static Map<String, Long> _previousMC = new HashMap<String, Long>();
- private static MBeanServerConnection _mbsc;
- private static final String DEFAULT_DATE_FORMAT = System.getProperty("qpid.dateFormat", "yyyy-MM-dd HH:mm:ss");
- private static final SimpleDateFormat _formatter = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
-
- private static final String QUEUE_ARGS = "queues=";
- private static Set<String> _queueNames;
- private static final String ATTRIB_ARGS = "attributes=";
- private static Set<String> _attribNames;
-
- private static MBeanAttributeInfo[] _attribInfo;
- private static String _vhost;
-
- /**
- * Params:
- * 0: host, e.g. eqd-myserver.mydomain.com
- * 1: port, e.g. 8999
- * 2: vhost e.g. dev-only
- * 3: username, e.g. guest
- * 4: pwd, e.g. guest
- * 5: loop pause, no value indicates one-off, any other value is millisecs
- * ..: attributes=<csv attribute list> , queue=<csv queue list>
- * The queue list can use wildcards such as * and ?. Basically any value
- * that JMX will accept in the query string for t name='' value of the queue.
- */
- public static void main(String[] args) throws Exception
- {
- if (args.length < 5 || args.length > 8)
- {
- System.out.println("Usage: ");
- System.out.println("<host> <port> <vhost> <username> <pwd> [<loop pause time in millisecs>] [queues=<queue list csv>] [attributes=<attribute list csv>]");
- return;
- }
- String host = args[0];
- int port = Integer.parseInt(args[1]);
- _vhost = args[2];
- String usr = args[3];
- String pwd = args[4];
- long pause = -1;
-
- if (args.length > 5)
- {
- try
- {
- pause = Long.parseLong(args[5]);
- }
- catch (NumberFormatException nfe)
- {
- // If it wasn't a queue or attribute request then show error
- if (!!args[5].startsWith(QUEUE_ARGS) &&
- !!args[5].startsWith(ATTRIB_ARGS))
- {
- System.out.println("Unknown argument '" + args[5] + "'");
- System.exit(1);
- }
- }
- }
-
- //Process remaining args
- // Skip arg 5 if we have assigned pause a value
- int arg = (pause == -1) ? 5 : 6;
- for (; args.length > arg; arg++)
- {
- processCommandLine(args[arg]);
- }
-
- JMXConnector con = getJMXConnection(host, port, usr, pwd);
-
- _mbsc = con.getMBeanServerConnection();
-
- Set<ObjectName> names = _mbsc.queryNames(new ObjectName("org.apache.qpid:type=VirtualHost.Queue,VirtualHost=" + _vhost + ",*"), null);
-
- // Print header
- if (names.size() > 0)
- {
- System.out.print("Time");
-
- MBeanAttributeInfo[] attributeList = getAttributeList(names.toArray(new ObjectName[1])[0]);
-
- for (int i = 0; attributeList.length > i; i++)
- {
- System.out.print(", " + attributeList[i].getName());
- }
-
- // Include update rate calculations
- if (pause > 0)
- {
- System.out.print(", Consumption rate");
- System.out.print(", Receive rate");
- }
- System.out.print("\n");
- }
- else
- {
- System.out.println("No queues found on specified vhost unable to continue.");
- System.exit(1);
- }
-
- try
- {
- do
- {
- getDetails(pause > -1);
- if (pause > 0)
- {
- _previousTimePoint = System.currentTimeMillis();
- Thread.currentThread().sleep(pause);
- }
- }
- while (pause > 0);
- }
- finally
- {
- con.close();
- }
- }
-
- private static MBeanAttributeInfo[] getAttributeList(ObjectName name)
- throws InstanceNotFoundException, IntrospectionException, ReflectionException, IOException
- {
- if (_attribInfo == null)
- {
- MBeanAttributeInfo[] allAttribs = ((MBeanInfo) _mbsc.getMBeanInfo((ObjectName) name)).getAttributes();
-
- if (_attribNames != null && _attribNames.size() != 0)
- {
- LinkedList<MBeanAttributeInfo> tmpList = new LinkedList<MBeanAttributeInfo>();
-
- for (MBeanAttributeInfo attribute : allAttribs)
- {
- if (_attribNames.contains(attribute.getName()))
- {
- tmpList.add(attribute);
- }
- }
-
- _attribInfo = tmpList.toArray(new MBeanAttributeInfo[tmpList.size()]);
- }
- else
- {
- _attribInfo = allAttribs;
- }
- }
- return _attribInfo;
- }
-
- private static void processCommandLine(String arg)
- {
- if (arg.startsWith(QUEUE_ARGS))
- {
- String[] queues = arg.substring(arg.indexOf("=") + 1).split(",");
-
- _queueNames = new HashSet<String>();
-
- for (String queue : queues)
- {
- if (queue.length() > 0)
- {
- _queueNames.add(queue);
- }
- }
-
- if (_queueNames.size() == 0)
- {
- System.out.println("No Queues specified on queue argument: '" + arg + "'");
- System.exit(1);
- }
-
- }
- else if (arg.startsWith(ATTRIB_ARGS))
- {
- String[] attribs = arg.substring(arg.indexOf("=") + 1).split(",");
-
- _attribNames = new HashSet<String>();
-
- for (String attrib : attribs)
- {
- if (attrib.length() > 0)
- {
- _attribNames.add(attrib);
- }
- }
-
- if (_attribNames.size() == 0)
- {
- System.out.println("No Attributes specified on attribute argument: '" + arg + "'");
- System.exit(1);
- }
- }
- else
- {
- System.out.println("Unknown argument '" + arg + "'");
- System.exit(1);
- }
-
- }
-
- private static void getDetails(boolean printRates) throws Exception
- {
- for (ObjectName object : getMatchingObjects())
- {
- try
- {
-
- // There should normally be only one but allow queue Names such as tmp_*
- // Line format is
- // <time> <attributes value>, [<attribute value, ]* <consumption rate> <buildup rate>
-
- String name = object.getKeyProperty("name");
-
- Date todaysDate = new java.util.Date();
-
- System.out.print(_formatter.format(todaysDate));
-
- MBeanAttributeInfo[] attributeList = getAttributeList(object);
-
- for (int i = 0; attributeList.length > i; i++)
- {
- System.out.print(", " + _mbsc.getAttribute(object, attributeList[i].getName()));
- }
-
- // Output consumption rate calc
- if (printRates)
- {
- double timeDelta = (System.currentTimeMillis() - _previousTimePoint) / 1000.0f;
-
- long rmc2 = (Long) _mbsc.getAttribute(object, "ReceivedMessageCount");
- long mc2 = (Integer) _mbsc.getAttribute(object, "MessageCount");
-
- long rmc1 = 0l;
- if (_previousRMC.get(name) != null)
- {
- rmc1 = _previousRMC.get(name);
- }
- long mc1 = 0l;
- if (_previousMC.get(name) != null)
- {
- mc1 = _previousMC.get(name);
- }
-
- // If we don't have a previous value then ensure we print 0
- if (rmc1 == 0)
- {
- rmc1 = rmc2;
- }
-
- double consumptionRate = ((rmc2 - rmc1) - (mc2 - mc1)) / timeDelta;
- System.out.print(", ");
-
- System.out.print(String.format("%.2f", consumptionRate));
-
- System.out.print(", ");
- double buildupRate = (mc2 - mc1) / timeDelta;
- System.out.print(String.format("%.2f", buildupRate));
-
- _previousRMC.put(name, rmc2);
- _previousMC.put(name, mc2);
- }
- }
- catch (InstanceNotFoundException e)
- {
- System.out.print(" ..queue has been removed.");
- }
- catch (Exception e)
- {
- System.out.print(" ..error :" + e.getMessage());
- }
- finally
- {
- System.out.print("\n");
- }
-
- }// for ObjectName
- }
-
- private static JMXConnector getJMXConnection(String host, int port, String username, String password) throws IOException
- {
- //Open JMX connection
- JMXServiceURL jmxUrl = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + host + ":" + port + "/jmxrmi");
- Map<String, Object> env = new HashMap<String, Object>();
- env.put(JMXConnector.CREDENTIALS, new String[]{username, password});
- JMXConnector con = JMXConnectorFactory.connect(jmxUrl, env);
- return con;
- }
-
- public static ObjectName[] getMatchingObjects() throws IOException, MalformedObjectNameException
- {
-
- // Gets all Queues names
- if (_queueNames == null)
- {
- _queueNames = new HashSet<String>();
- _queueNames.add("*");
- }
-
- Set<ObjectName> requestedObjects = new HashSet<ObjectName>();
-
- for (String queue : _queueNames)
- {
- Set<ObjectName> matchingObjects = _mbsc.queryNames(new ObjectName("org.apache.qpid:type=VirtualHost.Queue,VirtualHost=" + _vhost + ",name=" + queue + ",*"), null);
-
- if (!matchingObjects.isEmpty())
- {
- requestedObjects.addAll(matchingObjects);
- }
- }
-
- return requestedObjects.toArray(new ObjectName[requestedObjects.size()]);
- }
-}
-
diff --git a/java/maven-settings.xml b/java/maven-settings.xml
deleted file mode 100644
index 985f39b6f1..0000000000
--- a/java/maven-settings.xml
+++ /dev/null
@@ -1,2 +0,0 @@
-<settings>
-</settings>
diff --git a/java/module.xml b/java/module.xml
deleted file mode 100644
index 8c6a05e035..0000000000
--- a/java/module.xml
+++ /dev/null
@@ -1,909 +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.
- -
- -->
-<project name="module" xmlns:artifact="antlib:org.apache.maven.artifact.ant">
-
- <import file="common.xml"/>
-
- <path id="maven-ant-tasks.classpath" path="${project.root}/lib/maven-ant-tasks-2.1.1.jar" />
- <typedef resource="org/apache/maven/artifact/ant/antlib.xml"
- uri="antlib:org.apache.maven.artifact.ant"
- classpathref="maven-ant-tasks.classpath" />
-
- <map property="module" value="${basedir}" split="${path.separator}">
- <globmapper from="${project.root}${file.separator}*" to="*"/>
- </map>
-
- <map property="module.name" value="${module}">
- <filtermapper>
- <replacestring from="${file.separator}" to="-"/>
- </filtermapper>
- </map>
-
- <echo message="Running ant for module : ${module}" level="info"/>
-
- <property file="${project.root}/build.deps"/>
-
- <property name="module.build" location="${build.scratch}/${module}"/>
- <property name="module.classes" location="${module.build}/classes"/>
- <property name="module.instrumented" location="${module.build}/classes-instrumented"/>
- <property name="module.precompiled" location="${module.build}/src"/>
- <property name="module.api" location="${build.api}/${module}/"/>
- <property name="module.test.api" location="${build.test.api}/${module}"/>
- <property name="module.test.classes" location="${module.build}/test/classes"/>
- <property name="module.results" location="${build.results}/${module}"/>
- <property name="module.failed" location="${module.results}/FAILED"/>
- <property name="module.src" location="src/main/java"/>
- <property name="module.test.src" location="src/test/java"/>
- <property name="module.bin" location="bin"/>
- <property name="module.etc" location="etc"/>
-
- <property name="module.namever" value="${project.name}-${module.name}-${project.version}"/>
- <property name="module.namever.osgi" value="${project.name}-${module.name}_${project.version}.0.osgi"/>
- <property name="module.release.base" value="${basedir}/release"/>
- <property name="module.release" value="${module.release.base}/${module.namever}"/>
- <property name="module.release.lib" value="${module.release}/lib"/>
- <property name="module.release.zip" location="${module.release.base}/${module.namever}.zip"/>
- <property name="module.release.tar" location="${module.release.base}/${module.namever}.tar"/>
- <property name="module.release.tgz" location="${module.release.base}/${module.namever}.tar.gz"/>
- <property name="module.release.bz2" location="${module.release}/${module.namever}.tar.bz2"/>
-
- <property name="module.genpom.args" value=""/>
- <property name="maven.remote.repo" value="file://${module.release.base}/maven"/>
-
- <property name="broker.log.prefix" value="BROKER: "/>
- <property name="broker.log.interleave" value="true"/>
-
- <property name="module.qpid.jar" location="${module.release.lib}/qpid-all.jar"/>
- <basename property="qpid.jar.name" file="${module.qpid.jar}"/>
-
- <property name="module.coverage" location="${module.build}/coverage"/>
- <property name="cobertura.datafile" location="${module.instrumented}/cobetura.ser"/>
-
-
- <available property="module.test.src.exists" file="${module.test.src}"/>
- <available property="module.etc.exists" file="${module.etc}"/>
- <available property="module.bin.exists" file="${module.bin}"/>
-
- <property name="module.source.jar"
- location="${build.lib}/${project.name}-${module.name}-${project.version}-sources.jar"/>
-
- <!-- module.depends and module.test.depends are supplied by the importing file -->
- <property name="module.depends" value=""/>
- <property name="module.test.depends" value=""/>
- <property name="module.test.excludes" value=""/>
-
- <map property="module.depends.path" value="${module.depends}" join="${path.separator}">
- <globmapper from="*" to="${build.scratch}/*/classes"/>
- </map>
-
- <map property="module.test.depends.path" value="${module.test.depends}" join="${path.separator}">
- <globmapper from="*" to="${build.scratch}/*/classes"/>
- </map>
-
-
- <!-- Add depenencies dependencies to path -->
- <map property="module.depends.libs" value="${module.depends}" join=" ">
- <chainedmapper>
- <filtermapper>
- <replacestring from="${file.separator}" to="-"/>
- </filtermapper>
- <propertymapper from="*" to="*.libs"/>
- </chainedmapper>
- </map>
- <condition property="module.depends.libs.includes" value="__EMPTY__" else="${module.depends.libs}">
- <equals trim="true" arg1="${module.depends.libs}" arg2=""/>
- </condition>
-
-
- <!-- Add depenencies test dependencies to path -->
- <map property="module.test.depends.libs" value="${module.test.depends}" join=" ">
- <chainedmapper>
- <filtermapper>
- <replacestring from="${file.separator}" to="-"/>
- </filtermapper>
- <propertymapper from="*" to="*.libs"/>
- </chainedmapper>
- </map>
- <condition property="module.test.depends.libs.includes" value="__EMPTY__" else="${module.test.depends.libs}">
- <equals trim="true" arg1="${module.test.depends.libs}" arg2=""/>
- </condition>
-
-
- <indirect name="module.libs" variable="${module.name}.libs"/>
- <condition property="module.libs.includes" value="__EMPTY__" else="${module.libs}">
- <equals trim="true" arg1="${module.libs}" arg2=""/>
- </condition>
-
- <indirect name="module.test.libs" variable="${module.name}.test.libs"/>
- <condition property="module.test.libs.includes" value="__EMPTY__" else="${module.test.libs}">
- <equals trim="true" arg1="${module.test.libs}" arg2=""/>
- </condition>
-
- <path id="module.libs">
- <fileset dir="${project.root}" includes="${module.libs.includes}"/>
- <fileset dir="${project.root}" includes="${module.depends.libs.includes}"/>
- </path>
-
- <path id="module.test.libs">
- <fileset dir="${project.root}" includes="${module.test.libs.includes}"/>
- <fileset dir="${project.root}" includes="${module.test.depends.libs.includes}"/>
- </path>
-
- <path id="module.src.path">
- <pathelement location="${module.src}"/>
- <pathelement location="${module.precompiled}"/>
- </path>
-
- <path id="module.test.src.path">
- <pathelement location="${module.test.src}"/>
- </path>
-
- <condition property="module.jar"
- value="${build.plugins}/${project.name}-${module.name}-${project.version}.jar"
- else="${build.lib}/${project.name}-${module.name}-${project.version}.jar">
- <and>
- <isset property="module.plugin"/>
- <istrue value="${module.plugin}"/>
- </and>
- </condition>
-
- <property name="module.test.jar"
- location="${build.lib}/${project.name}-${module.name}-tests-${project.version}.jar"/>
-
- <path id="module.class.path">
- <pathelement location="${module.classes}"/>
- <pathelement path="${module.depends.path}"/>
- <path refid="module.libs"/>
- </path>
-
- <path id="module.test.path">
- <pathelement path="${module.test.classes}"/>
- <path refid="module.class.path"/>
- <pathelement path="${module.test.depends.path}"/>
- <path refid="module.test.libs"/>
- </path>
-
- <property name="javac.deprecation" value="off"/>
-
- <target name="debug">
- <echo-prop name="basedir"/>
- <echo-prop name="project.root"/>
- <echo-prop name="module"/>
- <echo-prop name="module.libs"/>
- <echo-prop name="module.test.libs"/>
- <echo-prop name="module.name"/>
- <echo-prop name="module.jar"/>
- <echo-prop name="module.depends"/>
- <echo-prop name="module.depends.path"/>
- <echo-prop name="module.test.depends"/>
- <echo-prop name="module.test.depends.path"/>
- <echo-prop name="module.depends.libs"/>
- <echo-prop name="module.test.depends.libs"/>
- <echo-path refid="module.src.path"/>
- <echo-path refid="module.class.path"/>
- <echo-path refid="module.test.path"/>
- </target>
-
- <target name="prepare">
- <mkdir dir="${build.bin}"/>
- <mkdir dir="${build.etc}"/>
- <mkdir dir="${build.lib}"/>
- <mkdir dir="${build.results}"/>
- <mkdir dir="${build.data}"/>
- <mkdir dir="${build.plugins}"/>
- <mkdir dir="${module.classes}"/>
- <mkdir dir="${module.precompiled}"/>
- <mkdir dir="${module.api}"/>
- <mkdir dir="${module.test.api}"/>
- <mkdir dir="${module.test.classes}"/>
- <mkdir dir="${module.results}"/>
- </target>
-
- <target name="pom" depends="prepare" if="module.genpom">
- <jython path="${mllib.dir}">
- <args>
- <arg line='"${project.root}/genpom"'/>
- <arg line='-s "${project.root}/lib/poms"'/>
- <arg line='-o "${build.scratch}/qpid-${module.name}.pom"'/>
- <arg line="-u ${project.url}"/>
- <arg line="-g ${project.groupid}"/>
- <arg line="-v ${project.version}${maven.version.suffix}"/>
- <arg line="-p qpid"/>
- <arg line='-m "${module.depends}"'/>
- <arg line="-a ${module.name}"/>
- <arg line="${module.genpom.args}"/>
- <arg line="${module.libs}"/>
- </args>
- </jython>
- </target>
-
- <target name="release-mvn" depends="pom" if="module.genpom" description="Install the artifacts into the local repository and prepare the release">
- <antcall target="build"/>
-
- <artifact:pom id="module.pom" file="${build.scratch}/qpid-${module.name}.pom"/>
-
- <artifact:install file="${module.jar}" pomRefId="module.pom" settingsFile="${maven.settings.xml}">
- <localRepository path="${maven.local.repo}"/>
- </artifact:install>
-
- <artifact:deploy file="${module.jar}" pomRefId="module.pom" uniqueVersion="${maven.unique.version}" settingsFile="${maven.settings.xml}">
- <attach file="${module.source.jar}" classifier="sources"/>
- <localRepository path="${maven.local.repo}"/>
- <remoteRepository url="${maven.remote.repo}"/>
- </artifact:deploy>
- </target>
-
- <target name="precompile"/>
-
- <target name="compile" depends="prepare,precompile" description="compile sources">
-
- <echo message="Targeting : ${java.target}" level="info"/>
-
- <javac source="${java.source}" target="${java.target}"
- destdir="${module.classes}" debug="on" debuglevel="lines,vars,source" includeantruntime="false"
- deprecation="${javac.deprecation}">
- <compilerarg line="${javac.compiler.args}"/>
- <src refid="module.src.path"/>
- <classpath refid="module.class.path"/>
- </javac>
-
- <!-- copy any non java src files into the build tree, e.g. log4j.properties -->
- <copy todir="${module.classes}" verbose="true">
- <fileset dir="${module.src}">
- <exclude name="**/*.java"/>
- <exclude name="**/package.html"/>
- </fileset>
- </copy>
- </target>
-
- <target name="precompile-tests" if="module.test.src.exists"/>
-
- <target name="compile-tests" depends="compile,precompile-tests" if="module.test.src.exists"
- description="compilte unit tests">
- <javac target="${java.target}" source="${java.source}"
- destdir="${module.test.classes}" debug="on"
- deprecation="${javac.deprecation}"
- srcdir="${module.test.src}">
- <classpath refid="module.test.path"/>
- </javac>
-
- <!-- copy any non java src files into the build tree, e.g. log4j.properties -->
- <copy todir="${module.test.classes}" verbose="true">
- <fileset dir="${module.test.src}">
- <exclude name="**/*.java"/>
- <exclude name="**/package.html"/>
- </fileset>
- </copy>
- </target>
-
-
- <property name="profile" value="default"/>
- <property name="testprofile.file" value="${test.profiles}/${profile}.testprofile"/>
-
- <available file="${testprofile.file}" property="testprofile.file.present"/>
- <fail unless="testprofile.file.present" message="The requested test profile was not found: ${testprofile.file}"/>
-
- <property file="${testprofile.file}" prefix="preload"/>
- <property name="preload.include" value=""/>
- <condition property="profiles"
- value="${preload.include} ${profile}"
- else="default ${preload.include} ${profile}">
- <equals arg1="${profile}" arg2="default"/>
- </condition>
- <map property="_profile_files" value="${profiles}" join=" ">
- <globmapper from="*" to="*.testprofile"/>
- </map>
- <concat destfile="${build.scratch}/test-${profile}.properties" force="no" fixlastline="yes">
- <filelist dir="${test.profiles}" files="${_profile_files}"/>
- </concat>
- <property file="${build.scratch}/test-${profile}.properties"/>
-
- <map property="test.excludefiles" value="${test.excludes}">
- <globmapper from="*" to="${test.profiles}/*"/>
- </map>
-
-
- <condition property="dontruntest" value="dontruntest" else="runtest">
- <contains substring="${module.name}" string="${exclude.modules}" />
- </condition>
-
- <property name="jvm.args" value=""/>
- <property name="broker.existing.qpid.work" value=""/>
-
- <target name="test" depends="build,compile-tests" if="module.test.src.exists"
- unless="${dontruntest}" description="execute unit tests">
-
- <delete file="${module.failed}"/>
-
- <echo message="Using profile:${profile}" level="info"/>
- <junit fork="yes" forkmode="once" maxmemory="${test.mem}" reloading="no"
- haltonfailure="${haltonfailure}" haltonerror="${haltonerror}"
- failureproperty="test.failures" printsummary="on" timeout="6000000" >
-
- <jvmarg line="${jvm.args}" />
-
- <sysproperty key="amqj.logging.level" value="${amqj.logging.level}"/>
- <sysproperty key="amqj.server.logging.level" value="${amqj.server.logging.level}"/>
- <sysproperty key="amqj.protocol.logging.level" value="${amqj.protocol.logging.level}"/>
- <sysproperty key="log4j.debug" value="${log4j.debug}"/>
- <sysproperty key="root.logging.level" value="${root.logging.level}"/>
- <sysproperty key="log4j.configuration" value="${log4j.configuration}"/>
- <sysproperty key="java.naming.factory.initial" value="${java.naming.factory.initial}"/>
- <sysproperty key="java.naming.provider.url" value="${java.naming.provider.url}"/>
- <sysproperty key="broker" value="${broker}"/>
- <sysproperty key="broker.clean" value="${broker.clean}"/>
- <sysproperty key="broker.clean.between.tests" value="${broker.clean.between.tests}"/>
- <sysproperty key="broker.existing.qpid.work" value="${broker.existing.qpid.work}"/>
- <sysproperty key="broker.persistent" value="${broker.persistent}"/>
- <sysproperty key="broker.version" value="${broker.version}"/>
- <sysproperty key="broker.ready" value="${broker.ready}" />
- <sysproperty key="broker.stopped" value="${broker.stopped}" />
- <sysproperty key="broker.config" value="${broker.config}" />
- <sysproperty key="messagestore.class.name" value="${messagestore.class.name}" />
- <sysproperty key="test.output" value="${module.results}"/>
- <sysproperty key="qpid.amqp.version" value="${qpid.amqp.version}"/>
-
- <syspropertyset>
- <propertyref prefix="test"/>
- </syspropertyset>
- <syspropertyset>
- <propertyref prefix="profile"/>
- </syspropertyset>
- <syspropertyset>
- <propertyref prefix="javax.net.ssl"/>
- </syspropertyset>
- <syspropertyset>
- <propertyref prefix="broker"/>
- </syspropertyset>
-
- <sysproperty key="max_prefetch" value ="${max_prefetch}"/>
- <sysproperty key="qpid.dest_syntax" value ="${qpid.dest_syntax}"/>
-
- <sysproperty key="example.plugin.target" value="${project.root}/build/lib/plugins"/>
- <sysproperty key="QPID_EXAMPLE_HOME" value="${qpid.home}"/>
- <sysproperty key="QPID_HOME" value="${qpid.home}"/>
- <sysproperty key="QPID_WORK" value="${qpid.work}"/>
-
- <formatter type="plain"/>
- <formatter type="xml"/>
-
- <classpath refid="module.test.path"/>
-
- <batchtest todir="${module.results}">
- <fileset dir="${module.test.src}" excludes="${module.test.excludes}">
- <include name="**/${test}.java"/>
- </fileset>
- </batchtest>
- </junit>
-
- <antcall target="touch-failed"/>
-
- <condition property="failed">
- <and>
- <isfalse value="${test.failures.ignore}"/>
- <available file="${module.failed}"/>
- </and>
- </condition>
-
- <fail if="failed" message="TEST SUITE FAILED"/>
-
- </target>
-
- <target name="report-module" description="generate junit reports for each module">
- <junitreport todir="${module.results}">
- <fileset dir="${module.results}">
- <include name="TEST-*.xml"/>
- </fileset>
- <report format="frames" todir="${module.results}/report/html"/>
- </junitreport>
- </target>
-
- <target name="touch-failed" if="test.failures">
- <touch file="${module.failed}"/>
- <touch file="${build.failed}"/>
- </target>
-
- <target name="copy-bin" if="module.bin.exists" description="copy bin directory if it exists to build tree">
- <copy todir="${build.bin}" failonerror="false">
- <fileset dir="${module.bin}"/>
- </copy>
- <chmod dir="${build.bin}" perm="ugo+rx" includes="**/*"/>
- </target>
-
- <target name="copy-bin-release" if="module.bin.exists" description="copy dependencies into module release">
- <copy todir="${module.release}/bin" failonerror="true">
- <fileset dir="${module.bin}" />
- </copy>
- <chmod dir="${module.release}/bin" perm="ugo+rx" includes="**/*"/>
- </target>
-
- <target name="copy-etc" if="module.etc.exists" description="copy etc directory if it exists to build tree">
- <copy todir="${build.etc}" failonerror="false">
- <fileset dir="${module.etc}"/>
- </copy>
- </target>
-
- <target name="copy-etc-release" if="module.etc.exists" description="copy etc directory if it exists to build tree">
- <copy todir="${module.release}/etc" failonerror="false" flatten="true">
- <fileset dir="${module.etc}"/>
- </copy>
- </target>
-
- <target name="postbuild" description="run after a build"/>
-
- <target name="build" depends="jar,jar-tests,jar-sources,libs,copy-bin,copy-etc,postbuild" description="compile and copy resources into build tree"/>
- <target name="jar.manifest" depends="compile" if="module.manifest">
- <jar destfile="${module.jar}" basedir="${module.classes}" manifest="${module.manifest}"/>
- </target>
-
- <target name="jar.nomanifest" depends="compile" unless="module.manifest">
- <jar destfile="${module.jar}" basedir="${module.classes}">
- <metainf dir="${project.root}/resources/" />
- </jar>
- </target>
-
- <target name="jar" depends="jar.manifest,jar.nomanifest" description="create jar"/>
-
- <target name="jar-tests" depends="compile-tests" description="create unit test jar">
- <jar destfile="${module.test.jar}" basedir="${module.test.classes}"/>
- </target>
-
- <target name="jar-sources" depends="prepare" description="create sources jar">
- <jar destfile="${module.source.jar}">
- <fileset dir="${project.root}/resources">
- <include name="LICENSE"/>
- <include name="NOTICE"/>
- </fileset>
- <fileset dir="${module.src}" includes="**/*.java"/>
- <fileset dir="${module.precompiled}" includes="**/*.java"/>
- </jar>
- </target>
-
- <target name="libs" description="copy dependencies into build tree">
- <copylist todir="${build.lib}" dir="${project.root}" files="${module.libs}"/>
- </target>
-
- <map property="module.depends.jars" value="${module.depends}" join=",">
- <globmapper from="*" to="${project.name}-*-${project.version}.jar"/>
- <filtermapper>
- <replacestring from="/" to="-"/>
- </filtermapper>
- </map>
-
-
- <target name="libs-release" description="copy dependencies into module release">
- <!-- Copy the module dependencies -->
- <echo message="${module.libs}"/>
- <copylist todir="${module.release}/lib" dir="${project.root}" files="${module.libs}"/>
- <copylist todir="${module.release}/lib" dir="${project.root}" files="${module.depends.libs}"/>
-
- <!-- Copy the jar for this module -->
- <copy todir="${module.release}/lib" failonerror="true">
- <fileset file="${module.jar}"/>
- <fileset dir="${build.lib}" includes="${module.depends.jars}"/>
- </copy>
- </target>
-
- <target name="resources" description="copy resources into build tree">
- <copy todir="${build}" failonerror="false" flatten="true">
- <fileset dir="${basedir}${file.separator}.." includes="${resources}"/>
- </copy>
- </target>
-
- <target name="resources-release" description="copy resources into module release">
- <copy todir="${module.release}" failonerror="false" flatten="true">
- <fileset dir="${resources}" excludes="META-INF"/>
- </copy>
- </target>
-
- <uptodate property="doc.done" targetfile="${module.api}/index.html">
- <srcfiles dir="${module.src}" includes="**/*.java"/>
- </uptodate>
-
- <property name="module.doc.access" value="package"/>
- <target name="doc" depends="prepare" unless="doc.done" description="generate api-doc">
- <javadoc access="${module.doc.access}" destdir="${module.api}" author="false" version="true" use="true"
- windowtitle="${project.name} - ${module.name} - API Documentation"
- sourcepathref="module.src.path" classpathref="module.class.path" packagenames="*">
- <arg value="-J-Dhttp.proxyHost=${http.proxyHost}"/>
- <arg value="-J-Dhttp.proxyPort=${http.proxyPort}"/>
- <bottom><![CDATA[<em><a href="http://www.apache.org/licenses/LICENSE-2.0">Licensed to the Apache Software Foundation</a></em>]]></bottom>
- <link href="http://java.sun.com/j2se/1.5.0/docs/api/"/>
- <link href="http://download.oracle.com/docs/cd/E17477_01/javaee/5/api/"/>
- <link href="http://commons.apache.org/configuration/apidocs/"/>
- <tag name="todo" scope="all" description="Todo:" />
- </javadoc>
- </target>
-
- <uptodate property="test-doc.done" targetfile="${module.test.api}/index.html">
- <srcfiles dir="${module.test.src}" includes="**/*.java"/>
- </uptodate>
-
- <property name="module.test.doc.access" value="public"/>
- <target name="test-doc" depends="prepare" unless="testdoc.done" if="module.test.src.exists" description="generate test api-doc">
- <javadoc access="${module.test.doc.access}" destdir="${module.test.api}" author="false" version="true" use="true"
- windowtitle="${project.name} - ${module.name} - Test API Documentation"
- sourcepathref="module.test.src.path" classpathref="module.test.path" packagenames="*">
- <arg value="-J-Dhttp.proxyHost=${http.proxyHost}"/>
- <arg value="-J-Dhttp.proxyPort=${http.proxyPort}"/>
- <bottom><![CDATA[<em><a href="http://www.apache.org/licenses/LICENSE-2.0">Licensed to the Apache Software Foundation</a></em>]]></bottom>
- <link href="http://java.sun.com/j2se/1.5.0/docs/api/"/>
- <link href="http://download.oracle.com/docs/cd/E17477_01/javaee/5/api/"/>
- <link href="http://commons.apache.org/configuration/apidocs/"/>
- <tag name="todo" scope="all" description="Todo:" />
- </javadoc>
- </target>
-
- <target name="release-bin-prepare">
- <mkdir dir="${module.release}"/>
- <available property="module.release.exists" file="${module.release}"/>
- </target>
-
- <target name="check-module-manifest">
- <uptodate property="module-manifest.done" targetfile="${qpid.jar}">
- <srcfiles dir="${build.lib}" includes="**/*.jar" excludes="**/${qpid.jar.name}"/>
- </uptodate>
- </target>
-
- <target name="module-manifest" depends="check-module-manifest" unless="module-manifest.done">
- <path id="class.path">
- <fileset dir="${module.release.lib}" >
- <include name="*.jar"/>
- <exclude name="${qpid.jar.name}"/>
- </fileset>
- </path>
- <pathconvert property="qpid.jar.classpath" pathsep=" " dirsep="/">
- <path refid="class.path"/>
- <globmapper from="${module.release.lib}${file.separator}*" to="*"/>
- </pathconvert>
-
- <jar destfile="${module.qpid.jar}">
- <manifest>
- <attribute name="Class-Path" value="${qpid.jar.classpath}"/>
- </manifest>
- <metainf dir="${project.root}/resources/"/>
- </jar>
-
- <touch file="${module.qpid.jar}"/>
- </target>
-
-
- <target name="zip-release" depends="build-release-bin" description="build module release archive">
- <zip destfile="${module.release.zip}">
- <zipfileset dir="${module.release}" prefix="${module.namever}" filemode="755">
- <include name="bin/*"/>
- <exclude name="bin/*.txt"/>
- </zipfileset>
-
- <zipfileset dir="${module.release}" prefix="${module.namever}" filemode="644">
- <include name="bin/*.txt"/>
- </zipfileset>
-
- <zipfileset dir="${module.release}" prefix="${module.namever}" excludes="${module.release.excludes}" filemode="644" dirmode="755">
- <exclude name="bin/**"/>
- <exclude name="**/*.class"/>
- </zipfileset>
- </zip>
- </target>
-
- <target name="bundle" description="Build module osgi artifact. Override and depend on bundle-tasks to use"/>
-
- <target name="bundle-tasks" depends="jar">
- <taskdef resource="aQute/bnd/ant/taskdef.properties" classpath="${project.root}/lib/bnd-0.0.384.jar"/>
- <echo message="Bundling ${build}/lib/${module.namever}.jar with ${module.src}/${module.name}.bnd"/>
- <bnd
- classpath="${build}/lib/${module.namever}.jar"
- eclipse="false"
- failok="false"
- exceptions="true"
- output="${build}/lib/${module.namever.osgi}.jar"
- files="${module.src}/${module.name}.bnd"/>
- </target>
-
- <target name="tar-release" depends="zip-release" description="build release archive">
- <tar destfile="${module.release.tar}" longfile="gnu" >
- <zipfileset src="${module.release.zip}"/>
- </tar>
- </target>
-
- <target name="gzip-release" depends="tar-release" description="build release archive">
- <gzip src="${module.release.tar}" destfile="${module.release.tgz}"/>
- </target>
-
- <target name="bzip2-release" depends="tar-release" description="build release archive">
- <bzip2 src="${module.release.tar}" destfile="${module.release.bz2}"/>
- </target>
-
- <target name="doc-release" description="no-op override if a doc step is requried "/>
-
-
- <target name="build-release-bin" depends="release-bin-prepare,libs-release,copy-bin-release,
- copy-etc-release,doc-release,resources-release,release-bin-other,module-manifest"
- description="Task that includes all tasks required to create a module binary release"/>
-
- <!-- ,zip-release,gzip-release -->
- <target name="release-bin-tasks" depends="gzip-release" description="build all release archives except .bz2"/>
-
- <target name="release-bin-all-tasks" depends="bzip2-release" description="build all release archives"/>
-
- <!-- Dummy targets to no-op for most modules. Override if a module package is required -->
- <target name="release-bin-other" description="Override if there is tasks required for the module bin release to occur last"/>
- <target name="release-bin" description="Override and depend on release-bin-tasks to generate"/>
- <target name="release-bin-all" description="Override and depend on release-bin-tasks to generate"/>
-
- <target name="clean" description="remove build artifacts">
- <delete dir="${module.build}"/>
- <delete dir="${module.results}"/>
- <delete dir="${module.release.base}"/>
- <delete dir="${module.instrumented}"/>
- </target>
-
- <target name="instrument" depends="cobertura-init">
- <cobertura-instrument todir="${module.instrumented}"
- datafile="${cobertura.datafile}">
- <fileset dir="${module.classes}">
- <include name="**/*.class"/>
- </fileset>
- </cobertura-instrument>
- </target>
-
- <target name="cover-test" depends="instrument">
-
- <mkdir dir="${build.coveragereport}" />
- <junit fork="yes" forkmode="once" maxmemory="${test.mem}" reloading="no"
- haltonfailure="${haltonfailure}" haltonerror="${haltonerror}"
- failureproperty="test.failures" printsummary="on" timeout="600000" >
-
- <sysproperty key="amqj.logging.level" value="${amqj.logging.level}"/>
- <sysproperty key="amqj.protocol.logging.level" value="${amqj.protocol.logging.level}"/>
- <sysproperty key="log4j.debug" value="${log4j.debug}"/>
- <sysproperty key="root.logging.level" value="${root.logging.level}"/>
- <sysproperty key="log4j.configuration" value="${log4j.configuration}"/>
- <sysproperty key="java.naming.factory.initial" value="${java.naming.factory.initial}"/>
- <sysproperty key="java.naming.provider.url" value="${java.naming.provider.url}"/>
- <sysproperty key="broker" value="${broker}"/>
- <sysproperty key="broker.clean" value="${broker.clean}"/>
- <sysproperty key="broker.version" value="${broker.version}"/>
- <sysproperty key="broker.ready" value="${broker.ready}" />
- <sysproperty key="test.output" value="${module.results}"/>
-
- <syspropertyset>
- <propertyref prefix="test"/>
- </syspropertyset>
- <syspropertyset>
- <propertyref prefix="broker"/>
- </syspropertyset>
-
- <sysproperty key="max_prefetch" value ="${max_prefetch}"/>
- <sysproperty key="example.plugin.target" value="${project.root}/build/lib/plugins"/>
- <sysproperty key="QPID_EXAMPLE_HOME" value="${project.root}/build"/>
- <sysproperty key="QPID_HOME" value="${project.root}/build"/>
-
- <sysproperty key="net.sourceforge.cobertura.datafile"
- file="${cobertura.datafile}" />
-
- <formatter type="plain"/>
- <formatter type="xml"/>
-
- <classpath path="${module.instrumented}"/>
- <classpath>
- <fileset dir="${build}">
- <include name="**/classes-instrumented/*.class"/>
- </fileset>
- </classpath>
- <classpath refid="module.test.path"/>
- <classpath refid="cobertura.classpath"/>
-
- <batchtest todir="${module.results}">
- <fileset dir="${module.test.src}" excludes="${module.test.excludes}">
- <include name="**/${test}.java"/>
- </fileset>
- </batchtest>
- </junit>
- </target>
-
- <target name="coverage-report" depends="cobertura-init">
- <echo message="${cobertura.datafile}"/>
- <cobertura-report format="html"
- destdir="${module.coverage}"
- datafile="${cobertura.datafile}">
- <fileset dir="${module.src}" includes="**/*.java" />
- </cobertura-report>
- </target>
-
- <property name="version.file" location="${module.classes}/qpidversion.properties"/>
- <property file="${version.file}" prefix="old."/>
-
- <target name="check-version">
- <exec executable="svnversion" spawn="false" failifexecutionfails="false"
- dir="${project.root}" outputproperty="svnversion.output">
- <arg line="."/>
- </exec>
- <condition property="version.stale">
- <not>
- <equals arg1="${svnversion.output}" arg2="${old.qpid.svnversion}"/>
- </not>
- </condition>
- </target>
-
- <target name="create-version" depends="check-version" if="version.stale">
- <!-- Write the version.properties out.-->
- <!-- Echos exactly as shown, so leave no spaces before/after lines -->
- <echo file="${version.file}" append="false">qpid.version=${project.version}
-qpid.svnversion=${svnversion.output}
-qpid.name=${project.name}
-</echo>
- </target>
-
- <!-- Additions to perform LogMessage generation
- To activate for your plugin add the following to your plugin build.xml
-
- <target name="precompile" depends="gen_logging"/>
-
- -->
-
- <property name="gentools.home" location="${project.root}/../gentools" />
- <property name="generated.dir" location="${module.precompiled}" />
- <property name="velocity.compile.dir" value="${build.scratch}/broker/velocity"/>
- <property name="velocity.timestamp" location="${generated.dir}/velocity.timestamp" />
-
- <target name="compile_velocity" >
- <mkdir dir="${velocity.compile.dir}" />
- <!-- Compile LogMessages Velocity Generator -->
- <javac source="${java.source}" target="${java.target}"
- destdir="${velocity.compile.dir}" debug="on" includeantruntime="false"
- deprecation="${javac.deprecation}"
- srcdir="${project.root}/broker/src/velocity/java" >
- <classpath>
- <pathelement path="${gentools.home}/lib/velocity-1.4.jar" />
- </classpath>
- <compilerarg line="${javac.compiler.args}"/>
- </javac>
- </target>
-
-
- <target name="check_velocity_deps">
- <uptodate property="velocity.notRequired" targetfile="${velocity.timestamp}">
- <srcfiles dir="${module.src}" includes="**/*_logmessages.properties" />
- <srcfiles dir="${project.root}/broker/src/velocity/" includes="**/*.java **/*.vm" />
- </uptodate>
- </target>
-
-
- <target name="gen_logging" depends="compile_velocity,check_velocity_deps" unless="velocity.notRequired">
- <mkdir dir="${generated.dir}"/>
-
- <path id="logmessages.path">
- <fileset dir="${module.src}">
- <include name="**/*_logmessages.properties"/>
- </fileset>
- </path>
-
- <pathconvert property="logmessages"
- refid="logmessages.path"
- pathsep="' '"/>
-
- <echo message="logmessages is ${logmessages}"/>
-
- <java classname="org.apache.qpid.server.logging.GenerateLogMessages" fork="true" dir="${gentools.home}/src" failonerror="true">
- <arg line="'${logmessages}'"/>
- <arg value="-j"/>
- <arg value="-o"/>
- <arg value="${generated.dir}"/>
- <arg value="-t"/>
- <arg value="${project.root}/broker/src/velocity/templates/org/apache/qpid/server/logging/messages"/>
- <arg value="-s"/>
- <arg value="${module.src}"/>
-
-
- <classpath>
- <pathelement path="${module.src}"/>
- <pathelement path="${velocity.compile.dir}" />
- <fileset dir="${project.root}/lib">
- <include name="**/*.jar"/>
- </fileset>
- <pathelement path="${gentools.home}/lib/velocity-1.4.jar" />
- </classpath>
- </java>
- <touch file="${velocity.timestamp}" />
- </target>
-
- <target name="eclipse" depends="eclipse-setup,eclipse-project,eclipse-source-only,eclipse-source-and-test"/>
-
- <target name="eclipse-setup">
- <taskdef name="eclipse" classname="prantl.ant.eclipse.EclipseTask" />
-
- <!-- Build set of directories representing the dependencies -->
-
- <dirset id="eclipse.required.projectdirs.path" dir="${project.root}" includes="${module.depends} ${module.test.depends} neverBeEmpty">
- <!-- Select only those projects from module.depends that contain a build.xml. This serves to exclude dependencies that
- don't become Eclipse projects e.g. broker-plugins and common-tests -->
- <present targetdir="${project.root}">
- <mapper type="glob" from="*" to="*/build.xml"/>
- </present>
- </dirset>
-
- <!-- Convert from the set of directories into Eclipse project names proceeded by forward slashes -->
-
- <pathconvert property="eclipse.required.projectnames" refid="eclipse.required.projectdirs.path" pathsep=" " dirsep="-">
- <map from="${project.root}${file.separator}" to=''/>
- </pathconvert>
- <map property="eclipse.required.slashedprojectnames" value="${eclipse.required.projectnames}" join="${path.separator}">
- <globmapper from="*" to="/*"/>
- </map>
-
- <echo message="Ant module dependencies : ${module.depends} ${module.test.depends} converted to Eclipse required project(s): ${eclipse.required.slashedprojectnames}"/>
- <path id="eclipse.required.slashedprojectnames.path">
- <pathelement path="${eclipse.required.slashedprojectnames}"/>
- </path>
- </target>
-
- <!-- Create the Eclipse .project -->
- <target name="eclipse-project">
- <eclipse updatealways="${eclipse.updatealways}">
- <project name="${module.name}"/>
-
- <!-- If the Eclipse task were to ever support the generation of
- linked resources, we would configure it to generate
- the following:
-
- scratch_src -> ${module.precompiled}
-
- in each project. This would avoid the 'linked sources'
- manual step documented on the Wiki.
- -->
- </eclipse>
- </target>
-
- <!-- Create the Eclipse .classpath -->
- <target name="eclipse-source-only" unless="module.test.src.exists">
- <eclipse updatealways="${eclipse.updatealways}">
- <settings>
- <jdtcore compilercompliance="${eclipse.compilercompliance}" />
- </settings>
- <classpath>
- <container path="${eclipse.container}" />
- <source path="${module.src}" />
- <source pathref="eclipse.required.slashedprojectnames.path" />
- <library pathref="module.libs"/>
- <output path="classes" />
- </classpath>
- </eclipse>
- </target>
-
- <!-- Create the Eclipse .classpath -->
- <target name="eclipse-source-and-test" if="module.test.src.exists">
- <eclipse updatealways="${eclipse.updatealways}">
- <settings>
- <jdtcore compilercompliance="${eclipse.compilercompliance}" />
- </settings>
- <classpath>
- <container path="${eclipse.container}" />
- <source path="${module.src}" />
- <source path="${module.test.src}" />
- <source pathref="eclipse.required.slashedprojectnames.path" />
- <library pathref="module.libs"/>
- <library pathref="module.test.libs"/>
- <output path="classes" />
- </classpath>
- </eclipse>
- </target>
-</project>
diff --git a/java/perftests/RunningPerformanceTests.txt b/java/perftests/RunningPerformanceTests.txt
deleted file mode 100644
index 2bc9220774..0000000000
--- a/java/perftests/RunningPerformanceTests.txt
+++ /dev/null
@@ -1,141 +0,0 @@
-The Performance Tests
--------------------------
-
-Building the Tests (Only develoeprs need to know how to do this).
------------------------------------------------------------------
-
-The performance tests are compiled as part of the Maven build by default, but the performance test scripts are not. There is also an additional step to perform, that generates a convenient Jar file containing all of the test dependencies, to simplify invoking Java with a very long command line. The steps to build the performance test suite are:
-
- 1. Cd to the /java/perftests directory.
- 2. Execute: mvn org.apache.qpid:junit-toolkit-maven-plugin:tkscriptgen (this generates the scripts).
- 3. Execute: mvn assembly:assembly
-
-The assembly:assembly step generates a Jar with all the dependecies in it in a file name ending with -all-test-deps.jar, which contains the client code and all its dependencies, plus JUnit and the toolkit test runners. The generated scripts expect to find the jar in the current directory. You can Cd to the /target directory and run the scripts from there. The assembly:assembly step also outputs some archives that contain all the scripts and required Jar for convenient shipping of the test suite. Unpack this anywhere you like and run the tests from there.
-
-Running the Tests
------------------
-
-All the performance tests are run through shell scripts, that have been configured with parameters set up in the pom.xml file. You can override any of these parameters on the command line. It is also possible to pass parameters through the script to the JVM that is running the test. For example to change the heap size you might do:
-
-./Ping-Once.sh -java:Xmx1024M
-
-The tests have all been set up to accept a single integer 'size' parameter, passed to the JUnit TestCase for the test, through the JUnit Toolkit asymptotic test case extension. The 'size' parameter is always interpreted in the performance tests as standing for the number of messages to send per test method invocation. Therefore, in the results of the test the throughput of messages is equal to the number of test method invocations times the 'size' divided by the time taken.
-
-** TODO: Change this, use seconds not millis.
-
-Test timing results are output to .csv files, which can easily be imported into a spreadsheet for graphing and analysis. The timings in this file are always given in milliseconds, which may be a bit confusing and should really be changed to seconds.
-
-The JUnit Toolkit provides a framework for controlling how long tests are run for, how many are run at once and what the 'size' parameter is, which is general enough to handle a wide variety of performance tests. Here is the documentation from the TKTestRunner class that explains what its command line parameters are:
-
- ...
- * TKTestRunner extends {@link junit.textui.TestRunner} with the ability to run tests multiple times, to execute a test
- * simultaneously using many threads, to put a delay between test runs and adds support for tests that take integer
- * parameters that can be 'stepped' through on multiple test runs. These features can be accessed by using this class
- * as an entry point and passing command line arguments to specify which features to use:
- *
- * <pre>
- * -w ms The number of milliseconds between invocations of test cases.
- * -c pattern The number of tests to run concurrently.
- * -r num The number of times to repeat each test.
- * -d duration The length of time to run the tests for.
- * -t name The name of the test case to execute.
- * -s pattern The size parameter to run tests with.
- * -o dir The name of the directory to output test timings to.
- * -v Verbose mode.
- * </pre>
- *
- * <p/>The pattern arguments are of the form [lowest(, ...)(, highest)](,sample=s)(,exp), where round brackets
- * enclose optional values. Using this pattern form it is possible to specify a single value, a range of values divided
- * into s samples, a range of values divided into s samples but distributed exponentially, or a fixed set of samples.
- *
- * <p/>The duration arguments are of the form dD(:hH)(:mM)(:sS), where round brackets enclose optional values.
- *
- * <p/>Here are some examples:
- *
- * <p/><table>
- * <tr><td><pre> -c [10,20,30,40,50] </pre><td> Runs the test with 10,20,...,50 threads.
- * <tr><td><pre> -s [1,100],samples=10 </pre>
- * <td> Runs the test with ten different size parameters evenly spaced between 1 and 100.
- * <tr><td><pre> -s [1,1000000],samples=10,exp </pre>
- * <td> Runs the test with ten different size parameters exponentially spaced between 1 and 1000000.
- * <tr><td><pre> -r 10 </pre><td> Runs each test ten times.
- * <tr><td><pre> -d 10H </pre><td> Runs the test repeatedly for 10 hours.
- * <tr><td><pre> -d 1M, -r 10 </pre>
- * <td> Runs the test repeatedly for 1 minute but only takes a timing sample every 10 test runs.
- * <tr><td><pre> -r 10, -c [1, 5, 10, 50], -s [100, 1000, 10000] </pre>
- * <td> Runs 12 test cycles (4 concurrency samples * 3 size sample), with 10 repeats each. In total the test
- * will be run 199 times (3 + 15 + 30 + 150)
- * </table>
- ...
-
-The specific performance test cases for QPid are implemented as extensions to JUnit TestCase (asymptotic test cases), and also accept a large number of different parameters to control the characteristics of the test. The are passed into the test scripts as name=value pairs. Here is the documentation from the PingPongProducer class that explains what the available parameters and default values are:
-
- ...
- * <p/>This ping tool accepts a vast number of configuration options, all of which are passed in to the constructor. It
- * can ping topics or queues; ping multiple destinations; do persistent pings; send messages of any size; do pings within
- * transactions; control the number of pings to send in each transaction; limit its sending rate; and perform failover
- * testing. A complete list of accepted parameters, default values and comments on their usage is provided here:
- *
- * <p/><table><caption>Parameters</caption>
- * <tr><th> Parameter <th> Default <th> Comments
- * <tr><td> messageSize <td> 0 <td> Message size in bytes. Not including any headers.
- * <tr><td> destinationName <td> ping <td> The root name to use to generate destination names to ping.
- * <tr><td> persistent <td> false <td> Determines whether peristent delivery is used.
- * <tr><td> transacted <td> false <td> Determines whether messages are sent/received in transactions.
- * <tr><td> broker <td> tcp://localhost:5672 <td> Determines the broker to connect to.
- * <tr><td> virtualHost <td> test <td> Determines the virtual host to send all ping over.
- * <tr><td> rate <td> 0 <td> The maximum rate (in hertz) to send messages at. 0 means no limit.
- * <tr><td> verbose <td> false <td> The verbose flag for debugging. Prints to console on every message.
- * <tr><td> pubsub <td> false <td> Whether to ping topics or queues. Uses p2p by default.
- * <tr><td> failAfterCommit <td> false <td> Whether to prompt user to kill broker after a commit batch.
- * <tr><td> failBeforeCommit <td> false <td> Whether to prompt user to kill broker before a commit batch.
- * <tr><td> failAfterSend <td> false <td> Whether to prompt user to kill broker after a send.
- * <tr><td> failBeforeSend <td> false <td> Whether to prompt user to kill broker before a send.
- * <tr><td> failOnce <td> true <td> Whether to prompt for failover only once.
- * <tr><td> username <td> guest <td> The username to access the broker with.
- * <tr><td> password <td> guest <td> The password to access the broker with.
- * <tr><td> selector <td> null <td> Not used. Defines a message selector to filter pings with.
- * <tr><td> destinationCount <td> 1 <td> The number of receivers listening to the pings.
- * <tr><td> timeout <td> 30000 <td> In milliseconds. The timeout to stop waiting for replies.
- * <tr><td> commitBatchSize <td> 1 <td> The number of messages per transaction in transactional mode.
- * <tr><td> uniqueDests <td> true <td> Whether each receiver only listens to one ping destination or all.
- * <tr><td> durableDests <td> false <td> Whether or not durable destinations are used.
- * <tr><td> ackMode <td> AUTO_ACK <td> The message acknowledgement mode. Possible values are:
- * 0 - SESSION_TRANSACTED
- * 1 - AUTO_ACKNOWLEDGE
- * 2 - CLIENT_ACKNOWLEDGE
- * 3 - DUPS_OK_ACKNOWLEDGE
- * 257 - NO_ACKNOWLEDGE
- * 258 - PRE_ACKNOWLEDGE
- * <tr><td> maxPending <td> 0 <td> The maximum size in bytes, of messages sent but not yet received.
- * Limits the volume of messages currently buffered on the client
- * or broker. Can help scale test clients by limiting amount of buffered
- * data to avoid out of memory errors.
- * </table>
- ...
-
-The most common test case to run is implemented in the class PingAsyncTestPerf, which sends and recieves messages simultaneously. This class uses a PingPongProdicer to do its sending and receiving, and wraps it in a suitable way to make it callable through the extended JUnit test runner. This class also accpets another parameter "batchSize" with a default of "1000". This tells the test how many messages to send before stopping sending and waiting for them all to come back. The actual value entered does not matter too much, but typically values larger than 1000 are used to ensure that there is a reasonable opportunity for simultaneous sending and receiving, and less than 10000 to ensure that each test method invocation does not go on for too long.
-
-The test script parameters can all be seen in the pom.xml file. A three letter code is used on the test scripts, first letter P or T for persistent or transient, second letter Q or T for queue (p2p) or topic (pub/sub), third letter R for reliability tests, C for client scaling tests, M for message size tests.Typically tests run and sample their results for 10 minutes, to get a reasonable measurement of a broker running under a steady load. The tests as configured do not measure 'burst' performance.
-
-The reliability/burn in tests, test the broker running at slightly below its maximum throughput for a period of 24 hours. Their purpose is to check that the broker remains stable under load for a reasonable duration, in order to provide some confidence in the long-term stability of its process. These tests are intended to be run as a two step process. The first two tests run for 10 minutes and are used to asses the broker throughput for the test. The output from these tests are to be fed into the rate limiter for the second set of tests, so that the broker may be set up to run at slightly below its maximum throughput for the 24 hour duration. It is suggested that 90% of the rate achieved by the first two tests should be used for this.
-
-The client scaling tests are split into two sub-sections. The first section tests the performance of increasing numbers of client connections, each sending at a fixed rate. The purpose of this is to determine the brokers saturation load, and to evaluate how its performance degrades uder higher loads. The second section varies the fan-out or fan-in ratio of the number of sending clients to receving clients. This is primarily intended to test the pubsub messaging model, but the tests are also run in p2p mode (with each message being received by one consumer), for completeness and to provide a comparison with the pubsub performance.
-
-The message size scaling tests, examine the brokers performance with different message payload sizes. The purpose of these tests is to evaluate where the broker process switches from being an io-bound to a cpu-bound process (if at all). The expected model is that the amount of CPU processing the broker has to carry out depends largely on the number of messages, and not on their size, because it carries out de-framing and routing for each message header but just copies payloads in-place or in a tight instruction loop. Therefore large message should be io-bound and a constant data rate through the broker should be seen for messages larger than the io/cpu threshold. Small messages require more processing so a constant message rate should be seen for message smaller than the io/cpu threshold. If the broker implementation is extremely efficient the threshold may dissapear altogether and the broker will be purely io-bound.
-The final variation, which is applied to all tests, is to run a transactional and non-transactional version of each. Messages are always batched into transactions of 100 messages each.
-
-Running the entire test suite can take some time, in particular their are about 4 24 hour burn-in tests. There are also 8 30 minute client scaling ramp up tests. If you want to run the test for a short time, to skim test that they work on your environment a command line like the following is usefull:
-
-> find . -name '*.sh' -exec {} -d10S \;
-
-If you want to run just a sub-set of the tests, you can use variations of the above command line. For example, to run just the message size tests using persistent p2p messaging do:
-
-> find . -name 'PPM-*.sh' -exec {} \;
-
-and so on.
-
-Interpreting the Results
-------------------------
-
-TODO: Explain what the results are expected to show and how to look for it. What should be graphed to get a visualization of the broker performance. How to turn the measurements into a description of the performance 'envelope'. \ No newline at end of file
diff --git a/java/perftests/bin/monitoring/monitor-broker.sh b/java/perftests/bin/monitoring/monitor-broker.sh
deleted file mode 100755
index 27c8ff25f6..0000000000
--- a/java/perftests/bin/monitoring/monitor-broker.sh
+++ /dev/null
@@ -1,221 +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.
-#
-#
-
-#
-# This script starts a broker and then starts additional logging as required.
-# *.pid files are generated in the LOG_DIR for later use by the stop-monitored-broker
-# script.
-#
-# Currently this process starts:
-# - The broker with additional QPID_OPTS for gc logging
-# - Top to monitoring the CPU usage
-#
-# Additional processes can be started and as long as they write a PID into LOG_DIR/*.pid
-# it will be shutdown with the stop script
-#
-
-#
-# Output the broker log file to aid problem diagnosis
-# then exit.
-#
-brokerFailExit()
-{
- echo "Broker failed to start up."
- cat $BROKER_LOG
- exit 1
-}
-
-showUsageExit()
-{
- echo "Usage $0 <Path to Test Broker> <LOG DIR> <CPU Monitor Rate (s)> [Additional options to
- pass to Qpid broker startup]"
- exit 1
-}
-
-#
-# Perform 3 attempts to get the broker PID via ps and grep
-# if unable the output broker log and exit
-#
-getBrokerPID()
-{
- attempts=3
- ready=0
- while [ $ready == 0 ] ; do
-
- PID=`ps auxwww| grep java | grep Xloggc | awk '{print $2}'`
-
- if [ ! $PID == 0 ] ; then
- ready=1
- else
- attempts=$[ $attempts - 1 ]
-
- if [ $attempts == 0 ] ; then
- brokerFailExit
- fi
-
- sleep 1
- fi
- done
-
-}
-
-
-#
-# Additional Check to ensure that the broker process
-# has correctly written 'Ready' to the log file.
-#
-checkBrokerStarted()
-{
- attempts=3
- ready=0
- while [ $ready == 0 ] ; do
-
- grep Ready $BROKER_LOG > /dev/null
-
- if [ $? == 0 ] ; then
- ready=1
- else
- attempts=$[ $attempts - 1 ]
-
- if [ $attempts == 0 ] ; then
- brokerFailExit
- fi
-
- echo "Broker not ready sleeping 1s"
- sleep 1
- fi
- done
-}
-
-#
-# Command Line setup
-#
-
-# Ensure we have minimum of three arguments
-if [[ $# > 2 ]] ; then
- BROKER_VERSION=$1
- LOG_DIR=$2
- CPU_MONITOR_RATE=$3
- # Remove these arguments from the $@ variable
- shift
- shift
- shift
-else
- # If we have no arguments then use these as the default
- CPU_MONITOR_RATE=0.5
- LOG_DIR=$QPID_WORK/logging
- BROKER_VERSION=qpid-0.5
-fi
-
-
-#
-# Check the specified broker is reachable
-# it it is not the log and show usage
-#
-if [ ! -d $BROKER_VERSION ] ; then
- echo "Broker not available at: $BROKER_VERSION"
- showUsageExit
-fi
-
-#
-# Check to see if we have an absolute path for logging
-#
-logStart=`echo $LOG_DIR|cut -c 1`
-
-
-#
-# If we don't have an absolute path then add the current
-# directory path to the start.
-#
-if [[ $logStart != '/' ]] ; then
- echo -n "$LOG_DIR is not absolute, using "
- LOG_DIR=`pwd`/$LOG_DIR
- echo $LOG_DIR
-fi
-
-#
-# Validate that the directory does not exist
-# - this is so we can guarrantee a clean run.
-# If it does exit then log and show usage
-#
-if [ -d $LOG_DIR ] ; then
- echo "Log directory already exists : $LOG_DIR"
- showUsageExit
-fi
-
-#
-# Create the logging directory
-#
-mkdir -p $LOG_DIR
-
-#
-# Variable for broker log
-#
-BROKER_LOG=$LOG_DIR/broker.log
-
-# Variable to hold broker PID
-PID=0
-
-export QPID_OPTS="-Xloggc:$LOG_DIR/gc.log -verbose:gc -XX:+PrintGCDetails -XX:+PrintGCTimeStamps"
-
-#
-# Start Qpid Broker
-#
-echo "Starting Broker : $BROKER_VERSION"
-pushd $BROKER_VERSION/bin > /dev/null
-./qpid-server $@ 2> $BROKER_LOG >&2 &
-popd > /dev/null
-
-# Wait and check startup was ok
-echo "Waiting for broker startup"
-getBrokerPID
-
-checkBrokerStarted
-
-echo $PID > $LOG_DIR/broker.pid
-
-#
-# Start CPU Monitoring via TOP
-#
-echo "Starting CPU Monitor at RATE:$CPU_MONITOR_RATE on $SERVER1"
-pushd $LOG_DIR > /dev/null
-
-echo $CPU_MONITOR_RATE > top.rate
-
-top -d $CPU_MONITOR_RATE -S -c -p $PID -b > broker_cpu.log &
-
-#
-# Get top pid using $!
-#
-echo $! > $LOG_DIR/top.pid
-
-popd > /dev/null
-
-
-#
-# Generate Stat files
-#
-echo "Generating Stat data"
-stat $BROKER_LOG > $BROKER_LOG.stat
-stat $LOG_DIR/broker_cpu.log > $LOG_DIR/broker_cpu.log.stat
-stat $LOG_DIR/gc.log > $LOG_DIR/gc.log.stat
-
diff --git a/java/perftests/bin/monitoring/runTests.sh b/java/perftests/bin/monitoring/runTests.sh
deleted file mode 100755
index 676db0d4fa..0000000000
--- a/java/perftests/bin/monitoring/runTests.sh
+++ /dev/null
@@ -1,148 +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.
-#
-#
-
-#
-# Run specified performance tests and
-# gather details about the test run
-#
-
-
-runTest()
-{
- echo "$@"
- echo "$@ --csv -o $LOG_DIR" >> $LOG_DIR/TestRun.log 2>&1
- ./$@ --csv -o $LOG_DIR >> $LOG_DIR/TestRun.log 2>&1
-}
-
-showUsageExit()
-{
- echo "Usage $0 <Path to Test Pack> <LOG DIR> <TEST LIST FILE>"
- exit 1
-}
-
-# Ensure we have minimum of three arguments
-if [[ $# > 2 ]] ; then
- TEST_VERSION=$1
- LOG_DIR=$2
- TEST_LIST=$3
- # Remove these arguments from the $@ variable
- shift
- shift
- shift
-else
- showUsageExit
-fi
-
-#
-# Check the specified broker is reachable
-# it it is not the log and show usage
-#
-if [ ! -d $TEST_VERSION ] ; then
- echo "Tests not available at: $TEST_VERSION"
- showUsageExit
-fi
-
-
-#
-# Check to see if we have an absolute path for logging
-#
-logStart=`echo $LOG_DIR|cut -c 1`
-
-#
-# If we don't have an absolute path then add the current
-# directory path to the start.
-#
-if [[ $logStart != '/' ]] ; then
- echo -n "$LOG_DIR is not absolute, using "
- LOG_DIR=`pwd`/$LOG_DIR
- echo $LOG_DIR
-fi
-
-#
-# Validate that the directory does not exist
-# - this is so we can guarrantee a clean run.
-# If it does exit then log and show usage
-#
-if [ -d $LOG_DIR ] ; then
- echo "Log directory already exists : $LOG_DIR"
- showUsageExit
-fi
-
-#
-# Check to see if we have an absolute path for test list
-#
-testListStart=`echo $TEST_LIST|cut -c 1`
-
-#
-# If we don't have an absolute path then add the current
-# directory path to the start.
-#
-if [[ $testListStart != '/' ]] ; then
- echo -n "$TEST_LIST is not absolute, using "
- TEST_LIST=`pwd`/$TEST_LIST
- echo $TEST_LIST
-fi
-
-#
-# Validate that the directory does not exist
-# - this is so we can guarrantee a clean run.
-# If it does exit then log and show usage
-#
-# -r Check file exists and is readable
-if [ ! -r $TEST_LIST ] ; then
- echo "Test file is not readable : $TEST_LIST"
- showUsageExit
-fi
-
-
-
-#
-# Create the logging directory
-#
-mkdir -p $LOG_DIR
-
-
-
-echo "Starting Test Run in : $TEST_VERSION"
-pushd $TEST_VERSION/bin > /dev/null
-
-#
-# Run tests
-#
-
-
-while read testCommand
-do
- runTest $testCommand
-done < "$TEST_LIST"
-
-
-popd > /dev/null
-
-
-#
-# Generate Stat files
-#
-echo "Generating Stat data"
-for file in `find $LOG_DIR -name "*.csv"` ; do
- stat $file > $file.stat
-done
diff --git a/java/perftests/bin/monitoring/stop-monitored-broker.sh b/java/perftests/bin/monitoring/stop-monitored-broker.sh
deleted file mode 100755
index ad882b0bea..0000000000
--- a/java/perftests/bin/monitoring/stop-monitored-broker.sh
+++ /dev/null
@@ -1,124 +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.
-#
-#
-
-#
-# Script to stop the running of a monitored broker
-# and the associated monitoring processes.
-#
-# Looks in the specifed directory for pid files and
-# stops those proceses
-#
-
-
-usage()
-{
- echo "Usage: $0 <LOG_DIR>"
-}
-
-#
-# Attempt to gracefully kill processs
-#
-stopRun()
-{
- kill $PIDS
-}
-
-
-#
-# Forcibly stop processes
-#
-forceStopRun()
-{
- kill -9 $PIDS
-}
-
-#
-# Show usage if we are not started correctly
-#
-if [ $# != 1 ] ; then
- usage
- exit 1
-fi
-
-LOG_DIR=$1
-
-
-PIDS=`cat $LOG_DIR/*.pid`
-
-echo "Preparing to stop:"
-#
-# Escape the path so we can use sed to remove it.
-#
-path=`echo $LOG_DIR|sed -e s/\\\//\\\\\\\\\\\//g`
-
-for i in `ls $LOG_DIR/*.pid` ; do
- # Remove path from pid item then remove any final '/'
- echo $i|cut -d '.' -f 1| sed -e s/$path// |tr '/' ' '
-done
-
-status=`ps $PIDS |wc -l`
-
-if [ $status == 1 ] ; then
- echo "Processes do not appear to be running."
- echo "Have they already been stopped?"
- exit 0
-fi
-
-attempts=3
-
-while [ ! $status == 1 ] ; do
- stopRun
- sleep 1
- status=`ps $PIDS |wc -l`
-
- if [ $status == 1 ] ; then
- echo "Done"
- exit 0
- else
- attempts=$[ $attempts - 1 ]
-
- if [ $attempts == 0 ] ; then
- break
- fi
-
- echo "Sleeping as processes not stopped"
- sleep 2
-
- fi
-done
-
-# If we haven't been able to kill the processes then
-# forcibly do it
-if [ ! $status == 1 ] ; then
- forceStopRun
- sleep 1
- status=`ps $PIDS |wc -l`
-
- if [ $status == 1 ] ; then
- echo "Done"
- else
- echo "Stop failed"
- exit 1
- fi
-else
- echo "Done"
-fi
diff --git a/java/perftests/bin/processing/process.sh b/java/perftests/bin/processing/process.sh
deleted file mode 100755
index 6dbf9b9ea8..0000000000
--- a/java/perftests/bin/processing/process.sh
+++ /dev/null
@@ -1,388 +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.
-#
-#
-
-
-usage()
-{
- echo "usage: process.sh <Qpid Version> <Test Type Queue/Topic/Latency..> <Volume of data %age> <broker details>"
- echo "These parameters are used to title and name the graphs:"
- echo 'Title = $<Qpid Version> $<Test Type> : $<Volume>% volume'
- echo 'File = $<Qpid Version>-$<Broker Details>-$<Test Type>-$<Volume>'
- exit 1
-}
-
-processCMSGCFile()
-{
- # Extract all the ParNew timings: Ignore any lines corrupted by concurrent CMS logging.
- grep -v CMS gc.log|grep ParNew > $work/parnew.gc.log
-
- # Calculate Full GC Data
- grep failure -B 1 gc.log | sed -e :a -e '$!N;s/\n.(concurrent/ /;ta' -e 'P;D' |grep -v ^\- > $work/full.gc.log
- cut -d ':' -f 1 $work/full.gc.log > $work/full.time.log
- sed -e 's/failure)/\#/g' $work/full.gc.log |cut -d '#' -f 2- |awk '{print $3}' > $work/full.dur.log
-
- # Move to the working directory to further process the gathered data.
- pushd $work &> /dev/null
-
- # Extract the Heap and timing data.
- #8 is the full gc data
- #5 is the paranew gc data
- cat parnew.gc.log | awk '{print $8}' | cut -d '(' -f 2 | cut -d 'K' -f 1 > HEAP_MAX.log
- cat parnew.gc.log | awk '{print $8}' | cut -d 'K' -f 1 > HEAP_PRE_GC.log
- cat parnew.gc.log | awk '{print $8}' | cut -d 'K' -f 2 | cut -d '>' -f 2 > HEAP_POST_GC.log
- cat parnew.gc.log | awk '{print $1}' | cut -d ':' -f 1 > GC_TIME.log
-
- calculateStats "MEM_PRE" HEAP_PRE_GC.log
- calculateStats "MEM_POST" HEAP_POST_GC.log
- calculateStatsBC "GC_FREQ" GC_TIME.log
-
-
- # Calculate ParNew GC Cumulative total
- cat parnew.gc.log |awk '{sum=sum+$6; print $6, sum}' > GC_DUR.log
- # Give a count of GC occurances
- parNewGCCount=`wc -l GC_DUR.log| awk '{print $1}'`
-
- # Create the Heap data file
- paste GC_TIME.log HEAP_POST_GC.log HEAP_PRE_GC.log HEAP_MAX.log > GC.Heap.data
- # Create ParNew GC Duration data file for graphing
- paste GC_TIME.log GC_DUR.log > GC.Dur.data
- # Create Full GC occurance log file for plotting
- paste full.time.log full.dur.log > GC.Full.data
-
- # Calculate All GC Timing and give a count of their occurance
- awk '{print $1}' GC_DUR.log > gc_dur.log
- paste GC_TIME.log gc_dur.log > gc_all.log
- cat GC.Full.data >> gc_all.log
- sort -n gc_all.log | awk '{sum=sum+$2;print $1 , sum}' > GC.Dur.All.data
- fullGCCount=`wc -l GC.Full.data| awk '{print $1}'`
-}
-
-processG1GCFile()
-{
- cat gc.log | grep -e \^[0-9]*.[0-9]*\: -e \^.*[0-9]*.\-\> > $work/g1.gc.log
-
- # Move to the working directory to further process the gathered data.
- pushd $work &> /dev/null
-
- # Calculate Full GC Data
- cat g1.gc.log | sed -e :a -e '$!N;s/\n.\ *\[/ \[/;ta' -e 'P;D' > full.gc.log
- grep Full full.gc.log |awk '{print $1}'| tr ':' ' ' > full.time.log
- grep Full full.gc.log |awk '{print $5}' > full.dur.log
- fullGCCount=`wc -l GC.Full.data| awk '{print $1}'`
-
- # Create Full GC occurance log file for plotting
- paste full.time.log full.dur.log > GC.Full.data
-
- # Extract the Heap and timing data.
- # Create G1 Young Duration data file for graphing
- grep "(young)," full.gc.log |awk '{print $1}' | tr ':' ' ' > GC_TIME.log
- grep "(young)," full.gc.log |awk '{print $5}' > young.gc.time.log
- # Calculate G1 young Cumulative total
- cat young.gc.time.log |awk '{sum=sum+$1; print $1, sum}' > GC_DUR.log
- # Create G1 Young Duration data file for graphing
- paste GC_TIME.log GC_DUR.log > GC.Dur.data
-
- # Give a count of GC occurances
- youngGCCount=`wc -l GC_DUR.log| awk '{print $1}'`
-
- #
- # If we have no GCs then something is wrong
- if [ $youngGCCount == 0 ] ; then
- echo "Error no YoungGC log entries to proceses"
- return
- fi
-
- # Gather the Heap Size data
-
- grep "(young)," full.gc.log | awk '{print $8}' | cut -d '(' -f 2 | cut -d ')' -f 1 > HEAP_MAX.Sized.log
- grep "(young)," full.gc.log | awk '{print $8}' | cut -d '-' -f 1 > HEAP_PRE_GC.Sized.log
- grep "(young)," full.gc.log | awk '{print $8}' | cut -d '>' -f 2| cut -d '(' -f 1 > HEAP_POST_GC.Sized.log
-
- normaliseSizeMemFile HEAP_MAX.Sized.log HEAP_MAX.log
- normaliseSizeMemFile HEAP_PRE_GC.Sized.log HEAP_PRE_GC.log
- normaliseSizeMemFile HEAP_POST_GC.Sized.log HEAP_POST_GC.log
-
-
- # Create the Heap data file
- paste GC_TIME.log HEAP_POST_GC.log HEAP_PRE_GC.log HEAP_MAX.log > GC.Heap.data
-
- # Calculate All GC Timing and give a count of their occurance
- awk '{print $1}' GC_DUR.log > gc_dur.log
- paste GC_TIME.log gc_dur.log > gc_all.log
- cat GC.Full.data >> gc_all.log
- sort -n gc_all.log | awk '{sum=sum+$2;print $1 , sum}' > GC.Dur.All.data
-
-}
-
-calculateStatsBC()
-{
-label=$1
-statFile=$2
-# Calculate GC Frequencies
- prevFreq=0
- countFreq=0
- gcFreqTotal=0
- minFreq=99999999
- maxFreq=0
-
- echo "" > GC_FREQ.log
- for time in `cat $statFile` ; do
- if [ $prevFreq == 0 ] ; then
- prevFreq=$time
- else
- freq=`echo $time - $prevFreq | bc`
- echo $freq >> GC_FREQ.log
-
- prevFreq=$time
- gcFreqTotal=`echo $gcFreqTotal + $freq | bc`
- countFreq=$[$countFreq + 1]
-
- if [ `echo "$freq > $maxFreq " | bc` == 1 ] ; then
- maxFreq=$freq
- fi
-
- if [ `echo "$freq < $minFreq " | bc ` == 1 ] ; then
- minFreq=$freq
- fi
- fi
- done
-
- # Extract Min/Max/Avg
- echo "#type:min/max/avg" > $statFile.stats
-
- if [ $countFreq != 0 ] ; then
- avgFreq=`echo $gcFreqTotal / $countFreq | bc -l 2&> /dev/null`
- echo "$label:$minFreq/$maxFreq/$avgFreq" >> $statFile.stats
- echo "Done GC Freq Stat generation for $statFile"
- else
- echo "$label:-/-/-" >> $statFile.stats
- echo "Unable to calculate GC Freq stats as no freq entries found."
- fi
-}
-
-calculateStats()
-{
-label=$1
-statFile=$2
-
-# Calculate GC Frequencies
- count=0
- gcTotal=0
- min=0
- max=0
-
-
- for item in `cat $statFile` ; do
- if [ $min == 0 ] ; then
- min=$item
- fi
-
- gcTotal=$[$gcTotal + $item]
- count=$[$count + 1]
-
- if [ $item -gt $max ] ; then
- max=$item
- fi
-
- if [ $item -lt $min ] ; then
- min=$item
- fi
- done
-
- # Extract Min/Max/Avg
- echo "#type:min/max/avg" > $statFile.stats
-
- if [ $count != 0 ] ; then
- avg=`echo $gcTotal / $count | bc -l`
-
- echo "$label:$min/$max/$avg" >> $statFile.stats
- echo "Done $label Stat generation for $statFile"
- else
- echo "$label:-/-/-" >> $statFile.stats
- echo "Unable to calculate $label stats as no entries found."
- fi
-
-}
-
-#
-# Take an input file ($1) of lines
-# <value><K|M>
-# and output file $2 of <value> in whole M
-#
-normaliseSizeMemFile()
-{
-rm -f $2
-for i in `cat $1` ; do
- if [[ `echo $i | grep -c "K" ` == 1 ]] ; then
- kb=`echo $i|cut -d 'K' -f 1`
- echo $[ $kb / 1024 ] >> $2
- else
- echo $i|cut -d 'M' -f 1 >> $2
- fi
-done
-
-
-}
-
-
-# Parse command line
-# TODO more advanced processing
-# Check we have enough parameters
-if [ $# != 4 ] ; then
- # Take one arg to be a graph data file.
- if [ $# == 1 ] ; then
- textArray[0]="" # hold text
- length=0
- # read whole file in loop
- while read line
- do
- textArray[$length]=$line # store line
- length=$(expr $length + 1) # increase length by 1
- done < $1
-
- if [ $length != 2 ] ; then
- usage
- fi
-
- #Get Title and file name
- title=${textArray[0]}
- file=${textArray[1]}
-
- pushd `dirname $1`
-
- else
- usage
- fi
-else
- version=$1
- type=$2
- volume=$3
- brokerState=$4
-
-
- # Configure Graph Title and image file names
- title="$version $type : $volume% volume"
- file="$version-$brokerState-$type-$volume"
-fi
-
-work=work
-
-mkdir -p $work
-
-echo -n "Processing GC Usage Data : "
-ParNew=`grep -c ParNew gc.log`
-
-if [ $ParNew != 0 ] ; then
- echo "CMS log file"
- processCMSGCFile
- PLOT="\"GC.Dur.data\" with lines axis x1y1 ti \"ParNew GC Time ($parNewGCCount)\", "
-else
- echo "G1 log file"
- processG1GCFile
- PLOT="\"GC.Dur.data\" with lines axis x1y1 ti \"G1 Young Time ($youngGCCount)\", "
-fi
-
-#
-# Colate Stats
-#
-echo -n "Colating stat Data : "
-echo "#type:min/max/avg" > $file.statistics.txt
-find .. -name "*stats" -exec grep -v "type" {} >> $file.statistics.txt \;
-
-
-# Prepare the plot command
-# If a Full GC occured during this test then plot those
-if [[ $fullGCCount > 0 ]] ; then
-PLOT=$PLOT"\"GC.Dur.data\" using 1:3 with lines axis x1y2 ti \"Cumulative Total Time(ParNew)\", \
- \"GC.Dur.All.data\" with lines axis x1y2 ti \"Cumulative Total Time(All)\", \
- \"GC.Full.data\" with points ti \"Full GCs Time ($fullGCCount)\" "
-else
-PLOT=$PLOT"\"GC.Dur.data\" using 1:3 with lines axis x1y2 ti \"Cumulative Total Time(ParNew)\", \
- \"GC.Dur.All.data\" with lines axis x1y2 ti \"Cumulative Total Time(All)\" "
-fi
-
-if [ $ParNew != 0 ] ; then
- gcs=$parNewGCCount
-else
- gcs=$youngGCCount
-fi
-
-# Call out to gnuplot to generate graphs
-# Only do this if we have data
-if [ $gcs != 0 ] ; then
- # Generate the Heap Graph and the GC Duration Graph
- gnuplot << EOGNUPLOT
-set xlabel "Run Time(s)"
-
-set title "$title : Heap Size"
-set term png
-set output "$file-Heap.png"
-set ylabel "MB" +0.5,0
-plot "GC.Heap.data" using 1:2 with lines axis x1y1 ti "GC Size Post",\
- "GC.Heap.data" using 1:4 with lines axis x1y1 ti "GC Size Max ", \
- "GC.Heap.data" using 1:3 with lines axis x1y1 ti "GC Size Pre "
-
-set y2tics nomirror
-set ytics nomirror
-set key top left
-set title "$title GC Time"
-set ylabel "Time(s)" +0.5,0
-set y2label "Total Time(s)"
-set output "$file-GCDuration.png"
-plot $PLOT
-EOGNUPLOT
-
-else
- echo "Warning: No GC Data to graph"
-fi
-
-# pop back to further process for CPU usage
-popd &> /dev/null
-
-echo "Processing CPU Usage Data"
-
-# CPU.data is just TimeStamp + %age
-cat broker_cpu.log |awk '{print $1 "T" $2 " " $3}' > $work/CPU.data
-
-# Move to work directory to run gnuplot
-pushd $work &> /dev/null
-
-# Call out to gnuplot to generate graphs
-# Generate the Heap Graph and the GC Duration Graph
-gnuplot << EOGNUPLOT
-set term png
-set title "$title : CPU"
-set output "$file-CPU.png"
-unset key
-set xlabel "Real Time(h:m)"
-set ylabel "Usage(%)"
-
-set xdata time
-set timefmt "%Y-%m-%dT%H:%M:%S"
-set format x "%H:%M"
-plot "CPU.data" using 1:2 with lines
-EOGNUPLOT
-
-#"
-# Pop out of $work directory.
-#
-popd &> /dev/null \ No newline at end of file
diff --git a/java/perftests/bin/processing/processAll.sh b/java/perftests/bin/processing/processAll.sh
deleted file mode 100755
index 895d59c316..0000000000
--- a/java/perftests/bin/processing/processAll.sh
+++ /dev/null
@@ -1,58 +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.
-#
-#
-
-
-usage()
-{
- echo "processResults.sh <search dir>"
- exit 1
-}
-
-root=`pwd`
-echo $root
-graphFile=graph.data
-
-if [ $# != 1 ] ; then
- usage
-fi
-
-mkdir -p results
-
-for file in `find $1 -name $graphFile` ; do
-
- dir=`dirname $file`
-
- echo Processing : $dir
- pushd $dir &> /dev/null
-
- $root/process.sh $graphFile
-
- echo Copying Images
- cp work/*png $root/results/
-
- echo Copying Stats
- cp work/*.statistics.txt $root/results/
-
-
- popd &> /dev/null
- echo Done
-done \ No newline at end of file
diff --git a/java/perftests/bin/processing/processTests.py b/java/perftests/bin/processing/processTests.py
deleted file mode 100755
index 8db44eda79..0000000000
--- a/java/perftests/bin/processing/processTests.py
+++ /dev/null
@@ -1,850 +0,0 @@
-#!/usr/bin/env python
-#
-#
-# 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 os
-import re
-import datetime
-import sys
-import string
-from optparse import OptionParser
-from datetime import datetime, timedelta
-import shutil
-
-
-def showUsage():
- log("./processTests.py [-b|--broker-log-dir] <dir> [-t|--test-dir] <dir>")
-
-
-ACCESS="Access"
-MODIFY="Modify"
-
-BROKER_LOG="broker.log"
-BROKER_PID="broker.pid"
-BROKER_CPU="broker_cpu.log"
-BROKER_CPU_DATED="broker_cpu.log.dated"
-BROKER_STATS="broker.stats"
-BROKER_GC="gc.log"
-
-GRAPH_DATA="graph.data"
-
-_verbose = False
-_debug = False
-_brokerLogs = ""
-
-def exitError(message):
- log(message)
- sys.exit(1)
-
-def main():
- global _log, _verbose, _debug, _brokerLogs
-
- # Load the
- parser = OptionParser()
-
- parser.add_option("-v", "--verbose", dest="verbose",
- action="store_true", default=False, help="enable verbose output")
-
- parser.add_option("-d", "--debug", dest="debug",
- action="store_true", default=False, help="enable debug output")
-
- parser.add_option("-b", "--broker-log-dir", dest="brokerLogs",
- action="store", default=True, help="Broker Logs")
-
- parser.add_option("-t", "--test-dir", dest="testDir",
- action="store", default="", help="Test Results")
-
-
- (options, args) = parser.parse_args()
-
- _verbose = options.verbose
- _debug = options.debug
- testDir = options.testDir
- _brokerLogs = options.brokerLogs
-
- if testDir == "" or _brokerLogs == "" :
- log("Broker Log Dir and Test Dir are both requried.")
- showUsage()
-
- if not os.path.exists(testDir):
- exitError("Test directory does not exist:" + testDir)
-
- if not os.path.exists(_brokerLogs):
- exitError("Broker log directory does not exist:" + _brokerLogs)
-
-
- # Standardize the format of the broker logs
- preProcessBrokerLogs(_brokerLogs)
-
- # Get list of test results from test_dir
- processTestResults(testDir)
-
-#
-# Process the log files we know of
-#
-def preProcessBrokerLogs(resultDir):
-
- print "Pre Processing Broker Logs"
- # Pre-Process GC - no pre processing required
-
- # Process Log4j - no processing required as file is already time stamped.
-
- # Pre-Process broker_cpu
- processCPUUsage(resultDir)
-
-#
-# Process the broker CPU log file and create an output file of format
-# <Date Time> <CPU Usage>
-#
-#
-def processCPUUsage(resultDir):
- logfile=resultDir+os.sep+BROKER_CPU
- datedFile=resultDir+os.sep+BROKER_CPU_DATED
-
- start = extractTime(ACCESS, logfile+".stat")
-
- pid = getPID(BROKER_PID)
-
- topRate = getFirstLine(_brokerLogs+os.sep+"top.rate")
-
- #
- # Calulate addition required per process line output
- #
- if topRate.find(".") == -1:
- seconds = topRate
- millis = 0
- else:
- split = topRate.split('.')
- seconds = split[0]
- # Convert
- millis = float("0."+split[1]) * 1000
-
- offset = timedelta(seconds=int(seconds),milliseconds=int(millis))
-
- #
- # Process the CPU log file and make a file of format:
- # datetime <CPU% usage> <MEM% usage>
- #
- # Open log CPU file for reading
- logfile = open(logfile, "r")
-
- # Open the output file, erasing any existing version
- # Keep track of the min/max sum and entries,.
- minCPU=float(sys.maxint)
- maxCPU=0.0
- minMem=float(sys.maxint)
- maxMem=0.0
-
- entries=0
- sumCPU=0.0
- sumMem=0.0
-
- output= open(datedFile, "w")
- for line in logfile:
- #
- # Data format
- # 0 1 2 3 4 5 6 7 8 9 10 11
- # PID USER PR NI %CPU TIME+ %MEM VIRT RES SHR S COMMAND
- # PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
- #
- # %CPU and %MEM are vary, probably based on os/version of top.
- # lets auto-detect where it is.
- #
- # Index is 0 based for array usage.
- index = 0
- if line.find("PID") != -1:
- for key in line.split(" "):
- strippedKey = key.lstrip()
- if len(strippedKey) > 0:
- # Record the key index
- if (strippedKey == "%CPU"):
- cpuIndex=index
- if (strippedKey == "%MEM"):
- memIndex=index
- # Increase count for next key
- index = index + 1
-
-
- # Find lines that contain our broker process
- if line.find("QPBRKR") != -1:
-
- # Split line on whitespace
- data = line.split()
-
- #Write out the date time (ISO-8601 format)
- output.write(str(start))
- # Output the %CPU value
- output.write(" "+str(data[cpuIndex]))
- # Output the %MEM value
- output.write(" "+str(data[memIndex]))
- output.write('\n')
-
- # Add the offset based on the logging rate
- start = start + offset
-
- # Record entires
- entries = entries + 1
-
- # Record Metrics
- # Record CPU data
- cpu = float(data[cpuIndex])
- if (cpu < minCPU):
- minCPU = cpu
-
- if (cpu > maxCPU):
- maxCPU = cpu
-
- sumCPU = sumCPU + cpu
-
- # Record Mem data
- mem = float(data[memIndex])
-
- if (mem < minMem):
- minMem = mem
-
- if (mem > maxMem):
- maxMem = mem
-
- sumMem = sumMem + mem
-
-
- #end for
-
- # Close the files
- logfile.close
- output.close
-
- # Output stats file
- statFile=resultDir+os.sep+BROKER_CPU+".stats"
- output= open(statFile, "w")
- output.write("#type:min/max/avg")
- output.write('\n')
- output.write("CPU:"+str(minCPU)+"/"+str(maxCPU)+"/"+str(float(sumCPU)/float(entries)))
- output.write('\n')
- output.write("MEM:"+str(minMem)+"/"+str(maxMem)+"/"+str(float(sumMem)/float(entries)))
- output.write('\n')
- output.close
-
- log("Pre Process of CPU Log file '"+BROKER_CPU+"' complete")
-
-
-#
-# Give an known process type get the recorded PID.
-#
-def getPID(process):
- return getFirstLine(_brokerLogs+os.sep+process)
-
-#
-# Get the first line of the file without EOL chars.
-# NOTE: this will load the entire file into memory to do it.
-#
-def getFirstLine(fileName):
- f = open(fileName,"r")
- line = f.read().splitlines()[0]
- f.close
- return line
-
-
-#
-# Walk the directory given and process all csv test results
-#
-def processTestResults(resultDir):
- for root, dirs, files in os.walk(resultDir, topdown=False):
- if len(files) == 0:
- exitError("Test result directory is empty:" + resultDir)
- for file in files:
- if file.endswith(".csv"):
- processTestResult(root , file)
-
-def processTestResult(root, resultFile):
- # Open stat file and extract test times, we determine:
- # -start time based on the 'Access' value
- # -end time based on the 'Modify' value 'Change' would also work
-
- statFile=root+os.sep+resultFile+".stat"
-
- if not os.path.exists(statFile):
- log("Unable to process : Unable to open stat file:" + statFile)
- return
-
-
- createResultSetPackage(root, resultFile)
-
-
-def extractTime(field, statFile):
- stats = open(statFile, "r")
- for line in stats:
- if line.startswith(field):
- if line.find("(") == -1:
- dt = lineToDate(" ".join(line.split()[1:]))
-
- #
- # TODO We need to handle time time zone issues as I'm sure we will have issues with the
- # log4j matching.
-
- stats.close
- return dt
-
-#
-# Given a text line in ISO format convert it to a date object
-#
-def lineToDate(line):
- #2009-06-22 17:04:44,320
- #2009-06-22 17:04:44.320
- pattern = re.compile(r'(?P<year>^[0-9][0-9][0-9][0-9])-(?P<month>[0-9][0-9])-(?P<day>[0-9][0-9]) (?P<hour>[0-9][0-9]):(?P<minute>[0-9][0-9]):(?P<seconds>[0-9][0-9])')
-
-
- m = pattern.match(line)
- if m:
- year = int(m.group('year'))
- month = int(m.group('month'))
- day = int(m.group('day'))
- hour = int(m.group('hour'))
- minute = int(m.group('minute'))
- seconds = int(m.group('seconds'))
-
- pattern = re.compile(r'(?P<year>^[0-9][0-9][0-9][0-9])-(?P<month>[0-9][0-9])-(?P<day>[0-9][0-9]) (?P<hour>[0-9][0-9]):(?P<minute>[0-9][0-9]):(?P<seconds>[0-9][0-9])[.|,](?P<micro>[0-9]+)')
- m = pattern.match(line)
- micro = None
- if m:
- micro = m.group('micro')
-
- if micro == None:
- micro = 0
-
- # Correct issue where micros are actually nanos
- if int(micro) > 999999:
- micro = int(micro) / 1000
-
- return datetime(year,month,day,hour,minute,seconds,int(micro))
- else:
- # Error we shouldn't get here
- return null
-
-def createResultSetPackage(root, resultFile):
- # Get the Name of the test to make a directory with said name
- testName = resultFile.split(".csv")[0]
- resultDir = root+ os.sep + testName
-
- log("Processing Result set for:"+ testName)
-
- mkdir(resultDir)
-
- # Move result file to new directory
- shutil.move(root + os.sep + resultFile, resultDir)
-
- # Move stat file to new directory
- shutil.move(root + os.sep + resultFile + ".stat", resultDir)
-
- statFile=resultDir + os.sep + resultFile + ".stat"
-
- #
- # Get start and end time for test run
- #
- start = extractTime(ACCESS, statFile)
- end = extractTime(MODIFY, statFile)
-
- sliceBrokerLogs(resultDir, start, end)
- createGraphData(resultDir, testName)
- createTestStatData(resultDir, testName)
-
- log("Created Result Package for:"+ testName)
-
-def sliceBrokerLogs(resultDir, start, end):
- sliceCPULog(resultDir, start, end)
- sliceLog4j(resultDir, start, end)
- sliceGCLog(resultDir, start, end)
-
-
-def sliceCPULog(resultDir, start, end):
- global _brokerLogs
- logfilePath=_brokerLogs+os.sep+BROKER_CPU_DATED
- cpuSliceFile=resultDir+os.sep+BROKER_CPU
-
- # Process the CPU log file and make a file of format:
- # datetime <CPU% usage> <MEM% usage>
- #
- # Open log CPU file for reading
- logFile = open(logfilePath, "r")
-
- # Open the output file, erasing any existing version
- # Keep track of the min/max sum and entries,.
- minCPU=float(sys.maxint)
- maxCPU=0.0
- minMem=float(sys.maxint)
- maxMem=0.0
-
- entries=0
- sumCPU=0.0
- sumMem=0.0
-
- #
- # Create outputfile
- #
- cpuslice = open(cpuSliceFile,"w")
- for line in logFile:
- data = line.split()
- #
- # //fixme remove tz addition.
- #
- lineTime = lineToDate(" ".join(data[0:2])+" +0000")
-
- if lineTime > start:
- if lineTime < end:
- # Write the data though to the new file
- cpuslice.writelines(line)
-
- # Perform stat processing for the min/max/avg
-
- data = line.split()
-
- #
- # Data format is
- # <Date> <Time> <%CPU> <%MEM>
- # 2010-02-19 10:16:17 157 28.1
- #
- cpuIndex = 2
- memIndex = 3
-
- # Record entires
- entries = entries + 1
-
- # Record Metrics
- # Record CPU data
- cpu = float(data[cpuIndex])
- if (cpu < minCPU):
- minCPU = cpu
-
- if (cpu > maxCPU):
- maxCPU = cpu
-
- sumCPU = sumCPU + cpu
-
- # Record Mem data
- mem = float(data[memIndex])
-
- if (mem < minMem):
- minMem = mem
-
- if (mem > maxMem):
- maxMem = mem
-
- sumMem = sumMem + mem
-
- logFile.close()
- cpuslice.close()
- log("Sliced CPU log")
-
- # Output stats file
- statFile=cpuSliceFile+".stats"
- output= open(statFile, "w")
- output.write("#type:min/max/avg")
- output.write('\n')
- output.write("CPU:"+str(minCPU)+"/"+str(maxCPU)+"/"+str(float(sumCPU)/float(entries)))
- output.write('\n')
- output.write("MEM:"+str(minMem)+"/"+str(maxMem)+"/"+str(float(sumMem)/float(entries)))
- output.write('\n')
- output.close
-
- log("Generated stat data from CPU Log file")
-
-
-def sliceGCLog(resultDir, start, end):
- global _brokerLogs
- logfilePath=_brokerLogs+os.sep+BROKER_GC
- sliceFile=resultDir+os.sep+BROKER_GC
-
- gcstart = extractTime(ACCESS, logfilePath+".stat")
-
- # Open the output file, erasing any existing version
- # Keep track of the min/max sum and entries,.
- minGCDuration=float(sys.maxint)
- maxGCDuration=0.0
- sumGCDuration=0.0
- entriesGCDuration = 0
-
-
- # Open log GC file for reading
- logFile = open(logfilePath, "r")
-
- # Open the output file, erasing any existing version
- output= open(sliceFile, "w")
-
- # Use a regular expression to pull out the Seconds.Millis values from the
- # Start of the gc log line.
- pattern = re.compile(r'(?P<seconds>^[0-9]+)\.(?P<millis>[0-9]+):')
-
- for line in logFile:
- m = pattern.match(line)
-
- if m:
- seconds = m.group('seconds');
- millis = m.group('millis');
-
- offset = timedelta(seconds=int(seconds),milliseconds=int(millis))
-
- lineTime = gcstart + offset
-
- if lineTime > start:
- if lineTime < end:
- output.writelines(line)
- # Perform stat processing for the min/max/avg
-
- # Process GC Duration lines in ParNew gc ,
- # ensure we do not have CMS printed as that means the line line has been corrupted
- if line.find("ParNew") != -1 & line.find("CMS") == -1:
-
- #
- # Example data line
- # 7.646: [GC 7.646: [ParNew: 14778K->461K(14784K), 0.0026610 secs] 49879K->36609K(73288K), 0.0027560 secs] [Times: user=0.01 sys=0.00, real=0.01 secs]
- #
- # So entry 5 is the ParNew time and 8 is the whole GC cycle. 14 entries total
-
- data = line.split()
-
- gcTime = 0
- # Check we have a valid ParNew Line
- if (len(data) == 15):
-
- # Record entires
- # Record GC Duration data
-
- entriesGCDuration = entriesGCDuration + 1
- gcTime = float(data[8])
-
- if (gcTime < minGCDuration):
- minGCDuration = gcTime
-
- if (gcTime > maxGCDuration):
- maxGCDuration = gcTime
-
- sumGCDuration = sumGCDuration + gcTime
-
-
-
- # Close the files
- logFile.close
- output.close()
-
- log("Sliced gc log")
-
- # Output stats file
- statFile=sliceFile+".stats"
- output= open(statFile, "w")
- output.write("#type:min/max/avg")
- output.write('\n')
- #
- # Only provide GCDuration if it was processed
- #
- output.write("GC_DUR:%.14f/%.14f/%.14f" % (minGCDuration, maxGCDuration , (sumGCDuration/float(entriesGCDuration))))
- output.write('\n')
- output.close
-
- log("Generated stat data from CPU Log file")
-
-
-def sliceLog4j(resultDir, start, end):
- global _brokerLogs
- logfilePath=_brokerLogs+os.sep+BROKER_LOG
- log4jSliceFile=resultDir+os.sep+BROKER_LOG
-
- log4jstart = extractTime(ACCESS, logfilePath+".stat")
-
- #
- # Say that first line is the start of the file,
- # This value will give a time value to the initial
- # logging before Log4j kicks in.
- #
- lineTime = log4jstart
-
- # Process the broker log4j file
- # Open log CPU file for reading
- logFile = open(logfilePath, "r")
-
- #
- # Create outputfile
- #
- log4jslice = open(log4jSliceFile,"w")
-
- for line in logFile:
- data = line.split()
-
- #
- # If the line has a time at the start then process it
- # otherwise use the previous time. This means if there is
- # a stack trace in the middle of the log file then it will
- # be copied over to the split file as long as it is in the
- # split time.
- #
- if (hasTime(data)):
- #
- # //fixme remove tz addition.
- #
- lineTime = lineToDate(" ".join(data[0:2])+" +0000")
-
- if lineTime > start:
- if lineTime < end:
- print line
- log4jslice.writelines(line)
-
- logFile.close()
- log4jslice.close()
- log("Sliced broker log")
-
-
-#
-# Check the first two entries of data can make a datetime object
-#
-def hasTime(data):
- date = data[0]
- time = data[1]
-
- # Examples:
- # 2009-06-22 17:04:44,246
- # 2009-06-22 17:04:44.2464
- # 2009-06-22 17:04:44
-
- # ISO-8601 '-' format date
- dateRE = re.compile('[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]')
-
- #
- # Check for times with/out millis
- # e.g.
- # 10:00:00,000 - log4j
- # 10:00:00.0000 - generated in script for cpu time
- #
- timeRE = re.compile('[0-9][0-9]:[0-9][0-9]:[0-9][0-9]?[0-9]*')
-
- return dateRE.match(date) and timeRE.match(time)
-
-def createGraphData(resultDir, testName):
- # Create graph.data file for process.sh
- # Format two lines : Title and filename
- # $version $type : $volume% volume
- # $version-$brokerState-$type-$volume
- version=getBrokerVersion()
-
- test= extractTestValue("n",resultDir, testName)
- volume = int(float(extractTestResult("Test * Size Throughput", resultDir, testName)) * 1000)
- messageSize = extractTestValue("messageSize",resultDir, testName)
- ackMode = ackModeToString(extractTestValue("consAckMode",resultDir, testName))
-
- graphDataFile=resultDir+os.sep+GRAPH_DATA
-
- graphData = open(graphDataFile, "w")
-
- #
- # Write Title
- graphData.write(version+":"+test+":"+str(messageSize)+"kb x "+str(volume)+" msg/sec using "+ackMode)
- graphData.write('\n')
-
- #
- # Write FileName
- graphData.writelines(version+"-"+testName)
- graphData.write('\n')
- graphData.close
- log("Created graph.data")
-
-
-def getBrokerVersion():
- global _brokerLogs
- READY = "Qpid Broker Ready"
- brokerLogFile = _brokerLogs + os.sep + BROKER_LOG
-
- log = open(brokerLogFile, "r")
-
- dataLine = ""
- for line in log:
- if line.find(READY) != -1:
- dataLine = line
- break
-
- # Log Entry
- #2009-06-19 17:04:02,493 INFO [main] server.Main (Main.java:456) - Qpid Broker Ready :2.3.0.1 build: 727403M
- # Split on READY
- data = dataLine.split(READY)
-
- # So [1] should be
- # :2.3.0.1 build: 727403M
- readyEntries = data[1].split()
-
- # so spliting on white space should give us ':version'
- # and a quick split on ':' will give us the version
- version = readyEntries[0].split(':')[1]
-
- # Strip to ensure we have no whitespace
- return version.strip()
-
-
-def extractTestValue(property,resultDir,testName):
- return extractTestData(property,resultDir,testName," =")
-
-def extractTestResult(property,resultDir,testName):
- return extractTestData(property,resultDir,testName,":")
-
-def extractTestData(property,resultDir,testName,type):
- resultFile = resultDir + os.sep + testName+".csv"
-
- results = open(resultFile, "r")
-
- dataLine = ""
- for line in results:
- if line.find("Total Tests:") == 0:
- dataLine = line
-
- results.close()
-
- # Data is CSV
- data = dataLine.split(',')
-
- found = False
- result = ""
- searchProperty = property+type
-
- for entry in data:
- if found:
- result = entry
- break
- if entry.strip() == searchProperty:
- found=True
-
- return result.strip()
-
-def createTestStatData(resultDir, testName):
- csvFilePath=resultDir + os.sep + testName + ".csv"
-
- # Open the output file, erasing any existing version
- # Keep track of the min/max sum and entries,.
- minLatency=float(sys.maxint)
- maxLatency=0.0
- minThroughput=float(sys.maxint)
- maxThroughput=0.0
-
- entries=0
- sumLatency=0.0
- sumThroughput=0.0
-
- #
- # Open csv File
- #
- csvFile = open(csvFilePath,"r")
- for line in csvFile:
-
- # The PingAsyncTestPerf test class outputs the latency and throughput data.
- if line.find("PingAsyncTestPerf") != -1:
- #
- # Data format is
- # <Test> <TestName> <Thread> <Status> <Time> <Latency> <Concurrency> <Thread> <TestSize>
- #org.apache.qpid.ping.PingAsyncTestPerf, testAsyncPingOk, Dispatcher-Channel-1, Pass, 209.074, 219.706, 0, 1, 10
- LatencyIndex = 5
- ThroughputIndex = 4
-
- # The PingLatencyTestPerf test class just outputs the latency data.
- if line.find("PingLatencyTestPerf") != -1:
- #
- # Data format is
- # <Test> <TestName> <Thread> <Status> <Time> <Latency> <Concurrency> <Thread> <TestSize>
- # org.apache.qpid.ping.PingLatencyTestPerf, testPingLatency, Dispatcher-Channel-1, Pass, 397.05502, 0, 2, 1000
- LatencyIndex = 4
- ThroughputIndex = -1
-
-
- # Only process the test lines that have 'org.apache.qpid.ping', i.e. skip header and footer.
- if line.find("org.apache.qpid.ping") != -1:
- # Perform stat processing for the min/max/avg
- data = line.split(",")
-
- # Record entires
- entries = entries + 1
-
- # Record Metrics
- # Record Latency data
- latency = float(data[LatencyIndex])
- if (latency < minLatency):
- minLatency = latency
-
- if (latency > maxLatency):
- maxLatency = latency
-
- sumLatency = sumLatency + latency
-
- if (ThroughputIndex != -1):
- # Record Latency data
- throughput = float(data[ThroughputIndex])
- if (throughput < minThroughput):
- minThroughput = throughput
-
- if (throughput > maxThroughput):
- maxThroughput = throughput
-
- sumThroughput = sumThroughput + throughput
-
-
- csvFile.close()
-
- # Output stats file
- statFile=resultDir + os.sep + testName+".stats"
- output= open(statFile, "w")
- output.write("#type:min/max/avg")
- output.write('\n')
- output.write("LATENCY:"+str(minLatency)+"/"+str(maxLatency)+"/"+str(float(sumLatency)/float(entries)))
- output.write('\n')
-
- if (ThroughputIndex != -1):
- # Output msgs/sec based on time for a batch of msgs
- output.write("THROUGHPUT:"+str(float(1000)/maxThroughput)+"/"+str(float(1000)/minThroughput)+"/"+str(float(1000)/(float(sumThroughput)/float(entries))))
- output.write('\n')
-
- output.close
-
- log("Generated stat data from test "+testName+" CSV file")
-
-
-def ackModeToString(ackMode):
- if ackMode == '0':
- return "Transacted"
- elif ackMode == '1':
- return "AutoAck"
- elif ackMode == '2':
- return "ClientAck"
- elif ackMode == '3':
- return "DupsOK"
- elif ackMode == '257':
- return "NoAck"
- elif ackMode == '258':
- return "PreAck"
- else:
- return str(ackMode)
-
-
-
-def debug(msg):
- global _debug
- if _debug:
- log(msg)
-
-def log(msg):
- print msg
-
-def mkdir(dir):
- if not os.path.exists(dir):
- os.mkdir(dir)
-
-if __name__ == "__main__":
- main() \ No newline at end of file
diff --git a/java/perftests/bin/run_many.sh b/java/perftests/bin/run_many.sh
deleted file mode 100755
index cca2ffec21..0000000000
--- a/java/perftests/bin/run_many.sh
+++ /dev/null
@@ -1,30 +0,0 @@
-#!/bin/sh
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-#
-
-
-# args:
-# <number of processes to start>
-# <name of run>
-# <command ro run>
-
-for i in `seq 1 $1`; do
- $3 >$2.$i.out 2>>$2.err &
- echo $! > $2.$i.pid
-done;
diff --git a/java/perftests/bin/topicListener.sh b/java/perftests/bin/topicListener.sh
deleted file mode 100755
index 3a925910ad..0000000000
--- a/java/perftests/bin/topicListener.sh
+++ /dev/null
@@ -1,32 +0,0 @@
-#!/bin/bash
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-#
-
-
-# XXX -Xmx512m -Xms512m -XX:NewSize=150m
-QPID_LIBS=$QPID_HOME/lib/qpid-all.jar
-
-# Set other variables used by the qpid-run script before calling
-export JAVA=java \
- JAVA_VM=-server \
- JAVA_MEM="-Xmx128m -Dlog4j.configuration=$HOME/log4j.properties" \
- JAVA_GC="-XX:-UseConcMarkSweepGC -XX:+HeapDumpOnOutOfMemoryError" \
- QPID_CLASSPATH=$QPID_LIBS
-
-. qpid-run -Damqj.logging.level="INFO" org.apache.qpid.oldtopic.Listener $*
diff --git a/java/perftests/bin/topicPublisher.sh b/java/perftests/bin/topicPublisher.sh
deleted file mode 100755
index e4e9981a75..0000000000
--- a/java/perftests/bin/topicPublisher.sh
+++ /dev/null
@@ -1,31 +0,0 @@
-#!/bin/bash
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-#
-
-# XXX -Xmx512m -Xms512m -XX:NewSize=150m
-QPID_LIBS=$QPID_HOME/lib/qpid-all.jar
-
-# Set other variables used by the qpid-run script before calling
-export JAVA=java \
- JAVA_VM=-server \
- JAVA_MEM=-Xmx128m \
- JAVA_GC="-XX:-UseConcMarkSweepGC -XX:+HeapDumpOnOutOfMemoryError" \
- QPID_CLASSPATH=$QPID_LIBS
-
-. qpid-run -Damqj.logging.level="INFO" org.apache.qpid.oldtopic.Publisher $*
diff --git a/java/perftests/build.xml b/java/perftests/build.xml
deleted file mode 100644
index 497bfc8035..0000000000
--- a/java/perftests/build.xml
+++ /dev/null
@@ -1,339 +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.
- -
- -->
-<project name="Performance Tests" default="build">
-
- <property name="module.depends" value="systests client broker common common/test junit-toolkit"/>
-
- <import file="../module.xml"/>
-
- <property name="xms" value="-Xms256m"/>
- <property name="xmx" value="-Xmx1024m"/>
- <property name="test.logging.level" value="-Damqj.test.logging.level=info"/>
- <property name="qpid.logging.level" value="-Damqj.logging.level=warn"/>
- <property name="log4j.config" value="-Dlog4j.configuration=perftests.log4j"/>
- <property name="properties" value="perftests.properties"/>
- <property name="scripts.dir" value="${build.bin}/${module.name}"/>
-
- <condition property="results" value="${result-path}/results" else="${project.root}/${module}/results">
- <isset property="result-path"/>
- </condition>
-
- <property name="scripts.timestamp" location="${build.scratch}/perftests/scripts.timestamp" />
-
- <target name="check_scripts_uptodate">
- <uptodate property="scripts.notRequired" targetfile="${scripts.timestamp}">
- <srcfiles dir="${scripts.dir}" includes="**.sh" />
- <srcfiles dir="${project.root}/perftests/" includes="scripts.xml" />
- </uptodate>
- </target>
-
- <target name="precompile" depends="check_scripts_uptodate" unless="scripts.notRequired">
- <mkdir dir="${scripts.dir}"/>
- <jython path="${mllib.dir}">
- <args>
- <arg value="generate-scripts"/>
- <arg value="scripts.xml"/>
- <arg value="${scripts.dir}"/>
- </args>
- </jython>
- <touch file="${scripts.timestamp}" />
- </target>
-
- <target name="all-tests" depends="all-queue-tests,all-topic-tests"/>
-
- <target name="all-queue-tests" depends="Queue-Duration-Persistent,Queue-Concurrent,
- Queue-Duration,Queue-Latency,Queue-Duration-Transacted,Queue-LargeMessage-Persistent"/>
-
- <target name="all-topic-tests" depends="Topic-Concurrent,Topic-Duration,Topic-Latency,
- Topic-Duration-Transacted"/>
-
- <!-- Queue tests -->
-
- <!--
- Send 10000 (.5K) messages and measure the time for receiving 1000 messages (10 intervals)
- the overall latency is also calculated (See Test * Size Throughput)
- Note that "Test Throughput" is the average time for receiving 1000 messages
- -->
- <target name="Queue-Latency" depends="build" description="Run Queue-Latency">
- <java classname="org.apache.qpid.junit.extensions.TKTestRunner" fork="true">
- <classpath refid="module.test.path"/>
- <jvmarg value="${xms}"/>
- <jvmarg value="${xmx}"/>
- <jvmarg value="${test.logging.level}"/>
- <jvmarg value="${qpid.logging.level}"/>
- <jvmarg value="${log4j.config}"/>
- <!-- args -->
- <arg value="-n Queue-Latency"/>
- <arg value="-s[10000]"/>
- <arg value="-t testPingLatency"/>
- <arg value="-o${results}"/>
- <arg value="--csv"/>
- <arg value="org.apache.qpid.ping.PingLatencyTestPerf"/>
- <arg value="rate=100"/>
- <arg value="batchSize=1000"/>
- <arg value="messageSize=512"/>
- </java>
- </target>
-
- <!--
- Measure the time required for one producer/consumer pair
- for sending and receiving 10000 transient messages.
- The test last for 5 minutes.
- -->
- <target name="Queue-Duration" depends="build" description="">
- <java classname="org.apache.qpid.junit.extensions.TKTestRunner" fork="true">
- <classpath refid="module.test.path"/>
- <jvmarg value="${xms}"/>
- <jvmarg value="${xmx}"/>
- <jvmarg value="${test.logging.level}"/>
- <jvmarg value="${qpid.logging.level}"/>
- <jvmarg value="${log4j.config}"/>
- <!-- args -->
- <arg value="-d5M"/>
- <arg value="-n Queue-Duration"/>
- <arg value="-s[1000]"/>
- <arg value="-t testAsyncPingOk"/>
- <arg value="-o${results}"/>
- <arg value="--csv"/>
- <arg value="org.apache.qpid.ping.PingAsyncTestPerf"/>
- <arg value="messageSize=512"/>
- </java>
- </target>
-
- <!--
- Measure the time required for one producer/consumer pair
- for sending and receiving 10000 0.5K persistent messages.
- The test last for 5 minutes.
- -->
- <target name="Queue-Duration-Persistent" depends="build" description="">
- <java classname="org.apache.qpid.junit.extensions.TKTestRunner" fork="true">
- <classpath refid="module.test.path"/>
- <jvmarg value="${xms}"/>
- <jvmarg value="${xmx}"/>
- <jvmarg value="${test.logging.level}"/>
- <jvmarg value="${qpid.logging.level}"/>
- <jvmarg value="${log4j.config}"/>
- <!-- args -->
- <arg value="-d5M"/>
- <arg value="-n Queue-Duration-Persistent"/>
- <arg value="-s[1000]"/>
- <arg value="-t testAsyncPingOk"/>
- <arg value="-o${results}"/>
- <arg value="--csv"/>
- <arg value="org.apache.qpid.ping.PingAsyncTestPerf"/>
- <arg value="persistent=true"/>
- <arg value="messageSize=512"/>
- </java>
- </target>
-
- <!--
- Measure the time required for one producer/consumer pair
- for sending and receiving 10000 100K persistent messages.
- The test last for 5 minutes.
- -->
- <target name="Queue-LargeMessage-Persistent" depends="build" description="">
- <java classname="org.apache.qpid.junit.extensions.TKTestRunner" fork="true">
- <classpath refid="module.test.path"/>
- <jvmarg value="${xms}"/>
- <jvmarg value="${xmx}"/>
- <jvmarg value="${test.logging.level}"/>
- <jvmarg value="${qpid.logging.level}"/>
- <jvmarg value="${log4j.config}"/>
- <!-- args -->
- <arg value="-d5M"/>
- <arg value="-n Queue-LargeMessage-Persistent"/>
- <arg value="-s[1000]"/>
- <arg value="-t testAsyncPingOk"/>
- <arg value="-o${results}"/>
- <arg value="--csv"/>
- <arg value="org.apache.qpid.ping.PingAsyncTestPerf"/>
- <arg value="persistent=true"/>
- <arg value="messageSize=102400"/>
- </java>
- </target>
-
- <!--
- Measure the time required for one (transacted producer)/(Transacted consumer) pair
- for sending and receiving 10000 (0.5K) persistent messages.
- Tx batch size is 100 (consumer and producer)
- The test last for 5 minutes.
- -->
- <target name="Queue-Duration-Transacted" depends="build" description="">
- <java classname="org.apache.qpid.junit.extensions.TKTestRunner" fork="true">
- <classpath refid="module.test.path"/>
- <jvmarg value="${xms}"/>
- <jvmarg value="${xmx}"/>
- <jvmarg value="${test.logging.level}"/>
- <jvmarg value="${qpid.logging.level}"/>
- <jvmarg value="${log4j.config}"/>
- <!-- args -->
- <arg value="-d5M"/>
- <arg value="-n Queue-Duration-Transacted"/>
- <arg value="-s[1000]"/>
- <arg value="-t testAsyncPingOk"/>
- <arg value="-o${results}"/>
- <arg value="--csv"/>
- <arg value="org.apache.qpid.ping.PingAsyncTestPerf"/>
- <arg value="persistent=true"/>
- <arg value="transacted=true"/>
- <arg value="batchSize=100"/>
- <arg value="consTransacted=true"/>
- <arg value="commitBatchSize=100"/>
- <arg value="messageSize=512"/>
- </java>
- </target>
-
- <!--
- Measure the time for four concurrent producer/receiver pairs to send and receive 1000 transient messages
- -->
- <target name="Queue-Concurrent" depends="build" description="">
- <java classname="org.apache.qpid.junit.extensions.TKTestRunner" fork="true">
- <classpath refid="module.test.path"/>
- <jvmarg value="${xms}"/>
- <jvmarg value="${xmx}"/>
- <jvmarg value="${test.logging.level}"/>
- <jvmarg value="${qpid.logging.level}"/>
- <jvmarg value="${log4j.config}"/>
- <!-- args -->
- <arg value="-r1"/>
- <arg value="-n Queue-Concurrent"/>
- <arg value="-s[1000]"/>
- <arg value="-c[4]"/>
- <arg value="-t testAsyncPingOk"/>
- <arg value="-o${results}"/>
- <arg value="--csv"/>
- <arg value="org.apache.qpid.ping.PingAsyncTestPerf"/>
- <arg value="messageSize=512"/>
- </java>
- </target>
-
-
- <!-- Topic tests -->
-
- <!--
- Send 10000 (.5K) messages and measure the time for receiving 1000 messages (10 intervals)
- the overall latency is also calculated (See Test * Size Throughput)
- Note that "Test Throughput" is the average time for receiving 1000 messages
- -->
- <target name="Topic-Latency" depends="build" description="Run Queue-Latency">
- <java classname="org.apache.qpid.junit.extensions.TKTestRunner" fork="true">
- <classpath refid="module.test.path"/>
- <jvmarg value="${xms}"/>
- <jvmarg value="${xmx}"/>
- <jvmarg value="${test.logging.level}"/>
- <jvmarg value="${qpid.logging.level}"/>
- <jvmarg value="${log4j.config}"/>
- <!-- args -->
- <arg value="-n Topic-Latency"/>
- <arg value="-s[10000]"/>
- <arg value="-t testPingLatency"/>
- <arg value="-o${results}"/>
- <arg value="--csv"/>
- <arg value="org.apache.qpid.ping.PingLatencyTestPerf"/>
- <arg value="rate=100"/>
- <arg value="batchSize=1000"/>
- <arg value="messageSize=512"/>
- <arg value="pubsub=true"/>
- </java>
- </target>
-
- <!--
- Measure the time required for one producer/consumer pair
- for sending and receiving 10000 transient messages.
- The test last for 5 minutes.
- -->
- <target name="Topic-Duration" depends="build" description="">
- <java classname="org.apache.qpid.junit.extensions.TKTestRunner" fork="true">
- <classpath refid="module.test.path"/>
- <jvmarg value="${xms}"/>
- <jvmarg value="${xmx}"/>
- <jvmarg value="${test.logging.level}"/>
- <jvmarg value="${qpid.logging.level}"/>
- <jvmarg value="${log4j.config}"/>
- <!-- args -->
- <arg value="-d5M"/>
- <arg value="-n Topic-Duration"/>
- <arg value="-s[1000]"/>
- <arg value="-t testAsyncPingOk"/>
- <arg value="-o${results}"/>
- <arg value="--csv"/>
- <arg value="org.apache.qpid.ping.PingAsyncTestPerf"/>
- <arg value="messageSize=512"/>
- <arg value="pubsub=true"/>
- </java>
- </target>
-
- <!--
- Measure the time required for one (transacted producer)/(Transacted consumer) pair
- for sending and receiving 10000 (0.5K) persistent messages.
- Tx batch size is 100 (consumer and producer)
- The test last for 5 minutes.
- -->
- <target name="Topic-Duration-Transacted" depends="build" description="">
- <java classname="org.apache.qpid.junit.extensions.TKTestRunner" fork="true">
- <classpath refid="module.test.path"/>
- <jvmarg value="${xms}"/>
- <jvmarg value="${xmx}"/>
- <jvmarg value="${test.logging.level}"/>
- <jvmarg value="${qpid.logging.level}"/>
- <jvmarg value="${log4j.config}"/>
- <!-- args -->
- <arg value="-d5M"/>
- <arg value="-n Topic-Duration-Transacted"/>
- <arg value="-s[1000]"/>
- <arg value="-t testAsyncPingOk"/>
- <arg value="-o${results}"/>
- <arg value="--csv"/>
- <arg value="org.apache.qpid.ping.PingAsyncTestPerf"/>
- <arg value="persistent=true"/>
- <arg value="transacted=true"/>
- <arg value="batchSize=100"/>
- <arg value="consTransacted=true"/>
- <arg value="commitBatchSize=100"/>
- <arg value="messageSize=512"/>
- </java>
- </target>
-
- <!--
- Measure the time for four concurrent producer/receiver pairs to send and receive 1000 transient messages
- -->
- <target name="Topic-Concurrent" depends="build" description="">
- <java classname="org.apache.qpid.junit.extensions.TKTestRunner" fork="true">
- <classpath refid="module.test.path"/>
- <jvmarg value="${xms}"/>
- <jvmarg value="${xmx}"/>
- <jvmarg value="${test.logging.level}"/>
- <jvmarg value="${qpid.logging.level}"/>
- <jvmarg value="${log4j.config}"/>
- <!-- args -->
- <arg value="-r1"/>
- <arg value="-n Topic-Concurrent"/>
- <arg value="-s[1000]"/>
- <arg value="-c[4]"/>
- <arg value="-t testAsyncPingOk"/>
- <arg value="-o${results}"/>
- <arg value="--csv"/>
- <arg value="org.apache.qpid.ping.PingAsyncTestPerf"/>
- <arg value="messageSize=512"/>
- </java>
- </target>
-
-</project>
diff --git a/java/perftests/dist-zip.xml b/java/perftests/dist-zip.xml
deleted file mode 100644
index 0039bfb157..0000000000
--- a/java/perftests/dist-zip.xml
+++ /dev/null
@@ -1,45 +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 is an assembly descriptor that produces a zip containing all the test scripts and
- the all dependencies jar. -->
-<assembly>
- <id>perftests</id>
- <formats>
- <format>zip</format>
- <format>tar.gz</format>
- </formats>
- <includeBaseDirectory>false</includeBaseDirectory>
- <fileSets>
- <fileSet>
- <directory>target</directory>
- <outputDirectory>PerformanceTests</outputDirectory>
- <includes>
- <include>qpid-perftests-${qpid.version}-all-test-deps.jar</include>
- <include>*.sh</include>
- </includes>
- </fileSet>
- <fileSet>
- <directory>etc/scripts</directory>
- <outputDirectory>PerformanceTests</outputDirectory>
- <includes>
- <include>*.sh</include>
- </includes>
- </fileSet>
- </fileSets>
-</assembly>
diff --git a/java/perftests/etc/jndi/activemq.properties b/java/perftests/etc/jndi/activemq.properties
deleted file mode 100644
index 281577c4a8..0000000000
--- a/java/perftests/etc/jndi/activemq.properties
+++ /dev/null
@@ -1,20 +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.
-
-java.naming.factory.initial = org.apache.activemq.jndi.ActiveMQInitialContextFactory
-java.naming.provider.url= tcp://localhost:61616
-
diff --git a/java/perftests/etc/jndi/failovertest.properties b/java/perftests/etc/jndi/failovertest.properties
deleted file mode 100644
index b437d12062..0000000000
--- a/java/perftests/etc/jndi/failovertest.properties
+++ /dev/null
@@ -1,19 +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.
-
-java.naming.factory.initial = org.apache.qpid.jndi.PropertiesFileInitialContextFactory
-connectionfactory.local = amqp://guest:guest@clientid/test?brokerlist='tcp://localhost:5001;tcp://localhost:5002'
diff --git a/java/perftests/etc/jndi/perftests.properties b/java/perftests/etc/jndi/perftests.properties
deleted file mode 100644
index a2348f4547..0000000000
--- a/java/perftests/etc/jndi/perftests.properties
+++ /dev/null
@@ -1,19 +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.
-
-java.naming.factory.initial = org.apache.qpid.jndi.PropertiesFileInitialContextFactory
-connectionfactory.local = amqp://guest:guest@clientid/test?brokerlist='tcp://localhost:5672'
diff --git a/java/perftests/etc/jndi/swiftmq.properties b/java/perftests/etc/jndi/swiftmq.properties
deleted file mode 100644
index 2d037a2513..0000000000
--- a/java/perftests/etc/jndi/swiftmq.properties
+++ /dev/null
@@ -1,20 +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.
-
-java.naming.factory.initial = com.swiftmq.jndi.InitialContextFactoryImpl
-java.naming.provider.url=smqp://localhost:4001/timeout=10000
-#connectionfactory.local = amqp://guest:guest@clientid/test?brokerlist='tcp://localhost:5672'
diff --git a/java/perftests/etc/perftests.log4j b/java/perftests/etc/perftests.log4j
deleted file mode 100644
index af8c1b0784..0000000000
--- a/java/perftests/etc/perftests.log4j
+++ /dev/null
@@ -1,46 +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.
-#
-log4j.rootLogger=${root.logging.level}
-
-
-log4j.logger.org.apache.mina=${amqj.logging.level}
-
-log4j.logger.org.apache.qpid=${amqj.logging.level}, console
-log4j.additivity.org.apache.qpid=false
-
-log4j.logger.org.apache.qpid.requestreply=${amqj.test.logging.level}
-log4j.logger.org.apache.qpid.pingpong=${amqj.test.logging.level}
-log4j.logger.org.apache.qpid.ping=${amqj.test.logging.level}
-log4j.logger.org.apache.qpid.topic=${amqj.test.logging.level}
-
-log4j.logger.org.apache.qpid.junit.extensions=${badger.level}, console
-log4j.additivity.org.apache.qpid.junit.extensions=false
-
-log4j.appender.console=org.apache.log4j.ConsoleAppender
-log4j.appender.console.Threshold=all
-log4j.appender.console.layout=org.apache.log4j.PatternLayout
-
-log4j.appender.console.layout.ConversionPattern=%t %d %p [%c{4}] %m%n
-#log4j.appender.console.layout.ConversionPattern=%t %p [%c] %m%n
-
-log4j.appender.fileApp=org.apache.log4j.FileAppender
-log4j.appender.fileApp.file=${log.dir}/perftests.volumetest.log
-log4j.appender.fileApp.Threshold=info
-log4j.appender.fileApp.append=false
-log4j.appender.fileApp.layout=org.apache.log4j.PatternLayout
diff --git a/java/perftests/etc/scripts/CTQ-Qpid-1.sh b/java/perftests/etc/scripts/CTQ-Qpid-1.sh
deleted file mode 100755
index 057dec5c63..0000000000
--- a/java/perftests/etc/scripts/CTQ-Qpid-1.sh
+++ /dev/null
@@ -1,21 +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.
-#
-
-./PQ-Qpid-1.sh $@ & ./PQ-Qpid-1-P.sh $@
diff --git a/java/perftests/etc/scripts/CTQ-Qpid-2.sh b/java/perftests/etc/scripts/CTQ-Qpid-2.sh
deleted file mode 100755
index 08057cbf44..0000000000
--- a/java/perftests/etc/scripts/CTQ-Qpid-2.sh
+++ /dev/null
@@ -1,21 +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.
-#
-
-./PQ-Qpid-2.sh $@ & ./PQ-Qpid-2-P.sh $@
diff --git a/java/perftests/etc/scripts/CTQ-Qpid-3.sh b/java/perftests/etc/scripts/CTQ-Qpid-3.sh
deleted file mode 100755
index 0bb7e25197..0000000000
--- a/java/perftests/etc/scripts/CTQ-Qpid-3.sh
+++ /dev/null
@@ -1,21 +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.
-#
-
-./PQ-Qpid-3.sh $@ & ./PQ-Qpid-3-P.sh $@
diff --git a/java/perftests/etc/scripts/CTQ-Qpid-4.sh b/java/perftests/etc/scripts/CTQ-Qpid-4.sh
deleted file mode 100755
index 278e44d12b..0000000000
--- a/java/perftests/etc/scripts/CTQ-Qpid-4.sh
+++ /dev/null
@@ -1,21 +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.
-#
-
-./PQ-Qpid-4.sh $@ & ./PQ-Qpid-4-P.sh $@
diff --git a/java/perftests/etc/scripts/CTQ-Qpid-5.sh b/java/perftests/etc/scripts/CTQ-Qpid-5.sh
deleted file mode 100755
index 5dee0176b2..0000000000
--- a/java/perftests/etc/scripts/CTQ-Qpid-5.sh
+++ /dev/null
@@ -1,21 +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.
-#
-
-./PQ-Qpid-5.sh $@ & ./PQ-Qpid-5-P.sh $@
diff --git a/java/perftests/etc/scripts/CTQ-Qpid-6.sh b/java/perftests/etc/scripts/CTQ-Qpid-6.sh
deleted file mode 100755
index b9996da77d..0000000000
--- a/java/perftests/etc/scripts/CTQ-Qpid-6.sh
+++ /dev/null
@@ -1,21 +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.
-#
-
-./PQ-Qpid-6.sh $@ & ./PQ-Qpid-6-P.sh $@
diff --git a/java/perftests/etc/scripts/Connections.sh b/java/perftests/etc/scripts/Connections.sh
deleted file mode 100755
index 17e69166bf..0000000000
--- a/java/perftests/etc/scripts/Connections.sh
+++ /dev/null
@@ -1,20 +0,0 @@
-#!/bin/sh
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-#
-find . -regex '\.\/[P|T].CT-.*\.sh' -exec {} -o results-Connections/ --csv \;
diff --git a/java/perftests/etc/scripts/JobQueue.sh b/java/perftests/etc/scripts/JobQueue.sh
deleted file mode 100755
index 312037f5ab..0000000000
--- a/java/perftests/etc/scripts/JobQueue.sh
+++ /dev/null
@@ -1,20 +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.
-#
-find . -regex '.*BL-.*\.sh' -exec {} -o results-JobQueue/ --csv \;
diff --git a/java/perftests/etc/scripts/Latency.sh b/java/perftests/etc/scripts/Latency.sh
deleted file mode 100755
index f70131de38..0000000000
--- a/java/perftests/etc/scripts/Latency.sh
+++ /dev/null
@@ -1,21 +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.
-#
-
-find . -regex '\.\/[P|T].CL-.*\.sh' -exec {} -o results-Latency/ --csv \;
diff --git a/java/perftests/etc/scripts/MessageSize.sh b/java/perftests/etc/scripts/MessageSize.sh
deleted file mode 100755
index bb10822257..0000000000
--- a/java/perftests/etc/scripts/MessageSize.sh
+++ /dev/null
@@ -1,20 +0,0 @@
-#!/bin/sh
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-#
-find . -regex '.*M-Qpid-.*\.sh' -exec {} -o results-messageSize/ --csv $* \;
diff --git a/java/perftests/etc/scripts/PT-Qpid-13.sh b/java/perftests/etc/scripts/PT-Qpid-13.sh
deleted file mode 100755
index df35f718b9..0000000000
--- a/java/perftests/etc/scripts/PT-Qpid-13.sh
+++ /dev/null
@@ -1,42 +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.
-#
-
-# Parse arguements taking all - prefixed args as JAVA_OPTS
-for arg in "$@"; do
- if [[ $arg == -java:* ]]; then
- JAVA_OPTS="${JAVA_OPTS}-`echo $arg|cut -d ':' -f 2` "
- else
- ARGS="${ARGS}$arg "
- fi
-done
-
-echo "Starting 6 parallel tests"
-java -Xms256m -Dlog4j.configuration=perftests.log4j -Xmx3072m -Dbadger.level=warn -Damqj.test.logging.level=info -Damqj.logging.level=warn ${JAVA_OPTS} -cp qpid-perftests-1.0-incubating-M2-SNAPSHOT-all-test-deps.jar org.apache.qpid.junit.extensions.TKTestRunner -n PT-Qpid-13.1 -s [250] -c[200] -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf pubsub=true messageSize=256 destinationName=newd1 uniqueDests=true batchSize=250 transacted=true commitBatchSize=50 -o $QPID_WORK/results ${ARGS} &
-
-java -Xms256m -Dlog4j.configuration=perftests.log4j -Xmx3072m -Dbadger.level=warn -Damqj.test.logging.level=info -Damqj.logging.level=warn ${JAVA_OPTS} -cp qpid-perftests-1.0-incubating-M2-SNAPSHOT-all-test-deps.jar org.apache.qpid.junit.extensions.TKTestRunner -n PT-Qpid-13.2 -s [250] -c[200] -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf pubsub=true messageSize=256 destinationName=newd2 uniqueDests=true batchSize=250 transacted=true commitBatchSize=50 -o $QPID_WORK/results ${ARGS} &
-
-java -Xms256m -Dlog4j.configuration=perftests.log4j -Xmx3072m -Dbadger.level=warn -Damqj.test.logging.level=info -Damqj.logging.level=warn ${JAVA_OPTS} -cp qpid-perftests-1.0-incubating-M2-SNAPSHOT-all-test-deps.jar org.apache.qpid.junit.extensions.TKTestRunner -n PT-Qpid-13.3 -s [250] -c[200] -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf pubsub=true messageSize=256 destinationName=newd3 uniqueDests=true batchSize=250 transacted=true commitBatchSize=50 -o $QPID_WORK/results ${ARGS} &
-
-java -Xms256m -Dlog4j.configuration=perftests.log4j -Xmx3072m -Dbadger.level=warn -Damqj.test.logging.level=info -Damqj.logging.level=warn ${JAVA_OPTS} -cp qpid-perftests-1.0-incubating-M2-SNAPSHOT-all-test-deps.jar org.apache.qpid.junit.extensions.TKTestRunner -n PT-Qpid-13.4 -s [250] -c[200] -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf pubsub=true messageSize=256 destinatioNname=newd4 uniqueDests=true batchSize=250 transacted=true commitBatchSize=50 -o $QPID_WORK/results ${ARGS} &
-
-java -Xms256m -Dlog4j.configuration=perftests.log4j -Xmx3072m -Dbadger.level=warn -Damqj.test.logging.level=info -Damqj.logging.level=warn ${JAVA_OPTS} -cp qpid-perftests-1.0-incubating-M2-SNAPSHOT-all-test-deps.jar org.apache.qpid.junit.extensions.TKTestRunner -n PT-Qpid-13.5 -s [250] -c[100] -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf pubsub=true messageSize=256 destinationName=newd5 uniqueDests=true batchSize=250 transacted=true commitBatchSize=50 -o $QPID_WORK/results ${ARGS} &
-
-java -Xms256m -Dlog4j.configuration=perftests.log4j -Xmx3072m -Dbadger.level=warn -Damqj.test.logging.level=info -Damqj.logging.level=warn ${JAVA_OPTS} -cp qpid-perftests-1.0-incubating-M2-SNAPSHOT-all-test-deps.jar org.apache.qpid.junit.extensions.TKTestRunner -n PT-Qpid-13.6 -s [250] -c[100] -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf pubsub=true messageSize=256 destinationName=newd6 uniqueDests=true batchSize=250 transacted=true commitBatchSize=50 -o $QPID_WORK/results ${ARGS}
-
diff --git a/java/perftests/etc/scripts/PT-Qpid-14.sh b/java/perftests/etc/scripts/PT-Qpid-14.sh
deleted file mode 100755
index ff5b8a76f9..0000000000
--- a/java/perftests/etc/scripts/PT-Qpid-14.sh
+++ /dev/null
@@ -1,41 +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.
-#
-
-# Parse arguements taking all - prefixed args as JAVA_OPTS
-for arg in "$@"; do
- if [[ $arg == -java:* ]]; then
- JAVA_OPTS="${JAVA_OPTS}-`echo $arg|cut -d ':' -f 2` "
- else
- ARGS="${ARGS}$arg "
- fi
-done
-echo "Starting 6 parallel tests"
-
-java -Xms256m -Dlog4j.configuration=perftests.log4j -Xmx3072m -Dbadger.level=warn -Damqj.test.logging.level=info -Damqj.logging.level=warn ${JAVA_OPTS} -cp qpid-perftests-1.0-incubating-M2-SNAPSHOT-all-test-deps.jar org.apache.qpid.junit.extensions.TKTestRunner -n PT-Qpid-14 -s [250] -c[200] -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf pubsub=true messageSize=256 destinationName=ping1 batchSize=250 -o $QPID_WORK/results ${ARGS} &
-
-java -Xms256m -Dlog4j.configuration=perftests.log4j -Xmx3072m -Dbadger.level=warn -Damqj.test.logging.level=info -Damqj.logging.level=warn ${JAVA_OPTS} -cp qpid-perftests-1.0-incubating-M2-SNAPSHOT-all-test-deps.jar org.apache.qpid.junit.extensions.TKTestRunner -n PT-Qpid-14 -s [250] -c[200] -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf pubsub=true messageSize=256 destinationName=ping2 batchSize=250 -o $QPID_WORK/results ${ARGS} &
-
-java -Xms256m -Dlog4j.configuration=perftests.log4j -Xmx3072m -Dbadger.level=warn -Damqj.test.logging.level=info -Damqj.logging.level=warn ${JAVA_OPTS} -cp qpid-perftests-1.0-incubating-M2-SNAPSHOT-all-test-deps.jar org.apache.qpid.junit.extensions.TKTestRunner -n PT-Qpid-14 -s [250] -c[200] -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf pubsub=true messageSize=256 destinationName=ping3 batchSize=250 -o $QPID_WORK/results ${ARGS} &
-
-java -Xms256m -Dlog4j.configuration=perftests.log4j -Xmx3072m -Dbadger.level=warn -Damqj.test.logging.level=info -Damqj.logging.level=warn ${JAVA_OPTS} -cp qpid-perftests-1.0-incubating-M2-SNAPSHOT-all-test-deps.jar org.apache.qpid.junit.extensions.TKTestRunner -n PT-Qpid-14 -s [250] -c[200] -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf pubsub=true messageSize=256destinationname=ping4 batchSize=250 -o $QPID_WORK/results ${ARGS} &
-
-java -Xms256m -Dlog4j.configuration=perftests.log4j -Xmx3072m -Dbadger.level=warn -Damqj.test.logging.level=info -Damqj.logging.level=warn ${JAVA_OPTS} -cp qpid-perftests-1.0-incubating-M2-SNAPSHOT-all-test-deps.jar org.apache.qpid.junit.extensions.TKTestRunner -n PT-Qpid-14 -s [250] -c[100] -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf pubsub=true messageSize=256 destinationName=ping5 batchSize=250 -o $QPID_WORK/results ${ARGS} &
-
-java -Xms256m -Dlog4j.configuration=perftests.log4j -Xmx3072m -Dbadger.level=warn -Damqj.test.logging.level=info -Damqj.logging.level=warn ${JAVA_OPTS} -cp qpid-perftests-1.0-incubating-M2-SNAPSHOT-all-test-deps.jar org.apache.qpid.junit.extensions.TKTestRunner -n PT-Qpid-14 -s [250] -c[100] -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf pubsub=true messageSize=256 destinationName=ping6 batchSize=250 -o $QPID_WORK/results ${ARGS}
diff --git a/java/perftests/etc/scripts/Reliability.sh b/java/perftests/etc/scripts/Reliability.sh
deleted file mode 100755
index 9e5e508743..0000000000
--- a/java/perftests/etc/scripts/Reliability.sh
+++ /dev/null
@@ -1,20 +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.
-#
-find . -regex '.*R-Qpid-0[1-8].*\.sh' -exec {} -o results-Reliability/ --csv \;
diff --git a/java/perftests/etc/scripts/RunAll.sh b/java/perftests/etc/scripts/RunAll.sh
deleted file mode 100755
index 8b0d8b6e7c..0000000000
--- a/java/perftests/etc/scripts/RunAll.sh
+++ /dev/null
@@ -1,23 +0,0 @@
-#!/bin/sh
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-#
-./RunCore.sh
-./Connections.sh
-./JobQueue.sh
-./MessageSize.sh
diff --git a/java/perftests/etc/scripts/RunCore.sh b/java/perftests/etc/scripts/RunCore.sh
deleted file mode 100755
index fcc45aacf0..0000000000
--- a/java/perftests/etc/scripts/RunCore.sh
+++ /dev/null
@@ -1,22 +0,0 @@
-#!/bin/sh
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-#
-./Throughput.sh
-./Latency.sh
-./Reliability.sh
diff --git a/java/perftests/etc/scripts/Test-ActiveMQ.sh b/java/perftests/etc/scripts/Test-ActiveMQ.sh
deleted file mode 100644
index 27e0411870..0000000000
--- a/java/perftests/etc/scripts/Test-ActiveMQ.sh
+++ /dev/null
@@ -1,32 +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.
-#
-
-# Parse arguements taking all - prefixed args as JAVA_OPTS
-for arg in "$@"; do
- if [[ $arg == -java:* ]]; then
- JAVA_OPTS="${JAVA_OPTS}-`echo $arg|cut -d ':' -f 2` "
- else
- ARGS="${ARGS}$arg "
- fi
-done
-
-java -Xms256m -Dlog4j.configuration=perftests.log4j -Xmx1024m -Dbadger.level=warn -Damqj.test.logging.level=info -Damqj.logging.level=warn ${JAVA_OPTS} -cp "qpid-perftests-1.0-incubating-M2.1-SNAPSHOT.jar;activemq-jars/apache-activemq-4.1.1.jar" org.apache.qpid.junit.extensions.TKTestRunner -n Test-ActiveMQ -s[1] -r 1 -t testAsyncPingOk -o . org.apache.qpid.ping.PingAsyncTestPerf properties=activemq.properties factoryName=ConnectionFactory ${ARGS}
-
-# queueNamePostfix=@router1 overrideClientId=true
diff --git a/java/perftests/etc/scripts/Test-SwiftMQ.sh b/java/perftests/etc/scripts/Test-SwiftMQ.sh
deleted file mode 100644
index 1f0b38ccc2..0000000000
--- a/java/perftests/etc/scripts/Test-SwiftMQ.sh
+++ /dev/null
@@ -1,30 +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.
-#
-
-# Parse arguements taking all - prefixed args as JAVA_OPTS
-for arg in "$@"; do
- if [[ $arg == -java:* ]]; then
- JAVA_OPTS="${JAVA_OPTS}-`echo $arg|cut -d ':' -f 2` "
- else
- ARGS="${ARGS}$arg "
- fi
-done
-
-java -Xms256m -Dlog4j.configuration=perftests.log4j -Xmx1024m -Dbadger.level=warn -Damqj.test.logging.level=info -Damqj.logging.level=warn ${JAVA_OPTS} -cp "qpid-perftests-1.0-incubating-M2.1-SNAPSHOT.jar;swiftmqjars/swiftmq.jar" org.apache.qpid.junit.extensions.TKTestRunner -n Test-SwiftMQ -s[1] -r 1 -t testAsyncPingOk -o . org.apache.qpid.ping.PingAsyncTestPerf properties=swiftmq.properties factoryName=ConnectionFactory queueNamePostfix=@router1 overrideClientId=true ${ARGS}
diff --git a/java/perftests/etc/scripts/Throughput.sh b/java/perftests/etc/scripts/Throughput.sh
deleted file mode 100755
index d08ad248a5..0000000000
--- a/java/perftests/etc/scripts/Throughput.sh
+++ /dev/null
@@ -1,20 +0,0 @@
-#!/bin/sh
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-#
-find . -regex '.*[P|T].BT-.*\.sh' -exec {} -o results-throughput/ --csv $* \;
diff --git a/java/perftests/etc/scripts/drainBroker.sh b/java/perftests/etc/scripts/drainBroker.sh
deleted file mode 100755
index eea7209f03..0000000000
--- a/java/perftests/etc/scripts/drainBroker.sh
+++ /dev/null
@@ -1,41 +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.
-#
-
-if [ -z "$QPID_HOME" ]; then
- export QPID_HOME=$(dirname $(dirname $(dirname $(readlink -f $0))))
- export PATH=${PATH}:${QPID_HOME}/bin
-fi
-
-# Parse arguements taking all - prefixed args as JAVA_OPTS
-for arg in "$@"; do
- if [[ $arg == -java:* ]]; then
- JAVA_OPTS="${JAVA_OPTS}-`echo $arg|cut -d ':' -f 2` "
- else
- ARGS="${ARGS}$arg "
- fi
-done
-
-# Set classpath to include Qpid jar with all required jars in manifest
-QPID_LIBS=$QPID_HOME/lib/qpid-all.jar
-
-# Set other variables used by the qpid-run script before calling
-export JAVA=java JAVA_VM=-server JAVA_MEM=-Xmx1024m QPID_CLASSPATH=$QPID_LIBS
-
-. qpid-run -Xms256m -Dlog4j.configuration=file://${QPID_HOME}/etc/perftests.log4j -Dbadger.level=warn -Damqj.test.logging.level=info -Damqj.logging.level=warn org.apache.qpid.junit.extensions.TKTestRunner -n PQBT-TX-Qpid-01 -s[1000] -c[1] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=0 consumeOnly=true consumeOnly=true${ARGS}
diff --git a/java/perftests/etc/scripts/extractResults.sh b/java/perftests/etc/scripts/extractResults.sh
deleted file mode 100755
index 4fc74059af..0000000000
--- a/java/perftests/etc/scripts/extractResults.sh
+++ /dev/null
@@ -1,34 +0,0 @@
-#!/bin/bash +x
-#
-#
-# 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.
-#
-#
-
-#
-# Process a given directory (defaults to '.') and provide a list of the tests run so
-# identification of any failures can be seen.
-#
-
-if [ $# == 0 ] ; then
- dir=.
-else
- dir=$1
-fi
-
-grep 'Total Tests:' $dir/*Qpid* | sed -e 's/^.*\/\([A-Z\-]*-Qpid-[0-9]*\).*Total Tests:, \([0-9.]*\).*Total Passed:, \([0-9.]*\).*Total Failed:, \([0-9.]*\).*Total Error:, \([0-9.]*\).*$/\1, Total:\t\2,\tPassed:\t\3,\tFailed:\t\4,\tError:\t\5/'
diff --git a/java/perftests/etc/scripts/extractThroughputResults.sh b/java/perftests/etc/scripts/extractThroughputResults.sh
deleted file mode 100755
index 14236c68bc..0000000000
--- a/java/perftests/etc/scripts/extractThroughputResults.sh
+++ /dev/null
@@ -1,51 +0,0 @@
-#!/bin/bash +x
-#
-#
-# 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.
-#
-#
-
-#
-# Process a given directory (defaults to '.') and provides the throughput results as
-# reported by the tests.
-#
-# if a second argument of -n is provided then it will only list the number output for
-# easy copy/paste
-#
-
-if [ $# == 0 ] ; then
- dir=.
-else
- dir=$1
-fi
-
-numeric=0
-if [ "$dir" == "-n" ] ; then
- numeric=1
- dir=.
-fi
-
-if [ "$2" == "-n" ] ; then
- numeric=1
-fi
-
-if [ $numeric == 1 ] ; then
- grep 'Total Tests:' $dir/*Qpid* | sed -e 's/^.*\/\([A-Z]*-[A-Z][A-Z]-Qpid-01\).*Size Throughput:, \([0-9.]*\).*$/\1, \2/' | sed -e 's/\.\([0-9][0-9][0-9]\)/\1\./' | sed -e 's/, 0/, /' | awk '{print $2}'
-else
- grep 'Total Tests:' $dir/*Qpid* | sed -e 's/^.*\/\([A-Z]*-[A-Z][A-Z]-Qpid-01\).*Size Throughput:, \([0-9.]*\).*$/\1, \2/' | sed -e 's/\.\([0-9][0-9][0-9]\)/\1\./' | sed -e 's/, 0/, /'
-fi
diff --git a/java/perftests/etc/scripts/fillBroker.sh b/java/perftests/etc/scripts/fillBroker.sh
deleted file mode 100755
index 5b7de6f999..0000000000
--- a/java/perftests/etc/scripts/fillBroker.sh
+++ /dev/null
@@ -1,41 +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.
-#
-
-if [ -z "$QPID_HOME" ]; then
- export QPID_HOME=$(dirname $(dirname $(dirname $(readlink -f $0))))
- export PATH=${PATH}:${QPID_HOME}/bin
-fi
-
-# Parse arguements taking all - prefixed args as JAVA_OPTS
-for arg in "$@"; do
- if [[ $arg == -java:* ]]; then
- JAVA_OPTS="${JAVA_OPTS}-`echo $arg|cut -d ':' -f 2` "
- else
- ARGS="${ARGS}$arg "
- fi
-done
-
-# Set classpath to include Qpid jar with all required jars in manifest
-QPID_LIBS=$QPID_HOME/lib/qpid-all.jar
-
-# Set other variables used by the qpid-run script before calling
-export JAVA=java JAVA_VM=-server JAVA_MEM=-Xmx1024m QPID_CLASSPATH=$QPID_LIBS
-
-. qpid-run -Xms256m -Dlog4j.configuration=file://${QPID_HOME}/etc/perftests.log4j -Dbadger.level=warn -Damqj.test.logging.level=info -Damqj.logging.level=warn org.apache.qpid.junit.extensions.TKTestRunner -n PQBT-TX-Qpid-01 -s[1000] -c[1] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=0 transacted=true consTransacted=true consAckMode=0 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=0 ${ARGS}
diff --git a/java/perftests/etc/scripts/sendAndWaitClient.sh b/java/perftests/etc/scripts/sendAndWaitClient.sh
deleted file mode 100755
index af4b788658..0000000000
--- a/java/perftests/etc/scripts/sendAndWaitClient.sh
+++ /dev/null
@@ -1,22 +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.
-#
-#
-
-$JAVA_HOME/bin/java -Dlog4j.configuration=backup-log4j.xml -cp qpid-perftests-1.0-incubating-M2-SNAPSHOT-all-test-deps.jar org.apache.qpid.ping.PingSendOnlyClient messageSize=512
diff --git a/java/perftests/etc/scripts/testWithPreFill.sh b/java/perftests/etc/scripts/testWithPreFill.sh
deleted file mode 100755
index 721ecf6ecc..0000000000
--- a/java/perftests/etc/scripts/testWithPreFill.sh
+++ /dev/null
@@ -1,41 +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.
-#
-
-if [ -z "$QPID_HOME" ]; then
- export QPID_HOME=$(dirname $(dirname $(dirname $(readlink -f $0))))
- export PATH=${PATH}:${QPID_HOME}/bin
-fi
-
-# Parse arguements taking all - prefixed args as JAVA_OPTS
-for arg in "$@"; do
- if [[ $arg == -java:* ]]; then
- JAVA_OPTS="${JAVA_OPTS}-`echo $arg|cut -d ':' -f 2` "
- else
- ARGS="${ARGS}$arg "
- fi
-done
-
-# Set classpath to include Qpid jar with all required jars in manifest
-QPID_LIBS=$QPID_HOME/lib/qpid-all.jar
-
-# Set other variables used by the qpid-run script before calling
-export JAVA=java JAVA_VM=-server JAVA_MEM=-Xmx1024m QPID_CLASSPATH=$QPID_LIBS
-
-. qpid-run -Xms256m -Dlog4j.configuration=file://${QPID_HOME}/etc/perftests.log4j -Dbadger.level=warn -Damqj.test.logging.level=info -Damqj.logging.level=warn org.apache.qpid.junit.extensions.TKTestRunner -n PQBT-TX-Qpid-01 -s[1000] -c[1] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=0 preFill=1000 delayBeforeConsume=1000 ${ARGS}
diff --git a/java/perftests/generate-scripts b/java/perftests/generate-scripts
deleted file mode 100644
index 3d12cc13c3..0000000000
--- a/java/perftests/generate-scripts
+++ /dev/null
@@ -1,74 +0,0 @@
-#!/usr/bin/env python
-#
-# 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 os, sys, mllib
-
-template = """#!/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.
-#
-
-if [ -z "$QPID_HOME" ]; then
- export QPID_HOME=$(dirname $(dirname $(dirname $(readlink -f $0))))
- export PATH=${PATH}:${QPID_HOME}/bin
-fi
-
-# Parse arguements taking all - prefixed args as JAVA_OPTS
-for arg in "$@"; do
- if [[ $arg == -java:* ]]; then
- JAVA_OPTS="${JAVA_OPTS}-`echo $arg|cut -d ':' -f 2` "
- else
- ARGS="${ARGS}$arg "
- fi
-done
-
-# Set classpath to include Qpid jar with all required jars in manifest
-QPID_LIBS=$QPID_HOME/lib/qpid-all.jar
-
-# Set other variables used by the qpid-run script before calling
-export JAVA=java \
- JAVA_VM=-server \
- JAVA_MEM=-Xmx1024m \
- QPID_CLASSPATH=$QPID_LIBS
-
-. qpid-run -Xms256m -Dlog4j.configuration=file://${QPID_HOME}/etc/perftests.log4j -Dbadger.level=warn -Damqj.test.logging.level=info -Damqj.logging.level=warn org.apache.qpid.junit.extensions.TKTestRunner %s ${ARGS}
-"""
-
-doc = mllib.xml_parse(sys.argv[1])
-dir = sys.argv[2]
-for s in doc.query["scripts/script"]:
- file = open(os.path.join(dir, "%s.sh" % s["@name"]), "w")
- file.write(template % s.text())
- file.close()
diff --git a/java/perftests/jar-with-dependencies.xml b/java/perftests/jar-with-dependencies.xml
deleted file mode 100644
index bbbbd3788e..0000000000
--- a/java/perftests/jar-with-dependencies.xml
+++ /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.
--->
-<!-- This is an assembly descriptor that produces a distribution that contains all the
- dependencies, with a manifest only jar that references them, required to run the
- tests of a maven project.
--->
-<assembly>
- <id>all-test-deps</id>
- <formats>
- <format>tar.gz</format>
- <format>zip</format>
- </formats>
- <includeBaseDirectory>false</includeBaseDirectory>
- <dependencySets>
- <dependencySet>
- <outputDirectory>/</outputDirectory>
- <unpack>false</unpack>
- <scope>test</scope>
- </dependencySet>
- </dependencySets>
- <fileSets>
- <fileSet>
- <directory>target/classes</directory>
- <outputDirectory></outputDirectory>
- </fileSet>
- <fileSet>
- <directory>target/test-classes</directory>
- <outputDirectory></outputDirectory>
- </fileSet>
-
- <!-- Include all the test scripts, both generated and hand-written. -->
- <fileSet>
- <directory>target</directory>
- <outputDirectory></outputDirectory>
- <includes>
- <include>*.sh</include>
- </includes>
- </fileSet>
- <fileSet>
- <directory>etc/scripts</directory>
- <outputDirectory></outputDirectory>
- <includes>
- <include>*.sh</include>
- </includes>
- </fileSet>
-
- <!-- Include all jndi configurations needed to run the tests. -->
- <fileSet>
- <directory>etc/jndi</directory>
- <outputDirectory></outputDirectory>
- <includes>
- <include>*.properties</include>
- </includes>
- </fileSet>
-
- <!-- Include the build artifact. -->
- <fileSet>
- <directory>target</directory>
- <outputDirectory></outputDirectory>
- <includes>
- <include>qpid-perftests-1.0-incubating-M2-SNAPSHOT.jar</include>
- </includes>
- </fileSet>
-
- <!-- Include the manifest with classpath jar. -->
- <fileSet>
- <directory>target</directory>
- <outputDirectory></outputDirectory>
- <includes>
- <include>qpid-perftests-${qpid.version}.jar</include>
- </includes>
- </fileSet>
-
- </fileSets>
-</assembly>
diff --git a/java/perftests/scripts.xml b/java/perftests/scripts.xml
deleted file mode 100644
index 9a5163c598..0000000000
--- a/java/perftests/scripts.xml
+++ /dev/null
@@ -1,328 +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.
- -
- -->
-
-<scripts>
- <!-- Single pings. These can be scaled up by overriding the parameters when calling the test script. -->
- <script name="Ping-Once">-n Ping-Once -s[1] -r 1 -t testPingOk -o . org.apache.qpid.ping.PingTestPerf</script>
- <script name="Ping-Once-Async">-n Ping-Once-Async -s[1] -r 1 -t testAsyncPingOk -o . org.apache.qpid.ping.PingAsyncTestPerf</script>
- <script name="Ping-Latency">-n Ping-Latency -s[1000] -d10S -t testPingLatency -o . org.apache.qpid.ping.PingLatencyTestPerf rate=100 batchSize=100</script>
-
- <!-- More example Tests. These are examples to exercise all the features of the test harness. Can scale up with option overrides. -->
- <script name="Ping-Tx">-n Ping-Tx -s[100] -o . -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf transacted=true</script>
- <script name="Ping-Size">-n Ping-Size -s[100] -o . -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf messageSize=512</script>
- <script name="Ping-Concurrent">-n Ping-Concurrent -s[100] -c [4] -o . -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf</script>
- <script name="Ping-Many-Queues">-n Ping-Many-Queues -s[100] -o . -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf destinationCount=4</script>
- <script name="Ping-Duration">-n Ping-Duration -s[100] -d10S -o . -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf</script>
- <script name="Ping-Rate">-n Ping-Rate -s[100] -d10S -o . -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf rate=500</script>
- <script name="Ping-PubSub">-n Ping-PubSub -s[100] -o . -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf pubsub=true</script>
- <script name="Ping-Many-Topics">-n Ping-Many-Topics -s[100] -o . -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf pubsub=true destinationCount=4</script>
- <script name="Ping-Persistent">-n Ping-Persistent -s[100] -o . -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true</script>
- <script name="Ping-Batch-Logging">-n Ping-Batch-Logging -s[100] -o . -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf batchSize=10</script>
- <script name="Ping-Failover-Before-Send">-n Ping-Failover-Before-Send -s[100] -o . -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf commitBatchSize=10 failBeforeSend=true</script>
- <script name="Ping-Failover-After-Send">-n Ping-Failover-After-Send -s[100] -o . -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf commitBatchSize=10 failAfterSend=true</script>
- <script name="Ping-Failover-Before-Commit">-n Ping-Failover-Before-Commit -s[100] -o . -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf commitBatchSize=10 failBeforeCommit=true</script>
- <script name="Ping-Failover-After-Commit">-n Ping-Failover-After-Commit -s[100] -o . -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf commitBatchSize=10 failAfterCommit=true</script>
-
- <!--
- ***** If editing below, please use a non line wrapping mode and keep in columns, makes it easier to check for consistent
- ***** parameter setting accross all of the tests.
- -->
-
- <!--
- Reliability tests. The longer these tests can be run, the better.
- Tests 01 and 02 run for a short time. Use these to get an idea of the expected throughput.
- Tests 03 to 08 test all ack modes, transient/persistent, p2p/pubsub. There are 24 tests in total running for 1 hour each.
- This can be shortened or lengthened for the desired burn-in test time.
- -->
- <script name="TQR-Qpid-01">-n TQR-Qpid-01 -d1M -s[1000] -c[16] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </script>
- <script name="TQR-Qpid-02">-n TQR-Qpid-02 -d1M -s[1000] -c[16] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </script>
- <script name="TTR-Qpid-01">-n TTR-Qpid-01 -d1M -s[100] -c[2] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=8 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </script>
- <script name="TTR-Qpid-02">-n TTR-Qpid-02 -d1M -s[100] -c[2] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=8 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </script>
- <script name="PQR-Qpid-01">-n PQR-Qpid-01 -d1M -s[1000] -c[16] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </script>
- <script name="PQR-Qpid-02">-n PQR-Qpid-02 -d1M -s[1000] -c[16] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </script>
- <script name="PTR-Qpid-01">-n PTR-Qpid-01 -d1M -s[100] -c[2] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=8 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </script>
- <script name="PTR-Qpid-02">-n PTR-Qpid-02 -d1M -s[100] -c[2] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=8 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </script>
-
- <script name="TQR-Qpid-03-TX">-n TQR-Qpid-03 -d1H -s[10000] -c[16] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </script>
- <script name="TQR-Qpid-04-AUTOACK">-n TQR-Qpid-04 -d1H -s[10000] -c[16] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </script>
- <script name="TQR-Qpid-05-CLIENTACK">-n TQR-Qpid-05 -d1H -s[10000] -c[16] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=2 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </script>
- <script name="TQR-Qpid-06-DUPSOKACK">-n TQR-Qpid-06 -d1H -s[10000] -c[16] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=3 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </script>
- <script name="TQR-Qpid-07-NOACK">-n TQR-Qpid-07 -d1H -s[10000] -c[16] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=257 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </script>
- <script name="TQR-Qpid-08-PREACK">-n TQR-Qpid-08 -d1H -s[10000] -c[16] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=258 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </script>
-
- <script name="TTR-Qpid-03-TX">-n TTR-Qpid-03 -d1H -s[1000] -c[2] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=8 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </script>
- <script name="TTR-Qpid-04-AUTOACK">-n TTR-Qpid-04 -d1H -s[1000] -c[2] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=8 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </script>
- <script name="TTR-Qpid-05-CLIENTACK">-n TTR-Qpid-05 -d1H -s[1000] -c[2] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=8 transacted=false consTransacted=false consAckMode=2 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </script>
- <script name="TTR-Qpid-06-DUPSOKACK">-n TTR-Qpid-06 -d1H -s[1000] -c[2] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=8 transacted=false consTransacted=false consAckMode=3 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </script>
- <script name="TTR-Qpid-07-NOACK">-n TTR-Qpid-07 -d1H -s[1000] -c[2] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=8 transacted=false consTransacted=false consAckMode=257 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </script>
- <script name="TTR-Qpid-08-PREACK">-n TTR-Qpid-08 -d1H -s[1000] -c[2] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=8 transacted=false consTransacted=false consAckMode=258 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </script>
-
- <script name="PQR-Qpid-03-TX">-n PQR-Qpid-03 -d1H -s[1000] -c[16] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </script>
- <script name="PQR-Qpid-04-AUTOACK">-n PQR-Qpid-04 -d1H -s[1000] -c[16] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </script>
- <script name="PQR-Qpid-05-CLIENTACK">-n PQR-Qpid-05 -d1H -s[1000] -c[16] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=2 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </script>
- <script name="PQR-Qpid-06-DUPSOKACK">-n PQR-Qpid-06 -d1H -s[1000] -c[16] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=3 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </script>
- <script name="PQR-Qpid-07-NOACK">-n PQR-Qpid-07 -d1H -s[1000] -c[16] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=257 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </script>
- <script name="PQR-Qpid-08-PREACK">-n PQR-Qpid-08 -d1H -s[1000] -c[16] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=258 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </script>
-
- <script name="PTR-Qpid-03-TX">-n PTR-Qpid-03 -d1H -s[100] -c[2] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=8 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </script>
- <script name="PTR-Qpid-04-AUTOACK">-n PTR-Qpid-04 -d1H -s[100] -c[2] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=8 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </script>
- <script name="PTR-Qpid-05-CLIENTACK">-n PTR-Qpid-05 -d1H -s[100] -c[2] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=8 transacted=false consTransacted=false consAckMode=2 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </script>
- <script name="PTR-Qpid-06-DUPSOKACK">-n PTR-Qpid-06 -d1H -s[100] -c[2] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=8 transacted=false consTransacted=false consAckMode=3 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </script>
- <script name="PTR-Qpid-07-NOACK">-n PTR-Qpid-07 -d1H -s[100] -c[2] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=8 transacted=false consTransacted=false consAckMode=257 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </script>
- <script name="PTR-Qpid-08-PREACK">-n PTR-Qpid-08 -d1H -s[100] -c[2] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=8 transacted=false consTransacted=false consAckMode=258 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </script>
-
- <!-- Performance Tests. -->
-
- <!-- Transient, P2P Tests -->
- <!-- Concurrency Tests : What are the effects of increasing consumers from 1...30 consumers -->
- <script name="TQCT-Qpid-01">-n TQCT-Qpid-01 -d1M -s[1000] -c[1:30]:samples=30 -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=2000 maxPending=2000000 </script>
- <script name="TQCT-Qpid-02">-n TQCT-Qpid-02 -d1M -s[1000] -c[1:30]:samples=30 -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=2000 maxPending=2000000 </script>
- <!-- Latency Tests : What are the effects on latency of increasing consumers from 1...30 consumers -->
- <script name="TQCL-Qpid-01">-n TQCL-Qpid-01 -d1M -s[1000] -c[1:30]:samples=30 -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=2000 maxPending=2000000 </script>
- <script name="TQCL-Qpid-02">-n TQCL-Qpid-02 -d1M -s[1000] -c[1:30]:samples=30 -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=2000 maxPending=2000000 </script>
-
- <!-- <script name="TQC-Qpid-05">-n TQC-Qpid-05 -d10M -s[10] -c[100] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=10 rate=0 maxPending=100000 </script> -->
- <!-- <script name="TQC-Qpid-06">-n TQC-Qpid-06 -d10M -s[10] -c[100] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=10 rate=0 maxPending=100000 </script> -->
-
-
- <!-- Message Size Tests : Tests sending message from 512b upto 1M with Point to Point messaging -->
- <script name="TQM-Qpid-01-512b">-n TQM-Qpid-01-512b -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=512 destinationCount=1 rate=0 maxPending=2000000 </script>
- <script name="TQM-Qpid-02-512b">-n TQM-Qpid-02-512b -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=512 destinationCount=1 rate=0 maxPending=2000000 </script>
- <script name="TQM-Qpid-01-1K">-n TQM-Qpid-01-1K -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=1024 destinationCount=1 rate=0 maxPending=2000000 </script>
- <script name="TQM-Qpid-02-1K">-n TQM-Qpid-02-1K -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=1024 destinationCount=1 rate=0 maxPending=2000000 </script>
- <script name="TQM-Qpid-01-5K">-n TQM-Qpid-01-5K -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=5120 destinationCount=1 rate=0 maxPending=2000000 </script>
- <script name="TQM-Qpid-02-5K">-n TQM-Qpid-02-5K -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=5120 destinationCount=1 rate=0 maxPending=2000000 </script>
- <script name="TQM-Qpid-01-10K">-n TQM-Qpid-01-10K -d10M -s[100] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=10240 destinationCount=1 rate=0 maxPending=2000000 </script>
- <script name="TQM-Qpid-02-10K">-n TQM-Qpid-02-10K -d10M -s[100] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=10240 destinationCount=1 rate=0 maxPending=2000000 </script>
- <script name="TQM-Qpid-01-50K">-n TQM-Qpid-01-50K -d10M -s[100] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=51200 destinationCount=1 rate=0 maxPending=100000000</script>
- <script name="TQM-Qpid-02-50K">-n TQM-Qpid-02-50K -d10M -s[100] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=51200 destinationCount=1 rate=0 maxPending=100000000</script>
- <script name="TQM-Qpid-01-100K">-n TQM-Qpid-01-100K -d10M -s[100] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=102400 destinationCount=1 rate=0 maxPending=100000000</script>
- <script name="TQM-Qpid-02-100K">-n TQM-Qpid-02-100K -d10M -s[100] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=102400 destinationCount=1 rate=0 maxPending=100000000</script>
- <script name="TQM-Qpid-01-500K">-n TQM-Qpid-01-500K -d10M -s[100] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=512000 destinationCount=1 rate=0 maxPending=100000000</script>
- <script name="TQM-Qpid-02-500K">-n TQM-Qpid-02-500K -d10M -s[100] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=512000 destinationCount=1 rate=0 maxPending=100000000</script>
- <script name="TQM-Qpid-01-1M">-n TQM-Qpid-01-1M -d10M -s[100] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=1048576 destinationCount=1 rate=0 maxPending=100000000</script>
- <script name="TQM-Qpid-02-1M">-n TQM-Qpid-02-1M -d10M -s[100] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=1048576 destinationCount=1 rate=0 maxPending=100000000</script>
-
- <!-- Transient, Pub/Sub Tests -->
- <!-- Concurrency Tests : What are the effects of increasing consumers from 1...30 consumers -->
- <script name="TTCT-Qpid-01">-n TTCT-Qpid-01 -d1M -s[10] -c[1:30]:samples=30 -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=40 maxPending=2000000 </script>
- <script name="TTCT-Qpid-02">-n TTCT-Qpid-02 -d1M -s[10] -c[1:30]:samples=30 -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=40 maxPending=2000000 </script>
- <!-- Latency Tests : What are the effects on latency of increasing consumers from 1...30 consumers -->
- <script name="TTCL-Qpid-01">-n TTCL-Qpid-01 -d1M -s[10] -c[1:30]:samples=30 -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=40 maxPending=2000000 </script>
- <script name="TTCL-Qpid-02">-n TTCL-Qpid-02 -d1M -s[10] -c[1:30]:samples=30 -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=40 maxPending=2000000 </script>
-
- <!-- <script name="TTC-Qpid-05">-n TTC-Qpid-05 -d10M -s[10] -c[100] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=10 rate=0 maxPending=100000 </script> -->
- <!-- <script name="TTC-Qpid-06">-n TTC-Qpid-06 -d10M -s[10] -c[100] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=10 rate=0 maxPending=100000 </script> -->
-
- <!-- Message Size Tests : Tests sending message from 512b upto 1M with Point to Point messaging -->
- <script name="TTM-Qpid-01-512b">-n TTM-Qpid-01-512b -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=512 destinationCount=1 rate=0 maxPending=2000000 </script>
- <script name="TTM-Qpid-02-512b">-n TTM-Qpid-02-512b -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=512 destinationCount=1 rate=0 maxPending=2000000 </script>
- <script name="TTM-Qpid-01-1K">-n TTM-Qpid-01-1K -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=1024 destinationCount=1 rate=0 maxPending=2000000 </script>
- <script name="TTM-Qpid-02-1K">-n TTM-Qpid-02-1K -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=1024 destinationCount=1 rate=0 maxPending=2000000 </script>
- <script name="TTM-Qpid-01-5K">-n TTM-Qpid-01-5K -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=5120 destinationCount=1 rate=0 maxPending=2000000 </script>
- <script name="TTM-Qpid-02-5K">-n TTM-Qpid-02-5K -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=5120 destinationCount=1 rate=0 maxPending=2000000 </script>
- <script name="TTM-Qpid-01-10K">-n TTM-Qpid-01-10K -d10M -s[100] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=10240 destinationCount=1 rate=0 maxPending=2000000 </script>
- <script name="TTM-Qpid-02-10K">-n TTM-Qpid-02-10K -d10M -s[100] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=10240 destinationCount=1 rate=0 maxPending=2000000 </script>
- <script name="TTM-Qpid-01-50K">-n TTM-Qpid-01-50K -d10M -s[100] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=51200 destinationCount=1 rate=0 maxPending=20000000</script>
- <script name="TTM-Qpid-02-50K">-n TTM-Qpid-02-50K -d10M -s[100] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=51200 destinationCount=1 rate=0 maxPending=20000000</script>
- <script name="TTM-Qpid-01-100K">-n TTM-Qpid-01-100K -d10M -s[40] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=102400 destinationCount=1 rate=0 maxPending=20000000</script>
- <script name="TTM-Qpid-02-100K">-n TTM-Qpid-02-100K -d10M -s[40] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=102400 destinationCount=1 rate=0 maxPending=20000000</script>
- <script name="TTM-Qpid-01-500K">-n TTM-Qpid-01-500K -d10M -s[8] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=512000 destinationCount=1 rate=0 maxPending=20000000</script>
- <script name="TTM-Qpid-02-500K">-n TTM-Qpid-02-500K -d10M -s[8] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=512000 destinationCount=1 rate=0 maxPending=20000000</script>
- <script name="TTM-Qpid-01-1M">-n TTM-Qpid-01-1M -d10M -s[4] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=1048576 destinationCount=1 rate=0 maxPending=20000000</script>
- <script name="TTM-Qpid-02-1M">-n TTM-Qpid-02-1M -d10M -s[4] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=1048476 destinationCount=1 rate=0 maxPending=20000000</script>
-
- <!-- Persistent, P2P Tests -->
- <!-- Concurrency Tests : What are the effects of increasing consumers from 1...30 consumers -->
- <script name="PQCT-Qpid-01">-n PQCT-Qpid-01 -d1M -s[1000] -c[1:30]:samples=30 -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=600 maxPending=2000000 </script>
- <script name="PQCT-Qpid-02">-n PQCT-Qpid-02 -d1M -s[1000] -c[1:30]:samples=30 -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=100 maxPending=2000000 </script>
- <!-- Latency Tests : What are the effects on latency of increasing consumers from 1...30 consumers -->
- <script name="PQCL-Qpid-01">-n PQCL-Qpid-01 -d1M -s[1000] -c[1:30]:samples=30 -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=600 maxPending=2000000 </script>
- <script name="PQCL-Qpid-02">-n PQCL-Qpid-02 -d1M -s[1000] -c[1:30]:samples=30 -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=100 maxPending=2000000 </script>
-
- <!-- <script name="PQC-Qpid-05">-n PQC-Qpid-05 -d10M -s[10] -c[100] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=10 rate=0 maxPending=100000 </script> -->
- <!-- <script name="PQC-Qpid-06">-n PQC-Qpid-06 -d10M -s[10] -c[100] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=10 rate=0 maxPending=100000 </script> -->
-
- <!-- Message Size Tests : Tests sending message from 512b upto 1M with Point to Point messaging -->
- <script name="PQM-Qpid-01-512b">-n PQM-Qpid-01-512b -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=512 destinationCount=1 rate=0 maxPending=2000000 </script>
- <script name="PQM-Qpid-02-512b">-n PQM-Qpid-02-512b -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=512 destinationCount=1 rate=0 maxPending=2000000 </script>
- <script name="PQM-Qpid-01-1K">-n PQM-Qpid-01-1K -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=1024 destinationCount=1 rate=0 maxPending=2000000 </script>
- <script name="PQM-Qpid-02-1K">-n PQM-Qpid-02-1K -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=1024 destinationCount=1 rate=0 maxPending=2000000 </script>
- <script name="PQM-Qpid-01-5K">-n PQM-Qpid-01-5K -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=5120 destinationCount=1 rate=0 maxPending=2000000 </script>
- <script name="PQM-Qpid-02-5K">-n PQM-Qpid-02-5K -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=5120 destinationCount=1 rate=0 maxPending=2000000 </script>
- <script name="PQM-Qpid-01-10K">-n PQM-Qpid-01-10K -d10M -s[100] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=10240 destinationCount=1 rate=0 maxPending=2000000 </script>
- <script name="PQM-Qpid-02-10K">-n PQM-Qpid-02-10K -d10M -s[100] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=10240 destinationCount=1 rate=0 maxPending=2000000 </script>
- <script name="PQM-Qpid-01-50K">-n PQM-Qpid-01-50K -d10M -s[100] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=51200 destinationCount=1 rate=0 maxPending=20000000</script>
- <script name="PQM-Qpid-02-50K">-n PQM-Qpid-02-50K -d10M -s[100] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=51200 destinationCount=1 rate=0 maxPending=20000000</script>
- <script name="PQM-Qpid-01-100K">-n PQM-Qpid-01-100K -d10M -s[40] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=102400 destinationCount=1 rate=0 maxPending=20000000</script>
- <script name="PQM-Qpid-02-100K">-n PQM-Qpid-02-100K -d10M -s[40] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=102400 destinationCount=1 rate=0 maxPending=20000000</script>
- <script name="PQM-Qpid-01-500K">-n PQM-Qpid-01-500K -d10M -s[8] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=512000 destinationCount=1 rate=0 maxPending=20000000</script>
- <script name="PQM-Qpid-02-500K">-n PQM-Qpid-02-500K -d10M -s[8] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=512000 destinationCount=1 rate=0 maxPending=20000000</script>
- <script name="PQM-Qpid-01-1M">-n PQM-Qpid-01-1M -d10M -s[4] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=1048576 destinationCount=1 rate=0 maxPending=20000000</script>
- <script name="PQM-Qpid-02-1M">-n PQM-Qpid-02-1M -d10M -s[4] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=1048576 destinationCount=1 rate=0 maxPending=20000000</script>
-
- <!-- Persistent, Pub/Sub Tests -->
- <script name="PTCT-Qpid-01">-n PTCT-Qpid-01 -d1M -s[1] -c[1:30]:samples=30 -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=1 maxPending=2000000 </script>
- <script name="PTCT-Qpid-02">-n PTCT-Qpid-02 -d1M -s[1] -c[1:30]:samples=30 -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=1 maxPending=2000000 </script>
- <script name="PTCL-Qpid-01">-n PTCL-Qpid-01 -d1M -s[1] -c[1:30]:samples=30 -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=1 maxPending=2000000 </script>
- <script name="PTCL-Qpid-02">-n PTCL-Qpid-02 -d1M -s[1] -c[1:30]:samples=30 -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=1 maxPending=2000000 </script>
-
- <!-- <script name="PTC-Qpid-05">-n PTC-Qpid-05 -d10M -s[10] -c[100] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=10 rate=0 maxPending=100000 </script> -->
- <!-- <script name="PTC-Qpid-06">-n PTC-Qpid-06 -d10M -s[10] -c[100] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=10 rate=0 maxPending=100000 </script> -->
-
- <script name="PTM-Qpid-01-512b">-n PTM-Qpid-01-512b -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=512 destinationCount=1 rate=0 maxPending=2000000 </script>
- <script name="PTM-Qpid-02-512b">-n PTM-Qpid-02-512b -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=512 destinationCount=1 rate=0 maxPending=2000000 </script>
- <script name="PTM-Qpid-01-1K">-n PTM-Qpid-01-1K -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=1024 destinationCount=1 rate=0 maxPending=2000000 </script>
- <script name="PTM-Qpid-02-1K">-n PTM-Qpid-02-1K -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=1024 destinationCount=1 rate=0 maxPending=2000000 </script>
- <script name="PTM-Qpid-01-5K">-n PTM-Qpid-01-5K -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=5120 destinationCount=1 rate=0 maxPending=2000000 </script>
- <script name="PTM-Qpid-02-5K">-n PTM-Qpid-02-5K -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=5120 destinationCount=1 rate=0 maxPending=2000000 </script>
- <script name="PTM-Qpid-01-10K">-n PTM-Qpid-01-10K -d10M -s[100] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=10240 destinationCount=1 rate=0 maxPending=2000000 </script>
- <script name="PTM-Qpid-02-10K">-n PTM-Qpid-02-10K -d10M -s[100] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=10240 destinationCount=1 rate=0 maxPending=2000000 </script>
- <script name="PTM-Qpid-01-50K">-n PTM-Qpid-01-50K -d10M -s[100] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=51200 destinationCount=1 rate=0 maxPending=20000000</script>
- <script name="PTM-Qpid-02-50K">-n PTM-Qpid-02-50K -d10M -s[100] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=51200 destinationCount=1 rate=0 maxPending=20000000</script>
- <script name="PTM-Qpid-01-100K">-n PTM-Qpid-01-100K -d10M -s[40] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=102400 destinationCount=1 rate=0 maxPending=20000000</script>
- <script name="PTM-Qpid-02-100K">-n PTM-Qpid-02-100K -d10M -s[40] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=102400 destinationCount=1 rate=0 maxPending=20000000</script>
- <script name="PTM-Qpid-01-500K">-n PTM-Qpid-01-500K -d10M -s[8] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=512000 destinationCount=1 rate=0 maxPending=20000000</script>
- <script name="PTM-Qpid-02-500K">-n PTM-Qpid-02-500K -d10M -s[8] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=512000 destinationCount=1 rate=0 maxPending=20000000</script>
- <script name="PTM-Qpid-01-1M">-n PTM-Qpid-01-1M -d10M -s[4] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=1048576 destinationCount=1 rate=0 maxPending=20000000</script>
- <script name="PTM-Qpid-02-1M">-n PTM-Qpid-02-1M -d10M -s[4] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=1048476 destinationCount=1 rate=0 maxPending=20000000</script>
-
- <!-- Benchmarking tests. -->
- <!-- Throughput. -->
- <script name="TQBT-TX-Qpid-01">-n TQBT-TX-Qpid-01 -d10M -s[1000] -c[16] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </script>
- <script name="TQBT-AA-Qpid-01">-n TQBT-AA-Qpid-01 -d10M -s[1000] -c[16] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </script>
- <script name="TQBT-NA-Qpid-01">-n TQBT-NA-Qpid-01 -d10M -s[1000] -c[16] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=257 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </script>
- <script name="TTBT-TX-Qpid-01">-n TTBT-TX-Qpid-01 -d10M -s[1000] -c[2] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=8 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </script>
- <script name="TTBT-AA-Qpid-01">-n TTBT-AA-Qpid-01 -d10M -s[1000] -c[2] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=8 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </script>
- <script name="TTBT-NA-Qpid-01">-n TTBT-NA-Qpid-01 -d10M -s[1000] -c[2] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=8 transacted=false consTransacted=false consAckMode=257 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </script>
-
- <script name="PQBT-TX-Qpid-01">-n PQBT-TX-Qpid-01 -d10M -s[1000] -c[16] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </script>
- <script name="PQBT-AA-Qpid-01">-n PQBT-AA-Qpid-01 -d10M -s[1000] -c[16] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </script>
- <script name="PTBT-TX-Qpid-01">-n PTBT-TX-Qpid-01 -d10M -s[1000] -c[2] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=8 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </script>
- <script name="PTBT-AA-Qpid-01">-n PTBT-AA-Qpid-01 -d10M -s[1000] -c[2] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=8 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </script>
-
- <!-- Benchmark Latency testing-->
- <!-- Job Queueing. 1:10 -->
- <script name="TQBL-AA-Qpid-02-01">-n TQBL-AA-Qpid-02 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=10 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=5120 destinationCount=1 rate=1000 maxPending=2000000 </script>
- <script name="TQBL-AA-Qpid-02-02">-n TQBL-AA-Qpid-02 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=10 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=5120 destinationCount=1 rate=2000 maxPending=2000000 </script>
- <script name="TQBL-AA-Qpid-02-03">-n TQBL-AA-Qpid-02 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=10 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=5120 destinationCount=1 rate=3000 maxPending=2000000 </script>
- <script name="TQBL-AA-Qpid-02-04">-n TQBL-AA-Qpid-02 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=10 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=5120 destinationCount=1 rate=4000 maxPending=2000000 </script>
- <script name="TQBL-AA-Qpid-02-05">-n TQBL-AA-Qpid-02 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=10 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=5120 destinationCount=1 rate=5000 maxPending=2000000 </script>
- <script name="TQBL-AA-Qpid-02-06">-n TQBL-AA-Qpid-02 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=10 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=5120 destinationCount=1 rate=6000 maxPending=2000000 </script>
- <script name="TQBL-AA-Qpid-02-07">-n TQBL-AA-Qpid-02 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=10 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=5120 destinationCount=1 rate=7000 maxPending=2000000 </script>
- <script name="TQBL-AA-Qpid-02-08">-n TQBL-AA-Qpid-02 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=10 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=5120 destinationCount=1 rate=8000 maxPending=2000000 </script>
- <script name="TQBL-AA-Qpid-02-09">-n TQBL-AA-Qpid-02 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=10 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=5120 destinationCount=1 rate=9000 maxPending=2000000 </script>
- <script name="TQBL-AA-Qpid-02-10">-n TQBL-AA-Qpid-02 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=10 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=5120 destinationCount=1 rate=10000 maxPending=2000000 </script>
-
- <script name="PQBL-AA-Qpid-02-01">-n PQBL-AA-Qpid-02 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=10 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=5120 destinationCount=1 rate=100 maxPending=2000000 </script>
- <script name="PQBL-AA-Qpid-02-02">-n PQBL-AA-Qpid-02 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=10 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=5120 destinationCount=1 rate=200 maxPending=2000000 </script>
- <script name="PQBL-AA-Qpid-02-03">-n PQBL-AA-Qpid-02 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=10 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=5120 destinationCount=1 rate=300 maxPending=2000000 </script>
- <script name="PQBL-AA-Qpid-02-04">-n PQBL-AA-Qpid-02 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=10 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=5120 destinationCount=1 rate=400 maxPending=2000000 </script>
- <script name="PQBL-AA-Qpid-02-05">-n PQBL-AA-Qpid-02 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=10 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=5120 destinationCount=1 rate=500 maxPending=2000000 </script>
- <script name="PQBL-AA-Qpid-02-06">-n PQBL-AA-Qpid-02 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=10 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=5120 destinationCount=1 rate=600 maxPending=2000000 </script>
- <script name="PQBL-AA-Qpid-02-07">-n PQBL-AA-Qpid-02 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=10 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=5120 destinationCount=1 rate=700 maxPending=2000000 </script>
- <script name="PQBL-AA-Qpid-02-08">-n PQBL-AA-Qpid-02 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=10 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=5120 destinationCount=1 rate=800 maxPending=2000000 </script>
- <script name="PQBL-AA-Qpid-02-09">-n PQBL-AA-Qpid-02 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=10 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=5120 destinationCount=1 rate=900 maxPending=2000000 </script>
- <script name="PQBL-AA-Qpid-02-10">-n PQBL-AA-Qpid-02 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=10 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=5120 destinationCount=1 rate=1000 maxPending=2000000 </script>
-
- <!-- Broadcast of small sized time critical messages. Lowish rates. Transient/Persistent. 1:100, auto ack. -->
- <script name="TTBL-AA-Qpid-03-01">-n TTBL-AA-Qpid-03 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1001 messageSize=256 destinationCount=1 rate=200 maxPending=2000000 </script>
- <script name="TTBL-AA-Qpid-03-02">-n TTBL-AA-Qpid-03 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1001 messageSize=256 destinationCount=1 rate=400 maxPending=2000000 </script>
- <script name="TTBL-AA-Qpid-03-03">-n TTBL-AA-Qpid-03 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1001 messageSize=256 destinationCount=1 rate=600 maxPending=2000000 </script>
- <script name="TTBL-AA-Qpid-03-04">-n TTBL-AA-Qpid-03 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1001 messageSize=256 destinationCount=1 rate=800 maxPending=2000000 </script>
- <script name="TTBL-AA-Qpid-03-05">-n TTBL-AA-Qpid-03 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1001 messageSize=256 destinationCount=1 rate=1000 maxPending=2000000 </script>
- <script name="TTBL-AA-Qpid-03-06">-n TTBL-AA-Qpid-03 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1001 messageSize=256 destinationCount=1 rate=1200 maxPending=2000000 </script>
- <script name="TTBL-AA-Qpid-03-07">-n TTBL-AA-Qpid-03 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1001 messageSize=256 destinationCount=1 rate=1400 maxPending=2000000 </script>
- <script name="TTBL-AA-Qpid-03-08">-n TTBL-AA-Qpid-03 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1001 messageSize=256 destinationCount=1 rate=1600 maxPending=2000000 </script>
- <script name="TTBL-AA-Qpid-03-09">-n TTBL-AA-Qpid-03 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1001 messageSize=256 destinationCount=1 rate=1800 maxPending=2000000 </script>
- <script name="TTBL-AA-Qpid-03-10">-n TTBL-AA-Qpid-03 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1001 messageSize=256 destinationCount=1 rate=2000 maxPending=2000000 </script>
-
- <script name="PTBL-AA-Qpid-03-01">-n PTBL-AA-Qpid-03 -d1M -s[100] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=101 messageSize=256 destinationCount=1 rate=10 maxPending=2000000 </script>
- <script name="PTBL-AA-Qpid-03-02">-n PTBL-AA-Qpid-03 -d1M -s[100] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=101 messageSize=256 destinationCount=1 rate=20 maxPending=2000000 </script>
- <script name="PTBL-AA-Qpid-03-03">-n PTBL-AA-Qpid-03 -d1M -s[100] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=101 messageSize=256 destinationCount=1 rate=30 maxPending=2000000 </script>
- <script name="PTBL-AA-Qpid-03-04">-n PTBL-AA-Qpid-03 -d1M -s[100] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=101 messageSize=256 destinationCount=1 rate=40 maxPending=2000000 </script>
- <script name="PTBL-AA-Qpid-03-05">-n PTBL-AA-Qpid-03 -d1M -s[100] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=101 messageSize=256 destinationCount=1 rate=50 maxPending=2000000 </script>
- <script name="PTBL-AA-Qpid-03-06">-n PTBL-AA-Qpid-03 -d1M -s[100] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=101 messageSize=256 destinationCount=1 rate=60 maxPending=2000000 </script>
- <script name="PTBL-AA-Qpid-03-07">-n PTBL-AA-Qpid-03 -d1M -s[100] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=101 messageSize=256 destinationCount=1 rate=70 maxPending=2000000 </script>
- <script name="PTBL-AA-Qpid-03-08">-n PTBL-AA-Qpid-03 -d1M -s[100] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=101 messageSize=256 destinationCount=1 rate=80 maxPending=2000000 </script>
- <script name="PTBL-AA-Qpid-03-09">-n PTBL-AA-Qpid-03 -d1M -s[100] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=101 messageSize=256 destinationCount=1 rate=90 maxPending=2000000 </script>
- <script name="PTBL-AA-Qpid-03-10">-n PTBL-AA-Qpid-03 -d1M -s[100] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=101 messageSize=256 destinationCount=1 rate=100 maxPending=2000000 </script>
-
- <!-- Broadcast of medium sized time critical messages. Lowish rates. Transient/Persistent. 1:100, auto ack. -->
- <script name="TTBL-AA-Qpid-04-01">-n TTBL-AA-Qpid-04 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1001 messageSize=5120 destinationCount=1 rate=100 maxPending=2000000 </script>
- <script name="TTBL-AA-Qpid-04-02">-n TTBL-AA-Qpid-04 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1001 messageSize=5120 destinationCount=1 rate=200 maxPending=2000000 </script>
- <script name="TTBL-AA-Qpid-04-03">-n TTBL-AA-Qpid-04 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1001 messageSize=5120 destinationCount=1 rate=300 maxPending=2000000 </script>
- <script name="TTBL-AA-Qpid-04-04">-n TTBL-AA-Qpid-04 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1001 messageSize=5120 destinationCount=1 rate=400 maxPending=2000000 </script>
- <script name="TTBL-AA-Qpid-04-05">-n TTBL-AA-Qpid-04 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1001 messageSize=5120 destinationCount=1 rate=500 maxPending=2000000 </script>
- <script name="TTBL-AA-Qpid-04-06">-n TTBL-AA-Qpid-04 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1001 messageSize=5120 destinationCount=1 rate=600 maxPending=2000000 </script>
- <script name="TTBL-AA-Qpid-04-07">-n TTBL-AA-Qpid-04 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1001 messageSize=5120 destinationCount=1 rate=700 maxPending=2000000 </script>
- <script name="TTBL-AA-Qpid-04-08">-n TTBL-AA-Qpid-04 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1001 messageSize=5120 destinationCount=1 rate=800 maxPending=2000000 </script>
- <script name="TTBL-AA-Qpid-04-09">-n TTBL-AA-Qpid-04 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1001 messageSize=5120 destinationCount=1 rate=900 maxPending=2000000 </script>
- <script name="TTBL-AA-Qpid-04-10">-n TTBL-AA-Qpid-04 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1001 messageSize=5120 destinationCount=1 rate=1000 maxPending=2000000 </script>
-
- <script name="PTBL-AA-Qpid-04-01">-n PTBL-AA-Qpid-04 -d1M -s[100] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=101 messageSize=5120 destinationCount=1 rate=10 maxPending=2000000 </script>
- <script name="PTBL-AA-Qpid-04-02">-n PTBL-AA-Qpid-04 -d1M -s[100] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=101 messageSize=5120 destinationCount=1 rate=20 maxPending=2000000 </script>
- <script name="PTBL-AA-Qpid-04-03">-n PTBL-AA-Qpid-04 -d1M -s[100] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=101 messageSize=5120 destinationCount=1 rate=30 maxPending=2000000 </script>
- <script name="PTBL-AA-Qpid-04-04">-n PTBL-AA-Qpid-04 -d1M -s[100] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=101 messageSize=5120 destinationCount=1 rate=40 maxPending=2000000 </script>
- <script name="PTBL-AA-Qpid-04-05">-n PTBL-AA-Qpid-04 -d1M -s[100] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=101 messageSize=5120 destinationCount=1 rate=50 maxPending=2000000 </script>
- <script name="PTBL-AA-Qpid-04-06">-n PTBL-AA-Qpid-04 -d1M -s[100] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=101 messageSize=5120 destinationCount=1 rate=60 maxPending=2000000 </script>
- <script name="PTBL-AA-Qpid-04-07">-n PTBL-AA-Qpid-04 -d1M -s[100] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=101 messageSize=5120 destinationCount=1 rate=70 maxPending=2000000 </script>
- <script name="PTBL-AA-Qpid-04-08">-n PTBL-AA-Qpid-04 -d1M -s[100] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=101 messageSize=5120 destinationCount=1 rate=80 maxPending=2000000 </script>
- <script name="PTBL-AA-Qpid-04-09">-n PTBL-AA-Qpid-04 -d1M -s[100] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=101 messageSize=5120 destinationCount=1 rate=90 maxPending=2000000 </script>
- <script name="PTBL-AA-Qpid-04-10">-n PTBL-AA-Qpid-04 -d1M -s[100] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=101 messageSize=5120 destinationCount=1 rate=100 maxPending=2000000 </script>
-
- <!-- Low-latency broadcast of time sensitive events. Transient, no_ack. -->
- <script name="TTBL-NA-Qpid-05-01">-n TTBL-NA-Qpid-05 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=257 commitBatchSize=1 batchSize=1001 messageSize=256 destinationCount=1 rate=400 maxPending=2000000 </script>
- <script name="TTBL-NA-Qpid-05-02">-n TTBL-NA-Qpid-05 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=257 commitBatchSize=1 batchSize=1001 messageSize=256 destinationCount=1 rate=800 maxPending=2000000 </script>
- <script name="TTBL-NA-Qpid-05-03">-n TTBL-NA-Qpid-05 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=257 commitBatchSize=1 batchSize=1001 messageSize=256 destinationCount=1 rate=1200 maxPending=2000000 </script>
- <script name="TTBL-NA-Qpid-05-04">-n TTBL-NA-Qpid-05 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=257 commitBatchSize=1 batchSize=1001 messageSize=256 destinationCount=1 rate=1600 maxPending=2000000 </script>
- <script name="TTBL-NA-Qpid-05-05">-n TTBL-NA-Qpid-05 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=257 commitBatchSize=1 batchSize=1001 messageSize=256 destinationCount=1 rate=2000 maxPending=2000000 </script>
- <script name="TTBL-NA-Qpid-05-06">-n TTBL-NA-Qpid-05 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=257 commitBatchSize=1 batchSize=1001 messageSize=256 destinationCount=1 rate=2400 maxPending=2000000 </script>
- <script name="TTBL-NA-Qpid-05-07">-n TTBL-NA-Qpid-05 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=257 commitBatchSize=1 batchSize=1001 messageSize=256 destinationCount=1 rate=2800 maxPending=2000000 </script>
- <script name="TTBL-NA-Qpid-05-08">-n TTBL-NA-Qpid-05 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=257 commitBatchSize=1 batchSize=1001 messageSize=256 destinationCount=1 rate=3200 maxPending=2000000 </script>
- <script name="TTBL-NA-Qpid-05-09">-n TTBL-NA-Qpid-05 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=257 commitBatchSize=1 batchSize=1001 messageSize=256 destinationCount=1 rate=3600 maxPending=2000000 </script>
- <script name="TTBL-NA-Qpid-05-10">-n TTBL-NA-Qpid-05 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=257 commitBatchSize=1 batchSize=1001 messageSize=256 destinationCount=1 rate=4000 maxPending=2000000 </script>
-
- <!-- Low-latency broadcast of medium sized time sensitive events. Transient, no_ack. -->
- <script name="TTBL-NA-Qpid-06-01">-n TTBL-NA-Qpid-06 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=257 commitBatchSize=1 batchSize=1001 messageSize=5120 destinationCount=1 rate=100 maxPending=2000000 </script>
- <script name="TTBL-NA-Qpid-06-02">-n TTBL-NA-Qpid-06 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=257 commitBatchSize=1 batchSize=1001 messageSize=5120 destinationCount=1 rate=200 maxPending=2000000 </script>
- <script name="TTBL-NA-Qpid-06-03">-n TTBL-NA-Qpid-06 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=257 commitBatchSize=1 batchSize=1001 messageSize=5120 destinationCount=1 rate=300 maxPending=2000000 </script>
- <script name="TTBL-NA-Qpid-06-04">-n TTBL-NA-Qpid-06 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=257 commitBatchSize=1 batchSize=1001 messageSize=5120 destinationCount=1 rate=400 maxPending=2000000 </script>
- <script name="TTBL-NA-Qpid-06-05">-n TTBL-NA-Qpid-06 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=257 commitBatchSize=1 batchSize=1001 messageSize=5120 destinationCount=1 rate=500 maxPending=2000000 </script>
- <script name="TTBL-NA-Qpid-06-06">-n TTBL-NA-Qpid-06 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=257 commitBatchSize=1 batchSize=1001 messageSize=5120 destinationCount=1 rate=600 maxPending=2000000 </script>
- <script name="TTBL-NA-Qpid-06-07">-n TTBL-NA-Qpid-06 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=257 commitBatchSize=1 batchSize=1001 messageSize=5120 destinationCount=1 rate=700 maxPending=2000000 </script>
- <script name="TTBL-NA-Qpid-06-08">-n TTBL-NA-Qpid-06 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=257 commitBatchSize=1 batchSize=1001 messageSize=5120 destinationCount=1 rate=800 maxPending=2000000 </script>
- <script name="TTBL-NA-Qpid-06-09">-n TTBL-NA-Qpid-06 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=257 commitBatchSize=1 batchSize=1001 messageSize=5120 destinationCount=1 rate=900 maxPending=2000000 </script>
- <script name="TTBL-NA-Qpid-06-10">-n TTBL-NA-Qpid-06 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=257 commitBatchSize=1 batchSize=1001 messageSize=5120 destinationCount=1 rate=1000 maxPending=2000000 </script>
-
- <!-- Failover Tests. -->
- <script name="FT-Qpid-01">-n FT-Qpid-01 -s[2500] -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf messageSize=256 batchSize=10000 transacted=true properties=failovertest.properties failBeforeSend=true -o $QPID_WORK/results</script>
- <script name="FT-Qpid-02">-n FT-Qpid-02 -s[2500] -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf messageSize=256 batchSize=10000 transacted=true properties=failovertest.properties failAfterSend=true -o $QPID_WORK/results</script>
- <script name="FT-Qpid-03">-n FT-Qpid-03 -s[2500] -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf messageSize=256 batchSize=1000 transacted=true properties=failovertest.properties failAfterCommit=true -o $QPID_WORK/results</script>
- <script name="FT-Qpid-04">-n FT-Qpid-04 -s[2500] -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf messageSize=256 batchSize=1000 properties=failovertest.properties transacted=false failBeforeSend=true -o $QPID_WORK/results</script>
- <script name="FT-Qpid-05">-n FT-Qpid-05 -s[2500] -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf messageSize=256 batchSize=1000 properties=failovertest.properties transacted=false failAfterSend=true -o $QPID_WORK/results</script>
- <script name="FT-Qpid-01-P">-n FT-Qpid-01-P -s[2500] -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true messageSize=256 batchSize=1000 transacted=true properties=failovertest.properties failBeforeSend=true -o $QPID_WORK/results</script>
- <script name="FT-Qpid-02-P">-n FT-Qpid-02-P -s[2500] -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true messageSize=256 batchSize=1000 transacted=true properties=failovertest.properties failAfterSend=true -o $QPID_WORK/results</script>
- <script name="FT-Qpid-03-P">-n FT-Qpid-03-P -s[2500] -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true messageSize=256 batchSize=1000 transacted=true properties=failovertest.properties failAfterCommit=true -o $QPID_WORK/results</script>
- <script name="FT-Qpid-04-P">-n FT-Qpid-04-P -s[250] -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true messageSize=256 batchSize=1000 properties=failovertest.properties transacted=false failBeforeSend=true -o $QPID_WORK/results</script>
- <script name="FT-Qpid-05-P">-n FT-Qpid-05-P -s[250] -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true messageSize=256 batchSize=1000 properties=failovertest.properties transacted=false failAfterSend=true -o $QPID_WORK/results</script>
-
-</scripts>
diff --git a/java/perftests/src/main/java/org/apache/qpid/client/message/TestMessageFactory.java b/java/perftests/src/main/java/org/apache/qpid/client/message/TestMessageFactory.java
deleted file mode 100644
index 3ad6c021bd..0000000000
--- a/java/perftests/src/main/java/org/apache/qpid/client/message/TestMessageFactory.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.client.message;
-
-import org.apache.mina.common.ByteBuffer;
-import org.apache.mina.common.SimpleByteBufferAllocator;
-
-import javax.jms.JMSException;
-import javax.jms.Session;
-import javax.jms.ObjectMessage;
-import javax.jms.StreamMessage;
-import javax.jms.BytesMessage;
-import javax.jms.TextMessage;
-import javax.jms.DeliveryMode;
-import javax.jms.Destination;
-
-public class TestMessageFactory
-{
- private static final String MESSAGE_DATA_BYTES = "-message payload-message paylaod-message payload-message paylaod";
-
- public static TextMessage newTextMessage(Session session, int size) throws JMSException
- {
- return session.createTextMessage(createMessagePayload(size));
- }
-
- public static TextMessage newJMSTextMessage(Session session, int size, String encoding) throws JMSException
- {
-
- TextMessage message = session.createTextMessage();
- message.clearBody();
- message.setText(createMessagePayload(size));
- return message;
- }
-
- public static BytesMessage newBytesMessage(Session session, int size) throws JMSException
- {
- BytesMessage message = session.createBytesMessage();
- message.writeUTF(createMessagePayload(size));
- return message;
- }
-
- public static StreamMessage newStreamMessage(Session session, int size) throws JMSException
- {
- StreamMessage message = session.createStreamMessage();
- message.writeString(createMessagePayload(size));
- return message;
- }
-
- public static ObjectMessage newObjectMessage(Session session, int size) throws JMSException
- {
- if (size == 0)
- {
- return session.createObjectMessage();
- }
- else
- {
- return session.createObjectMessage(createMessagePayload(size));
- }
- }
-
- /**
- * Creates an ObjectMessage with given size and sets the JMS properties (JMSReplyTo and DeliveryMode)
- * @param session
- * @param replyDestination
- * @param size
- * @param persistent
- * @return the new ObjectMessage
- * @throws JMSException
- */
- public static ObjectMessage newObjectMessage(Session session, Destination replyDestination, int size, boolean persistent) throws JMSException
- {
- ObjectMessage msg = newObjectMessage(session, size);
-
- // Set the messages persistent delivery flag.
- msg.setJMSDeliveryMode(persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT);
-
- // Ensure that the temporary reply queue is set as the reply to destination for the message.
- if (replyDestination != null)
- {
- msg.setJMSReplyTo(replyDestination);
- }
-
- return msg;
- }
-
- public static String createMessagePayload(int size)
- {
- StringBuffer buf = new StringBuffer(size);
- int count = 0;
- while (count <= (size - MESSAGE_DATA_BYTES.length()))
- {
- buf.append(MESSAGE_DATA_BYTES);
- count += MESSAGE_DATA_BYTES.length();
- }
- if (count < size)
- {
- buf.append(MESSAGE_DATA_BYTES, 0, size - count);
- }
-
- return buf.toString();
- }
-}
diff --git a/java/perftests/src/main/java/org/apache/qpid/config/AMQConnectionFactoryInitialiser.java b/java/perftests/src/main/java/org/apache/qpid/config/AMQConnectionFactoryInitialiser.java
deleted file mode 100644
index cac0064785..0000000000
--- a/java/perftests/src/main/java/org/apache/qpid/config/AMQConnectionFactoryInitialiser.java
+++ /dev/null
@@ -1,35 +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.config;
-
-import org.apache.qpid.client.AMQConnectionFactory;
-import org.apache.qpid.config.ConnectionFactoryInitialiser;
-import org.apache.qpid.config.ConnectorConfig;
-
-import javax.jms.ConnectionFactory;
-
-class AMQConnectionFactoryInitialiser implements ConnectionFactoryInitialiser
-{
- public ConnectionFactory getFactory(ConnectorConfig config)
- {
- return new AMQConnectionFactory(config.getHost(), config.getPort(), "/test_path");
- }
-}
diff --git a/java/perftests/src/main/java/org/apache/qpid/config/AbstractConfig.java b/java/perftests/src/main/java/org/apache/qpid/config/AbstractConfig.java
deleted file mode 100644
index 14db74438f..0000000000
--- a/java/perftests/src/main/java/org/apache/qpid/config/AbstractConfig.java
+++ /dev/null
@@ -1,69 +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.config;
-
-public abstract class AbstractConfig
-{
- public boolean setOptions(String[] argv)
- {
- try
- {
- for(int i = 0; i < argv.length - 1; i += 2)
- {
- String key = argv[i];
- String value = argv[i+1];
- setOption(key, value);
- }
- return true;
- }
- catch(Exception e)
- {
- System.out.println(e.getMessage());
- }
- return false;
- }
-
- protected int parseInt(String msg, String i)
- {
- try
- {
- return Integer.parseInt(i);
- }
- catch(NumberFormatException e)
- {
- throw new RuntimeException(msg + ": " + i, e);
- }
- }
-
- protected long parseLong(String msg, String i)
- {
- try
- {
- return Long.parseLong(i);
- }
- catch(NumberFormatException e)
- {
- throw new RuntimeException(msg + ": " + i, e);
- }
- }
-
- public abstract void setOption(String key, String value);
-}
diff --git a/java/perftests/src/main/java/org/apache/qpid/config/ConnectionFactoryInitialiser.java b/java/perftests/src/main/java/org/apache/qpid/config/ConnectionFactoryInitialiser.java
deleted file mode 100644
index a9984eb09a..0000000000
--- a/java/perftests/src/main/java/org/apache/qpid/config/ConnectionFactoryInitialiser.java
+++ /dev/null
@@ -1,29 +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.config;
-
-import javax.jms.ConnectionFactory;
-import javax.jms.JMSException;
-
-public interface ConnectionFactoryInitialiser
-{
- public ConnectionFactory getFactory(ConnectorConfig config) throws JMSException;
-}
diff --git a/java/perftests/src/main/java/org/apache/qpid/config/Connector.java b/java/perftests/src/main/java/org/apache/qpid/config/Connector.java
deleted file mode 100644
index ff2377f087..0000000000
--- a/java/perftests/src/main/java/org/apache/qpid/config/Connector.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.config;
-
-import javax.jms.Connection;
-import javax.jms.ConnectionFactory;
-
-public class Connector
-{
- public Connection createConnection(ConnectorConfig config) throws Exception
- {
- return getConnectionFactory(config).createConnection();
- }
-
- ConnectionFactory getConnectionFactory(ConnectorConfig config) throws Exception
- {
- String factory = config.getFactory();
- if(factory == null) factory = AMQConnectionFactoryInitialiser.class.getName();
- System.out.println("Using " + factory);
- return ((ConnectionFactoryInitialiser) Class.forName(factory).newInstance()).getFactory(config);
- }
-}
diff --git a/java/perftests/src/main/java/org/apache/qpid/config/ConnectorConfig.java b/java/perftests/src/main/java/org/apache/qpid/config/ConnectorConfig.java
deleted file mode 100644
index b120ed3f12..0000000000
--- a/java/perftests/src/main/java/org/apache/qpid/config/ConnectorConfig.java
+++ /dev/null
@@ -1,28 +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.config;
-
-public interface ConnectorConfig
-{
- public String getHost();
- public int getPort();
- public String getFactory();
-}
diff --git a/java/perftests/src/main/java/org/apache/qpid/config/JBossConnectionFactoryInitialiser.java b/java/perftests/src/main/java/org/apache/qpid/config/JBossConnectionFactoryInitialiser.java
deleted file mode 100644
index a0248a8f79..0000000000
--- a/java/perftests/src/main/java/org/apache/qpid/config/JBossConnectionFactoryInitialiser.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.config;
-
-import org.apache.qpid.config.ConnectionFactoryInitialiser;
-import org.apache.qpid.config.ConnectorConfig;
-import org.apache.qpid.client.JMSAMQException;
-
-import javax.jms.ConnectionFactory;
-import javax.jms.JMSException;
-import javax.management.MBeanServerConnection;
-import javax.management.ObjectName;
-import javax.management.MBeanException;
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-import javax.naming.NameNotFoundException;
-import java.util.Hashtable;
-
-public class JBossConnectionFactoryInitialiser implements ConnectionFactoryInitialiser
-{
- public ConnectionFactory getFactory(ConnectorConfig config) throws JMSException
- {
- ConnectionFactory cf = null;
- InitialContext ic = null;
- Hashtable ht = new Hashtable();
- ht.put(InitialContext.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
- String jbossHost = System.getProperty("jboss.host", "eqd-lxamq01");
- String jbossPort = System.getProperty("jboss.port", "1099");
- ht.put(InitialContext.PROVIDER_URL, "jnp://" + jbossHost + ":" + jbossPort);
- ht.put(InitialContext.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");
-
- try
- {
- ic = new InitialContext(ht);
- if (!doesDestinationExist("topictest.messages", ic))
- {
- deployTopic("topictest.messages", ic);
- }
- if (!doesDestinationExist("topictest.control", ic))
- {
- deployTopic("topictest.control", ic);
- }
-
- cf = (ConnectionFactory) ic.lookup("/ConnectionFactory");
- return cf;
- }
- catch (NamingException e)
- {
- throw new JMSAMQException("Unable to lookup object: " + e, e);
- }
- catch (Exception e)
- {
- throw new JMSAMQException("Error creating topic: " + e, e);
- }
- }
-
- private boolean doesDestinationExist(String name, InitialContext ic) throws Exception
- {
- try
- {
- ic.lookup("/" + name);
- }
- catch (NameNotFoundException e)
- {
- return false;
- }
- return true;
- }
-
- private void deployTopic(String name, InitialContext ic) throws Exception
- {
- MBeanServerConnection mBeanServer = lookupMBeanServerProxy(ic);
-
- ObjectName serverObjectName = new ObjectName("jboss.messaging:service=ServerPeer");
-
- String jndiName = "/" + name;
- try
- {
- mBeanServer.invoke(serverObjectName, "createTopic",
- new Object[]{name, jndiName},
- new String[]{"java.lang.String", "java.lang.String"});
- }
- catch (MBeanException e)
- {
- System.err.println("Error: " + e);
- System.err.println("Cause: " + e.getCause());
- }
- }
-
- private MBeanServerConnection lookupMBeanServerProxy(InitialContext ic) throws NamingException
- {
- return (MBeanServerConnection) ic.lookup("jmx/invoker/RMIAdaptor");
- }
-}
diff --git a/java/perftests/src/main/java/org/apache/qpid/oldtopic/Config.java b/java/perftests/src/main/java/org/apache/qpid/oldtopic/Config.java
deleted file mode 100644
index 5b6169ed2d..0000000000
--- a/java/perftests/src/main/java/org/apache/qpid/oldtopic/Config.java
+++ /dev/null
@@ -1,243 +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.oldtopic;
-
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.config.ConnectorConfig;
-import org.apache.qpid.config.ConnectionFactoryInitialiser;
-import org.apache.qpid.config.Connector;
-import org.apache.qpid.config.AbstractConfig;
-
-import javax.jms.Connection;
-import javax.jms.ConnectionFactory;
-
-class Config extends AbstractConfig implements ConnectorConfig
-{
-
- private String host = "localhost";
- private int port = 5672;
- private String factory = null;
-
- private int payload = 256;
- private int messages = 1000;
- private int clients = 1;
- private int batch = 1;
- private long delay = 1;
- private int warmup;
- private int ackMode= AMQSession.NO_ACKNOWLEDGE;
- private String clientId;
- private String subscriptionId;
- private boolean persistent;
-
- public Config()
- {
- }
-
- int getAckMode()
- {
- return ackMode;
- }
-
- void setPayload(int payload)
- {
- this.payload = payload;
- }
-
- int getPayload()
- {
- return payload;
- }
-
- void setClients(int clients)
- {
- this.clients = clients;
- }
-
- int getClients()
- {
- return clients;
- }
-
- void setMessages(int messages)
- {
- this.messages = messages;
- }
-
- int getMessages()
- {
- return messages;
- }
-
- public String getHost()
- {
- return host;
- }
-
- public void setHost(String host)
- {
- this.host = host;
- }
-
- public int getPort()
- {
- return port;
- }
-
- public String getFactory()
- {
- return factory;
- }
-
- public void setPort(int port)
- {
- this.port = port;
- }
-
- int getBatch()
- {
- return batch;
- }
-
- void setBatch(int batch)
- {
- this.batch = batch;
- }
-
- int getWarmup()
- {
- return warmup;
- }
-
- void setWarmup(int warmup)
- {
- this.warmup = warmup;
- }
-
- public long getDelay()
- {
- return delay;
- }
-
- public void setDelay(long delay)
- {
- this.delay = delay;
- }
-
- String getClientId()
- {
- return clientId;
- }
-
- String getSubscriptionId()
- {
- return subscriptionId;
- }
-
- boolean usePersistentMessages()
- {
- return persistent;
- }
-
- public void setOption(String key, String value)
- {
- if("-host".equalsIgnoreCase(key))
- {
- setHost(value);
- }
- else if("-port".equalsIgnoreCase(key))
- {
- try
- {
- setPort(Integer.parseInt(value));
- }
- catch(NumberFormatException e)
- {
- throw new RuntimeException("Bad port number: " + value);
- }
- }
- else if("-payload".equalsIgnoreCase(key))
- {
- setPayload(parseInt("Bad payload size", value));
- }
- else if("-messages".equalsIgnoreCase(key))
- {
- setMessages(parseInt("Bad message count", value));
- }
- else if("-clients".equalsIgnoreCase(key))
- {
- setClients(parseInt("Bad client count", value));
- }
- else if("-batch".equalsIgnoreCase(key))
- {
- setBatch(parseInt("Bad batch count", value));
- }
- else if("-delay".equalsIgnoreCase(key))
- {
- setDelay(parseLong("Bad batch delay", value));
- }
- else if("-warmup".equalsIgnoreCase(key))
- {
- setWarmup(parseInt("Bad warmup count", value));
- }
- else if("-ack".equalsIgnoreCase(key))
- {
- ackMode = parseInt("Bad ack mode", value);
- }
- else if("-factory".equalsIgnoreCase(key))
- {
- factory = value;
- }
- else if("-clientId".equalsIgnoreCase(key))
- {
- clientId = value;
- }
- else if("-subscriptionId".equalsIgnoreCase(key))
- {
- subscriptionId = value;
- }
- else if("-persistent".equalsIgnoreCase(key))
- {
- persistent = "true".equalsIgnoreCase(value);
- }
- else
- {
- System.out.println("Ignoring unrecognised option: " + key);
- }
- }
-
- static String getAckModeDescription(int ackMode)
- {
- switch(ackMode)
- {
- case AMQSession.NO_ACKNOWLEDGE: return "NO_ACKNOWLEDGE";
- case AMQSession.AUTO_ACKNOWLEDGE: return "AUTO_ACKNOWLEDGE";
- case AMQSession.CLIENT_ACKNOWLEDGE: return "CLIENT_ACKNOWLEDGE";
- case AMQSession.DUPS_OK_ACKNOWLEDGE: return "DUPS_OK_ACKNOWELDGE";
- case AMQSession.PRE_ACKNOWLEDGE: return "PRE_ACKNOWLEDGE";
- }
- return "AckMode=" + ackMode;
- }
-
- public Connection createConnection() throws Exception
- {
- return new Connector().createConnection(this);
- }
-}
diff --git a/java/perftests/src/main/java/org/apache/qpid/oldtopic/Listener.java b/java/perftests/src/main/java/org/apache/qpid/oldtopic/Listener.java
deleted file mode 100644
index 4732782d4c..0000000000
--- a/java/perftests/src/main/java/org/apache/qpid/oldtopic/Listener.java
+++ /dev/null
@@ -1,141 +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.oldtopic;
-import org.apache.log4j.*;
-import javax.jms.Connection;
-import javax.jms.Message;
-import javax.jms.MessageListener;
-import javax.jms.MessageProducer;
-import javax.jms.Session;
-
-public class Listener implements MessageListener
-{
- private final Connection _connection;
- private final MessageProducer _controller;
- private final javax.jms.Session _session;
- private final MessageFactory _factory;
- private boolean init;
- private int count;
- private long start;
-
- Listener(Connection connection, int ackMode) throws Exception
- {
- this(connection, ackMode, null);
- }
-
- Listener(Connection connection, int ackMode, String name) throws Exception
- {
- _connection = connection;
- _session = connection.createSession(false, ackMode);
- _factory = new MessageFactory(_session);
-
- //register for events
- if(name == null)
- {
- _factory.createTopicConsumer().setMessageListener(this);
- }
- else
- {
- _factory.createDurableTopicConsumer(name).setMessageListener(this);
- }
-
- _connection.start();
-
- _controller = _factory.createControlPublisher();
- System.out.println("Waiting for messages " +
- Config.getAckModeDescription(ackMode)
- + (name == null ? "" : " (subscribed with name " + name + " and client id " + connection.getClientID() + ")")
- + "...");
-
- }
-
- private void shutdown()
- {
- try
- {
- _session.close();
- _connection.stop();
- _connection.close();
- }
- catch(Exception e)
- {
- e.printStackTrace(System.out);
- }
- }
-
- private void report()
- {
- try
- {
- String msg = getReport();
- _controller.send(_factory.createReportResponseMessage(msg));
- System.out.println("Sent report: " + msg);
- }
- catch(Exception e)
- {
- e.printStackTrace(System.out);
- }
- }
-
- private String getReport()
- {
- long time = (System.currentTimeMillis() - start);
- return "Received " + count + " in " + time + "ms";
- }
-
- public void onMessage(Message message)
- {
- if(!init)
- {
- start = System.currentTimeMillis();
- count = 0;
- init = true;
- }
-
- if(_factory.isShutdown(message))
- {
- shutdown();
- }
- else if(_factory.isReport(message))
- {
- //send a report:
- report();
- init = false;
- }
- else if (++count % 100 == 0)
- {
- System.out.println("Received " + count + " messages.");
- }
- }
-
- public static void main(String[] argv) throws Exception
- {
- Config config = new Config();
- config.setOptions(argv);
-
- Connection con = config.createConnection();
- if(config.getClientId() != null)
- {
- con.setClientID(config.getClientId());
- }
- new Listener(con, config.getAckMode(), config.getSubscriptionId());
- }
-}
diff --git a/java/perftests/src/main/java/org/apache/qpid/oldtopic/MessageFactory.java b/java/perftests/src/main/java/org/apache/qpid/oldtopic/MessageFactory.java
deleted file mode 100644
index b2fbeb7e35..0000000000
--- a/java/perftests/src/main/java/org/apache/qpid/oldtopic/MessageFactory.java
+++ /dev/null
@@ -1,153 +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.oldtopic;
-
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.client.AMQTopic;
-
-import javax.jms.*;
-
-/**
- */
-class MessageFactory
-{
- private static final char[] DATA = "abcdefghijklmnopqrstuvwxyz".toCharArray();
-
- private final Session _session;
- private final Topic _topic;
- private final Topic _control;
- private final byte[] _payload;
-
-
- MessageFactory(Session session) throws JMSException
- {
- this(session, 256);
- }
-
- MessageFactory(Session session, int size) throws JMSException
- {
- _session = session;
-/* if(session instanceof AMQSession)
- {
- _topic = new AMQTopic("topictest.messages");
- _control = new AMQTopic("topictest.control");
- }
- else*/
- {
- _topic = session.createTopic("topictest.messages");
- _control = session.createTopic("topictest.control");
- }
- _payload = new byte[size];
-
- for(int i = 0; i < size; i++)
- {
- _payload[i] = (byte) DATA[i % DATA.length];
- }
- }
-
- Topic getTopic()
- {
- return _topic;
- }
-
- Message createEventMessage() throws JMSException
- {
- BytesMessage msg = _session.createBytesMessage();
- msg.writeBytes(_payload);
- return msg;
- }
-
- Message createShutdownMessage() throws JMSException
- {
- return _session.createTextMessage("SHUTDOWN");
- }
-
- Message createReportRequestMessage() throws JMSException
- {
- return _session.createTextMessage("REPORT");
- }
-
- Message createReportResponseMessage(String msg) throws JMSException
- {
- return _session.createTextMessage(msg);
- }
-
- boolean isShutdown(Message m)
- {
- return checkText(m, "SHUTDOWN");
- }
-
- boolean isReport(Message m)
- {
- return checkText(m, "REPORT");
- }
-
- Object getReport(Message m)
- {
- try
- {
- return ((TextMessage) m).getText();
- }
- catch (JMSException e)
- {
- e.printStackTrace(System.out);
- return e.toString();
- }
- }
-
- MessageConsumer createTopicConsumer() throws Exception
- {
- return _session.createConsumer(_topic);
- }
-
- MessageConsumer createDurableTopicConsumer(String name) throws Exception
- {
- return _session.createDurableSubscriber(_topic, name);
- }
-
- MessageConsumer createControlConsumer() throws Exception
- {
- return _session.createConsumer(_control);
- }
-
- MessageProducer createTopicPublisher() throws Exception
- {
- return _session.createProducer(_topic);
- }
-
- MessageProducer createControlPublisher() throws Exception
- {
- return _session.createProducer(_control);
- }
-
- private static boolean checkText(Message m, String s)
- {
- try
- {
- return m instanceof TextMessage && ((TextMessage) m).getText().equals(s);
- }
- catch (JMSException e)
- {
- e.printStackTrace(System.out);
- return false;
- }
- }
-}
diff --git a/java/perftests/src/main/java/org/apache/qpid/oldtopic/Publisher.java b/java/perftests/src/main/java/org/apache/qpid/oldtopic/Publisher.java
deleted file mode 100644
index f811704323..0000000000
--- a/java/perftests/src/main/java/org/apache/qpid/oldtopic/Publisher.java
+++ /dev/null
@@ -1,175 +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.oldtopic;
-
-import javax.jms.*;
-
-public class Publisher implements MessageListener
-{
- private final Object _lock = new Object();
- private final Connection _connection;
- private final Session _session;
- private final MessageFactory _factory;
- private final MessageProducer _publisher;
- private int _count;
-
- Publisher(Connection connection, int size, int ackMode, boolean persistent) throws Exception
- {
- _connection = connection;
- _session = _connection.createSession(false, ackMode);
- _factory = new MessageFactory(_session, size);
- _publisher = _factory.createTopicPublisher();
- _publisher.setDeliveryMode(persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT);
- System.out.println("Publishing " + (persistent ? "persistent" : "non-persistent") + " messages of " + size + " bytes, " + Config.getAckModeDescription(ackMode) + ".");
- }
-
- private void test(Config config) throws Exception
- {
- test(config.getBatch(), config.getDelay(), config.getMessages(), config.getClients(), config.getWarmup());
- }
-
- private void test(int batches, long delay, int msgCount, int consumerCount, int warmup) throws Exception
- {
- _factory.createControlConsumer().setMessageListener(this);
- _connection.start();
-
- if(warmup > 0)
- {
- System.out.println("Runing warmup (" + warmup + " msgs)");
- long time = batch(warmup, consumerCount);
- System.out.println("Warmup completed in " + time + "ms");
- }
-
- long[] times = new long[batches];
- for(int i = 0; i < batches; i++)
- {
- if(i > 0) Thread.sleep(delay*1000);
- times[i] = batch(msgCount, consumerCount);
- System.out.println("Batch " + (i+1) + " of " + batches + " completed in " + times[i] + " ms.");
- }
-
- long min = min(times);
- long max = max(times);
- System.out.println("min: " + min + ", max: " + max + " avg: " + avg(times, min, max));
-
- //request shutdown
- _publisher.send(_factory.createShutdownMessage());
-
- _connection.stop();
- _connection.close();
- }
-
- private long batch(int msgCount, int consumerCount) throws Exception
- {
- _count = consumerCount;
- long start = System.currentTimeMillis();
- publish(msgCount);
- waitForCompletion(consumerCount);
- return System.currentTimeMillis() - start;
- }
-
- private void publish(int count) throws Exception
- {
-
- //send events
- for (int i = 0; i < count; i++)
- {
- _publisher.send(_factory.createEventMessage());
- if ((i + 1) % 100 == 0)
- {
- System.out.println("Sent " + (i + 1) + " messages");
- }
- }
-
- //request report
- _publisher.send(_factory.createReportRequestMessage());
- }
-
- private void waitForCompletion(int consumers) throws Exception
- {
- System.out.println("Waiting for completion...");
- synchronized (_lock)
- {
- while (_count > 0)
- {
- _lock.wait();
- }
- }
- }
-
-
- public void onMessage(Message message)
- {
- System.out.println("Received report " + _factory.getReport(message) + " " + --_count + " remaining");
- if (_count == 0)
- {
- synchronized (_lock)
- {
- _lock.notify();
- }
- }
- }
-
- static long min(long[] times)
- {
- long min = times.length > 0 ? times[0] : 0;
- for(int i = 0; i < times.length; i++)
- {
- min = Math.min(min, times[i]);
- }
- return min;
- }
-
- static long max(long[] times)
- {
- long max = times.length > 0 ? times[0] : 0;
- for(int i = 0; i < times.length; i++)
- {
- max = Math.max(max, times[i]);
- }
- return max;
- }
-
- static long avg(long[] times, long min, long max)
- {
- long sum = 0;
- for(int i = 0; i < times.length; i++)
- {
- sum += times[i];
- }
- sum -= min;
- sum -= max;
-
- return (sum / (times.length - 2));
- }
-
- public static void main(String[] argv) throws Exception
- {
- Config config = new Config();
- config.setOptions(argv);
-
- Connection con = config.createConnection();
- int size = config.getPayload();
- int ackMode = config.getAckMode();
- boolean persistent = config.usePersistentMessages();
- new Publisher(con, size, ackMode, persistent).test(config);
- }
-}
diff --git a/java/perftests/src/main/java/org/apache/qpid/ping/PingAsyncTestPerf.java b/java/perftests/src/main/java/org/apache/qpid/ping/PingAsyncTestPerf.java
deleted file mode 100644
index dc78276edd..0000000000
--- a/java/perftests/src/main/java/org/apache/qpid/ping/PingAsyncTestPerf.java
+++ /dev/null
@@ -1,322 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.ping;
-
-import junit.framework.Test;
-import junit.framework.TestSuite;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.requestreply.PingPongProducer;
-
-import org.apache.qpid.junit.extensions.TimingController;
-import org.apache.qpid.junit.extensions.TimingControllerAware;
-
-import javax.jms.JMSException;
-import javax.jms.Message;
-
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.concurrent.atomic.AtomicLong;
-
-/**
- * PingAsyncTestPerf is a performance test that outputs multiple timings from its test method, using the timing controller
- * interface supplied by the test runner from a seperate listener thread. It differs from the {@link PingTestPerf} test
- * that it extends because it can output timings as replies are received, rather than waiting until all expected replies
- * are received. This is less 'blocky' than the tests in {@link PingTestPerf}, and provides a truer simulation of sending
- * and recieving clients working asynchronously.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><td> Responsibilities <th> Collaborations
- * <tr><td> Send many ping messages and output timings asynchronously on batches received.
- * </table>
- */
-public class PingAsyncTestPerf extends PingTestPerf implements TimingControllerAware
-{
- private static Logger _logger = Logger.getLogger(PingAsyncTestPerf.class);
-
- /** Holds the name of the property to get the test results logging batch size. */
- public static final String TEST_RESULTS_BATCH_SIZE_PROPNAME = "batchSize";
-
- /** Holds the default test results logging batch size. */
- public static final int TEST_RESULTS_BATCH_SIZE_DEFAULT = 1000;
-
- /** Used to hold the timing controller passed from the test runner. */
- private TimingController _timingController;
-
- /** Used to generate unique correlation ids for each test run. */
- private AtomicLong corellationIdGenerator = new AtomicLong();
-
- /** Holds test specifics by correlation id. This consists of the expected number of messages and the timing controler. */
- private Map<String, PerCorrelationId> perCorrelationIds =
- Collections.synchronizedMap(new HashMap<String, PerCorrelationId>());
-
- /** Holds the batched results listener, that does logging on batch boundaries. */
- private BatchedResultsListener batchedResultsListener = null;
-
- /**
- * Creates a new asynchronous ping performance test with the specified name.
- *
- * @param name The test name.
- */
- public PingAsyncTestPerf(String name)
- {
- super(name);
-
- // Sets up the test parameters with defaults.
- testParameters.setPropertyIfNull(TEST_RESULTS_BATCH_SIZE_PROPNAME,
- Integer.toString(TEST_RESULTS_BATCH_SIZE_DEFAULT));
- }
-
- /**
- * Compile all the tests into a test suite.
- * @return The test suite to run. Should only contain testAsyncPingOk method.
- */
- public static Test suite()
- {
- // Build a new test suite
- TestSuite suite = new TestSuite("Ping Performance Tests");
-
- // Run performance tests in read committed mode.
- suite.addTest(new PingAsyncTestPerf("testAsyncPingOk"));
-
- return suite;
- }
-
- /**
- * Accepts a timing controller from the test runner.
- *
- * @param timingController The timing controller to register mutliple timings with.
- */
- public void setTimingController(TimingController timingController)
- {
- _timingController = timingController;
- }
-
- /**
- * Gets the timing controller passed in by the test runner.
- *
- * @return The timing controller passed in by the test runner.
- */
- public TimingController getTimingController()
- {
- return _timingController;
- }
-
- /**
- * Sends the specified number of pings, asynchronously outputs timings on every batch boundary, and waits until
- * all replies have been received or a time out occurs before exiting this method.
- *
- * @param numPings The number of pings to send.
- * @throws Exception pass all errors out to the test harness
- */
- public void testAsyncPingOk(int numPings) throws Exception
- {
- // _logger.debug("public void testAsyncPingOk(int numPings): called");
-
- // get prefill count to update the expected count
- int preFill = testParameters.getPropertyAsInteger(PingPongProducer.PREFILL_PROPNAME);
-
- // Ensure that at least one ping was requeusted.
- if (numPings + preFill == 0)
- {
- _logger.error("Number of pings requested was zero.");
- fail("Number of pings requested was zero.");
- }
-
- // Get the per thread test setup to run the test through.
- PerThreadSetup perThreadSetup = threadSetup.get();
- PingClient pingClient = perThreadSetup._pingClient;
-
- // Advance the correlation id of messages to send, to make it unique for this run.
- perThreadSetup._correlationId = Long.toString(corellationIdGenerator.incrementAndGet());
- // String messageCorrelationId = perThreadSetup._correlationId;
- // _logger.debug("messageCorrelationId = " + messageCorrelationId);
-
-
- // Initialize the count and timing controller for the new correlation id.
- // This perCorrelationId is only used for controlling the test.
- // The PingClient itself uses its own perCorrelationId see in PingPongProducer
- PerCorrelationId perCorrelationId = new PerCorrelationId();
- TimingController tc = getTimingController().getControllerForCurrentThread();
- perCorrelationId._tc = tc;
- perCorrelationId._expectedCount = pingClient.getExpectedNumPings(numPings + preFill);
- perCorrelationIds.put(perThreadSetup._correlationId, perCorrelationId);
-
- // Must be called before pingAndWaitForReply to setup the CorrelationID.
- // This is required because pingClient.start() will start all client threads
- // This means that the CorrelationID must be registered before hand.
- pingClient.setupCorrelationID(perThreadSetup._correlationId, perCorrelationId._expectedCount);
-
- // Start the client connection if:
- // 1) we are not in a SEND_ONLY test.
- // 2) if we have not yet started client because messages are sitting on broker.
- // This is either due to a preFill or a consume only test.
- if (!testParameters.getPropertyAsBoolean(PingPongProducer.SEND_ONLY_PROPNAME) &&
- (preFill > 0 || testParameters.getPropertyAsBoolean(PingPongProducer.CONSUME_ONLY_PROPNAME)))
- {
- pingClient.start();
- }
-
- // Send the requested number of messages, and wait until they have all been received.
- long timeout = Long.parseLong(testParameters.getProperty(PingPongProducer.TIMEOUT_PROPNAME));
- int numReplies = pingClient.pingAndWaitForReply(null, numPings , preFill, timeout, perThreadSetup._correlationId);
-
- // Check that all the replies were received and log a fail if they were not.
- if (numReplies < perCorrelationId._expectedCount)
- {
- perCorrelationId._tc.completeTest(false, numPings - perCorrelationId._expectedCount);
- }
-
- // Remove the expected count and timing controller for the message correlation id, to ensure they are cleaned up.
- perCorrelationIds.remove(perThreadSetup._correlationId);
- }
-
- /**
- * Performs test fixture creation on a per thread basis. This will only be called once for each test thread.
- */
- public void threadSetUp()
- {
- _logger.debug("public void threadSetUp(): called");
-
- try
- {
- // Call the set up method in the super class. This creates a PingClient pinger.
- super.threadSetUp();
-
- // Create the chained message listener, only if it has not already been created. This is set up with the
- // batch size property, to tell it what batch size to output results on. A synchronized block is used to
- // ensure that only one thread creates this.
- synchronized (this)
- {
- if (batchedResultsListener == null)
- {
- int batchSize = Integer.parseInt(testParameters.getProperty(TEST_RESULTS_BATCH_SIZE_PROPNAME));
- batchedResultsListener = new BatchedResultsListener(batchSize);
- }
- }
-
- // Get the set up that the super class created.
- PerThreadSetup perThreadSetup = threadSetup.get();
-
- // Register the chained message listener on the pinger to do its asynchronous test timings from.
- perThreadSetup._pingClient.setChainedMessageListener(batchedResultsListener);
- }
- catch (Exception e)
- {
- _logger.warn("There was an exception during per thread setup.", e);
- }
- }
-
- /**
- * BatchedResultsListener is a {@link PingPongProducer.ChainedMessageListener} that can be attached to the
- * pinger, in order to receive notifications about every message received and the number remaining to be
- * received. Whenever the number remaining crosses a batch size boundary this results listener outputs
- * a test timing for the actual number of messages received in the current batch.
- */
- private class BatchedResultsListener implements PingPongProducer.ChainedMessageListener
- {
- /** The test results logging batch size. */
- int _batchSize;
-
- /** The latency recoreded for the batch */
- private long _batchLatency = 0;
-
- /**
- * Creates a results listener on the specified batch size.
- *
- * @param batchSize The batch size to use.
- */
- public BatchedResultsListener(int batchSize)
- {
- _batchSize = batchSize;
- }
-
- /**
- * This callback method is called from all of the pingers that this test creates. It uses the correlation id
- * from the message to identify the timing controller for the test thread that was responsible for sending those
- * messages.
- *
- * @param message The message.
- * @param remainingCount The count of messages remaining to be received with a particular correlation id.
- *
- * @throws JMSException Any underlying JMSException is allowed to fall through.
- */
- public void onMessage(Message message, int remainingCount, long latency) throws JMSException
- {
- // Record the latency for the whole batch
- _batchLatency += latency;
- // Check if a batch boundary has been crossed.
- if ((remainingCount % _batchSize) == 0)
- {
- // Extract the correlation id from the message.
- String correlationId = message.getJMSCorrelationID();
-
- /*_logger.debug("public void onMessage(Message message, int remainingCount = " + remainingCount
- + "): called on batch boundary for message id: " + correlationId + " with thread id: "
- + Thread.currentThread().getId());*/
-
- // Get the details for the correlation id and check that they are not null. They can become null
- // if a test times out.
- PerCorrelationId perCorrelationId = perCorrelationIds.get(correlationId);
- if (perCorrelationId != null)
- {
- // Get the timing controller and expected count for this correlation id.
- TimingController tc = perCorrelationId._tc;
- int expected = perCorrelationId._expectedCount;
-
- // Calculate how many messages were actually received in the last batch. This will be the batch size
- // except where the number expected is not a multiple of the batch size and this is the first remaining
- // count to cross a batch size boundary, in which case it will be the number expected modulo the batch
- // size.
- int receivedInBatch = ((expected - remainingCount) < _batchSize) ? (expected % _batchSize) : _batchSize;
-
- // Register a test result for the correlation id.
- try
- {
- // Record the total latency for the batch.
- // if batchSize=1 then this will just be the message latency
- tc.completeTest(true, receivedInBatch, null, _batchSize == 1 ? latency : _batchLatency);
- // Reset latency
- _batchLatency = 0;
- }
- catch (InterruptedException e)
- {
- // Ignore this. It means the test runner wants to stop as soon as possible.
- _logger.warn("Got InterruptedException.", e);
- }
- }
- // Else ignore, test timed out. Should log a fail here?
- }
- }
- }
-
- /**
- * Holds state specific to each correlation id, needed to output test results. This consists of the count of
- * the total expected number of messages, and the timing controller for the thread sending those message ids.
- */
- private static class PerCorrelationId
- {
- public int _expectedCount;
- public TimingController _tc;
- }
-}
diff --git a/java/perftests/src/main/java/org/apache/qpid/ping/PingClient.java b/java/perftests/src/main/java/org/apache/qpid/ping/PingClient.java
deleted file mode 100644
index dcfc67d4fc..0000000000
--- a/java/perftests/src/main/java/org/apache/qpid/ping/PingClient.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.ping;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.requestreply.PingPongProducer;
-
-import javax.jms.Destination;
-
-import java.util.List;
-import java.util.Properties;
-
-/**
- * PingClient is a {@link PingPongProducer} that does not need a {@link org.apache.qpid.requestreply.PingPongBouncer}
- * to send replies to its pings. It simply listens to its own ping destinations, rather than seperate reply queues.
- * It is an all in one ping client, that produces and consumes its own pings.
- *
- * <p/>The constructor increments a count of the number of ping clients created. It is assumed that where many
- * are created they will all be run in parallel and be active in sending and consuming pings at the same time.
- * If the unique destinations flag is not set and a pub/sub ping cycle is being run, this means that they will all hear
- * pings sent by each other. The expected number of pings received will therefore be multiplied up by the number of
- * active ping clients. The {@link #getConsumersPerDestination()} method is used to supply this multiplier under these
- * conditions.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Create a ping producer that listens to its own pings <td> {@link PingPongProducer}
- * <tr><td> Count the number of ping producers and produce multiplier for scaling up messages expected over topic pings.
- * </table>
- */
-public class PingClient extends PingPongProducer
-{
- /** Used for debugging. */
- private final Logger log = Logger.getLogger(PingClient.class);
-
- /** Used to count the number of ping clients created. */
- private static int _pingClientCount;
-
- /**
- * Creates a ping producer with the specified parameters, of which there are many. See the class level comments
- * for {@link PingPongProducer} for details. This constructor creates a connection to the broker and creates
- * producer and consumer sessions on it, to send and recieve its pings and replies on.
- *
- * @param overrides Properties containing any desired overrides to the defaults.
- *
- * @throws Exception Any exceptions are allowed to fall through.
- */
- public PingClient(Properties overrides) throws Exception
- {
- super(overrides);
-
- _pingClientCount++;
- }
-
- /**
- * Returns the ping destinations themselves as the reply destinations for this pinger to listen to. This has the
- * effect of making this pinger listen to its own pings.
- *
- * @return The ping destinations.
- */
- public List<Destination> getReplyDestinations()
- {
- return _pingDestinations;
- }
-
- /**
- * Supplies the multiplier for the number of ping clients that will hear each ping when doing pub/sub pinging.
- *
- * @return The scaling up of the number of expected pub/sub pings.
- */
- public int getConsumersPerDestination()
- {
- log.debug("public int getConsumersPerDestination(): called");
-
- if (_isUnique)
- {
- log.debug(_noOfConsumers + " consumer per destination.");
-
- return _noOfConsumers;
- }
- else
- {
- log.debug((_pingClientCount * _noOfConsumers) + " consumers per destination.");
-
- return _pingClientCount * _noOfConsumers;
- }
- }
-
- public int getClientCount()
- {
- return _pingClientCount;
- }
-}
diff --git a/java/perftests/src/main/java/org/apache/qpid/ping/PingDurableClient.java b/java/perftests/src/main/java/org/apache/qpid/ping/PingDurableClient.java
deleted file mode 100644
index a15897c82b..0000000000
--- a/java/perftests/src/main/java/org/apache/qpid/ping/PingDurableClient.java
+++ /dev/null
@@ -1,452 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.ping;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.requestreply.PingPongProducer;
-import org.apache.qpid.util.CommandLineParser;
-
-import org.apache.qpid.junit.extensions.util.MathUtils;
-import org.apache.qpid.junit.extensions.util.ParsedProperties;
-
-import javax.jms.*;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.util.List;
-import java.util.Properties;
-import java.util.concurrent.atomic.AtomicInteger;
-
-/**
- * PingDurableClient is a variation of the {@link PingPongProducer} ping tool. Instead of sending its pings and
- * receiving replies to them at the same time, this tool sends pings until it is signalled by some 'event' to stop
- * sending. It then waits for another signal before it re-opens a fresh connection and attempts to receive all of the
- * pings that it has succesfully sent. It is intended to be an interactive test that lets a user experiment with
- * failure conditions when using durable messaging.
- *
- * <p/>The events that can stop it from sending are input from the user on the console, failure of its connection to
- * the broker, completion of sending a specified number of messages, or expiry of a specified duration. In all cases
- * it will do its best to clean up and close the connection before opening a fresh connection to receive the pings
- * with.
- *
- * <p/>The event to re-connect and attempt to recieve the pings is input from the user on the console.
- *
- * <p/>This ping client inherits the configuration properties of its parent class ({@link PingPongProducer}) and
- * additionally accepts the following parameters:
- *
- * <p/><table><caption>Parameters</caption>
- * <tr><th> Parameter <th> Default <th> Comments
- * <tr><td> numMessages <td> 100 <td> The total number of messages to send.
- * <tr><td> numMessagesToAction <td> -1 <td> The number of messages to send before taking a custom 'action'.
- * <tr><td> duration <td> 30S <td> The length of time to ping for. (Format dDhHmMsS, for d days, h hours,
- * m minutes and s seconds).
- * </table>
- *
- * <p/>This ping client also overrides some of the defaults of its parent class, to provide a reasonable set up
- * when no parameters are specified.
- *
- * <p/><table><caption>Parameters</caption>
- * <tr><th> Parameter <th> Default <th> Comments
- * <tr><td> uniqueDests <td> false <td> Prevents destination names being timestamped.
- * <tr><td> transacted <td> true <td> Only makes sense to test with transactions.
- * <tr><td> persistent <td> true <td> Only makes sense to test persistent.
- * <tr><td> durableDests <td> true <td> Should use durable queues with persistent messages.
- * <tr><td> commitBatchSize <td> 10
- * <tr><td> rate <td> 20 <td> Total default test time is 5 seconds.
- * </table>
- *
- * <p/>When a number of messages or duration is specified, this ping client will ping until the first of those limits
- * is reached. Reaching the limit will be interpreted as the first signal to stop sending, and the ping client will
- * wait for the second signal before receiving its pings.
- *
- * <p/>This class provides a mechanism for extensions to add arbitrary actions, after a particular number of messages
- * have been sent. When the number of messages equal the value set in the 'numMessagesToAction' property is method,
- * the {@link #takeAction} method is called. By default this does nothing, but extensions of this class can provide
- * custom behaviour with alternative implementations of this method (for example taking a backup).
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Send and receive pings.
- * <tr><td> Accept user input to signal stop sending.
- * <tr><td> Accept user input to signal start receiving.
- * <tr><td> Provide feedback on pings sent versus pings received.
- * <tr><td> Provide extension point for arbitrary action on a particular message count.
- * </table>
- */
-public class PingDurableClient extends PingPongProducer implements ExceptionListener
-{
- private static final Logger log = Logger.getLogger(PingDurableClient.class);
-
- public static final String NUM_MESSAGES_PROPNAME = "numMessages";
- public static final String NUM_MESSAGES_DEFAULT = "100";
- public static final String DURATION_PROPNAME = "duration";
- public static final String DURATION_DEFAULT = "30S";
- public static final String NUM_MESSAGES_TO_ACTION_PROPNAME = "numMessagesToAction";
- public static final String NUM_MESSAGES_TO_ACTION_DEFAULT = "-1";
-
- /** The maximum length of time to wait whilst receiving pings before assuming that no more are coming. */
- private static final long TIME_OUT = 3000;
-
- static
- {
- defaults.setProperty(NUM_MESSAGES_PROPNAME, NUM_MESSAGES_DEFAULT);
- defaults.setProperty(DURATION_PROPNAME, DURATION_DEFAULT);
- defaults.setProperty(UNIQUE_DESTS_PROPNAME, "false");
- defaults.setProperty(TRANSACTED_PROPNAME, "true");
- defaults.setProperty(PERSISTENT_MODE_PROPNAME, "true");
- defaults.setProperty(TX_BATCH_SIZE_PROPNAME, "10");
- defaults.setProperty(RATE_PROPNAME, "20");
- defaults.setProperty(DURABLE_DESTS_PROPNAME, "true");
- defaults.setProperty(NUM_MESSAGES_TO_ACTION_PROPNAME, NUM_MESSAGES_TO_ACTION_DEFAULT);
- }
-
- /** Specifies the number of pings to send, if larger than 0. 0 means send until told to stop. */
- private int numMessages;
-
- /** Holds the number of messages to send before taking triggering the action. */
- private int numMessagesToAction;
-
- /** Sepcifies how long to ping for, if larger than 0. 0 means send until told to stop. */
- private long duration;
-
- /** Used to indciate that this application should terminate. Set by the shutdown hook. */
- private boolean terminate = false;
-
- /**
- * @throws Exception Any exceptions are allowed to fall through.
- */
- public PingDurableClient(Properties overrides) throws Exception
- {
- super(overrides);
- log.debug("public PingDurableClient(Properties overrides = " + overrides + "): called");
-
- // Extract the additional configuration parameters.
- ParsedProperties properties = new ParsedProperties(defaults);
- properties.putAll(overrides);
-
- numMessages = properties.getPropertyAsInteger(NUM_MESSAGES_PROPNAME);
- String durationSpec = properties.getProperty(DURATION_PROPNAME);
- numMessagesToAction = properties.getPropertyAsInteger(NUM_MESSAGES_TO_ACTION_PROPNAME);
-
- if (durationSpec != null)
- {
- duration = MathUtils.parseDuration(durationSpec) * 1000000;
- }
- }
-
- /**
- * Starts the ping/wait/receive process.
- *
- * @param args The command line arguments.
- */
- public static void main(String[] args)
- {
- try
- {
- // Create a ping producer overriding its defaults with all options passed on the command line.
- Properties options =
- CommandLineParser.processCommandLine(args, new CommandLineParser(new String[][] {}), System.getProperties());
- PingDurableClient pingProducer = new PingDurableClient(options);
-
- // Create a shutdown hook to terminate the ping-pong producer.
- Runtime.getRuntime().addShutdownHook(pingProducer.getShutdownHook());
-
- // Ensure that the ping pong producer is registered to listen for exceptions on the connection too.
- // pingProducer.getConnection().setExceptionListener(pingProducer);
-
- // Run the test procedure.
- int sent = pingProducer.send();
- pingProducer.closeConnection();
- pingProducer.waitForUser("Press return to begin receiving the pings.");
- pingProducer.receive(sent);
-
- System.exit(0);
- }
- catch (Exception e)
- {
- System.err.println(e.getMessage());
- log.error("Top level handler caught execption.", e);
- System.exit(1);
- }
- }
-
- /**
- * Performs the main test procedure implemented by this ping client. See the class level comment for details.
- */
- protected int send() throws Exception
- {
- log.debug("public void sendWaitReceive(): called");
-
- log.debug("duration = " + duration);
- log.debug("numMessages = " + numMessages);
-
- if (duration > 0)
- {
- System.out.println("Sending for up to " + (duration / 1000000000f) + " seconds.");
- }
-
- if (_rate > 0)
- {
- System.out.println("Sending at " + _rate + " messages per second.");
- }
-
- if (numMessages > 0)
- {
- System.out.println("Sending up to " + numMessages + " messages.");
- }
-
- // Establish the connection and the message producer.
- establishConnection(true, false);
- _connection.start();
-
- Message message = getTestMessage(getReplyDestinations().get(0), _messageSize, _persistent);
-
- // Send pings until a terminating condition is received.
- boolean endCondition = false;
- int messagesSent = 0;
- int messagesCommitted = 0;
- int messagesNotCommitted = 0;
- long start = System.nanoTime();
-
- // Clear console in.
- clearConsole();
-
- while (!endCondition)
- {
- boolean committed = false;
-
- try
- {
- committed = sendMessage(messagesSent, message) && _transacted;
-
- messagesSent++;
- messagesNotCommitted++;
-
- // Keep count of the number of messsages currently committed and pending commit.
- if (committed)
- {
- log.debug("Adding " + messagesNotCommitted + " messages to the committed count.");
- messagesCommitted += messagesNotCommitted;
- messagesNotCommitted = 0;
-
- System.out.println("Commited: " + messagesCommitted);
- }
- }
- catch (JMSException e)
- {
- log.debug("Got JMSException whilst sending.");
- _publish = false;
- }
-
- // Perform the arbitrary action if the number of messages sent has reached the right number.
- if (messagesSent == numMessagesToAction)
- {
- System.out.println("At action point, Messages sent = " + messagesSent + ", Messages Committed = "
- + messagesCommitted + ", Messages not Committed = " + messagesNotCommitted);
- takeAction();
- }
-
- // Determine if the end condition has been met, based on the number of messages, time passed, errors on
- // the connection or user input.
- long now = System.nanoTime();
-
- if ((duration != 0) && ((now - start) > duration))
- {
- System.out.println("Send halted because duration expired.");
- endCondition = true;
- }
- else if ((numMessages != 0) && (messagesSent >= numMessages))
- {
- System.out.println("Send halted because # messages completed.");
- endCondition = true;
- }
- else if (System.in.available() > 0)
- {
- System.out.println("Send halted by user input.");
- endCondition = true;
-
- clearConsole();
- }
- else if (!_publish)
- {
- System.out.println("Send halted by error on the connection.");
- endCondition = true;
- }
- }
-
- log.debug("messagesSent = " + messagesSent);
- log.debug("messagesCommitted = " + messagesCommitted);
- log.debug("messagesNotCommitted = " + messagesNotCommitted);
-
- System.out.println("Messages sent: " + messagesSent + ", Messages Committed = " + messagesCommitted
- + ", Messages not Committed = " + messagesNotCommitted);
-
- return messagesSent;
- }
-
- protected void closeConnection()
- {
- // Clean up the connection.
- try
- {
- close();
- }
- catch (JMSException e)
- {
- log.debug("There was an error whilst closing the connection: " + e, e);
- System.out.println("There was an error whilst closing the connection.");
-
- // Ignore as did best could manage to clean up.
- }
- }
-
- protected void receive(int messagesSent) throws Exception
- {
- // Re-establish the connection and the message consumer.
- _queueJVMSequenceID = new AtomicInteger();
- _queueSharedID = new AtomicInteger();
-
- establishConnection(false, true);
- _consumer[0].setMessageListener(null);
- _consumerConnection[0].start();
-
- // Try to receive all of the pings that were successfully sent.
- int messagesReceived = 0;
- boolean endCondition = false;
-
- while (!endCondition)
- {
- // Message received = _consumer.receiveNoWait();
- Message received = _consumer[0].receive(TIME_OUT);
- log.debug("received = " + received);
-
- if (received != null)
- {
- messagesReceived++;
- }
-
- // Determine if the end condition has been met, based on the number of messages and time passed since last
- // receiving a message.
- if (received == null)
- {
- System.out.println("Timed out.");
- endCondition = true;
- }
- else if (messagesReceived >= messagesSent)
- {
- System.out.println("Got all messages.");
- endCondition = true;
- }
- }
-
- // Ensure messages received are committed.
- if (_consTransacted)
- {
- try
- {
- _consumerSession[0].commit();
- System.out.println("Committed for all messages received.");
- }
- catch (JMSException e)
- {
- log.debug("Error during commit: " + e, e);
- System.out.println("Error during commit.");
- try
- {
- _consumerSession[0].rollback();
- System.out.println("Rolled back on all messages received.");
- }
- catch (JMSException e2)
- {
- log.debug("Error during rollback: " + e, e);
- System.out.println("Error on roll back of all messages received.");
- }
-
- }
- }
-
- log.debug("messagesReceived = " + messagesReceived);
-
- System.out.println("Messages received: " + messagesReceived);
-
- // Clean up the connection.
- close();
- }
-
- /**
- * Clears any pending input from the console.
- */
- private void clearConsole()
- {
- try
- {
- BufferedReader bis = new BufferedReader(new InputStreamReader(System.in));
-
- // System.in.skip(System.in.available());
- while (bis.ready())
- {
- bis.readLine();
- }
- }
- catch (IOException e)
- { }
- }
-
- /**
- * Returns the ping destinations themselves as the reply destinations for this pinger to listen to. This has the
- * effect of making this pinger listen to its own pings.
- *
- * @return The ping destinations.
- */
- public List<Destination> getReplyDestinations()
- {
- return _pingDestinations;
- }
-
- /**
- * Gets a shutdown hook that will cleanly shut this down when it is running the ping loop. This can be registered with
- * the runtime system as a shutdown hook. This shutdown hook sets an additional terminate flag, compared with the
- * shutdown hook in {@link PingPongProducer}, because the publish flag is used to indicate that sending or receiving
- * message should stop, not that the application should termiante.
- *
- * @return A shutdown hook for the ping loop.
- */
- public Thread getShutdownHook()
- {
- return new Thread(new Runnable()
- {
- public void run()
- {
- stop();
- terminate = true;
- }
- });
- }
-
- /**
- * Performs an aribtrary action once the 'numMesagesToAction' count is reached on sending messages. This default
- * implementation does nothing.
- */
- public void takeAction()
- { }
-}
diff --git a/java/perftests/src/main/java/org/apache/qpid/ping/PingLatencyTestPerf.java b/java/perftests/src/main/java/org/apache/qpid/ping/PingLatencyTestPerf.java
deleted file mode 100644
index 5ba4004c56..0000000000
--- a/java/perftests/src/main/java/org/apache/qpid/ping/PingLatencyTestPerf.java
+++ /dev/null
@@ -1,311 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.ping;
-
-import junit.framework.Test;
-import junit.framework.TestSuite;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.requestreply.PingPongProducer;
-
-import org.apache.qpid.junit.extensions.TimingController;
-import org.apache.qpid.junit.extensions.TimingControllerAware;
-import org.apache.qpid.junit.extensions.util.ParsedProperties;
-
-import javax.jms.JMSException;
-import javax.jms.Message;
-
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.concurrent.atomic.AtomicLong;
-
-/**
- * PingLatencyTestPerf is a performance test that outputs multiple timings from its test method, using the timing
- * controller interface supplied by the test runner from a seperate listener thread. It outputs round trip timings for
- * individual ping messages rather than for how long a complete batch of messages took to process. It also differs from
- * the {@link PingTestPerf} test that it extends because it can output timings as replies are received, rather than
- * waiting until all expected replies are received.
- *
- * <p/>This test does not output timings for every single ping message, as when running at high volume, writing the test
- * log for a vast number of messages would slow the testing down. Instead samples ping latency occasionally. The
- * frequency of ping sampling is set using the {@link #TEST_RESULTS_BATCH_SIZE_PROPNAME} property, to override the
- * default of every {@link #DEFAULT_TEST_RESULTS_BATCH_SIZE}.
- *
- * <p/>The size parameter logged for each individual ping is set to the size of the batch of messages that the
- * individual timed ping was taken from, rather than 1 for a single message. This is so that the total throughput
- * (messages / time) can be calculated in order to examine the relationship between throughput and latency.
- *
- * <p/><table id="crc"><caption>CRC Card</caption> <tr><td> Responsibilities <th> Collaborations <tr><td> Send many ping
- * messages and output timings for sampled individual pings. </table>
- */
-public class PingLatencyTestPerf extends PingTestPerf implements TimingControllerAware
-{
- private static Logger _logger = Logger.getLogger(PingLatencyTestPerf.class);
-
- /** Holds the name of the property to get the test results logging batch size. */
- public static final String TEST_RESULTS_BATCH_SIZE_PROPNAME = "batchSize";
-
- /** Holds the default test results logging batch size. */
- public static final int DEFAULT_TEST_RESULTS_BATCH_SIZE = 1000;
-
- /** Used to hold the timing controller passed from the test runner. */
- private TimingController _timingController;
-
- /** Used to generate unique correlation ids for each test run. */
- private AtomicLong corellationIdGenerator = new AtomicLong();
-
- /**
- * Holds test specifics by correlation id. This consists of the expected number of messages and the timing
- * controler.
- */
- private Map<String, PerCorrelationId> perCorrelationIds =
- Collections.synchronizedMap(new HashMap<String, PerCorrelationId>());
-
- /** Holds the batched results listener, that does logging on batch boundaries. */
- private BatchedResultsListener batchedResultsListener = null;
-
- /**
- * Creates a new asynchronous ping performance test with the specified name.
- *
- * @param name The test name.
- */
- public PingLatencyTestPerf(String name)
- {
- super(name);
-
- // Sets up the test parameters with defaults.
- ParsedProperties.setSysPropertyIfNull(TEST_RESULTS_BATCH_SIZE_PROPNAME,
- Integer.toString(DEFAULT_TEST_RESULTS_BATCH_SIZE));
- }
-
- /** Compile all the tests into a test suite. */
- public static Test suite()
- {
- // Build a new test suite
- TestSuite suite = new TestSuite("Ping Latency Tests");
-
- // Run performance tests in read committed mode.
- suite.addTest(new PingLatencyTestPerf("testPingLatency"));
-
- return suite;
- }
-
- /**
- * Accepts a timing controller from the test runner.
- *
- * @param timingController The timing controller to register mutliple timings with.
- */
- public void setTimingController(TimingController timingController)
- {
- _timingController = timingController;
- }
-
- /**
- * Gets the timing controller passed in by the test runner.
- *
- * @return The timing controller passed in by the test runner.
- */
- public TimingController getTimingController()
- {
- return _timingController;
- }
-
- /**
- * Sends the specified number of pings, asynchronously outputs timings on every batch boundary, and waits until all
- * replies have been received or a time out occurs before exiting this method.
- *
- * @param numPings The number of pings to send.
- */
- public void testPingLatency(int numPings) throws Exception
- {
- _logger.debug("public void testPingLatency(int numPings): called");
-
- // Ensure that at least one ping was requeusted.
- if (numPings == 0)
- {
- _logger.error("Number of pings requested was zero.");
- }
-
- // Get the per thread test setup to run the test through.
- PerThreadSetup perThreadSetup = threadSetup.get();
- PingClient pingClient = perThreadSetup._pingClient;
-
- // Advance the correlation id of messages to send, to make it unique for this run.
- String messageCorrelationId = Long.toString(corellationIdGenerator.incrementAndGet());
- _logger.debug("messageCorrelationId = " + messageCorrelationId);
-
- // Initialize the count and timing controller for the new correlation id.
- PerCorrelationId perCorrelationId = new PerCorrelationId();
- TimingController tc = getTimingController().getControllerForCurrentThread();
- perCorrelationId._tc = tc;
- perCorrelationId._expectedCount = numPings;
- perCorrelationIds.put(messageCorrelationId, perCorrelationId);
-
- // Attach the chained message listener to the ping producer to listen asynchronously for the replies to these
- // messages.
- pingClient.setChainedMessageListener(batchedResultsListener);
-
- // Generate a sample message of the specified size.
- Message msg =
- pingClient.getTestMessage(perThreadSetup._pingClient.getReplyDestinations().get(0),
- testParameters.getPropertyAsInteger(PingPongProducer.MESSAGE_SIZE_PROPNAME),
- testParameters.getPropertyAsBoolean(PingPongProducer.PERSISTENT_MODE_PROPNAME));
-
- // Send the requested number of messages, and wait until they have all been received.
- long timeout = Long.parseLong(testParameters.getProperty(PingPongProducer.TIMEOUT_PROPNAME));
- int numReplies = pingClient.pingAndWaitForReply(msg, numPings, timeout, null);
-
- // Check that all the replies were received and log a fail if they were not.
- if (numReplies < numPings)
- {
- tc.completeTest(false, 0);
- }
-
- // Remove the chained message listener from the ping producer.
- pingClient.removeChainedMessageListener();
-
- // Remove the expected count and timing controller for the message correlation id, to ensure they are cleaned up.
- perCorrelationIds.remove(messageCorrelationId);
- }
-
- /** Performs test fixture creation on a per thread basis. This will only be called once for each test thread. */
- public void threadSetUp()
- {
- _logger.debug("public void threadSetUp(): called");
-
- try
- {
- // Call the set up method in the super class. This creates a PingClient pinger.
- super.threadSetUp();
-
- // Create the chained message listener, only if it has not already been created. This is set up with the
- // batch size property, to tell it what batch size to output results on. A synchronized block is used to
- // ensure that only one thread creates this.
- synchronized (this)
- {
- if (batchedResultsListener == null)
- {
- int batchSize = Integer.parseInt(testParameters.getProperty(TEST_RESULTS_BATCH_SIZE_PROPNAME));
- batchedResultsListener = new BatchedResultsListener(batchSize);
- }
- }
-
- // Get the set up that the super class created.
- PerThreadSetup perThreadSetup = threadSetup.get();
-
- // Register the chained message listener on the pinger to do its asynchronous test timings from.
- perThreadSetup._pingClient.setChainedMessageListener(batchedResultsListener);
- }
- catch (Exception e)
- {
- _logger.warn("There was an exception during per thread setup.", e);
- }
- }
-
- /**
- * BatchedResultsListener is a {@link org.apache.qpid.requestreply.PingPongProducer.ChainedMessageListener} that can
- * be attached to the pinger, in order to receive notifications about every message received and the number
- * remaining to be received. Whenever the number remaining crosses a batch size boundary this results listener
- * outputs a test timing for the actual number of messages received in the current batch.
- */
- private class BatchedResultsListener implements PingPongProducer.ChainedMessageListener
- {
- /** The test results logging batch size. */
- int _batchSize;
- private boolean _strictAMQP;
-
- /**
- * Creates a results listener on the specified batch size.
- *
- * @param batchSize The batch size to use.
- */
- public BatchedResultsListener(int batchSize)
- {
- _batchSize = batchSize;
- _strictAMQP =
- Boolean.parseBoolean(System.getProperties().getProperty(AMQSession.STRICT_AMQP,
- AMQSession.STRICT_AMQP_DEFAULT));
- }
-
- /**
- * This callback method is called from all of the pingers that this test creates. It uses the correlation id
- * from the message to identify the timing controller for the test thread that was responsible for sending those
- * messages.
- *
- * @param message The message.
- * @param remainingCount The count of messages remaining to be received with a particular correlation id.
- *
- * @throws javax.jms.JMSException Any underlying JMSException is allowed to fall through.
- */
- public void onMessage(Message message, int remainingCount, long latency) throws JMSException
- {
- _logger.debug("public void onMessage(Message message, int remainingCount = " + remainingCount + "): called");
-
- // Check if a batch boundary has been crossed.
- if ((remainingCount % _batchSize) == 0)
- {
- // Extract the correlation id from the message.
- String correlationId = message.getJMSCorrelationID();
-
- // Get the details for the correlation id and check that they are not null. They can become null
- // if a test times out.
- PerCorrelationId perCorrelationId = perCorrelationIds.get(correlationId);
- if (perCorrelationId != null)
- {
- // Get the timing controller and expected count for this correlation id.
- TimingController tc = perCorrelationId._tc;
- int expected = perCorrelationId._expectedCount;
-
- // Calculate how many messages were actually received in the last batch. This will be the batch size
- // except where the number expected is not a multiple of the batch size and this is the first remaining
- // count to cross a batch size boundary, in which case it will be the number expected modulo the batch
- // size.
- int receivedInBatch = ((expected - remainingCount) < _batchSize) ? (expected % _batchSize) : _batchSize;
-
- // Register a test result for the correlation id.
- try
- {
- tc.completeTest(true, receivedInBatch, latency);
- }
- catch (InterruptedException e)
- {
- // Ignore this. It means the test runner wants to stop as soon as possible.
- _logger.warn("Got InterruptedException.", e);
- }
- }
- // Else ignore, test timed out. Should log a fail here?
- }
- }
- }
-
- /**
- * Holds state specific to each correlation id, needed to output test results. This consists of the count of the
- * total expected number of messages, and the timing controller for the thread sending those message ids.
- */
- private static class PerCorrelationId
- {
- public int _expectedCount;
- public TimingController _tc;
- }
-}
diff --git a/java/perftests/src/main/java/org/apache/qpid/ping/PingSendOnlyClient.java b/java/perftests/src/main/java/org/apache/qpid/ping/PingSendOnlyClient.java
deleted file mode 100644
index 2fe852af77..0000000000
--- a/java/perftests/src/main/java/org/apache/qpid/ping/PingSendOnlyClient.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.qpid.ping;
-
-import java.util.Properties;
-
-import javax.jms.Destination;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.ObjectMessage;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.client.message.TestMessageFactory;
-import org.apache.qpid.util.CommandLineParser;
-
-/**
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * </table>
- */
-public class PingSendOnlyClient extends PingDurableClient
-{
- private static final Logger log = Logger.getLogger(PingSendOnlyClient.class);
-
- public PingSendOnlyClient(Properties overrides) throws Exception
- {
- super(overrides);
- }
-
- /**
- * Starts the ping/wait/receive process.
- *
- * @param args The command line arguments.
- */
- public static void main(String[] args)
- {
- try
- {
- // Create a ping producer overriding its defaults with all options passed on the command line.
- Properties options = CommandLineParser.processCommandLine(args, new CommandLineParser(new String[][] {}), System.getProperties());
- PingSendOnlyClient pingProducer = new PingSendOnlyClient(options);
-
- // Create a shutdown hook to terminate the ping-pong producer.
- Runtime.getRuntime().addShutdownHook(pingProducer.getShutdownHook());
-
- // Ensure that the ping pong producer is registered to listen for exceptions on the connection too.
- // pingProducer.getConnection().setExceptionListener(pingProducer);
-
- // Run the test procedure.
- pingProducer.send();
- pingProducer.waitForUser("Press return to close connection and quit.");
- pingProducer.closeConnection();
-
- System.exit(0);
- }
- catch (Exception e)
- {
- System.err.println(e.getMessage());
- log.error("Top level handler caught execption.", e);
- System.exit(1);
- }
- }
-
- public Message getTestMessage(Destination replyQueue, int messageSize, boolean persistent) throws JMSException
- {
- Message msg = TestMessageFactory.newTextMessage(_producerSession, messageSize);
-
- // Timestamp the message in nanoseconds.
- msg.setLongProperty(MESSAGE_TIMESTAMP_PROPNAME, System.nanoTime());
-
- return msg;
- }
-}
diff --git a/java/perftests/src/main/java/org/apache/qpid/ping/PingTestPerf.java b/java/perftests/src/main/java/org/apache/qpid/ping/PingTestPerf.java
deleted file mode 100644
index cf16abc596..0000000000
--- a/java/perftests/src/main/java/org/apache/qpid/ping/PingTestPerf.java
+++ /dev/null
@@ -1,281 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.ping;
-
-import junit.framework.Assert;
-import junit.framework.Test;
-import junit.framework.TestSuite;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.requestreply.PingPongProducer;
-
-import org.apache.qpid.junit.extensions.AsymptoticTestCase;
-import org.apache.qpid.junit.extensions.TestThreadAware;
-import org.apache.qpid.junit.extensions.util.ParsedProperties;
-import org.apache.qpid.junit.extensions.util.TestContextProperties;
-
-import javax.jms.*;
-
-/**
- * PingTestPerf is a ping test, that has been written with the intention of being scaled up to run many times
- * simultaneously to simluate many clients/producers/connections.
- *
- * <p/>A single run of the test using the default JUnit test runner will result in the sending and timing of a single
- * full round trip ping. This test may be scaled up using a suitable JUnit test runner.
- *
- * <p/>The setup/teardown cycle establishes a connection to a broker and sets up a queue to send ping messages to and a
- * temporary queue for replies. This setup is only established once for all the test repeats/threads that may be run,
- * except if the connection is lost in which case an attempt to re-establish the setup is made.
- *
- * <p/>The test cycle is: Connects to a queue, creates a temporary queue, creates messages containing a property that
- * is the name of the temporary queue, fires off a message on the original queue and waits for a response on the
- * temporary queue.
- *
- * <p/>Configurable test properties: message size, transacted or not, persistent or not. Broker connection details.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * </table>
- */
-public class PingTestPerf extends AsymptoticTestCase implements TestThreadAware
-{
- private static Logger _logger = Logger.getLogger(PingTestPerf.class);
-
- /** Thread local to hold the per-thread test setup fields. */
- ThreadLocal<PerThreadSetup> threadSetup = new ThreadLocal<PerThreadSetup>();
-
- /** Holds a property reader to extract the test parameters from. */
- protected ParsedProperties testParameters =
- TestContextProperties.getInstance(PingPongProducer.defaults /*System.getProperties()*/);
-
- public PingTestPerf(String name)
- {
- super(name);
-
- _logger.debug("testParameters = " + testParameters);
- }
-
- /**
- * Compile all the tests into a test suite.
- * @return The test method testPingOk.
- */
- public static Test suite()
- {
- // Build a new test suite
- TestSuite suite = new TestSuite("Ping Performance Tests");
-
- // Run performance tests in read committed mode.
- suite.addTest(new PingTestPerf("testPingOk"));
-
- return suite;
- }
-
- public void testPingOk(int numPings) throws Exception
- {
- if (numPings == 0)
- {
- Assert.fail("Number of pings requested was zero.");
- }
-
- // Get the per thread test setup to run the test through.
- PerThreadSetup perThreadSetup = threadSetup.get();
-
- if (perThreadSetup == null)
- {
- Assert.fail("Could not get per thread test setup, it was null.");
- }
-
- // Generate a sample message. This message is already time stamped and has its reply-to destination set.
- Message msg =
- perThreadSetup._pingClient.getTestMessage(perThreadSetup._pingClient.getReplyDestinations().get(0),
- testParameters.getPropertyAsInteger(PingPongProducer.MESSAGE_SIZE_PROPNAME),
- testParameters.getPropertyAsBoolean(PingPongProducer.PERSISTENT_MODE_PROPNAME));
-
- // start the test
- long timeout = Long.parseLong(testParameters.getProperty(PingPongProducer.TIMEOUT_PROPNAME));
- int numReplies = perThreadSetup._pingClient.pingAndWaitForReply(msg, numPings, timeout, null);
-
- // Fail the test if the timeout was exceeded.
- if (numReplies != perThreadSetup._pingClient.getExpectedNumPings(numPings))
- {
- Assert.fail("The ping timed out after " + timeout + " ms. Messages Sent = " + numPings + ", MessagesReceived = "
- + numReplies);
- }
- }
-
- /** Performs test fixture creation on a per thread basis. This will only be called once for each test thread. */
- public void threadSetUp()
- {
- _logger.debug("public void threadSetUp(): called");
-
- try
- {
- PerThreadSetup perThreadSetup = new PerThreadSetup();
-
- // This is synchronized because there is a race condition, which causes one connection to sleep if
- // all threads try to create connection concurrently.
- synchronized (this)
- {
- // Establish a client to ping a Destination and listen the reply back from same Destination
- perThreadSetup._pingClient = new PingClient(testParameters);
- perThreadSetup._pingClient.establishConnection(true, true);
- }
-
- // Attach the per-thread set to the thread.
- threadSetup.set(perThreadSetup);
- }
- catch (Exception e)
- {
- _logger.warn("There was an exception during per thread setup.", e);
- }
- }
-
- /**
- * Called after all threads have completed their setup.
- */
- public void postThreadSetUp()
- {
- _logger.debug("public void postThreadSetUp(): called");
-
- PerThreadSetup perThreadSetup = threadSetup.get();
- // Prefill the broker unless we are in consume only mode.
- int preFill = testParameters.getPropertyAsInteger(PingPongProducer.PREFILL_PROPNAME);
- if (!testParameters.getPropertyAsBoolean(PingPongProducer.CONSUME_ONLY_PROPNAME) && preFill > 0)
- {
- try
- {
- // Manually set the correlation ID to 1. This is not ideal but it is the
- // value that the main test loop will use.
- perThreadSetup._pingClient.pingNoWaitForReply(null, preFill, String.valueOf(perThreadSetup._pingClient.getClientCount()));
-
- // Note with a large preFill and non-tx session the messages will be
- // rapidly pushed in to the mina buffers. OOM's are a real risk here.
- // Should perhaps consider using a TX session for the prefill.
-
- long delayBeforeConsume = testParameters.getPropertyAsLong(PingPongProducer.DELAY_BEFORE_CONSUME_PROPNAME);
-
- // Only delay if we are
- // not doing send only
- // and we have consumers
- // and a delayBeforeConsume
- if (!(testParameters.getPropertyAsBoolean(PingPongProducer.SEND_ONLY_PROPNAME))
- && (testParameters.getPropertyAsInteger(PingPongProducer.NUM_CONSUMERS_PROPNAME) > 0)
- && delayBeforeConsume > 0)
- {
-
- boolean verbose = testParameters.getPropertyAsBoolean(PingPongProducer.VERBOSE_PROPNAME);
- // Only do logging if in verbose mode.
- if (verbose)
- {
- if (delayBeforeConsume > 60000)
- {
- long minutes = delayBeforeConsume / 60000;
- long seconds = (delayBeforeConsume - (minutes * 60000)) / 1000;
- long ms = delayBeforeConsume - (minutes * 60000) - (seconds * 1000);
- _logger.info("Delaying for " + minutes + "m " + seconds + "s " + ms + "ms before starting test.");
- }
- else
- {
- _logger.info("Delaying for " + delayBeforeConsume + "ms before starting test.");
- }
- }
-
- Thread.sleep(delayBeforeConsume);
-
- if (verbose)
- {
- _logger.info("Starting Test.");
- }
- }
-
- // We can't start the client's here as the test client has not yet been configured to receieve messages.
- // only when the test method is executed will the correlationID map be set up and ready to consume
- // the messages we have sent here.
- }
- catch (Exception e)
- {
- _logger.warn("There was an exception during per thread setup.", e);
- }
- }
- else //Only start the consumer if we are not preFilling.
- {
- // Start the consumers, unless we have data on the broker
- // already this is signified by being in consume_only, we will
- // start the clients after setting up the correlation IDs.
- // We should also not start the clients if we are in Send only
- if (!testParameters.getPropertyAsBoolean(PingPongProducer.CONSUME_ONLY_PROPNAME) &&
- !(testParameters.getPropertyAsBoolean(PingPongProducer.SEND_ONLY_PROPNAME)))
- {
- // Start the client connection
- try
- {
- perThreadSetup._pingClient.start();
- }
- catch (JMSException e)
- {
- e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
- }
- }
- }
- }
-
- /**
- * Performs test fixture clean
- */
- public void threadTearDown()
- {
- _logger.debug("public void threadTearDown(): called");
-
- try
- {
- // Get the per thread test fixture.
- PerThreadSetup perThreadSetup = threadSetup.get();
-
- // Close the pingers so that it cleans up its connection cleanly.
- synchronized (this)
- {
- if ((perThreadSetup != null) && (perThreadSetup._pingClient != null))
- {
- perThreadSetup._pingClient.close();
- }
- }
- }
- catch (JMSException e)
- {
- _logger.warn("There was an exception during per thread tear down.");
- }
- finally
- {
- // Ensure the per thread fixture is reclaimed.
- threadSetup.remove();
- }
- }
-
- protected static class PerThreadSetup
- {
- /**
- * Holds the test ping client.
- */
- protected PingClient _pingClient;
- protected String _correlationId;
- }
-}
diff --git a/java/perftests/src/main/java/org/apache/qpid/requestreply/PingPongBouncer.java b/java/perftests/src/main/java/org/apache/qpid/requestreply/PingPongBouncer.java
deleted file mode 100644
index 8e010ccf07..0000000000
--- a/java/perftests/src/main/java/org/apache/qpid/requestreply/PingPongBouncer.java
+++ /dev/null
@@ -1,453 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.requestreply;
-
-import java.io.IOException;
-import java.net.InetAddress;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-
-import javax.jms.*;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.client.AMQTopic;
-import org.apache.qpid.jms.ConnectionListener;
-import org.apache.qpid.jms.Session;
-import org.apache.qpid.topic.Config;
-import org.apache.qpid.exchange.ExchangeDefaults;
-
-/**
- * PingPongBouncer is a message listener the bounces back messages to their reply to destination. This is used to return
- * ping messages generated by {@link org.apache.qpid.requestreply.PingPongProducer} but could be used for other purposes
- * too.
- *
- * <p/>The correlation id from the received message is extracted, and placed into the reply as the correlation id. Messages
- * are bounced back to their reply-to destination. The original sender of the message has the option to use either a unique
- * temporary queue or the correlation id to correlate the original message to the reply.
- *
- * <p/>There is a verbose mode flag which causes information about each ping to be output to the console
- * (info level logging, so usually console). This can be helpfull to check the bounce backs are happening but should
- * be disabled for real timing tests as writing to the console will slow things down.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Bounce back messages to their reply to destination.
- * <tr><td> Provide command line invocation to start the bounce back on a configurable broker url.
- * </table>
- *
- * @todo Replace the command line parsing with a neater tool.
- *
- * @todo Make verbose accept a number of messages, only prints to console every X messages.
- */
-public class PingPongBouncer implements MessageListener
-{
- private static final Logger _logger = Logger.getLogger(PingPongBouncer.class);
-
- /** The default prefetch size for the message consumer. */
- private static final int PREFETCH = 1;
-
- /** The default no local flag for the message consumer. */
- private static final boolean NO_LOCAL = true;
-
- private static final String DEFAULT_DESTINATION_NAME = "ping";
-
- /** The default exclusive flag for the message consumer. */
- private static final boolean EXCLUSIVE = false;
-
- /** A convenient formatter to use when time stamping output. */
- protected static final SimpleDateFormat timestampFormatter = new SimpleDateFormat("hh:mm:ss:SS");
-
- /** Used to indicate that the reply generator should log timing info to the console (logger info level). */
- private boolean _verbose = false;
-
- /** Determines whether this bounce back client bounces back messages persistently. */
- private boolean _persistent = false;
-
- private Destination _consumerDestination;
-
- /** Keeps track of the response destination of the previous message for the last reply to producer cache. */
- private Destination _lastResponseDest;
-
- /** The producer for sending replies with. */
- private MessageProducer _replyProducer;
-
- /** The consumer controlSession. */
- private Session _consumerSession;
-
- /** The producer controlSession. */
- private Session _producerSession;
-
- /** Holds the connection to the broker. */
- private AMQConnection _connection;
-
- /** Flag used to indicate if this is a point to point or pub/sub ping client. */
- private boolean _isPubSub = false;
-
- /**
- * This flag is used to indicate that the user should be prompted to kill a broker, in order to test
- * failover, immediately before committing a transaction.
- */
- protected boolean _failBeforeCommit = false;
-
- /**
- * This flag is used to indicate that the user should be prompted to a kill a broker, in order to test
- * failover, immediate after committing a transaction.
- */
- protected boolean _failAfterCommit = false;
-
- /**
- * Creates a PingPongBouncer on the specified producer and consumer sessions.
- *
- * @param brokerDetails The addresses of the brokers to connect to.
- * @param username The broker username.
- * @param password The broker password.
- * @param virtualpath The virtual host name within the broker.
- * @param destinationName The name of the queue to receive pings on
- * (or root of the queue name where many queues are generated).
- * @param persistent A flag to indicate that persistent message should be used.
- * @param transacted A flag to indicate that pings should be sent within transactions.
- * @param selector A message selector to filter received pings with.
- * @param verbose A flag to indicate that message timings should be sent to the console.
- *
- * @throws Exception All underlying exceptions allowed to fall through. This is only test code...
- */
- public PingPongBouncer(String brokerDetails, String username, String password, String virtualpath,
- String destinationName, boolean persistent, boolean transacted, String selector, boolean verbose,
- boolean pubsub) throws Exception
- {
- // Create a client id to uniquely identify this client.
- InetAddress address = InetAddress.getLocalHost();
- String clientId = address.getHostName() + System.currentTimeMillis();
- _verbose = verbose;
- _persistent = persistent;
- setPubSub(pubsub);
- // Connect to the broker.
- setConnection(new AMQConnection(brokerDetails, username, password, clientId, virtualpath));
- _logger.info("Connected with URL:" + getConnection().toURL());
-
- // Set up the failover notifier.
- getConnection().setConnectionListener(new FailoverNotifier());
-
- // Create a controlSession to listen for messages on and one to send replies on, transactional depending on the
- // command line option.
- _consumerSession = (Session) getConnection().createSession(transacted, Session.AUTO_ACKNOWLEDGE);
- _producerSession = (Session) getConnection().createSession(transacted, Session.AUTO_ACKNOWLEDGE);
-
- // Create the queue to listen for message on.
- createConsumerDestination(destinationName);
- MessageConsumer consumer =
- _consumerSession.createConsumer(_consumerDestination, PREFETCH, NO_LOCAL, EXCLUSIVE, selector);
-
- // Create a producer for the replies, without a default destination.
- _replyProducer = _producerSession.createProducer(null);
- _replyProducer.setDisableMessageTimestamp(true);
- _replyProducer.setDeliveryMode(_persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT);
-
- // Set this up to listen for messages on the queue.
- consumer.setMessageListener(this);
- }
-
- /**
- * Starts a stand alone ping-pong client running in verbose mode.
- *
- * @param args
- */
- public static void main(String[] args) throws Exception
- {
- System.out.println("Starting...");
-
- // Display help on the command line.
- if (args.length == 0)
- {
- _logger.info("Running test with default values...");
- //usage();
- //System.exit(0);
- }
-
- // Extract all command line parameters.
- Config config = new Config();
- config.setOptions(args);
- String brokerDetails = config.getHost() + ":" + config.getPort();
- String virtualpath = "test";
- String destinationName = config.getDestination();
- if (destinationName == null)
- {
- destinationName = DEFAULT_DESTINATION_NAME;
- }
-
- String selector = config.getSelector();
- boolean transacted = config.isTransacted();
- boolean persistent = config.usePersistentMessages();
- boolean pubsub = config.isPubSub();
- boolean verbose = true;
-
- //String selector = null;
-
- // Instantiate the ping pong client with the command line options and start it running.
- PingPongBouncer pingBouncer =
- new PingPongBouncer(brokerDetails, "guest", "guest", virtualpath, destinationName, persistent, transacted,
- selector, verbose, pubsub);
- pingBouncer.getConnection().start();
-
- System.out.println("Waiting...");
- }
-
- private static void usage()
- {
- System.err.println("Usage: PingPongBouncer \n" + "-host : broker host\n" + "-port : broker port\n"
- + "-destinationname : queue/topic name\n" + "-transacted : (true/false). Default is false\n"
- + "-persistent : (true/false). Default is false\n"
- + "-pubsub : (true/false). Default is false\n" + "-selector : selector string\n");
- }
-
- /**
- * This is a callback method that is notified of all messages for which this has been registered as a message
- * listener on a message consumer. It sends a reply (pong) to all messages it receieves on the reply to
- * destination of the message.
- *
- * @param message The message that triggered this callback.
- */
- public void onMessage(Message message)
- {
- try
- {
- String messageCorrelationId = message.getJMSCorrelationID();
- if (_verbose)
- {
- _logger.info(timestampFormatter.format(new Date()) + ": Got ping with correlation id, "
- + messageCorrelationId);
- }
-
- // Get the reply to destination from the message and check it is set.
- Destination responseDest = message.getJMSReplyTo();
-
- if (responseDest == null)
- {
- _logger.debug("Cannot send reply because reply-to destination is null.");
-
- return;
- }
-
- // Spew out some timing information if verbose mode is on.
- if (_verbose)
- {
- Long timestamp = message.getLongProperty("timestamp");
-
- if (timestamp != null)
- {
- long diff = System.currentTimeMillis() - timestamp;
- _logger.info("Time to bounce point: " + diff);
- }
- }
-
- // Correlate the reply to the original.
- message.setJMSCorrelationID(messageCorrelationId);
-
- // Send the receieved message as the pong reply.
- _replyProducer.send(responseDest, message);
-
- if (_verbose)
- {
- _logger.info(timestampFormatter.format(new Date()) + ": Sent reply with correlation id, "
- + messageCorrelationId);
- }
-
- // Commit the transaction if running in transactional mode.
- commitTx(_producerSession);
- }
- catch (JMSException e)
- {
- _logger.debug("There was a JMSException: " + e.getMessage(), e);
- }
- }
-
- /**
- * Gets the underlying connection that this ping client is running on.
- *
- * @return The underlying connection that this ping client is running on.
- */
- public AMQConnection getConnection()
- {
- return _connection;
- }
-
- /**
- * Sets the connection that this ping client is using.
- *
- * @param connection The ping connection.
- */
- public void setConnection(AMQConnection connection)
- {
- this._connection = connection;
- }
-
- /**
- * Sets or clears the pub/sub flag to indiciate whether this client is pinging a queue or a topic.
- *
- * @param pubsub <tt>true</tt> if this client is pinging a topic, <tt>false</tt> if it is pinging a queue.
- */
- public void setPubSub(boolean pubsub)
- {
- _isPubSub = pubsub;
- }
-
- /**
- * Checks whether this client is a p2p or pub/sub ping client.
- *
- * @return <tt>true</tt> if this client is pinging a topic, <tt>false</tt> if it is pinging a queue.
- */
- public boolean isPubSub()
- {
- return _isPubSub;
- }
-
- /**
- * Convenience method to commit the transaction on the specified controlSession. If the controlSession to commit on is not
- * a transactional controlSession, this method does nothing.
- *
- * <p/>If the {@link #_failBeforeCommit} flag is set, this will prompt the user to kill the broker before the
- * commit is applied. If the {@link #_failAfterCommit} flag is set, this will prompt the user to kill the broker
- * after the commit is applied.
- *
- * @throws javax.jms.JMSException If the commit fails and then the rollback fails.
- */
- protected void commitTx(Session session) throws JMSException
- {
- if (session.getTransacted())
- {
- try
- {
- if (_failBeforeCommit)
- {
- _logger.debug("Failing Before Commit");
- doFailover();
- }
-
- session.commit();
-
- if (_failAfterCommit)
- {
- _logger.debug("Failing After Commit");
- doFailover();
- }
-
- _logger.debug("Session Commited.");
- }
- catch (JMSException e)
- {
- _logger.trace("JMSException on commit:" + e.getMessage(), e);
-
- try
- {
- session.rollback();
- _logger.debug("Message rolled back.");
- }
- catch (JMSException jmse)
- {
- _logger.trace("JMSE on rollback:" + jmse.getMessage(), jmse);
-
- // Both commit and rollback failed. Throw the rollback exception.
- throw jmse;
- }
- }
- }
- }
-
- /**
- * Prompts the user to terminate the named broker, in order to test failover functionality. This method will block
- * until the user supplied some input on the terminal.
- *
- * @param broker The name of the broker to terminate.
- */
- protected void doFailover(String broker)
- {
- System.out.println("Kill Broker " + broker + " now.");
- try
- {
- System.in.read();
- }
- catch (IOException e)
- { }
-
- System.out.println("Continuing.");
- }
-
- /**
- * Prompts the user to terminate the broker, in order to test failover functionality. This method will block
- * until the user supplied some input on the terminal.
- */
- protected void doFailover()
- {
- System.out.println("Kill Broker now.");
- try
- {
- System.in.read();
- }
- catch (IOException e)
- { }
-
- System.out.println("Continuing.");
-
- }
-
- private void createConsumerDestination(String name)
- {
- if (isPubSub())
- {
- _consumerDestination = new AMQTopic(ExchangeDefaults.TOPIC_EXCHANGE_NAME, name);
- }
- else
- {
- _consumerDestination = new AMQQueue(ExchangeDefaults.DIRECT_EXCHANGE_NAME, name);
- }
- }
-
- /**
- * A connection listener that logs out any failover complete events. Could do more interesting things with this
- * at some point...
- */
- public static class FailoverNotifier implements ConnectionListener
- {
- public void bytesSent(long count)
- { }
-
- public void bytesReceived(long count)
- { }
-
- public boolean preFailover(boolean redirect)
- {
- return true;
- }
-
- public boolean preResubscribe()
- {
- return true;
- }
-
- public void failoverComplete()
- {
- _logger.info("App got failover complete callback.");
- }
- }
-}
diff --git a/java/perftests/src/main/java/org/apache/qpid/requestreply/PingPongProducer.java b/java/perftests/src/main/java/org/apache/qpid/requestreply/PingPongProducer.java
deleted file mode 100644
index 0bf952b7e1..0000000000
--- a/java/perftests/src/main/java/org/apache/qpid/requestreply/PingPongProducer.java
+++ /dev/null
@@ -1,1833 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.requestreply;
-
-import org.apache.log4j.Logger;
-import org.apache.log4j.NDC;
-
-import org.apache.qpid.test.framework.TestUtils;
-
-import org.apache.qpid.junit.extensions.BatchedThrottle;
-import org.apache.qpid.junit.extensions.Throttle;
-import org.apache.qpid.junit.extensions.util.CommandLineParser;
-import org.apache.qpid.junit.extensions.util.ParsedProperties;
-
-import javax.jms.*;
-import javax.naming.Context;
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-
-import java.io.*;
-import java.net.InetAddress;
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.util.*;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.SynchronousQueue;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.concurrent.atomic.AtomicLong;
-
-/**
- * PingPongProducer is a client that sends test messages, and waits for replies to these messages. The replies may
- * either be generated by another client (see {@link PingPongBouncer}, or an extension of it may be used that listens
- * to its own messages and does not send replies (see {@link org.apache.qpid.ping.PingClient}). The intention of ping
- * pong producer is that it is a swiss-army knife test client that makes almost every aspect of its behaviour
- * configurable.
- *
- * <p/>The pings are sent with a reply-to field set to a single temporary queue, which is the same for all pings. This
- * means that this class has to do some work to correlate pings with pongs; it expectes the original message correlation
- * id in the ping to be bounced back in the reply correlation id.
- *
- * <p/>This ping tool accepts a vast number of configuration options, all of which are passed in to the constructor. It
- * can ping topics or queues; ping multiple destinations; do persistent pings; send messages of any size; do pings within
- * transactions; control the number of pings to send in each transaction; limit its sending rate; and perform failover
- * testing. A complete list of accepted parameters, default values and comments on their usage is provided here:
- *
- * <p/><table><caption>Parameters</caption>
- * <tr><th> Parameter <th> Default <th> Comments
- * <tr><td> messageSize <td> 0 <td> Message size in bytes. Not including any headers.
- * <tr><td> destinationName <td> ping <td> The root name to use to generate destination names to ping.
- * <tr><td> persistent <td> false <td> Determines whether peristent delivery is used.
- * <tr><td> transacted <td> false <td> Determines whether messages are sent/received in transactions.
- * <tr><td> broker <td> tcp://localhost:5672 <td> Determines the broker to connect to.
- * <tr><td> virtualHost <td> test <td> Determines the virtual host to send all ping over.
- * <tr><td> rate <td> 0 <td> The maximum rate (in hertz) to send messages at. 0 means no limit.
- * <tr><td> verbose <td> false <td> The verbose flag for debugging. Prints to console on every message.
- * <tr><td> pubsub <td> false <td> Whether to ping topics or queues. Uses p2p by default.
- * <tr><td> failAfterCommit <td> false <td> Whether to prompt user to kill broker after a commit batch.
- * <tr><td> failBeforeCommit <td> false <td> Whether to prompt user to kill broker before a commit batch.
- * <tr><td> failAfterSend <td> false <td> Whether to prompt user to kill broker after a send.
- * <tr><td> failBeforeSend <td> false <td> Whether to prompt user to kill broker before a send.
- * <tr><td> failOnce <td> true <td> Whether to prompt for failover only once.
- * <tr><td> username <td> guest <td> The username to access the broker with.
- * <tr><td> password <td> guest <td> The password to access the broker with.
- * <tr><td> selector <td> null <td> Not used. Defines a message selector to filter pings with.
- * <tr><td> destinationCount <td> 1 <td> The number of destinations to send pings to.
- * <tr><td> numConsumers <td> 1 <td> The number of consumers on each destination.
- * <tr><td> timeout <td> 30000 <td> In milliseconds. The timeout to stop waiting for replies.
- * <tr><td> commitBatchSize <td> 1 <td> The number of messages per transaction in transactional mode.
- * <tr><td> uniqueDests <td> true <td> Whether each receivers only listens to one ping destination or all.
- * <tr><td> durableDests <td> false <td> Whether or not durable destinations are used.
- * <tr><td> ackMode <td> AUTO_ACK <td> The message acknowledgement mode. Possible values are:
- * 0 - SESSION_TRANSACTED
- * 1 - AUTO_ACKNOWLEDGE
- * 2 - CLIENT_ACKNOWLEDGE
- * 3 - DUPS_OK_ACKNOWLEDGE
- * 257 - NO_ACKNOWLEDGE
- * 258 - PRE_ACKNOWLEDGE
- * <tr><td> consTransacted <td> false <td> Whether or not consumers use transactions. Defaults to the same value
- * as the 'transacted' option if not seperately defined.
- * <tr><td> consAckMode <td> AUTO_ACK <td> The message acknowledgement mode for consumers. Defaults to the same
- * value as 'ackMode' if not seperately defined.
- * <tr><td> maxPending <td> 0 <td> The maximum size in bytes, of messages sent but not yet received.
- * Limits the volume of messages currently buffered on the client
- * or broker. Can help scale test clients by limiting amount of buffered
- * data to avoid out of memory errors.
- * </table>
- *
- * <p/>This implements the Runnable interface with a run method that implements an infinite ping loop. The ping loop
- * does all its work through helper methods, so that code wishing to run a ping-pong cycle is not forced to do so by
- * starting a new thread. The command line invocation does take advantage of this ping loop. A shutdown hook is also
- * registered to terminate the ping-pong loop cleanly.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Provide a ping and wait for all responses cycle.
- * <tr><td> Provide command line invocation to loop the ping cycle on a configurable broker url.
- * </table>
- *
- * @todo Use read/write lock in the onmessage, not for reading writing but to make use of a shared and exlcusive lock pair.
- * Obtain read lock on all messages, before decrementing the message count. At the end of the on message method add a
- * block that obtains the write lock for the very last message, releases any waiting producer. Means that the last
- * message waits until all other messages have been handled before releasing producers but allows messages to be
- * processed concurrently, unlike the current synchronized block.
- */
-public class PingPongProducer implements Runnable, ExceptionListener
-{
- /** Used for debugging. */
- private static final Logger log = Logger.getLogger(PingPongProducer.class);
-
- /** Holds the name of the property to determine whether of not client id is overridden at connection time. */
- public static final String OVERRIDE_CLIENT_ID_PROPNAME = "overrideClientId";
-
- /** Holds the default value of the override client id flag. */
- public static final String OVERRIDE_CLIENT_ID_DEAFULT = "false";
-
- /** Holds the name of the property to define the JNDI factory name with. */
- public static final String FACTORY_NAME_PROPNAME = "factoryName";
-
- /** Holds the default JNDI name of the connection factory. */
- public static final String FACTORY_NAME_DEAFULT = "local";
-
- /** Holds the name of the property to set the JNDI initial context properties with. */
- public static final String FILE_PROPERTIES_PROPNAME = "properties";
-
- /** Holds the default file name of the JNDI initial context properties. */
- public static final String FILE_PROPERTIES_DEAFULT = "perftests.properties";
-
- /** Holds the name of the property to get the test message size from. */
- public static final String MESSAGE_SIZE_PROPNAME = "messageSize";
-
- /** Used to set up a default message size. */
- public static final int MESSAGE_SIZE_DEAFULT = 0;
-
- /** Holds the name of the property to get the ping queue name from. */
- public static final String PING_QUEUE_NAME_PROPNAME = "destinationName";
-
- /** Holds the name of the default destination to send pings on. */
- public static final String PING_QUEUE_NAME_DEFAULT = "ping";
-
- /** Holds the name of the property to get the queue name postfix from. */
- public static final String QUEUE_NAME_POSTFIX_PROPNAME = "queueNamePostfix";
-
- /** Holds the default queue name postfix value. */
- public static final String QUEUE_NAME_POSTFIX_DEFAULT = "";
-
- /** Holds the name of the property to get the test delivery mode from. */
- public static final String PERSISTENT_MODE_PROPNAME = "persistent";
-
- /** Holds the message delivery mode to use for the test. */
- public static final boolean PERSISTENT_MODE_DEFAULT = false;
-
- /** Holds the name of the property to get the test transactional mode from. */
- public static final String TRANSACTED_PROPNAME = "transacted";
-
- /** Holds the transactional mode to use for the test. */
- public static final boolean TRANSACTED_DEFAULT = false;
-
- /** Holds the name of the property to get the test consumer transacted mode from. */
- public static final String CONSUMER_TRANSACTED_PROPNAME = "consTransacted";
-
- /** Holds the consumer transactional mode default setting. */
- public static final boolean CONSUMER_TRANSACTED_DEFAULT = false;
-
- /** Holds the name of the property to get the test broker url from. */
- public static final String BROKER_PROPNAME = "broker";
-
- /** Holds the default broker url for the test. */
- public static final String BROKER_DEFAULT = "tcp://localhost:5672";
-
- /** Holds the name of the property to get the test broker virtual path. */
- public static final String VIRTUAL_HOST_PROPNAME = "virtualHost";
-
- /** Holds the default virtual path for the test. */
- public static final String VIRTUAL_HOST_DEFAULT = "";
-
- /** Holds the name of the property to get the message rate from. */
- public static final String RATE_PROPNAME = "rate";
-
- /** Defines the default rate (in pings per second) to send pings at. 0 means as fast as possible, no restriction. */
- public static final int RATE_DEFAULT = 0;
-
- /** Holds the name of the property to get the verbose mode proeprty from. */
- public static final String VERBOSE_PROPNAME = "verbose";
-
- /** Holds the default verbose mode. */
- public static final boolean VERBOSE_DEFAULT = false;
-
- /** Holds the name of the property to get the p2p or pub/sub messaging mode from. */
- public static final String PUBSUB_PROPNAME = "pubsub";
-
- /** Holds the pub/sub mode default, true means ping a topic, false means ping a queue. */
- public static final boolean PUBSUB_DEFAULT = false;
-
- /** Holds the name of the property to get the fail after commit flag from. */
- public static final String FAIL_AFTER_COMMIT_PROPNAME = "failAfterCommit";
-
- /** Holds the default failover after commit test flag. */
- public static final boolean FAIL_AFTER_COMMIT_DEFAULT = false;
-
- /** Holds the name of the proeprty to get the fail before commit flag from. */
- public static final String FAIL_BEFORE_COMMIT_PROPNAME = "failBeforeCommit";
-
- /** Holds the default failover before commit test flag. */
- public static final boolean FAIL_BEFORE_COMMIT_DEFAULT = false;
-
- /** Holds the name of the proeprty to get the fail after send flag from. */
- public static final String FAIL_AFTER_SEND_PROPNAME = "failAfterSend";
-
- /** Holds the default failover after send test flag. */
- public static final boolean FAIL_AFTER_SEND_DEFAULT = false;
-
- /** Holds the name of the property to get the fail before send flag from. */
- public static final String FAIL_BEFORE_SEND_PROPNAME = "failBeforeSend";
-
- /** Holds the default failover before send test flag. */
- public static final boolean FAIL_BEFORE_SEND_DEFAULT = false;
-
- /** Holds the name of the property to get the fail once flag from. */
- public static final String FAIL_ONCE_PROPNAME = "failOnce";
-
- /** The default failover once flag, true means only do one failover, false means failover on every commit cycle. */
- public static final boolean FAIL_ONCE_DEFAULT = true;
-
- /** Holds the name of the property to get the broker access username from. */
- public static final String USERNAME_PROPNAME = "username";
-
- /** Holds the default broker log on username. */
- public static final String USERNAME_DEFAULT = "guest";
-
- /** Holds the name of the property to get the broker access password from. */
- public static final String PASSWORD_PROPNAME = "password";
-
- /** Holds the default broker log on password. */
- public static final String PASSWORD_DEFAULT = "guest";
-
- /** Holds the name of the proeprty to get the. */
- public static final String SELECTOR_PROPNAME = "selector";
-
- /** Holds the default message selector. */
- public static final String SELECTOR_DEFAULT = "";
-
- /** Holds the name of the property to get the destination count from. */
- public static final String DESTINATION_COUNT_PROPNAME = "destinationCount";
-
- /** Defines the default number of destinations to ping. */
- public static final int DESTINATION_COUNT_DEFAULT = 1;
-
- /** Holds the name of the property to get the number of consumers per destination from. */
- public static final String NUM_CONSUMERS_PROPNAME = "numConsumers";
-
- /** Defines the default number consumers per destination. */
- public static final int NUM_CONSUMERS_DEFAULT = 1;
-
- /** Holds the name of the property to get the waiting timeout for response messages. */
- public static final String TIMEOUT_PROPNAME = "timeout";
-
- /** Default time to wait before assuming that a ping has timed out. */
- public static final long TIMEOUT_DEFAULT = 30000;
-
- /** Holds the name of the property to get the commit batch size from. */
- public static final String TX_BATCH_SIZE_PROPNAME = "commitBatchSize";
-
- /** Defines the default number of pings to send in each transaction when running transactionally. */
- public static final int TX_BATCH_SIZE_DEFAULT = 1;
-
- /** Holds the name of the property to get the unique destinations flag from. */
- public static final String UNIQUE_DESTS_PROPNAME = "uniqueDests";
-
- /** Defines the default value for the unique destinations property. */
- public static final boolean UNIQUE_DESTS_DEFAULT = true;
-
- /** Holds the name of the property to get the durable destinations flag from. */
- public static final String DURABLE_DESTS_PROPNAME = "durableDests";
-
- /** Defines the default value of the durable destinations flag. */
- public static final boolean DURABLE_DESTS_DEFAULT = false;
-
- /** Holds the name of the proeprty to get the message acknowledgement mode from. */
- public static final String ACK_MODE_PROPNAME = "ackMode";
-
- /** Defines the default message acknowledgement mode. */
- public static final int ACK_MODE_DEFAULT = Session.AUTO_ACKNOWLEDGE;
-
- /** Holds the name of the property to get the consumers message acknowledgement mode from. */
- public static final String CONSUMER_ACK_MODE_PROPNAME = "consAckMode";
-
- /** Defines the default consumers message acknowledgement mode. */
- public static final int CONSUMER_ACK_MODE_DEFAULT = Session.AUTO_ACKNOWLEDGE;
-
- /** Holds the name of the property to get the maximum pending message size setting from. */
- public static final String MAX_PENDING_PROPNAME = "maxPending";
-
- /** Defines the default value for the maximum pending message size setting. 0 means no limit. */
- public static final int MAX_PENDING_DEFAULT = 0;
-
- /** Defines the default prefetch size to use when consuming messages. */
- public static final int PREFETCH_DEFAULT = 100;
-
- /** Defines the default value of the no local flag to use when consuming messages. */
- public static final boolean NO_LOCAL_DEFAULT = false;
-
- /** Defines the default value of the exclusive flag to use when consuming messages. */
- public static final boolean EXCLUSIVE_DEFAULT = false;
-
- /** Holds the name of the property to store nanosecond timestamps in ping messages with. */
- public static final String MESSAGE_TIMESTAMP_PROPNAME = "timestamp";
-
- /** Holds the name of the property to get the number of message to prefill the broker with before starting the main test. */
- public static final String PREFILL_PROPNAME = "preFill";
-
- /** Defines the default value for the number of messages to prefill. 0,default, no messages. */
- public static final int PREFILL_DEFAULT = 0;
-
- /** Holds the name of the property to get the delay to wait in ms before starting the main test after having prefilled. */
- public static final String DELAY_BEFORE_CONSUME_PROPNAME = "delayBeforeConsume";
-
- /** Defines the default value for delay in ms to wait before starting thet test run. 0,default, no delay. */
- public static final long DELAY_BEFORE_CONSUME = 0;
-
- /** Holds the name of the property to get when no messasges should be sent. */
- public static final String CONSUME_ONLY_PROPNAME = "consumeOnly";
-
- /** Defines the default value of the consumeOnly flag to use when publishing messages is not desired. */
- public static final boolean CONSUME_ONLY_DEFAULT = false;
-
- /** Holds the name of the property to get when no messasges should be sent. */
- public static final String SEND_ONLY_PROPNAME = "sendOnly";
-
- /** Defines the default value of the consumeOnly flag to use when publishing messages is not desired. */
- public static final boolean SEND_ONLY_DEFAULT = false;
-
- /** Holds the default configuration properties. */
- public static ParsedProperties defaults = new ParsedProperties();
-
- static
- {
- defaults.setPropertyIfNull(OVERRIDE_CLIENT_ID_PROPNAME, OVERRIDE_CLIENT_ID_DEAFULT);
- defaults.setPropertyIfNull(FILE_PROPERTIES_PROPNAME, FILE_PROPERTIES_DEAFULT);
- defaults.setPropertyIfNull(FACTORY_NAME_PROPNAME, FACTORY_NAME_DEAFULT);
- defaults.setPropertyIfNull(BROKER_PROPNAME, BROKER_DEFAULT);
- defaults.setPropertyIfNull(USERNAME_PROPNAME, USERNAME_DEFAULT);
- defaults.setPropertyIfNull(PASSWORD_PROPNAME, PASSWORD_DEFAULT);
- defaults.setPropertyIfNull(VIRTUAL_HOST_PROPNAME, VIRTUAL_HOST_DEFAULT);
- defaults.setPropertyIfNull(PING_QUEUE_NAME_PROPNAME, PING_QUEUE_NAME_DEFAULT);
- defaults.setPropertyIfNull(QUEUE_NAME_POSTFIX_PROPNAME, QUEUE_NAME_POSTFIX_DEFAULT);
- defaults.setPropertyIfNull(SELECTOR_PROPNAME, SELECTOR_DEFAULT);
- defaults.setPropertyIfNull(TRANSACTED_PROPNAME, TRANSACTED_DEFAULT);
- defaults.setPropertyIfNull(CONSUMER_TRANSACTED_PROPNAME, CONSUMER_TRANSACTED_DEFAULT);
- defaults.setPropertyIfNull(PERSISTENT_MODE_PROPNAME, PERSISTENT_MODE_DEFAULT);
- defaults.setPropertyIfNull(ACK_MODE_PROPNAME, ACK_MODE_DEFAULT);
- defaults.setPropertyIfNull(CONSUMER_ACK_MODE_PROPNAME, CONSUMER_ACK_MODE_DEFAULT);
- defaults.setPropertyIfNull(MESSAGE_SIZE_PROPNAME, MESSAGE_SIZE_DEAFULT);
- defaults.setPropertyIfNull(VERBOSE_PROPNAME, VERBOSE_DEFAULT);
- defaults.setPropertyIfNull(PUBSUB_PROPNAME, PUBSUB_DEFAULT);
- defaults.setPropertyIfNull(UNIQUE_DESTS_PROPNAME, UNIQUE_DESTS_DEFAULT);
- defaults.setPropertyIfNull(DURABLE_DESTS_PROPNAME, DURABLE_DESTS_DEFAULT);
- defaults.setPropertyIfNull(FAIL_BEFORE_COMMIT_PROPNAME, FAIL_BEFORE_COMMIT_DEFAULT);
- defaults.setPropertyIfNull(FAIL_AFTER_COMMIT_PROPNAME, FAIL_AFTER_COMMIT_DEFAULT);
- defaults.setPropertyIfNull(FAIL_BEFORE_SEND_PROPNAME, FAIL_BEFORE_SEND_DEFAULT);
- defaults.setPropertyIfNull(FAIL_AFTER_SEND_PROPNAME, FAIL_AFTER_SEND_DEFAULT);
- defaults.setPropertyIfNull(FAIL_ONCE_PROPNAME, FAIL_ONCE_DEFAULT);
- defaults.setPropertyIfNull(TX_BATCH_SIZE_PROPNAME, TX_BATCH_SIZE_DEFAULT);
- defaults.setPropertyIfNull(DESTINATION_COUNT_PROPNAME, DESTINATION_COUNT_DEFAULT);
- defaults.setPropertyIfNull(NUM_CONSUMERS_PROPNAME, NUM_CONSUMERS_DEFAULT);
- defaults.setPropertyIfNull(RATE_PROPNAME, RATE_DEFAULT);
- defaults.setPropertyIfNull(TIMEOUT_PROPNAME, TIMEOUT_DEFAULT);
- defaults.setPropertyIfNull(MAX_PENDING_PROPNAME, MAX_PENDING_DEFAULT);
- defaults.setPropertyIfNull(PREFILL_PROPNAME, PREFILL_DEFAULT);
- defaults.setPropertyIfNull(DELAY_BEFORE_CONSUME_PROPNAME, DELAY_BEFORE_CONSUME);
- defaults.setPropertyIfNull(CONSUME_ONLY_PROPNAME, CONSUME_ONLY_DEFAULT);
- defaults.setPropertyIfNull(SEND_ONLY_PROPNAME, SEND_ONLY_DEFAULT);
- }
-
- /** Allows setting of client ID on the connection, rather than through the connection URL. */
- protected boolean _overrideClientId;
-
- /** Holds the JNDI name of the JMS connection factory. */
- protected String _factoryName;
-
- /** Holds the name of the properties file to configure JNDI with. */
- protected String _fileProperties;
-
- /** Holds the broker url. */
- protected String _brokerDetails;
-
- /** Holds the username to access the broker with. */
- protected String _username;
-
- /** Holds the password to access the broker with. */
- protected String _password;
-
- /** Holds the virtual host on the broker to run the tests through. */
- protected String _virtualpath;
-
- /** Holds the root name from which to generate test destination names. */
- protected String _destinationName;
-
- /** Holds the default queue name postfix value. */
- protected String _queueNamePostfix;
-
- /** Holds the message selector to filter the pings with. */
- protected String _selector;
-
- /** Holds the producers transactional mode flag. */
- protected boolean _transacted;
-
- /** Holds the consumers transactional mode flag. */
- protected boolean _consTransacted;
-
- /** Determines whether this producer sends persistent messages. */
- protected boolean _persistent;
-
- /** Holds the acknowledgement mode used for the producers. */
- protected int _ackMode;
-
- /** Holds the acknowledgement mode setting for the consumers. */
- protected int _consAckMode;
-
- /** Determines what size of messages this producer sends. */
- protected int _messageSize;
-
- /** Used to indicate that the ping loop should print out whenever it pings. */
- protected boolean _verbose;
-
- /** Flag used to indicate if this is a point to point or pub/sub ping client. */
- protected boolean _isPubSub;
-
- /** Flag used to indicate if the destinations should be unique client. */
- protected boolean _isUnique;
-
- /** Flag used to indicate that durable destination should be used. */
- protected boolean _isDurable;
-
- /** Flag used to indicate that the user should be prompted to terminate a broker, to test failover before a commit. */
- protected boolean _failBeforeCommit;
-
- /** Flag used to indicate that the user should be prompted to terminate a broker, to test failover after a commit. */
- protected boolean _failAfterCommit;
-
- /** Flag used to indicate that the user should be prompted to terminate a broker, to test failover before a send. */
- protected boolean _failBeforeSend;
-
- /** Flag used to indicate that the user should be prompted to terminate a broker, to test failover after a send. */
- protected boolean _failAfterSend;
-
- /** Flag used to indicate that failover prompting should only be done on the first commit, not on every commit. */
- protected boolean _failOnce;
-
- /** Holds the number of sends that should be performed in every transaction when using transactions. */
- protected int _txBatchSize;
-
- /** Holds the number of destinations to ping. */
- protected int _noOfDestinations;
-
- /** Holds the number of consumers per destination. */
- protected int _noOfConsumers;
-
- /** Holds the maximum send rate in herz. */
- protected int _rate;
-
- /**
- * Holds the size of the maximum amount of pending data that the client should buffer, sending is suspended
- * if this limit is breached.
- */
- protected int _maxPendingSize;
-
- /**
- * Holds the number of messages to send during the setup phase, before the clients start consuming.
- */
- private Integer _preFill;
-
- /**
- * Holds the time in ms to wait after preFilling before starting thet test.
- */
- private Long _delayBeforeConsume;
-
- /**
- * Holds a boolean value of wither this test should just consume, i.e. skips
- * sending messages, but still expects to receive the specified number.
- */
- private boolean _consumeOnly;
-
- /**
- * Holds a boolean value of wither this test should just send, i.e. skips
- * consuming messages, but still creates clients just doesn't start them.
- */
- private boolean _sendOnly;
-
-
- /** A source for providing sequential unique correlation ids. These will be unique within the same JVM. */
- private static AtomicLong _correlationIdGenerator = new AtomicLong(0L);
-
- /** A source for providing sequential unqiue ids for instances of this class to be identifed with. */
- private static AtomicInteger _instanceIdGenerator = new AtomicInteger(0);
-
- /** Holds this instances unique id. */
- private int instanceId;
-
- /**
- * Holds a map from message ids to latches on which threads wait for replies. This map is shared accross multiple
- * ping producers on the same JVM.
- */
- private static Map<String, PerCorrelationId> perCorrelationIds =
- Collections.synchronizedMap(new HashMap<String, PerCorrelationId>());
-
- /** A convenient formatter to use when time stamping output. */
- protected static final DateFormat timestampFormatter = new SimpleDateFormat("hh:mm:ss:SS");
-
- /** Holds the connection for the message producer. */
- protected Connection _connection;
-
- /** Holds the consumer connections. */
- protected Connection[] _consumerConnection;
-
- /** Holds the controlSession on which ping replies are received. */
- protected Session[] _consumerSession;
-
- /** Holds the producer controlSession, needed to create ping messages. */
- protected Session _producerSession;
-
- /** Holds the destination where the response messages will arrive. */
- protected Destination _replyDestination;
-
- /** Holds the set of destinations that this ping producer pings. */
- protected List<Destination> _pingDestinations;
-
- /** Used to restrict the sending rate to a specified limit. */
- protected Throttle _rateLimiter;
-
- /** Holds a message listener that this message listener chains all its messages to. */
- protected ChainedMessageListener _chainedMessageListener = null;
-
- /**
- * This id generator is used to generate ids to append to the queue name to ensure that queues can be unique when
- * creating multiple ping producers in the same JVM.
- */
- protected static AtomicInteger _queueJVMSequenceID = new AtomicInteger();
-
- /**
- * This id generator is used to generates ids that are only unique within this pinger. Creating multiple pingers
- * on the same JVM using this id generator will allow them to ping on the same queues.
- */
- protected AtomicInteger _queueSharedID = new AtomicInteger();
-
- /** Used to tell the ping loop when to terminate, it only runs while this is true. */
- protected boolean _publish = true;
-
- /** Holds the message producer to send the pings through. */
- protected MessageProducer _producer;
-
- /** Holds the message consumer to receive the ping replies through. */
- protected MessageConsumer[] _consumer;
-
- /** The prompt to display when asking the user to kill the broker for failover testing. */
- private static final String KILL_BROKER_PROMPT = "Kill broker now, then press Return.";
-
- /** Holds the name for this test client to be identified to the broker with. */
- private String _clientID;
-
- /** Keeps count of the total messages sent purely for debugging purposes. */
- private static AtomicInteger numSent = new AtomicInteger();
-
- /**
- * Holds a monitor which is used to synchronize sender and receivers threads, where the sender has elected
- * to wait until the number of unreceived message is reduced before continuing to send. This monitor is a
- * fair SynchronousQueue becuase that provides fair scheduling, to ensure that all producer threads get an
- * equal chance to produce messages.
- */
- static final SynchronousQueue _sendPauseMonitor = new SynchronousQueue(true);
-
- /** Keeps a count of the number of message currently sent but not received. */
- static AtomicInteger _unreceived = new AtomicInteger(0);
-
- /**
- * Creates a ping producer with the specified parameters, of which there are many. See the class level comments
- * for details. This constructor creates a connection to the broker and creates producer and consumer sessions on
- * it, to send and recieve its pings and replies on.
- *
- * @param overrides Properties containing any desired overrides to the defaults.
- *
- * @throws Exception Any exceptions are allowed to fall through.
- */
- public PingPongProducer(Properties overrides) throws Exception
- {
- // log.debug("public PingPongProducer(Properties overrides = " + overrides + "): called");
- instanceId = _instanceIdGenerator.getAndIncrement();
-
- // Create a set of parsed properties from the defaults overriden by the passed in values.
- ParsedProperties properties = new ParsedProperties(defaults);
- properties.putAll(overrides);
-
- // Extract the configuration properties to set the pinger up with.
- _overrideClientId = properties.getPropertyAsBoolean(OVERRIDE_CLIENT_ID_PROPNAME);
- _factoryName = properties.getProperty(FACTORY_NAME_PROPNAME);
- _fileProperties = properties.getProperty(FILE_PROPERTIES_PROPNAME);
- _brokerDetails = properties.getProperty(BROKER_PROPNAME);
- _username = properties.getProperty(USERNAME_PROPNAME);
- _password = properties.getProperty(PASSWORD_PROPNAME);
- _virtualpath = properties.getProperty(VIRTUAL_HOST_PROPNAME);
- _destinationName = properties.getProperty(PING_QUEUE_NAME_PROPNAME);
- _queueNamePostfix = properties.getProperty(QUEUE_NAME_POSTFIX_PROPNAME);
- _selector = properties.getProperty(SELECTOR_PROPNAME);
- _transacted = properties.getPropertyAsBoolean(TRANSACTED_PROPNAME);
- _consTransacted = properties.getPropertyAsBoolean(CONSUMER_TRANSACTED_PROPNAME);
- _persistent = properties.getPropertyAsBoolean(PERSISTENT_MODE_PROPNAME);
- _messageSize = properties.getPropertyAsInteger(MESSAGE_SIZE_PROPNAME);
- _verbose = properties.getPropertyAsBoolean(VERBOSE_PROPNAME);
- _failAfterCommit = properties.getPropertyAsBoolean(FAIL_AFTER_COMMIT_PROPNAME);
- _failBeforeCommit = properties.getPropertyAsBoolean(FAIL_BEFORE_COMMIT_PROPNAME);
- _failAfterSend = properties.getPropertyAsBoolean(FAIL_AFTER_SEND_PROPNAME);
- _failBeforeSend = properties.getPropertyAsBoolean(FAIL_BEFORE_SEND_PROPNAME);
- _failOnce = properties.getPropertyAsBoolean(FAIL_ONCE_PROPNAME);
- _txBatchSize = properties.getPropertyAsInteger(TX_BATCH_SIZE_PROPNAME);
- _noOfDestinations = properties.getPropertyAsInteger(DESTINATION_COUNT_PROPNAME);
- _noOfConsumers = properties.getPropertyAsInteger(NUM_CONSUMERS_PROPNAME);
- _rate = properties.getPropertyAsInteger(RATE_PROPNAME);
- _isPubSub = properties.getPropertyAsBoolean(PUBSUB_PROPNAME);
- _isUnique = properties.getPropertyAsBoolean(UNIQUE_DESTS_PROPNAME);
- _isDurable = properties.getPropertyAsBoolean(DURABLE_DESTS_PROPNAME);
- _ackMode = _transacted ? 0 : properties.getPropertyAsInteger(ACK_MODE_PROPNAME);
- _consAckMode = _consTransacted ? 0 : properties.getPropertyAsInteger(CONSUMER_ACK_MODE_PROPNAME);
- _maxPendingSize = properties.getPropertyAsInteger(MAX_PENDING_PROPNAME);
- _preFill = properties.getPropertyAsInteger(PREFILL_PROPNAME);
- _delayBeforeConsume = properties.getPropertyAsLong(DELAY_BEFORE_CONSUME_PROPNAME);
- _consumeOnly = properties.getPropertyAsBoolean(CONSUME_ONLY_PROPNAME);
- _sendOnly = properties.getPropertyAsBoolean(SEND_ONLY_PROPNAME);
-
- // Check that one or more destinations were specified.
- if (_noOfDestinations < 1)
- {
- throw new IllegalArgumentException("There must be at least one destination.");
- }
-
- // Set up a throttle to control the send rate, if a rate > 0 is specified.
- if (_rate > 0)
- {
- _rateLimiter = new BatchedThrottle();
- _rateLimiter.setRate(_rate);
- }
-
- // Create the connection and message producers/consumers.
- // establishConnection(true, true);
- }
-
- /**
- * Establishes a connection to the broker and creates message consumers and producers based on the parameters
- * that this ping client was created with.
- *
- * @param producer Flag to indicate whether or not the producer should be set up.
- * @param consumer Flag to indicate whether or not the consumers should be set up.
- *
- * @throws Exception Any exceptions are allowed to fall through.
- */
- public void establishConnection(boolean producer, boolean consumer) throws Exception
- {
- // log.debug("public void establishConnection(): called");
-
- // Generate a unique identifying name for this client, based on it ip address and the current time.
- InetAddress address = InetAddress.getLocalHost();
- // _clientID = address.getHostName() + System.currentTimeMillis();
- _clientID = "perftest_" + instanceId;
-
- // Create a connection to the broker.
- createConnection(_clientID);
-
- // Create transactional or non-transactional sessions, based on the command line arguments.
- _producerSession = _connection.createSession(_transacted, _ackMode);
-
- _consumerSession = new Session[_noOfConsumers];
-
- for (int i = 0; i < _noOfConsumers; i++)
- {
- _consumerSession[i] = _consumerConnection[i].createSession(_consTransacted, _consAckMode);
- }
-
- // Create the destinations to send pings to and receive replies from.
- if (_noOfConsumers > 0)
- {
- _replyDestination = _consumerSession[0].createTemporaryQueue();
- }
- createPingDestinations(_noOfDestinations, _selector, _destinationName, _isUnique, _isDurable);
-
- // Create the message producer only if instructed to.
- if (producer)
- {
- createProducer();
- }
-
- // Create the message consumer only if instructed to.
- if (consumer)
- {
- createReplyConsumers(getReplyDestinations(), _selector);
- }
- }
-
- /**
- * Establishes a connection to the broker, based on the configuration parameters that this ping client was
- * created with.
- *
- * @param clientID The clients identifier.
- *
- * @throws JMSException Underlying exceptions allowed to fall through.
- * @throws NamingException Underlying exceptions allowed to fall through.
- * @throws IOException Underlying exceptions allowed to fall through.
- */
- protected void createConnection(String clientID) throws JMSException, NamingException, IOException
- {
- // _log.debug("protected void createConnection(String clientID = " + clientID + "): called");
-
- // _log.debug("Creating a connection for the message producer.");
- File propsFile = new File(_fileProperties);
- InputStream is = new FileInputStream(propsFile);
- Properties properties = new Properties();
- properties.load(is);
-
- Context context = new InitialContext(properties);
- ConnectionFactory factory = (ConnectionFactory) context.lookup(_factoryName);
- _connection = factory.createConnection(_username, _password);
-
- if (_overrideClientId)
- {
- _connection.setClientID(clientID);
- }
-
- // _log.debug("Creating " + _noOfConsumers + " connections for the consumers.");
-
- _consumerConnection = new Connection[_noOfConsumers];
-
- for (int i = 0; i < _noOfConsumers; i++)
- {
- _consumerConnection[i] = factory.createConnection(_username, _password);
- // _consumerConnection[i].setClientID(clientID);
- }
- }
-
- /**
- * Starts a ping-pong loop running from the command line. The bounce back client {@link PingPongBouncer} also needs
- * to be started to bounce the pings back again.
- *
- * @param args The command line arguments.
- */
- public static void main(String[] args)
- {
- try
- {
- Properties options =
- CommandLineParser.processCommandLine(args, new CommandLineParser(new String[][] {}), System.getProperties());
-
- // Create a ping producer overriding its defaults with all options passed on the command line.
- PingPongProducer pingProducer = new PingPongProducer(options);
- pingProducer.establishConnection(true, true);
-
- // Start the ping producers dispatch thread running.
- pingProducer._connection.start();
-
- // Create a shutdown hook to terminate the ping-pong producer.
- Runtime.getRuntime().addShutdownHook(pingProducer.getShutdownHook());
-
- // Ensure that the ping pong producer is registered to listen for exceptions on the connection too.
- pingProducer._connection.setExceptionListener(pingProducer);
-
- // Create the ping loop thread and run it until it is terminated by the shutdown hook or exception.
- Thread pingThread = new Thread(pingProducer);
- pingThread.run();
- pingThread.join();
- }
- catch (Exception e)
- {
- System.err.println(e.getMessage());
- log.error("Top level handler caught execption.", e);
- System.exit(1);
- }
- }
-
- /**
- * Convenience method for a short pause.
- *
- * @param sleepTime The time in milliseconds to pause for.
- */
- public static void pause(long sleepTime)
- {
- if (sleepTime > 0)
- {
- try
- {
- Thread.sleep(sleepTime);
- }
- catch (InterruptedException ie)
- { }
- }
- }
-
- /**
- * Gets all the reply destinations (to listen for replies on). In this case this will just be the single reply to
- * destination of this pinger.
- *
- * @return The single reply to destination of this pinger, wrapped in a list.
- */
- public List<Destination> getReplyDestinations()
- {
- // log.debug("public List<Destination> getReplyDestinations(): called");
-
- List<Destination> replyDestinations = new ArrayList<Destination>();
- replyDestinations.add(_replyDestination);
-
- // log.debug("replyDestinations = " + replyDestinations);
-
- return replyDestinations;
- }
-
- /**
- * Creates the producer to send the pings on. This is created without a default destination. Its persistent delivery
- * flag is set accoring the ping producer creation options.
- *
- * @throws JMSException Any JMSExceptions are allowed to fall through.
- */
- public void createProducer() throws JMSException
- {
- // log.debug("public void createProducer(): called");
-
- _producer = (MessageProducer) _producerSession.createProducer(null);
- _producer.setDeliveryMode(_persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT);
-
- // log.debug("Created producer for " + (_persistent ? "persistent" : "non-persistent") + " messages.");
- }
-
- /**
- * Creates consumers for the specified number of destinations. The destinations themselves are also created by this
- * method.
- *
- * @param noOfDestinations The number of destinations to create consumers for.
- * @param selector The message selector to filter the consumers with.
- * @param rootName The root of the name, or actual name if only one is being created.
- * @param unique <tt>true</tt> to make the destinations unique to this pinger, <tt>false</tt> to share the
- * numbering with all pingers on the same JVM.
- * @param durable If the destinations are durable topics.
- *
- * @throws JMSException Any JMSExceptions are allowed to fall through.
- */
- public void createPingDestinations(int noOfDestinations, String selector, String rootName, boolean unique,
- boolean durable) throws JMSException
- {
- /*log.debug("public void createPingDestinations(int noOfDestinations = " + noOfDestinations + ", String selector = "
- + selector + ", String rootName = " + rootName + ", boolean unique = " + unique + ", boolean durable = "
- + durable + "): called");*/
-
- _pingDestinations = new ArrayList<Destination>();
-
- // Create the desired number of ping destinations and consumers for them.
- // log.debug("Creating " + noOfDestinations + " destinations to ping.");
-
- for (int i = 0; i < noOfDestinations; i++)
- {
- Destination destination;
- String id;
-
- // Generate an id, unique within this pinger or to the whole JVM depending on the unique flag.
- if (unique)
- {
- // log.debug("Creating unique destinations.");
- id = "_" + _queueJVMSequenceID.incrementAndGet() + "_" + _connection.getClientID();
- }
- else
- {
- // log.debug("Creating shared destinations.");
- id = "_" + _queueSharedID.incrementAndGet();
- }
-
- // Check if this is a pub/sub pinger, in which case create topics.
- if (_isPubSub)
- {
- destination = _producerSession.createTopic(rootName + id);
- // log.debug("Created non-durable topic " + destination);
-
- if (durable)
- {
- _producerSession.createDurableSubscriber((Topic) destination, _connection.getClientID());
- }
- }
- // Otherwise this is a p2p pinger, in which case create queues.
- else
- {
- destination = _producerSession.createQueue(rootName + id + _queueNamePostfix);
- // log.debug("Created queue " + destination);
- }
-
- // Keep the destination.
- _pingDestinations.add(destination);
- }
- }
-
- /**
- * Creates consumers for the specified destinations and registers this pinger to listen to their messages.
- *
- * @param destinations The destinations to listen to.
- * @param selector A selector to filter the messages with.
- *
- * @throws javax.jms.JMSException Any JMSExceptions are allowed to fall through.
- */
- public void createReplyConsumers(Collection<Destination> destinations, String selector) throws JMSException
- {
- /*log.debug("public void createReplyConsumers(Collection<Destination> destinations = " + destinations
- + ", String selector = " + selector + "): called");*/
-
- log.debug("There are " + destinations.size() + " destinations.");
- log.debug("Creating " + _noOfConsumers + " consumers on each destination.");
- log.debug("Total number of consumers is: " + (destinations.size() * _noOfConsumers));
-
- for (Destination destination : destinations)
- {
- _consumer = new MessageConsumer[_noOfConsumers];
-
- // If we don't have consumers then ensure we have created the
- // destination.
- if (_noOfConsumers == 0)
- {
- _producerSession.createConsumer(destination, selector,
- NO_LOCAL_DEFAULT).close();
- }
-
- for (int i = 0; i < _noOfConsumers; i++)
- {
- // Create a consumer for the destination and set this pinger to listen to its messages.
- _consumer[i] = _consumerSession[i].createConsumer(destination, selector, NO_LOCAL_DEFAULT);
-
- final int consumerNo = i;
-
- _consumer[i].setMessageListener(new MessageListener()
- {
- public void onMessage(Message message)
- {
- onMessageWithConsumerNo(message, consumerNo);
- }
- });
-
- log.debug("Set consumer " + i + " to listen to replies sent to destination: " + destination);
- }
- }
- }
-
- /**
- * Stores the received message in the replies map, then resets the boolean latch that a thread waiting for a
- * correlating reply may be waiting on. This is only done if the reply has a correlation id that is expected in the
- * replies map.
- *
- * @param message The received message.
- * @param consumerNo The consumer number within this test pinger instance.
- */
- public void onMessageWithConsumerNo(Message message, int consumerNo)
- {
- // log.debug("public void onMessageWithConsumerNo(Message message, int consumerNo = " + consumerNo + "): called");
- try
- {
- long now = System.nanoTime();
- long timestamp = getTimestamp(message);
- long pingTime = now - timestamp;
-
- // NDC.push("id" + instanceId + "/cons" + consumerNo);
-
- // Extract the messages correlation id.
- String correlationID = message.getJMSCorrelationID();
- // log.debug("correlationID = " + correlationID);
-
- // int num = message.getIntProperty("MSG_NUM");
- // log.info("Message " + num + " received.");
-
- boolean isRedelivered = message.getJMSRedelivered();
- // log.debug("isRedelivered = " + isRedelivered);
-
- if (!isRedelivered)
- {
- // Countdown on the traffic light if there is one for the matching correlation id.
- PerCorrelationId perCorrelationId = perCorrelationIds.get(correlationID);
-
- if (perCorrelationId != null)
- {
- CountDownLatch trafficLight = perCorrelationId.trafficLight;
-
- // Restart the timeout timer on every message.
- perCorrelationId.timeOutStart = System.nanoTime();
-
- // log.debug("Reply was expected, decrementing the latch for the id, " + correlationID);
-
- // Release waiting senders if there are some and using maxPending limit.
- if ((_maxPendingSize > 0))
- {
- // Decrement the count of sent but not yet received messages.
- int unreceived = _unreceived.decrementAndGet();
- int unreceivedSize =
- (unreceived * ((_messageSize == 0) ? 1 : _messageSize))
- / (_isPubSub ? getConsumersPerDestination() : 1);
-
- // log.debug("unreceived = " + unreceived);
- // log.debug("unreceivedSize = " + unreceivedSize);
-
- // synchronized (_sendPauseMonitor)
- // {
- if (unreceivedSize < _maxPendingSize)
- {
- _sendPauseMonitor.poll();
- }
- // }
- }
-
- // Decrement the countdown latch. Before this point, it is possible that two threads might enter this
- // method simultanesouly with the same correlation id. Decrementing the latch in a synchronized block
- // ensures that each thread will get a unique value for the remaining messages.
- long trueCount;
- long remainingCount;
-
- synchronized (trafficLight)
- {
- trafficLight.countDown();
-
- trueCount = trafficLight.getCount();
- remainingCount = trueCount - 1;
-
- // NDC.push("/rem" + remainingCount);
-
- // log.debug("remainingCount = " + remainingCount);
- // log.debug("trueCount = " + trueCount);
-
- // Commit on transaction batch size boundaries. At this point in time the waiting producer
- // remains blocked, even on the last message.
- // Commit count is divided by noOfConsumers in p2p mode, so that each consumer only commits on
- // each batch boundary. For pub/sub each consumer gets every message so no division is done.
- // When running in client ack mode, an ack is done instead of a commit, on the commit batch
- // size boundaries.
- long commitCount = _isPubSub ? remainingCount : (remainingCount / _noOfConsumers);
- // _noOfConsumers can be set to 0 on the command line but we will not get here to
- // divide by 0 as this is executed by the onMessage code when a message is recevied.
- // no consumers means no message reception.
-
-
- // log.debug("commitCount = " + commitCount);
-
- if ((commitCount % _txBatchSize) == 0)
- {
- if (_consAckMode == 2)
- {
- // log.debug("Doing client ack for consumer " + consumerNo + ".");
- message.acknowledge();
- }
- else
- {
- // log.debug("Trying commit for consumer " + consumerNo + ".");
- commitTx(_consumerSession[consumerNo]);
- // log.info("Tx committed on consumer " + consumerNo);
- }
- }
-
- // Forward the message and remaining count to any interested chained message listener.
- if (_chainedMessageListener != null)
- {
- _chainedMessageListener.onMessage(message, (int) remainingCount, pingTime);
- }
-
- // Check if this is the last message, in which case release any waiting producers. This is done
- // after the transaction has been committed and any listeners notified.
- if (trueCount == 1)
- {
- trafficLight.countDown();
- }
- }
- }
- else
- {
- log.warn(consumerNo + " Got unexpected message with correlationId: " + correlationID);
- log.warn(consumerNo + " Map contains:" + perCorrelationIds.entrySet());
- }
- }
- else
- {
- log.warn("Got redelivered message, ignoring.");
- }
- }
- catch (JMSException e)
- {
- log.warn("There was a JMSException: " + e.getMessage(), e);
- }
- finally
- {
- // log.debug("public void onMessageWithConsumerNo(Message message, int consumerNo): ending");
- // NDC.clear();
- }
- }
-
- public void setupCorrelationID(String correlationId, int expectedCount)
- {
- PerCorrelationId perCorrelationId = new PerCorrelationId();
-
- // Create a count down latch to count the number of replies with. This is created before the messages are
- // sent so that the replies cannot be received before the count down is created.
- // One is added to this, so that the last reply becomes a special case. The special case is that the
- // chained message listener must be called before this sender can be unblocked, but that decrementing the
- // countdown needs to be done before the chained listener can be called.
- perCorrelationId.trafficLight = new CountDownLatch(expectedCount + 1);
-
- perCorrelationIds.put(correlationId, perCorrelationId);
- }
-
-
- /**
- * Sends the specified number of ping message and then waits for all correlating replies. If the wait times out
- * before a reply arrives, then a null reply is returned from this method. This method allows the caller to specify
- * the correlation id.
- *
- * Can be augmented through a pre-fill property (PingPongProducer.PREFILL_PROPNAME) that will populate the destination
- * with a set number of messages so the total pings sent and therefore expected will be PREFILL + numPings.
- *
- * If pre-fill is specified then the consumers will start paused to allow the prefilling to occur.
- *
- * @param message The message to send. If this is null, one is generated.
- * @param numPings The number of ping messages to send.
- * @param timeout The timeout in milliseconds.
- * @param messageCorrelationId The message correlation id. If this is null, one is generated.
- *
- * @return The number of replies received. This may be less than the number sent if the timeout terminated the wait
- * for all prematurely. If we are running in noConsumer=0 so send only mode then it will return the no msgs sent.
- *
- * @throws JMSException All underlying JMSExceptions are allowed to fall through.
- * @throws InterruptedException When interrupted by a timeout
- */
- public int pingAndWaitForReply(Message message, int numPings, long timeout, String messageCorrelationId)
- throws JMSException, InterruptedException
- {
- return pingAndWaitForReply(message, numPings, 0, timeout, messageCorrelationId);
- }
-
- public int pingAndWaitForReply(Message message, int numPings, int preFill, long timeout, String messageCorrelationId)
- throws JMSException, InterruptedException
- {
- /*log.debug("public int pingAndWaitForReply(Message message, int numPings = " + numPings + ", long timeout = "
- + timeout + ", String messageCorrelationId = " + messageCorrelationId + "): called");*/
-
- int totalPingsRequested = numPings + preFill;
-
- // Generate a unique correlation id to put on the messages before sending them, if one was not specified.
- if (messageCorrelationId == null)
- {
- messageCorrelationId = Long.toString(_correlationIdGenerator.incrementAndGet());
-
- setupCorrelationID(messageCorrelationId, getExpectedNumPings(totalPingsRequested));
- }
-
- try
- {
- // NDC.push("prod");
-
- PerCorrelationId perCorrelationId = perCorrelationIds.get(messageCorrelationId);
-
- // Set up the current time as the start time for pinging on the correlation id. This is used to determine
- // timeouts.
- perCorrelationId.timeOutStart = System.nanoTime();
-
- // Send the specifed number of messages for this test
- pingNoWaitForReply(message, numPings, messageCorrelationId);
-
- boolean timedOut;
- boolean allMessagesReceived;
- int numReplies;
-
- // We don't have a consumer so don't try and wait for the messages.
- // this does mean that if the producerSession is !TXed then we may
- // get to exit before all msgs have been received.
- //
- // Return the number of requested messages, this will let the test
- // report a pass.
- if (_noOfConsumers == 0 || _sendOnly)
- {
- return getExpectedNumPings(totalPingsRequested);
- }
-
- do
- {
- // Block the current thread until replies to all the messages are received, or it times out.
- perCorrelationId.trafficLight.await(timeout, TimeUnit.MILLISECONDS);
-
- // Work out how many replies were receieved.
- numReplies = getExpectedNumPings(totalPingsRequested) - (int) perCorrelationId.trafficLight.getCount();
-
- allMessagesReceived = numReplies == getExpectedNumPings(totalPingsRequested);
-
- // log.debug("numReplies = " + numReplies);
- // log.debug("allMessagesReceived = " + allMessagesReceived);
-
- // Recheck the timeout condition.
- long now = System.nanoTime();
- long lastMessageReceievedAt = perCorrelationId.timeOutStart;
- timedOut = (now - lastMessageReceievedAt) > (timeout * 1000000);
-
- // log.debug("now = " + now);
- // log.debug("lastMessageReceievedAt = " + lastMessageReceievedAt);
- }
- while (!timedOut && !allMessagesReceived);
-
- if ((numReplies < getExpectedNumPings(totalPingsRequested)) && _verbose)
- {
- log.info("Timed out (" + timeout + " ms) before all replies received on id, " + messageCorrelationId);
- }
- else if (_verbose)
- {
- log.info("Got all replies on id, " + messageCorrelationId);
- }
-
- // commitTx(_consumerSession);
-
- // log.debug("public int pingAndWaitForReply(Message message, int numPings, long timeout): ending");
-
- return numReplies;
- }
- // Ensure that the message countdown latch is always removed from the reply map. The reply map is long lived,
- // so will be a memory leak if this is not done.
- finally
- {
- // NDC.pop();
- perCorrelationIds.remove(messageCorrelationId);
- }
- }
-
- /**
- * Sends the specified number of ping messages and does not wait for correlating replies.
- *
- * @param message The message to send.
- * @param numPings The number of pings to send.
- * @param messageCorrelationId A correlation id to place on all messages sent.
- *
- * @throws JMSException All underlying JMSExceptions are allowed to fall through.
- */
- public void pingNoWaitForReply(Message message, int numPings, String messageCorrelationId) throws JMSException
- {
- /*log.debug("public void pingNoWaitForReply(Message message, int numPings = " + numPings
- + ", String messageCorrelationId = " + messageCorrelationId + "): called");*/
-
- // If we are runnning a consumeOnly test then don't send any messages
- if (_consumeOnly)
- {
- return;
- }
-
- if (message == null)
- {
- message = getTestMessage(getReplyDestinations().get(0), _messageSize, _persistent);
- }
-
- message.setJMSCorrelationID(messageCorrelationId);
-
- // Set up a committed flag to detect uncommitted messages at the end of the send loop. This may occurr if the
- // transaction batch size is not a factor of the number of pings. In which case an extra commit at the end is
- // needed.
- boolean committed = false;
-
- // Send all of the ping messages.
- for (int i = 0; i < numPings; i++)
- {
- // Re-timestamp the message.
- // message.setLongProperty(MESSAGE_TIMESTAMP_PROPNAME, System.nanoTime());
-
- // Send the message, passing in the message count.
- committed = sendMessage(i, message);
-
- // Spew out per message timings on every message sonly in verbose mode.
- /*if (_verbose)
- {
- log.info(timestampFormatter.format(new Date()) + ": Pinged at with correlation id, " + messageCorrelationId);
- }*/
- }
-
- // Call commit if the send loop finished before reaching a batch size boundary so there may still be uncommitted messages.
- if (!committed)
- {
- commitTx(_producerSession);
- }
- }
-
- /**
- * Sends the sepcified message, applies rate limiting and possibly commits the current transaction. The count of
- * messages sent so far must be specified and is used to round robin the ping destinations (where there are more
- * than one), and to determine if the transaction batch size has been reached and the sent messages should be
- * committed.
- *
- * @param i The count of messages sent so far in a loop of multiple calls to this send method.
- * @param message The message to send.
- *
- * @return <tt>true</tt> if the messages were committed, <tt>false</tt> otherwise.
- *
- * @throws JMSException All underlyiung JMSExceptions are allowed to fall through.
- */
- protected boolean sendMessage(int i, Message message) throws JMSException
- {
- try
- {
- NDC.push("id" + instanceId + "/prod");
-
- // log.debug("protected boolean sendMessage(int i = " + i + ", Message message): called");
- // log.debug("_txBatchSize = " + _txBatchSize);
-
- // Round robin the destinations as the messages are sent.
- Destination destination = _pingDestinations.get(i % _pingDestinations.size());
-
- // Prompt the user to kill the broker when doing failover testing.
- _failBeforeSend = waitForUserToPromptOnFailure(_failBeforeSend);
-
- // Get the test setup for the correlation id.
- String correlationID = message.getJMSCorrelationID();
- PerCorrelationId perCorrelationId = perCorrelationIds.get(correlationID);
-
- // If necessary, wait until the max pending message size comes within its limit.
- if (_maxPendingSize > 0)
- {
- synchronized (_sendPauseMonitor)
- {
- // Used to keep track of the number of times that send has to wait.
- int numWaits = 0;
-
- // The maximum number of waits before the test gives up and fails. This has been chosen to correspond with
- // the test timeout.
- int waitLimit = (int) (TIMEOUT_DEFAULT / 10000);
-
- while (true)
- {
- // Get the size estimate of sent but not yet received messages.
- int unreceived = _unreceived.get();
- int unreceivedSize =
- (unreceived * ((_messageSize == 0) ? 1 : _messageSize))
- / (_isPubSub ? getConsumersPerDestination() : 1);
-
- // log.debug("unreceived = " + unreceived);
- // log.debug("unreceivedSize = " + unreceivedSize);
- // log.debug("_maxPendingSize = " + _maxPendingSize);
-
- if (unreceivedSize > _maxPendingSize)
- {
- // log.debug("unreceived size estimate over limit = " + unreceivedSize);
-
- // Fail the test if the send has had to wait more than the maximum allowed number of times.
- if (numWaits > waitLimit)
- {
- String errorMessage =
- "Send has had to wait for the unreceivedSize (" + unreceivedSize
- + ") to come below the maxPendingSize (" + _maxPendingSize + ") more that " + waitLimit
- + " times.";
- log.warn(errorMessage);
- throw new RuntimeException(errorMessage);
- }
-
- // Wait on the send pause barrier for the limit to be re-established.
- try
- {
- long start = System.nanoTime();
- // _sendPauseMonitor.wait(10000);
- _sendPauseMonitor.offer(new Object(), 10000, TimeUnit.MILLISECONDS);
- long end = System.nanoTime();
-
- // Count the wait only if it was for > 99% of the requested wait time.
- if (((float) (end - start) / (float) (10000 * 1000000L)) > 0.99)
- {
- numWaits++;
- }
- }
- catch (InterruptedException e)
- {
- // Restore the interrupted status
- Thread.currentThread().interrupt();
- throw new RuntimeException(e);
- }
- }
- else
- {
- break;
- }
- }
- }
- }
-
- // Send the message either to its round robin destination, or its default destination.
- // int num = numSent.incrementAndGet();
- // message.setIntProperty("MSG_NUM", num);
- setTimestamp(message);
-
- if (destination == null)
- {
- _producer.send(message);
- }
- else
- {
- _producer.send(destination, message);
- }
-
- // Increase the unreceived size, this may actually happen after the message is received.
- // The unreceived size is incremented by the number of consumers that will get a copy of the message,
- // in pub/sub mode.
- if (_maxPendingSize > 0)
- {
- int newUnreceivedCount = _unreceived.addAndGet(_isPubSub ? getConsumersPerDestination() : 1);
- // log.debug("newUnreceivedCount = " + newUnreceivedCount);
- }
-
- // Apply message rate throttling if a rate limit has been set up.
- if (_rateLimiter != null)
- {
- _rateLimiter.throttle();
- }
-
- // Call commit every time the commit batch size is reached.
- boolean committed = false;
-
- // Commit on every transaction batch size boundary. Here i + 1 is the count of actual messages sent.
- if (((i + 1) % _txBatchSize) == 0)
- {
- // log.debug("Trying commit on producer session.");
- committed = commitTx(_producerSession);
- }
-
- return committed;
- }
- finally
- {
- NDC.clear();
- }
- }
-
- /**
- * If the specified fail flag is set, this method waits for the user to cause a failure and then indicate to the
- * test that the failure has occurred, before the method returns.
- *
- * @param failFlag The fail flag to test.
- *
- * @return The new value for the fail flag. If the {@link #_failOnce} flag is set, then each fail flag is only
- * used once, then reset.
- */
- private boolean waitForUserToPromptOnFailure(boolean failFlag)
- {
- if (failFlag)
- {
- if (_failOnce)
- {
- failFlag = false;
- }
-
- // log.debug("Failing Before Send");
- waitForUser(KILL_BROKER_PROMPT);
- }
-
- return failFlag;
- }
-
- /**
- * Implements a single iteration of the ping loop. This sends the number of pings specified by the transaction batch
- * size property, and waits for replies to all of them. Any errors cause the publish flag to be cleared, which will
- * terminate the pinger.
- */
- public void pingLoop()
- {
- try
- {
- // Generate a sample message and time stamp it.
- Message msg = getTestMessage(_replyDestination, _messageSize, _persistent);
- // setTimestamp(msg);
-
- // Send the message and wait for a reply.
- pingAndWaitForReply(msg, TX_BATCH_SIZE_DEFAULT, TIMEOUT_DEFAULT, null);
- }
- catch (JMSException e)
- {
- _publish = false;
- // log.debug("There was a JMSException: " + e.getMessage(), e);
- }
- catch (InterruptedException e)
- {
- _publish = false;
- // log.debug("There was an interruption: " + e.getMessage(), e);
- }
- }
-
- /**
- * Sets a chained message listener. The message listener on this pinger, chains all its messages to the one set
- * here.
- *
- * @param messageListener The chained message listener.
- */
- public void setChainedMessageListener(ChainedMessageListener messageListener)
- {
- _chainedMessageListener = messageListener;
- }
-
- /** Removes any chained message listeners from this pinger. */
- public void removeChainedMessageListener()
- {
- _chainedMessageListener = null;
- }
-
- /**
- * Generates a test message of the specified size, with the specified reply-to destination and persistence flag.
- *
- * @param replyQueue The reply-to destination for the message.
- * @param messageSize The desired size of the message in bytes.
- * @param persistent <tt>true</tt> if the message should use persistent delivery, <tt>false</tt> otherwise.
- *
- * @return A freshly generated test message.
- *
- * @throws javax.jms.JMSException All underlying JMSException are allowed to fall through.
- */
- public Message getTestMessage(Destination replyQueue, int messageSize, boolean persistent) throws JMSException
- {
- // return TestMessageFactory.newObjectMessage(_producerSession, replyQueue, messageSize, persistent);
- return TestUtils.createTestMessageOfSize(_producerSession, messageSize);
- }
-
- /**
- * Sets the current time in nanoseconds as the timestamp on the message.
- *
- * @param msg The message to timestamp.
- *
- * @throws JMSException Any JMSExceptions are allowed to fall through.
- */
- protected void setTimestamp(Message msg) throws JMSException
- {
- /*if (((AMQSession)_producerSession).isStrictAMQP())
- {
- ((AMQMessage)msg).setTimestampProperty(new AMQShortString(MESSAGE_TIMESTAMP_PROPNAME), System.nanoTime());
- }
- else
- {*/
- msg.setLongProperty(MESSAGE_TIMESTAMP_PROPNAME, System.nanoTime());
- // }
- }
-
- /**
- * Extracts the nanosecond timestamp from a message.
- *
- * @param msg The message to extract the time stamp from.
- *
- * @return The timestamp in nanos.
- *
- * @throws JMSException Any JMSExceptions are allowed to fall through.
- */
- protected long getTimestamp(Message msg) throws JMSException
- {
- /*if (((AMQSession)_producerSession).isStrictAMQP())
- {
- Long value = ((AMQMessage)msg).getTimestampProperty(new AMQShortString(MESSAGE_TIMESTAMP_PROPNAME));
-
- return (value == null) ? 0L : value;
- }
- else
- {*/
- return msg.getLongProperty(PingPongProducer.MESSAGE_TIMESTAMP_PROPNAME);
- // }
- }
-
- /**
- * Stops the ping loop by clearing the publish flag. The current loop will complete when it notices that this flag
- * has been cleared.
- */
- public void stop()
- {
- _publish = false;
- }
-
- /**
- * Starts the producer and consumer connections.
- *
- * @throws JMSException Any JMSExceptions are allowed to fall through.
- */
- public void start() throws JMSException
- {
- // log.debug("public void start(): called");
-
- _connection.start();
- // log.debug("Producer started.");
-
- for (int i = 0; i < _noOfConsumers; i++)
- {
- _consumerConnection[i].start();
- // log.debug("Consumer " + i + " started.");
- }
- }
-
- /** Implements a ping loop that repeatedly pings until the publish flag becomes false. */
- public void run()
- {
- // Keep running until the publish flag is cleared.
- while (_publish)
- {
- pingLoop();
- }
- }
-
- /**
- * Callback method, implementing ExceptionListener. This should be registered to listen for exceptions on the
- * connection, this clears the publish flag which in turn will halt the ping loop.
- *
- * @param e The exception that triggered this callback method.
- */
- public void onException(JMSException e)
- {
- // log.debug("public void onException(JMSException e = " + e + "): called", e);
- _publish = false;
- }
-
- /**
- * Gets a shutdown hook that will cleanly shut this down when it is running the ping loop. This can be registered
- * with the runtime system as a shutdown hook.
- *
- * @return A shutdown hook for the ping loop.
- */
- public Thread getShutdownHook()
- {
- return new Thread(new Runnable()
- {
- public void run()
- {
- stop();
- }
- });
- }
-
- /**
- * Closes all of the producer and consumer connections.
- *
- * @throws JMSException All JMSException are allowed to fall through.
- */
- public void close() throws JMSException
- {
- // log.debug("public void close(): called");
-
- try
- {
- if (_connection != null)
- {
- // log.debug("Before close producer connection.");
- _connection.close();
- // log.debug("Closed producer connection.");
- }
-
- for (int i = 0; i < _noOfConsumers; i++)
- {
- if (_consumerConnection[i] != null)
- {
- // log.debug("Before close consumer connection " + i + ".");
- _consumerConnection[i].close();
- // log.debug("Closed consumer connection " + i + ".");
- }
- }
- }
- finally
- {
- _connection = null;
- _producerSession = null;
- _consumerSession = null;
- _consumerConnection = null;
- _producer = null;
- _consumer = null;
- _pingDestinations = null;
- _replyDestination = null;
- }
- }
-
- /**
- * Convenience method to commit the transaction on the specified controlSession. If the controlSession to commit on is not a
- * transactional controlSession, this method does nothing (unless the failover after send flag is set).
- *
- * <p/>If the {@link #_failAfterSend} flag is set, this will prompt the user to kill the broker before the commit is
- * applied. This flag applies whether the pinger is transactional or not.
- *
- * <p/>If the {@link #_failBeforeCommit} flag is set, this will prompt the user to kill the broker before the commit
- * is applied. If the {@link #_failAfterCommit} flag is set, this will prompt the user to kill the broker after the
- * commit is applied. These flags will only apply if using a transactional pinger.
- *
- * @param session The controlSession to commit
- *
- * @return <tt>true</tt> if the controlSession was committed, <tt>false</tt> if it was not.
- *
- * @throws javax.jms.JMSException If the commit fails and then the rollback fails.
- *
- * @todo Consider moving the fail after send logic into the send method. It is confusing to have it in this commit
- * method, because commits only apply to transactional pingers, but fail after send applied to transactional and
- * non-transactional alike.
- */
- protected boolean commitTx(Session session) throws JMSException
- {
- // log.debug("protected void commitTx(Session session): called");
-
- boolean committed = false;
-
- _failAfterSend = waitForUserToPromptOnFailure(_failAfterSend);
-
- if (session.getTransacted())
- {
- // log.debug("Session is transacted.");
-
- try
- {
- _failBeforeCommit = waitForUserToPromptOnFailure(_failBeforeCommit);
-
- long start = System.nanoTime();
- session.commit();
- committed = true;
- // log.debug("Time taken to commit :" + ((System.nanoTime() - start) / 1000000f) + " ms");
-
- _failAfterCommit = waitForUserToPromptOnFailure(_failAfterCommit);
-
- // log.debug("Session Commited.");
- }
- catch (JMSException e)
- {
- // log.debug("JMSException on commit:" + e.getMessage(), e);
-
- try
- {
- session.rollback();
- // log.debug("Message rolled back.");
- }
- catch (JMSException jmse)
- {
- // log.debug("JMSE on rollback:" + jmse.getMessage(), jmse);
-
- // Both commit and rollback failed. Throw the rollback exception.
- throw jmse;
- }
- }
- }
-
- return committed;
- }
-
- /**
- * Outputs a prompt to the console and waits for the user to press return.
- *
- * @param prompt The prompt to display on the console.
- */
- public void waitForUser(String prompt)
- {
- System.out.println(prompt);
-
- try
- {
- System.in.read();
- }
- catch (IOException e)
- {
- // Ignored.
- }
-
- System.out.println("Continuing.");
- }
-
- /**
- * Gets the number of consumers that are listening to each destination in the test.
- *
- * @return int The number of consumers subscribing to each topic.
- */
- public int getConsumersPerDestination()
- {
- return _noOfConsumers;
- }
-
- /**
- * Calculates how many pings are expected to be received for the given number sent.
- *
- * Note : that if you have set noConsumers to 0 then this will also return 0
- * in the case of PubSub testing. This is correct as without consumers there
- * will be no-one to receive the sent messages so they will be unable to respond.
- *
- * @param numpings The number of pings that will be sent.
- *
- * @return The number that should be received, for the test to pass.
- */
- public int getExpectedNumPings(int numpings)
- {
- // Wow, I'm freaking sorry about this return here...
- return ((_failAfterSend || _failBeforeCommit) ? numpings - 1: numpings) *
- (_isPubSub ? getConsumersPerDestination() : 1);
- }
-
- /**
- * Defines a chained message listener interface that can be attached to this pinger. Whenever this pinger's {@link
- * PingPongProducer#onMessageWithConsumerNo} method is called, the chained listener set through the {@link
- * PingPongProducer#setChainedMessageListener} method is passed the message, and the remaining expected count of
- * messages with that correlation id.
- *
- * <p/>Provided only one pinger is producing messages with that correlation id, the chained listener will always be
- * given unique message counts. It will always be called while the producer waiting for all messages to arrive is
- * still blocked.
- */
- public static interface ChainedMessageListener
- {
- /**
- * Notifies interested listeners about message arrival and important test stats, the number of messages
- * remaining in the test, and the messages send timestamp.
- *
- * @param message The newly arrived message.
- * @param remainingCount The number of messages left to complete the test.
- * @param latency The nanosecond latency of the message.
- *
- * @throws JMSException Any JMS exceptions is allowed to fall through.
- */
- public void onMessage(Message message, int remainingCount, long latency) throws JMSException;
- }
-
- /**
- * Holds information on each correlation id. The countdown latch, the current timeout timer... More stuff to be
- * added to this: read/write lock to make onMessage more concurrent as described in class header comment.
- */
- protected static class PerCorrelationId
- {
- /** Holds a countdown on number of expected messages. */
- CountDownLatch trafficLight;
-
- /** Holds the last timestamp that the timeout was reset to. */
- Long timeOutStart;
- }
-}
diff --git a/java/perftests/src/main/java/org/apache/qpid/requestreply/PingPongTestPerf.java b/java/perftests/src/main/java/org/apache/qpid/requestreply/PingPongTestPerf.java
deleted file mode 100644
index 009254c612..0000000000
--- a/java/perftests/src/main/java/org/apache/qpid/requestreply/PingPongTestPerf.java
+++ /dev/null
@@ -1,251 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.requestreply;
-
-import junit.framework.Assert;
-import junit.framework.Test;
-import junit.framework.TestSuite;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.junit.extensions.AsymptoticTestCase;
-import org.apache.qpid.junit.extensions.util.ParsedProperties;
-import org.apache.qpid.junit.extensions.util.TestContextProperties;
-
-import javax.jms.*;
-
-/**
- * PingPongTestPerf is a full round trip ping test, that has been written with the intention of being scaled up to run
- * many times simultaneously to simluate many clients/producer/connections. A full round trip ping sends a message from
- * a producer to a conumer, then the consumer replies to the message on a temporary queue.
- *
- * <p/>A single run of the test using the default JUnit test runner will result in the sending and timing of the number
- * of pings specified by the test size and time how long it takes for all of these to complete. This test may be scaled
- * up using a suitable JUnit test runner. See {@link org.apache.qpid.junit.extensions.TKTestRunner} for more
- * information on how to do this.
- *
- * <p/>The setup/teardown cycle establishes a connection to a broker and sets up a queue to send ping messages to and a
- * temporary queue for replies. This setup is only established once for all the test repeats, but each test threads
- * gets its own connection/producer/consumer, this is only re-established if the connection is lost.
- *
- * <p/>The test cycle is: Connects to a queue, creates a temporary queue, creates messages containing a property that
- * is the name of the temporary queue, fires off many messages on the original queue and waits for them all to come
- * back on the temporary queue.
- *
- * <p/>Configurable test properties: message size, transacted or not, persistent or not. Broker connection details.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * </table>
- */
-public class PingPongTestPerf extends AsymptoticTestCase
-{
- private static Logger _logger = Logger.getLogger(PingPongTestPerf.class);
-
- /** Thread local to hold the per-thread test setup fields. */
- ThreadLocal<PerThreadSetup> threadSetup = new ThreadLocal<PerThreadSetup>();
-
- // Set up a property reader to extract the test parameters from. Once ContextualProperties is available in
- // the project dependencies, use it to get property overrides for configurable tests and to notify the test runner
- // of the test parameters to log with the results. It also providers some basic type parsing convenience methods.
- // private Properties testParameters = System.getProperties();
- private ParsedProperties testParameters =
- TestContextProperties.getInstance(PingPongProducer.defaults /*System.getProperties()*/);
-
- public PingPongTestPerf(String name)
- {
- super(name);
-
- _logger.debug(testParameters);
-
- // Sets up the test parameters with defaults.
- /*testParameters.setPropertyIfNull(PingPongProducer.TX_BATCH_SIZE_PROPNAME,
- Integer.toString(PingPongProducer.TX_BATCH_SIZE_DEFAULT));
- testParameters.setPropertyIfNull(PingPongProducer.MESSAGE_SIZE_PROPNAME,
- Integer.toString(PingPongProducer.MESSAGE_SIZE_DEAFULT));
- testParameters.setPropertyIfNull(PingPongProducer.PING_QUEUE_NAME_PROPNAME,
- PingPongProducer.PING_QUEUE_NAME_DEFAULT);
- testParameters.setPropertyIfNull(PingPongProducer.PERSISTENT_MODE_PROPNAME,
- Boolean.toString(PingPongProducer.PERSISTENT_MODE_DEFAULT));
- testParameters.setPropertyIfNull(PingPongProducer.TRANSACTED_PROPNAME,
- Boolean.toString(PingPongProducer.TRANSACTED_DEFAULT));
- testParameters.setPropertyIfNull(PingPongProducer.BROKER_PROPNAME, PingPongProducer.BROKER_DEFAULT);
- testParameters.setPropertyIfNull(PingPongProducer.USERNAME_PROPNAME, PingPongProducer.USERNAME_DEFAULT);
- testParameters.setPropertyIfNull(PingPongProducer.PASSWORD_PROPNAME, PingPongProducer.PASSWORD_DEFAULT);
- testParameters.setPropertyIfNull(PingPongProducer.VIRTUAL_HOST_PROPNAME, PingPongProducer.VIRTUAL_HOST_DEFAULT);
- testParameters.setPropertyIfNull(PingPongProducer.VERBOSE_PROPNAME,
- Boolean.toString(PingPongProducer.VERBOSE_DEFAULT));
- testParameters.setPropertyIfNull(PingPongProducer.RATE_PROPNAME, Integer.toString(PingPongProducer.RATE_DEFAULT));
- testParameters.setPropertyIfNull(PingPongProducer.PUBSUB_PROPNAME,
- Boolean.toString(PingPongProducer.PUBSUB_DEFAULT));
- testParameters.setPropertyIfNull(PingPongProducer.TX_BATCH_SIZE_PROPNAME,
- Integer.toString(PingPongProducer.TX_BATCH_SIZE_DEFAULT));
- testParameters.setPropertyIfNull(PingPongProducer.TIMEOUT_PROPNAME, Long.toString(PingPongProducer.TIMEOUT_DEFAULT));
- testParameters.setPropertyIfNull(PingPongProducer.DESTINATION_COUNT_PROPNAME,
- Integer.toString(PingPongProducer.DESTINATION_COUNT_DEFAULT));
- testParameters.setPropertyIfNull(PingPongProducer.FAIL_AFTER_COMMIT_PROPNAME,
- PingPongProducer.FAIL_AFTER_COMMIT_DEFAULT);
- testParameters.setPropertyIfNull(PingPongProducer.FAIL_BEFORE_COMMIT_PROPNAME,
- PingPongProducer.FAIL_BEFORE_COMMIT_DEFAULT);
- testParameters.setPropertyIfNull(PingPongProducer.FAIL_AFTER_SEND_PROPNAME,
- PingPongProducer.FAIL_AFTER_SEND_DEFAULT);
- testParameters.setPropertyIfNull(PingPongProducer.FAIL_BEFORE_SEND_PROPNAME,
- PingPongProducer.FAIL_BEFORE_SEND_DEFAULT);
- testParameters.setPropertyIfNull(PingPongProducer.FAIL_ONCE_PROPNAME, PingPongProducer.FAIL_ONCE_DEFAULT);
- testParameters.setPropertyIfNull(PingPongProducer.UNIQUE_DESTS_PROPNAME,
- Boolean.toString(PingPongProducer.UNIQUE_DESTS_DEFAULT));
- testParameters.setPropertyIfNull(PingPongProducer.ACK_MODE_PROPNAME,
- Integer.toString(PingPongProducer.ACK_MODE_DEFAULT));
- testParameters.setPropertyIfNull(PingPongProducer.PAUSE_AFTER_BATCH_PROPNAME,
- PingPongProducer.PAUSE_AFTER_BATCH_DEFAULT);*/
- }
-
- /**
- * Compile all the tests into a test suite.
- */
- public static Test suite()
- {
- // Build a new test suite
- TestSuite suite = new TestSuite("Ping-Pong Performance Tests");
-
- // Run performance tests in read committed mode.
- suite.addTest(new PingPongTestPerf("testPingPongOk"));
-
- return suite;
- }
-
- private static void setSystemPropertyIfNull(String propName, String propValue)
- {
- if (System.getProperty(propName) == null)
- {
- System.setProperty(propName, propValue);
- }
- }
-
- public void testPingPongOk(int numPings) throws Exception
- {
- // Get the per thread test setup to run the test through.
- PerThreadSetup perThreadSetup = threadSetup.get();
-
- // Generate a sample message. This message is already time stamped and has its reply-to destination set.
- Message msg =
- perThreadSetup._testPingProducer.getTestMessage(perThreadSetup._testPingProducer.getReplyDestinations().get(0),
- testParameters.getPropertyAsInteger(PingPongProducer.MESSAGE_SIZE_PROPNAME),
- testParameters.getPropertyAsBoolean(PingPongProducer.PERSISTENT_MODE_PROPNAME));
-
- // Send the message and wait for a reply.
- int numReplies =
- perThreadSetup._testPingProducer.pingAndWaitForReply(msg, numPings, PingPongProducer.TIMEOUT_DEFAULT, null);
-
- // Fail the test if the timeout was exceeded.
- if (numReplies != numPings)
- {
- Assert.fail("The ping timed out, got " + numReplies + " out of " + numPings);
- }
- }
-
- /**
- * Performs test fixture creation on a per thread basis. This will only be called once for each test thread.
- */
- public void threadSetUp()
- {
- try
- {
- PerThreadSetup perThreadSetup = new PerThreadSetup();
-
- // Extract the test set up paramaeters.
- String brokerDetails = testParameters.getProperty(PingPongProducer.BROKER_PROPNAME);
- String username = testParameters.getProperty(PingPongProducer.USERNAME_PROPNAME);
- String password = testParameters.getProperty(PingPongProducer.PASSWORD_PROPNAME);
- String virtualPath = testParameters.getProperty(PingPongProducer.VIRTUAL_HOST_PROPNAME);
- String destinationName = testParameters.getProperty(PingPongProducer.PING_QUEUE_NAME_PROPNAME);
- boolean persistent = testParameters.getPropertyAsBoolean(PingPongProducer.PERSISTENT_MODE_PROPNAME);
- boolean transacted = testParameters.getPropertyAsBoolean(PingPongProducer.TRANSACTED_PROPNAME);
- String selector = testParameters.getProperty(PingPongProducer.SELECTOR_PROPNAME);
- boolean verbose = testParameters.getPropertyAsBoolean(PingPongProducer.VERBOSE_PROPNAME);
- boolean pubsub = testParameters.getPropertyAsBoolean(PingPongProducer.PUBSUB_PROPNAME);
-
- synchronized (this)
- {
- // Establish a bounce back client on the ping queue to bounce back the pings.
- perThreadSetup._testPingBouncer =
- new PingPongBouncer(brokerDetails, username, password, virtualPath, destinationName, persistent,
- transacted, selector, verbose, pubsub);
-
- // Start the connections for client and producer running.
- perThreadSetup._testPingBouncer.getConnection().start();
-
- // Establish a ping-pong client on the ping queue to send the pings and receive replies with.
- perThreadSetup._testPingProducer = new PingPongProducer(testParameters);
- perThreadSetup._testPingProducer.establishConnection(true, true);
- perThreadSetup._testPingProducer.start();
- }
-
- // Attach the per-thread set to the thread.
- threadSetup.set(perThreadSetup);
- }
- catch (Exception e)
- {
- _logger.warn("There was an exception during per thread setup.", e);
- }
- }
-
- /**
- * Performs test fixture clean
- */
- public void threadTearDown()
- {
- _logger.debug("public void threadTearDown(): called");
-
- try
- {
- // Get the per thread test fixture.
- PerThreadSetup perThreadSetup = threadSetup.get();
-
- // Close the pingers so that it cleans up its connection cleanly.
- synchronized (this)
- {
- perThreadSetup._testPingProducer.close();
- // perThreadSetup._testPingBouncer.close();
- }
-
- // Ensure the per thread fixture is reclaimed.
- threadSetup.remove();
- }
- catch (JMSException e)
- {
- _logger.warn("There was an exception during per thread tear down.");
- }
- }
-
- protected static class PerThreadSetup
- {
- /**
- * Holds the test ping-pong producer.
- */
- private PingPongProducer _testPingProducer;
-
- /**
- * Holds the test ping client.
- */
- private PingPongBouncer _testPingBouncer;
- }
-}
diff --git a/java/perftests/src/main/java/org/apache/qpid/test/testcases/MessageThroughputPerf.java b/java/perftests/src/main/java/org/apache/qpid/test/testcases/MessageThroughputPerf.java
deleted file mode 100644
index e2e97ab6f8..0000000000
--- a/java/perftests/src/main/java/org/apache/qpid/test/testcases/MessageThroughputPerf.java
+++ /dev/null
@@ -1,207 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.testcases;
-
-import junit.framework.Test;
-import junit.framework.TestSuite;
-
-import org.apache.log4j.Logger;
-import org.apache.log4j.NDC;
-
-import org.apache.qpid.test.framework.Assertion;
-import org.apache.qpid.test.framework.Circuit;
-import org.apache.qpid.test.framework.FrameworkBaseCase;
-import org.apache.qpid.test.framework.MessagingTestConfigProperties;
-import org.apache.qpid.test.framework.sequencers.CircuitFactory;
-
-import org.apache.qpid.junit.extensions.TestThreadAware;
-import org.apache.qpid.junit.extensions.TimingController;
-import org.apache.qpid.junit.extensions.TimingControllerAware;
-import org.apache.qpid.junit.extensions.util.ParsedProperties;
-import org.apache.qpid.junit.extensions.util.TestContextProperties;
-
-import java.util.LinkedList;
-
-/**
- * MessageThroughputPerf runs a test over a {@link Circuit} controlled by the test parameters. It logs timings of
- * the time required to receive samples consisting of batches of messages.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Measure message throughput accross a test circuit. <td> {@link Circuit}
- * </table>
- *
- * @todo Check that all of the messages were sent. Check that the receiving end got the same number of messages as
- * the publishing end.
- *
- * @todo Set this up to run with zero sized tests. Size zero means send forever. Continuous sending to be interrupted
- * by completion of the test duration, or shutdown hook when the user presses Ctrl-C.
- */
-public class MessageThroughputPerf extends FrameworkBaseCase implements TimingControllerAware, TestThreadAware
-{
- /** Used for debugging. */
- private static final Logger log = Logger.getLogger(MessageThroughputPerf.class);
-
- /** Holds the timing controller, used to log test timings from self-timed tests. */
- private TimingController timingController;
-
- /** Thread local to hold the per-thread test setup fields. */
- ThreadLocal<PerThreadSetup> threadSetup = new ThreadLocal<PerThreadSetup>();
-
- /**
- * Creates a new test case with the specified name.
- *
- * @param name The test case name.
- */
- public MessageThroughputPerf(String name)
- {
- super(name);
- }
-
- /**
- * Performs the a basic P2P test case.
- *
- * @param numMessages The number of messages to send in the test.
- */
- public void testThroughput(int numMessages)
- {
- log.debug("public void testThroughput(): called");
-
- PerThreadSetup setup = threadSetup.get();
- assertNoFailures(setup.testCircuit.test(numMessages, new LinkedList<Assertion>()));
- }
-
- /**
- * Should provide a translation from the junit method name of a test to its test case name as known to the test
- * clients that will run the test. The purpose of this is to convert the JUnit method name into the correct test
- * case name to place into the test invite. For example the method "testP2P" might map onto the interop test case
- * name "TC2_BasicP2P".
- *
- * @param methodName The name of the JUnit test method.
- *
- * @return The name of the corresponding interop test case.
- */
- public String getTestCaseNameForTestMethod(String methodName)
- {
- log.debug("public String getTestCaseNameForTestMethod(String methodName = " + methodName + "): called");
-
- return "DEFAULT_CIRCUIT_TEST";
- }
-
- /**
- * Used by test runners that can supply a {@link org.apache.qpid.junit.extensions.TimingController} to set the
- * controller on an aware test.
- *
- * @param controller The timing controller.
- */
- public void setTimingController(TimingController controller)
- {
- timingController = controller;
- }
-
- /**
- * Overrides the parent setUp method so that the in-vm broker creation is not done on a per test basis.
- *
- * @throws Exception Any exceptions allowed to fall through and fail the test.
- */
- protected void setUp() throws Exception
- {
- NDC.push(getName());
-
- setTestProps(TestContextProperties.getInstance(MessagingTestConfigProperties.defaults));
- }
-
- /**
- * Overrides the parent setUp method so that the in-vm broker clean-up is not done on a per test basis.
- */
- protected void tearDown()
- {
- NDC.pop();
- }
-
- /**
- * Performs test fixture creation on a per thread basis. This will only be called once for each test thread.
- */
- public void threadSetUp()
- {
- // Run the test setup tasks. This may create an in-vm broker, if a decorator has injected a task for this.
- getTaskHandler().runSetupTasks();
-
- // Get the test parameters, any overrides on the command line will have been applied.
- ParsedProperties testProps = TestContextProperties.getInstance(MessagingTestConfigProperties.defaults);
-
- // Customize the test parameters.
- testProps.setProperty("TEST_NAME", "DEFAULT_CIRCUIT_TEST");
- testProps.setProperty(MessagingTestConfigProperties.SEND_DESTINATION_NAME_ROOT_PROPNAME, "testqueue");
-
- // Get the test circuit factory to create test circuits and run the standard test procedure through.
- CircuitFactory circuitFactory = getCircuitFactory();
-
- // Create the test circuit. This projects the circuit onto the available test nodes and connects it up.
- Circuit testCircuit = circuitFactory.createCircuit(null, testProps);
-
- // Store the test configuration for the thread.
- PerThreadSetup setup = new PerThreadSetup();
- setup.testCircuit = testCircuit;
- threadSetup.set(setup);
- }
-
- /**
- * Called after all threads have completed their setup.
- */
- public void postThreadSetUp()
- {
- //Nothing to do here, potentially implement preFill as per PingTestPerf.
- }
-
- /**
- * Called when a test thread is destroyed.
- */
- public void threadTearDown()
- {
- // Run the test teardown tasks. This may destroy the in-vm broker, if a decorator has injected a task for this.
- getTaskHandler().runSetupTasks();
- }
-
- /**
- * Holds the per-thread test configurations.
- */
- protected static class PerThreadSetup
- {
- /** Holds the test circuit to run tests on. */
- Circuit testCircuit;
- }
-
- /**
- * Compiles all the tests in this class into a suite.
- *
- * @return The test suite.
- */
- public static Test suite()
- {
- // Build a new test suite
- TestSuite suite = new TestSuite("Qpid Throughput Performance Tests");
-
- suite.addTest(new MessageThroughputPerf("testThroughput"));
-
- return suite;
- }
-}
diff --git a/java/perftests/src/main/java/org/apache/qpid/topic/Config.java b/java/perftests/src/main/java/org/apache/qpid/topic/Config.java
deleted file mode 100644
index d5c0979399..0000000000
--- a/java/perftests/src/main/java/org/apache/qpid/topic/Config.java
+++ /dev/null
@@ -1,326 +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.topic;
-
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.config.ConnectorConfig;
-import org.apache.qpid.config.Connector;
-import org.apache.qpid.config.AbstractConfig;
-
-import javax.jms.Connection;
-
-public class Config extends AbstractConfig implements ConnectorConfig
-{
-
- private String host = "localhost";
- private int port = 5672;
- private String factory = null;
-
- private int payload = 256;
- private int messages = 1000;
- private int clients = 1;
- private int batch = 1;
- private long delay = 1;
- private int warmup;
- private int ackMode= AMQSession.NO_ACKNOWLEDGE;
- private String clientId;
- private String subscriptionId;
- private String selector;
- private String destinationName;
- private boolean persistent;
- private boolean transacted;
- private int destinationsCount;
- private int batchSize;
- private int rate;
- private boolean ispubsub;
- private long timeout;
-
- public Config()
- {
- }
-
- public int getAckMode()
- {
- return ackMode;
- }
-
- public void setPayload(int payload)
- {
- this.payload = payload;
- }
-
- public int getPayload()
- {
- return payload;
- }
-
- void setClients(int clients)
- {
- this.clients = clients;
- }
-
- int getClients()
- {
- return clients;
- }
-
- void setMessages(int messages)
- {
- this.messages = messages;
- }
-
- public int getMessages()
- {
- return messages;
- }
-
- public int getBatchSize()
- {
- return batchSize;
- }
-
- public int getRate()
- {
- return rate;
- }
-
- public int getDestinationsCount()
- {
- return destinationsCount;
- }
-
- public String getHost()
- {
- return host;
- }
-
- public void setHost(String host)
- {
- this.host = host;
- }
-
- public int getPort()
- {
- return port;
- }
-
- public String getFactory()
- {
- return factory;
- }
-
- public void setPort(int port)
- {
- this.port = port;
- }
-
- int getBatch()
- {
- return batch;
- }
-
- void setBatch(int batch)
- {
- this.batch = batch;
- }
-
- int getWarmup()
- {
- return warmup;
- }
-
- void setWarmup(int warmup)
- {
- this.warmup = warmup;
- }
-
- public long getDelay()
- {
- return delay;
- }
-
- public void setDelay(long delay)
- {
- this.delay = delay;
- }
-
- public long getTimeout()
- {
- return timeout;
- }
-
- public void setTimeout(long time)
- {
- this.timeout = time;
- }
-
- public String getClientId()
- {
- return clientId;
- }
-
- public String getSubscriptionId()
- {
- return subscriptionId;
- }
-
- public String getSelector()
- {
- return selector;
- }
-
- public String getDestination()
- {
- return destinationName;
- }
-
- public boolean usePersistentMessages()
- {
- return persistent;
- }
-
- public boolean isTransacted()
- {
- return transacted;
- }
-
- public boolean isPubSub()
- {
- return ispubsub;
- }
-
- public void setOption(String key, String value)
- {
- if("-host".equalsIgnoreCase(key))
- {
- setHost(value);
- }
- else if("-port".equalsIgnoreCase(key))
- {
- try
- {
- setPort(Integer.parseInt(value));
- }
- catch(NumberFormatException e)
- {
- throw new RuntimeException("Bad port number: " + value, e);
- }
- }
- else if("-payload".equalsIgnoreCase(key))
- {
- setPayload(parseInt("Bad payload size", value));
- }
- else if("-messages".equalsIgnoreCase(key))
- {
- setMessages(parseInt("Bad message count", value));
- }
- else if("-clients".equalsIgnoreCase(key))
- {
- setClients(parseInt("Bad client count", value));
- }
- else if("-batch".equalsIgnoreCase(key))
- {
- setBatch(parseInt("Bad batch count", value));
- }
- else if("-delay".equalsIgnoreCase(key))
- {
- setDelay(parseLong("Bad batch delay", value));
- }
- else if("-warmup".equalsIgnoreCase(key))
- {
- setWarmup(parseInt("Bad warmup count", value));
- }
- else if("-ack".equalsIgnoreCase(key))
- {
- ackMode = parseInt("Bad ack mode", value);
- }
- else if("-factory".equalsIgnoreCase(key))
- {
- factory = value;
- }
- else if("-clientId".equalsIgnoreCase(key))
- {
- clientId = value;
- }
- else if("-subscriptionId".equalsIgnoreCase(key))
- {
- subscriptionId = value;
- }
- else if("-persistent".equalsIgnoreCase(key))
- {
- persistent = "true".equalsIgnoreCase(value);
- }
- else if("-transacted".equalsIgnoreCase(key))
- {
- transacted = "true".equalsIgnoreCase(value);
- }
- else if ("-destinationscount".equalsIgnoreCase(key))
- {
- destinationsCount = parseInt("Bad destinations count", value);
- }
- else if ("-batchsize".equalsIgnoreCase(key))
- {
- batchSize = parseInt("Bad batch size", value);
- }
- else if ("-rate".equalsIgnoreCase(key))
- {
- rate = parseInt("MEssage rate", value);
- }
- else if("-pubsub".equalsIgnoreCase(key))
- {
- ispubsub = "true".equalsIgnoreCase(value);
- }
- else if("-selector".equalsIgnoreCase(key))
- {
- selector = value;
- }
- else if("-destinationname".equalsIgnoreCase(key))
- {
- destinationName = value;
- }
- else if("-timeout".equalsIgnoreCase(key))
- {
- setTimeout(parseLong("Bad timeout data", value));
- }
- else
- {
- System.out.println("Ignoring unrecognised option: " + key);
- }
- }
-
- static String getAckModeDescription(int ackMode)
- {
- switch(ackMode)
- {
- case AMQSession.NO_ACKNOWLEDGE: return "NO_ACKNOWLEDGE";
- case AMQSession.AUTO_ACKNOWLEDGE: return "AUTO_ACKNOWLEDGE";
- case AMQSession.CLIENT_ACKNOWLEDGE: return "CLIENT_ACKNOWLEDGE";
- case AMQSession.DUPS_OK_ACKNOWLEDGE: return "DUPS_OK_ACKNOWELDGE";
- case AMQSession.PRE_ACKNOWLEDGE: return "PRE_ACKNOWLEDGE";
- }
- return "AckMode=" + ackMode;
- }
-
- public Connection createConnection() throws Exception
- {
- return new Connector().createConnection(this);
- }
-}
diff --git a/java/perftests/src/main/java/org/apache/qpid/topic/Listener.java b/java/perftests/src/main/java/org/apache/qpid/topic/Listener.java
deleted file mode 100644
index 6dcea42bfe..0000000000
--- a/java/perftests/src/main/java/org/apache/qpid/topic/Listener.java
+++ /dev/null
@@ -1,303 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.topic;
-
-import java.util.Random;
-
-import javax.jms.*;
-
-import org.apache.log4j.Logger;
-import org.apache.log4j.NDC;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.client.AMQTopic;
-import org.apache.qpid.exchange.ExchangeDefaults;
-
-/**
- * This class has not kept up to date with the topic_listener in the cpp tests. It should provide identical behaviour for
- * cross testing the java and cpp clients.
- *
- * <p/>How the cpp topic_publisher operates:
- * It publishes text messages to the default topic exchange, on virtual host "/test", on the topic "topic_control", for
- * the specified number of test messages to be sent.
- * It publishes a report request message (on same topic), with the header text field "TYPE", value "REPORT_REQUEST",
- * optionally within a transaction, and waits for the specified number of consumers to reply to this request. The
- * listeners should reply to this message on a queue named "response", on virtual host "/test", with some sort of message
- * about the number of messages received and how long it took, although the publisher never looks at the message content.
- * The publisher then send a message (on the same topic), with the header text field "TYPE", value "TERMINATION_REQUEST",
- * which the listener should close its connection and terminate upon receipt of.
- *
- * @todo I've added lots of field table types in the report message, just to check if the other end can decode them
- * correctly. Not really the right place to test this, so remove them from
- * {@link #createReportResponseMessage(String)} once a better test exists.
- */
-public class Listener implements MessageListener
-{
- private static Logger log = Logger.getLogger(Listener.class);
-
- public static final String CONTROL_TOPIC = "topic_control";
- public static final String RESPONSE_QUEUE = "response";
-
- private final Topic _topic;
- //private final Topic _control;
-
- private final Queue _response;
-
- /** Holds the connection to listen on. */
- private final Connection _connection;
-
- /** Holds the producer to send control messages on. */
- private final MessageProducer _controller;
-
- /** Holds the JMS session. */
- private final javax.jms.Session _session;
-
- /** Holds a flag to indicate that a timer has begun on the first message. Reset when report is sent. */
- private boolean init;
-
- /** Holds the count of messages received by this listener. */
- private int count;
-
- /** Used to hold the start time of the first message. */
- private long start;
- private static String clientId;
-
- Listener(Connection connection, int ackMode, String name) throws Exception
- {
- log.debug("Listener(Connection connection = " + connection + ", int ackMode = " + ackMode + ", String name = " + name
- + "): called");
-
- _connection = connection;
- _session = connection.createSession(false, ackMode);
-
- if (_session instanceof AMQSession)
- {
- _topic = new AMQTopic(ExchangeDefaults.TOPIC_EXCHANGE_NAME, CONTROL_TOPIC);
- //_control = new AMQTopic(CONTROL_TOPIC);
- _response = new AMQQueue(ExchangeDefaults.DIRECT_EXCHANGE_NAME, RESPONSE_QUEUE);
- }
- else
- {
- _topic = _session.createTopic(CONTROL_TOPIC);
- //_control = _session.createTopic(CONTROL_TOPIC);
- _response = _session.createQueue(RESPONSE_QUEUE);
- }
-
- //register for events
- if (name == null)
- {
- log.debug("Calling _factory.createTopicConsumer().setMessageListener(this)");
- createTopicConsumer().setMessageListener(this);
- }
- else
- {
- log.debug("Calling createDurableTopicConsumer(name).setMessageListener(this)");
- createDurableTopicConsumer(name).setMessageListener(this);
- }
-
- _connection.start();
-
- _controller = createControlPublisher();
- System.out.println("Waiting for messages " + Config.getAckModeDescription(ackMode)
- +
- ((name == null)
- ? "" : (" (subscribed with name " + name + " and client id " + connection.getClientID() + ")"))
- + "...");
- }
-
- public static void main(String[] argv) throws Exception
- {
- clientId = "Listener-" + System.currentTimeMillis();
-
- NDC.push(clientId);
-
- Config config = new Config();
- config.setOptions(argv);
-
- //Connection con = config.createConnection();
- Connection con =
- new AMQConnection("amqp://guest:guest@testid/test?brokerlist='" + config.getHost() + ":" + config.getPort()
- + "'");
-
- if (config.getClientId() != null)
- {
- con.setClientID(config.getClientId());
- }
-
- new Listener(con, config.getAckMode(), config.getSubscriptionId());
-
- NDC.pop();
- NDC.remove();
- }
-
- /**
- * Checks whether or not a text field on a message has the specified value.
- *
- * @param m The message to check.
- * @param fieldName The name of the field to check.
- * @param value The expected value of the field to compare with.
- *
- * @return <tt>true</tt>If the specified field has the specified value, <tt>fals</tt> otherwise.
- *
- * @throws JMSException Any JMSExceptions are allowed to fall through.
- */
- private static boolean checkTextField(Message m, String fieldName, String value) throws JMSException
- {
- log.debug("private static boolean checkTextField(Message m = " + m + ", String fieldName = " + fieldName
- + ", String value = " + value + "): called");
-
- String comp = m.getStringProperty(fieldName);
- log.debug("comp = " + comp);
-
- boolean result = (comp != null) && comp.equals(value);
- log.debug("result = " + result);
-
- return result;
- }
-
- public void onMessage(Message message)
- {
- NDC.push(clientId);
-
- log.debug("public void onMessage(Message message = " + message + "): called");
-
- if (!init)
- {
- start = System.nanoTime() / 1000000;
- count = 0;
- init = true;
- }
-
- try
- {
- if (isShutdown(message))
- {
- log.debug("Got a shutdown message.");
- shutdown();
- }
- else if (isReport(message))
- {
- log.debug("Got a report request message.");
-
- // Send the report.
- report();
- init = false;
- }
- }
- catch (JMSException e)
- {
- log.warn("There was a JMSException during onMessage.", e);
- }
- finally
- {
- NDC.pop();
- }
- }
-
- Message createReportResponseMessage(String msg) throws JMSException
- {
- Message message = _session.createTextMessage(msg);
-
- // Shove some more field table type in the message just to see if the other end can handle it.
- message.setBooleanProperty("BOOLEAN", true);
- message.setByteProperty("BYTE", (byte) 5);
- message.setDoubleProperty("DOUBLE", Math.PI);
- message.setFloatProperty("FLOAT", 1.0f);
- message.setIntProperty("INT", 1);
- message.setShortProperty("SHORT", (short) 1);
- message.setLongProperty("LONG", (long) 1827361278);
- message.setStringProperty("STRING", "hello");
-
- return message;
- }
-
- boolean isShutdown(Message m) throws JMSException
- {
- boolean result = checkTextField(m, "TYPE", "TERMINATION_REQUEST");
-
- //log.debug("isShutdown = " + result);
-
- return result;
- }
-
- boolean isReport(Message m) throws JMSException
- {
- boolean result = checkTextField(m, "TYPE", "REPORT_REQUEST");
-
- //log.debug("isReport = " + result);
-
- return result;
- }
-
- MessageConsumer createTopicConsumer() throws Exception
- {
- return _session.createConsumer(_topic);
- }
-
- MessageConsumer createDurableTopicConsumer(String name) throws Exception
- {
- return _session.createDurableSubscriber(_topic, name);
- }
-
- MessageProducer createControlPublisher() throws Exception
- {
- return _session.createProducer(_response);
- }
-
- private void shutdown()
- {
- try
- {
- _session.close();
- _connection.stop();
- _connection.close();
- }
- catch (Exception e)
- {
- e.printStackTrace(System.out);
- }
- }
-
- private void report()
- {
- log.debug("private void report(): called");
-
- try
- {
- String msg = getReport();
- _controller.send(createReportResponseMessage(msg));
- log.debug("Sent report: " + msg);
- }
- catch (Exception e)
- {
- e.printStackTrace(System.out);
- }
- }
-
- private String getReport()
- {
- long time = ((System.nanoTime() / 1000000) - start);
-
- return "Received " + count + " in " + time + "ms";
- }
-}
diff --git a/java/perftests/src/main/java/org/apache/qpid/topic/MessageFactory.java b/java/perftests/src/main/java/org/apache/qpid/topic/MessageFactory.java
deleted file mode 100644
index 4efdc1cb56..0000000000
--- a/java/perftests/src/main/java/org/apache/qpid/topic/MessageFactory.java
+++ /dev/null
@@ -1,157 +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.topic;
-
-import javax.jms.*;
-
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.client.AMQTopic;
-import org.apache.qpid.exchange.ExchangeDefaults;
-
-/**
- */
-class MessageFactory
-{
- private static final char[] DATA = "abcdefghijklmnopqrstuvwxyz".toCharArray();
-
- private final Session _session;
- private final Topic _topic;
- private final Topic _control;
- private final byte[] _payload;
-
- MessageFactory(Session session) throws JMSException
- {
- this(session, 256);
- }
-
- MessageFactory(Session session, int size) throws JMSException
- {
- _session = session;
- if (session instanceof AMQSession)
- {
- _topic = new AMQTopic(ExchangeDefaults.TOPIC_EXCHANGE_NAME, "topic_control");
- _control = new AMQTopic(ExchangeDefaults.TOPIC_EXCHANGE_NAME, "topictest.control");
- }
- else
- {
- _topic = session.createTopic("topic_control");
- _control = session.createTopic("topictest.control");
- }
-
- _payload = new byte[size];
-
- for (int i = 0; i < size; i++)
- {
- _payload[i] = (byte) DATA[i % DATA.length];
- }
- }
-
- private static boolean checkText(Message m, String s)
- {
- try
- {
- return (m instanceof TextMessage) && ((TextMessage) m).getText().equals(s);
- }
- catch (JMSException e)
- {
- e.printStackTrace(System.out);
-
- return false;
- }
- }
-
- Topic getTopic()
- {
- return _topic;
- }
-
- Message createEventMessage() throws JMSException
- {
- BytesMessage msg = _session.createBytesMessage();
- msg.writeBytes(_payload);
-
- return msg;
- }
-
- Message createShutdownMessage() throws JMSException
- {
- return _session.createTextMessage("SHUTDOWN");
- }
-
- Message createReportRequestMessage() throws JMSException
- {
- return _session.createTextMessage("REPORT");
- }
-
- Message createReportResponseMessage(String msg) throws JMSException
- {
- return _session.createTextMessage(msg);
- }
-
- boolean isShutdown(Message m)
- {
- return checkText(m, "SHUTDOWN");
- }
-
- boolean isReport(Message m)
- {
- return checkText(m, "REPORT");
- }
-
- Object getReport(Message m)
- {
- try
- {
- return ((TextMessage) m).getText();
- }
- catch (JMSException e)
- {
- e.printStackTrace(System.out);
-
- return e.toString();
- }
- }
-
- MessageConsumer createTopicConsumer() throws Exception
- {
- return _session.createConsumer(_topic);
- }
-
- MessageConsumer createDurableTopicConsumer(String name) throws Exception
- {
- return _session.createDurableSubscriber(_topic, name);
- }
-
- MessageConsumer createControlConsumer() throws Exception
- {
- return _session.createConsumer(_control);
- }
-
- MessageProducer createTopicPublisher() throws Exception
- {
- return _session.createProducer(_topic);
- }
-
- MessageProducer createControlPublisher() throws Exception
- {
- return _session.createProducer(_control);
- }
-}
diff --git a/java/perftests/src/main/java/org/apache/qpid/topic/Publisher.java b/java/perftests/src/main/java/org/apache/qpid/topic/Publisher.java
deleted file mode 100644
index c3b19b558a..0000000000
--- a/java/perftests/src/main/java/org/apache/qpid/topic/Publisher.java
+++ /dev/null
@@ -1,186 +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.topic;
-
-import javax.jms.*;
-
-public class Publisher implements MessageListener
-{
- private final Object _lock = new Object();
- private final Connection _connection;
- private final Session _session;
- private final MessageFactory _factory;
- private final MessageProducer _publisher;
- private int _count;
-
- Publisher(Connection connection, int size, int ackMode, boolean persistent) throws Exception
- {
- _connection = connection;
- _session = _connection.createSession(false, ackMode);
- _factory = new MessageFactory(_session, size);
- _publisher = _factory.createTopicPublisher();
- _publisher.setDeliveryMode(persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT);
- System.out.println("Publishing " + (persistent ? "persistent" : "non-persistent") + " messages of " + size + " bytes, " + Config.getAckModeDescription(ackMode) + ".");
- }
-
- private void test(Config config) throws Exception
- {
- test(config.getBatch(), config.getDelay(), config.getMessages(), config.getClients(), config.getWarmup());
- }
-
- private void test(int batches, long delay, int msgCount, int consumerCount, int warmup) throws Exception
- {
- _factory.createControlConsumer().setMessageListener(this);
- _connection.start();
-
- if (warmup > 0)
- {
- System.out.println("Runing warmup (" + warmup + " msgs)");
- long time = batch(warmup, consumerCount);
- System.out.println("Warmup completed in " + time + "ms");
- }
-
- long[] times = new long[batches];
- for (int i = 0; i < batches; i++)
- {
- if (i > 0)
- {
- Thread.sleep(delay * 1000);
- }
- times[i] = batch(msgCount, consumerCount);
- System.out.println("Batch " + (i + 1) + " of " + batches + " completed in " + times[i] + " ms.");
- }
-
- long min = min(times);
- long max = max(times);
- System.out.println("min: " + min + ", max: " + max + " avg: " + avg(times, min, max));
-
- //request shutdown
- _publisher.send(_factory.createShutdownMessage());
-
- _connection.stop();
- _connection.close();
- }
-
- private long batch(int msgCount, int consumerCount) throws Exception
- {
- _count = consumerCount;
- long start = System.currentTimeMillis();
- publish(msgCount);
- waitForCompletion(consumerCount);
- return System.currentTimeMillis() - start;
- }
-
- private void publish(int count) throws Exception
- {
-
- //send events
- for (int i = 0; i < count; i++)
- {
- _publisher.send(_factory.createEventMessage());
- if ((i + 1) % 100 == 0)
- {
- System.out.println("Sent " + (i + 1) + " messages");
- }
- }
-
- //request report
- _publisher.send(_factory.createReportRequestMessage());
- }
-
- private void waitForCompletion(int consumers) throws Exception
- {
- System.out.println("Waiting for completion...");
- synchronized (_lock)
- {
- while (_count > 0)
- {
- _lock.wait();
- }
- }
- }
-
-
- public void onMessage(Message message)
- {
- System.out.println("Received report " + _factory.getReport(message) + " " + --_count + " remaining");
- if (_count == 0)
- {
- synchronized (_lock)
- {
- _lock.notify();
- }
- }
- }
-
- static long min(long[] times)
- {
- long min = times.length > 0 ? times[0] : 0;
- for (int i = 0; i < times.length; i++)
- {
- min = Math.min(min, times[i]);
- }
- return min;
- }
-
- static long max(long[] times)
- {
- long max = times.length > 0 ? times[0] : 0;
- for (int i = 0; i < times.length; i++)
- {
- max = Math.max(max, times[i]);
- }
- return max;
- }
-
- static long avg(long[] times, long min, long max)
- {
- long sum = 0;
- for (int i = 0; i < times.length; i++)
- {
- sum += times[i];
- }
-
- int adjustment = 0;
-
- // Remove min and max if we have run enough batches.
- if (times.length > 2)
- {
- sum -= min;
- sum -= max;
- adjustment = 2;
- }
-
- return (sum / (times.length - adjustment));
- }
-
- public static void main(String[] argv) throws Exception
- {
- Config config = new Config();
- config.setOptions(argv);
-
- Connection con = config.createConnection();
- int size = config.getPayload();
- int ackMode = config.getAckMode();
- boolean persistent = config.usePersistentMessages();
- new Publisher(con, size, ackMode, persistent).test(config);
- }
-}
diff --git a/java/perftests/src/main/java/org/apache/qpid/topic/TopicWithSelectorsTransientVolumeTest.java b/java/perftests/src/main/java/org/apache/qpid/topic/TopicWithSelectorsTransientVolumeTest.java
deleted file mode 100644
index e0c0b00335..0000000000
--- a/java/perftests/src/main/java/org/apache/qpid/topic/TopicWithSelectorsTransientVolumeTest.java
+++ /dev/null
@@ -1,344 +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.topic;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-
-import javax.jms.BytesMessage;
-import javax.jms.DeliveryMode;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.Session;
-import javax.jms.Topic;
-import javax.jms.TopicConnection;
-import javax.jms.TopicPublisher;
-import javax.jms.TopicSession;
-import javax.jms.TopicSubscriber;
-import javax.naming.NamingException;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.client.AMQTopic;
-import org.apache.qpid.exchange.ExchangeDefaults;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-public class TopicWithSelectorsTransientVolumeTest extends QpidBrokerTestCase
-{
- private static final int NUM_MSG_PER_ITERATION = 50;//must be a multiple of 10
- private static final int NUM_ITERATIONS = 1000;
-
- private static final int NUM_CONSUMERS = 50;
- private static final int MSG_SIZE = 1024;
- private static final byte[] BYTE_ARRAY = new byte[MSG_SIZE];
-
- ArrayList<MyMessageSubscriber> _subscribers = new ArrayList<MyMessageSubscriber>();
- HashMap<String,Long> _queueMsgCounts = new HashMap<String,Long>();
-
- private final static Object _lock=new Object();
- private boolean _producerFailed;
- private static int _finishedCount;
- private static int _failedCount;
-
- protected void setUp() throws Exception
- {
- super.setUp();
- init();
- }
-
- protected void tearDown() throws Exception
- {
- super.tearDown();
- }
-
- private void init()
- {
- _finishedCount = 0;
- _failedCount = 0;
- _producerFailed = false;
- _subscribers.clear();
- _queueMsgCounts.clear();
- }
-
-
- private Message createMessage(Session session) throws JMSException
- {
- BytesMessage message = session.createBytesMessage();
- message.writeBytes(BYTE_ARRAY);
-
- return message;
- }
-
- /**
- * 1 Topic with 50 subscribers using a selector, and 1 producer sending 50,000 1K messages with 90% selector success ratio.
- */
- public void test50SubscribersWith90PercentMatched() throws Exception
- {
- Topic topic = new AMQTopic(ExchangeDefaults.TOPIC_EXCHANGE_NAME, "test50ConsumersWith10PercentUnmatched");
-
- System.out.println("Creating consumers");
-
- MyMessageSubscriber sub;
-
- for(int i=1; i <= NUM_CONSUMERS; i++)
- {
- sub = new MyMessageSubscriber(topic, "consumer" + i, ((9 * NUM_MSG_PER_ITERATION * NUM_ITERATIONS) / 10));
- _subscribers.add(sub);
- }
-
- System.out.println("Starting consumers");
- for(MyMessageSubscriber s: _subscribers)
- {
- Thread consumer = new Thread(s);
- consumer.start();
- }
-
- System.out.println("Creating producer");
- MyMessageProducer prod = new MyMessageProducer(topic);
-
- long startTime = System.currentTimeMillis();
-
- System.out.println("Starting producer");
- Thread producer = new Thread(prod);
- producer.start();
-
-
- // Wait for all the messageConsumers to have finished or failed
- synchronized (_lock)
- {
- while (_finishedCount + _failedCount < NUM_CONSUMERS)
- {
- try
- {
- _lock.wait();
- }
- catch (InterruptedException e)
- {
- //ignore
- }
- }
- }
-
- long endTime = System.currentTimeMillis();
- System.out.println("Elapsed time for messaging: " + (endTime-startTime) + "ms");
-
- assertFalse("Producer failed to send all messages", _producerFailed);
-
- //check if all messages received by consumers, or if there were failures
- if (_finishedCount != NUM_CONSUMERS)
- {
- fail(_failedCount + " consumers did not recieve all their expected messages");
- }
-
- //check if all queue depths were 0
- for(String consumer: _queueMsgCounts.keySet())
- {
- long depth = _queueMsgCounts.get(consumer);
- assertEquals(consumer + " subscription queue msg count was not 0", 0, depth);
- }
-
- }
-
- private class MyMessageProducer implements Runnable
- {
- private TopicConnection _connection;
- private TopicSession _session;
- private TopicPublisher _messagePublisher;
-
- public MyMessageProducer(Topic topic) throws JMSException, NamingException
- {
- _connection = (TopicConnection) getConnection();
- _session = (TopicSession) _connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- _messagePublisher = _session.createPublisher(topic);
- }
-
- public void run()
- {
- try
- {
- for(int iter = 0; iter < NUM_ITERATIONS; iter++)
- {
- int i = 0;
-
- //send 90% matching messages
- for (; i < (9 * NUM_MSG_PER_ITERATION)/10; i++)
- {
- Message message = createMessage(_session);
- message.setStringProperty("testprop", "true");
-
- _messagePublisher.publish(message, DeliveryMode.NON_PERSISTENT,
- Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE);
-
- Thread.yield();
- }
-
- //send remaining 10% non-matching messages
- for (; i < NUM_MSG_PER_ITERATION; i++)
- {
- Message message = _session.createMessage();
- message.setStringProperty("testprop", "false");
-
- _messagePublisher.publish(message, DeliveryMode.NON_PERSISTENT,
- Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE);
-
- Thread.yield();
- }
- }
-
- }
- catch (Exception exp)
- {
- System.out.println("producer: caught an exception, probably exiting before all messages sent");
- exp.printStackTrace();
- synchronized (_lock)
- {
- _producerFailed=true;
- _lock.notifyAll();
- }
- }
- }
- }
-
-
- private class MyMessageSubscriber implements Runnable
- {
- /* The topic this subscriber is subscribing to */
- private Topic _topic;
- private String _consumerName;
- private int _outstandingMsgCount;
- private TopicConnection _connection;
- private TopicSession _session;
- private TopicSubscriber _durSub;
-
- public MyMessageSubscriber(Topic topic, String consumerName, int messageCount) throws JMSException, NamingException
- {
- _outstandingMsgCount = messageCount;
- _topic=topic;
- _consumerName = consumerName;
- _connection = (TopicConnection) getConnection();
- _session = (TopicSession) _connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- _durSub = _session.createDurableSubscriber(_topic, _consumerName,"testprop='true'", false);
- _connection.start();
- }
-
- public void run()
- {
-
- boolean failed = false;
- do
- {
- Message m = null;
- try
- {
- m = _durSub.receive(10000);
- }
- catch (JMSException exp)
- {
- System.out.println(_consumerName + ": caught an exception handling a received message");
- exp.printStackTrace();
-
- failed = true;
- break;
- }
-
- Thread.yield();
-
- _outstandingMsgCount--;
-
- if(_outstandingMsgCount % 500 == 0)
- {
- System.out.println(_consumerName + ": outstanding message count: " + _outstandingMsgCount);
- }
-
- if(m == null)
- {
- if(_outstandingMsgCount != 0)
- {
- failed = true;
- }
- break;
- }
- }
- while(_outstandingMsgCount > 0);
-
- System.out.println(_consumerName + ": outstanding message count: " + _outstandingMsgCount);
-
- try
- {
- AMQQueue subcriptionQueue = new AMQQueue(ExchangeDefaults.TOPIC_EXCHANGE_NAME,"clientid" + ":" + _consumerName);
-
- ((AMQSession)_session).sync();
- Long depth = ((AMQSession)_session).getQueueDepth(subcriptionQueue);
- _queueMsgCounts.put(_consumerName, depth);
-
- System.out.println(_consumerName + ": completion queue msg count: " + depth);
- }
- catch (AMQException exp)
- {
- System.out.println(_consumerName + ": caught an exception determining completion queue depth");
- exp.printStackTrace();
- }
- finally
- {
- try
- {
- _session.unsubscribe(_consumerName);
- }
- catch (JMSException e)
- {
- System.out.println(_consumerName + ": caught an exception whilst unsubscribing");
- e.printStackTrace();
- }
- }
-
- synchronized (_lock)
- {
- if (_outstandingMsgCount == 0 && !failed)
- {
- _finishedCount++;
- System.out.println(_consumerName + ": finished");
- }
- else
- {
- _failedCount++;
- System.out.println(_consumerName + ": failed");
- }
- _lock.notifyAll();
- }
-
- }
- }
-
- //helper method to allow easily running against an external standalone broker
-// public static void main(String[] args) throws Exception
-// {
-// System.setProperty("broker.config", "/dev/null");
-// System.setProperty("broker", "external");
-// System.setProperty("java.naming.factory.initial", "org.apache.qpid.jndi.PropertiesFileInitialContextFactory");
-// System.setProperty("java.naming.provider.url", "test-profiles/test-provider.properties");
-//
-// TopicWithSelectorsTransientVolumeTest test = new TopicWithSelectorsTransientVolumeTest();
-// test.init();
-// test.test50SubscribersWith90PercentMatched();
-// test.tearDown();
-// }
-}
diff --git a/java/perftests/src/main/java/org/apache/qpid/topic/topicselectors.properties b/java/perftests/src/main/java/org/apache/qpid/topic/topicselectors.properties
deleted file mode 100644
index 1f572af58a..0000000000
--- a/java/perftests/src/main/java/org/apache/qpid/topic/topicselectors.properties
+++ /dev/null
@@ -1,24 +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.
-#
-java.naming.factory.initial = org.apache.qpid.jndi.PropertiesFileInitialContextFactory
-
-
-# register some connection factories
-# connectionfactory.[jndiname] = [ConnectionURL]
-connectionfactory.default = amqp://guest:guest@clientid/test?brokerlist='tcp://localhost:5672' \ No newline at end of file
diff --git a/java/release-docs/RELEASE_NOTES.txt b/java/release-docs/RELEASE_NOTES.txt
deleted file mode 100644
index f94c45fd4d..0000000000
--- a/java/release-docs/RELEASE_NOTES.txt
+++ /dev/null
@@ -1,21 +0,0 @@
-Apache Qpid Java 0.8 Release Notes
--------------------------------------------
-
-The Qpid 0.8 release contains support for AMQP 0-8, 0-9 and 0-10. You
-can access the specifications from
-
-http://www.amqp.org/confluence/display/AMQP/AMQP+Specification
-
-For full details of Apache Qpid's capabilities see our detailed
-project documentation at:
-
-http://cwiki.apache.org/confluence/display/qpid/Qpid+Java+Documentation
-
-From the link above you can access our Getting Started Guide, FAQ, Build How To
-and detailed developer documentation.
-
-Known Issues/Outstanding Work
------------------------------
-
-You can view the outstanding task list for Qpid by visiting our JIRA:
-http://issues.apache.org/jira/browse/QPID
diff --git a/java/resources/LICENSE b/java/resources/LICENSE
deleted file mode 100644
index 12d0eecaf2..0000000000
--- a/java/resources/LICENSE
+++ /dev/null
@@ -1,826 +0,0 @@
-=========================================================================
-== Apache License ==
-=========================================================================
-
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, "submitted"
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as "Not a Contribution."
-
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
- END OF TERMS AND CONDITIONS
-
- APPENDIX: How to apply the Apache License to your work.
-
- To apply the Apache License to your work, attach the following
- boilerplate notice, with the fields enclosed by brackets "[]"
- replaced with your own identifying information. (Don't include
- the brackets!) The text should be enclosed in the appropriate
- comment syntax for the file format. We also recommend that a
- file or class name and description of purpose be included on the
- same "printed page" as the copyright notice for easier
- identification within third-party archives.
-
- Copyright [yyyy] [name of copyright owner]
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-
-
-=========================================================================
-== SL4Fj (MIT) License ==
-=========================================================================
-
-SLF4J source code and binaries are distributed under the following license.
-Copyright (c) 2004-2005 SLF4J.ORG
-Copyright (c) 2004-2005 QOS.ch
-
-All rights reserved.
-
-Permission is hereby granted, free of charge, to any person obtaining
-a copy of this software and associated documentation files (the
-"Software"), to deal in the Software without restriction, including
-without limitation the rights to use, copy, modify, merge, publish,
-distribute, and/or sell copies of the Software, and to permit persons
-to whom the Software is furnished to do so, provided that the above
-copyright notice(s) and this permission notice appear in all copies of
-the Software and that both the above copyright notice(s) and this
-permission notice appear in supporting documentation.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
-OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
-HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY
-SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER
-RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
-CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
-CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-
-Except as contained in this notice, the name of a copyright holder
-shall not be used in advertising or otherwise to promote the sale, use
-or other dealings in this Software without prior written authorization
-of the copyright holder.
-
-=========================================================================
-== Public Domain License for Backport of JSR 166 ==
-=========================================================================
-
-Copyright-Only Dedication (based on United States law) or Public Domain Certification
-
-The person or persons who have associated work with this document (the "Dedicator" or "Certifier") hereby either (a) certifies that, to the best of his knowledge, the work of authorship identified is in the public domain of the country from which the work is published, or (b) hereby dedicates whatever copyright the dedicators holds in the work of authorship identified below (the "Work") to the public domain. A certifier, moreover, dedicates any copyright interest he may have in the associated work, and for these purposes, is described as a "dedicator" below.
-
-A certifier has taken reasonable steps to verify the copyright status of this work. Certifier recognizes that his good faith efforts may not shield him from liability if in fact the work certified is not in the public domain.
-
-Dedicator makes this dedication for the benefit of the public at large and to the detriment of the Dedicator's heirs and successors. Dedicator intends this dedication to be an overt act of relinquishment in perpetuity of all present and future rights under copyright law, whether vested or contingent, in the Work. Dedicator understands that such relinquishment of all rights includes the relinquishment of all rights to enforce (by lawsuit or otherwise) those copyrights in the Work.
-
-Dedicator recognizes that, once placed in the public domain, the Work may be freely reproduced, distributed, transmitted, used, modified, built upon, or otherwise exploited by anyone for any purpose, commercial or non-commercial, and in any way, including by methods that have not yet been invented or conceived.
-
-=========================================================================
-== Eclipse Public License ==
-=========================================================================
-
-Eclipse Public License - v 1.0
-
-THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
-
-1. DEFINITIONS
-
-"Contribution" means:
-
-a) in the case of the initial Contributor, the initial code and documentation distributed under this Agreement, and
-b) in the case of each subsequent Contributor:
-
-i) changes to the Program, and
-
-ii) additions to the Program;
-
-where such changes and/or additions to the Program originate from and are distributed by that particular Contributor. A Contribution 'originates' from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf. Contributions do not include additions to the Program which: (i) are separate modules of software distributed in conjunction with the Program under their own license agreement, and (ii) are not derivative works of the Program.
-
-"Contributor" means any person or entity that distributes the Program.
-
-"Licensed Patents " mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program.
-
-"Program" means the Contributions distributed in accordance with this Agreement.
-
-"Recipient" means anyone who receives the Program under this Agreement, including all Contributors.
-
-2. GRANT OF RIGHTS
-
-a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, distribute and sublicense the Contribution of such Contributor, if any, and such derivative works, in source code and object code form.
-
-b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in source code and object code form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder.
-
-c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to distribute the Program, it is Recipient's responsibility to acquire that license before distributing the Program.
-
-d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement.
-
-3. REQUIREMENTS
-
-A Contributor may choose to distribute the Program in object code form under its own license agreement, provided that:
-
-a) it complies with the terms and conditions of this Agreement; and
-
-b) its license agreement:
-
-i) effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose;
-
-ii) effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits;
-
-iii) states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party; and
-
-iv) states that source code for the Program is available from such Contributor, and informs licensees how to obtain it in a reasonable manner on or through a medium customarily used for software exchange.
-
-When the Program is made available in source code form:
-
-a) it must be made available under this Agreement; and
-
-b) a copy of this Agreement must be included with each copy of the Program.
-
-Contributors may not remove or alter any copyright notices contained within the Program.
-
-Each Contributor must identify itself as the originator of its Contribution, if any, in a manner that reasonably allows subsequent Recipients to identify the originator of the Contribution.
-
-4. COMMERCIAL DISTRIBUTION
-
-Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor ("Commercial Contributor") hereby agrees to defend and indemnify every other Contributor ("Indemnified Contributor") against any losses, damages and costs (collectively "Losses") arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense.
-
-For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages.
-
-5. NO WARRANTY
-
-EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement , including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations.
-
-6. DISCLAIMER OF LIABILITY
-
-EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
-
-7. GENERAL
-
-If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable.
-
-If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's rights granted under Section 2(b) shall terminate as of the date such litigation is filed.
-
-All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive.
-
-Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to distribute the Program (including its Contributions) under the new version. Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved.
-
-This Agreement is governed by the laws of the State of New York and the intellectual property laws of the United States of America. No party to this Agreement will bring a legal action under this Agreement more than one year after the cause of action arose. Each party waives its rights to a jury trial in any resulting litigation.
-
-
-
-=========================================================================
-== ICU License ==
-=========================================================================
-ICU License - ICU 1.8.1 and later
-
-COPYRIGHT AND PERMISSION NOTICE
-
-Copyright (c) 1995-2006 International Business Machines Corporation and others
-
-All rights reserved.
-
-Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, provided that the above copyright notice(s) and this permission notice appear in all copies of the Software and that both the above copyright notice(s) and this permission notice appear in supporting documentation.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-
-Except as contained in this notice, the name of a copyright holder shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization of the copyright holder.
-
-All trademarks and registered trademarks mentioned herein are the property of their respective owners.
-
-
-=========================================================================
-== AMQP License ==
-=========================================================================
-Copyright Notice
- ================
- (c) Copyright JPMorgan Chase Bank & Co., Cisco Systems, Inc., Envoy Technologies Inc.,
- iMatix Corporation, IONA\ufffd Technologies, Red Hat, Inc.,
- TWIST Process Innovations, and 29West Inc. 2006. All rights reserved.
-
- License
- =======
- JPMorgan Chase Bank & Co., Cisco Systems, Inc., Envoy Technologies Inc., iMatix
- Corporation, IONA Technologies, Red Hat, Inc., TWIST Process Innovations, and
- 29West Inc. (collectively, the "Authors") each hereby grants to you a worldwide,
- perpetual, royalty-free, nontransferable, nonexclusive license to
- (i) copy, display, distribute and implement the Advanced Messaging Queue Protocol
- ("AMQP") Specification and (ii) the Licensed Claims that are held by
- the Authors, all for the purpose of implementing the Advanced Messaging
- Queue Protocol Specification. Your license and any rights under this
- Agreement will terminate immediately without notice from
- any Author if you bring any claim, suit, demand, or action related to
- the Advanced Messaging Queue Protocol Specification against any Author.
- Upon termination, you shall destroy all copies of the Advanced Messaging
- Queue Protocol Specification in your possession or control.
-
- As used hereunder, "Licensed Claims" means those claims of a patent or
- patent application, throughout the world, excluding design patents and
- design registrations, owned or controlled, or that can be sublicensed
- without fee and in compliance with the requirements of this
- Agreement, by an Author or its affiliates now or at any
- future time and which would necessarily be infringed by implementation
- of the Advanced Messaging Queue Protocol Specification. A claim is
- necessarily infringed hereunder only when it is not possible to avoid
- infringing it because there is no plausible non-infringing alternative
- for implementing the required portions of the Advanced Messaging Queue
- Protocol Specification. Notwithstanding the foregoing, Licensed Claims
- shall not include any claims other than as set forth above even if
- contained in the same patent as Licensed Claims; or that read solely
- on any implementations of any portion of the Advanced Messaging Queue
- Protocol Specification that are not required by the Advanced Messaging
- Queue Protocol Specification, or that, if licensed, would require a
- payment of royalties by the licensor to unaffiliated third parties.
- Moreover, Licensed Claims shall not include (i) any enabling technologies
- that may be necessary to make or use any Licensed Product but are not
- themselves expressly set forth in the Advanced Messaging Queue Protocol
- Specification (e.g., semiconductor manufacturing technology, compiler
- technology, object oriented technology, networking technology, operating
- system technology, and the like); or (ii) the implementation of other
- published standards developed elsewhere and merely referred to in the
- body of the Advanced Messaging Queue Protocol Specification, or
- (iii) any Licensed Product and any combinations thereof the purpose or
- function of which is not required for compliance with the Advanced
- Messaging Queue Protocol Specification. For purposes of this definition,
- the Advanced Messaging Queue Protocol Specification shall be deemed to
- include both architectural and interconnection requirements essential
- for interoperability and may also include supporting source code artifacts
- where such architectural, interconnection requirements and source code
- artifacts are expressly identified as being required or documentation to
- achieve compliance with the Advanced Messaging Queue Protocol Specification.
-
- As used hereunder, "Licensed Products" means only those specific portions
- of products (hardware, software or combinations thereof) that implement
- and are compliant with all relevant portions of the Advanced Messaging
- Queue Protocol Specification.
-
- The following disclaimers, which you hereby also acknowledge as to any
- use you may make of the Advanced Messaging Queue Protocol Specification:
-
- THE ADVANCED MESSAGING QUEUE PROTOCOL SPECIFICATION IS PROVIDED "AS IS,"
- AND THE AUTHORS MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
- IMPLIED, INCLUDING, BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, OR TITLE; THAT THE
- CONTENTS OF THE ADVANCED MESSAGING QUEUE PROTOCOL SPECIFICATION ARE
- SUITABLE FOR ANY PURPOSE; NOR THAT THE IMPLEMENTATION OF THE ADVANCED
- MESSAGING QUEUE PROTOCOL SPECIFICATION WILL NOT INFRINGE ANY THIRD PARTY
- PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS.
-
- THE AUTHORS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL,
- INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF OR RELATING TO ANY
- USE, IMPLEMENTATION OR DISTRIBUTION OF THE ADVANCED MESSAGING QUEUE
- PROTOCOL SPECIFICATION.
-
- The name and trademarks of the Authors may NOT be used in any manner,
- including advertising or publicity pertaining to the Advanced Messaging
- Queue Protocol Specification or its contents without specific, written
- prior permission. Title to copyright in the Advanced Messaging Queue
- Protocol Specification will at all times remain with the Authors.
-
- No other rights are granted by implication, estoppel or otherwise.
-
- Upon termination of your license or rights under this Agreement, you
- shall destroy all copies of the Advanced Messaging Queue Protocol
- Specification in your possession or control.
-
- Trademarks
- ==========
- "JPMorgan", "JPMorgan Chase", "Chase", the JPMorgan Chase logo and the
- Octagon Symbol are trademarks of JPMorgan Chase & Co.
-
- IMATIX and the iMatix logo are trademarks of iMatix Corporation sprl.
-
- IONA, IONA Technologies, and the IONA logos are trademarks of IONA
- Technologies PLC and/or its subsidiaries.
-
- LINUX is a trademark of Linus Torvalds. RED HAT and JBOSS are registered
- trademarks of Red Hat, Inc. in the US and other countries.
-
- Java, all Java-based trademarks and OpenOffice.org are trademarks of
- Sun Microsystems, Inc. in the United States, other countries, or both.
-
- Other company, product, or service names may be trademarks or service
- marks of others.
-
- Links to full AMQP specification:
- =================================
- http://www.envoytech.org/spec/amq/
- http://www.iona.com/opensource/amqp/
- http://www.redhat.com/solutions/specifications/amqp/
- http://www.twiststandards.org/tiki-index.php?page=AMQ
- http://www.imatix.com/amqp
-
- JZlib 0.0.* were released under the GNU LGPL license. Later, we have switched
- over to a BSD-style license.
-
-
- =========================================================================
- == JCraft License ==
- =========================================================================
-
- ------------------------------------------------------------------------------
- Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright
- notice, this list of conditions and the following disclaimer in
- the documentation and/or other materials provided with the distribution.
-
- 3. The names of the authors may not be used to endorse or promote products
- derived from this software without specific prior written permission.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
- INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
- INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
- OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
- EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-=============================================================================
-== JLine (BSD) License
-=============================================================================
-Copyright (c) 2008, Apache Software Foundation
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
-
- * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
- * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
- * Neither the name of the <ORGANIZATION> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-
-====================================
-== The Jython License
-====================================
-
-
-A. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING JYTHON
-==============================================================================================================
-
-PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
-----------------------------------------------------------------------------------------
-
-1. This LICENSE AGREEMENT is between the Python Software Foundation
-("PSF"), and the Individual or Organization ("Licensee") accessing and
-otherwise using this software ("Jython") in source or binary form and
-its associated documentation.
-
-2. Subject to the terms and conditions of this License Agreement, PSF
-hereby grants Licensee a nonexclusive, royalty-free, world-wide
-license to reproduce, analyze, test, perform and/or display publicly,
-prepare derivative works, distribute, and otherwise use Jython alone
-or in any derivative version, provided, however, that PSF's License
-Agreement and PSF's notice of copyright, i.e., "Copyright (c) 2007
-Python Software Foundation; All Rights Reserved" are retained in
-Jython alone or in any derivative version prepared by Licensee.
-
-3. In the event Licensee prepares a derivative work that is based on
-or incorporates Jython or any part thereof, and wants to make
-the derivative work available to others as provided herein, then
-Licensee hereby agrees to include in any such work a brief summary of
-the changes made to Jython.
-
-4. PSF is making Jython available to Licensee on an "AS IS"
-basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
-IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
-DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
-FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF JYTHON WILL NOT
-INFRINGE ANY THIRD PARTY RIGHTS.
-
-5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF JYTHON
-FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
-A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING JYTHON,
-OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
-
-6. This License Agreement will automatically terminate upon a material
-breach of its terms and conditions.
-
-7. Nothing in this License Agreement shall be deemed to create any
-relationship of agency, partnership, or joint venture between PSF and
-Licensee. This License Agreement does not grant permission to use PSF
-trademarks or trade name in a trademark sense to endorse or promote
-products or services of Licensee, or any third party.
-
-8. By copying, installing or otherwise using Jython, Licensee
-agrees to be bound by the terms and conditions of this License
-Agreement.
-
-Jython 2.0, 2.1 License
---------------------------------------------
-
-Copyright (c) 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007 Jython Developers
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions
-are met:
-
- - Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
-
- - Redistributions in binary form must reproduce the above copyright
- notice, this list of conditions and the following disclaimer in
- the documentation and/or other materials provided with the distribution.
-
- - Neither the name of the Jython Developers nor the names of
- its contributors may be used to endorse or promote products
- derived from this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-"AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR
-CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
-EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
-PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
-PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
-OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
-NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-
-
-
-JPython 1.1.x Software License.
-______________________________________________________________________
-
- 1. This LICENSE AGREEMENT is between the Corporation for National Research
- Initiatives, having an office at 1895 Preston White Drive, Reston, VA
- 20191 ("CNRI"), and the Individual or Organization ("Licensee")
- accessing and using JPython version 1.1.x in source or binary form and
- its associated documentation as provided herein ("Software").
-
- 2. Subject to the terms and conditions of this License Agreement, CNRI
- hereby grants Licensee a non-exclusive, non-transferable, royalty-free,
- world-wide license to reproduce, analyze, test, perform and/or display
- publicly, prepare derivative works, distribute, and otherwise use the
- Software alone or in any derivative version, provided, however, that
- CNRI's License Agreement and CNRI's notice of copyright, i.e.,
- "Copyright ©1996-1999 Corporation for National Research Initiatives;
- All Rights Reserved" are both retained in the Software, alone or in any
- derivative version prepared by Licensee.
-
- Alternatively, in lieu of CNRI's License Agreement, Licensee may
- substitute the following text (omitting the quotes), provided, however,
- that such text is displayed prominently in the Software alone or in any
- derivative version prepared by Licensee: "JPython (Version 1.1.x) is
- made available subject to the terms and conditions in CNRI's License
- Agreement. This Agreement may be located on the Internet using the
- following unique, persistent identifier (known as a handle):
- 1895.22/1006. The License may also be obtained from a proxy server on
- the Web using the following URL: http://hdl.handle.net/1895.22/1006."
-
- 3. In the event Licensee prepares a derivative work that is based on or
- incorporates the Software or any part thereof, and wants to make the
- derivative work available to the public as provided herein, then
- Licensee hereby agrees to indicate in any such work, in a prominently
- visible way, the nature of the modifications made to CNRI's Software.
-
- 4. Licensee may not use CNRI trademarks or trade name, including JPython
- or CNRI, in a trademark sense to endorse or promote products or
- services of Licensee, or any third party. Licensee may use the mark
- JPython in connection with Licensee's derivative versions that are
- based on or incorporate the Software, but only in the form
- "JPython-based ___________________," or equivalent.
-
- 5. CNRI is making the Software available to Licensee on an "AS IS" basis.
- CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY
- OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND DISCLAIMS ANY
- REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY
- PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT INFRINGE
- ANY THIRD PARTY RIGHTS.
-
- 6. CNRI SHALL NOT BE LIABLE TO LICENSEE OR OTHER USERS OF THE SOFTWARE FOR
- ANY INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF
- USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY DERIVATIVE
- THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. SOME STATES DO NOT
- ALLOW THE LIMITATION OR EXCLUSION OF LIABILITY SO THE ABOVE DISCLAIMER
- MAY NOT APPLY TO LICENSEE.
-
- 7. This License Agreement may be terminated by CNRI (i) immediately upon
- written notice from CNRI of any material breach by the Licensee, if the
- nature of the breach is such that it cannot be promptly remedied; or
- (ii) sixty (60) days following notice from CNRI to Licensee of a
- material remediable breach, if Licensee has not remedied such breach
- within that sixty-day period.
-
- 8. This License Agreement shall be governed by and interpreted in all
- respects by the law of the State of Virginia, excluding conflict of law
- provisions. Nothing in this Agreement shall be deemed to create any
- relationship of agency, partnership, or joint venture between CNRI and
- Licensee.
-
- 9. By clicking on the "ACCEPT" button where indicated, or by installing,
- copying or otherwise using the Software, Licensee agrees to be bound by
- the terms and conditions of this License Agreement.
-
- [ACCEPT BUTTON]
-
-=========================================================================
-== COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0 1. ==
-=========================================================================
-Definitions.
-
-1.1. Contributor means each individual or entity that creates or contributes to the creation of Modifications.
-
-1.2. Contributor Version means the combination of the Original Software, prior Modifications used by a Contributor (if any), and the Modifications made by that particular Contributor.
-
-1.3. Covered Software means (a) the Original Software, or (b) Modifications, or (c) the combination of files containing Original Software with files containing Modifications, in each case including portions thereof.
-
-1.4. Executable means the Covered Software in any form other than Source Code.
-
-1.5. Initial Developer means the individual or entity that first makes Original Software available under this License.
-
-1.6. Larger Work means a work which combines Covered Software or portions thereof with code not governed by the terms of this License.
-
-1.7. License means this document.
-
-1.8. Licensable means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently acquired, any and all of the rights conveyed herein.
-
-1.9. Modifications means the Source Code and Executable form of any of the following: A. Any file that results from an addition to, deletion from or modification of the contents of a file containing Original Software or previous Modifications; B. Any new file that contains any part of the Original Software or previous Modification; or C. Any new file that is contributed or otherwise made available under the terms of this License.
-
-1.10. Original Software means the Source Code and Executable form of computer software code that is originally released under this License.
-
-1.11. Patent Claims means any patent claim(s), now owned or hereafter acquired, including without limitation, method, process, and apparatus claims, in any patent Licensable by grantor.
-
-1.12. Source Code means (a) the common form of computer software code in which modifications are made and (b) associated documentation included in or with such code.
-
-1.13. You (or Your) means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, You includes any entity which controls, is controlled by, or is under common control with You. For purposes of this definition, control means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity.
-
-2. License Grants.
-
- 2.1. The Initial Developer Grant. Conditioned upon Your compliance with Section 3.1 below and subject to third party intellectual property claims, the Initial Developer hereby grants You a world-wide, royalty-free, non-exclusive license:
-
-(a) under intellectual property rights (other than patent or trademark) Licensable by Initial Developer, to use, reproduce, modify, display, perform, sublicense and distribute the Original Software (or portions thereof), with or without Modifications, and/or as part of a Larger Work; and
-
-(b) under Patent Claims infringed by the making, using or selling of Original Software, to make, have made, use, practice, sell, and offer for sale, and/or otherwise dispose of the Original Software (or portions thereof);
-
-(c) The licenses granted in Sections 2.1(a) and (b) are effective on the date Initial Developer first distributes or otherwise makes the Original Software available to a third party under the terms of this License;
-
-(d) Notwithstanding Section 2.1(b) above, no patent license is granted: (1) for code that You delete from the Original Software, or (2) for infringements caused by: (i) the modification of the Original Software, or (ii) the combination of the Original Software with other software or devices.
-
-2.2. Contributor Grant. Conditioned upon Your compliance with Section 3.1 below and subject to third party intellectual property claims, each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license:
-
-(a) under intellectual property rights (other than patent or trademark) Licensable by Contributor to use, reproduce, modify, display, perform, sublicense and distribute the Modifications created by such Contributor (or portions thereof), either on an unmodified basis, with other Modifications, as Covered Software and/or as part of a Larger Work; and
-
-(b) under Patent Claims infringed by the making, using, or selling of Modifications made by that Contributor either alone and/or in combination with its Contributor Version (or portions of such combination), to make, use, sell, offer for sale, have made, and/or otherwise dispose of: (1) Modifications made by that Contributor (or portions thereof); and (2) the combination of Modifications made by that Contributor with its Contributor Version (or portions of such combination).
-
-(c) The licenses granted in Sections 2.2(a) and 2.2(b) are effective on the date Contributor first distributes or otherwise makes the Modifications available to a third party.
-
-(d) Notwithstanding Section 2.2(b) above, no patent license is granted: (1) for any code that Contributor has deleted from the Contributor Version; (2) for infringements caused by: (i) third party modifications of Contributor Version, or (ii) the combination of Modifications made by that Contributor with other software (except as part of the Contributor Version) or other devices; or (3) under Patent Claims infringed by Covered Software in the absence of Modifications made by that Contributor.
-
-3. Distribution Obligations.
-
-3.1. Availability of Source Code. Any Covered Software that You distribute or otherwise make available in Executable form must also be made available in Source Code form and that Source Code form must be distributed only under the terms of this License. You must include a copy of this License with every copy of the Source Code form of the Covered Software You distribute or otherwise make available. You must inform recipients of any such Covered Software in Executable form as to how they can obtain such Covered Software in Source Code form in a reasonable manner on or through a medium customarily used for software exchange.
-
-3.2. Modifications. The Modifications that You create or to which You contribute are governed by the terms of this License. You represent that You believe Your Modifications are Your original creation(s) and/or You have sufficient rights to grant the rights conveyed by this License.
-
-3.3. Required Notices. You must include a notice in each of Your Modifications that identifies You as the Contributor of the Modification. You may not remove or alter any copyright, patent or trademark notices contained within the Covered Software, or any notices of licensing or any descriptive text giving attribution to any Contributor or the Initial Developer.
-
-3.4. Application of Additional Terms. You may not offer or impose any terms on any Covered Software in Source Code form that alters or restricts the applicable version of this License or the recipients rights hereunder. You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, you may do so only on Your own behalf, and not on behalf of the Initial Developer or any Contributor. You must make it absolutely clear that any such warranty, support, indemnity or liability obligation is offered by You alone, and You hereby agree to indemnify the Initial Developer and every Contributor for any liability incurred by the Initial Developer or such Contributor as a result of warranty, support, indemnity or liability terms You offer.
-
-3.5. Distribution of Executable Versions. You may distribute the Executable form of the Covered Software under the terms of this License or under the terms of a license of Your choice, which may contain terms different from this License, provided that You are in compliance with the terms of this License and that the license for the Executable form does not attempt to limit or alter the recipients rights in the Source Code form from the rights set forth in this License. If You distribute the Covered Software in Executable form under a different license, You must make it absolutely clear that any terms which differ from this License are offered by You alone, not by the Initial Developer or Contributor. You hereby agree to indemnify the Initial Developer and every Contributor for any liability incurred by the Initial Developer or such Contributor as a result of any such terms You offer.
-
-3.6. Larger Works. You may create a Larger Work by combining Covered Software with other code not governed by the terms of this License and distribute the Larger Work as a single product. In such a case, You must make sure the requirements of this License are fulfilled for the Covered Software.
-
-4. Versions of the License.
-
-4.1. New Versions. Sun Microsystems, Inc. is the initial license steward and may publish revised and/or new versions of this License from time to time. Each version will be given a distinguishing version number. Except as provided in Section 4.3, no one other than the license steward has the right to modify this License.
-
-4.2. Effect of New Versions. You may always continue to use, distribute or otherwise make the Covered Software available under the terms of the version of the License under which You originally received the Covered Software. If the Initial Developer includes a notice in the Original Software prohibiting it from being distributed or otherwise made available under any subsequent version of the License, You must distribute and make the Covered Software available under the terms of the version of the License under which You originally received the Covered Software. Otherwise, You may also choose to use, distribute or otherwise make the Covered Software available under the terms of any subsequent version of the License published by the license steward.
-
-4.3. Modified Versions. When You are an Initial Developer and You want to create a new license for Your Original Software, You may create and use a modified version of this License if You: (a) rename the license and remove any references to the name of the license steward (except to note that the license differs from this License); and (b) otherwise make it clear that the license contains terms which differ from this License.
-
-5. DISCLAIMER OF WARRANTY. COVERED SOFTWARE IS PROVIDED UNDER THIS LICENSE ON AN AS IS BASIS, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COVERED SOFTWARE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED SOFTWARE IS WITH YOU. SHOULD ANY COVERED SOFTWARE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF ANY COVERED SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER.
-
-6. TERMINATION.
-
-6.1. This License and the rights granted hereunder will terminate automatically if You fail to comply with terms herein and fail to cure such breach within 30 days of becoming aware of the breach. Provisions which, by their nature, must remain in effect beyond the termination of this License shall survive.
-
-6.2. If You assert a patent infringement claim (excluding declaratory judgment actions) against Initial Developer or a Contributor (the Initial Developer or Contributor against whom You assert such claim is referred to as Participant) alleging that the Participant Software (meaning the Contributor Version where the Participant is a Contributor or the Original Software where the Participant is the Initial Developer) directly or indirectly infringes any patent, then any and all rights granted directly or indirectly to You by such Participant, the Initial Developer (if the Initial Developer is not the Participant) and all Contributors under Sections 2.1 and/or 2.2 of this License shall, upon 60 days notice from Participant terminate prospectively and automatically at the expiration of such 60 day notice period, unless if within such 60 day period You withdraw Your claim with respect to the Participant Software against such Participant either unilaterally or pursuant to a written agreement with Participant.
-
-6.3. In the event of termination under Sections 6.1 or 6.2 above, all end user licenses that have been validly granted by You or any distributor hereunder prior to termination (excluding licenses granted to You by any distributor) shall survive termination.
-
-7. LIMITATION OF LIABILITY. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE INITIAL DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF COVERED SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO ANY PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOST PROFITS, LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN INFORMED OF THE POSSIBILITY OF SUCH DAMAGES. THIS LIMITATION OF LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL INJURY RESULTING FROM SUCH PARTYS NEGLIGENCE TO THE EXTENT APPLICABLE LAW PROHIBITS SUCH LIMITATION. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THIS EXCLUSION AND LIMITATION MAY NOT APPLY TO YOU.
-
-8. U.S. GOVERNMENT END USERS. The Covered Software is a commercial item, as that term is defined in 48 C.F.R. 2.101 (Oct. 1995), consisting of commercial computer software (as that term is defined at 48 C.F.R. 252.227-7014(a)(1)) and commercial computer software documentation as such terms are used in 48 C.F.R. 12.212 (Sept. 1995). Consistent with 48 C.F.R. 12.212 and 48 C.F.R. 227.7202-1 through 227.7202-4 (June 1995), all U.S. Government End Users acquire Covered Software with only those rights set forth herein. This U.S. Government Rights clause is in lieu of, and supersedes, any other FAR, DFAR, or other clause or provision that addresses Government rights in computer software under this License.
-
-9. MISCELLANEOUS. This License represents the complete agreement concerning subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. This License shall be governed by the law of the jurisdiction specified in a notice contained within the Original Software (except to the extent applicable law, if any, provides otherwise), excluding such jurisdictions conflict-of-law provisions. Any litigation relating to this License shall be subject to the jurisdiction of the courts located in the jurisdiction and venue specified in a notice contained within the Original Software, with the losing party responsible for costs, including, without limitation, court costs and reasonable attorneys fees and expenses. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not apply to this License. You agree that You alone are responsible for compliance with the United States export administration regulations (and the export control laws and regulation of any other countries) when You use, distribute or otherwise make available any Covered Software.
-
-10. RESPONSIBILITY FOR CLAIMS. As between Initial Developer and the Contributors, each party is responsible for claims and damages arising, directly or indirectly, out of its utilization of rights under this License and You agree to work with Initial Developer and Contributors to distribute such responsibility on an equitable basis. Nothing herein is intended or shall be deemed to constitute any admission of liability.
-
-NOTICE PURSUANT TO SECTION 9 OF THE COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) The code released under the CDDL shall be governed by the laws of the State of California (excluding conflict-of-law provisions). Any litigation relating to this License shall be subject to the jurisdiction of the Federal Courts of the Northern District of California and the state courts of the State of California, with venue lying in Santa Clara County, California.
-
-B. HISTORY OF THE SOFTWARE
-=======================================================
-
-JPython was created in late 1997 by Jim Hugunin. Jim was also the
-primary developer while he was at CNRI. In February 1999 Barry Warsaw
-took over as primary developer and released JPython version 1.1.
-
-In October 2000 Barry helped move the software to SourceForge
-where it was renamed to Jython. Jython 2.0 and 2.1 were developed
-under the Jython specific license below.
-
-From the 2.2 release on, Jython contributors have signed
-Python Software Foundation contributor agreements and releases are
-covered under the Python Software Foundation license version 2.
-
-The standard library is covered by the Python Software Foundation
-license as well. See the Lib/LICENSE file for details.
-
-The zxJDBC package was written by Brian Zimmer and originally licensed
-under the GNU Public License. The package is now covered by the Jython
-Software License.
-
-The command line interpreter is covered by the Apache Software
-License. See the org/apache/LICENSE file for details.
-
diff --git a/java/resources/NOTICE b/java/resources/NOTICE
deleted file mode 100644
index 607c1c1580..0000000000
--- a/java/resources/NOTICE
+++ /dev/null
@@ -1,113 +0,0 @@
-Apache Qpid
-Copyright 2006-2008 Apache Software Foundation
-This product includes software developed at
-Apache Software Foundation (http://www.apache.org/)
-
-Message logging is provided by the SLF4J library package,
-which is open source software, written by Ceki Gülcü, and
-copyright by SLF4J.ORG and QOS.ch. The original software is
-available from
-
- http://www.slf4j.org/
-
-Concurrency utlitity classes are provided by the backport-util-concurrent
-library package, which is open source software, written by
-Dawid Kurzyniec, and copyright by Distributed Computing Laboratory,
-Emory University. The original software is available from
-
- http://dcl.mathcs.emory.edu/util/backport-util-concurrent/
-
-Data compression support is provided by the JZLib library package,
-which is open source software, written by JCraft, and copyright
-by JCraft. The original software is available from
-
- http://www.jcraft.com/jzlib/
-
-Spring framework is provided by the Spring framework library
-package, which is open source software, written by Rod Johnson
-et al, and copyright by Springframework.org. The original
-software is available from
-
- http://www.springframework.org/
-
-
-This product includes software developed at
-The OSGi Alliance (http://www.osgi.org/).
-Copyright 2006 The OSGi Alliance.
-Licensed under the Apache License 2.0.
-
-Handling console input is provided bye the Jline library package,
-JLine is a Java library for handling console input. It is similar
-in functionality to BSD editline and GNU readline.Original software is
-available from
-
-pphttp://jline.sourceforge.net/index.html
-
-Jython is used within ant scripts for generating code.
-Jython is hosted at http://www.jython.org
-The license for jython is located at http://www.jython.org/Project/license.txt
-
-The Apache Muse Project is a Java-based implementation
-of the WS-ResourceFramework (WSRF), WS-BaseNotification (WSN),
-and WS-DistributedManagement (WSDM) specifications.
-It is licensed under the Apache License 2.0.
-The original software is available from
-
-http://ws.apache.org/muse/
-
-The Web Services Description Language for Java Toolkit (WSDL4J) allows
-the creation, representation, and manipulation of WSDL documents
-It is licensed under the Common Public License 1.0
-The original software is available from
-
-http://sourceforge.net/projects/wsdl4j
-
-Xml manipulation and all related xml common utilities are provider by the
-xml-apis library, which is an open source software.
-It is licensed under the Apache License 2.0 and is available from :
-
-http://xml.apache.org/commons/
-
-Xerces Java is a library for parsing, validating and manipulating XML documents.
-It is licensed under the Apache License 2.0 and is available from :
-
-http://xerces.apache.org/
-
-Xalan is an XSLT processor for transforming XML documents into HTML,
-text, or other XML document types.
-It is licensed under the Apache License 2.0.
-The original software is available from :
-
-http://xml.apache.org/xalan-j/
-
-Jetty is an open-source, standards-based, full-featured web server
-implemented entirely in Java. It is used as a web server / servlet engine
-on WS-DM adapter.
-Licensed under the Apache License 2.0.
-The original software is available from :
-
-http://www.mortbay.org/jetty/
-
-Javassist is a load-time reflective system for Java. It is a class library
-for editing bytecodes in Java;
-Licensend under MPL or LGPL.
-The original software is available from :
-
-http://www.jboss.org/javassist/
-
-The core library is an eclipse plugin that contains a bytecode disassembler
-("Disassembler") that can produce a listing of the Java assembler mnemonics ("Assembler Mnemonics")
-for a Java method. It is needed in order to enable JSP support in Jetty.
-It is licensed under Eclipse Public License Version 1.0
-
-The JSP implementation library is used for QMan admin console that is a web application running
-on Jetty.
-It is licensed under Common Development and Distribution license version 1.0. License information
-is available from :
-
-https://glassfish.dev.java.net/public/CDDLv1.0.html
-
-The JSP API library is used is used for QMan admin console that is a web application running
-on Jetty.
-It is licensed under Apache License Version 2.0.
-
diff --git a/java/resources/README.txt b/java/resources/README.txt
deleted file mode 100644
index 1d52d487fb..0000000000
--- a/java/resources/README.txt
+++ /dev/null
@@ -1,40 +0,0 @@
-
-Documentation
---------------
-All of our user documentation for the Qpid Java components can be accessed on our wiki at:
-
-http://cwiki.apache.org/confluence/display/qpid/Qpid+Java+Documentation
-
-This includes a Getting Started Guide and FAQ as well as detailed developer documentation.
-However, here's a VERY quick guide to running the installed Qpid broker, once you have installed it somewhere !
-
-
-Running the Broker
-------------------
-
-To run the broker, set the QPID_HOME environment variable to
-distribution directory and add $QPID_HOME/bin to your PATH. Then run
-the qpid-server shell script or qpid-server.bat batch file to start
-the broker. By default, the broker will use $QPID_HOME/etc to find
-the configuration files. You can supply a custom configuration using
-the -c argument.
-
-For example:
-
-qpid-server -c ~/etc/config.xml
-
-You can get a list of all command line arguments by using the -h argument.
-
-
-Developing
-----------
-
-In order to build Qpid you need Ant 1.6.5. Use ant -p to list the
-available targets. The default ant target, build, creates a working
-development-mode distribution in the build directory. To run the
-scripts in build/bin set QPID_HOME to the build directory and put
-${QPID_HOME}/bin on your PATH. The scripts in that directory include
-the standard ones in the distribution and a number of testing scripts.
-
-
-
diff --git a/java/systests/build.xml b/java/systests/build.xml
deleted file mode 100644
index 1da0a6d355..0000000000
--- a/java/systests/build.xml
+++ /dev/null
@@ -1,29 +0,0 @@
-<!--
- -
- - Licensed to the Apache Software Foundation (ASF) under one
-nn - or more contributor license agreements. See the NOTICE file
- -n distributed with this work for additional information
- - regarding copyright ownership. The ASF licenses this file
- - to you under the Apache License, Version 2.0 (the
- - "License"); you may not use this file except in compliance
- - with the License. You may obtain a copy of the License at
- -
- - http://www.apache.org/licenses/LICENSE-2.0
- -
- - Unless required by applicable law or agreed to in writing,
- - software distributed under the License is distributed on an
- - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- - KIND, either express or implied. See the License for the
- - specific language governing permissions and limitations
- - under the License.
- -
- -->
-<project name="System Tests" default="build">
- <property name="module.depends" value="client management/tools/qpid-cli management/common broker broker/test common common/test junit-toolkit"/>
- <property name="module.test.src" location="src/main/java"/>
- <property name="module.test.excludes"
- value="**/TTLTest.java,**/DropInTest.java,**/TestClientControlledTest.java"/>
-
- <import file="../module.xml"/>
-
-</project>
diff --git a/java/systests/etc/bin/fail.py b/java/systests/etc/bin/fail.py
deleted file mode 100644
index 517f31d075..0000000000
--- a/java/systests/etc/bin/fail.py
+++ /dev/null
@@ -1,88 +0,0 @@
-#!/usr/bin/env python
-#
-#
-# 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 os
-import re
-import datetime
-
-from optparse import OptionParser
-
-BASE_CMD = "mvn -Dskip.python.test=true %s test"
-
-def main():
- parser = OptionParser()
- parser.add_option("-t", "--test", dest="test",
- action="store", type="string",
- help="run specific tests")
- parser.add_option("-c", "--continuous", dest="continuous",
- action="store_true", default=False,
- help="run tests after failures, don't stop")
-
-
- (options, args) = parser.parse_args()
-
- # determine command to run
- if (options.test != None):
- cmd = (BASE_CMD % ("-Dtest="+options.test))
- else:
- cmd = (BASE_CMD % (""))
-
- run_forever = options.continuous
-
-
- failed_runs = []
- iteration = 0
- fail_match = re.compile("BUILD SUCCESSFUL")
- done = False
-
- while (run_forever or not (len(failed_runs) > 0)):
- iteration = iteration + 1
- if (run_forever):
- extra_text = (", %d failures so far: %s:" % (len(failed_runs), failed_runs))
- else:
- extra_text = ""
- print ("%s Test run %d%s" % (datetime.datetime.today().isoformat(), iteration, extra_text))
- (child_stdin, child_stdout_and_stderr) = os.popen4(cmd)
- output = child_stdout_and_stderr.read()
- child_stdin.close()
- child_stdout_and_stderr.close()
- matches = fail_match.search(output)
- if (matches == None):
- failed_runs.append(iteration)
- output_name = ("test-run-%d.out" % (iteration))
- #write testouput
- test_output = file(output_name, "w")
- test_output.write(output)
- test_output.close()
- #tar test-output and surefire reports together
- find_stdout = os.popen("find . -type d -name surefire-reports")
- surefire_dirs = find_stdout.read().replace('\n', ' ')
- find_stdout.close()
- tarcmd = ("tar -zcf test-failures-%d.tar.gz %s %s" % (iteration, output_name, surefire_dirs))
- tar_stdout = os.popen(tarcmd)
- tar_output = tar_stdout.read()
- tar_exitstatus = tar_stdout.close()
- print ("Something failed! Check %s" % (output_name))
- if (tar_exitstatus != None):
- print ("tar exited abornmally, aborting\n %s" % (tar_output))
- run_forever = False
-
-if __name__ == "__main__":
- main() \ No newline at end of file
diff --git a/java/systests/etc/bin/testclients.sh b/java/systests/etc/bin/testclients.sh
deleted file mode 100755
index 002f3d98bb..0000000000
--- a/java/systests/etc/bin/testclients.sh
+++ /dev/null
@@ -1,23 +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.
-#
-for x in `seq 1 $1`;
-do
- java -cp qpid-integrationtests-1.0-incubating-M2-SNAPSHOT-all-test-deps.jar -Dlog4j.configuration=file:/home/rupert/qpid/trunk/qpid/java/etc/mylog4j.xml org.apache.qpid.test.framework.distributedtesting.TestClient -n java$x &
-done
diff --git a/java/systests/etc/config-systests-ServerConfigurationTest-New.xml b/java/systests/etc/config-systests-ServerConfigurationTest-New.xml
deleted file mode 100644
index 39805cbc48..0000000000
--- a/java/systests/etc/config-systests-ServerConfigurationTest-New.xml
+++ /dev/null
@@ -1,77 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-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.
- -
- -->
-
-<broker>
- <work>${QPID_WORK}</work>
- <conf>${QPID_HOME}/etc</conf>
- <passwordDir>${conf}</passwordDir>
- <plugin-directory>${QPID_HOME}/lib/plugins</plugin-directory>
- <cache-directory>${QPID_WORK}/cache</cache-directory>
- <connector>
- <transport>nio</transport>
- <port>5672</port>
- <socketReceiveBuffer>32768</socketReceiveBuffer>
- <socketSendBuffer>32768</socketSendBuffer>
- </connector>
- <management>
- <enabled>false</enabled>
- <jmxport>8999</jmxport>
- </management>
- <advanced>
- <filterchain enableExecutorPool="true"/>
- <enablePooledAllocator>false</enablePooledAllocator>
- <enableDirectBuffers>false</enableDirectBuffers>
- <framesize>65535</framesize>
- <compressBufferOnQueue>false</compressBufferOnQueue>
- </advanced>
-
- <security>
- <principal-databases>
- <principal-database>
- <name>passwordfile</name>
- <class>org.apache.qpid.server.security.auth.database.PlainPasswordFilePrincipalDatabase</class>
- <attributes>
- <attribute>
- <name>passwordFile</name>
- <value>${passwordDir}/passwd</value>
- </attribute>
- </attributes>
- </principal-database>
- </principal-databases>
-
- <jmx>
- <principal-database>passwordfile</principal-database>
- </jmx>
- </security>
-
- <virtualhosts>${conf}/virtualhosts-ServerConfigurationTest-New.xml</virtualhosts>
-
- <heartbeat>
- <delay>0</delay>
- <timeoutFactor>2.0</timeoutFactor>
- </heartbeat>
- <queue>
- <auto_register>true</auto_register>
- </queue>
-</broker>
-
-
diff --git a/java/systests/etc/config-systests-ServerConfigurationTest-Old.xml b/java/systests/etc/config-systests-ServerConfigurationTest-Old.xml
deleted file mode 100644
index e87be87154..0000000000
--- a/java/systests/etc/config-systests-ServerConfigurationTest-Old.xml
+++ /dev/null
@@ -1,91 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
-
--->
-
-<configuration>
-<work>${QPID_WORK}</work>
-<conf>${QPID_HOME}/etc</conf>
-<passwordDir>${conf}</passwordDir>
-<plugin-directory>${QPID_HOME}/lib/plugins</plugin-directory>
-<cache-directory>${QPID_WORK}/cache</cache-directory>
-<connector>
-<transport>nio</transport>
-<port>5672</port>
-<socketReceiveBuffer>32768</socketReceiveBuffer>
-<socketSendBuffer>32768</socketSendBuffer>
-</connector>
-<management>
-<enabled>false</enabled>
-<jmxport>8999</jmxport>
-</management>
-<advanced>
-<filterchain enableExecutorPool="true"/>
-<enablePooledAllocator>false</enablePooledAllocator>
-<enableDirectBuffers>false</enableDirectBuffers>
-<framesize>65535</framesize>
-<compressBufferOnQueue>false</compressBufferOnQueue>
-</advanced>
-<security>
-<principal-databases>
-<principal-database>
-<name>passwordfile</name>
-<class>org.apache.qpid.server.security.auth.database.PlainPasswordFilePrincipalDatabase</class>
-<attributes>
-<attribute>
-<name>passwordFile</name>
-<value>${passwordDir}/passwd</value>
-</attribute>
-</attributes>
-</principal-database>
-</principal-databases>
-<jmx>
-<principal-database>passwordfile</principal-database>
-</jmx>
-</security>
-<virtualhosts>${conf}/virtualhosts-ServerConfigurationTest-New.xml
-<default>dev-only</default>
-<virtualhost>
-<name>dev-only</name>
-<dev-only>
-<store>
-<class>org.apache.qpid.server.store.MemoryMessageStore</class>
-<environment-path>${work}/bdbstore/dev-only-store</environment-path>
-</store>
-<queues>
-<exchange>amq.direct</exchange>
-<maximumQueueDepth>102400</maximumQueueDepth>
-<maximumMessageSize>20480</maximumMessageSize>
-<maximumMessageAge>60000</maximumMessageAge>
-<queue>
-<name>dev-queue</name>
-</queue>
-</queues>
-</dev-only>
-</virtualhost>
-</virtualhosts>
-<heartbeat>
-<delay>0</delay>
-<timeoutFactor>2.0</timeoutFactor>
-</heartbeat>
-<queue>
-<auto_register>true</auto_register>
-</queue>
-</configuration>
diff --git a/java/systests/etc/config-systests-acl-settings.xml b/java/systests/etc/config-systests-acl-settings.xml
deleted file mode 100644
index eebc75f05f..0000000000
--- a/java/systests/etc/config-systests-acl-settings.xml
+++ /dev/null
@@ -1,26 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-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.
- -
- -->
-<broker>
- <virtualhosts>${QPID_HOME}/etc/virtualhosts-systests-acl.xml</virtualhosts>
-</broker>
-
-
diff --git a/java/systests/etc/config-systests-acl.xml b/java/systests/etc/config-systests-acl.xml
deleted file mode 100644
index 535108235e..0000000000
--- a/java/systests/etc/config-systests-acl.xml
+++ /dev/null
@@ -1,30 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-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.
- -
- -->
-<configuration>
- <system/>
- <override>
- <xml fileName="${test.config}" optional="true"/>
- <xml fileName="${QPID_HOME}/etc/config-systests-acl-settings.xml"/>
- <xml fileName="${QPID_HOME}/etc/config-systests-settings.xml"/>
- <xml fileName="${QPID_HOME}/etc/config.xml"/>
- </override>
-</configuration>
diff --git a/java/systests/etc/config-systests-aclv2-settings.xml b/java/systests/etc/config-systests-aclv2-settings.xml
deleted file mode 100644
index fbf218fdfa..0000000000
--- a/java/systests/etc/config-systests-aclv2-settings.xml
+++ /dev/null
@@ -1,30 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-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.
- -
- -->
-<broker>
- <security>
- <aclv2>${QPID_HOME}/etc/global-default.txt</aclv2>
- </security>
-
- <virtualhosts>${QPID_HOME}/etc/virtualhosts-systests-aclv2.xml</virtualhosts>
-</broker>
-
-
diff --git a/java/systests/etc/config-systests-aclv2.xml b/java/systests/etc/config-systests-aclv2.xml
deleted file mode 100644
index 33563e7891..0000000000
--- a/java/systests/etc/config-systests-aclv2.xml
+++ /dev/null
@@ -1,30 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-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.
- -
- -->
-<configuration>
- <system/>
- <override>
- <xml fileName="${test.config}" optional="true"/>
- <xml fileName="${QPID_HOME}/etc/config-systests-aclv2-settings.xml"/>
- <xml fileName="${QPID_HOME}/etc/config-systests-settings.xml"/>
- <xml fileName="${QPID_HOME}/etc/config.xml"/>
- </override>
-</configuration>
diff --git a/java/systests/etc/config-systests-derby-settings.xml b/java/systests/etc/config-systests-derby-settings.xml
deleted file mode 100644
index 3ed3a9e33b..0000000000
--- a/java/systests/etc/config-systests-derby-settings.xml
+++ /dev/null
@@ -1,26 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-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.
- -
- -->
-<broker>
- <virtualhosts>${QPID_HOME}/etc/virtualhosts-systests-derby.xml</virtualhosts>
-</broker>
-
-
diff --git a/java/systests/etc/config-systests-derby.xml b/java/systests/etc/config-systests-derby.xml
deleted file mode 100644
index ba27a0c020..0000000000
--- a/java/systests/etc/config-systests-derby.xml
+++ /dev/null
@@ -1,30 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-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.
- -
- -->
-<configuration>
- <system/>
- <override>
- <xml fileName="${test.config}" optional="true"/>
- <xml fileName="${QPID_HOME}/etc/config-systests-derby-settings.xml"/>
- <xml fileName="${QPID_HOME}/etc/config-systests-settings.xml"/>
- <xml fileName="${QPID_HOME}/etc/config.xml"/>
- </override>
-</configuration>
diff --git a/java/systests/etc/config-systests-firewall-2.xml b/java/systests/etc/config-systests-firewall-2.xml
deleted file mode 100644
index 05c3eaff9f..0000000000
--- a/java/systests/etc/config-systests-firewall-2.xml
+++ /dev/null
@@ -1,108 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-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.
- -
- -->
-<broker>
- <prefix>${QPID_HOME}</prefix>
- <work>${QPID_WORK}</work>
- <conf>${prefix}/etc</conf>
- <plugin-directory>${QPID_HOME}/lib/plugins</plugin-directory>
- <cache-directory>${QPID_WORK}/cache</cache-directory>
- <connector>
- <!-- To enable SSL edit the keystorePath and keystorePassword
- and set enabled to true.
- To disasble Non-SSL port set sslOnly to true -->
- <ssl>
- <enabled>false</enabled>
- <sslOnly>false</sslOnly>
- <keystorePath>/path/to/keystore.ks</keystorePath>
- <keystorePassword>keystorepass</keystorePassword>
- </ssl>
- <qpidnio>false</qpidnio>
- <protectio>
- <enabled>false</enabled>
- <readBufferLimitSize>262144</readBufferLimitSize>
- <writeBufferLimitSize>262144</writeBufferLimitSize>
- </protectio>
- <transport>nio</transport>
- <port>5672</port>
- <sslport>8672</sslport>
- <socketReceiveBuffer>32768</socketReceiveBuffer>
- <socketSendBuffer>32768</socketSendBuffer>
- </connector>
- <management>
- <enabled>false</enabled>
- <jmxport>8999</jmxport>
- <ssl>
- <enabled>false</enabled>
- <!-- Update below path to your keystore location, eg ${conf}/qpid.keystore -->
- <keyStorePath>${prefix}/../test-profiles/test_resources/ssl/keystore.jks</keyStorePath>
- <keyStorePassword>password</keyStorePassword>
- </ssl>
- </management>
- <advanced>
- <filterchain enableExecutorPool="true"/>
- <enablePooledAllocator>false</enablePooledAllocator>
- <enableDirectBuffers>false</enableDirectBuffers>
- <framesize>65535</framesize>
- <compressBufferOnQueue>false</compressBufferOnQueue>
- <enableJMSXUserID>false</enableJMSXUserID>
- <locale>en_US</locale>
- </advanced>
-
- <security>
- <principal-databases>
- <!-- Example use of Base64 encoded MD5 hashes for authentication via CRAM-MD5-Hashed -->
- <principal-database>
- <name>passwordfile</name>
- <class>org.apache.qpid.server.security.auth.database.PlainPasswordFilePrincipalDatabase</class>
- <attributes>
- <attribute>
- <name>passwordFile</name>
- <value>${conf}/passwd</value>
- </attribute>
- </attributes>
- </principal-database>
- </principal-databases>
-
- <msg-auth>false</msg-auth>
-
- <jmx>
- <principal-database>passwordfile</principal-database>
- </jmx>
-
- <firewall default-action="deny"/>
- </security>
-
- <virtualhosts>${conf}/virtualhosts-systests-firewall-2.xml</virtualhosts>
-
- <heartbeat>
- <delay>0</delay>
- <timeoutFactor>2.0</timeoutFactor>
- </heartbeat>
- <queue>
- <auto_register>true</auto_register>
- </queue>
-
- <status-updates>ON</status-updates>
-
-</broker>
-
-
diff --git a/java/systests/etc/config-systests-firewall-3.xml b/java/systests/etc/config-systests-firewall-3.xml
deleted file mode 100644
index 861a3b33a3..0000000000
--- a/java/systests/etc/config-systests-firewall-3.xml
+++ /dev/null
@@ -1,110 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-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.
- -
- -->
-<broker>
- <prefix>${QPID_HOME}</prefix>
- <work>${QPID_WORK}</work>
- <conf>${prefix}/etc</conf>
- <plugin-directory>${QPID_HOME}/lib/plugins</plugin-directory>
- <cache-directory>${QPID_WORK}/cache</cache-directory>
- <connector>
- <!-- To enable SSL edit the keystorePath and keystorePassword
- and set enabled to true.
- To disasble Non-SSL port set sslOnly to true -->
- <ssl>
- <enabled>false</enabled>
- <sslOnly>false</sslOnly>
- <keystorePath>/path/to/keystore.ks</keystorePath>
- <keystorePassword>keystorepass</keystorePassword>
- </ssl>
- <qpidnio>false</qpidnio>
- <protectio>
- <enabled>false</enabled>
- <readBufferLimitSize>262144</readBufferLimitSize>
- <writeBufferLimitSize>262144</writeBufferLimitSize>
- </protectio>
- <transport>nio</transport>
- <port>5672</port>
- <sslport>8672</sslport>
- <socketReceiveBuffer>32768</socketReceiveBuffer>
- <socketSendBuffer>32768</socketSendBuffer>
- </connector>
- <management>
- <enabled>false</enabled>
- <jmxport>8999</jmxport>
- <ssl>
- <enabled>false</enabled>
- <!-- Update below path to your keystore location, eg ${conf}/qpid.keystore -->
- <keyStorePath>${prefix}/../test-profiles/test_resources/ssl/keystore.jks</keyStorePath>
- <keyStorePassword>password</keyStorePassword>
- </ssl>
- </management>
- <advanced>
- <filterchain enableExecutorPool="true"/>
- <enablePooledAllocator>false</enablePooledAllocator>
- <enableDirectBuffers>false</enableDirectBuffers>
- <framesize>65535</framesize>
- <compressBufferOnQueue>false</compressBufferOnQueue>
- <enableJMSXUserID>false</enableJMSXUserID>
- <locale>en_US</locale>
- </advanced>
-
- <security>
- <principal-databases>
- <!-- Example use of Base64 encoded MD5 hashes for authentication via CRAM-MD5-Hashed -->
- <principal-database>
- <name>passwordfile</name>
- <class>org.apache.qpid.server.security.auth.database.PlainPasswordFilePrincipalDatabase</class>
- <attributes>
- <attribute>
- <name>passwordFile</name>
- <value>${conf}/passwd</value>
- </attribute>
- </attributes>
- </principal-database>
- </principal-databases>
-
- <msg-auth>false</msg-auth>
-
- <jmx>
- <principal-database>passwordfile</principal-database>
- </jmx>
-
- <firewall default-action="deny">
- <rule access="allow" network="127.0.0.1"/>
- </firewall>
- </security>
-
- <virtualhosts>${conf}/virtualhosts-systests-firewall-3.xml</virtualhosts>
-
- <heartbeat>
- <delay>0</delay>
- <timeoutFactor>2.0</timeoutFactor>
- </heartbeat>
- <queue>
- <auto_register>true</auto_register>
- </queue>
-
- <status-updates>ON</status-updates>
-
-</broker>
-
-
diff --git a/java/systests/etc/config-systests-firewall-settings.xml b/java/systests/etc/config-systests-firewall-settings.xml
deleted file mode 100644
index aa73be0646..0000000000
--- a/java/systests/etc/config-systests-firewall-settings.xml
+++ /dev/null
@@ -1,30 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-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.
- -
- -->
-<broker>
- <security>
- <firewall>
- <rule access="allow" network="127.0.0.1"/>
- </firewall>
- </security>
-
- <virtualhosts>${QPID_HOME}/etc/virtualhosts-systests-firewall.xml</virtualhosts>
-</broker>
diff --git a/java/systests/etc/config-systests-firewall.xml b/java/systests/etc/config-systests-firewall.xml
deleted file mode 100644
index c0ce71210f..0000000000
--- a/java/systests/etc/config-systests-firewall.xml
+++ /dev/null
@@ -1,31 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-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.
- -
- -->
-<configuration>
- <system/>
- <override>
- <xml fileName="${test.config}" optional="true"/>
- <xml fileName="${QPID_FIREWALL_CONFIG_SETTINGS}" optional="true"/>
- <xml fileName="${QPID_HOME}/etc/config-systests-firewall-settings.xml"/>
- <xml fileName="${QPID_HOME}/etc/config-systests-settings.xml"/>
- <xml fileName="${QPID_HOME}/etc/config.xml"/>
- </override>
-</configuration>
diff --git a/java/systests/etc/config-systests-settings.xml b/java/systests/etc/config-systests-settings.xml
deleted file mode 100644
index 751ff133cb..0000000000
--- a/java/systests/etc/config-systests-settings.xml
+++ /dev/null
@@ -1,32 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-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.
- -
- -->
-<broker>
- <management>
- <enabled>false</enabled>
- <ssl>
- <enabled>false</enabled>
- <keyStorePath>${QPID_HOME}/../test-profiles/test_resources/ssl/keystore.jks</keyStorePath>
- <keyStorePassword>password</keyStorePassword>
- </ssl>
- </management>
- <virtualhosts>${QPID_HOME}/etc/virtualhosts-systests.xml</virtualhosts>
-</broker>
diff --git a/java/systests/etc/config-systests.xml b/java/systests/etc/config-systests.xml
deleted file mode 100644
index 5d7d878e76..0000000000
--- a/java/systests/etc/config-systests.xml
+++ /dev/null
@@ -1,29 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-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.
- -
- -->
-<configuration>
- <system/>
- <override>
- <xml fileName="${test.config}" optional="true"/>
- <xml fileName="${QPID_HOME}/etc/config-systests-settings.xml"/>
- <xml fileName="${QPID_HOME}/etc/config.xml"/>
- </override>
-</configuration>
diff --git a/java/systests/etc/global-default.txt b/java/systests/etc/global-default.txt
deleted file mode 100644
index 01b2c41809..0000000000
--- a/java/systests/etc/global-default.txt
+++ /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.
-#
-
-CONFIG expand=true
-
-# This section grants the admin user access to all management methods
-ACL ALLOW admin ALL METHOD
-
-# This section grants the client user access to all management methods except logging
-ACL DENY client ALL METHOD component="LoggingManagement"
-ACL ALLOW client ALL METHOD
-
-# This section grants the server user access to all management methods except configuration
-ACL DENY server ALL METHOD component="ConfigurationManagement"
-ACL ALLOW server ALL METHOD
diff --git a/java/systests/etc/global-externaladminacl-changeloggerleveldenied.txt b/java/systests/etc/global-externaladminacl-changeloggerleveldenied.txt
deleted file mode 100644
index a59b3176cb..0000000000
--- a/java/systests/etc/global-externaladminacl-changeloggerleveldenied.txt
+++ /dev/null
@@ -1,24 +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 section denies the admin user access to logging
-ACL DENY admin UPDATE METHOD component="LoggingManagement" name="setRuntimeRootLoggerLevel"
-
-# This section grants the admin user access to management methods
-ACL ALLOW admin ALL METHOD
diff --git a/java/systests/etc/global-externaladminacl-getallloggerlevelsdenied.txt b/java/systests/etc/global-externaladminacl-getallloggerlevelsdenied.txt
deleted file mode 100644
index ff024b5ee8..0000000000
--- a/java/systests/etc/global-externaladminacl-getallloggerlevelsdenied.txt
+++ /dev/null
@@ -1,25 +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 section denies the admin user access to logging methods
-ACL DENY admin ACCESS METHOD component="LoggingManagement" name="getAvailableLoggerLevels"
-
-# This section grants the admin user access to all management methods
-ACL ALLOW admin ALL METHOD
-
diff --git a/java/systests/etc/test-default.txt b/java/systests/etc/test-default.txt
deleted file mode 100644
index 95e733d077..0000000000
--- a/java/systests/etc/test-default.txt
+++ /dev/null
@@ -1,73 +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 section grants virtualhost access rights
-ACL ALLOW client ACCESS VIRTUALHOST
-ACL ALLOW server ACCESS VIRTUALHOST
-
-# This section grants publish rights to an exchange + routing key pair
-
-# Allow clients to publish requests
-ACL ALLOW client PUBLISH EXCHANGE name="amq.direct" routingKey="example.RequestQueue"
-
-# Allow the processor to respond to a client on their Temporary Topic
-ACL ALLOW server PUBLISH EXCHANGE name="amq.direct" routingKey="tmp_*"
-ACL ALLOW server PUBLISH EXCHANGE name="amq.direct" routingKey="TempQueue*"
-
-# This section grants users the ability to consume from the broker
-
-# Allow client to consume from temporary queues
-ACL ALLOW client CONSUME QUEUE temporary=true
-
-# Only allow the server to consume from the Request Queue
-ACL ALLOW server CONSUME QUEUE name="example.RequestQueue"
-
-# Allow client and server to consume from kipper queues
-ACL ALLOW client CONSUME QUEUE name="clientid:kipper"
-ACL ALLOW server CONSUME QUEUE name="clientid:kipper"
-
-# This section grants users the ability to create/delete queues and exchanges
-
-# Allow clients to create and delete temporary and kipper queue on this exchange
-ACL ALLOW client CREATE QUEUE temporary=true
-ACL ALLOW client DELETE QUEUE temporary=true
-ACL ALLOW client CREATE QUEUE durable="true"
-ACL ALLOW client DELETE QUEUE durable="true"
-
-# Allow the server to create the Request Queue and kipper queue
-ACL ALLOW server CREATE QUEUE name="example.RequestQueue"
-ACL ALLOW server CREATE QUEUE name="clientid:kipper"
-
-## Allow client and server exchange access for the relevant queues
-ACL ALLOW client BIND EXCHANGE name="amq.direct" temporary=true
-ACL ALLOW client UNBIND EXCHANGE name="amq.direct" temporary=true
-ACL ALLOW client BIND EXCHANGE name="amq.direct" durable=true
-ACL ALLOW client UNBIND EXCHANGE name="amq.direct" durable=true
-ACL ALLOW server BIND EXCHANGE name="amq.direct" queueName="example.RequestQueue"
-
-## Allow client and server exchange access for the relevant topics
-ACL ALLOW client BIND EXCHANGE name="amq.topic" durable=true routingKey=kipper
-ACL ALLOW client UNBIND EXCHANGE name="amq.topic" durable=true routingKey=kipper
-ACL ALLOW server BIND EXCHANGE name="amq.topic" durable=true routingKey=kipper
-
-# Action[operation=BIND,objectType=EXCHANGE,properties={OWNER=client, DURABLE=true, QUEUE_NAME=IllegalQueue, AUTO_DELETE=false, ROUTING_KEY=IllegalQueue, NAME=amq.direct, TEMPORARY=false, EXCLUSIVE=false}]
-
-
-ACL ALLOW client CREATE EXCHANGE
-ACL ALLOW server CREATE EXCHANGE
diff --git a/java/systests/etc/test-externalacljmx-deleteexchangefailure.txt b/java/systests/etc/test-externalacljmx-deleteexchangefailure.txt
deleted file mode 100644
index 197fe9dabe..0000000000
--- a/java/systests/etc/test-externalacljmx-deleteexchangefailure.txt
+++ /dev/null
@@ -1,26 +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 section grants virtualhost management rights
-ACL ALLOW admin ALL METHOD
-
-# testDeleteExchangeFailure()
-ACL ALLOW admin CREATE EXCHANGE name="amq.kipper.delete"
-ACL DENY admin DELETE EXCHANGE name="amq.kipper.delete"
-
diff --git a/java/systests/etc/test-externalacljmx.txt b/java/systests/etc/test-externalacljmx.txt
deleted file mode 100644
index f8a94bd44a..0000000000
--- a/java/systests/etc/test-externalacljmx.txt
+++ /dev/null
@@ -1,35 +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 section grants management access to the virtualhost
-ACL ALLOW admin ALL METHOD
-ACL ALLOW client ALL METHOD
-ACL ALLOW server ALL METHOD
-
-# Allow create kipper queue
-ACL ALLOW admin CREATE QUEUE name="kipper" owner = client # kipper
-ACL ALLOW admin BIND EXCHANGE name="amq.direct"
-
-# testCreateExchangeSuccess(), testDeleteExchangeSuccess()
-ACL ALLOW admin CREATE EXCHANGE name="amq.kipper.success"
-ACL ALLOW admin DELETE EXCHANGE name="amq.kipper.success"
-
-# testCreateExchangeFailure()
-ACL DENY admin CREATE EXCHANGE name="amq.kipper.failure"
-
diff --git a/java/systests/etc/test-logging.txt b/java/systests/etc/test-logging.txt
deleted file mode 100644
index 76c6e442e0..0000000000
--- a/java/systests/etc/test-logging.txt
+++ /dev/null
@@ -1,23 +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.
-#
-
-ACL ALLOW client CREATE QUEUE name="allow"
-ACL ALLOW-LOG client CREATE QUEUE name="allow-log"
-ACL DENY client CREATE QUEUE name="deny"
-ACL DENY-LOG client CREATE QUEUE name="deny-log"
diff --git a/java/systests/etc/test2-default.txt b/java/systests/etc/test2-default.txt
deleted file mode 100644
index 0855e631d7..0000000000
--- a/java/systests/etc/test2-default.txt
+++ /dev/null
@@ -1,21 +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 section grants all access rights
-ACL ALLOW guest ALL ALL \ No newline at end of file
diff --git a/java/systests/etc/virtualhosts-ServerConfigurationTest-New.xml b/java/systests/etc/virtualhosts-ServerConfigurationTest-New.xml
deleted file mode 100644
index 1b6845662b..0000000000
--- a/java/systests/etc/virtualhosts-ServerConfigurationTest-New.xml
+++ /dev/null
@@ -1,45 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-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.
- -
- -->
-<virtualhosts>
- <default>dev-only</default>
- <virtualhost>
- <name>dev-only</name>
- <dev-only>
- <queues>
- <exchange>amq.direct</exchange>
- <!-- Small defaults for development -->
- <maximumQueueDepth>102400</maximumQueueDepth> <!-- 100k -->
- <maximumMessageSize>20480</maximumMessageSize> <!-- 20kb -->
- <maximumMessageAge>60000</maximumMessageAge> <!-- 1 mins -->
-
- <queue>
- <name>dev-queue</name>
- </queue>
- </queues>
- <store>
- <class>org.apache.qpid.server.store.MemoryMessageStore</class>
- <environment-path>${QPID_WORK}/bdbstore/dev-only-store</environment-path>
- </store>
- </dev-only>
- </virtualhost>
-</virtualhosts>
- \ No newline at end of file
diff --git a/java/systests/etc/virtualhosts-systests-acl-settings.xml b/java/systests/etc/virtualhosts-systests-acl-settings.xml
deleted file mode 100644
index ffbace569f..0000000000
--- a/java/systests/etc/virtualhosts-systests-acl-settings.xml
+++ /dev/null
@@ -1,180 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-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.
- -
- -->
-<virtualhosts>
- <virtualhost>
- <name>test</name>
- <test>
- <queues>
- <exchange>amq.direct</exchange>
- <!-- 4Mb -->
- <maximumQueueDepth>4235264</maximumQueueDepth>
- <!-- 2Mb -->
- <maximumMessageSize>2117632</maximumMessageSize>
- <!-- 10 mins -->
- <maximumMessageAge>600000</maximumMessageAge>
- </queues>
-
-
- <security>
- <access_control_list>
- <!-- This section grants pubish rights to an exchange + routing key pair -->
- <publish>
- <exchanges>
- <exchange>
- <name>amq.direct</name>
- <routing_keys>
- <!-- Allow clients to publish requests -->
- <routing_key>
- <value>example.RequestQueue</value>
- <users>
- <user>client</user>
- </users>
- </routing_key>
-
- <!-- Allow the processor to respond to a client on their Temporary Topic -->
- <routing_key>
- <value>tmp_*</value>
- <users>
- <user>server</user>
- </users>
- </routing_key>
- <routing_key>
- <value>TempQueue*</value>
- <users>
- <user>server</user>
- </users>
- </routing_key>
- </routing_keys>
- </exchange>
- </exchanges>
- </publish>
-
- <!-- This section grants users the ability to consume from the broker -->
- <consume>
- <queues>
- <temporary>
- <users>
- <user>client</user>
- </users>
- </temporary>
-
- <!-- Only allow the server to consume from the Request Queue-->
- <queue>
- <name>example.RequestQueue</name>
- <users>
- <user>server</user>
- </users>
- </queue>
-
- <!-- Allow client and server to consume from the kipper Queue-->
- <queue>
- <name>clientid:kipper</name>
- <users>
- <user>client</user>
- <user>server</user>
- </users>
- </queue>
- </queues>
- </consume>
-
- <!-- This section grants users the ability to create queues and exchanges -->
- <create>
- <queues>
- <temporary>
- <users>
- <user>client</user>
- </users>
- </temporary>
-
- <!-- Allow clients to create queue on this exchange-->
- <queue>
- <exchanges>
- <exchange>
- <name>amq.direct</name>
- <users>
- <user>client</user>
- <user>server</user>
- </users>
- </exchange>
- <exchange>
- <name>amq.topic</name>
- <users>
- <user>client</user>
- <user>server</user>
- </users>
- </exchange>
- </exchanges>
- </queue>
-
- <!-- everyone can create the kipper queue -->
- <queue>
- <name>clientid:kipper</name>
- <users>
- <user>client</user>
- <user>server</user>
- </users>
- </queue>
-
- <!-- Allow the server to create the Request Queue-->
- <queue>
- <name>example.RequestQueue</name>
- <users>
- <user>server</user>
- </users>
- </queue>
- </queues>
- </create>
-
- <delete>
- <queues>
- <!-- only client can delete the kipper queue -->
- <queue>
- <name>clientid:kipper</name>
- <users>
- <user>client</user>
- </users>
- </queue>
- </queues>
- </delete>
- </access_control_list>
- </security>
- </test>
- </virtualhost>
-
- <virtualhost>
- <name>test2</name>
- <test2>
- <security>
- <access_control_list>
- <!-- This section grants specific users full permissions to all artifacts in this virtualhost -->
- <access>
- <users>
- <user>guest</user>
- </users>
- </access>
- </access_control_list>
- </security>
- </test2>
- </virtualhost>
-</virtualhosts>
-
-
diff --git a/java/systests/etc/virtualhosts-systests-acl.xml b/java/systests/etc/virtualhosts-systests-acl.xml
deleted file mode 100644
index 4a56c39de0..0000000000
--- a/java/systests/etc/virtualhosts-systests-acl.xml
+++ /dev/null
@@ -1,29 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-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.
- -
- -->
-<configuration>
- <system/>
- <override>
- <xml fileName="${test.virtualhosts}" optional="true"/>
- <xml fileName="${QPID_HOME}/etc/virtualhosts-systests-acl-settings.xml"/>
- <xml fileName="${QPID_HOME}/etc/virtualhosts.xml"/>
- </override>
-</configuration>
diff --git a/java/systests/etc/virtualhosts-systests-aclv2-settings.xml b/java/systests/etc/virtualhosts-systests-aclv2-settings.xml
deleted file mode 100644
index db1ad33a39..0000000000
--- a/java/systests/etc/virtualhosts-systests-aclv2-settings.xml
+++ /dev/null
@@ -1,48 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-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.
- -
- -->
-<virtualhosts>
- <virtualhost>
- <name>test</name>
- <test>
- <queues>
- <exchange>amq.direct</exchange>
- <!-- 4Mb -->
- <maximumQueueDepth>4235264</maximumQueueDepth>
- <!-- 2Mb -->
- <maximumMessageSize>2117632</maximumMessageSize>
- <!-- 10 mins -->
- <maximumMessageAge>600000</maximumMessageAge>
- </queues>
-
- <security>
- <aclv2>${QPID_HOME}/etc/test-default.txt</aclv2>
- </security>
- </test>
- </virtualhost>
-
- <virtualhost>
- <name>test2</name>
- <test2 />
- </virtualhost>
-</virtualhosts>
-
-
diff --git a/java/systests/etc/virtualhosts-systests-aclv2.xml b/java/systests/etc/virtualhosts-systests-aclv2.xml
deleted file mode 100644
index eb96577487..0000000000
--- a/java/systests/etc/virtualhosts-systests-aclv2.xml
+++ /dev/null
@@ -1,29 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-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.
- -
- -->
-<configuration>
- <system/>
- <override>
- <xml fileName="${test.virtualhosts}" optional="true"/>
- <xml fileName="${QPID_HOME}/etc/virtualhosts-systests-aclv2-settings.xml"/>
- <xml fileName="${QPID_HOME}/etc/virtualhosts.xml"/>
- </override>
-</configuration>
diff --git a/java/systests/etc/virtualhosts-systests-derby-settings.xml b/java/systests/etc/virtualhosts-systests-derby-settings.xml
deleted file mode 100644
index ed5ffbb1fd..0000000000
--- a/java/systests/etc/virtualhosts-systests-derby-settings.xml
+++ /dev/null
@@ -1,54 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-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.
- -
- -->
-<virtualhosts>
- <directory>${QPID_HOME}/virtualhosts</directory>
- <default>test</default>
-
- <virtualhost>
- <localhost>
- <store>
- <class>org.apache.qpid.server.store.DerbyMessageStore</class>
- <environment-path>${QPID_WORK}/derbyDB/localhost-store</environment-path>
- </store>
- </localhost>
- </virtualhost>
-
- <virtualhost>
- <development>
- <store>
- <class>org.apache.qpid.server.store.DerbyMessageStore</class>
- <environment-path>${QPID_WORK}/derbyDB/development-store</environment-path>
- </store>
- </development>
- </virtualhost>
-
- <virtualhost>
- <test>
- <store>
- <class>org.apache.qpid.server.store.DerbyMessageStore</class>
- <environment-path>${QPID_WORK}/derbyDB/test-store</environment-path>
- </store>
- </test>
- </virtualhost>
-</virtualhosts>
-
-
diff --git a/java/systests/etc/virtualhosts-systests-derby.xml b/java/systests/etc/virtualhosts-systests-derby.xml
deleted file mode 100644
index 171be37416..0000000000
--- a/java/systests/etc/virtualhosts-systests-derby.xml
+++ /dev/null
@@ -1,29 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-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.
- -
- -->
-<configuration>
- <system/>
- <override>
- <xml fileName="${test.virtualhosts}" optional="true"/>
- <xml fileName="${QPID_HOME}/etc/virtualhosts-systests-derby-settings.xml"/>
- <xml fileName="${QPID_HOME}/etc/virtualhosts.xml"/>
- </override>
-</configuration>
diff --git a/java/systests/etc/virtualhosts-systests-firewall-2.xml b/java/systests/etc/virtualhosts-systests-firewall-2.xml
deleted file mode 100644
index 20908e6eb4..0000000000
--- a/java/systests/etc/virtualhosts-systests-firewall-2.xml
+++ /dev/null
@@ -1,47 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-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.
- -
- -->
-<virtualhosts>
- <default>test</default>
-
- <virtualhost>
- <name>test</name>
- <test>
- <store>
- <class>org.apache.qpid.server.store.MemoryMessageStore</class>
- </store>
- </test>
- </virtualhost>
-
- <virtualhost>
- <name>test2</name>
- <test2>
- <store>
- <class>org.apache.qpid.server.store.MemoryMessageStore</class>
- </store>
- <security>
- <firewall default-action="deny">
- <rule access="allow" network="127.0.0.1"/>
- </firewall>
- </security>
- </test2>
- </virtualhost>
-</virtualhosts> \ No newline at end of file
diff --git a/java/systests/etc/virtualhosts-systests-firewall-3.xml b/java/systests/etc/virtualhosts-systests-firewall-3.xml
deleted file mode 100644
index 90377f345f..0000000000
--- a/java/systests/etc/virtualhosts-systests-firewall-3.xml
+++ /dev/null
@@ -1,47 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-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.
- -
- -->
-<virtualhosts>
- <default>test</default>
-
- <virtualhost>
- <name>test</name>
- <test>
- <store>
- <class>org.apache.qpid.server.store.MemoryMessageStore</class>
- </store>
- </test>
- </virtualhost>
-
- <virtualhost>
- <name>test2</name>
- <test2>
- <store>
- <class>org.apache.qpid.server.store.MemoryMessageStore</class>
- </store>
- <security>
- <firewall default-action="deny"/>
- </security>
- </test2>
- </virtualhost>
-</virtualhosts>
-
-
diff --git a/java/systests/etc/virtualhosts-systests-firewall.xml b/java/systests/etc/virtualhosts-systests-firewall.xml
deleted file mode 100644
index 51ab6739b3..0000000000
--- a/java/systests/etc/virtualhosts-systests-firewall.xml
+++ /dev/null
@@ -1,29 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-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.
- -
- -->
-<configuration>
- <system/>
- <override>
- <xml fileName="${test.virtualhosts}" optional="true"/>
- <xml fileName="${QPID_FIREWALL_VIRTUALHOSTS_SETTINGS}" optional="true"/>
- <xml fileName="${QPID_HOME}/etc/virtualhosts.xml"/>
- </override>
-</configuration>
diff --git a/java/systests/etc/virtualhosts-systests.xml b/java/systests/etc/virtualhosts-systests.xml
deleted file mode 100644
index 71f1cc9889..0000000000
--- a/java/systests/etc/virtualhosts-systests.xml
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-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.
- -
- -->
-<configuration>
- <system/>
- <override>
- <xml fileName="${test.virtualhosts}" optional="true"/>
- <xml fileName="${QPID_HOME}/etc/virtualhosts.xml"/>
- </override>
-</configuration>
diff --git a/java/systests/src/main/java/org/apache/mina/transport/vmpipe/support/VmPipeIdleStatusChecker.java b/java/systests/src/main/java/org/apache/mina/transport/vmpipe/support/VmPipeIdleStatusChecker.java
deleted file mode 100644
index 5323ad28bf..0000000000
--- a/java/systests/src/main/java/org/apache/mina/transport/vmpipe/support/VmPipeIdleStatusChecker.java
+++ /dev/null
@@ -1,125 +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.mina.transport.vmpipe.support;
-
-import org.apache.mina.common.IdleStatus;
-
-import java.util.HashMap;
-import java.util.IdentityHashMap;
-import java.util.Iterator;
-import java.util.Map;
-
-/**
- * This file is a patch to override MINA, because of the IdentityHashMap bug. Workaround to be supplied in MINA 1.0.7.
- * This patched file will be removed once upgraded onto a newer MINA.
- *
- * Dectects idle sessions and fires <tt>sessionIdle</tt> events to them.
- *
- * @author The Apache Directory Project (mina-dev@directory.apache.org)
- */
-public class VmPipeIdleStatusChecker
-{
- private static final VmPipeIdleStatusChecker INSTANCE = new VmPipeIdleStatusChecker();
-
- public static VmPipeIdleStatusChecker getInstance()
- {
- return INSTANCE;
- }
-
- private final Map sessions = new HashMap(); // will use as a set
-
- private final Worker worker = new Worker();
-
- private VmPipeIdleStatusChecker()
- {
- worker.start();
- }
-
- public void addSession(VmPipeSessionImpl session)
- {
- synchronized (sessions)
- {
- sessions.put(session, session);
- }
- }
-
- private class Worker extends Thread
- {
- private Worker()
- {
- super("VmPipeIdleStatusChecker");
- setDaemon(true);
- }
-
- public void run()
- {
- for (;;)
- {
- try
- {
- Thread.sleep(1000);
- }
- catch (InterruptedException e)
- { }
-
- long currentTime = System.currentTimeMillis();
-
- synchronized (sessions)
- {
- Iterator it = sessions.keySet().iterator();
- while (it.hasNext())
- {
- VmPipeSessionImpl session = (VmPipeSessionImpl) it.next();
- if (!session.isConnected())
- {
- it.remove();
- }
- else
- {
- notifyIdleSession(session, currentTime);
- }
- }
- }
- }
- }
- }
-
- private void notifyIdleSession(VmPipeSessionImpl session, long currentTime)
- {
- notifyIdleSession0(session, currentTime, session.getIdleTimeInMillis(IdleStatus.BOTH_IDLE), IdleStatus.BOTH_IDLE,
- Math.max(session.getLastIoTime(), session.getLastIdleTime(IdleStatus.BOTH_IDLE)));
- notifyIdleSession0(session, currentTime, session.getIdleTimeInMillis(IdleStatus.READER_IDLE), IdleStatus.READER_IDLE,
- Math.max(session.getLastReadTime(), session.getLastIdleTime(IdleStatus.READER_IDLE)));
- notifyIdleSession0(session, currentTime, session.getIdleTimeInMillis(IdleStatus.WRITER_IDLE), IdleStatus.WRITER_IDLE,
- Math.max(session.getLastWriteTime(), session.getLastIdleTime(IdleStatus.WRITER_IDLE)));
- }
-
- private void notifyIdleSession0(VmPipeSessionImpl session, long currentTime, long idleTime, IdleStatus status,
- long lastIoTime)
- {
- if ((idleTime > 0) && (lastIoTime != 0) && ((currentTime - lastIoTime) >= idleTime))
- {
- session.increaseIdleCount(status);
- session.getFilterChain().fireSessionIdle(session, status);
- }
- }
-
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/client/AMQQueueDeferredOrderingTest.java b/java/systests/src/main/java/org/apache/qpid/client/AMQQueueDeferredOrderingTest.java
deleted file mode 100644
index ca10126aa7..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/client/AMQQueueDeferredOrderingTest.java
+++ /dev/null
@@ -1,145 +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.client;
-
-import javax.jms.Connection;
-import javax.jms.Session;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-import javax.jms.TextMessage;
-
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.apache.qpid.client.transport.TransportConnection;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class AMQQueueDeferredOrderingTest extends QpidBrokerTestCase
-{
-
- private static final int NUM_MESSAGES = 1000;
-
- private Connection con;
- private Session session;
- private AMQQueue queue;
- private MessageConsumer consumer;
-
- private static final Logger _logger = LoggerFactory.getLogger(AMQQueueDeferredOrderingTest.class);
-
- private ASyncProducer producerThread;
-
- private class ASyncProducer extends Thread
- {
-
- private MessageProducer producer;
- private final Logger _logger = LoggerFactory.getLogger(ASyncProducer.class);
- private Session session;
- private int start;
- private int end;
-
- public ASyncProducer(AMQQueue q, int start, int end) throws Exception
- {
- this.session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
- this._logger.info("Create Consumer of Q1");
- this.producer = this.session.createProducer(q);
- this.start = start;
- this.end = end;
- }
-
- public void run()
- {
- try
- {
- this._logger.info("Starting to send messages");
- for (int i = start; i < end && !interrupted(); i++)
- {
- producer.send(session.createTextMessage(Integer.toString(i)));
- }
- this._logger.info("Sent " + (end - start) + " messages");
- }
- catch (JMSException e)
- {
- throw new RuntimeException(e);
- }
- }
- }
-
- protected void setUp() throws Exception
- {
- super.setUp();
-
- _logger.info("Create Connection");
- con = getConnection();
- _logger.info("Create Session");
- session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
- _logger.info("Create Q");
- queue = new AMQQueue(new AMQShortString("amq.direct"), new AMQShortString("Q"), new AMQShortString("Q"),
- false, true);
- _logger.info("Create Consumer of Q");
- consumer = session.createConsumer(queue);
- _logger.info("Start Connection");
- con.start();
- }
-
- public void testPausedOrder() throws Exception
- {
-
- // Setup initial messages
- _logger.info("Creating first producer thread");
- producerThread = new ASyncProducer(queue, 0, NUM_MESSAGES / 2);
- producerThread.start();
- // Wait for them to be done
- producerThread.join();
-
- // Setup second set of messages to produce while we consume
- _logger.info("Creating second producer thread");
- producerThread = new ASyncProducer(queue, NUM_MESSAGES / 2, NUM_MESSAGES);
- producerThread.start();
-
- // Start consuming and checking they're in order
- _logger.info("Consuming messages");
- for (int i = 0; i < NUM_MESSAGES; i++)
- {
- Message msg = consumer.receive(3000);
- assertNotNull("Message should not be null", msg);
- assertTrue("Message should be a text message", msg instanceof TextMessage);
- assertEquals("Message content does not match expected", Integer.toString(i), ((TextMessage) msg).getText());
- }
- }
-
- protected void tearDown() throws Exception
- {
- _logger.info("Interuptting producer thread");
- producerThread.interrupt();
- _logger.info("Closing connection");
- con.close();
-
- super.tearDown();
- }
-
- public static junit.framework.Test suite()
- {
- return new junit.framework.TestSuite(AMQQueueDeferredOrderingTest.class);
- }
-
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/client/AMQTestConnection_0_10.java b/java/systests/src/main/java/org/apache/qpid/client/AMQTestConnection_0_10.java
deleted file mode 100644
index 09a03a17a0..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/client/AMQTestConnection_0_10.java
+++ /dev/null
@@ -1,34 +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.client;
-
-import org.apache.qpid.transport.Connection;
-
-public class AMQTestConnection_0_10 extends AMQConnection
-{
- public AMQTestConnection_0_10(String url) throws Exception
- {
- super(url);
- }
-
- public Connection getConnection()
- {
- return((AMQConnectionDelegate_0_10)_delegate).getQpidConnection();
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/client/DispatcherTest.java b/java/systests/src/main/java/org/apache/qpid/client/DispatcherTest.java
deleted file mode 100644
index a8a23c2c41..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/client/DispatcherTest.java
+++ /dev/null
@@ -1,238 +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.client;
-
-import java.util.Hashtable;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-import javax.jms.Connection;
-import javax.jms.ConnectionFactory;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageListener;
-import javax.jms.MessageProducer;
-import javax.jms.Queue;
-import javax.jms.Session;
-import javax.naming.Context;
-import javax.naming.spi.InitialContextFactory;
-
-import org.apache.qpid.client.transport.TransportConnection;
-import org.apache.qpid.jndi.PropertiesFileInitialContextFactory;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * QPID-293 Setting MessageListener after connection has started can cause messages to be "lost" on a internal delivery queue
- * <p/>
- * The message delivery process:
- * Mina puts a message on _queue in AMQSession and the dispatcher thread take()s
- * from here and dispatches to the _consumers. If the _consumer doesn't have a message listener set at connection start
- * then messages are stored on _synchronousQueue (which needs to be > 1 to pass JMS TCK as multiple consumers on a
- * session can run in any order and a synchronous put/poll will block the dispatcher).
- * <p/>
- * When setting the message listener later the _synchronousQueue is just poll()'ed and the first message delivered
- * the remaining messages will be left on the queue and lost, subsequent messages on the session will arrive first.
- */
-public class DispatcherTest extends QpidBrokerTestCase
-{
- private static final Logger _logger = LoggerFactory.getLogger(DispatcherTest.class);
-
- Context _context;
-
- private static final int MSG_COUNT = 6;
- private int _receivedCount = 0;
- private int _receivedCountWhileStopped = 0;
- private Connection _clientConnection, _producerConnection;
- private MessageConsumer _consumer;
- MessageProducer _producer;
- Session _clientSession, _producerSession;
-
- private final CountDownLatch _allFirstMessagesSent = new CountDownLatch(1); // all messages Sent Lock
- private final CountDownLatch _allSecondMessagesSent = new CountDownLatch(1); // all messages Sent Lock
-
- private volatile boolean _connectionStopped = false;
-
- protected void setUp() throws Exception
- {
- super.setUp();
-
- // Create Client 1
- _clientConnection = getConnection();
-
- _clientSession = _clientConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- Queue queue = _clientSession.createQueue(this.getClass().getName());
- _consumer = _clientSession.createConsumer(queue);
-
- // Create Producer
- _producerConnection = getConnection();
-
- _producerConnection.start();
-
- _producerSession = _producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- _producer = _producerSession.createProducer(queue);
-
- for (int msg = 0; msg < MSG_COUNT; msg++)
- {
- _producer.send(_producerSession.createTextMessage("Message " + msg));
- }
- }
-
- protected void tearDown() throws Exception
- {
-
- _clientConnection.close();
-
- _producerConnection.close();
- super.tearDown();
- }
-
- public void testAsynchronousRecieve()
- {
- _logger.info("Test Start");
-
- assertTrue(!((AMQConnection) _clientConnection).started());
-
- // Set default Message Listener
- try
- {
- _consumer.setMessageListener(new MessageListener()
- {
- public void onMessage(Message message)
- {
- _logger.info("Client 1 ML 1 Received Message(" + _receivedCount + "):" + message);
-
- _receivedCount++;
-
- if (_receivedCount == MSG_COUNT)
- {
- _allFirstMessagesSent.countDown();
- }
-
- if (_connectionStopped)
- {
- _logger.info("Running with Message:" + _receivedCount);
- }
-
- if (_connectionStopped && (_allFirstMessagesSent.getCount() == 0))
- {
- _receivedCountWhileStopped++;
- }
-
- if (_allFirstMessagesSent.getCount() == 0)
- {
- if (_receivedCount == (MSG_COUNT * 2))
- {
- _allSecondMessagesSent.countDown();
- }
- }
- }
- });
-
- assertTrue("Connecion should not be started", !((AMQConnection) _clientConnection).started());
- _clientConnection.start();
- }
- catch (JMSException e)
- {
- _logger.error("Error Setting Default ML on consumer1");
- }
-
- try
- {
- _allFirstMessagesSent.await(1000, TimeUnit.MILLISECONDS);
- }
- catch (InterruptedException e)
- {
- // do nothing
- }
-
- try
- {
- assertTrue("Connecion should be started", ((AMQConnection) _clientConnection).started());
- _clientConnection.stop();
- _connectionStopped = true;
- }
- catch (JMSException e)
- {
- _logger.error("Error stopping connection");
- }
-
- try
- {
- _logger.error("Send additional messages");
-
- for (int msg = 0; msg < MSG_COUNT; msg++)
- {
- _producer.send(_producerSession.createTextMessage("Message " + msg));
- }
- }
- catch (JMSException e)
- {
- _logger.error("Unable to send additional messages", e);
- }
-
- try
- {
- Thread.sleep(1000);
- }
- catch (InterruptedException e)
- {
- // ignore
- }
-
- try
- {
- _logger.info("Restarting connection");
-
- _connectionStopped = false;
- _clientConnection.start();
- }
- catch (JMSException e)
- {
- _logger.error("Error Setting Better ML on consumer1", e);
- }
-
- _logger.info("Waiting upto 2 seconds for messages");
-
- try
- {
- _allSecondMessagesSent.await(1000, TimeUnit.MILLISECONDS);
- }
- catch (InterruptedException e)
- {
- // do nothing
- }
-
- assertEquals("Messages not received correctly", 0, _allFirstMessagesSent.getCount());
- assertEquals("Messages not received correctly", 0, _allSecondMessagesSent.getCount());
- assertEquals("Client didn't get all messages", MSG_COUNT * 2, _receivedCount);
- assertEquals("Messages received while stopped is not 0", 0, _receivedCountWhileStopped);
- }
-
- public static junit.framework.Test suite()
- {
- return new junit.framework.TestSuite(DispatcherTest.class);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/client/MessageListenerMultiConsumerImmediatePrefetch.java b/java/systests/src/main/java/org/apache/qpid/client/MessageListenerMultiConsumerImmediatePrefetch.java
deleted file mode 100644
index 7461f6c200..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/client/MessageListenerMultiConsumerImmediatePrefetch.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- *
- */
-package org.apache.qpid.client;
-
-/**
- * QPID-293 Setting MessageListener after connection has started can cause messages to be "lost" on a internal delivery
- * queue <p/> The message delivery process: Mina puts a message on _queue in AMQSession and the dispatcher thread
- * take()s from here and dispatches to the _consumers. If the _consumer1 doesn't have a message listener set at
- * connection start then messages are stored on _synchronousQueue (which needs to be > 1 to pass JMS TCK as multiple
- * consumers on a session can run in any order and a synchronous put/poll will block the dispatcher). <p/> When setting
- * the message listener later the _synchronousQueue is just poll()'ed and the first message delivered the remaining
- * messages will be left on the queue and lost, subsequent messages on the session will arrive first.
- */
-public class MessageListenerMultiConsumerImmediatePrefetch extends MessageListenerMultiConsumerTest
-{
- protected void setUp() throws Exception
- {
- System.setProperty(AMQSession.IMMEDIATE_PREFETCH, "true");
- super.setUp();
- }
-
- public static junit.framework.Test suite()
- {
- return new junit.framework.TestSuite(MessageListenerMultiConsumerImmediatePrefetch.class);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/client/MessageListenerMultiConsumerTest.java b/java/systests/src/main/java/org/apache/qpid/client/MessageListenerMultiConsumerTest.java
deleted file mode 100644
index ca83b99120..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/client/MessageListenerMultiConsumerTest.java
+++ /dev/null
@@ -1,253 +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.client;
-
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.jms.Connection;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageListener;
-import javax.jms.MessageProducer;
-import javax.jms.Queue;
-import javax.jms.Session;
-import javax.naming.Context;
-
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-import java.util.UUID;
-
-/**
- * QPID-293 Setting MessageListener after connection has started can cause messages to be "lost" on a internal delivery
- * queue <p/> The message delivery process: Mina puts a message on _queue in AMQSession and the dispatcher thread
- * take()s from here and dispatches to the _consumers. If the _consumer1 doesn't have a message listener set at
- * connection start then messages are stored on _synchronousQueue (which needs to be > 1 to pass JMS TCK as multiple
- * consumers on a session can run in any order and a synchronous put/poll will block the dispatcher). <p/> When setting
- * the message listener later the _synchronousQueue is just poll()'ed and the first message delivered the remaining
- * messages will be left on the queue and lost, subsequent messages on the session will arrive first.
- */
-public class MessageListenerMultiConsumerTest extends QpidBrokerTestCase
-{
- private static final Logger _logger = LoggerFactory.getLogger(MessageListenerMultiConsumerTest.class);
-
- Context _context;
-
- private static final int MSG_COUNT = 6;
- private int receivedCount1 = 0;
- private int receivedCount2 = 0;
- private Connection _clientConnection;
- private MessageConsumer _consumer1;
- private MessageConsumer _consumer2;
- private Session _clientSession1;
- private Queue _queue;
- private final CountDownLatch _allMessagesSent = new CountDownLatch(2); // all messages Sent Lock
- private static final String QUEUE_NAME = "queue" + UUID.randomUUID().toString();
-
- protected void setUp() throws Exception
- {
- super.setUp();
-
- // Create Client 1
- _clientConnection = getConnection("guest", "guest");
-
- _clientConnection.start();
-
- _clientSession1 = _clientConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- _queue =_clientSession1.createQueue(QUEUE_NAME);
-
- _consumer1 = _clientSession1.createConsumer(_queue);
-
- // Create Client 2
- Session clientSession2 = _clientConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- _consumer2 = clientSession2.createConsumer(_queue);
-
- // Create Producer
- Connection producerConnection = getConnection("guest", "guest");
-
- producerConnection.start();
-
- Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- MessageProducer producer = producerSession.createProducer(_queue);
-
- for (int msg = 0; msg < MSG_COUNT; msg++)
- {
- producer.send(producerSession.createTextMessage("Message " + msg));
- }
-
- producerConnection.close();
-
- }
-
- protected void tearDown() throws Exception
- {
- _clientConnection.close();
- super.tearDown();
- }
-
- public void testRecieveInterleaved() throws Exception
- {
- int msg = 0;
- int MAX_LOOPS = MSG_COUNT * 2;
- for (int loops = 0; (msg < MSG_COUNT) || (loops < MAX_LOOPS); loops++)
- {
-
- if (_consumer1.receive(1000) != null)
- {
- msg++;
- }
-
- if (_consumer2.receive(1000) != null)
- {
- msg++;
- }
- }
-
- assertEquals("Not all messages received.", MSG_COUNT, msg);
- }
-
- public void testAsynchronousRecieve() throws Exception
- {
- _consumer1.setMessageListener(new MessageListener()
- {
- public void onMessage(Message message)
- {
- _logger.info("Client 1 Received Message(" + receivedCount1 + "):" + message);
-
- receivedCount1++;
-
- if (receivedCount1 == (MSG_COUNT / 2))
- {
- _allMessagesSent.countDown();
- }
-
- }
- });
-
- _consumer2.setMessageListener(new MessageListener()
- {
- public void onMessage(Message message)
- {
- _logger.info("Client 2 Received Message(" + receivedCount2 + "):" + message);
-
- receivedCount2++;
- if (receivedCount2 == (MSG_COUNT / 2))
- {
- _allMessagesSent.countDown();
- }
- }
- });
-
- _logger.info("Waiting upto 2 seconds for messages");
-
- try
- {
- _allMessagesSent.await(4000, TimeUnit.MILLISECONDS);
- }
- catch (InterruptedException e)
- {
- // do nothing
- }
-
- assertEquals(MSG_COUNT, receivedCount1 + receivedCount2);
- }
-
- public void testRecieveC2Only() throws Exception
- {
- if (
- !Boolean.parseBoolean(
- System.getProperties().getProperty(AMQSession.IMMEDIATE_PREFETCH,
- AMQSession.IMMEDIATE_PREFETCH_DEFAULT)))
- {
- _logger.info("Performing Receive only on C2");
- for (int msg = 0; msg < MSG_COUNT; msg++)
- {
- assertTrue(MSG_COUNT + " msg should be received. Only received:" + msg, _consumer2.receive(1000) != null);
- }
- }
- }
-
- public void testRecieveBoth() throws Exception
- {
- if (
- !Boolean.parseBoolean(
- System.getProperties().getProperty(AMQSession.IMMEDIATE_PREFETCH,
- AMQSession.IMMEDIATE_PREFETCH_DEFAULT)))
- {
- _logger.info("Performing Receive only with two consumers on one session ");
-
- //Create a new consumer on session one that we don't use
- _clientSession1.createConsumer(_queue);
-
- int msg;
- for (msg = 0; msg < (MSG_COUNT / 2); msg++)
- {
-
- // Attempt to receive up to half the messages
- // The other half may have gone to the consumer above
- final Message message = _consumer1.receive(1000);
- if(message == null)
- {
- break;
- }
-
- }
-
- _consumer1.close();
- // This will close the unused consumer above.
- _clientSession1.close();
-
-
- // msg will now have recorded the number received on session 1
- // attempt to retrieve the rest on session 2
- for (; msg < MSG_COUNT ; msg++)
- {
- assertTrue("Failed at msg id" + msg, _consumer2.receive(1000) != null);
- }
-
- }
- else
- {
- _logger.info("Performing Receive only on both C1 and C2");
-
- for (int msg = 0; msg < (MSG_COUNT / 2); msg++)
- {
-
- assertTrue(_consumer1.receive(3000) != null);
- }
-
- for (int msg = 0; msg < (MSG_COUNT / 2); msg++)
- {
- assertTrue(_consumer2.receive(3000) != null);
- }
- }
- }
-
- public static junit.framework.Test suite()
- {
- return new junit.framework.TestSuite(MessageListenerMultiConsumerTest.class);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/client/MessageListenerTest.java b/java/systests/src/main/java/org/apache/qpid/client/MessageListenerTest.java
deleted file mode 100644
index e4d1c72208..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/client/MessageListenerTest.java
+++ /dev/null
@@ -1,261 +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.client;
-
-import org.apache.qpid.server.configuration.ServerConfiguration;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.apache.qpid.util.LogMonitor;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.jms.Connection;
-import javax.jms.ExceptionListener;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageListener;
-import javax.jms.MessageProducer;
-import javax.jms.Queue;
-import javax.jms.Session;
-import javax.naming.Context;
-
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-/**
- * QPID-293 Setting MessageListener after connection has started can cause messages to be "lost" on a internal delivery
- * queue <p/> The message delivery process: Mina puts a message on _queue in AMQSession and the dispatcher thread
- * take()s from here and dispatches to the _consumers. If the _consumer doesn't have a message listener set at
- * connection start then messages are stored on _synchronousQueue (which needs to be > 1 to pass JMS TCK as multiple
- * consumers on a session can run in any order and a synchronous put/poll will block the dispatcher). <p/> When setting
- * the message listener later the _synchronousQueue is just poll()'ed and the first message delivered the remaining
- * messages will be left on the queue and lost, subsequent messages on the session will arrive first.
- */
-public class MessageListenerTest extends QpidBrokerTestCase implements MessageListener, ExceptionListener
-{
- private static final Logger _logger = LoggerFactory.getLogger(MessageListenerTest.class);
-
- Context _context;
-
- private static final int MSG_COUNT = 5;
- private int _receivedCount = 0;
- private int _errorCount = 0;
- private MessageConsumer _consumer;
- private Connection _clientConnection;
- private CountDownLatch _awaitMessages = new CountDownLatch(MSG_COUNT);
-
- protected void setUp() throws Exception
- {
- super.setUp();
-
- // Create Client
- _clientConnection = getConnection("guest", "guest");
-
- _clientConnection.start();
-
- Session clientSession = _clientConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- Queue queue =clientSession.createQueue("message-listener-test-queue");
-
- _consumer = clientSession.createConsumer(queue);
-
- // Create Producer
-
- Connection producerConnection = getConnection("guest", "guest");
-
- producerConnection.start();
-
- Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- MessageProducer producer = producerSession.createProducer(queue);
-
- for (int msg = 0; msg < MSG_COUNT; msg++)
- {
- producer.send(producerSession.createTextMessage("Message " + msg));
- }
-
- producerConnection.close();
-
- }
-
- protected void tearDown() throws Exception
- {
- if (_clientConnection != null)
- {
- _clientConnection.close();
- }
- super.tearDown();
- }
-
- public void testSynchronousReceive() throws Exception
- {
- for (int msg = 0; msg < MSG_COUNT; msg++)
- {
- assertTrue(_consumer.receive(2000) != null);
- }
- }
-
- public void testSynchronousReceiveNoWait() throws Exception
- {
- for (int msg = 0; msg < MSG_COUNT; msg++)
- {
- assertTrue("Failed to receive message " + msg, _consumer.receiveNoWait() != null);
- }
- }
-
- public void testAsynchronousReceive() throws Exception
- {
- _consumer.setMessageListener(this);
-
- _logger.info("Waiting 3 seconds for messages");
-
- try
- {
- _awaitMessages.await(3000, TimeUnit.MILLISECONDS);
- }
- catch (InterruptedException e)
- {
- // do nothing
- }
- // Should have received all async messages
- assertEquals(MSG_COUNT, _receivedCount);
-
- }
-
- public void testReceiveThenUseMessageListener() throws Exception
- {
- _logger.error("Test disabled as initial receive is not called first");
- // Perform initial receive to start connection
- assertTrue(_consumer.receive(2000) != null);
- _receivedCount++;
-
- // Sleep to ensure remaining 4 msgs end up on _synchronousQueue
- Thread.sleep(1000);
-
- // Set the message listener and wait for the messages to come in.
- _consumer.setMessageListener(this);
-
- _logger.info("Waiting 3 seconds for messages");
-
- try
- {
- _awaitMessages.await(3000, TimeUnit.MILLISECONDS);
- }
- catch (InterruptedException e)
- {
- // do nothing
- }
- // Should have received all async messages
- assertEquals(MSG_COUNT, _receivedCount);
-
- _clientConnection.close();
-
- Connection conn = getConnection("guest", "guest");
- Session clientSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
- Queue queue = clientSession.createQueue("message-listener-test-queue");
- MessageConsumer cons = clientSession.createConsumer(queue);
- conn.start();
-
- // check that the messages were actually dequeued
- assertTrue(cons.receive(2000) == null);
- }
-
- /**
- * Tests the case where the message listener throws an java.lang.Error.
- *
- */
- public void testMessageListenerThrowsError() throws Exception
- {
- final String javaLangErrorMessageText = "MessageListener failed with java.lang.Error";
- _clientConnection.setExceptionListener(this);
-
- _awaitMessages = new CountDownLatch(1);
-
- _consumer.setMessageListener(new MessageListener()
- {
- public void onMessage(Message message)
- {
- try
- {
- _logger.debug("onMessage called");
- _receivedCount++;
-
-
- throw new Error(javaLangErrorMessageText);
- }
- finally
- {
- _awaitMessages.countDown();
- }
- }
- });
-
-
- _logger.info("Waiting 3 seconds for message");
- _awaitMessages.await(3000, TimeUnit.MILLISECONDS);
-
- assertEquals("onMessage should have been called", 1, _receivedCount);
- assertEquals("onException should NOT have been called", 0, _errorCount);
-
- // Check that Error has been written to the application log.
-
- LogMonitor _monitor = new LogMonitor(_outputFile);
- assertTrue("The expected message not written to log file.",
- _monitor.waitForMessage(javaLangErrorMessageText, LOGMONITOR_TIMEOUT));
-
- if (_clientConnection != null)
- {
- try
- {
- _clientConnection.close();
- }
- catch (JMSException e)
- {
- // Ignore connection close errors for this test.
- }
- finally
- {
- _clientConnection = null;
- }
- }
- }
-
- public void onMessage(Message message)
- {
- _logger.info("Received Message(" + _receivedCount + "):" + message);
-
- _receivedCount++;
- _awaitMessages.countDown();
- }
-
- @Override
- public void onException(JMSException e)
- {
- _logger.info("Exception received", e);
- _errorCount++;
- }
-
- public static junit.framework.Test suite()
- {
- return new junit.framework.TestSuite(MessageListenerTest.class);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/client/MultipleJCAProviderRegistrationTest.java b/java/systests/src/main/java/org/apache/qpid/client/MultipleJCAProviderRegistrationTest.java
deleted file mode 100644
index 29b4dd82a7..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/client/MultipleJCAProviderRegistrationTest.java
+++ /dev/null
@@ -1,82 +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.client;
-
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.apache.qpid.server.registry.ConfigurationFileApplicationRegistry;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-import org.apache.qpid.client.transport.TransportConnection;
-
-import java.io.File;
-import java.security.Provider;
-import java.security.Security;
-import java.util.List;
-import java.util.LinkedList;
-
-/**
- * QPID-1394 : Test to ensure that the client can register their custom JCAProviders after the broker to ensure that
- * the Qpid custom authentication SASL plugins are used.
- */
-public class MultipleJCAProviderRegistrationTest extends QpidBrokerTestCase
-{
-
- public void setUp() throws Exception
- {
- _broker = VM;
-
- super.setUp();
- }
-
- public void test() throws Exception
- {
- // Get the providers before connection
- Provider[] providers = Security.getProviders();
-
- // Force the client to load the providers
- getConnection();
-
- Provider[] afterConnectionCreation = Security.getProviders();
-
- // Find the additions
- List additions = new LinkedList();
- for (Provider afterCreation : afterConnectionCreation)
- {
- boolean found = false;
- for (Provider provider : providers)
- {
- if (provider == afterCreation)
- {
- found=true;
- break;
- }
- }
-
- // Record added registies
- if (!found)
- {
- additions.add(afterCreation);
- }
- }
-
- assertTrue("Client did not register any providers", additions.size() > 0);
- }
-
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/client/ResetMessageListenerTest.java b/java/systests/src/main/java/org/apache/qpid/client/ResetMessageListenerTest.java
deleted file mode 100644
index 303da29389..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/client/ResetMessageListenerTest.java
+++ /dev/null
@@ -1,229 +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.client;
-
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.jms.Connection;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageListener;
-import javax.jms.MessageProducer;
-import javax.jms.Queue;
-import javax.jms.Session;
-import javax.jms.TextMessage;
-import javax.naming.Context;
-
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-/**
- * QPID-293 Setting MessageListener after connection has started can cause messages to be "lost" on a internal delivery
- * queue <p/> The message delivery process: Mina puts a message on _queue in AMQSession and the dispatcher thread
- * take()s from here and dispatches to the _consumers. If the _consumer1 doesn't have a message listener set at
- * connection start then messages are stored on _synchronousQueue (which needs to be > 1 to pass JMS TCK as multiple
- * consumers on a session can run in any order and a synchronous put/poll will block the dispatcher). <p/> When setting
- * the message listener later the _synchronousQueue is just poll()'ed and the first message delivered the remaining
- * messages will be left on the queue and lost, subsequent messages on the session will arrive first.
- */
-public class ResetMessageListenerTest extends QpidBrokerTestCase
-{
- private static final Logger _logger = LoggerFactory.getLogger(ResetMessageListenerTest.class);
-
- Context _context;
-
- private static final int MSG_COUNT = 6;
- private Connection _clientConnection, _producerConnection;
- private MessageConsumer _consumer1;
- MessageProducer _producer;
- Session _clientSession, _producerSession;
-
- private final CountDownLatch _allFirstMessagesSent = new CountDownLatch(MSG_COUNT); // all messages Sent Lock
- private final CountDownLatch _allSecondMessagesSent = new CountDownLatch(MSG_COUNT); // all messages Sent Lock
-
- protected void setUp() throws Exception
- {
- super.setUp();
-
- _clientConnection = getConnection("guest", "guest");
- _clientConnection.start();
- // Create Client 1
-
- _clientSession = _clientConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- Queue queue = _clientSession.createQueue("reset-message-listener-test-queue");
-
- _consumer1 = _clientSession.createConsumer(queue);
-
- // Create Producer
- _producerConnection = getConnection("guest", "guest");
-
- _producerConnection.start();
-
- _producerSession = _producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- _producer = _producerSession.createProducer(queue);
-
- TextMessage m = _producerSession.createTextMessage();
- m.setStringProperty("rank", "first");
- for (int msg = 0; msg < MSG_COUNT; msg++)
- {
- m.setText("Message " + msg);
- _producer.send(m);
- }
- }
-
- protected void tearDown() throws Exception
- {
- _clientConnection.close();
-
- super.tearDown();
- }
-
- public void testAsynchronousRecieve()
- {
-
- _logger.info("Test Start");
-
- try
- {
- _consumer1.setMessageListener(new MessageListener()
- {
- public void onMessage(Message message)
- {
- try
- {
- if (message.getStringProperty("rank").equals("first"))
- {
- _allFirstMessagesSent.countDown();
- }
- }
- catch (JMSException e)
- {
- e.printStackTrace();
- fail("error receiving message");
- }
- }
- });
- }
- catch (JMSException e)
- {
- _logger.error("Error Setting Default ML on consumer1");
- }
- try
- {
- assertTrue("Did not receive all first batch of messages",
- _allFirstMessagesSent.await(1000, TimeUnit.MILLISECONDS));
- _logger.info("Received first batch of messages");
- }
- catch (InterruptedException e)
- {
- // do nothing
- }
-
- try
- {
- _clientConnection.stop();
- }
- catch (JMSException e)
- {
- _logger.error("Error stopping connection");
- }
-
- _logger.info("Reset Message Listener ");
- try
- {
- _consumer1.setMessageListener(new MessageListener()
- {
- public void onMessage(Message message)
- {
- try
- {
- if (message.getStringProperty("rank").equals("first"))
- {
- // Something ugly will happen, it'll probably kill the dispatcher
- fail("All first set of messages should have been received");
- }
- else
- {
- _allSecondMessagesSent.countDown();
- }
- }
- catch (JMSException e)
- {
- e.printStackTrace();
- // Something ugly will happen, it'll probably kill the dispatcher
- fail("error receiving message");
- }
- }
- });
-
- _clientConnection.start();
- }
- catch (javax.jms.IllegalStateException e)
- {
- _logger.error("Connection not stopped while setting ML", e);
- fail("Unable to change message listener:" + e.getCause());
- }
- catch (JMSException e)
- {
- _logger.error("Error Setting Better ML on consumer1", e);
- }
-
- try
- {
- _logger.info("Send additional messages");
- TextMessage m = _producerSession.createTextMessage();
- m.setStringProperty("rank", "second");
- for (int msg = 0; msg < MSG_COUNT; msg++)
- {
- m.setText("Message " + msg);
- _producer.send(m);
- }
- }
- catch (JMSException e)
- {
- _logger.error("Unable to send additional messages", e);
- }
-
- _logger.info("Waiting for messages");
-
- try
- {
- assertTrue(_allSecondMessagesSent.await(1000, TimeUnit.MILLISECONDS));
- }
- catch (InterruptedException e)
- {
- // do nothing
- }
- assertEquals("First batch of messages not received correctly", 0, _allFirstMessagesSent.getCount());
- assertEquals("Second batch of messages not received correctly", 0, _allSecondMessagesSent.getCount());
- }
-
- public static junit.framework.Test suite()
- {
- return new junit.framework.TestSuite(ResetMessageListenerTest.class);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/client/SessionCreateTest.java b/java/systests/src/main/java/org/apache/qpid/client/SessionCreateTest.java
deleted file mode 100644
index 15900a17fe..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/client/SessionCreateTest.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.client;
-
-import javax.jms.Connection;
-import javax.jms.Session;
-import javax.naming.Context;
-
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-
-/**
- * Class to check that session creation on a connection has no accidental limit
- */
-public class SessionCreateTest extends QpidBrokerTestCase
-{
- private static final Logger _logger = LoggerFactory.getLogger(MessageListenerTest.class);
-
- Context _context;
-
- private Connection _clientConnection;
- protected int maxSessions = 65555;
-
- public void testSessionCreationLimit() throws Exception
- {
- // Create Client
- _clientConnection = getConnection("guest", "guest");
-
- _clientConnection.start();
-
- for (int i=0; i < maxSessions; i++)
- {
- Session sess = _clientConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- assertNotNull(sess);
- sess.close();
- System.out.println("created session: " + i);
- }
-
- _clientConnection.close();
-
- }
-
-} \ No newline at end of file
diff --git a/java/systests/src/main/java/org/apache/qpid/client/message/AMQPEncodedMapMessageTest.java b/java/systests/src/main/java/org/apache/qpid/client/message/AMQPEncodedMapMessageTest.java
deleted file mode 100644
index bf96dae02e..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/client/message/AMQPEncodedMapMessageTest.java
+++ /dev/null
@@ -1,283 +0,0 @@
-package org.apache.qpid.client.message;
-/*
- *
- * 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 java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.UUID;
-
-import javax.jms.Connection;
-import javax.jms.JMSException;
-import javax.jms.MapMessage;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-import javax.jms.Queue;
-import javax.jms.Session;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.client.message.AMQPEncodedMapMessage;
-import org.apache.qpid.client.message.AbstractJMSMessage;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.ProtocolVersion;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-
-public class AMQPEncodedMapMessageTest extends QpidBrokerTestCase
-{
- private Connection _connection;
- private Session _session;
- MessageConsumer _consumer;
- MessageProducer _producer;
- UUID myUUID = UUID.randomUUID();
-
- public void setUp() throws Exception
- {
- super.setUp();
-
- //Create Connection
- _connection = getConnection();
-
- //Create Session
- _session = _connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- //Create Queue
- String queueName = getTestQueueName();
- Queue queue = _session.createQueue(queueName);
-
- //Create Consumer
- _consumer = _session.createConsumer(queue);
-
- //Create Producer
- _producer = _session.createProducer(queue);
-
- _connection.start();
- }
-
- public void testEmptyMessage() throws JMSException
- {
- MapMessage m = _session.createMapMessage();
- _producer.send(m);
- AMQPEncodedMapMessage msg = (AMQPEncodedMapMessage)_consumer.receive(RECEIVE_TIMEOUT);
- assertNotNull("Message was not received on time",msg);
- assertEquals("Message content-type is incorrect",
- AMQPEncodedMapMessage.MIME_TYPE,
- ((AbstractJMSMessage)msg).getContentType());
-
- assertEquals("Message content should be an empty map",
- Collections.EMPTY_MAP,
- ((AMQPEncodedMapMessage)msg).getMap());
- }
-
- public void testNullMessage() throws JMSException
- {
- MapMessage m = _session.createMapMessage();
- ((AMQPEncodedMapMessage)m).setMap(null);
- _producer.send(m);
- AMQPEncodedMapMessage msg = (AMQPEncodedMapMessage)_consumer.receive(RECEIVE_TIMEOUT);
- assertNotNull("Message was not received on time",msg);
- assertEquals("Message content-type is incorrect",
- AMQPEncodedMapMessage.MIME_TYPE,
- ((AbstractJMSMessage)msg).getContentType());
-
- assertEquals("Message content should be null",
- null,
- ((AMQPEncodedMapMessage)msg).getMap());
-
- }
-
- public void testMessageWithContent() throws JMSException
- {
- MapMessage m = _session.createMapMessage();
- m.setBoolean("Boolean", true);
- m.setByte("Byte", (byte)5);
- byte[] bytes = new byte[]{(byte)5,(byte)8};
- m.setBytes("Bytes", bytes);
- m.setChar("Char", 'X');
- m.setDouble("Double", 56.84);
- m.setFloat("Float", Integer.MAX_VALUE + 5000);
- m.setInt("Int", Integer.MAX_VALUE - 5000);
- m.setShort("Short", (short)58);
- m.setString("String", "Hello");
- m.setObject("uuid", myUUID);
- _producer.send(m);
-
- AMQPEncodedMapMessage msg = (AMQPEncodedMapMessage)_consumer.receive(RECEIVE_TIMEOUT);
- assertNotNull("Message was not received on time",msg);
- assertEquals("Message content-type is incorrect",
- AMQPEncodedMapMessage.MIME_TYPE,
- ((AbstractJMSMessage)msg).getContentType());
-
- assertEquals(true,m.getBoolean("Boolean"));
- assertEquals((byte)5,m.getByte("Byte"));
- byte[] bytesRcv = m.getBytes("Bytes");
- assertNotNull("Byte array is null",bytesRcv);
- assertEquals((byte)5,bytesRcv[0]);
- assertEquals((byte)8,bytesRcv[1]);
- assertEquals('X',m.getChar("Char"));
- assertEquals(56.84,m.getDouble("Double"));
- //assertEquals(Integer.MAX_VALUE + 5000,m.getFloat("Float"));
- assertEquals(Integer.MAX_VALUE - 5000,m.getInt("Int"));
- assertEquals((short)58,m.getShort("Short"));
- assertEquals("Hello",m.getString("String"));
- assertEquals(myUUID,(UUID)m.getObject("uuid"));
- }
-
-
- public void testMessageWithListEntries() throws JMSException
- {
- MapMessage m = _session.createMapMessage();
-
- List<Integer> myList = getList();
-
- m.setObject("List", myList);
-
- List<UUID> uuidList = new ArrayList<UUID>();
- uuidList.add(myUUID);
- m.setObject("uuid-list", uuidList);
- _producer.send(m);
-
- AMQPEncodedMapMessage msg = (AMQPEncodedMapMessage)_consumer.receive(RECEIVE_TIMEOUT);
- assertNotNull("Message was not received on time",msg);
- assertEquals("Message content-type is incorrect",
- AMQPEncodedMapMessage.MIME_TYPE,
- ((AbstractJMSMessage)msg).getContentType());
-
- List<Integer> list = (List<Integer>)msg.getObject("List");
- assertNotNull("List not received",list);
- Collections.sort(list);
- int i = 1;
- for (Integer j: list)
- {
- assertEquals(i,j.intValue());
- i++;
- }
-
- List<UUID> list2 = (List<UUID>)msg.getObject("uuid-list");
- assertNotNull("UUID List not received",list2);
- assertEquals(myUUID,list2.get(0));
- }
-
- public void testMessageWithMapEntries() throws JMSException
- {
- MapMessage m = _session.createMapMessage();
-
- Map<String,String> myMap = getMap();
- m.setObject("Map", myMap);
-
- Map<String,UUID> uuidMap = new HashMap<String,UUID>();
- uuidMap.put("uuid", myUUID);
- m.setObject("uuid-map", uuidMap);
-
- _producer.send(m);
-
- AMQPEncodedMapMessage msg = (AMQPEncodedMapMessage)_consumer.receive(RECEIVE_TIMEOUT);
- assertNotNull("Message was not received on time",msg);
- assertEquals("Message content-type is incorrect",
- AMQPEncodedMapMessage.MIME_TYPE,
- ((AbstractJMSMessage)msg).getContentType());
-
- Map<String,String> map = (Map<String,String>)msg.getObject("Map");
- assertNotNull("Map not received",map);
- for (int i=1; i <4; i++ )
- {
- assertEquals("String" + i,map.get("Key" + i));
- i++;
- }
-
- Map<String,UUID> map2 = (Map<String,UUID>)msg.getObject("uuid-map");
- assertNotNull("Map not received",map2);
- assertEquals(myUUID,map2.get("uuid"));
- }
-
- public void testMessageWithNestedListsAndMaps() throws JMSException
- {
- MapMessage m = _session.createMapMessage();
-
- Map<String,Object> myMap = new HashMap<String,Object>();
- myMap.put("map", getMap());
- myMap.put("list", getList());
-
- m.setObject("Map", myMap);
- _producer.send(m);
-
- AMQPEncodedMapMessage msg = (AMQPEncodedMapMessage)_consumer.receive(RECEIVE_TIMEOUT);
- assertNotNull("Message was not received on time",msg);
- assertEquals("Message content-type is incorrect",
- AMQPEncodedMapMessage.MIME_TYPE,
- ((AbstractJMSMessage)msg).getContentType());
-
- Map<String,Object> mainMap = (Map<String,Object>)msg.getObject("Map");
- assertNotNull("Main Map not received",mainMap);
-
- Map<String,String> map = (Map<String,String>)mainMap.get("map");
- assertNotNull("Nested Map not received",map);
- for (int i=1; i <4; i++ )
- {
- assertEquals("String" + i,map.get("Key" + i));
- i++;
- }
-
- List<Integer> list = (List<Integer>)mainMap.get("list");
- assertNotNull("Nested List not received",list);
- Collections.sort(list);
-
- int i = 1;
- for (Integer j: list)
- {
- assertEquals(i,j.intValue());
- i++;
- }
- }
-
- private List<Integer> getList()
- {
- List<Integer> myList = new ArrayList<Integer>();
- myList.add(1);
- myList.add(2);
- myList.add(3);
-
- return myList;
- }
-
- private Map<String,String> getMap()
- {
- Map<String,String> myMap = new HashMap<String,String>();
- myMap.put("Key1","String1");
- myMap.put("Key2","String2");
- myMap.put("Key3","String3");
-
- return myMap;
- }
-
- public void tearDown() throws Exception
- {
- //clean up
- _connection.close();
-
- super.tearDown();
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/client/message/NonQpidObjectMessage.java b/java/systests/src/main/java/org/apache/qpid/client/message/NonQpidObjectMessage.java
deleted file mode 100644
index 857adaf82c..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/client/message/NonQpidObjectMessage.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.client.message;
-
-import java.io.Serializable;
-import java.util.Enumeration;
-
-import javax.jms.Destination;
-import javax.jms.JMSException;
-import javax.jms.ObjectMessage;
-import javax.jms.Session;
-
-public class NonQpidObjectMessage implements ObjectMessage {
-
- private ObjectMessage _realMessage;
- private String _contentString;
-
- /**
- * Allows us to construct a JMS message which
- * does not inherit from the Qpid message superclasses
- * and expand our unit testing of MessageConverter et al
- * @param session
- */
- public NonQpidObjectMessage(Session session) throws JMSException
- {
- _realMessage = session.createObjectMessage();
- }
-
- public String getJMSMessageID() throws JMSException {
- return _realMessage.getJMSMessageID();
- }
-
- public void setJMSMessageID(String string) throws JMSException {
- _realMessage.setJMSMessageID(string);
- }
-
- public long getJMSTimestamp() throws JMSException {
- return _realMessage.getJMSTimestamp();
- }
-
- public void setJMSTimestamp(long l) throws JMSException {
- _realMessage.setJMSTimestamp(l);
- }
-
- public byte[] getJMSCorrelationIDAsBytes() throws JMSException {
- return _realMessage.getJMSCorrelationIDAsBytes();
- }
-
- public void setJMSCorrelationIDAsBytes(byte[] bytes) throws JMSException {
- _realMessage.setJMSCorrelationIDAsBytes(bytes);
- }
-
- public void setJMSCorrelationID(String string) throws JMSException {
- _realMessage.setJMSCorrelationID(string);
- }
-
- public String getJMSCorrelationID() throws JMSException {
- return _realMessage.getJMSCorrelationID();
- }
-
- public Destination getJMSReplyTo() throws JMSException {
- return _realMessage.getJMSReplyTo();
- }
-
- public void setJMSReplyTo(Destination destination) throws JMSException {
- _realMessage.setJMSReplyTo(destination);
- }
-
- public Destination getJMSDestination() throws JMSException {
- return _realMessage.getJMSDestination();
- }
-
- public void setJMSDestination(Destination destination) throws JMSException {
- _realMessage.setJMSDestination(destination);
- }
-
- public int getJMSDeliveryMode() throws JMSException {
- return _realMessage.getJMSDeliveryMode();
- }
-
- public void setJMSDeliveryMode(int i) throws JMSException {
- _realMessage.setJMSDeliveryMode(i);
- }
-
- public boolean getJMSRedelivered() throws JMSException {
- return _realMessage.getJMSRedelivered();
- }
-
- public void setJMSRedelivered(boolean b) throws JMSException {
- _realMessage.setJMSRedelivered(b);
- }
-
- public String getJMSType() throws JMSException {
- return _realMessage.getJMSType();
- }
-
- public void setJMSType(String string) throws JMSException {
- _realMessage.setJMSType(string);
- }
-
- public long getJMSExpiration() throws JMSException {
- return _realMessage.getJMSExpiration();
- }
-
- public void setJMSExpiration(long l) throws JMSException {
- _realMessage.setJMSExpiration(l);
- }
-
- public int getJMSPriority() throws JMSException {
- return _realMessage.getJMSPriority();
- }
-
- public void setJMSPriority(int i) throws JMSException {
- _realMessage.setJMSPriority(i);
- }
-
- public void clearProperties() throws JMSException {
- _realMessage.clearProperties();
- }
-
- public boolean propertyExists(String string) throws JMSException {
- return _realMessage.propertyExists(string);
- }
-
- public boolean getBooleanProperty(String string) throws JMSException {
- return _realMessage.getBooleanProperty(string);
- }
-
- public byte getByteProperty(String string) throws JMSException {
- return _realMessage.getByteProperty(string);
- }
-
- public short getShortProperty(String string) throws JMSException {
- return _realMessage.getShortProperty(string);
- }
-
- public int getIntProperty(String string) throws JMSException {
- return _realMessage.getIntProperty(string);
- }
-
- public long getLongProperty(String string) throws JMSException {
- return _realMessage.getLongProperty(string);
- }
-
- public float getFloatProperty(String string) throws JMSException {
- return _realMessage.getFloatProperty(string);
- }
-
- public double getDoubleProperty(String string) throws JMSException {
- return _realMessage.getDoubleProperty(string);
- }
-
- public String getStringProperty(String string) throws JMSException {
- return _realMessage.getStringProperty(string);
- }
-
- public Object getObjectProperty(String string) throws JMSException {
- return _realMessage.getObjectProperty(string);
- }
-
- public Enumeration getPropertyNames() throws JMSException {
- return _realMessage.getPropertyNames();
- }
-
- public void setBooleanProperty(String string, boolean b) throws JMSException {
- _realMessage.setBooleanProperty(string,b);
- }
-
- public void setByteProperty(String string, byte b) throws JMSException {
- _realMessage.setByteProperty(string,b);
- }
-
- public void setShortProperty(String string, short i) throws JMSException {
- _realMessage.setShortProperty(string,i);
- }
-
- public void setIntProperty(String string, int i) throws JMSException {
- _realMessage.setIntProperty(string,i);
- }
-
- public void setLongProperty(String string, long l) throws JMSException {
- _realMessage.setLongProperty(string,l);
- }
-
- public void setFloatProperty(String string, float v) throws JMSException {
- _realMessage.setFloatProperty(string,v);
- }
-
- public void setDoubleProperty(String string, double v) throws JMSException {
- _realMessage.setDoubleProperty(string,v);
- }
-
- public void setStringProperty(String string, String string1) throws JMSException {
- _realMessage.setStringProperty(string,string1);
- }
-
- public void setObjectProperty(String string, Object object) throws JMSException {
- _realMessage.setObjectProperty(string,object);
- }
-
- public void acknowledge() throws JMSException {
- _realMessage.acknowledge();
- }
-
- public void clearBody() throws JMSException {
- _realMessage.clearBody();
- }
-
- public void setObject(Serializable serializable) throws JMSException {
- if (serializable instanceof String)
- {
- _contentString = (String)serializable;
- }
- }
-
- public Serializable getObject() throws JMSException {
- return _contentString; }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/client/ssl/SSLTest.java b/java/systests/src/main/java/org/apache/qpid/client/ssl/SSLTest.java
deleted file mode 100644
index 8cdf12eaa4..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/client/ssl/SSLTest.java
+++ /dev/null
@@ -1,181 +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.client.ssl;
-
-import java.io.ByteArrayOutputStream;
-import java.io.PrintStream;
-
-import javax.jms.Session;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQTestConnection_0_10;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.apache.qpid.transport.Connection;
-
-public class SSLTest extends QpidBrokerTestCase
-{
-
- @Override
- protected void setUp() throws Exception
- {
- System.setProperty("javax.net.debug", "ssl");
- super.setUp();
- }
-
- @Override
- protected void tearDown() throws Exception
- {
- System.setProperty("javax.net.debug", "");
- super.tearDown();
- }
-
- public void testCreateSSLContextFromConnectionURLParams()
- {
- if (Boolean.getBoolean("profile.use_ssl"))
- {
- String url = "amqp://guest:guest@test/?brokerlist='tcp://localhost:%s" +
- "?ssl='true'&ssl_verify_hostname='true'" +
- "&key_store='%s'&key_store_password='%s'" +
- "&trust_store='%s'&trust_store_password='%s'" +
- "'";
-
- String keyStore = System.getProperty("javax.net.ssl.keyStore");
- String keyStorePass = System.getProperty("javax.net.ssl.keyStorePassword");
- String trustStore = System.getProperty("javax.net.ssl.trustStore");
- String trustStorePass = System.getProperty("javax.net.ssl.trustStorePassword");
-
- url = String.format(url,System.getProperty("test.port.ssl"),
- keyStore,keyStorePass,trustStore,trustStorePass);
-
- // temporarily set the trust/key store jvm args to something else
- // to ensure we only read from the connection URL param.
- System.setProperty("javax.net.ssl.trustStore","fessgsdgd");
- System.setProperty("javax.net.ssl.trustStorePassword","fessgsdgd");
- System.setProperty("javax.net.ssl.keyStore","fessgsdgd");
- System.setProperty("javax.net.ssl.keyStorePassword","fessgsdgd");
- try
- {
- AMQConnection con = new AMQConnection(url);
- Session ssn = con.createSession(false,Session.AUTO_ACKNOWLEDGE);
- }
- catch (Exception e)
- {
- fail("SSL Connection should be successful");
- }
- finally
- {
- System.setProperty("javax.net.ssl.trustStore",trustStore);
- System.setProperty("javax.net.ssl.trustStorePassword",trustStorePass);
- System.setProperty("javax.net.ssl.keyStore",keyStore);
- System.setProperty("javax.net.ssl.keyStorePassword",keyStorePass);
- }
- }
- }
-
- public void testMultipleCertsInSingleStore() throws Exception
- {
- if (Boolean.getBoolean("profile.use_ssl"))
- {
- String url = "amqp://guest:guest@test/?brokerlist='tcp://localhost:" +
- System.getProperty("test.port.ssl") +
- "?ssl='true'&ssl_cert_alias='app1''";
-
- AMQTestConnection_0_10 con = new AMQTestConnection_0_10(url);
- Connection transportCon = con.getConnection();
- String userID = transportCon.getSecurityLayer().getUserID();
- assertEquals("The correct certificate was not choosen","app1@acme.org",userID);
- con.close();
-
- url = "amqp://guest:guest@test/?brokerlist='tcp://localhost:" +
- System.getProperty("test.port.ssl") +
- "?ssl='true'&ssl_cert_alias='app2''";
-
- con = new AMQTestConnection_0_10(url);
- transportCon = con.getConnection();
- userID = transportCon.getSecurityLayer().getUserID();
- assertEquals("The correct certificate was not choosen","app2@acme.org",userID);
- con.close();
- }
- }
-
- public void testVerifyHostName()
- {
- if (Boolean.getBoolean("profile.use_ssl"))
- {
- String url = "amqp://guest:guest@test/?brokerlist='tcp://127.0.0.1:" +
- System.getProperty("test.port.ssl") +
- "?ssl='true'&ssl_verify_hostname='true''";
-
- try
- {
- AMQConnection con = new AMQConnection(url);
- fail("Hostname verification failed. No exception was thrown");
- }
- catch (Exception e)
- {
- ByteArrayOutputStream bout = new ByteArrayOutputStream();
- e.printStackTrace(new PrintStream(bout));
- String strace = bout.toString();
- assertTrue("Correct exception not thrown",strace.contains("SSL hostname verification failed"));
- }
-
- }
- }
-
- public void testVerifyLocalHost()
- {
- if (Boolean.getBoolean("profile.use_ssl"))
- {
- String url = "amqp://guest:guest@test/?brokerlist='tcp://localhost:" +
- System.getProperty("test.port.ssl") +
- "?ssl='true'&ssl_verify_hostname='true''";
-
- try
- {
- AMQConnection con = new AMQConnection(url);
- }
- catch (Exception e)
- {
- fail("Hostname verification should succeed");
- }
- }
- }
-
- public void testVerifyLocalHostLocalDomain()
- {
- if (Boolean.getBoolean("profile.use_ssl"))
- {
- String url = "amqp://guest:guest@test/?brokerlist='tcp://localhost.localdomain:" +
- System.getProperty("test.port.ssl") +
- "?ssl='true'&ssl_verify_hostname='true''";
-
- try
- {
- AMQConnection con = new AMQConnection(url);
- }
- catch (Exception e)
- {
- fail("Hostname verification should succeed");
- }
-
- }
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/management/jmx/ManagementActorLoggingTest.java b/java/systests/src/main/java/org/apache/qpid/management/jmx/ManagementActorLoggingTest.java
deleted file mode 100644
index 19657ef396..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/management/jmx/ManagementActorLoggingTest.java
+++ /dev/null
@@ -1,536 +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.management.jmx;
-
-import org.apache.qpid.management.common.mbeans.ManagedBroker;
-import org.apache.qpid.management.common.mbeans.ManagedConnection;
-import org.apache.qpid.management.common.mbeans.ManagedExchange;
-import org.apache.qpid.server.logging.AbstractTestLogging;
-import org.apache.qpid.server.logging.subjects.AbstractTestLogSubject;
-import org.apache.qpid.test.utils.JMXTestUtils;
-
-import javax.jms.Connection;
-import javax.jms.ExceptionListener;
-import javax.jms.JMSException;
-import javax.management.JMException;
-import java.io.IOException;
-import java.util.List;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-/**
- * Test class to test if any change in the broker JMX code is affesting the management console
- * There are some hardcoding of management feature names and parameter names to create a customized
- * look in the console.
- */
-public class ManagementActorLoggingTest extends AbstractTestLogging
-{
- private JMXTestUtils _jmxUtils;
- private boolean _closed = false;
- private static final String USER = "admin";
-
- @Override
- public void setUp() throws Exception
- {
- _jmxUtils = new JMXTestUtils(this, USER, USER);
- _jmxUtils.setUp();
- super.setUp();
- _jmxUtils.open();
- }
-
- @Override
- public void tearDown() throws Exception
- {
- if(!_closed)
- {
- _jmxUtils.close();
- }
- super.tearDown();
- }
-
- /**
- * Description:
- * When a JMX Management connection is made then this will be logged out.
- *
- * Input:
- *
- * 1. Running Broker
- * 2. Connect Management client via JMX
- * Output:
- *
- * <date> MNG-1007 : Open <user>
- *
- * Validation Steps:
- * 1. The MNG ID is correct
- * 2. The user is correct
- *
- * On connection close a MNG-1008 is expected
- *
- * * <date> MNG-1008 : Close
- *
- * Validation Steps:
- * 1. The MNG ID is correct
- *
- * @throws java.io.IOException - if there is a problem reseting the log monitor
- */
- public void testJMXManagementConsoleConnection() throws IOException
- {
- List<String> results = waitAndFindMatches("MNG-1007");
-
- assertEquals("Unexpected Management Connection count", 1, results.size());
-
- String log = getLogMessage(results, 0);
-
- validateMessageID("MNG-1007", log);
-
- assertTrue("User not in log message:" + log, log.endsWith(USER));
- // Extract the id from the log string
- // MESSAGE [mng:1(rmi://169.24.29.116)] MNG-1007 : Open : User admin
- int connectionID = Integer.parseInt(fromActor(getLog(results.get(0))).charAt(4) + "");
-
- results = findMatches("MNG-1008");
-
- assertEquals("Unexpected Management Connection close count", 0, results.size());
-
- _jmxUtils.close();
- _closed = true;
-
- results = waitAndFindMatches("MNG-1008");
-
- assertEquals("Unexpected Management Connection count", 1, results.size());
-
- assertEquals("Close does not have same id as open,", connectionID,
- Integer.parseInt(fromActor(getLog(results.get(0))).charAt(4) + ""));
- }
-
- /**
- * Description:
- * When a connected client has its connection closed via the Management Console this will be logged as a CON-1002 message.
- * Input:
- *
- * 1. Running Broker
- * 2. Connected Client
- * 3. Connection is closed via Management Console
- * Output:
- *
- * <date> CON-1002 : Close
- *
- * Validation Steps:
- * 4. The CON ID is correct
- * 5. This must be the last CON message for the Connection
- * 6. It must be preceded by a CON-1001 for this Connection
- *
- * @throws Exception - {@see ManagedConnection.closeConnection and #getConnection}
- * @throws java.io.IOException - if there is a problem reseting the log monitor
- */
- public void testConnectionCloseViaManagement() throws IOException, Exception
- {
- //Create a connection to the broker
- Connection connection = getConnection();
-
- // Monitor the connection for an exception being thrown
- // this should be a DisconnectionException but it is not this tests
- // job to valiate that. Only use the exception as a synchronisation
- // to check the log file for the Close message
- final CountDownLatch exceptionReceived = new CountDownLatch(1);
- connection.setExceptionListener(new ExceptionListener()
- {
- public void onException(JMSException e)
- {
- //Failover being attempted.
- exceptionReceived.countDown();
- }
- });
-
- //Remove the connection close from any 0-10 connections
- _monitor.reset();
-
- // Get a managedConnection
- ManagedConnection mangedConnection = _jmxUtils.getManagedObject(ManagedConnection.class, "org.apache.qpid:type=VirtualHost.Connection,*");
-
- //Close the connection
- mangedConnection.closeConnection();
-
- //Wait for the connection to close
- assertTrue("Timed out waiting for conneciton to report close",
- exceptionReceived.await(2, TimeUnit.SECONDS));
-
- //Validate results
- List<String> results = waitAndFindMatches("CON-1002");
-
- assertEquals("Unexpected Connection Close count", 1, results.size());
- }
-
- /**
- * Description:
- * Exchange creation is possible from the Management Console.
- * When an exchanged is created in this way then a EXH-1001 create message
- * is expected to be logged.
- * Input:
- *
- * 1. Running broker
- * 2. Connected Management Console
- * 3. Exchange Created via Management Console
- * Output:
- *
- * EXH-1001 : Create : [Durable] Type:<value> Name:<value>
- *
- * Validation Steps:
- * 4. The EXH ID is correct
- * 5. The correct tags are present in the message based on the create options
- *
- * @throws java.io.IOException - if there is a problem reseting the log monitor
- * @throws javax.management.JMException - {@see #createQueue and ManagedExchange.deleteQueue}
- */
- public void testCreateExchangeDirectTransientViaManagementConsole() throws IOException, JMException
- {
- _monitor.reset();
-
- _jmxUtils.createExchange("test", getName(), "direct", false);
-
- // Validate
-
- //1 - ID is correct
- List<String> results = waitAndFindMatches("EXH-1001");
-
- assertEquals("More than one exchange creation found", 1, results.size());
-
- String log = getLogMessage(results, 0);
-
- // Validate correct exchange name
- assertTrue("Incorrect exchange name created:" + log, log.endsWith(getName()));
-
- // Validate it was a management actor.
- String actor = fromActor(log);
- assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng"));
- }
-
- public void testCreateExchangeTopicTransientViaManagementConsole() throws IOException, JMException
- {
- //Remove any previous exchange declares
- _monitor.reset();
-
- _jmxUtils.createExchange("test", getName(), "topic", false);
-
- // Validate
-
- //1 - ID is correct
- List<String> results = waitAndFindMatches("EXH-1001");
-
- assertEquals("More than one exchange creation found", 1, results.size());
-
- String log = getLogMessage(results, 0);
-
- // Validate correct exchange name
- assertTrue("Incorrect exchange name created:" + log, log.endsWith(getName()));
-
- // Validate it was a management actor.
- String actor = fromActor(log);
- assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng"));
-
- }
-
- public void testCreateExchangeFanoutTransientViaManagementConsole() throws IOException, JMException
- {
- //Remove any previous exchange declares
- _monitor.reset();
-
- _jmxUtils.createExchange("test", getName(), "fanout", false);
-
- // Validate
-
- //1 - ID is correct
- List<String> results = waitAndFindMatches("EXH-1001");
-
- assertEquals("More than one exchange creation found", 1, results.size());
-
- String log = getLogMessage(results, 0);
-
- // Validate correct exchange name
- assertTrue("Incorrect exchange name created:" + log, log.endsWith(getName()));
-
- // Validate it was a management actor.
- String actor = fromActor(log);
- assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng"));
-
- }
-
- public void testCreateExchangeHeadersTransientViaManagementConsole() throws IOException, JMException
- {
- //Remove any previous exchange declares
- _monitor.reset();
-
- _jmxUtils.createExchange("test", getName(), "headers", false);
-
- // Validate
-
- //1 - ID is correct
- List<String> results = waitAndFindMatches("EXH-1001");
-
- assertEquals("More than one exchange creation found", 1, results.size());
-
- String log = getLogMessage(results, 0);
-
- // Validate correct exchange name
- assertTrue("Incorrect exchange name created:" + log, log.endsWith(getName()));
-
- // Validate it was a management actor.
- String actor = fromActor(log);
- assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng"));
-
- }
-
- /**
- * Description:
- * Queue creation is possible from the Management Console. When a queue is created in this way then a QUE-1001 create message is expected to be logged.
- * Input:
- *
- * 1. Running broker
- * 2. Connected Management Console
- * 3. Queue Created via Management Console
- * Output:
- *
- * <date> QUE-1001 : Create : Transient Owner:<name>
- *
- * Validation Steps:
- * 4. The QUE ID is correct
- * 5. The correct tags are present in the message based on the create options
- *
- * @throws java.io.IOException - if there is a problem reseting the log monitor
- * @throws javax.management.JMException - {@see #createQueue and ManagedExchange.deleteQueue}
- */
- public void testCreateQueueTransientViaManagementConsole() throws IOException, JMException
- {
- //Remove any previous queue declares
- _monitor.reset();
-
- _jmxUtils.createQueue("test", getName(), null, false);
-
- // Validate
-
- List<String> results = waitAndFindMatches("QUE-1001");
-
- assertEquals("More than one queue creation found", 1, results.size());
-
- String log = getLogMessage(results, 0);
-
- // Validate correct queue name
- String subject = fromSubject(log);
- assertEquals("Incorrect queue name created", getName(), AbstractTestLogSubject.getSlice("qu", subject));
-
- // Validate it was a management actor.
- String actor = fromActor(log);
- assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng"));
- }
-
- /**
- * Description:
- * The ManagementConsole can be used to delete a queue. When this is done a QUE-1002 Deleted message must be logged.
- * Input:
- *
- * 1. Running Broker
- * 2. Queue created on the broker with no subscribers
- * 3. Management Console connected
- * 4. Queue is deleted via Management Console
- * Output:
- *
- * <date> QUE-1002 : Deleted
- *
- * Validation Steps:
- * 5. The QUE ID is correct
- *
- * @throws java.io.IOException - if there is a problem reseting the log monitor
- * @throws javax.management.JMException - {@see #createQueue and ManagedExchange.deleteQueue}
- */
- public void testQueueDeleteViaManagementConsole() throws IOException, JMException
- {
- //Remove any previous queue declares
- _monitor.reset();
-
- _jmxUtils.createQueue("test", getName(), null, false);
-
- ManagedBroker managedBroker = _jmxUtils.getManagedBroker("test");
-
- managedBroker.deleteQueue(getName());
-
- List<String> results = waitAndFindMatches("QUE-1002");
-
- assertEquals("More than one queue deletion found", 1, results.size());
-
- String log = getLog(results.get(0));
-
- // Validate correct binding
- String subject = fromSubject(log);
- assertEquals("Incorrect queue named in delete", getName(), AbstractTestLogSubject.getSlice("qu", subject));
-
- // Validate it was a management actor.
- String actor = fromActor(log);
- assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng"));
-
- }
-
- /**
- * Description:
- * The binding of a Queue and an Exchange is done via a Binding. When this Binding is created via the Management Console a BND-1001 Create message will be logged.
- * Input:
- *
- * 1. Running Broker
- * 2. Connected Management Console
- * 3. Use Management Console to perform binding
- * Output:
- *
- * <date> BND-1001 : Create
- *
- * Validation Steps:
- * 4. The BND ID is correct
- * 5. This will be the first message for the given binding
- *
- * @throws java.io.IOException - if there is a problem reseting the log monitor
- * @throws javax.management.JMException - {@see #createQueue and ManagedExchange.createNewBinding}
- */
- public void testBindingCreateOnDirectViaManagementConsole() throws IOException, JMException
- {
- //Remove any previous queue declares
- _monitor.reset();
-
- _jmxUtils.createQueue("test", getName(), null, false);
-
- ManagedExchange managedExchange = _jmxUtils.getManagedExchange("amq.direct");
-
- managedExchange.createNewBinding(getName(), getName());
-
- List<String> results = waitAndFindMatches("BND-1001");
-
- assertEquals("More than one bind creation found", 1, results.size());
-
- String log = getLogMessage(results, 0);
-
- // Validate correct binding
- String subject = fromSubject(log);
- assertEquals("Incorrect queue named in create", getName(), AbstractTestLogSubject.getSlice("qu", subject));
- assertEquals("Incorrect routing key in create", getName(), AbstractTestLogSubject.getSlice("rk", subject));
-
- // Validate it was a management actor.
- String actor = fromActor(log);
- assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng"));
- }
-
- public void testBindingCreateOnTopicViaManagementConsole() throws IOException, JMException
- {
- //Remove any previous queue declares
- _monitor.reset();
-
- _jmxUtils.createQueue("test", getName(), null, false);
-
- ManagedExchange managedExchange = _jmxUtils.getManagedExchange("amq.topic");
-
- managedExchange.createNewBinding(getName(), getName());
-
- List<String> results = waitAndFindMatches("BND-1001");
-
- assertEquals("More than one bind creation found", 1, results.size());
-
- String log = getLogMessage(results, 0);
-
- // Validate correct binding
- String subject = fromSubject(log);
- assertEquals("Incorrect queue named in create", getName(), AbstractTestLogSubject.getSlice("qu", subject));
- assertEquals("Incorrect routing key in create", getName(), AbstractTestLogSubject.getSlice("rk", subject));
-
- // Validate it was a management actor.
- String actor = fromActor(log);
- assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng"));
- }
-
- public void testBindingCreateOnFanoutViaManagementConsole() throws IOException, JMException
- {
- //Remove any previous queue declares
- _monitor.reset();
-
- _jmxUtils.createQueue("test", getName(), null, false);
-
- ManagedExchange managedExchange = _jmxUtils.getManagedExchange("amq.fanout");
-
- managedExchange.createNewBinding(getName(), getName());
-
- List<String> results = waitAndFindMatches("BND-1001");
-
- assertEquals("More than one bind creation found", 1, results.size());
-
- String log = getLogMessage(results, 0);
-
- // Validate correct binding
- String subject = fromSubject(log);
- assertEquals("Incorrect queue named in create", getName(), AbstractTestLogSubject.getSlice("qu", subject));
- assertEquals("Incorrect routing key in create", getName(), AbstractTestLogSubject.getSlice("rk", subject));
-
- // Validate it was a management actor.
- String actor = fromActor(log);
- assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng"));
- }
-
- /**
- * Description:
- * Bindings can be deleted so that a queue can be rebound with a different set of values. This can be performed via the Management Console
- * Input:
- *
- * 1. Running Broker
- * 2. Management Console connected
- * 3. Management Console is used to perform unbind.
- * Output:
- *
- * <date> BND-1002 : Deleted
- *
- * Validation Steps:
- * 4. The BND ID is correct
- * 5. There must have been a BND-1001 Create message first.
- * 6. This will be the last message for the given binding
- *
- * @throws java.io.IOException - if there is a problem reseting the log monitor or an issue with the JMX Connection
- * @throws javax.management.JMException - {@see #createExchange and ManagedBroker.unregisterExchange}
- */
- public void testUnRegisterExchangeViaManagementConsole() throws IOException, JMException
- {
- //Remove any previous queue declares
- _monitor.reset();
-
- _jmxUtils.createExchange("test", getName(), "direct", false);
-
- ManagedBroker managedBroker = _jmxUtils.getManagedBroker("test");
-
- managedBroker.unregisterExchange(getName());
-
- List<String> results = waitAndFindMatches("EXH-1002");
-
- assertEquals("More than one exchange deletion found", 1, results.size());
-
- String log = getLog(results.get(0));
-
- // Validate correct binding
- String subject = fromSubject(log);
- assertEquals("Incorrect exchange named in delete", "direct/" + getName(), AbstractTestLogSubject.getSlice("ex", subject));
-
- // Validate it was a management actor.
- String actor = fromActor(log);
- assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng"));
- }
-
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/management/jmx/MessageConnectionStatisticsTest.java b/java/systests/src/main/java/org/apache/qpid/management/jmx/MessageConnectionStatisticsTest.java
deleted file mode 100644
index 9839c6e475..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/management/jmx/MessageConnectionStatisticsTest.java
+++ /dev/null
@@ -1,102 +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.management.jmx;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.jms.Connection;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.management.common.mbeans.ManagedBroker;
-import org.apache.qpid.management.common.mbeans.ManagedConnection;
-
-/**
- * Test enabling generation of message statistics on a per-connection basis.
- */
-public class MessageConnectionStatisticsTest extends MessageStatisticsTestCase
-{
- public void configureStatistics() throws Exception
- {
- // no statistics generation configured
- }
-
- /**
- * Test statistics on a single connection
- */
- public void testEnablingStatisticsPerConnection() throws Exception
- {
- ManagedBroker vhost = _jmxUtils.getManagedBroker("test");
-
- sendUsing(_test, 5, 200);
- Thread.sleep(1000);
-
- List<String> addresses = new ArrayList<String>();
- for (ManagedConnection mc : _jmxUtils.getManagedConnections("test"))
- {
- assertEquals("Incorrect connection total", 0, mc.getTotalMessagesReceived());
- assertEquals("Incorrect connection data", 0, mc.getTotalDataReceived());
- assertFalse("Connection statistics should not be enabled", mc.isStatisticsEnabled());
-
- addresses.add(mc.getRemoteAddress());
- }
- assertEquals("Incorrect vhost total", 0, vhost.getTotalMessagesReceived());
- assertEquals("Incorrect vhost data", 0, vhost.getTotalDataReceived());
-
- Connection test = new AMQConnection(_brokerUrl, USER, USER, "clientid", "test");
- test.start();
- for (ManagedConnection mc : _jmxUtils.getManagedConnections("test"))
- {
- if (addresses.contains(mc.getRemoteAddress()))
- {
- continue;
- }
- mc.setStatisticsEnabled(true);
- assertEquals("Incorrect connection total", 0, mc.getTotalMessagesReceived());
- assertEquals("Incorrect connection data", 0, mc.getTotalDataReceived());
- }
-
- sendUsing(test, 5, 200);
- sendUsing(_test, 5, 200);
- Thread.sleep(1000);
-
- for (ManagedConnection mc : _jmxUtils.getManagedConnections("test"))
- {
- if (addresses.contains(mc.getRemoteAddress()))
- {
- assertEquals("Incorrect connection total", 0, mc.getTotalMessagesReceived());
- assertEquals("Incorrect connection data", 0, mc.getTotalDataReceived());
- assertFalse("Connection statistics should not be enabled", mc.isStatisticsEnabled());
- }
- else
- {
- assertEquals("Incorrect connection total", 5, mc.getTotalMessagesReceived());
- assertEquals("Incorrect connection data", 1000, mc.getTotalDataReceived());
- assertTrue("Connection statistics should be enabled", mc.isStatisticsEnabled());
- }
- }
- assertEquals("Incorrect vhost total", 0, vhost.getTotalMessagesReceived());
- assertEquals("Incorrect vhost data", 0, vhost.getTotalDataReceived());
- assertFalse("Vhost statistics should not be enabled", vhost.isStatisticsEnabled());
-
- test.close();
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/management/jmx/MessageStatisticsConfigurationTest.java b/java/systests/src/main/java/org/apache/qpid/management/jmx/MessageStatisticsConfigurationTest.java
deleted file mode 100644
index df8c6e74cd..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/management/jmx/MessageStatisticsConfigurationTest.java
+++ /dev/null
@@ -1,177 +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.management.jmx;
-
-import org.apache.qpid.management.common.mbeans.ManagedBroker;
-import org.apache.qpid.management.common.mbeans.ManagedConnection;
-
-/**
- * Test enabling generation of message statistics on a per-connection basis.
- */
-public class MessageStatisticsConfigurationTest extends MessageStatisticsTestCase
-{
- public void configureStatistics() throws Exception
- {
- setConfigurationProperty("statistics.generation.broker", Boolean.toString(getName().contains("Broker")));
- setConfigurationProperty("statistics.generation.virtualhosts", Boolean.toString(getName().contains("Virtualhost")));
- setConfigurationProperty("statistics.generation.connections", Boolean.toString(getName().contains("Connection")));
- }
-
- /**
- * Just broker statistics.
- */
- public void testGenerateBrokerStatistics() throws Exception
- {
- sendUsing(_test, 5, 200);
- Thread.sleep(1000);
-
- for (ManagedConnection mc : _jmxUtils.getManagedConnections("test"))
- {
- assertEquals("Incorrect connection total", 0, mc.getTotalMessagesReceived());
- assertEquals("Incorrect connection data", 0, mc.getTotalDataReceived());
- assertFalse("Connection statistics should not be enabled", mc.isStatisticsEnabled());
- }
-
- ManagedBroker vhost = _jmxUtils.getManagedBroker("test");
- assertEquals("Incorrect vhost data", 0, vhost.getTotalMessagesReceived());
- assertEquals("Incorrect vhost data", 0, vhost.getTotalDataReceived());
- assertFalse("Vhost statistics should not be enabled", vhost.isStatisticsEnabled());
-
- if (!_broker.equals(VM))
- {
- assertEquals("Incorrect server total messages", 5, _jmxUtils.getServerInformation().getTotalMessagesReceived());
- assertEquals("Incorrect server total data", 1000, _jmxUtils.getServerInformation().getTotalDataReceived());
- assertTrue("Server statistics should be enabled", _jmxUtils.getServerInformation().isStatisticsEnabled());
- }
- }
-
- /**
- * Just virtualhost statistics.
- */
- public void testGenerateVirtualhostStatistics() throws Exception
- {
- sendUsing(_test, 5, 200);
- Thread.sleep(1000);
-
- for (ManagedConnection mc : _jmxUtils.getManagedConnections("test"))
- {
- assertEquals("Incorrect connection total", 0, mc.getTotalMessagesReceived());
- assertEquals("Incorrect connection data", 0, mc.getTotalDataReceived());
- assertFalse("Connection statistics should not be enabled", mc.isStatisticsEnabled());
- }
-
- ManagedBroker vhost = _jmxUtils.getManagedBroker("test");
- assertEquals("Incorrect vhost data", 5, vhost.getTotalMessagesReceived());
- assertEquals("Incorrect vhost data", 1000, vhost.getTotalDataReceived());
- assertTrue("Vhost statistics should be enabled", vhost.isStatisticsEnabled());
-
- if (!_broker.equals(VM))
- {
- assertEquals("Incorrect server total messages", 0, _jmxUtils.getServerInformation().getTotalMessagesReceived());
- assertEquals("Incorrect server total data", 0, _jmxUtils.getServerInformation().getTotalDataReceived());
- assertFalse("Server statistics should not be enabled", _jmxUtils.getServerInformation().isStatisticsEnabled());
- }
- }
-
- /**
- * Just connection statistics.
- */
- public void testGenerateConnectionStatistics() throws Exception
- {
- sendUsing(_test, 5, 200);
- Thread.sleep(1000);
-
- for (ManagedConnection mc : _jmxUtils.getManagedConnections("test"))
- {
- assertEquals("Incorrect connection total", 5, mc.getTotalMessagesReceived());
- assertEquals("Incorrect connection data", 1000, mc.getTotalDataReceived());
- assertTrue("Connection statistics should be enabled", mc.isStatisticsEnabled());
- }
-
- ManagedBroker vhost = _jmxUtils.getManagedBroker("test");
- assertEquals("Incorrect vhost data", 0, vhost.getTotalMessagesReceived());
- assertEquals("Incorrect vhost data", 0, vhost.getTotalDataReceived());
- assertFalse("Vhost statistics should not be enabled", vhost.isStatisticsEnabled());
-
- if (!_broker.equals(VM))
- {
- assertEquals("Incorrect server total messages", 0, _jmxUtils.getServerInformation().getTotalMessagesReceived());
- assertEquals("Incorrect server total data", 0, _jmxUtils.getServerInformation().getTotalDataReceived());
- assertFalse("Server statistics should not be enabled", _jmxUtils.getServerInformation().isStatisticsEnabled());
- }
- }
-
- /**
- * Both broker and virtualhost statistics.
- */
- public void testGenerateBrokerAndVirtualhostStatistics() throws Exception
- {
- sendUsing(_test, 5, 200);
- Thread.sleep(1000);
-
- for (ManagedConnection mc : _jmxUtils.getManagedConnections("test"))
- {
- assertEquals("Incorrect connection total", 0, mc.getTotalMessagesReceived());
- assertEquals("Incorrect connection data", 0, mc.getTotalDataReceived());
- assertFalse("Connection statistics should not be enabled", mc.isStatisticsEnabled());
- }
-
- ManagedBroker vhost = _jmxUtils.getManagedBroker("test");
- assertEquals("Incorrect vhost data", 5, vhost.getTotalMessagesReceived());
- assertEquals("Incorrect vhost data", 1000, vhost.getTotalDataReceived());
- assertTrue("Vhost statistics should be enabled", vhost.isStatisticsEnabled());
-
- if (!_broker.equals(VM))
- {
- assertEquals("Incorrect server total messages", 5, _jmxUtils.getServerInformation().getTotalMessagesReceived());
- assertEquals("Incorrect server total data", 1000, _jmxUtils.getServerInformation().getTotalDataReceived());
- assertTrue("Server statistics should be enabled", _jmxUtils.getServerInformation().isStatisticsEnabled());
- }
- }
-
- /**
- * Broker, virtualhost and connection statistics.
- */
- public void testGenerateBrokerVirtualhostAndConnectionStatistics() throws Exception
- {
- sendUsing(_test, 5, 200);
- Thread.sleep(1000);
-
- for (ManagedConnection mc : _jmxUtils.getManagedConnections("test"))
- {
- assertEquals("Incorrect connection total", 5, mc.getTotalMessagesReceived());
- assertEquals("Incorrect connection data", 1000, mc.getTotalDataReceived());
- assertTrue("Connection statistics should be enabled", mc.isStatisticsEnabled());
- }
-
- ManagedBroker vhost = _jmxUtils.getManagedBroker("test");
- assertEquals("Incorrect vhost data", 5, vhost.getTotalMessagesReceived());
- assertEquals("Incorrect vhost data", 1000, vhost.getTotalDataReceived());
- assertTrue("Vhost statistics should be enabled", vhost.isStatisticsEnabled());
-
- if (!_broker.equals(VM))
- {
- assertEquals("Incorrect server total messages", 5, _jmxUtils.getServerInformation().getTotalMessagesReceived());
- assertEquals("Incorrect server total data", 1000, _jmxUtils.getServerInformation().getTotalDataReceived());
- assertTrue("Server statistics should be enabled", _jmxUtils.getServerInformation().isStatisticsEnabled());
- }
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/management/jmx/MessageStatisticsDeliveryTest.java b/java/systests/src/main/java/org/apache/qpid/management/jmx/MessageStatisticsDeliveryTest.java
deleted file mode 100644
index e657856d0e..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/management/jmx/MessageStatisticsDeliveryTest.java
+++ /dev/null
@@ -1,110 +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.management.jmx;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.jms.Connection;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.Session;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.management.common.mbeans.ManagedBroker;
-import org.apache.qpid.management.common.mbeans.ManagedConnection;
-
-/**
- * Test statistics for delivery and receipt.
- */
-public class MessageStatisticsDeliveryTest extends MessageStatisticsTestCase
-{
- public void configureStatistics() throws Exception
- {
- setConfigurationProperty("statistics.generation.broker", "true");
- setConfigurationProperty("statistics.generation.virtualhosts", "true");
- setConfigurationProperty("statistics.generation.connections", "true");
- }
-
- public void testDeliveryAndReceiptStatistics() throws Exception
- {
- ManagedBroker vhost = _jmxUtils.getManagedBroker("test");
-
- sendUsing(_test, 5, 200);
- Thread.sleep(1000);
-
- List<String> addresses = new ArrayList<String>();
- for (ManagedConnection mc : _jmxUtils.getManagedConnections("test"))
- {
- assertEquals("Incorrect connection delivery total", 0, mc.getTotalMessagesDelivered());
- assertEquals("Incorrect connection delivery data", 0, mc.getTotalDataDelivered());
- assertEquals("Incorrect connection receipt total", 5, mc.getTotalMessagesReceived());
- assertEquals("Incorrect connection receipt data", 1000, mc.getTotalDataReceived());
-
- addresses.add(mc.getRemoteAddress());
- }
-
- assertEquals("Incorrect vhost delivery total", 0, vhost.getTotalMessagesDelivered());
- assertEquals("Incorrect vhost delivery data", 0, vhost.getTotalDataDelivered());
- assertEquals("Incorrect vhost receipt total", 5, vhost.getTotalMessagesReceived());
- assertEquals("Incorrect vhost receipt data", 1000, vhost.getTotalDataReceived());
-
- Connection test = new AMQConnection(_brokerUrl, USER, USER, "clientid", "test");
- test.start();
- receiveUsing(test, 5);
-
- for (ManagedConnection mc : _jmxUtils.getManagedConnections("test"))
- {
- if (addresses.contains(mc.getRemoteAddress()))
- {
- assertEquals("Incorrect connection delivery total", 0, mc.getTotalMessagesDelivered());
- assertEquals("Incorrect connection delivery data", 0, mc.getTotalDataDelivered());
- assertEquals("Incorrect connection receipt total", 5, mc.getTotalMessagesReceived());
- assertEquals("Incorrect connection receipt data", 1000, mc.getTotalDataReceived());
- }
- else
- {
- assertEquals("Incorrect connection delivery total", 5, mc.getTotalMessagesDelivered());
- assertEquals("Incorrect connection delivery data", 1000, mc.getTotalDataDelivered());
- assertEquals("Incorrect connection receipt total", 0, mc.getTotalMessagesReceived());
- assertEquals("Incorrect connection receipt data", 0, mc.getTotalDataReceived());
- }
- }
- assertEquals("Incorrect vhost delivery total", 5, vhost.getTotalMessagesDelivered());
- assertEquals("Incorrect vhost delivery data", 1000, vhost.getTotalDataDelivered());
- assertEquals("Incorrect vhost receipt total", 5, vhost.getTotalMessagesReceived());
- assertEquals("Incorrect vhost receipt data", 1000, vhost.getTotalDataReceived());
-
- test.close();
- }
-
- protected void receiveUsing(Connection con, int number) throws Exception
- {
- Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
- createQueue(session);
- MessageConsumer consumer = session.createConsumer(_queue);
- for (int i = 0; i < number; i++)
- {
- Message msg = consumer.receive(100);
- assertNotNull("Message " + i + " was not received", msg);
- }
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/management/jmx/MessageStatisticsReportingTest.java b/java/systests/src/main/java/org/apache/qpid/management/jmx/MessageStatisticsReportingTest.java
deleted file mode 100644
index 180440c0d6..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/management/jmx/MessageStatisticsReportingTest.java
+++ /dev/null
@@ -1,90 +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.management.jmx;
-
-import java.util.List;
-
-import org.apache.qpid.util.LogMonitor;
-
-/**
- * Test generation of message statistics reporting.
- */
-public class MessageStatisticsReportingTest extends MessageStatisticsTestCase
-{
- protected LogMonitor _monitor;
-
- public void configureStatistics() throws Exception
- {
- setConfigurationProperty("statistics.generation.broker", "true");
- setConfigurationProperty("statistics.generation.virtualhosts", "true");
-
- if (getName().equals("testEnabledStatisticsReporting"))
- {
- setConfigurationProperty("statistics.reporting.period", "10");
- }
-
- _monitor = new LogMonitor(_outputFile);
- }
-
- /**
- * Test enabling reporting.
- */
- public void testEnabledStatisticsReporting() throws Exception
- {
- sendUsing(_test, 10, 100);
- sendUsing(_dev, 20, 100);
- sendUsing(_local, 15, 100);
-
- Thread.sleep(10 * 1000); // 15s
-
- List<String> brokerStatsData = _monitor.findMatches("BRK-1008");
- List<String> brokerStatsMessages = _monitor.findMatches("BRK-1009");
- List<String> vhostStatsData = _monitor.findMatches("VHT-1003");
- List<String> vhostStatsMessages = _monitor.findMatches("VHT-1004");
-
- assertEquals("Incorrect number of broker data stats log messages", 2, brokerStatsData.size());
- assertEquals("Incorrect number of broker message stats log messages", 2, brokerStatsMessages.size());
- assertEquals("Incorrect number of virtualhost data stats log messages", 6, vhostStatsData.size());
- assertEquals("Incorrect number of virtualhost message stats log messages", 6, vhostStatsMessages.size());
- }
-
- /**
- * Test not enabling reporting.
- */
- public void testNotEnabledStatisticsReporting() throws Exception
- {
- sendUsing(_test, 10, 100);
- sendUsing(_dev, 20, 100);
- sendUsing(_local, 15, 100);
-
- Thread.sleep(10 * 1000); // 15s
-
- List<String> brokerStatsData = _monitor.findMatches("BRK-1008");
- List<String> brokerStatsMessages = _monitor.findMatches("BRK-1009");
- List<String> vhostStatsData = _monitor.findMatches("VHT-1003");
- List<String> vhostStatsMessages = _monitor.findMatches("VHT-1004");
-
- assertEquals("Incorrect number of broker data stats log messages", 0, brokerStatsData.size());
- assertEquals("Incorrect number of broker message stats log messages", 0, brokerStatsMessages.size());
- assertEquals("Incorrect number of virtualhost data stats log messages", 0, vhostStatsData.size());
- assertEquals("Incorrect number of virtualhost message stats log messages", 0, vhostStatsMessages.size());
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/management/jmx/MessageStatisticsTest.java b/java/systests/src/main/java/org/apache/qpid/management/jmx/MessageStatisticsTest.java
deleted file mode 100644
index 50ca51b18a..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/management/jmx/MessageStatisticsTest.java
+++ /dev/null
@@ -1,233 +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.management.jmx;
-
-import javax.jms.Connection;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.management.common.mbeans.ManagedBroker;
-import org.apache.qpid.management.common.mbeans.ManagedConnection;
-
-/**
- * Test generation of message statistics.
- */
-public class MessageStatisticsTest extends MessageStatisticsTestCase
-{
- public void configureStatistics() throws Exception
- {
- setConfigurationProperty("statistics.generation.broker", "true");
- setConfigurationProperty("statistics.generation.virtualhosts", "true");
- setConfigurationProperty("statistics.generation.connections", "true");
- }
-
- /**
- * Test message totals.
- */
- public void testMessageTotals() throws Exception
- {
- sendUsing(_test, 10, 100);
- sendUsing(_dev, 20, 100);
- sendUsing(_local, 5, 100);
- sendUsing(_local, 5, 100);
- sendUsing(_local, 5, 100);
- Thread.sleep(2000);
-
- ManagedBroker test = _jmxUtils.getManagedBroker("test");
- ManagedBroker dev = _jmxUtils.getManagedBroker("development");
- ManagedBroker local = _jmxUtils.getManagedBroker("localhost");
-
- if (!isBroker010())
- {
- long total = 0;
- long data = 0;
- for (ManagedConnection mc : _jmxUtils.getAllManagedConnections())
- {
- total += mc.getTotalMessagesReceived();
- data += mc.getTotalDataReceived();
- }
- assertEquals("Incorrect connection total", 45, total);
- assertEquals("Incorrect connection data", 4500, data);
- }
- if (!_broker.equals(VM))
- {
- assertEquals("Incorrect server total", 45, _jmxUtils.getServerInformation().getTotalMessagesReceived());
- assertEquals("Incorrect server data", 4500, _jmxUtils.getServerInformation().getTotalDataReceived());
- }
-
- if (!isBroker010())
- {
- long testTotal = 0;
- long testData = 0;
- for (ManagedConnection mc : _jmxUtils.getManagedConnections("test"))
- {
- testTotal += mc.getTotalMessagesReceived();
- testData += mc.getTotalDataReceived();
- }
- assertEquals("Incorrect test connection total", 10, testTotal);
- assertEquals("Incorrect test connection data", 1000, testData);
- }
- assertEquals("Incorrect test vhost total", 10, test.getTotalMessagesReceived());
- assertEquals("Incorrect test vhost data", 1000, test.getTotalDataReceived());
-
- if (!isBroker010())
- {
- long devTotal = 0;
- long devData = 0;
- for (ManagedConnection mc : _jmxUtils.getManagedConnections("development"))
- {
- devTotal += mc.getTotalMessagesReceived();
- devData += mc.getTotalDataReceived();
- }
- assertEquals("Incorrect test connection total", 20, devTotal);
- assertEquals("Incorrect test connection data", 2000, devData);
- }
- assertEquals("Incorrect development total", 20, dev.getTotalMessagesReceived());
- assertEquals("Incorrect development data", 2000, dev.getTotalDataReceived());
-
- if (!isBroker010())
- {
- long localTotal = 0;
- long localData = 0;
- for (ManagedConnection mc : _jmxUtils.getManagedConnections("localhost"))
- {
- localTotal += mc.getTotalMessagesReceived();
- localData += mc.getTotalDataReceived();
- }
- assertEquals("Incorrect test connection total", 15, localTotal);
- assertEquals("Incorrect test connection data", 1500, localData);
- }
- assertEquals("Incorrect localhost total", 15, local.getTotalMessagesReceived());
- assertEquals("Incorrect localhost data", 1500, local.getTotalDataReceived());
- }
-
- /**
- * Test message totals when a connection is closed.
- */
- public void testMessageTotalsWithClosedConnections() throws Exception
- {
- Connection temp = new AMQConnection(_brokerUrl, USER, USER, "clientid", "test");
- temp.start();
-
- sendUsing(_test, 10, 100);
- sendUsing(temp, 10, 100);
- sendUsing(_test, 10, 100);
- Thread.sleep(2000);
-
- temp.close();
-
- ManagedBroker test = _jmxUtils.getManagedBroker("test");
-
- if (!isBroker010())
- {
- long total = 0;
- long data = 0;
- for (ManagedConnection mc : _jmxUtils.getAllManagedConnections())
- {
- total += mc.getTotalMessagesReceived();
- data += mc.getTotalDataReceived();
- }
- assertEquals("Incorrect active connection total", 20, total);
- assertEquals("Incorrect active connection data", 2000, data);
- }
- if (!_broker.equals(VM))
- {
- assertEquals("Incorrect server total", 30, _jmxUtils.getServerInformation().getTotalMessagesReceived());
- assertEquals("Incorrect server data", 3000, _jmxUtils.getServerInformation().getTotalDataReceived());
- }
-
- if (!isBroker010())
- {
- long testTotal = 0;
- long testData = 0;
- for (ManagedConnection mc : _jmxUtils.getManagedConnections("test"))
- {
- testTotal += mc.getTotalMessagesReceived();
- testData += mc.getTotalDataReceived();
- }
- assertEquals("Incorrect test active connection total", 20, testTotal);
- assertEquals("Incorrect test active connection data", 20 * 100, testData);
- }
- assertEquals("Incorrect test vhost total", 30, test.getTotalMessagesReceived());
- assertEquals("Incorrect test vhost data", 30 * 100, test.getTotalDataReceived());
- }
-
- /**
- * Test message peak rate generation.
- */
- public void testMessagePeakRates() throws Exception
- {
- sendUsing(_test, 2, 10);
- Thread.sleep(10000);
- sendUsing(_dev, 4, 10);
- Thread.sleep(10000);
-
- ManagedBroker test = _jmxUtils.getManagedBroker("test");
- ManagedBroker dev = _jmxUtils.getManagedBroker("development");
-
- assertApprox("Incorrect test vhost peak messages", 0.2d, 1.0d, test.getPeakMessageReceiptRate());
- assertApprox("Incorrect test vhost peak data", 0.2d, 10.0d, test.getPeakDataReceiptRate());
- assertApprox("Incorrect dev vhost peak messages", 0.2d, 2.0d, dev.getPeakMessageReceiptRate());
- assertApprox("Incorrect dev vhost peak data", 0.2d, 20.0d, dev.getPeakDataReceiptRate());
-
- if (!_broker.equals(VM))
- {
- assertApprox("Incorrect server peak messages", 0.2d, 2.0d, _jmxUtils.getServerInformation().getPeakMessageReceiptRate());
- assertApprox("Incorrect server peak data", 0.2d, 20.0d, _jmxUtils.getServerInformation().getPeakDataReceiptRate());
- }
- }
-
- /**
- * Test message totals when a vhost has its statistics reset
- */
- public void testMessageTotalVhostReset() throws Exception
- {
- sendUsing(_test, 10, 10);
- sendUsing(_dev, 10, 10);
- Thread.sleep(2000);
-
- ManagedBroker test = _jmxUtils.getManagedBroker("test");
- ManagedBroker dev = _jmxUtils.getManagedBroker("development");
-
- assertEquals("Incorrect test vhost total messages", 10, test.getTotalMessagesReceived());
- assertEquals("Incorrect test vhost total data", 100, test.getTotalDataReceived());
- assertEquals("Incorrect dev vhost total messages", 10, dev.getTotalMessagesReceived());
- assertEquals("Incorrect dev vhost total data", 100, dev.getTotalDataReceived());
-
- if (!_broker.equals(VM))
- {
- assertEquals("Incorrect server total messages", 20, _jmxUtils.getServerInformation().getTotalMessagesReceived());
- assertEquals("Incorrect server total data", 200, _jmxUtils.getServerInformation().getTotalDataReceived());
- }
-
- test.resetStatistics();
-
- assertEquals("Incorrect test vhost total messages", 0, test.getTotalMessagesReceived());
- assertEquals("Incorrect test vhost total data", 0, test.getTotalDataReceived());
- assertEquals("Incorrect dev vhost total messages", 10, dev.getTotalMessagesReceived());
- assertEquals("Incorrect dev vhost total data", 100, dev.getTotalDataReceived());
-
- if (!_broker.equals(VM))
- {
- assertEquals("Incorrect server total messages", 20, _jmxUtils.getServerInformation().getTotalMessagesReceived());
- assertEquals("Incorrect server total data", 200, _jmxUtils.getServerInformation().getTotalDataReceived());
- }
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/management/jmx/MessageStatisticsTestCase.java b/java/systests/src/main/java/org/apache/qpid/management/jmx/MessageStatisticsTestCase.java
deleted file mode 100644
index a5b3aa283c..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/management/jmx/MessageStatisticsTestCase.java
+++ /dev/null
@@ -1,128 +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.management.jmx;
-
-import javax.jms.Connection;
-import javax.jms.Destination;
-import javax.jms.JMSException;
-import javax.jms.MessageProducer;
-import javax.jms.Session;
-import javax.jms.TextMessage;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQDestination;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.exchange.ExchangeDefaults;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.test.utils.JMXTestUtils;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-/**
- * Test generation of message statistics.
- */
-public abstract class MessageStatisticsTestCase extends QpidBrokerTestCase
-{
- protected static final String USER = "admin";
-
- protected JMXTestUtils _jmxUtils;
- protected Connection _test, _dev, _local;
- protected String _queueName = "statistics";
- protected Destination _queue;
- protected String _brokerUrl;
-
- @Override
- public void setUp() throws Exception
- {
- _jmxUtils = new JMXTestUtils(this, USER, USER);
- _jmxUtils.setUp();
-
- configureStatistics();
-
- super.setUp();
-
- _brokerUrl = getBroker().toString();
- _test = new AMQConnection(_brokerUrl, USER, USER, "clientid", "test");
- _dev = new AMQConnection(_brokerUrl, USER, USER, "clientid", "development");
- _local = new AMQConnection(_brokerUrl, USER, USER, "clientid", "localhost");
-
- _test.start();
- _dev.start();
- _local.start();
-
- _jmxUtils.open();
- }
-
- protected void createQueue(Session session) throws AMQException, JMSException
- {
- _queue = new AMQQueue(ExchangeDefaults.DIRECT_EXCHANGE_NAME, _queueName);
- if (!((AMQSession<?,?>) session).isQueueBound((AMQDestination) _queue))
- {
- ((AMQSession<?,?>) session).createQueue(new AMQShortString(_queueName), false, true, false, null);
- ((AMQSession<?,?>) session).declareAndBind((AMQDestination) new AMQQueue(ExchangeDefaults.DIRECT_EXCHANGE_NAME, _queueName));
- }
- }
-
-
- @Override
- public void tearDown() throws Exception
- {
- _jmxUtils.close();
-
- _test.close();
- _dev.close();
- _local.close();
-
- super.tearDown();
- }
-
- /**
- * Configure statistics generation properties on the broker.
- */
- public abstract void configureStatistics() throws Exception;
-
- protected void sendUsing(Connection con, int number, int size) throws Exception
- {
- Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
- createQueue(session);
- MessageProducer producer = session.createProducer(_queue);
- String content = new String(new byte[size]);
- TextMessage msg = session.createTextMessage(content);
- for (int i = 0; i < number; i++)
- {
- producer.send(msg);
- }
- }
-
- /**
- * Asserts that the actual value is within the expected value plus or
- * minus the given error.
- */
- public void assertApprox(String message, double error, double expected, double actual)
- {
- double min = expected * (1.0d - error);
- double max = expected * (1.0d + error);
- String assertion = String.format("%s: expected %f +/- %d%%, actual %f",
- message, expected, (int) (error * 100.0d), actual);
- assertTrue(assertion, actual > min && actual < max);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/server/BrokerStartupTest.java b/java/systests/src/main/java/org/apache/qpid/server/BrokerStartupTest.java
deleted file mode 100644
index f9227c53ba..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/server/BrokerStartupTest.java
+++ /dev/null
@@ -1,149 +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;
-
-import org.apache.qpid.server.logging.AbstractTestLogging;
-import org.apache.qpid.util.LogMonitor;
-import org.apache.log4j.Logger;
-import org.apache.log4j.Level;
-
-import java.util.List;
-
-import junit.framework.AssertionFailedError;
-
-import javax.jms.Connection;
-import javax.jms.Session;
-import javax.jms.Queue;
-
-/**
- * Series of tests to validate the external Java broker starts up as expected.
- */
-public class BrokerStartupTest extends AbstractTestLogging
-{
- public void setUp() throws Exception
- {
- // We either do this here or have a null check in tearDown.
- // As when this test is run against profiles other than java it will NPE
- _monitor = new LogMonitor(_outputFile);
- //We explicitly do not call super.setUp as starting up the broker is
- //part of the test case.
- }
-
-
- /**
- * Description:
- * Test that providing an invalid broker logging configuration file does not
- * cause the broker to enable DEBUG logging that will seriously impair
- * performance
- * Input:
- * -l value that does not exist
- * <p/>
- * Output:
- * <p/>
- * No DEBUG output
- * <p/>
- * Validation Steps:
- * <p/>
- * 1. Start the broker and verify no DEBUG output exists
- *
- * @throws Exception caused by broker startup
- */
- public void testInvalidLog4jConfigurationFile() throws Exception
- {
- // This logging startup code only occurs when you run a Java broker,
- // that broker must be started via Main so not an InVM broker.
- if (isJavaBroker() && isExternalBroker())
- {
- //Remove test Log4j config from the commandline
- _broker = _broker.substring(0, _broker.indexOf("-l"));
-
- // Add an invalid value
- _broker += " -l invalid";
-
- // The broker has a built in default log4j configuration set up
- // so if the the broker cannot load the -l value it will use default
- // use this default. Test that this is correctly loaded, by
- // including -Dlog4j.debug so we can validate.
- setBrokerEnvironment("QPID_OPTS", "-Dlog4j.debug");
-
- // Disable all client logging so we can test for broker DEBUG only.
- setLoggerLevel(Logger.getRootLogger(), Level.WARN);
- setLoggerLevel(Logger.getLogger("qpid.protocol"), Level.WARN);
- setLoggerLevel(Logger.getLogger("org.apache.qpid"), Level.WARN);
-
- // Set the broker to use info level logging, which is the qpid-server
- // default. Rather than debug which is the test default.
- setBrokerOnlySystemProperty("amqj.server.logging.level", "info");
- // Set the logging defaults to info for this test.
- setBrokerOnlySystemProperty("amqj.logging.level", "info");
- setBrokerOnlySystemProperty("root.logging.level", "info");
-
- startBroker();
-
- assertEquals("Log4j could not load desired configruation.",
- 0, findMatches("log4j:ERROR Could not read configuration file from URL").size());
-
- assertEquals("Logging did not error as expected",
- 1, waitAndFindMatches("Logging configuration error: unable to read file ").size());
-
-
- // Perfom some action on the broker to ensure that we hit the DEBUG
- // messages that we know are there. Though the current xml parsing
- // will generate a LOT of DEBUG on startup.
- Connection connection = getConnection();
-
- Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- Queue queue = session.createQueue(getTestQueueName());
- session.createConsumer(queue).close();
-
- int COUNT = 10;
- sendMessage(session, queue, COUNT);
-
- assertEquals(COUNT,drainQueue(queue));
-
- List<String> results = waitAndFindMatches("DEBUG");
- try
- {
- // Validation
-
- assertEquals("DEBUG messages should not be logged", 0, results.size());
- }
- catch (AssertionFailedError afe)
- {
- System.err.println("Log Dump:");
- for (String log : results)
- {
- System.err.println(log);
- }
-
- if (results.size() == 0)
- {
- System.err.println("Monitored file contents:");
- System.err.println(_monitor.readFile());
- }
-
- throw afe;
- }
- }
- }
-
-} \ No newline at end of file
diff --git a/java/systests/src/main/java/org/apache/qpid/server/configuration/ServerConfigurationFileTest.java b/java/systests/src/main/java/org/apache/qpid/server/configuration/ServerConfigurationFileTest.java
deleted file mode 100644
index d4c550bc08..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/server/configuration/ServerConfigurationFileTest.java
+++ /dev/null
@@ -1,89 +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.configuration;
-
-import org.apache.commons.configuration.ConfigurationException;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-/**
- * This system test ensures that when loading our default system-test
- * configuration file the configuration is correctly loaded.
- *
- * All configuration values should be set in the systest config file so that
- * the ability to load them can be validated.
- */
-public class ServerConfigurationFileTest extends QpidBrokerTestCase
-{
- ServerConfiguration _serverConfig;
-
- public void setUp() throws ConfigurationException
- {
- if (!_configFile.exists())
- {
- fail("Unable to test without config file:" + _configFile);
- }
-
- saveTestConfiguration();
- saveTestVirtualhosts();
-
- _serverConfig = new ServerConfiguration(_configFile);
- }
-
- /**
- * This helper method ensures that when we attempt to read a value that is
- * set in the configuration file we do actualy read a value and not
- * simply get a defaulted value from the ServerConfiguration.get*() methods.
- *
- * @param property the propert to test
- */
- private void validatePropertyDefinedInFile(String property)
- {
- //Verify that we are not just picking up the the default value from the getBoolean
- assertNotNull("The value set in the configuration file is not being read for property:" + property,
- _serverConfig.getConfig().getProperty(property));
- }
-
- public void testProtectIOEnabled() throws ConfigurationException
- {
- validatePropertyDefinedInFile(ServerConfiguration.CONNECTOR_PROTECTIO_ENABLED);
- }
-
- public void testProtectIOReadBufferLimitSize() throws ConfigurationException
- {
- validatePropertyDefinedInFile(ServerConfiguration.CONNECTOR_PROTECTIO_READ_BUFFER_LIMIT_SIZE);
- }
-
- public void testProtectIOWriteBufferLimitSize() throws ConfigurationException
- {
- validatePropertyDefinedInFile(ServerConfiguration.CONNECTOR_PROTECTIO_WRITE_BUFFER_LIMIT_SIZE);
- }
-
- public void testStatusUpdates() throws ConfigurationException
- {
- validatePropertyDefinedInFile(ServerConfiguration.STATUS_UPDATES);
- }
-
- public void testLocale() throws ConfigurationException
- {
- validatePropertyDefinedInFile(ServerConfiguration.ADVANCED_LOCALE);
- }
-
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/server/exchange/MessagingTestConfigProperties.java b/java/systests/src/main/java/org/apache/qpid/server/exchange/MessagingTestConfigProperties.java
deleted file mode 100644
index 2d89d319d7..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/server/exchange/MessagingTestConfigProperties.java
+++ /dev/null
@@ -1,308 +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.jms.Session;
-import org.apache.qpid.junit.extensions.util.ParsedProperties;
-
-/**
- * MessagingTestConfigProperties defines a set of property names and default values for specifying a messaging topology,
- * and test parameters for running a messaging test over that topology. A Properties object holding some of these
- * properties, superimposed onto the defaults, is used to establish test topologies and control test behaviour.
- *
- * <p/>A complete list of the parameters, default values and comments on their usage is provided here:
- *
- * <p/><table><caption>Parameters</caption>
- * <tr><th> Parameter <th> Default <th> Comments
- * <tr><td> messageSize <td> 0 <td> Message size in bytes. Not including any headers.
- * <tr><td> destinationName <td> ping <td> The root name to use to generate destination names to ping.
- * <tr><td> persistent <td> false <td> Determines whether peristent delivery is used.
- * <tr><td> transacted <td> false <td> Determines whether messages are sent/received in transactions.
- * <tr><td> broker <td> tcp://localhost:5672 <td> Determines the broker to connect to.
- * <tr><td> virtualHost <td> test <td> Determines the virtual host to send all ping over.
- * <tr><td> rate <td> 0 <td> The maximum rate (in hertz) to send messages at. 0 means no limit.
- * <tr><td> verbose <td> false <td> The verbose flag for debugging. Prints to console on every message.
- * <tr><td> pubsub <td> false <td> Whether to ping topics or queues. Uses p2p by default.
- * <tr><td> username <td> guest <td> The username to access the broker with.
- * <tr><td> password <td> guest <td> The password to access the broker with.
- * <tr><td> selector <td> null <td> Not used. Defines a message selector to filter pings with.
- * <tr><td> destinationCount <td> 1 <td> The number of receivers listening to the pings.
- * <tr><td> timeout <td> 30000 <td> In milliseconds. The timeout to stop waiting for replies.
- * <tr><td> commitBatchSize <td> 1 <td> The number of messages per transaction in transactional mode.
- * <tr><td> uniqueDests <td> true <td> Whether each receiver only listens to one ping destination or all.
- * <tr><td> durableDests <td> false <td> Whether or not durable destinations are used.
- * <tr><td> ackMode <td> AUTO_ACK <td> The message acknowledgement mode. Possible values are:
- * 0 - SESSION_TRANSACTED
- * 1 - AUTO_ACKNOWLEDGE
- * 2 - CLIENT_ACKNOWLEDGE
- * 3 - DUPS_OK_ACKNOWLEDGE
- * 257 - NO_ACKNOWLEDGE
- * 258 - PRE_ACKNOWLEDGE
- * <tr><td> maxPending <td> 0 <td> The maximum size in bytes, of messages sent but not yet received.
- * Limits the volume of messages currently buffered on the client
- * or broker. Can help scale test clients by limiting amount of buffered
- * data to avoid out of memory errors.
- * </table>
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Provide the names and defaults of all test parameters.
- * </table>
- */
-public class MessagingTestConfigProperties
-{
- // ====================== Connection Properties ==================================
-
- /** Holds the name of the default connection configuration. */
- public static final String CONNECTION_NAME = "broker";
-
- /** Holds the name of the property to get the initial context factory name from. */
- public static final String INITIAL_CONTEXT_FACTORY_PROPNAME = "java.naming.factory.initial";
-
- /** Defines the class to use as the initial context factory by default. */
- public static final String INITIAL_CONTEXT_FACTORY_DEFAULT = "org.apache.qpid.jndi.PropertiesFileInitialContextFactory";
-
- /** Holds the name of the default connection factory configuration property. */
- public static final String CONNECTION_PROPNAME = "connectionfactory.broker";
-
- /** Defeins the default connection configuration. */
- public static final String CONNECTION_DEFAULT = "amqp://guest:guest@clientid/?brokerlist='vm://:1'";
-
- /** Holds the name of the property to get the test broker url from. */
- public static final String BROKER_PROPNAME = "qpid.test.broker";
-
- /** Holds the default broker url for the test. */
- public static final String BROKER_DEFAULT = "vm://:1";
-
- /** Holds the name of the property to get the test broker virtual path. */
- public static final String VIRTUAL_HOST_PROPNAME = "virtualHost";
-
- /** Holds the default virtual path for the test. */
- public static final String VIRTUAL_HOST_DEFAULT = "";
-
- /** Holds the name of the property to get the broker access username from. */
- public static final String USERNAME_PROPNAME = "username";
-
- /** Holds the default broker log on username. */
- public static final String USERNAME_DEFAULT = "guest";
-
- /** Holds the name of the property to get the broker access password from. */
- public static final String PASSWORD_PROPNAME = "password";
-
- /** Holds the default broker log on password. */
- public static final String PASSWORD_DEFAULT = "guest";
-
- // ====================== Messaging Topology Properties ==========================
-
- /** Holds the name of the property to get the bind publisher procuder flag from. */
- public static final String PUBLISHER_PRODUCER_BIND_PROPNAME = "publisherProducerBind";
-
- /** Holds the default value of the publisher producer flag. */
- public static final boolean PUBLISHER_PRODUCER_BIND_DEFAULT = true;
-
- /** Holds the name of the property to get the bind publisher procuder flag from. */
- public static final String PUBLISHER_CONSUMER_BIND_PROPNAME = "publisherConsumerBind";
-
- /** Holds the default value of the publisher consumer flag. */
- public static final boolean PUBLISHER_CONSUMER_BIND_DEFAULT = false;
-
- /** Holds the name of the property to get the bind receiver procuder flag from. */
- public static final String RECEIVER_PRODUCER_BIND_PROPNAME = "receiverProducerBind";
-
- /** Holds the default value of the receiver producer flag. */
- public static final boolean RECEIVER_PRODUCER_BIND_DEFAULT = false;
-
- /** Holds the name of the property to get the bind receiver procuder flag from. */
- public static final String RECEIVER_CONSUMER_BIND_PROPNAME = "receiverConsumerBind";
-
- /** Holds the default value of the receiver consumer flag. */
- public static final boolean RECEIVER_CONSUMER_BIND_DEFAULT = true;
-
- /** Holds the name of the property to get the destination name root from. */
- public static final String SEND_DESTINATION_NAME_ROOT_PROPNAME = "sendDestinationRoot";
-
- /** Holds the root of the name of the default destination to send to. */
- public static final String SEND_DESTINATION_NAME_ROOT_DEFAULT = "sendTo";
-
- /** Holds the name of the property to get the destination name root from. */
- public static final String RECEIVE_DESTINATION_NAME_ROOT_PROPNAME = "receiveDestinationRoot";
-
- /** Holds the root of the name of the default destination to send to. */
- public static final String RECEIVE_DESTINATION_NAME_ROOT_DEFAULT = "receiveFrom";
-
- /** Holds the name of the proeprty to get the destination count from. */
- public static final String DESTINATION_COUNT_PROPNAME = "destinationCount";
-
- /** Defines the default number of destinations to ping. */
- public static final int DESTINATION_COUNT_DEFAULT = 1;
-
- /** Holds the name of the property to get the p2p or pub/sub messaging mode from. */
- public static final String PUBSUB_PROPNAME = "pubsub";
-
- /** Holds the pub/sub mode default, true means ping a topic, false means ping a queue. */
- public static final boolean PUBSUB_DEFAULT = false;
-
- // ====================== JMS Options and Flags =================================
-
- /** Holds the name of the property to get the test delivery mode from. */
- public static final String PERSISTENT_MODE_PROPNAME = "persistent";
-
- /** Holds the message delivery mode to use for the test. */
- public static final boolean PERSISTENT_MODE_DEFAULT = false;
-
- /** Holds the name of the property to get the test transactional mode from. */
- public static final String TRANSACTED_PROPNAME = "transacted";
-
- /** Holds the transactional mode to use for the test. */
- public static final boolean TRANSACTED_DEFAULT = false;
-
- /** Holds the name of the property to set the no local flag from. */
- public static final String NO_LOCAL_PROPNAME = "noLocal";
-
- /** Defines the default value of the no local flag to use when consuming messages. */
- public static final boolean NO_LOCAL_DEFAULT = false;
-
- /** Holds the name of the property to get the message acknowledgement mode from. */
- public static final String ACK_MODE_PROPNAME = "ackMode";
-
- /** Defines the default message acknowledgement mode. */
- public static final int ACK_MODE_DEFAULT = Session.AUTO_ACKNOWLEDGE;
-
- /** Holds the name of the property to get the durable subscriptions flag from, when doing pub/sub messaging. */
- public static final String DURABLE_SUBSCRIPTION_PROPNAME = "durableSubscription";
-
- /** Defines the default value of the durable subscriptions flag. */
- public static final boolean DURABLE_SUBSCRIPTION_DEFAULT = false;
-
- // ====================== Qpid Options and Flags ================================
-
- /** Holds the name of the property to set the exclusive flag from. */
- public static final String EXCLUSIVE_PROPNAME = "exclusive";
-
- /** Defines the default value of the exclusive flag to use when consuming messages. */
- public static final boolean EXCLUSIVE_DEFAULT = false;
-
- /** Holds the name of the property to set the immediate flag from. */
- public static final String IMMEDIATE_PROPNAME = "immediate";
-
- /** Defines the default value of the immediate flag to use when sending messages. */
- public static final boolean IMMEDIATE_DEFAULT = false;
-
- /** Holds the name of the property to set the mandatory flag from. */
- public static final String MANDATORY_PROPNAME = "mandatory";
-
- /** Defines the default value of the mandatory flag to use when sending messages. */
- public static final boolean MANDATORY_DEFAULT = false;
-
- /** Holds the name of the property to get the durable destinations flag from. */
- public static final String DURABLE_DESTS_PROPNAME = "durableDests";
-
- /** Default value for the durable destinations flag. */
- public static final boolean DURABLE_DESTS_DEFAULT = false;
-
- /** Holds the name of the proeprty to set the prefetch size from. */
- public static final String PREFECTH_PROPNAME = "prefetch";
-
- /** Defines the default prefetch size to use when consuming messages. */
- public static final int PREFETCH_DEFAULT = 100;
-
- // ====================== Common Test Parameters ================================
-
- /** Holds the name of the property to get the test message size from. */
- public static final String MESSAGE_SIZE_PROPNAME = "messageSize";
-
- /** Used to set up a default message size. */
- public static final int MESSAGE_SIZE_DEAFULT = 0;
-
- /** Holds the name of the property to get the message rate from. */
- public static final String RATE_PROPNAME = "rate";
-
- /** Defines the default rate (in pings per second) to send pings at. 0 means as fast as possible, no restriction. */
- public static final int RATE_DEFAULT = 0;
-
- /** Holds the name of the proeprty to get the. */
- public static final String SELECTOR_PROPNAME = "selector";
-
- /** Holds the default message selector. */
- public static final String SELECTOR_DEFAULT = "";
-
- /** Holds the name of the property to get the waiting timeout for response messages. */
- public static final String TIMEOUT_PROPNAME = "timeout";
-
- /** Default time to wait before assuming that a ping has timed out. */
- public static final long TIMEOUT_DEFAULT = 30000;
-
- /** Holds the name of the property to get the commit batch size from. */
- public static final String TX_BATCH_SIZE_PROPNAME = "commitBatchSize";
-
- /** Defines the default number of pings to send in each transaction when running transactionally. */
- public static final int TX_BATCH_SIZE_DEFAULT = 1;
-
- /** Holds the name of the property to set the maximum amount of pending message data for a producer to hold. */
- public static final String MAX_PENDING_PROPNAME = "maxPending";
-
- /** Defines the default maximum quantity of pending message data to allow producers to hold. */
- public static final int MAX_PENDING_DEFAULT = 0;
-
- /** Holds the name of the property to get the verbose mode proeprty from. */
- public static final String VERBOSE_PROPNAME = "verbose";
-
- /** Holds the default verbose mode. */
- public static final boolean VERBOSE_DEFAULT = false;
-
- /** Holds the default configuration properties. */
- public static ParsedProperties defaults = new ParsedProperties();
-
- static
- {
- defaults.setPropertyIfNull(INITIAL_CONTEXT_FACTORY_PROPNAME, INITIAL_CONTEXT_FACTORY_DEFAULT);
- defaults.setPropertyIfNull(CONNECTION_PROPNAME, CONNECTION_DEFAULT);
- defaults.setPropertyIfNull(MESSAGE_SIZE_PROPNAME, MESSAGE_SIZE_DEAFULT);
- defaults.setPropertyIfNull(PUBLISHER_PRODUCER_BIND_PROPNAME, PUBLISHER_PRODUCER_BIND_DEFAULT);
- defaults.setPropertyIfNull(PUBLISHER_CONSUMER_BIND_PROPNAME, PUBLISHER_CONSUMER_BIND_DEFAULT);
- defaults.setPropertyIfNull(RECEIVER_PRODUCER_BIND_PROPNAME, RECEIVER_PRODUCER_BIND_DEFAULT);
- defaults.setPropertyIfNull(RECEIVER_CONSUMER_BIND_PROPNAME, RECEIVER_CONSUMER_BIND_DEFAULT);
- defaults.setPropertyIfNull(SEND_DESTINATION_NAME_ROOT_PROPNAME, SEND_DESTINATION_NAME_ROOT_DEFAULT);
- defaults.setPropertyIfNull(RECEIVE_DESTINATION_NAME_ROOT_PROPNAME, RECEIVE_DESTINATION_NAME_ROOT_DEFAULT);
- defaults.setPropertyIfNull(PERSISTENT_MODE_PROPNAME, PERSISTENT_MODE_DEFAULT);
- defaults.setPropertyIfNull(TRANSACTED_PROPNAME, TRANSACTED_DEFAULT);
- defaults.setPropertyIfNull(BROKER_PROPNAME, BROKER_DEFAULT);
- defaults.setPropertyIfNull(VIRTUAL_HOST_PROPNAME, VIRTUAL_HOST_DEFAULT);
- defaults.setPropertyIfNull(RATE_PROPNAME, RATE_DEFAULT);
- defaults.setPropertyIfNull(VERBOSE_PROPNAME, VERBOSE_DEFAULT);
- defaults.setPropertyIfNull(PUBSUB_PROPNAME, PUBSUB_DEFAULT);
- defaults.setPropertyIfNull(USERNAME_PROPNAME, USERNAME_DEFAULT);
- defaults.setPropertyIfNull(PASSWORD_PROPNAME, PASSWORD_DEFAULT);
- defaults.setPropertyIfNull(SELECTOR_PROPNAME, SELECTOR_DEFAULT);
- defaults.setPropertyIfNull(DESTINATION_COUNT_PROPNAME, DESTINATION_COUNT_DEFAULT);
- defaults.setPropertyIfNull(TIMEOUT_PROPNAME, TIMEOUT_DEFAULT);
- defaults.setPropertyIfNull(TX_BATCH_SIZE_PROPNAME, TX_BATCH_SIZE_DEFAULT);
- defaults.setPropertyIfNull(DURABLE_DESTS_PROPNAME, DURABLE_DESTS_DEFAULT);
- defaults.setPropertyIfNull(ACK_MODE_PROPNAME, ACK_MODE_DEFAULT);
- defaults.setPropertyIfNull(DURABLE_SUBSCRIPTION_PROPNAME, DURABLE_SUBSCRIPTION_DEFAULT);
- defaults.setPropertyIfNull(MAX_PENDING_PROPNAME, MAX_PENDING_DEFAULT);
- defaults.setPropertyIfNull(PREFECTH_PROPNAME, PREFETCH_DEFAULT);
- defaults.setPropertyIfNull(NO_LOCAL_PROPNAME, NO_LOCAL_DEFAULT);
- defaults.setPropertyIfNull(EXCLUSIVE_PROPNAME, EXCLUSIVE_DEFAULT);
- defaults.setPropertyIfNull(IMMEDIATE_PROPNAME, IMMEDIATE_DEFAULT);
- defaults.setPropertyIfNull(MANDATORY_PROPNAME, MANDATORY_DEFAULT);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/server/exchange/ReturnUnroutableMandatoryMessageTest.java b/java/systests/src/main/java/org/apache/qpid/server/exchange/ReturnUnroutableMandatoryMessageTest.java
deleted file mode 100644
index 4b4fbd711b..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/server/exchange/ReturnUnroutableMandatoryMessageTest.java
+++ /dev/null
@@ -1,309 +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 java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-import javax.jms.Connection;
-import javax.jms.ExceptionListener;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-import javax.jms.Session;
-import javax.jms.TextMessage;
-
-import org.apache.log4j.Logger;
-import org.apache.qpid.client.AMQHeadersExchange;
-import org.apache.qpid.client.AMQNoRouteException;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.client.AMQTopic;
-import org.apache.qpid.configuration.ClientProperties;
-import org.apache.qpid.exchange.ExchangeDefaults;
-import org.apache.qpid.framing.FieldTable;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.apache.qpid.url.AMQBindingURL;
-import org.apache.qpid.url.BindingURL;
-
-public class ReturnUnroutableMandatoryMessageTest extends QpidBrokerTestCase implements ExceptionListener
-{
- private static final Logger _logger = Logger.getLogger(ReturnUnroutableMandatoryMessageTest.class);
-
- private final List<Message> _bouncedMessageList = Collections.synchronizedList(new ArrayList<Message>());
-
- static
- {
- String workdir = System.getProperty("QPID_WORK");
- if (workdir == null || workdir.equals(""))
- {
- String tempdir = System.getProperty("java.io.tmpdir");
- System.out.println("QPID_WORK not set using tmp directory: " + tempdir);
- System.setProperty("QPID_WORK", tempdir);
- }
- }
-
- /**
- * Tests that mandatory message which are not routable are returned to the producer
- *
- * @throws Exception
- */
- public void testReturnUnroutableMandatoryMessage_HEADERS() throws Exception
- {
- _bouncedMessageList.clear();
- MessageConsumer consumer = null;
- AMQSession producerSession = null;
- AMQHeadersExchange queue = null;
- Connection con=null, con2 = null;
- try
- {
- con = getConnection();
-
- AMQSession consumerSession = (AMQSession) con.createSession(false, Session.CLIENT_ACKNOWLEDGE);
-
- queue = new AMQHeadersExchange(new AMQBindingURL(ExchangeDefaults.HEADERS_EXCHANGE_CLASS + "://" + ExchangeDefaults.HEADERS_EXCHANGE_NAME + "/test/queue1?" + BindingURL.OPTION_ROUTING_KEY + "='F0000=1'"));
- FieldTable ft = new FieldTable();
- ft.setString("F1000", "1");
- consumer = consumerSession.createConsumer(queue, Integer.parseInt(ClientProperties.MAX_PREFETCH_DEFAULT), Integer.parseInt(ClientProperties.MAX_PREFETCH_DEFAULT) /2 , false, false, (String) null, ft);
-
- //force synch to ensure the consumer has resulted in a bound queue
- //((AMQSession) consumerSession).declareExchangeSynch(ExchangeDefaults.HEADERS_EXCHANGE_NAME, ExchangeDefaults.HEADERS_EXCHANGE_CLASS);
- // This is the default now
-
- con2 = getConnection();
-
- con2.setExceptionListener(this);
- producerSession = (AMQSession) con2.createSession(false, Session.CLIENT_ACKNOWLEDGE);
-
- // Need to start the "producer" connection in order to receive bounced messages
- _logger.info("Starting producer connection");
- con2.start();
- }
- catch (JMSException jmse)
- {
- fail(jmse.getMessage());
- }
-
- try
- {
- MessageProducer nonMandatoryProducer = producerSession.createProducer(queue, false, false);
- MessageProducer mandatoryProducer = producerSession.createProducer(queue);
-
- // First test - should neither be bounced nor routed
- _logger.info("Sending non-routable non-mandatory message");
- TextMessage msg1 = producerSession.createTextMessage("msg1");
- nonMandatoryProducer.send(msg1);
-
- // Second test - should be bounced
- _logger.info("Sending non-routable mandatory message");
- TextMessage msg2 = producerSession.createTextMessage("msg2");
- mandatoryProducer.send(msg2);
-
- // Third test - should be routed
- _logger.info("Sending routable message");
- TextMessage msg3 = producerSession.createTextMessage("msg3");
- msg3.setStringProperty("F1000", "1");
- mandatoryProducer.send(msg3);
-
- _logger.info("Starting consumer connection");
- con.start();
- TextMessage tm = (TextMessage) consumer.receive(1000L);
-
- assertTrue("No message routed to receiver", tm != null);
- assertTrue("Wrong message routed to receiver: " + tm.getText(), "msg3".equals(tm.getText()));
-
- try
- {
- Thread.sleep(1000L);
- }
- catch (InterruptedException e)
- {
- ;
- }
-
- assertTrue("Wrong number of messages bounced (expect 1): " + _bouncedMessageList.size(), _bouncedMessageList.size() == 1);
- Message m = _bouncedMessageList.get(0);
- assertTrue("Wrong message bounced: " + m.toString(), m.toString().contains("msg2"));
- }
- catch (JMSException jmse)
- {
-
- }
- con.close();
- con2.close();
-
- }
-
- public void testReturnUnroutableMandatoryMessage_QUEUE() throws Exception
- {
- _bouncedMessageList.clear();
- Connection con = getConnection();
-
- AMQSession consumerSession = (AMQSession) con.createSession(false, Session.CLIENT_ACKNOWLEDGE);
-
- AMQQueue valid_queue = new AMQQueue(ExchangeDefaults.DIRECT_EXCHANGE_CLASS, "testReturnUnroutableMandatoryMessage_QUEUE");
- AMQQueue invalid_queue = new AMQQueue(ExchangeDefaults.DIRECT_EXCHANGE_CLASS, "testReturnUnroutableMandatoryMessage_QUEUE_INVALID");
- MessageConsumer consumer = consumerSession.createConsumer(valid_queue);
-
- //force synch to ensure the consumer has resulted in a bound queue
- //((AMQSession) consumerSession).declareExchangeSynch(ExchangeDefaults.HEADERS_EXCHANGE_NAME, ExchangeDefaults.HEADERS_EXCHANGE_CLASS);
- // This is the default now
-
- Connection con2 = getConnection();
-
- con2.setExceptionListener(this);
- AMQSession producerSession = (AMQSession) con2.createSession(false, Session.CLIENT_ACKNOWLEDGE);
-
- // Need to start the "producer" connection in order to receive bounced messages
- _logger.info("Starting producer connection");
- con2.start();
-
- MessageProducer nonMandatoryProducer = producerSession.createProducer(valid_queue, false, false);
- MessageProducer mandatoryProducer = producerSession.createProducer(invalid_queue);
-
- // First test - should be routed
- _logger.info("Sending non-mandatory message");
- TextMessage msg1 = producerSession.createTextMessage("msg1");
- nonMandatoryProducer.send(msg1);
-
- // Second test - should be bounced
- _logger.info("Sending non-routable mandatory message");
- TextMessage msg2 = producerSession.createTextMessage("msg2");
- mandatoryProducer.send(msg2);
-
- _logger.info("Starting consumer connection");
- con.start();
- TextMessage tm = (TextMessage) consumer.receive(1000L);
-
- assertTrue("No message routed to receiver", tm != null);
- assertTrue("Wrong message routed to receiver: " + tm.getText(), "msg1".equals(tm.getText()));
-
- try
- {
- Thread.sleep(1000L);
- }
- catch (InterruptedException e)
- {
- ;
- }
-
- assertTrue("Wrong number of messages bounced (expect 1): " + _bouncedMessageList.size(), _bouncedMessageList.size() == 1);
- Message m = _bouncedMessageList.get(0);
- assertTrue("Wrong message bounced: " + m.toString(), m.toString().contains("msg2"));
-
- con.close();
- con2.close();
- }
-
- public void testReturnUnroutableMandatoryMessage_TOPIC() throws Exception
- {
- _bouncedMessageList.clear();
- Connection con = getConnection();
-
- AMQSession consumerSession = (AMQSession) con.createSession(false, Session.CLIENT_ACKNOWLEDGE);
-
- AMQTopic valid_topic = new AMQTopic(ExchangeDefaults.TOPIC_EXCHANGE_CLASS, "test.Return.Unroutable.Mandatory.Message.TOPIC");
- AMQTopic invalid_topic = new AMQTopic(ExchangeDefaults.TOPIC_EXCHANGE_CLASS, "test.Return.Unroutable.Mandatory.Message.TOPIC.invalid");
- MessageConsumer consumer = consumerSession.createConsumer(valid_topic);
-
- //force synch to ensure the consumer has resulted in a bound queue
- //((AMQSession) consumerSession).declareExchangeSynch(ExchangeDefaults.HEADERS_EXCHANGE_NAME, ExchangeDefaults.HEADERS_EXCHANGE_CLASS);
- // This is the default now
-
- Connection con2 = getConnection();
-
- con2.setExceptionListener(this);
- AMQSession producerSession = (AMQSession) con2.createSession(false, Session.CLIENT_ACKNOWLEDGE);
-
- // Need to start the "producer" connection in order to receive bounced messages
- _logger.info("Starting producer connection");
- con2.start();
-
- MessageProducer nonMandatoryProducer = producerSession.createProducer(valid_topic, false, false);
- MessageProducer mandatoryProducer = producerSession.createProducer(invalid_topic);
-
- // First test - should be routed
- _logger.info("Sending non-mandatory message");
- TextMessage msg1 = producerSession.createTextMessage("msg1");
- nonMandatoryProducer.send(msg1);
-
- // Second test - should be bounced
- _logger.info("Sending non-routable mandatory message");
- TextMessage msg2 = producerSession.createTextMessage("msg2");
- mandatoryProducer.send(msg2);
-
- _logger.info("Starting consumer connection");
- con.start();
- TextMessage tm = (TextMessage) consumer.receive(1000L);
-
- assertTrue("No message routed to receiver", tm != null);
- assertTrue("Wrong message routed to receiver: " + tm.getText(), "msg1".equals(tm.getText()));
-
- try
- {
- Thread.sleep(1000L);
- }
- catch (InterruptedException e)
- {
- ;
- }
-
- assertEquals("Wrong number of messages bounced: ", 1, _bouncedMessageList.size());
- Message m = _bouncedMessageList.get(0);
- assertTrue("Wrong message bounced: " + m.toString(), m.toString().contains("msg2"));
-
- con.close();
- con2.close();
- }
-
- public static junit.framework.Test suite()
- {
- return new junit.framework.TestSuite(ReturnUnroutableMandatoryMessageTest.class);
- }
-
- public void onException(JMSException jmsException)
- {
-
- Exception linkedException = null;
- try
- {
- linkedException = jmsException.getLinkedException();
- }
- catch (Exception e)
- {
- e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
- }
- if (linkedException instanceof AMQNoRouteException)
- {
- AMQNoRouteException noRoute = (AMQNoRouteException) linkedException;
- Message bounced = (Message) noRoute.getUndeliveredMessage();
- _bouncedMessageList.add(bounced);
- _logger.info("Caught expected NoRouteException");
- }
- else
- {
- _logger.warn("Caught exception on producer: ", jmsException);
- }
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/server/failover/FailoverMethodTest.java b/java/systests/src/main/java/org/apache/qpid/server/failover/FailoverMethodTest.java
deleted file mode 100644
index ec222ff03d..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/server/failover/FailoverMethodTest.java
+++ /dev/null
@@ -1,254 +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.failover;
-
-import junit.framework.TestCase;
-
-import org.apache.qpid.AMQDisconnectedException;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQConnectionURL;
-import org.apache.qpid.client.transport.TransportConnection;
-import org.apache.qpid.client.vmbroker.AMQVMBrokerCreationException;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-import org.apache.qpid.server.util.InternalBrokerBaseCase;
-import org.apache.qpid.url.URLSyntaxException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.jms.ExceptionListener;
-import javax.jms.JMSException;
-import java.util.concurrent.CountDownLatch;
-
-public class FailoverMethodTest extends InternalBrokerBaseCase implements ExceptionListener
-{
- private CountDownLatch _failoverComplete = new CountDownLatch(1);
- protected static final Logger _logger = LoggerFactory.getLogger(FailoverMethodTest.class);
-
- @Override
- public void createBroker() throws Exception
- {
- super.createBroker();
- TransportConnection.createVMBroker(ApplicationRegistry.DEFAULT_INSTANCE);
- }
-
- @Override
- public void stopBroker()
- {
- TransportConnection.killVMBroker(ApplicationRegistry.DEFAULT_INSTANCE);
- super.stopBroker();
- }
-
- /**
- * Test that the round robin method has the correct delays.
- * The first connection to vm://:1 will work but the localhost connection should fail but the duration it takes
- * to report the failure is what is being tested.
- *
- * @throws URLSyntaxException
- * @throws InterruptedException
- * @throws JMSException
- */
- public void testFailoverRoundRobinDelay() throws URLSyntaxException, InterruptedException, JMSException
- {
- //note: The VM broker has no connect delay and the default 1 retry
- // while the tcp:localhost broker has 3 retries with a 2s connect delay
- String connectionString = "amqp://guest:guest@/test?brokerlist=" +
- "'vm://:" + ApplicationRegistry.DEFAULT_INSTANCE +
- ";tcp://localhost:5670?connectdelay='2000',retries='3''";
-
- AMQConnectionURL url = new AMQConnectionURL(connectionString);
-
- try
- {
- long start = System.currentTimeMillis();
- AMQConnection connection = new AMQConnection(url, null);
-
- connection.setExceptionListener(this);
-
- stopBroker();
-
- _failoverComplete.await();
-
- long end = System.currentTimeMillis();
-
- long duration = (end - start);
-
- //Failover should take more that 6 seconds.
- // 3 Retires
- // so VM Broker NoDelay 0 (Connect) NoDelay 0
- // then TCP NoDelay 0 Delay 1 Delay 2 Delay 3
- // so 3 delays of 2s in total for connection
- // as this is a tcp connection it will take 1second per connection to fail
- // so max time is 6seconds of delay plus 4 seconds of TCP Delay + 1 second of runtime. == 11 seconds
-
- // Ensure we actually had the delay
- assertTrue("Failover took less than 6 seconds", duration > 6000);
-
- // Ensure we don't have delays before initial connection and reconnection.
- // We allow 1 second for initial connection and failover logic on top of 6s of sleep.
- assertTrue("Failover took more than 11 seconds:(" + duration + ")", duration < 11000);
- }
- catch (AMQException e)
- {
- fail(e.getMessage());
- }
- }
-
- public void testFailoverSingleDelay() throws URLSyntaxException, AMQVMBrokerCreationException,
- InterruptedException, JMSException
- {
- String connectionString = "amqp://guest:guest@/test?brokerlist='vm://:1?connectdelay='2000',retries='3''";
-
- AMQConnectionURL url = new AMQConnectionURL(connectionString);
-
- try
- {
- long start = System.currentTimeMillis();
- AMQConnection connection = new AMQConnection(url, null);
-
- connection.setExceptionListener(this);
-
- stopBroker();
-
- _failoverComplete.await();
-
- long end = System.currentTimeMillis();
-
- long duration = (end - start);
-
- //Failover should take more that 6 seconds.
- // 3 Retires
- // so NoDelay 0 (Connect) NoDelay 0 Delay 1 Delay 2 Delay 3
- // so 3 delays of 2s in total for connection
- // so max time is 6 seconds of delay + 1 second of runtime. == 7 seconds
-
- // Ensure we actually had the delay
- assertTrue("Failover took less than 6 seconds", duration > 6000);
-
- // Ensure we don't have delays before initial connection and reconnection.
- // We allow 1 second for initial connection and failover logic on top of 6s of sleep.
- assertTrue("Failover took more than 7 seconds:(" + duration + ")", duration < 7000);
- }
- catch (AMQException e)
- {
- fail(e.getMessage());
- }
- }
-
- public void onException(JMSException e)
- {
- if (e.getLinkedException() instanceof AMQDisconnectedException)
- {
- _logger.debug("Received AMQDisconnectedException");
- _failoverComplete.countDown();
- }
- }
-
- /**
- * Test that setting 'nofailover' as the failover policy does not result in
- * delays or connection attempts when the initial connection is lost.
- *
- * Test validates that there is a connection delay as required on initial
- * connection.
- *
- * @throws URLSyntaxException
- * @throws AMQVMBrokerCreationException
- * @throws InterruptedException
- * @throws JMSException
- */
- public void testNoFailover() throws URLSyntaxException, AMQVMBrokerCreationException,
- InterruptedException, JMSException
- {
- int CONNECT_DELAY = 2000;
- String connectionString = "amqp://guest:guest@/test?brokerlist='vm://:1?connectdelay='" + CONNECT_DELAY + "'," +
- "retries='3'',failover='nofailover'";
-
- AMQConnectionURL url = new AMQConnectionURL(connectionString);
-
- try
- {
- //Kill initial broker
- stopBroker();
-
- //Create a thread to start the broker asynchronously
- Thread brokerStart = new Thread(new Runnable()
- {
- public void run()
- {
- try
- {
- //Wait before starting broker
- // The wait should allow atleast 1 retries to fail before broker is ready
- Thread.sleep(750);
- createBroker();
- }
- catch (Exception e)
- {
- System.err.println(e.getMessage());
- e.printStackTrace();
- }
- }
- });
-
-
- brokerStart.start();
- long start = System.currentTimeMillis();
-
-
- //Start the connection so it will use the retries
- AMQConnection connection = new AMQConnection(url, null);
-
- long end = System.currentTimeMillis();
-
- long duration = (end - start);
-
- // Check that we actually had a delay had a delay in connection
- assertTrue("Initial connection should be longer than 1 delay : " + CONNECT_DELAY + " <:(" + duration + ")", duration > CONNECT_DELAY);
-
-
- connection.setExceptionListener(this);
-
- //Ensure we collect the brokerStart thread
- brokerStart.join();
-
- start = System.currentTimeMillis();
-
- //Kill connection
- stopBroker();
-
- _failoverComplete.await();
-
- end = System.currentTimeMillis();
-
- duration = (end - start);
-
- // Notification of the connection failure should be very quick as we are denying the ability to failover.
- // It may not be as quick for Java profile tests so lets just make sure it is less than the connectiondelay
- // Occasionally it takes 1s so we have to set CONNECT_DELAY to be higher to take that in to account.
- assertTrue("Notification of the connection failure took was : " + CONNECT_DELAY + " >:(" + duration + ")", duration < CONNECT_DELAY);
- }
- catch (AMQException e)
- {
- fail(e.getMessage());
- }
- }
-
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/server/failover/MessageDisappearWithIOExceptionTest.java b/java/systests/src/main/java/org/apache/qpid/server/failover/MessageDisappearWithIOExceptionTest.java
deleted file mode 100644
index 4c2758241e..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/server/failover/MessageDisappearWithIOExceptionTest.java
+++ /dev/null
@@ -1,338 +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.failover;
-
-import org.apache.mina.common.WriteTimeoutException;
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.protocol.AMQProtocolSession;
-import org.apache.qpid.jms.ConnectionListener;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.apache.qpid.test.utils.FailoverBaseCase;
-import org.apache.qpid.AMQConnectionClosedException;
-
-import javax.jms.Destination;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-import javax.jms.Queue;
-import javax.jms.Session;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-/**
- * Test case based on user reported error.
- *
- * Summary:
- * A user has reported message loss from their application. On bouncing of
- * the broker the 'lost' messages are delivered to the broker.
- *
- * Note:
- * The client was using Spring so that may influence the situation.
- *
- * Issue:
- * The log files show 7 instances of the following which result in 7
- * missing messages.
- *
- * The client log files show:
- *
- * The broker log file show:
- *
- *
- * 7 missing messages have delivery tags 5-11. Which says that they are
- * sequentially the next message from the broker.
- *
- * The only way for the 'without a handler' log to occur is if the consumer
- * has been removed from the look up table of the dispatcher.
- * And the only way for the 'null message' log to occur on the broker is is
- * if the message does not exist in the unacked-map
- *
- * The consumer is only removed from the list during session
- * closure and failover.
- *
- * If the session was closed then the broker would requeue the unacked
- * messages so the potential exists to have an empty map but the broker
- * will not send a message out after the unacked map has been cleared.
- *
- * When failover occurs the _consumer map is cleared and the consumers are
- * resubscribed. This is down without first stopping any existing
- * dispatcher so there exists the potential to receive a message after
- * the _consumer map has been cleared which is how the 'without a handler'
- * log statement occurs.
- *
- * Scenario:
- *
- * Looking over logs the sequence that best fits the events is as follows:
- * - Something causes Mina to be delayed causing the WriteTimoutException.
- * - This exception is recevied by AMQProtocolHandler#exceptionCaught
- * - As the WriteTimeoutException is an IOException this will cause
- * sessionClosed to be called to start failover.
- * + This is potentially the issues here. All IOExceptions are treated
- * as connection failure events.
- * - Failover Runs
- * + Failover assumes that the previous connection has been closed.
- * + Failover binds the existing objects (AMQConnection/Session) to the
- * new connection objects.
- * - Everything is reported as being successfully failed over.
- * However, what is neglected is that the original connection has not
- * been closed.
- * + So what occurs is that the broker sends a message to the consumer on
- * the original connection, as it was not notified of the client
- * failing over.
- * As the client failover reuses the original AMQSession and Dispatcher
- * the new messages the broker sends to the old consumer arrives at the
- * client and is processed by the same AMQSession and Dispatcher.
- * However, as the failover process cleared the _consumer map and
- * resubscribe the consumers the Dispatcher does not recognise the
- * delivery tag and so logs the 'without a handler' message.
- * - The Dispatcher then attempts to reject the message, however,
- * + The AMQSession/Dispatcher pair have been swapped to using a new Mina
- * ProtocolSession as part of the failover process so the reject is
- * sent down the second connection. The broker receives the Reject
- * request but as the Message was sent on a different connection the
- * unacknowledgemap is empty and a 'message is null' log message
- * produced.
- *
- * Test Strategy:
- *
- * It should be easy to demonstrate if we can send an IOException to
- * AMQProtocolHandler#exceptionCaught and then try sending a message.
- *
- * The current unknowns here are the type of consumers that are in use.
- * If it was an exclusive queue(Durable Subscription) then why did the
- * resubscribe not fail.
- *
- * If it was not exclusive then why did the messages not round robin?
- */
-public class MessageDisappearWithIOExceptionTest extends FailoverBaseCase implements ConnectionListener
-{
- private CountDownLatch _failoverOccured = new CountDownLatch(1);
- AMQConnection _connection;
- Session _session;
- Queue _queue;
- MessageConsumer _consumer;
-
- public void setUp() throws Exception
- {
- super.setUp();
- stopBroker(getFailingPort());
-
- }
-
- /**
- * Test Summary:
- *
- * Create a queue consumer and send 10 messages to the broker.
- *
- * Consume the first message.
- * This will pull the rest into the prefetch
- *
- * Send an IOException to the MinaProtocolHandler.
- *
- * This will force failover to occur.
- *
- * 9 messages would normally be expected but it is expected that none will
- * arrive. As they are still in the prefetch of the first session.
- *
- * To free the messages we need to close all connections.
- * - Simply doing connection.close() and retesting will not be enough as
- * the original connection's IO layer will still exist and is nolonger
- * connected to the connection object as a result of failover.
- *
- * - Test will need to retain a reference to the original connection IO so
- * that it can be closed releasing the messages to validate that the
- * messages have indeed been 'lost' on that sesssion.
- */
- public void test() throws Exception
- {
- initialiseConnection();
-
- // Create Producer
- // Send 10 messages
- List<Message> messages = sendNumberedBytesMessage(_session, _queue, 10);
-
- // Consume first messasge
- Message received = _consumer.receive(2000);
-
- // Verify received messages
- assertNotNull("First message not received.", received);
- assertEquals("Incorrect message Received",
- messages.remove(0).getIntProperty("count"),
- received.getIntProperty("count"));
-
- // When the Exception is received by the underlying IO layer it will
- // initiate failover. The first step of which is to ensure that the
- // existing conection is closed. So in this situation the connection
- // will be flushed casuing the above ACK to be sent to the broker.
- //
- // That said:
- // when the socket close is detected on the server it will rise up the
- // Mina filter chain and interrupt processing.
- // this has been raised as QPID-2138
- _session.createConsumer(_session.createTemporaryQueue()).close();
-
- //Retain IO Layer
- AMQProtocolSession protocolSession = _connection.getProtocolHandler().getProtocolSession();
-
- // Send IO Exception - causing failover
- _connection.getProtocolHandler().
- exception(new WriteTimeoutException("WriteTimeoutException to cause failover."));
-
- // Verify Failover occured through ConnectionListener
- assertTrue("Failover did not occur",
- _failoverOccured.await(4000, TimeUnit.MILLISECONDS));
-
- /***********************************/
- // This verifies that the bug has been resolved
-
- // Attempt to consume again. Expect 9 messages
- for (int count = 1; count < 10; count++)
- {
- received = _consumer.receive(2000);
- assertNotNull("Expected message not received:" + count, received);
- assertEquals(messages.remove(0).getIntProperty("count"),
- received.getIntProperty("count"));
- }
-
- //Verify there are no more messages
- received = _consumer.receive(1000);
- assertNull("Message receieved when there should be none:" + received,
- received);
-
-// /***********************************/
-// // This verifies that the bug exists
-//
-// // Attempt to consume remaining 9 messages.. Expecting NONE.
-// // receiving just one message should fail so no need to fail 9 times
-// received = _consumer.receive(1000);
-// assertNull("Message receieved when it should be null:" + received, received);
-//
-//// //Close the Connection which you would assume would free the messages
-//// _connection.close();
-////
-//// // Reconnect
-//// initialiseConnection();
-////
-//// // We should still be unable to receive messages
-//// received = _consumer.receive(1000);
-//// assertNull("Message receieved when it should be null:" + received, received);
-////
-//// _connection.close();
-//
-// // Close original IO layer. Expecting messages to be released
-// protocolSession.closeProtocolSession();
-//
-// // Reconnect and all should be good.
-//// initialiseConnection();
-//
-// // Attempt to consume again. Expect 9 messages
-// for (int count = 1; count < 10; count++)
-// {
-// received = _consumer.receive(2000);
-// assertNotNull("Expected message not received:" + count, received);
-// assertEquals(messages.remove(0).getIntProperty("count"),
-// received.getIntProperty("count"));
-// }
-//
-// //Verify there are no more messages
-// received = _consumer.receive(1000);
-// assertNull("Message receieved when there should be none:" + received,
-// received);
- }
-
- private void initialiseConnection()
- throws Exception
- {
- //Create Connection using the default connection URL. i.e. not the Failover URL that would be used by default
- _connection = (AMQConnection) getConnectionFactory("default").createConnection("guest", "guest");
- // The default connection does not have any retries configured so
- // Allow this connection to retry so that we can block on the failover.
- // The alternative would be to use the getConnection() default. However,
- // this would add additional complexity in the logging as a second
- // broker is defined in that url. We do not need it for this test.
- _connection.getFailoverPolicy().getCurrentMethod().setRetries(1);
- _connection.setConnectionListener(this);
-
- _session = _connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- _queue = _session.createQueue(getTestQueueName());
-
- // Create Consumer
- _consumer = _session.createConsumer(_queue);
-
- //Start connection
- _connection.start();
- }
-
- /** QpidTestCase back port to this release */
-
- // modified from QTC as sendMessage is not testable.
- // - should be renamed sendBlankBytesMessage
- // - should be renamed sendNumberedBytesMessage
- public List<Message> sendNumberedBytesMessage(Session session, Destination destination,
- int count) throws Exception
- {
- List<Message> messages = new ArrayList<Message>(count);
-
- MessageProducer producer = session.createProducer(destination);
-
- for (int i = 0; i < count; i++)
- {
- Message next = session.createMessage();
-
- next.setIntProperty("count", i);
-
- producer.send(next);
-
- messages.add(next);
- }
-
- producer.close();
- return messages;
- }
-
- public void bytesSent(long count)
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void bytesReceived(long count)
- {
- }
-
- public boolean preFailover(boolean redirect)
- {
- //Allow failover to occur
- return true;
- }
-
- public boolean preResubscribe()
- {
- //Allow failover to occur
- return true;
- }
-
- public void failoverComplete()
- {
- _failoverOccured.countDown();
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/server/failure/HeapExhaustion.java b/java/systests/src/main/java/org/apache/qpid/server/failure/HeapExhaustion.java
deleted file mode 100644
index 22a1b119fa..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/server/failure/HeapExhaustion.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.failure;
-
-import junit.framework.TestCase;
-import org.apache.qpid.test.utils.QpidClientConnectionHelper;
-import org.apache.qpid.client.failover.FailoverException;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.protocol.AMQConstant;
-import org.apache.log4j.Logger;
-
-import javax.jms.JMSException;
-import javax.jms.DeliveryMode;
-import java.io.IOException;
-
-
-/** Test Case provided by client Non-functional Test NF101: heap exhaustion behaviour */
-public class HeapExhaustion extends TestCase
-{
- private static final Logger _logger = Logger.getLogger(HeapExhaustion.class);
-
- protected QpidClientConnectionHelper conn;
- protected final String BROKER = "localhost";
- protected final String vhost = "/test";
- protected final String queue = "direct://amq.direct//queue";
-
- protected String hundredK;
- protected String megabyte;
-
- protected String generatePayloadOfSize(Integer numBytes)
- {
- return new String(new byte[numBytes]);
- }
-
- protected void setUp() throws Exception
- {
- conn = new QpidClientConnectionHelper(BROKER);
- conn.setVirtualHost(vhost);
-
- try
- {
- conn.connect();
- } catch (JMSException e)
- {
- e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
- }
- // clear queue
- _logger.debug("setup: clearing test queue");
- conn.consume(queue, 2000);
-
- hundredK = generatePayloadOfSize(1024 * 100);
- megabyte = generatePayloadOfSize(1024 * 1024);
- }
-
- protected void tearDown() throws Exception
- {
- conn.disconnect();
- }
-
-
- /**
- * PUT at maximum rate (although we commit after each PUT) until failure
- *
- * @throws Exception on error
- */
- public void testUntilFailureTransient() throws Exception
- {
- int copies = 0;
- int total = 0;
- String payload = hundredK;
- int size = payload.getBytes().length;
- while (true)
- {
- conn.put(queue, payload, 1, DeliveryMode.NON_PERSISTENT);
- copies++;
- total += size;
- System.out.println("put copy " + copies + " OK for total bytes: " + total);
- }
- }
-
- /**
- * PUT at lower rate (5 per second) until failure
- *
- * @throws Exception on error
- */
- public void testUntilFailureWithDelaysTransient() throws Exception
- {
- int copies = 0;
- int total = 0;
- String payload = hundredK;
- int size = payload.getBytes().length;
- while (true)
- {
- conn.put(queue, payload, 1, DeliveryMode.NON_PERSISTENT);
- copies++;
- total += size;
- System.out.println("put copy " + copies + " OK for total bytes: " + total);
- Thread.sleep(200);
- }
- }
-
- public static void noDelay()
- {
- HeapExhaustion he = new HeapExhaustion();
-
- try
- {
- he.setUp();
- }
- catch (Exception e)
- {
- _logger.info("Unable to connect");
- System.exit(0);
- }
-
- try
- {
- _logger.info("Running testUntilFailure");
- try
- {
- he.testUntilFailureTransient();
- }
- catch (FailoverException fe)
- {
- _logger.error("Caught failover:" + fe);
- }
- _logger.info("Finishing Connection ");
-
- try
- {
- he.tearDown();
- }
- catch (JMSException jmse)
- {
- if (((AMQException) jmse.getLinkedException()).getErrorCode() == AMQConstant.REQUEST_TIMEOUT)
- {
- _logger.info("Successful test of testUntilFailure");
- }
- else
- {
- _logger.error("Test Failed due to:" + jmse);
- }
- }
- }
- catch (Exception e)
- {
- _logger.error("Test Failed due to:" + e);
- }
- }
-
- public static void withDelay()
- {
- HeapExhaustion he = new HeapExhaustion();
-
- try
- {
- he.setUp();
- }
- catch (Exception e)
- {
- _logger.info("Unable to connect");
- System.exit(0);
- }
-
- try
- {
- _logger.info("Running testUntilFailure");
- try
- {
- he.testUntilFailureWithDelaysTransient();
- }
- catch (FailoverException fe)
- {
- _logger.error("Caught failover:" + fe);
- }
- _logger.info("Finishing Connection ");
-
- try
- {
- he.tearDown();
- }
- catch (JMSException jmse)
- {
- if (((AMQException) jmse.getLinkedException()).getErrorCode() == AMQConstant.REQUEST_TIMEOUT)
- {
- _logger.info("Successful test of testUntilFailure");
- }
- else
- {
- _logger.error("Test Failed due to:" + jmse);
- }
- }
- }
- catch (Exception e)
- {
- _logger.error("Test Failed due to:" + e);
- }
- }
-
- public static void main(String args[])
- {
- noDelay();
-
-
- try
- {
- System.out.println("Restart failed broker now to retest broker with delays in send.");
- System.in.read();
- }
- catch (IOException e)
- {
- _logger.info("Continuing");
- }
-
- withDelay();
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/server/logging/AbstractTestLogging.java b/java/systests/src/main/java/org/apache/qpid/server/logging/AbstractTestLogging.java
deleted file mode 100644
index f56f428f0b..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/server/logging/AbstractTestLogging.java
+++ /dev/null
@@ -1,448 +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.logging;
-
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-
-import org.apache.commons.configuration.ConfigurationException;
-import org.apache.qpid.server.configuration.ServerConfiguration;
-import org.apache.qpid.server.logging.subjects.AbstractTestLogSubject;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-import org.apache.qpid.server.util.InternalBrokerBaseCase;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.apache.qpid.util.LogMonitor;
-
-/**
- * Abstract superclass for logging test set up and utility methods.
- *
- * So named to prevent it being selected itself as a test to run by the test suite.
- */
-public class AbstractTestLogging extends QpidBrokerTestCase
-{
- public static final long DEFAULT_LOG_WAIT = 2000;
- public static final String TEST_LOG_PREFIX = "MESSAGE";
- protected LogMonitor _monitor;
-
- InternalBrokerBaseCase _configLoader;
-
- @Override
- public void setUp() throws Exception
- {
- setLogMessagePrefix();
-
- super.setUp();
- _monitor = new LogMonitor(_outputFile);
- }
-
- protected ServerConfiguration getServerConfig() throws ConfigurationException
- {
- ServerConfiguration _serverConfiguration;
- if (isExternalBroker())
- {
- _serverConfiguration = new ServerConfiguration(_configFile)
- {
- @Override
- public void initialise() throws ConfigurationException
- {
- //Overriding initialise to only setup the vhosts and not
- //perform the ConfigurationPlugin setup, removing need for
- //an ApplicationRegistry to be loaded.
- setupVirtualHosts(getConfig());
- }
- };
- _serverConfiguration.initialise();
- }
- else
- {
- _serverConfiguration = ApplicationRegistry.getInstance().getConfiguration();
- }
-
- return _serverConfiguration;
- }
-
- protected void setLogMessagePrefix()
- {
- //set the message prefix to facilitate scraping from the munged test output.
- setSystemProperty("qpid.logging.prefix", TEST_LOG_PREFIX);
- }
-
- @Override
- public void tearDown() throws Exception
- {
- _monitor.close();
- if (isExternalBroker() && _configLoader != null)
- {
- _configLoader.tearDown();
- }
- super.tearDown();
- }
-
- /**
- * assert that the requested log message has not occured
- *
- * @param log
- *
- * @throws IOException
- */
- public void assertLoggingNotYetOccured(String log) throws IOException
- {
- // Ensure the alert has not occured yet
- assertEquals("Message has already occured:" + log, 0,
- findMatches(log).size());
- }
-
- protected void validateMessageID(String id, String log)
- {
- assertEquals("Incorrect message", id, getMessageID(log));
- }
-
- protected String getMessageID(String log)
- {
- String message = fromMessage(log);
-
- return message.substring(0, message.indexOf(" "));
- }
-
- /**
- * Return the first channel id from the log string
- * ' ch;X' if there is no channel id return -1.
- *
- * @param log the log string to search.
- *
- * @return channel id or -1 if no channel id exists.
- */
- protected int getChannelID(String log)
- {
- int start = log.indexOf("ch:") + 3;
-
- // If we do a check for ] as the boundary we will get cases where log
- // is presented with the bounding. If we don't match a ] then we can use
- // the end of the string as the boundary.
- int end = log.indexOf("]", start);
- if (end == -1)
- {
- end = log.length();
- }
-
- try
- {
- return Integer.parseInt(log.substring(start, end));
- }
- catch (Exception e)
- {
- return -1;
- }
- }
-
- protected String fromMessage(String log)
- {
- int startSubject = log.indexOf("]") + 1;
- int start = log.indexOf("]", startSubject) + 1;
-
- // If we don't have a subject then the second indexOf will return 0
- // in which case we can use the end of the actor as the index.
- if (start == 0)
- {
- start = startSubject;
- }
-
- return log.substring(start).trim();
- }
-
- /**
- * Extract the Subject from the Log Message.
- *
- * The subject is the second block inclosed in brackets '[ ]'.
- *
- * If there is no Subject or the second block of brackets '[ ]' cannot be
- * identified then an empty String ("") is returned.
- *
- * The brackets '[ ]' are not included in the returned String.
- *
- * @param log The log message to process
- *
- * @return the Subject string or the empty string ("") if the subject can't be identified.
- */
- protected String fromSubject(String log)
- {
- int start = log.indexOf("[") + 1;
- // Take the second index
- start = log.indexOf("[", start) + 1;
-
- // There may not be a subject so in that case return nothing.
- if (start == 0)
- {
- return "";
- }
-
- int end = log.indexOf("]", start);
- try
- {
- return log.substring(start, end);
- }
- catch (IndexOutOfBoundsException iobe)
- {
- return "";
- }
- }
-
- /**
- * Extract the actor segment from the log message.
- * The Actor segment is the first section enclosed in '[ ]'.
- *
- * No analysis is performed to ensure that the first '[ ]' section of the
- * given log is really an Actor segment.
- *
- * The brackets '[ ]' are not included in the returned String.
- *
- * @param log the Log Message
- *
- * @return the Actor segment or "" if unable to locate '[ ]' section
- */
- protected String fromActor(String log)
- {
- int start = log.indexOf("[") + 1;
- int end = log.indexOf("]", start);
- try
- {
- return log.substring(start, end).trim();
- }
- catch (IndexOutOfBoundsException iobe)
- {
- return "";
- }
- }
-
- /**
- * Return the message String from the given message section
- *
- * @param log the Message Section
- *
- * @return the Message String.
- */
- protected String getMessageString(String log)
- {
- // Remove the Log ID from the returned String
- int start = log.indexOf(":") + 1;
-
- return log.substring(start).trim();
- }
-
- /**
- * Given our log message extract the connection ID:
- *
- * The log string will contain the connectionID identified by 'con:'
- *
- * So extract the value shown here by X:
- *
- * 'con:X('
- *
- * Extract the value between the ':' and '(' and process it as an Integer
- *
- * If we are unable to find the right index or process the substring as an
- * Integer then return -1.
- *
- * @param log the log String to process
- *
- * @return the connection ID or -1.
- */
- protected int getConnectionID(String log)
- {
- int conIDStart = log.indexOf("con:") + 4;
- int conIDEnd = log.indexOf("(", conIDStart);
- try
- {
- return Integer.parseInt(log.substring(conIDStart, conIDEnd));
- }
- catch (Exception e)
- {
- return -1;
- }
- }
-
- /**
- * Extract the log entry from the raw log line which will contain other
- * log4j formatting.
- *
- * This formatting may impead our testing process so extract the log message
- * as we know it to be formatted.
- *
- * This starts with the string MESSAGE
- *
- * @param rawLog the raw log
- *
- * @return the log we are expecting to be printed without the log4j prefixes
- */
- protected String getLog(String rawLog)
- {
- int start = rawLog.indexOf(TEST_LOG_PREFIX);
- return rawLog.substring(start);
- }
-
- /**
- * Extract the log entry from the result set. Positions are 0-based.
- *
- * @param results list of log message results to extract from
- * @param position position in the list of the message to extract
- * @return the message string
- */
- protected String getLogMessage(List<String> results, int position)
- {
- return getLog(results.get(position));
- }
-
- /**
- * Extract the nth-from-last log entry from the result set.
- *
- * @param results list of log message results to extract from
- * @param positionFromEnd position from end of the message list to extract (eg 0 for last)
- * @return the message string
- */
- protected String getLogMessageFromEnd(List<String> results, int positionFromEnd)
- {
- int resultSize = results.size();
- return getLogMessage(results, resultSize - 1 - positionFromEnd);
- }
-
- protected List<String> findMatches(String toFind) throws IOException
- {
- return _monitor.findMatches(toFind);
- }
-
- protected List<String> waitAndFindMatches(String toFind) throws IOException
- {
- return waitAndFindMatches(toFind, DEFAULT_LOG_WAIT);
- }
-
- protected List<String> waitAndFindMatches(String toFind, long wait) throws IOException
- {
- return _monitor.waitAndFindMatches(toFind, wait);
- }
-
- public boolean waitForMessage(String message) throws FileNotFoundException, IOException
- {
- return waitForMessage(message, DEFAULT_LOG_WAIT);
- }
-
- public boolean waitForMessage(String message, long wait) throws FileNotFoundException, IOException
- {
- return _monitor.waitForMessage(message, wait, true);
- }
-
- /**
- * Given a list of messages that have been pulled out of a log file
- * Process the results splitting the log statements in to lists based on the
- * actor's connection ID.
- *
- * So for each log entry extract the Connecition ID from the Actor of the log
- *
- * Then use that as a key to a HashMap storing the list of log messages for
- * that connection.
- *
- * @param logMessages The list of mixed connection log messages
- *
- * @return Map indexed by connection id to a list of log messages just for that connection.
- */
- protected HashMap<Integer, List<String>> splitResultsOnConnectionID(List<String> logMessages)
- {
- HashMap<Integer, List<String>> connectionSplitList = new HashMap<Integer, List<String>>();
-
- for (String log : logMessages)
- {
- // Get the connectionID from the Actor in the Message Log.
- int cID = getConnectionID(fromActor(getLog(log)));
-
- List<String> connectionData = connectionSplitList.get(cID);
-
- // Create the initial List if we don't have one already
- if (connectionData == null)
- {
- connectionData = new LinkedList<String>();
- connectionSplitList.put(cID, connectionData);
- }
-
- // Store the log
- connectionData.add(log);
- }
-
- return connectionSplitList;
- }
-
- /**
- * Filter the give result set by the specficifed virtualhost.
- * This is done using the getSlice to identify the virtualhost (vh) in the
- * log message
- *
- * @param results full list of logs
- * @param virtualHostName the virtualhostName to filter on
- *
- * @return the list of messages only for that virtualhost
- */
- protected List<String> filterResultsByVirtualHost(List<String> results, String virtualHostName)
- {
- List<String> filteredResults = new LinkedList<String>();
- Iterator<String> iterator = results.iterator();
-
- while (iterator.hasNext())
- {
- String log = iterator.next();
-
- if (AbstractTestLogSubject.getSlice("vh", log).equals(virtualHostName))
- {
- filteredResults.add(log);
- }
- }
-
- return filteredResults;
- }
-
- /**
- * Dump the log results.
- */
- protected void dumpLogs(List<String> results) throws IOException
- {
- dumpLogs(results, null);
- }
-
- /**
- * Dump the log results or if there are none, the contents of the
- * monitored log file if the monitor is non-null.
- */
- protected void dumpLogs(List<String> results, LogMonitor monitor) throws IOException
- {
- System.err.println("Log Dump:");
- for (String log : results)
- {
- System.err.println(log);
- }
-
- if (results.isEmpty() && monitor != null)
- {
- System.err.println("Monitored file contents:");
- System.err.println(monitor.readFile());
- }
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/server/logging/AccessControlLoggingTest.java b/java/systests/src/main/java/org/apache/qpid/server/logging/AccessControlLoggingTest.java
deleted file mode 100644
index 2629e82831..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/server/logging/AccessControlLoggingTest.java
+++ /dev/null
@@ -1,174 +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.logging;
-
-import java.io.File;
-import java.util.List;
-
-import javax.jms.Connection;
-import javax.jms.JMSException;
-import javax.jms.Session;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.protocol.AMQConstant;
-
-/**
- * ACL version 2/3 file testing to verify that ACL actor logging works correctly.
- *
- * This suite of tests validate that the AccessControl messages occur correctly
- * and according to the following format:
- *
- * <pre>
- * ACL-1001 : Allowed Operation Object {PROPERTIES}
- * ACL-1002 : Denied Operation Object {PROPERTIES}
- * </pre>
- */
-public class AccessControlLoggingTest extends AbstractTestLogging
-{
- private static final String ACL_LOG_PREFIX = "ACL-";
- private static final String USER = "client";
- private static final String PASS = "guest";
-
- public void setUp() throws Exception
- {
- setConfigurationProperty("virtualhosts.virtualhost.test.security.aclv2",
- QpidHome + File.separator + "etc" + File.separator + "test-logging.txt");
-
- super.setUp();
- }
-
- /** FIXME This comes from SimpleACLTest and makes me suspicious. */
- @Override
- public void tearDown() throws Exception
- {
- try
- {
- super.tearDown();
- }
- catch (JMSException e)
- {
- //we're throwing this away as it can happen in this test as the state manager remembers exceptions
- //that we provoked with authentication failures, where the test passes - we can ignore on con close
- }
- }
-
- /**
- * Test that {@code allow} ACL entries do not log anything.
- */
- public void testAllow() throws Exception
- {
- Connection conn = getConnection(USER, PASS);
- Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
- conn.start();
- ((AMQSession<?, ?>) sess).createQueue(new AMQShortString("allow"), false, false, false);
-
- List<String> matches = findMatches(ACL_LOG_PREFIX);
-
- assertTrue("Should be no ACL log messages", matches.isEmpty());
- }
-
- /**
- * Test that {@code allow-log} ACL entries log correctly.
- */
- public void testAllowLog() throws Exception
- {
- Connection conn = getConnection(USER, PASS);
- Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
- conn.start();
- ((AMQSession<?, ?>) sess).createQueue(new AMQShortString("allow-log"), false, false, false);
-
- List<String> matches = findMatches(ACL_LOG_PREFIX);
-
- assertEquals("Should only be one ACL log message", 1, matches.size());
-
- String log = getLogMessage(matches, 0);
- String actor = fromActor(log);
- String subject = fromSubject(log);
- String message = getMessageString(fromMessage(log));
-
- validateMessageID(ACL_LOG_PREFIX + 1001, log);
-
- assertTrue("Actor should contain the user identity", actor.contains(USER));
- assertTrue("Subject should be empty", subject.length() == 0);
- assertTrue("Message should start with 'Allowed'", message.startsWith("Allowed"));
- assertTrue("Message should contain 'Create Queue'", message.contains("Create Queue"));
- assertTrue("Message should have contained the queue name", message.contains("allow-log"));
- }
-
- /**
- * Test that {@code deny-log} ACL entries log correctly.
- */
- public void testDenyLog() throws Exception
- {
- Connection conn = getConnection(USER, PASS);
- Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
- conn.start();
- try {
- ((AMQSession<?, ?>) sess).createQueue(new AMQShortString("deny-log"), false, false, false);
- fail("Should have denied queue creation");
- }
- catch (AMQException amqe)
- {
- // Denied, so exception thrown
- assertEquals("Expected ACCESS_REFUSED error code", AMQConstant.ACCESS_REFUSED, amqe.getErrorCode());
- }
-
- List<String> matches = findMatches(ACL_LOG_PREFIX);
-
- assertEquals("Should only be one ACL log message", 1, matches.size());
-
- String log = getLogMessage(matches, 0);
- String actor = fromActor(log);
- String subject = fromSubject(log);
- String message = getMessageString(fromMessage(log));
-
- validateMessageID(ACL_LOG_PREFIX + 1002, log);
-
- assertTrue("Actor should contain the user identity", actor.contains(USER));
- assertTrue("Subject should be empty", subject.length() == 0);
- assertTrue("Message should start with 'Denied'", message.startsWith("Denied"));
- assertTrue("Message should contain 'Create Queue'", message.contains("Create Queue"));
- assertTrue("Message should have contained the queue name", message.contains("deny-log"));
- }
-
- /**
- * Test that {@code deny} ACL entries do not log anything.
- */
- public void testDeny() throws Exception
- {
- Connection conn = getConnection(USER, PASS);
- Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
- conn.start();
- try {
- ((AMQSession<?, ?>) sess).createQueue(new AMQShortString("deny"), false, false, false);
- fail("Should have denied queue creation");
- }
- catch (AMQException amqe)
- {
- // Denied, so exception thrown
- assertEquals("Expected ACCESS_REFUSED error code", AMQConstant.ACCESS_REFUSED, amqe.getErrorCode());
- }
-
- List<String> matches = findMatches(ACL_LOG_PREFIX);
-
- assertTrue("Should be no ACL log messages", matches.isEmpty());
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/server/logging/AlertingTest.java b/java/systests/src/main/java/org/apache/qpid/server/logging/AlertingTest.java
deleted file mode 100644
index 05aaf16af1..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/server/logging/AlertingTest.java
+++ /dev/null
@@ -1,202 +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.logging;
-
-import javax.jms.Connection;
-import javax.jms.Queue;
-import javax.jms.Session;
-
-import org.apache.qpid.client.AMQDestination;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.server.configuration.ServerConfiguration;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-import org.apache.qpid.util.FileUtils;
-
-public class AlertingTest extends AbstractTestLogging
-{
- private String VIRTUALHOST = "test";
- private Session _session;
- private Connection _connection;
- private Queue _destination;
- private int _numMessages;
-
- private static final int ALERT_LOG_WAIT_PERIOD = 5000;
- private static final String MESSAGE_COUNT_ALERT = "MESSAGE_COUNT_ALERT";
-
- public void setUp() throws Exception
- {
- // Update the configuration to make our virtualhost Persistent.
- makeVirtualHostPersistent(VIRTUALHOST);
- setConfigurationProperty("virtualhosts.virtualhost." + VIRTUALHOST + ".housekeeping.expiredMessageCheckPeriod", "5000");
-
- _numMessages = 50;
-
- // Then we do the normal setup stuff like starting the broker, getting a connection etc.
- super.setUp();
-
- setupConnection();
- }
-
- @Override
- public void tearDown() throws Exception
- {
- // Ensure queue is clean for next run.
- drainQueue(_destination);
- super.tearDown();
- }
-
-
- /**
- * Create a new connection and ensure taht our destination queue is created
- * and bound.
- *
- * Note that the tests here that restart the broker rely on persistence.
- * However, the queue creation here is transient. So the queue will not be
- * rebound on restart. Hence the consumer creation here rather than just the
- * once.
- *
- * The persistent messages will recreate the queue but not bind it (as it
- * was not a durable queue) However, the consumer creation here will ensure
- * that the queue is correctly bound and can receive new messages.
- *
- * @throws Exception
- */
- private void setupConnection()
- throws Exception
- {
- _connection = getConnection();
- _session = _connection.createSession(true, Session.SESSION_TRANSACTED);
- _destination = _session.createQueue(getTestQueueName());
-
- // Consumer is only used to actually create the destination
- _session.createConsumer(_destination).close();
- }
-
- /**
- * Checks the log file for MESSAGE_COUNT_ALERT, fails() the test if it's not found and
- * places the entire contents in the message to help debug cruise control failures.
- *
- * @throws Exception
- */
- private void wasAlertFired() throws Exception
- {
- if (!waitForMessage(MESSAGE_COUNT_ALERT, ALERT_LOG_WAIT_PERIOD))
- {
- StringBuffer message = new StringBuffer("Could not find 'MESSAGE_COUNT_ALERT' in log file: " + _monitor.getMonitoredFile().getAbsolutePath());
- message.append("\n");
-
- // Add the current contents of the log file to test output
- message.append(_monitor.readFile());
-
- // Write the test config file to test output
- message.append("Server configuration overrides in use:\n");
- message.append(FileUtils.readFileAsString(getTestConfigFile()));
-
- message.append("\nVirtualhost maxMessageCount:\n");
- ServerConfiguration config = new ServerConfiguration(_configFile);
- config.initialise();
- message.append(config.getVirtualHostConfig(VIRTUALHOST).getMaximumMessageCount());
-
- fail(message.toString());
- }
- }
-
- public void testAlertingReallyWorks() throws Exception
- {
- // Send 5 messages, make sure that the alert was fired properly.
- sendMessage(_session, _destination, _numMessages + 1);
- _session.commit();
- wasAlertFired();
- }
-
- public void testAlertingReallyWorksWithRestart() throws Exception
- {
- sendMessage(_session, _destination, _numMessages + 1);
- _session.commit();
- _connection.close();
- stopBroker();
-
- // Rest the monitoring clearing the current output file.
- _monitor.reset();
- startBroker();
- wasAlertFired();
- }
-
- /**
- * Test that if the alert value is change from the previous value we can
- * still get alerts.
- *
- * Test sends two messages to the broker then restarts the broker with new
- * configuration.
- *
- * If the test is running inVM the test validates that the new configuration
- * has been applied.
- *
- * Validates that we only have two messages on the queue and then sends
- * enough messages to trigger the alert.
- *
- * The alert is then validate.
- *
- *
- * @throws Exception
- */
- public void testAlertingReallyWorksWithChanges() throws Exception
- {
- // send some messages and nuke the logs
- sendMessage(_session, _destination, 2);
- _session.commit();
- // To prevent any failover/retry/connection dropped errors
- _connection.close();
-
- stopBroker();
-
- _monitor.reset();
-
- // Change max message count to 5, start broker and make sure that that's triggered at the right time
- setConfigurationProperty("virtualhosts.virtualhost." + VIRTUALHOST + ".queues.maximumMessageCount", "5");
-
- startBroker();
-
- if (!isExternalBroker())
- {
- assertEquals("Alert Max Msg Count is not correct", 5, ApplicationRegistry.getInstance().getVirtualHostRegistry().
- getVirtualHost(VIRTUALHOST).getQueueRegistry().getQueue(new AMQShortString(_destination.getQueueName())).
- getMaximumMessageCount());
- }
-
- setupConnection();
-
- // Validate the queue depth is as expected
- long messageCount = ((AMQSession<?, ?>) _session).getQueueDepth((AMQDestination) _destination);
- assertEquals("Broker has invalid message count for test", 2, messageCount);
-
- // Ensure the alert has not occured yet
- assertLoggingNotYetOccured(MESSAGE_COUNT_ALERT);
-
- // Trigger the new value
- sendMessage(_session, _destination, 3);
- _session.commit();
-
- // Validate that the alert occured.
- wasAlertFired();
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/server/logging/BindingLoggingTest.java b/java/systests/src/main/java/org/apache/qpid/server/logging/BindingLoggingTest.java
deleted file mode 100644
index 97914f84a5..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/server/logging/BindingLoggingTest.java
+++ /dev/null
@@ -1,271 +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.logging;
-
-import org.apache.qpid.server.logging.subjects.AbstractTestLogSubject;
-
-import javax.jms.Connection;
-import javax.jms.JMSException;
-import javax.jms.Queue;
-import javax.jms.Session;
-import javax.jms.Topic;
-import java.io.IOException;
-import java.util.List;
-
-/**
- * Binding
- *
- * The Binding test suite validates that the follow log messages as specified in the Functional Specification.
- *
- * This suite of tests validate that the Binding messages occur correctly and according to the following format:
- *
- * BND-1001 : Create [: Arguments : <key=value>]
- * BND-1002 : Deleted
- */
-public class BindingLoggingTest extends AbstractTestLogging
-{
-
- static final String BND_PREFIX = "BND-";
-
- Connection _connection;
- Session _session;
- Queue _queue;
- Topic _topic;
-
- @Override
- public void setUp() throws Exception
- {
- super.setUp();
- //Ignore broker startup messages
- _monitor.reset();
-
- _connection = getConnection();
-
- _session = _connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- _queue = _session.createQueue(getName());
- _topic = (Topic) getInitialContext().lookup(TOPIC);
- }
-
- private void validateLogMessage(String log, String messageID, String message, String exchange, String rkey, String queueName)
- {
- validateMessageID(messageID, log);
-
- String subject = fromSubject(log);
-
- assertEquals("Queue not correct.", queueName,
- AbstractTestLogSubject.getSlice("qu", subject));
- assertEquals("Routing Key not correct.", rkey,
- AbstractTestLogSubject.getSlice("rk", subject));
- assertEquals("Virtualhost not correct.", "/test",
- AbstractTestLogSubject.getSlice("vh", subject));
- assertEquals("Exchange not correct.", exchange,
- AbstractTestLogSubject.getSlice("ex", subject));
-
- assertEquals("Log Message not as expected", message, getMessageString(fromMessage(log)));
- }
-
- /**
- * testBindingCreate
- *
- * Description:
- * The binding of a Queue and an Exchange is done via a Binding. When this Binding is created a BND-1001 Create message will be logged.
- * Input:
- *
- * 1. Running Broker
- * 2. New Client requests that a Queue is bound to a new exchange.
- * Output:
- *
- * <date> BND-1001 : Create : Arguments : {x-filter-jms-selector=}
- *
- * Validation Steps:
- * 3. The BND ID is correct
- * 4. This will be the first message for the given binding
- */
- public void testBindingCreate() throws JMSException, IOException
- {
- _session.createConsumer(_queue).close();
-
- List<String> results = waitAndFindMatches(BND_PREFIX);
-
- // We will have two binds as we bind all queues to the default exchange
- assertEquals("Result set larger than expected.", 2, results.size());
-
- String exchange = "direct/<<default>>";
- String messageID = "BND-1001";
- String message = "Create";
- String queueName = _queue.getQueueName();
-
- validateLogMessage(getLogMessage(results, 0), messageID, message, exchange, queueName, queueName);
-
- exchange = "direct/amq.direct";
- message = "Create : Arguments : {x-filter-jms-selector=}";
- validateLogMessage(getLogMessage(results, 1), messageID, message, exchange, queueName, queueName);
- }
-
- /**
- * Description:
- * A Binding can be made with a set of arguments. When this occurs we logged the key,value pairs as part of the Binding log message. When the subscriber with a JMS Selector consumes from an exclusive queue such as a topic. The binding is made with the JMS Selector as an argument.
- * Input:
- *
- * 1. Running Broker
- * 2. Java Client consumes from a topic with a JMS selector.
- * Output:
- *
- * <date> BND-1001 : Create : Arguments : {x-filter-jms-selector=<value>}
- *
- * Validation Steps:
- * 3. The BND ID is correct
- * 4. The JMS Selector argument is present in the message
- * 5. This will be the first message for the given binding
- */
- public void testBindingCreateWithArguments() throws JMSException, IOException
- {
- final String SELECTOR = "Selector='True'";
-
- _session.createDurableSubscriber(_topic, getName(), SELECTOR, false).close();
-
- List<String> results = waitAndFindMatches(BND_PREFIX);
-
- // We will have two binds as we bind all queues to the default exchange
- assertEquals("Result set larger than expected.", 2, results.size());
-
- //Verify the first entry is the default binding
- String messageID = "BND-1001";
- String message = "Create";
-
- validateLogMessage(getLogMessage(results, 0), messageID, message,
- "direct/<<default>>", "clientid:" + getName(), "clientid:" + getName());
-
- //Default binding will be without the selector
- assertTrue("JMSSelector identified in binding:"+message, !message.contains("jms-selector"));
-
- // Perform full testing on the second non default binding
- message = getMessageString(fromMessage(getLogMessage(results, 1)));
-
- validateLogMessage(getLogMessage(results, 1), messageID, message,
- "topic/amq.topic", "topic", "clientid:" + getName());
-
- assertTrue("JMSSelector not identified in binding:"+message, message.contains("jms-selector"));
- assertTrue("Selector not part of binding.:"+message, message.contains(SELECTOR));
-
- }
-
- /**
- * Description:
- * Bindings can be deleted so that a queue can be rebound with a different set of values.
- * Input:
- *
- * 1. Running Broker
- * 2. AMQP UnBind Request is made
- * Output:
- *
- * <date> BND-1002 : Deleted
- *
- * Validation Steps:
- * 3. The BND ID is correct
- * 4. There must have been a BND-1001 Create message first.
- * 5. This will be the last message for the given binding
- */
- public void testBindingDelete() throws JMSException, IOException
- {
- //Closing a consumer on a temporary queue will cause it to autodelete
- // and so unbind.
- _session.createConsumer(_session.createTemporaryQueue()).close();
-
- if(isBroker010())
- {
- //auto-delete is at session close for 0-10
- _session.close();
- }
-
- //wait for the deletion messages to be logged
- waitForMessage("BND-1002");
-
- //gather all the BND messages
- List<String> results = waitAndFindMatches(BND_PREFIX);
-
- // We will have two binds as we bind all queues to the default exchange
- assertEquals("Result not as expected." + results, 4, results.size());
-
-
- String messageID = "BND-1001";
- String message = "Create";
-
- String log = getLogMessage(results, 0);
- validateMessageID(messageID, log);
- assertEquals("Log Message not as expected", message, getMessageString(fromMessage(log)));
-
- log = getLogMessage(results, 1);
- validateMessageID(messageID, log);
- assertEquals("Log Message not as expected", message, getMessageString(fromMessage(log)));
-
-
- String DEFAULT = "direct/<<default>>";
- String DIRECT = "direct/amq.direct";
-
- messageID = "BND-1002";
- message = "Deleted";
-
- log = getLogMessage(results, 2);
- validateMessageID(messageID, log);
-
- String subject = fromSubject(log);
-
- validateBindingDeleteArguments(subject, "/test");
-
- boolean defaultFirst = DEFAULT.equals(AbstractTestLogSubject.getSlice("ex", subject));
- boolean directFirst = DIRECT.equals(AbstractTestLogSubject.getSlice("ex", subject));
-
- assertEquals("Log Message not as expected", message, getMessageString(fromMessage(log)));
-
- log = getLogMessage(results, 3);
-
- validateMessageID(messageID, log);
-
- subject = fromSubject(log);
-
- validateBindingDeleteArguments(subject, "/test");
-
- if (!defaultFirst)
- {
- assertEquals(DEFAULT, AbstractTestLogSubject.getSlice("ex", subject));
- assertTrue("First Exchange Log was not a direct exchange delete",directFirst);
- }
- else
- {
- assertEquals(DIRECT, AbstractTestLogSubject.getSlice("ex", subject));
- assertTrue("First Exchange Log was not a default exchange delete",defaultFirst);
- }
-
- assertEquals("Log Message not as expected", message, getMessageString(fromMessage(log)));
- }
-
- private void validateBindingDeleteArguments(String subject, String vhostName)
- {
- String routingKey = AbstractTestLogSubject.getSlice("rk", subject);
-
- assertTrue("Routing Key does not start with TempQueue:"+routingKey,
- routingKey.startsWith("TempQueue"));
- assertEquals("Virtualhost not correct.", vhostName,
- AbstractTestLogSubject.getSlice("vh", subject));
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/server/logging/BrokerLoggingTest.java b/java/systests/src/main/java/org/apache/qpid/server/logging/BrokerLoggingTest.java
deleted file mode 100644
index 8fd2c085c3..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/server/logging/BrokerLoggingTest.java
+++ /dev/null
@@ -1,1003 +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.logging;
-
-import junit.framework.AssertionFailedError;
-import org.apache.qpid.server.Main;
-import org.apache.qpid.transport.ConnectionException;
-import org.apache.qpid.util.LogMonitor;
-
-import java.io.File;
-import java.io.IOException;
-import java.net.Socket;
-import java.util.List;
-
-/**
- * Broker Test Suite
- *
- * The Broker test suite validates that the follow log messages as specified in the Functional Specification.
- *
- * BRK-1001 : Startup : Version: <Version> Build: <Build>
- * BRK-1002 : Starting : Listening on <Transport> port <Port>
- * BRK-1003 : Shuting down : <Transport> port <Port>
- * BRK-1004 : Ready
- * BRK-1005 : Stopped
- * BRK-1006 : Using configuration : <path>
- * BRK-1007 : Using logging configuration : <path>
- *
- * These messages should only occur during startup. The tests need to verify the order of messages. In the case of the BRK-1002 and BRK-1003 the respective ports should only be available between the two log messages.
- */
-public class BrokerLoggingTest extends AbstractTestLogging
-{
- private static final String BRK_LOG_PREFIX = "BRK-";
-
- public void setUp() throws Exception
- {
- setLogMessagePrefix();
-
- // We either do this here or have a null check in tearDown.
- // As when this test is run against profiles other than java it will NPE
- _monitor = new LogMonitor(_outputFile);
- //We explicitly do not call super.setUp as starting up the broker is
- //part of the test case.
- }
-
- /**
- * Description:
- * On startup the broker must report the active configuration file. The
- * logging system must output this so that we can know what configuration
- * is being used for this broker instance.
- *
- * Input:
- * The value of -c specified on the command line.
- * Output:
- * <date> MESSAGE BRK-1006 : Using configuration : <config file>
- * Constraints:
- * This MUST BE the first BRK log message.
- *
- * Validation Steps:
- * 1. This is first BRK log message.
- * 2. The BRK ID is correct
- * 3. The config file is the full path to the file specified on
- * the commandline.
- *
- * @throws Exception caused by broker startup
- */
- public void testBrokerStartupConfiguration() throws Exception
- {
- String TESTID="BRK-1006";
-
- // This logging startup code only occurs when you run a Java broker,
- // that broker must be started via Main so not an InVM broker.
- if (isJavaBroker() && isExternalBroker())
- {
- startBroker();
-
- // Now we can create the monitor as _outputFile will now be defined
- _monitor = new LogMonitor(_outputFile);
-
-
- String configFilePath = _configFile.toString();
-
- // Ensure we wait for TESTID to be logged
- waitAndFindMatches(TESTID);
-
- List<String> results = waitAndFindMatches(BRK_LOG_PREFIX);
- try
- {
- // Validation
-
- assertTrue("BRKer message not logged", results.size() > 0);
-
- String log = getLogMessage(results, 0);
-
- //1
- validateMessageID(TESTID, log);
-
- //2
- results = findMatches(TESTID);
- assertEquals("More than one configuration message found.",
- 1, results.size());
-
- //3
- assertTrue("Config file details not correctly logged",
- log.endsWith(configFilePath));
- }
- catch (AssertionFailedError afe)
- {
- dumpLogs(results, _monitor);
-
- throw afe;
- }
- }
- }
-
- /**
- * Description:
- * On startup the broker must report correctly report the log4j file in use. This is important as it can help diagnose why logging messages are not being reported.
- * Input:
- * No custom -l value should be provided on the command line so that the default value is correctly reported.
- * Output:
- *
- * <date> MESSAGE BRK-1007 : Using logging configuration : <$QPID_HOME>/etc/log4j.xml
- *
- * Validation Steps:
- *
- * 1. The BRK ID is correct
- * 2. This occurs before the BRK-1001 startup message.
- * 3. The log4j file is the full path to the file specified on the commandline.
- *
- * @throws Exception caused by broker startup
- */
- public void testBrokerStartupDefaultLog4j() throws Exception
- {
- // This logging startup code only occurs when you run a Java broker,
- // that broker must be started via Main so not an InVM broker.
- if (isJavaBroker() && isExternalBroker())
- {
- String TESTID = "BRK-1007";
-
- //Remove test Log4j config from the commandline
- _broker = _broker.substring(0, _broker.indexOf("-l"));
-
- startBroker();
-
- // Now we can create the monitor as _outputFile will now be defined
- _monitor = new LogMonitor(_outputFile);
-
- // Ensure broker has fully started up.
- getConnection();
-
- // Ensure we wait for TESTID to be logged
- waitAndFindMatches(TESTID);
-
- List<String> results = waitAndFindMatches(BRK_LOG_PREFIX);
- try
- {
- // Validation
-
- assertTrue("BRKer message not logged", results.size() > 0);
-
- boolean validation = false;
- for (String rawLog : results)
- {
- // We don't care about messages after we have our log config
- if (validation)
- {
- break;
- }
-
- String log = getLog(rawLog);
-
- // Ensure we do not have a BRK-1001 message before
- if (!getMessageID(log).equals(TESTID))
- {
- assertFalse(getMessageID(log).equals("BRK-1001"));
- continue;
- }
-
- //1
- validateMessageID(TESTID, log);
-
- //2
- //There will be 1 copy of this startup message (via SystemOut)
- assertEquals("Unexpected log4j configuration message count.",
- 1, findMatches(TESTID).size());
-
- //3
- String defaultLog4j = _configFile.getParent() + "/" + Main.DEFAULT_LOG_CONFIG_FILENAME;
- assertTrue("Log4j file(" + defaultLog4j + ") details not correctly logged:" + getMessageString(log),
- getMessageString(log).endsWith(defaultLog4j));
-
- validation = true;
- }
-
- assertTrue("Validation not performed: " + TESTID + " not logged", validation);
- }
- catch (AssertionFailedError afe)
- {
- dumpLogs(results, _monitor);
-
- throw afe;
- }
- }
- }
-
- /**
- * Description:
- * On startup the broker must report correctly report the log4j file in use. This is important as it can help diagnose why logging messages are not being reported. The broker must also be capable of correctly recognising the command line property to specify the custom logging configuration.
- * Input:
- * The value of -l specified on the command line.
- * Output:
- *
- * <date> MESSAGE BRK-1007 : Using logging configuration : <log4j file>
- *
- * Validation Steps:
- *
- * 1. The BRK ID is correct
- * 2. This should occur before the BRK-1001 : Startup message
- * 3. The log4j file is the full path to the file specified on the commandline.
- *
- * @throws Exception caused by broker startup
- */
- public void testBrokerStartupCustomLog4j() throws Exception
- {
- // This logging startup code only occurs when you run a Java broker,
- // that broker must be started via Main so not an InVM broker.
- if (isJavaBroker() && isExternalBroker())
- {
- // Get custom -l value used during testing for the broker startup
- String customLog4j = _broker.substring(_broker.indexOf("-l") + 2);
-
- String TESTID = "BRK-1007";
-
- startBroker();
-
- // Now we can create the monitor as _outputFile will now be defined
- _monitor = new LogMonitor(_outputFile);
-
-
- // Ensure broker has fully started up.
- getConnection();
-
- // Ensure we wait for TESTID to be logged
- waitAndFindMatches(TESTID);
-
- List<String> results = waitAndFindMatches(BRK_LOG_PREFIX);
- try
- {
- // Validation
-
- assertTrue("BRKer message not logged", results.size() > 0);
-
- boolean validation = false;
- for (String rawLog : results)
- {
- // We don't care about messages after we have our log config
- if (validation)
- {
- break;
- }
- String log = getLog(rawLog);
-
- // Ensure we do not have a BRK-1001 message before
- if (!getMessageID(log).equals(TESTID))
- {
- assertFalse(getMessageID(log).equals("BRK-1001"));
- continue;
- }
-
- //1
- validateMessageID(TESTID, log);
-
- //2
- //There will be 1 copy of this startup message (via SystemOut)
- assertEquals("Unexpected log4j configuration message count.",
- 1, findMatches(TESTID).size());
-
- //3
- assertTrue("Log4j file details not correctly logged:" + getMessageString(log),
- getMessageString(log).endsWith(customLog4j));
-
- validation = true;
- }
-
- assertTrue("Validation not performed: " + TESTID + " not logged", validation);
- }
- catch (AssertionFailedError afe)
- {
- dumpLogs(results, _monitor);
-
- throw afe;
- }
- }
- }
-
- /**
- * Description: On startup the broker reports the broker version number and svn build revision. This information is retrieved from the resource 'qpidversion.properties' which is located via the classloader.
- * Input: The 'qpidversion.properties' file located on the classpath.
- * Output:
- *
- * <date> MESSAGE BRK-1001 : Startup : qpid Version: 0.6 Build: 767150
- *
- * Validation Steps:
- *
- * 1. The BRK ID is correct
- * 2. This occurs before any BRK-1002 listening messages are reported.
- *
- * @throws Exception caused by broker startup
- */
- public void testBrokerStartupStartup() throws Exception
- {
- // This logging startup code only occurs when you run a Java broker,
- // that broker must be started via Main so not an InVM broker.
- if (isJavaBroker() && isExternalBroker())
- {
- String TESTID = "BRK-1001";
-
- startBroker();
-
- // Now we can create the monitor as _outputFile will now be defined
- _monitor = new LogMonitor(_outputFile);
-
- // Ensure we wait for TESTID to be logged
- waitAndFindMatches(TESTID);
-
- // Retrieve all BRK- log messages so we can check for an erroneous
- // BRK-1002 message.
- List<String> results = findMatches(BRK_LOG_PREFIX);
-
- try
- {
- // Validation
-
- assertTrue("BRKer message not logged", results.size() > 0);
-
- boolean validation = false;
- for (String rawLog : results)
- {
- if (validation)
- {
- //Stop checking once we have got to our startup test
- break;
- }
- String log = getLog(rawLog);
-
- // Ensure we do not have a BRK-1002 message
- if (!getMessageID(log).equals(TESTID))
- {
- assertFalse(getMessageID(log).equals("BRK-1002"));
- continue;
- }
-
- //1
- validateMessageID(TESTID, log);
-
- //2
- //There will be 2 copies of the startup message (one via SystemOut, and one via Log4J)
- assertEquals("Unexpected startup message count",
- 2, findMatches(TESTID).size());
-
- validation = true;
- }
-
- assertTrue("Validation not performed: " + TESTID + " not logged", validation);
- }
- catch (AssertionFailedError afe)
- {
- dumpLogs(results, _monitor);
-
- throw afe;
- }
- }
- }
-
- /**
- * Description:
- * On startup the broker may listen on a number of ports and protocols. Each of these must be reported as they are made available.
- * Input:
- * The default configuration with no SSL
- * Output:
- *
- * <date> MESSAGE BRK-1002 : Starting : Listening on TCP port 5672
- *
- * Constraints:
- * Additional broker configuration will occur between the Startup(BRK-1001) and Starting(BRK-1002) messages depending on what VirtualHosts are configured.
- * Validation Steps:
- *
- * 1. The BRK ID is correct
- * 2. This occurs after the BRK-1001 startup message
- * 3. Using the default configuration a single BRK-1002 will be printed showing values TCP / 5672
- *
- * @throws Exception caused by broker startup
- */
- public void testBrokerStartupListeningTCPDefault() throws Exception
- {
- // This logging startup code only occurs when you run a Java broker,
- // that broker must be started via Main so not an InVM broker.
- if (isJavaBroker() && isExternalBroker())
- {
- String TESTID = "BRK-1002";
-
- startBroker();
-
- // Now we can create the monitor as _outputFile will now be defined
- _monitor = new LogMonitor(_outputFile);
-
- // Ensure broker has fully started up.
- getConnection();
-
- // Ensure we wait for TESTID to be logged
- waitAndFindMatches(TESTID);
-
- // Retrieve all BRK- log messages so we can check for an erroneous
- // BRK-1002 message.
- List<String> results = findMatches(BRK_LOG_PREFIX);
- try
- {
- // Validation
-
- assertTrue("BRKer message not logged", results.size() > 0);
-
- boolean validation = false;
- boolean foundBRK1001 = false;
- for (String rawLog : results)
- {
- String log = getLog(rawLog);
-
- // Ensure we do not have a BRK-1002 message
- if (!getMessageID(log).equals(TESTID))
- {
- if (getMessageID(log).equals("BRK-1001"))
- {
- foundBRK1001 = true;
- }
- continue;
- }
-
- assertTrue("BRK-1001 not logged before this message", foundBRK1001);
-
- //1
- validateMessageID(TESTID, log);
-
- //2
- //There will be 2 copies of the startup message (one via SystemOut, and one via Log4J)
- assertEquals("Unexpected listen message count",
- 2, findMatches(TESTID).size());
-
- //3
- String message = getMessageString(log);
- assertTrue("Expected Listen log not correct" + message,
- message.endsWith("Listening on TCP port " + getPort()));
-
- validation = true;
- }
-
- assertTrue("Validation not performed: " + TESTID + " not logged", validation);
- }
- catch (AssertionFailedError afe)
- {
- dumpLogs(results, _monitor);
-
- throw afe;
- }
- }
- }
-
- /**
- * Description:
- * On startup the broker may listen on a number of ports and protocols. Each of these must be reported as they are made available.
- * Input:
- * The default configuration with SSL enabled
- * Output:
- *
- * <date> MESSAGE BRK-1002 : Starting : Listening on TCP port 5672
- * <date> MESSAGE BRK-1002 : Starting : Listening on TCP/SSL port 8672
- *
- * Constraints:
- * Additional broker configuration will occur between the Startup(BRK-1001) and Starting(BRK-1002) messages depending on what VirtualHosts are configured.
- * Validation Steps:
- *
- * 1. The BRK ID is correct
- * 2. This occurs after the BRK-1001 startup message
- * 3. With SSL enabled in the configuration two BRK-1002 will be printed (order is not specified)
- * 1. One showing values TCP / 5672
- * 2. One showing values TCP/SSL / 5672
- *
- * @throws Exception caused by broker startup
- */
- public void testBrokerStartupListeningTCPSSL() throws Exception
- {
- // This logging startup code only occurs when you run a Java broker,
- // that broker must be started via Main so not an InVM broker.
- if (isJavaBroker() && isExternalBroker())
- {
- String TESTID = "BRK-1002";
-
- // Enable SSL on the connection
- setConfigurationProperty("connector.ssl.enabled", "true");
- setConfigurationProperty("connector.ssl.sslOnly", "false");
- setConfigurationProperty("connector.ssl.keyStorePath", getConfigurationStringProperty("management.ssl.keyStorePath"));
- setConfigurationProperty("connector.ssl.keyStorePassword", getConfigurationStringProperty("management.ssl.keyStorePassword"));
-
- Integer sslPort = Integer.parseInt(getConfigurationStringProperty("connector.sslport"));
-
- startBroker();
-
- // Now we can create the monitor as _outputFile will now be defined
- _monitor = new LogMonitor(_outputFile);
-
- // Ensure broker has fully started up.
- getConnection();
-
- // Ensure we wait for TESTID to be logged
- waitAndFindMatches(TESTID);
-
- // Retrieve all BRK- log messages so we can check for an erroneous
- // BRK-1002 message.
- List<String> results = findMatches(BRK_LOG_PREFIX);
- try
- {
- // Validation
-
- assertTrue("BRKer message not logged", results.size() > 0);
-
- boolean validation = false;
- boolean foundBRK1001 = false;
- for (String rawLog : results)
- {
- String log = getLog(rawLog);
-
- // Ensure we do not have a BRK-1002 message
- if (!getMessageID(log).equals(TESTID))
- {
- if (getMessageID(log).equals("BRK-1001"))
- {
- foundBRK1001 = true;
- }
- continue;
- }
-
- assertTrue("BRK-1001 not logged before this message", foundBRK1001);
-
- //1
- validateMessageID(TESTID, log);
-
- //2
- //There will be 4 copies of the startup message (two via SystemOut, and two via Log4J)
- List<String> listenMessages = findMatches(TESTID);
- assertEquals("Four listen messages should be found.",
- 4, listenMessages .size());
-
- //3
- //Check the first
- String message = getMessageString(getLog(listenMessages .get(0)));
- assertTrue("Expected Listen log not correct" + message,
- message.endsWith("Listening on TCP port " + getPort()));
-
- // Check the third, ssl listen.
- message = getMessageString(getLog(listenMessages .get(2)));
- assertTrue("Expected Listen log not correct" + message,
- message.endsWith("Listening on TCP/SSL port " + sslPort));
-
- //4 Test ports open
- testSocketOpen(getPort());
- testSocketOpen(sslPort);
-
- validation = true;
- }
-
- assertTrue("Validation not performed: " + TESTID + " not logged", validation);
- }
- catch (AssertionFailedError afe)
- {
- dumpLogs(results, _monitor);
-
- throw afe;
- }
- }
- }
-
- /**
- * Description:
- * The final message the broker will print when it has performed all initialisation and listener startups will be to log the BRK-1004 Ready message
- * Input:
- * No input, all successful broker startups will show BRK-1004 messages.
- * Output:
- *
- * 2009-07-09 15:50:20 +0100 MESSAGE BRK-1004 : Qpid Broker Ready
- *
- * Validation Steps:
- *
- * 1. The BRK ID is correct
- * 2. This occurs after the BRK-1001 startup message
- * 3. This must be the last message the broker prints after startup. Currently, if there is no further interaction with the broker then there should be no more logging.
- *
- * @throws Exception caused by broker startup
- */
- public void testBrokerStartupReady() throws Exception
- {
- // This logging startup code only occurs when you run a Java broker,
- // that broker must be started via Main so not an InVM broker.
- if (isJavaBroker() && isExternalBroker())
- {
- String TESTID = "BRK-1004";
-
- startBroker();
-
- //Ensure the broker has fully started up.
- getConnection();
- // Ensure we wait for TESTID to be logged
- waitAndFindMatches(TESTID);
-
- // Retrieve all BRK- log messages so we can check for an erroneous
- // BRK-1001 message.
- List<String> results = findMatches(BRK_LOG_PREFIX);
- try
- {
- // Validation
-
- assertTrue("BRKer message not logged", results.size() > 0);
-
- boolean validationComplete = false;
- boolean foundBRK1001 = false;
-
- for (int i=0; i < results.size(); i++)
- {
- String rawLog = results.get(i);
- String log = getLog(rawLog);
-
- // Ensure we do not have a BRK-1001 message
- if (!getMessageID(log).equals(TESTID))
- {
- if (getMessageID(log).equals("BRK-1001"))
- {
- foundBRK1001 = true;
- }
- continue;
- }
-
- assertTrue("BRK-1001 not logged before this message", foundBRK1001);
-
- //1
- validateMessageID(TESTID, log);
-
- //2
- assertEquals("Ready message not present", "Qpid Broker Ready", getMessageString(log));
-
- //There will be 2 copies of the startup message (one via SystemOut, and one via Log4J)
- assertEquals("Unexpected ready message count",
- 2, findMatches(TESTID).size());
- assertEquals("The ready messages should have been the last 2 messages", results.size() - 2, i);
-
- validationComplete = true;
- break;
- }
-
- assertTrue("Validation not performed: " + TESTID + " not logged", validationComplete);
- }
- catch (AssertionFailedError afe)
- {
- dumpLogs(results, _monitor);
-
- throw afe;
- }
- }
- }
-
- /**
- * Description:
- * On startup the broker may listen on a number of ports and protocols. Each of these must then report a shutting down message as they stop listening.
- * Input:
- * The default configuration with no SSL
- * Output:
- *
- * <date> MESSAGE BRK-1003 : Shutting down : TCP port 5672
- *
- * Validation Steps:
- *
- * 1. The BRK ID is correct
- * 2. Only TCP is reported with the default configuration with no SSL.
- * 3. The default port is correct
- * 4. The port is not accessible after this message
- *
- * @throws Exception caused by broker startup
- */
- public void testBrokerShutdownListeningTCPDefault() throws Exception
- {
- // This logging startup code only occurs when you run a Java broker,
- // that broker must be started via Main so not an InVM broker.
- if (isJavaBroker() && isExternalBroker())
- {
- String TESTID = "BRK-1003";
-
- startBroker();
-
- // Now we can create the monitor as _outputFile will now be defined
- _monitor = new LogMonitor(_outputFile);
-
- stopBroker();
-
- //Give broker time to shutdown and flush log
- checkSocketClosed(getPort());
-
- List<String> results = waitAndFindMatches(BRK_LOG_PREFIX);
- try
- {
- // Validation
-
- assertTrue("BRKer message not logged", results.size() > 0);
-
- boolean validation = false;
- boolean foundBRK1001 = false;
- for (String rawLog : results)
- {
- String log = getLog(rawLog);
-
- // Ensure we do not have a BRK-1002 message
- if (!getMessageID(log).equals(TESTID))
- {
- if (getMessageID(log).equals("BRK-1001"))
- {
- foundBRK1001 = true;
- }
- continue;
- }
-
- assertTrue("BRK-1001 not logged before this message", foundBRK1001);
-
- //1
- validateMessageID(TESTID, log);
-
- //2
- assertEquals("More than one listen message found.",
- 1, findMatches(TESTID).size());
-
- //3
- String message = getMessageString(log);
- assertTrue("Expected shutdown log not correct" + message,
- message.endsWith("TCP port " + getPort()));
-
- //4
- checkSocketClosed(getPort());
-
- validation = true;
- }
-
- assertTrue("Validation not performed: " + TESTID + " not logged", validation);
- }
- catch (AssertionFailedError afe)
- {
- dumpLogs(results, _monitor);
-
- throw afe;
- }
- }
- }
-
- /**
- * Description:
- * On startup the broker may listen on a number of ports and protocols. Each of these must be reported as they are made available.
- * Input:
- * The default configuration with SSL enabled
- * Output:
- *
- * <date> MESSAGE BRK-1002 : Starting : Listening on TCP port 5672
- * <date> MESSAGE BRK-1002 : Starting : Listening on TCP/SSL port 8672
- *
- * Constraints:
- * Additional broker configuration will occur between the Startup(BRK-1001) and Starting(BRK-1002) messages depending on what VirtualHosts are configured.
- * Validation Steps:
- *
- * 1. The BRK ID is correct
- * 2. This occurs after the BRK-1001 startup message
- * 3. With SSL enabled in the configuration two BRK-1002 will be printed (order is not specified)
- * 1. One showing values TCP / 5672
- * 2. One showing values TCP/SSL / 5672
- *
- * @throws Exception caused by broker startup
- */
- public void testBrokerShutdownListeningTCPSSL() throws Exception
- {
- // This logging startup code only occurs when you run a Java broker,
- // that broker must be started via Main so not an InVM broker.
- if (isJavaBroker() && isExternalBroker())
- {
- String TESTID = "BRK-1003";
-
- // Enable SSL on the connection
- setConfigurationProperty("connector.ssl.enabled", "true");
- setConfigurationProperty("connector.ssl.keyStorePath", getConfigurationStringProperty("management.ssl.keyStorePath"));
- setConfigurationProperty("connector.ssl.keyStorePassword", getConfigurationStringProperty("management.ssl.keyStorePassword"));
-
- Integer sslPort = Integer.parseInt(getConfigurationStringProperty("connector.sslport"));
-
- startBroker();
-
- // Now we can create the monitor as _outputFile will now be defined
- _monitor = new LogMonitor(_outputFile);
-
-
-// //Clear any startup messages as we don't need them for validation
-// _monitor.reset();
- //Stop the broker to get the log messages for testing
- stopBroker();
-
- //Give broker time to shutdown and flush log
- checkSocketClosed(getPort());
-
- List<String> results = waitAndFindMatches(TESTID);
- try
- {
- // Validation
-
- assertTrue(TESTID + " messages not logged", results.size() > 0);
-
- String log = getLog(results.get(0));
-
- //1
- validateMessageID(TESTID, log);
-
- //2
- List<String> listenMessages = findMatches(TESTID);
- assertEquals("Two shutdown messages should be found.",
- 2, listenMessages.size());
-
- //3
- String message = getMessageString(getLog(listenMessages.get(0)));
- assertTrue("Expected shutdown log not correct" + message,
- message.endsWith("TCP port " + getPort()));
-
- // Check second, ssl, listen.
- message = getMessageString(getLog(listenMessages.get(1)));
- assertTrue("Expected shutdown log not correct" + message,
- message.endsWith("TCP/SSL port " + sslPort));
-
- //4
- //Test Port closed
- checkSocketClosed(getPort());
- //Test SSL Port closed
- checkSocketClosed(sslPort);
- }
- catch (AssertionFailedError afe)
- {
- dumpLogs(results, _monitor);
-
- throw afe;
- }
- }
- }
-
- /**
- * Description:
- * Input:
- * No input, all clean broker shutdowns will show BRK-1005 messages.
- * Output:
- *
- * <date> MESSAGE BRK-1005 : Stopped
- *
- * Constraints:
- * This is the LAST message the broker will log.
- * Validation Steps:
- *
- * 1. The BRK ID is correct
- * 2. This is the last message the broker will log.
- *
- * @throws Exception caused by broker startup
- */
- public void testBrokerShutdownStopped() throws Exception
- {
- // This logging startup code only occurs when you run a Java broker,
- // that broker must be started via Main so not an InVM broker.
- if (isJavaBroker() && isExternalBroker())
- {
- String TESTID = "BRK-1005";
-
- startBroker();
-
- // Now we can create the monitor as _outputFile will now be defined
- _monitor = new LogMonitor(_outputFile);
-
- getConnection().close();
-
- stopBroker();
-
- // Ensure the broker has shutdown before retreving results
- checkSocketClosed(getPort());
-
- waitAndFindMatches(TESTID);
-
- List<String> results = waitAndFindMatches(BRK_LOG_PREFIX);
- try
- {
- // Validation
-
- assertTrue("BRKer message not logged", results.size() > 0);
-
- boolean validation = false;
- for (String rawLog : results)
- {
- assertFalse("More broker log statements present after ready message", validation);
- String log = getLog(rawLog);
-
- // Ignore all logs until we get to the test id.
- if (!getMessageID(log).equals(TESTID))
- {
- continue;
- }
-
- //1
- validateMessageID(TESTID, log);
-
- //2
- assertEquals("More than one ready message found.",
- 1, findMatches(TESTID).size());
-
- //3
- assertEquals("Stopped message not present", "Stopped", getMessageString(log));
-
- validation = true;
- }
-
- assertTrue("Validation not performed: " + TESTID + " not logged", validation);
- }
- catch (AssertionFailedError afe)
- {
- dumpLogs(results, _monitor);
-
- throw afe;
- }
- }
- }
-
- /**
- * Test that a socket on the given port is closed.
- *
- * Does this by attempting to connect to the port and expecting a
- * ConnectionRefused IOException or a ConnectionException
- *
- * @param port the port number
- */
- private void checkSocketClosed(int port)
- {
- try
- {
- Socket socket = new Socket((String) null, port);
- fail("Socket not closed on port:" + port);
- }
- catch (ConnectionException e)
- {
- //normal path
- }
- catch (IOException e)
- {
- if (!e.getMessage().equals("Connection refused"))
- {
- fail("Socket not closed on port:" + port + ":" + e.getMessage());
- // Keep stack trace for diagnosis.
- e.printStackTrace(System.err);
- }
- }
- }
-
- /**
- * Test that a socket on the given port is open.
- *
- * Does this by attempting to connect to the port and expecting a
- * The connection to succeed.
- * It then closes the socket and expects that to work cleanly.
- *
- * @param port the port number
- */
- private void testSocketOpen(int port)
- {
- try
- {
- Socket socket = new Socket((String) null, port);
- socket.close();
- }
- catch (IOException e)
- {
- fail("Unable to open and close socket to port:" + port
- + ". Due to:" + e.getMessage());
- }
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/server/logging/ChannelLoggingTest.java b/java/systests/src/main/java/org/apache/qpid/server/logging/ChannelLoggingTest.java
deleted file mode 100644
index 02d0d6f334..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/server/logging/ChannelLoggingTest.java
+++ /dev/null
@@ -1,313 +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.logging;
-
-import org.apache.qpid.client.AMQConnection;
-
-import javax.jms.Connection;
-import javax.jms.MessageConsumer;
-import javax.jms.Queue;
-import javax.jms.Session;
-import java.util.List;
-
-public class ChannelLoggingTest extends AbstractTestLogging
-{
- private static final String CHANNEL_PREFIX = "CHN-";
-
- // No explicit startup configuration is required for this test
- // so no setUp() method
-
- /**
- * Description:
- * When a new Channel (JMS Session) is created this will be logged as a CHN-1001 Create message. The messages will contain the prefetch details about this new Channel.
- * Input:
- *
- * 1. Running Broker
- * 2. New JMS Session/Channel creation
- *
- * Output:
- * <date> CHN-1001 : Create
- * <date> CHN-1004 : Prefetch Size (bytes) {0,number} : Count {1,number}
- *
- * Validation Steps:
- * 1. The CHN ID is correct
- * 2. The prefetch value matches that defined by the requesting client.
- *
- * @throws Exception - if an error occurs
- */
- public void testChannelCreate() throws Exception
- {
- assertLoggingNotYetOccured(CHANNEL_PREFIX);
-
- Connection connection = getConnection();
-
- int PREFETCH = 12;
-
- // Test that calling session.close gives us the expected output
- ((AMQConnection)connection).createSession(false, Session.AUTO_ACKNOWLEDGE,PREFETCH);
-
- // Wait to ensure that the CHN-1001 message is logged
- waitForMessage("CHN-1001");
-
- List<String> results = findMatches("CHN-1001");
-
- // Validation
- assertEquals("CHN-1001 messages not logged", 1, results.size());
-
- String log = getLogMessage(results, 0);
- // MESSAGE [con:0(guest@anonymous(3273383)/test)/ch:1] CHN-1001 : Create
- validateMessageID("CHN-1001", log);
- assertEquals("Incorrect Channel in actor:"+fromActor(log), isBroker010()? 0 : 1, getChannelID(fromActor(log)));
-
- if (isBroker08())
- {
- // Wait to ensure that the CHN-1004 message is logged
- waitForMessage("CHN-1004");
-
- results = findMatches("CHN-1004");
-
- // Validation
- assertEquals("CHN-1004 messages not logged", 1, results.size());
- log = getLogMessage(results, 0);
- // MESSAGE [con:0(guest@anonymous(3273383)/test)/ch:1] CHN-1004 : Prefetch Size (bytes) {0,number} : Count {1,number}
- validateMessageID("CHN-1004", log);
- assertEquals("Incorrect Channel in actor:"+fromActor(log), isBroker010()? 0 : 1, getChannelID(fromActor(log)));
- assertTrue("Prefetch Count not correct",getMessageString(fromMessage(log)).endsWith("Count "+PREFETCH));
- }
-
- connection.close();
- }
-
- /**
- * Description:
- * The Java Broker implements consumer flow control for all ack modes except
- * No-Ack. When a client connects the session's flow is initially set to
- * Stopped. Verify this message appears
- *
- * Input:
- * 1. Running broker
- * 2. Create consumer
- * Output:
- *
- * <date> CHN-1002 : Flow Stopped
- *
- * Validation Steps:
- * 4. The CHN ID is correct
- *
- * @throws Exception - if an error occurs
- */
-
- public void testChannelStartsFlowStopped() throws Exception
- {
- assertLoggingNotYetOccured(CHANNEL_PREFIX);
-
- Connection connection = getConnection();
-
- // Create a session to fill up
- Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- Queue queue = (Queue) getInitialContext().lookup(QUEUE);
- MessageConsumer consumer = session.createConsumer(queue);
-
- connection.start();
-
- // Wait to ensure that the CHN-1002 message is logged
- waitForMessage("CHN-1002");
-
- List<String> results = findMatches(CHANNEL_PREFIX);
-
- assertTrue("No CHN messages logged", results.size() > 0);
-
- // The last channel message should be:
- //
- // INFO - MESSAGE [con:0(guest@anonymous(4205299)/test)/ch:1] [con:0(guest@anonymous(4205299)/test)/ch:1] CHN-1002 : Flow Stopped
-
- // Verify the last channel message is stopped
- validateChannelStart(results, false);
- }
-
- private void validateChannelStart(List<String> results, boolean flowStarted)
- {
- String log = getLogMessageFromEnd(results, 0);
-
- String flow = flowStarted ? "Started" : "Stopped";
- validateMessageID("CHN-1002", log);
- assertEquals("Message should be Flow " + flow, "Flow " + flow, getMessageString(fromMessage(log)));
- }
-
- /**
- * Description:
- * The Java Broker implements consumer flow control for all ack modes except
- * No-Ack. When the client first attempts to receive a message then the Flow
- * status of the Session is set to Started.
- *
- * Input:
- * 1. Running broker
- * 2. Create a consumer
- * 3. Attempt to receive a message
- * Output:
- *
- * <date> CHN-1002 : Flow Started
- *
- * Validation Steps:
- * 4. The CHN ID is correct
- *
- * @throws Exception - if an error occurs
- */
-
- public void testChannelStartConsumerFlowStarted() throws Exception
- {
- assertLoggingNotYetOccured(CHANNEL_PREFIX);
-
- Connection connection = getConnection();
-
- // Create a session to fill up
- Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- Queue queue = (Queue) getInitialContext().lookup(QUEUE);
- MessageConsumer consumer = session.createConsumer(queue);
-
- connection.start();
-
- //Call receive to send the Flow On message
- consumer.receiveNoWait();
-
- //Wait for up to 2 seconds for message to appear
- // ignore response as we will use the findMatches afterwards just
- // incase it did take more than 2 seconds to log.
- _monitor.waitForMessage(CHANNEL_PREFIX, 2000);
-
- // Wait to ensure that the CHN-1002 message is logged
- waitForMessage("CHN-1002");
-
- List<String> results = findMatches(CHANNEL_PREFIX);
-
- assertTrue("No CHN messages logged", results.size() > 0);
-
- // The last two channel messages(before the close) should be:
- //
- // INFO [qpid.message] MESSAGE [con:1(guest@/127.0.0.1:49869/test)/ch:1] [con:1(guest@/127.0.0.1:49869/test)/ch:1] CHN-1002 : Flow Stopped
- // INFO [qpid.message] MESSAGE [con:1(guest@/127.0.0.1:49869/test)/ch:1] [con:1(guest@/127.0.0.1:49869/test)/ch:1] CHN-1002 : Flow Started
-
- // Verify the last channel msg is Started.
- validateChannelStart(results, true);
- }
-
- /**
- * Description:
- * When the client gracefully closes the Connection then a CHN-1003 Close
- * message will be issued. This must be the last message logged for this
- * Channel.
- * Input:
- * 1. Running Broker
- * 2. Connected Client
- * 3. Client then requests that the Connection is closed
- * Output:
- *
- * <date> CHN-1003 : Close
- *
- * Validation Steps:
- * 4. The MST ID is correct
- * 5. This must be the last message logged for this Channel.
- *
- * @throws Exception - if an error occurs
- */
- public void testChannelCloseViaConnectionClose() throws Exception
- {
- assertLoggingNotYetOccured(CHANNEL_PREFIX);
-
- Connection connection = getConnection();
-
- // Create a session
- connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- // Close the connection to verify the created session closing is logged.
- connection.close();
-
- // Wait to ensure that the CHN-1003 message is logged
- waitForMessage("CHN-1003");
-
- List<String> results = findMatches(CHANNEL_PREFIX);
-
- assertTrue("No CHN messages logged", results.size() > 0);
-
- // The last two channel messages should be:
- //
- // INFO - MESSAGE [con:0(guest@anonymous(4205299)/test)/ch:1] [con:0(guest@anonymous(4205299)/test)/ch:1] CHN-1002 : Flow On
-
- // Verify
- validateChannelClose(results);
- }
-
- /**
- * Description:
- * When the client gracefully closes the Connection then a CHN-1003 Close
- * message will be issued. This must be the last message logged for this
- * Channel.
- * Input:
- * 1. Running Broker
- * 2. Connected Client
- * 3. Client then requests that the Channel is closed
- * Output:
- *
- * <date> CHN-1003 : Close
- *
- * Validation Steps:
- * 4. The MST ID is correct
- * 5. This must be the last message logged for this Channel.
- *
- * @throws Exception - if an error occurs
- */
- public void testChannelCloseViaChannelClose() throws Exception
- {
- assertLoggingNotYetOccured(CHANNEL_PREFIX);
-
- Connection connection = getConnection();
-
- // Create a session and then close it
- Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- waitForMessage("CHN-1001");
-
- // Wait to ensure that the CHN-1003 message is logged
- session.close();
- waitForMessage("CHN-1003");
-
- List<String> results = findMatches(CHANNEL_PREFIX);
-
- assertTrue("No CHN messages logged", results.size() > 0);
-
- // Verify
- validateChannelClose(results);
- }
-
- private void validateChannelClose(List<String> results)
- {
- String open = getLogMessage(results, 0);
- String close = getLogMessageFromEnd(results, 0);
-
- validateMessageID("CHN-1001", open);
- validateMessageID("CHN-1003", close);
- assertEquals("Message should be Close", "Close", getMessageString(fromMessage(close)));
- assertEquals("Incorrect Channel ID closed", isBroker010()? 0 : 1, getChannelID(fromSubject(close)));
- assertEquals("Channel IDs should be the same", getChannelID(fromActor(open)), getChannelID(fromSubject(close)));
- assertEquals("Connection IDs should be the same", getConnectionID(fromActor(open)), getConnectionID(fromSubject(close)));
- }
-} \ No newline at end of file
diff --git a/java/systests/src/main/java/org/apache/qpid/server/logging/ConnectionLoggingTest.java b/java/systests/src/main/java/org/apache/qpid/server/logging/ConnectionLoggingTest.java
deleted file mode 100644
index d28429aa39..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/server/logging/ConnectionLoggingTest.java
+++ /dev/null
@@ -1,192 +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.logging;
-
-import javax.jms.Connection;
-import java.util.List;
-import java.util.HashMap;
-import java.util.TreeSet;
-
-public class ConnectionLoggingTest extends AbstractTestLogging
-{
- private static final String CONNECTION_PREFIX = "CON-";
-
- // No explicit startup configuration is required for this test
- // so no setUp() method
-
- /**
- * Description:
- * When a new connection is made to the broker this must be logged.
- *
- * Input:
- * 1. Running Broker
- * 2. Connecting client
- * Output:
- * <date> CON-1001 : Open : Client ID {0}[ : Protocol Version : {1}] <version>
- *
- * Validation Steps:
- * 1. The CON ID is correct
- * 2. This is the first CON message for that Connection
- *
- * @throws Exception - if an error occurs
- */
- public void testConnectionOpen() throws Exception
- {
- assertLoggingNotYetOccured(CONNECTION_PREFIX);
-
- Connection connection = getConnection();
- String clientid = connection.getClientID();
-
- // Wait until opened
- waitForMessage("CON-1001");
-
- // Close the conneciton
- connection.close();
-
- // Wait to ensure that the desired message is logged
- waitForMessage("CON-1002");
-
- List<String> results = waitAndFindMatches("CON-1001");
-
- // Validation
- // We should have at least three messages when running InVM but when running External
- // we will get 0-10 negotiation on con:0 whcih may close at some random point
- // MESSAGE [con:0(/127.0.0.1:46926)] CON-1001 : Open
- // MESSAGE [con:0(/127.0.0.1:46926)] CON-1001 : Open : Protocol Version : 0-10
- // MESSAGE [con:1(/127.0.0.1:46927)] CON-1001 : Open
- // MESSAGE [con:1(/127.0.0.1:46927)] CON-1001 : Open : Protocol Version : 0-9
- // MESSAGE [con:0(/127.0.0.1:46926)] CON-1002 : Close
- // MESSAGE [con:1(/127.0.0.1:46927)] CON-1001 : Open : Client ID : clientid : Protocol Version : 0-9
-
- //So check how many connections we have in the result set and extract the last one.
- // When running InVM we will have con:0 and externally con:1
-
- HashMap<Integer, List<String>> connectionData = splitResultsOnConnectionID(results);
-
- // Get the last Integer from keySet of the ConnectionData
- int connectionID = new TreeSet<Integer>(connectionData.keySet()).last();
-
- //Use just the data from the last connection for the test
- results = connectionData.get(connectionID);
-
- // If we are running inVM or with 0-10 we will get three open messagse
- // if running externally with 0-8/0-9 we will also have open and close messages from the failed 0-10 negotiation
- assertTrue("CON messages not logged:" + results.size(), results.size() >= 3);
-
- String log = getLogMessage(results, 0);
- // MESSAGE [con:1(/127.0.0.1:52540)] CON-1001 : Open
- //1 & 2
- validateMessageID("CON-1001",log);
-
- // validate the last three CON- messages.
- // This is because when running externally we may also have logged the failed
- // 0-10 negotiation messages if using 0-8/0-9 on the broker.
-
- // 3 - Assert the options are correct
- // MESSAGE [con:1(/127.0.0.1:52540)] CON-1001 : Open : Client ID : clientid : Protocol Version : 0-9
- validateConnectionOpen(results, 0, true, true, clientid);
-
- // MESSAGE [con:1(/127.0.0.1:52540)] CON-1001 : Open : Protocol Version : 0-9
- validateConnectionOpen(results, 1, true, false, null);
-
- validateConnectionOpen(results, 2, false, false, null);
- }
-
- private void validateConnectionOpen(List<String> results, int positionFromEnd,
- boolean protocolVersionPresent, boolean clientIdOptionPresent, String clientIdValue)
- {
- String log = getLogMessageFromEnd(results, positionFromEnd);
-
- validateMessageID("CON-1001",log);
-
- assertEquals("unexpected Client ID option state", clientIdOptionPresent, fromMessage(log).contains("Client ID :"));
-
- if(clientIdOptionPresent && clientIdValue != null)
- {
- assertTrue("Client ID value is not present: " + clientIdValue, fromMessage(log).contains(clientIdValue));
- }
-
- assertEquals("unexpected Protocol Version option state",
- protocolVersionPresent, fromMessage(log).contains("Protocol Version :"));
- //fixme there is no way currently to find out the negotiated protocol version
- // The delegate is the versioned class ((AMQConnection)connection)._delegate
- }
-
- /**
- * Description:
- * When a connected client closes the connection this will be logged as a CON-1002 message.
- * Input:
- *
- * 1. Running Broker
- * 2. Connected Client
- * Output:
- *
- * <date> CON-1002 : Close
- *
- * Validation Steps:
- * 3. The CON ID is correct
- * 4. This must be the last CON message for the Connection
- * 5. It must be preceded by a CON-1001 for this Connection
- */
- public void testConnectionClose() throws Exception
- {
- assertLoggingNotYetOccured(CONNECTION_PREFIX);
-
- Connection connection = getConnection();
-
- // Wait until opened
- waitForMessage("CON-1001");
-
- // Close the conneciton
- connection.close();
-
- // Wait to ensure that the desired message is logged
- waitForMessage("CON-1002");
-
- List<String> results = findMatches(CONNECTION_PREFIX);
-
- // Validation
-
- // We should have at least four messages
- assertTrue("CON messages not logged:" + results.size(), results.size() >= 4);
-
- // Validate Close message occurs
- String log = getLogMessageFromEnd(results, 0);
- validateMessageID("CON-1002",log);
- assertTrue("Message does not end with close:" + log, log.endsWith("Close"));
-
- // Extract connection ID to validate there is a CON-1001 messasge for it
- int closeConnectionID = getConnectionID(fromSubject(log));
- assertTrue("Could not find connection id in CLOSE", closeConnectionID != -1);
-
- //Previous log message should be the open
- log = getLogMessageFromEnd(results, 1);
- // MESSAGE [con:1(/127.0.0.1:52540)] CON-1001 : Open : Client ID : clientid : Protocol Version : 0-9
- validateMessageID("CON-1001",log);
-
- // Extract connection ID to validate it matches the CON-1002 messasge
- int openConnectionID = getConnectionID(fromActor(log));
- assertTrue("Could not find connection id in OPEN", openConnectionID != -1);
-
- // Check connection ids match
- assertEquals("Connection IDs do not match", closeConnectionID, openConnectionID);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/server/logging/DerbyMessageStoreLoggingTest.java b/java/systests/src/main/java/org/apache/qpid/server/logging/DerbyMessageStoreLoggingTest.java
deleted file mode 100644
index 16c529316a..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/server/logging/DerbyMessageStoreLoggingTest.java
+++ /dev/null
@@ -1,574 +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.logging;
-
-import org.apache.commons.configuration.Configuration;
-import org.apache.qpid.server.configuration.ServerConfiguration;
-import org.apache.qpid.server.logging.subjects.AbstractTestLogSubject;
-
-import javax.jms.Connection;
-import javax.jms.Queue;
-import javax.jms.Session;
-import java.util.List;
-import java.io.File;
-
-/**
- * The MessageStore test suite validates that the follow log messages as
- * specified in the Functional Specification.
- *
- * This suite of tests validate that the MessageStore messages occur correctly
- * and according to the following format:
- *
- * MST-1001 : Created : <name>
- * MST-1003 : Closed
- *
- * NOTE: Only for Persistent Stores
- * MST-1002 : Store location : <path>
- * MST-1004 : Recovery Start [: <queue.name>]
- * MST-1005 : Recovered <count> messages for queue <queue.name>
- * MST-1006 : Recovery Complete [: <queue.name>]
- */
-public class DerbyMessageStoreLoggingTest extends MemoryMessageStoreLoggingTest
-{
-
- @Override
- public void setUp() throws Exception
- {
- super.setUp();
- // MemoryMessageStoreLoggingTest setUp itself does not call super.setUp
- //We call super.setUp but this will not start the broker as that is
- //part of the test case.
-
- // Load the default configuration file to get the list of defined vhosts
- ServerConfiguration configuration = new ServerConfiguration(new File(_configFile.getParent() + "/config.xml"));
- configuration.initialise();
- List<String> vhosts = configuration.getConfig().getList("virtualhosts.virtualhost.name");
-
- // Make them all persistent i.e. Use DerbyMessageStore and
- // test that it logs correctly.
- for (String vhost : vhosts)
- {
- makeVirtualHostPersistent(vhost);
- }
- }
-
- /**
- * Description:
- * Persistent MessageStores will require space on disk to persist the data.
- * This value will be logged on startup after the MessageStore has been
- * created.
- * Input:
- * Default configuration
- * Output:
- *
- * <date> MST-1002 : Store location : <path>
- *
- * Validation Steps:
- *
- * 1. The MST ID is correct
- * 2. This must occur after MST-1001
- */
- public void testMessageStoreStoreLocation() throws Exception
- {
- assertLoggingNotYetOccured(MESSAGES_STORE_PREFIX);
-
- startBroker();
-
- List<String> results = waitAndFindMatches(MESSAGES_STORE_PREFIX);
-
- // Validation
-
- assertTrue("MST messages not logged", results.size() > 0);
-
- // Load VirtualHost list from file.
- ServerConfiguration configuration = new ServerConfiguration(_configFile);
- configuration.initialise();
- List<String> vhosts = configuration.getConfig().getList("virtualhosts.virtualhost.name");
-
- //Validate each vhost logs a creation
- results = waitAndFindMatches("MST-1002");
-
- assertEquals("Each vhost did not close its store.", vhosts.size(), results.size());
-
- for (int index = 0; index < results.size(); index++)
- {
- String result = getLogMessage(results, index);;
-
- // getSlize will return extract the vhost from vh(/test) -> '/test'
- // so remove the '/' to get the name
- String vhostName = AbstractTestLogSubject.getSlice("vh", result).substring(1);
-
- // To get the store class used in the configuration we need to know
- // the virtualhost name, found above. AND
- // the index that the virtualhost is within the configuration.
- // we can retrive that from the vhosts list previously extracted.
- String fullStoreName = configuration.getConfig().getString("virtualhosts.virtualhost(" + vhosts.indexOf(vhostName) + ")." + vhostName + ".store.class");
-
- // Get the Simple class name from the expected class name of o.a.q.s.s.MMS
- String storeName = fullStoreName.substring(fullStoreName.lastIndexOf(".") + 1);
-
- assertTrue("MST-1002 does not contain a store path" + getMessageString(result),
- getMessageString(result).length() > 0);
-
- assertEquals("The store name does not match expected value",
- storeName, AbstractTestLogSubject.getSlice("ms", fromSubject(result)));
- }
- }
-
- /**
- * Description:
- * Persistent message stores may have state on disk that they must recover
- * during startup. As the MessageStore starts up it will report that it is
- * about to start the recovery process by logging MST-1004. This message
- * will always be logged for persistent MessageStores. If there is no data
- * to recover then there will be no subsequent recovery messages.
- * Input:
- * Default persistent configuration
- * Output:
- * <date> MST-1004 : Recovery Start
- *
- * Validation Steps:
- *
- * 1. The MST ID is correct
- * 2. The MessageStore must have first logged a creation event.
- */
- public void testMessageStoreRecoveryStart() throws Exception
- {
- assertLoggingNotYetOccured(MESSAGES_STORE_PREFIX);
-
- startBroker();
-
- List<String> results = waitAndFindMatches(MESSAGES_STORE_PREFIX);
-
- // Validation
-
- assertTrue("MST messages not logged", results.size() > 0);
-
- // Load VirtualHost list from file.
- ServerConfiguration configuration = new ServerConfiguration(_configFile);
- configuration.initialise();
- List<String> vhosts = configuration.getConfig().getList("virtualhosts.virtualhost.name");
-
- //Validate each vhost logs a creation
- results = waitAndFindMatches("MST-1004");
-
- assertTrue("Each vhost did not close its store.", vhosts.size() <= results.size());
-
- for (int index = 0; index < results.size(); index++)
- {
- String result = getLogMessage(results, index);;
-
- if (getMessageString(result).contains("Recovery Start :"))
- {
- //Don't test queue start recoveries
- continue;
- }
-
- // getSlize will return extract the vhost from vh(/test) -> '/test'
- // so remove the '/' to get the name
- String vhostName = AbstractTestLogSubject.getSlice("vh", result).substring(1);
-
- // To get the store class used in the configuration we need to know
- // the virtualhost name, found above. AND
- // the index that the virtualhost is within the configuration.
- // we can retrive that from the vhosts list previously extracted.
- String fullStoreName = configuration.getConfig().getString("virtualhosts.virtualhost(" + vhosts.indexOf(vhostName) + ")." + vhostName + ".store.class");
-
- // Get the Simple class name from the expected class name of o.a.q.s.s.MMS
- String storeName = fullStoreName.substring(fullStoreName.lastIndexOf(".") + 1);
-
- assertEquals("MST-1004 does have expected message", "Recovery Start",
- getMessageString(result));
-
- assertEquals("The store name does not match expected value",
- storeName, AbstractTestLogSubject.getSlice("ms", fromSubject(result)));
- }
- }
-
- /**
- * Description:
- * Once all persistent queues have been recovered and the MessageStore has completed all recovery it must logged that the recovery process has completed.
- * Input:
- * Default persistent configuration
- * Output:
- *
- * <date> MST-1006 : Recovery Complete
- *
- * Validation Steps:
- *
- * 1. The MST ID is correct
- * 2. This is the last message from the MessageStore during startup.
- * 3. This must be proceeded by a MST-1006 Recovery Start.
- */
- public void testMessageStoreRecoveryComplete() throws Exception
- {
- assertLoggingNotYetOccured(MESSAGES_STORE_PREFIX);
-
- startBroker();
-
- List<String> results = waitAndFindMatches(MESSAGES_STORE_PREFIX);
-
- // Validation
-
- assertTrue("MST messages not logged", results.size() > 0);
-
- // Load VirtualHost list from file.
- ServerConfiguration configuration = new ServerConfiguration(_configFile);
- configuration.initialise();
- List<String> vhosts = configuration.getConfig().getList("virtualhosts.virtualhost.name");
-
- //Validate each vhost logs a creation
- results = waitAndFindMatches("MST-1006");
-
- assertTrue("Each vhost did not close its store.", vhosts.size() <= results.size());
-
- for (int index = 0; index < results.size(); index++)
- {
- String result = getLogMessage(results, index);
-
- if (getMessageString(result).contains("Recovery Complete :"))
- {
- //Don't test queue start recoveries
- continue;
- }
-
- // getSlize will return extract the vhost from vh(/test) -> '/test'
- // so remove the '/' to get the name
- String vhostName = AbstractTestLogSubject.getSlice("vh", result).substring(1);
-
- // To get the store class used in the configuration we need to know
- // the virtualhost name, found above. AND
- // the index that the virtualhost is within the configuration.
- // we can retrive that from the vhosts list previously extracted.
- String fullStoreName = configuration.getConfig().getString("virtualhosts.virtualhost(" + vhosts.indexOf(vhostName) + ")." + vhostName + ".store.class");
-
- // Get the Simple class name from the expected class name of o.a.q.s.s.MMS
- String storeName = fullStoreName.substring(fullStoreName.lastIndexOf(".") + 1);
-
- assertEquals("MST-1006 does have expected message", "Recovery Complete",
- getMessageString(result));
-
- assertEquals("The store name does not match expected value",
- storeName, AbstractTestLogSubject.getSlice("ms", fromSubject(result)));
- }
- }
-
- /**
- * Description:
- * A persistent MessageStore may have data to recover from disk. The message store will use MST-1004 to report the start of recovery for a specific queue that it has previously persisted.
- * Input:
- * Default persistent configuration
- * Output:
- *
- * <date> MST-1004 : Recovery Start : <queue.name>
- *
- * Validation Steps:
- *
- * 1. The MST ID is correct
- * 2. This must occur after the recovery start MST-1004 has been logged.
- */
- public void testMessageStoreQueueRecoveryStart() throws Exception
- {
- assertLoggingNotYetOccured(MESSAGES_STORE_PREFIX);
-
- startBroker();
-
- List<String> results = waitAndFindMatches(MESSAGES_STORE_PREFIX);
-
- // Validation
-
- assertTrue("MST messages not logged", results.size() > 0);
-
- // Load VirtualHost list from file.
- ServerConfiguration configuration = new ServerConfiguration(_configFile);
- configuration.initialise();
- List<String> vhosts = configuration.getConfig().getList("virtualhosts.virtualhost.name");
-
- //Validate each vhost logs a creation
- results = waitAndFindMatches("MST-1004 : Recovery Start :");
-
- // We are only looking for the default queue defined in local host being
- // recovered. If other tests have made queues in test then we want to
- // exclude them here.
- results = filterResultsByVirtualHost(results, "/localhost");
-
- assertEquals("Recovered test queue not found.", 1, results.size());
-
- String result = getLogMessage(results, 0);
-
- // getSlize will return extract the vhost from vh(/test) -> '/test'
- // so remove the '/' to get the name
- String vhostName = AbstractTestLogSubject.getSlice("vh", result).substring(1);
-
- // To get the store class used in the configuration we need to know
- // the virtualhost name, found above. AND
- // the index that the virtualhost is within the configuration.
- // we can retrive that from the vhosts list previously extracted.
- String fullStoreName = configuration.getConfig().getString("virtualhosts.virtualhost(" + vhosts.indexOf(vhostName) + ")." + vhostName + ".store.class");
-
- // Get the Simple class name from the expected class name of o.a.q.s.s.MMS
- String storeName = fullStoreName.substring(fullStoreName.lastIndexOf(".") + 1);
-
- assertTrue("MST-1006 does end with queue 'test-queue':" + getMessageString(result),
- getMessageString(result).endsWith("test-queue"));
-
- assertEquals("The store name does not match expected value",
- storeName, AbstractTestLogSubject.getSlice("ms", fromSubject(result)));
-
- }
-
- /**
- * Description:
- * After the queue has been recovered the store will log that recovery has been completed. The MessageStore must not report further status about the recovery of this queue after this message. In addition every MST-1004 queue recovery start message must be matched with a MST-1006 recovery complete.
- * Input:
- * Default persistent configuration
- * Output:
- *
- * <date> MST-1006 : Recovery Complete : <queue.name>
- *
- * Validation Steps:
- *
- * 1. The MST ID is correct
- * 2. This must occur after the queue recovery start MST-1004 has been logged.
- * 3. The queue.name is non-empty
- * 4. The queue.name correlates with a previous recovery start
- */
- public void testMessageStoreQueueRecoveryComplete() throws Exception
- {
- assertLoggingNotYetOccured(MESSAGES_STORE_PREFIX);
-
- startBroker();
-
- List<String> results = waitAndFindMatches(MESSAGES_STORE_PREFIX);
-
- // Validation
-
- assertTrue("MST messages not logged", results.size() > 0);
-
- // Load VirtualHost list from file.
- ServerConfiguration configuration = new ServerConfiguration(_configFile);
- configuration.initialise();
- List<String> vhosts = configuration.getConfig().getList("virtualhosts.virtualhost.name");
-
- //Validate each vhost logs a creation
- results = waitAndFindMatches("MST-1006 : Recovery Complete :");
-
- // We are only looking for the default queue defined in local host being
- // recovered. If other tests have made queues in test then we want to
- // exclude them here.
- results = filterResultsByVirtualHost(results, "/localhost");
-
- assertEquals("Recovered test queue not found.", 1, results.size());
-
- String result = getLogMessage(results, 0);
-
- // getSlize will return extract the vhost from vh(/test) -> '/test'
- // so remove the '/' to get the name
- String vhostName = AbstractTestLogSubject.getSlice("vh", result).substring(1);
-
- // To get the store class used in the configuration we need to know
- // the virtualhost name, found above. AND
- // the index that the virtualhost is within the configuration.
- // we can retrive that from the vhosts list previously extracted.
- String fullStoreName = configuration.getConfig().getString("virtualhosts.virtualhost(" + vhosts.indexOf(vhostName) + ")." + vhostName + ".store.class");
-
- // Get the Simple class name from the expected class name of o.a.q.s.s.MMS
- String storeName = fullStoreName.substring(fullStoreName.lastIndexOf(".") + 1);
-
- assertTrue("MST-1006 does end with queue 'test-queue':" + getMessageString(result),
- getMessageString(result).endsWith("test-queue"));
-
- assertEquals("The store name does not match expected value",
- storeName, AbstractTestLogSubject.getSlice("ms", fromSubject(result)));
-
- results = findMatches("MST-1004 : Recovery Start : test-queue");
-
- assertEquals("MST-1004 for test-queue not found", 1, results.size());
- }
-
- /**
- * Description:
- * A persistent queue must be persisted so that on recovery it can be restored independently of any messages that may be stored on it. This test verifies that the MessageStore will log that it has recovered 0 messages for persistent queues that do not have any messages.
- * Input:
- *
- * 1. Default persistent configuration
- * 2. Persistent queue with no messages enqueued
- * Output:
- *
- * <date> MST-1005 : Recovered 0 messages for queue <queue.name>
- *
- * Validation Steps:
- * 3. The MST ID is correct
- * 4. This must occur after the queue recovery start MST-1004 has been logged.
- * 5. The count is 0
- * 6. 'messages' is correctly printed
- * 7. The queue.name is non-empty
- */
- public void testMessageStoreQueueRecoveryCountEmpty() throws Exception
- {
- assertLoggingNotYetOccured(MESSAGES_STORE_PREFIX);
-
- String queueName = getTestQueueName();
-
- startBroker();
- Connection connetion = getConnection();
- Session session = connetion.createSession(false, Session.AUTO_ACKNOWLEDGE);
- Queue queue = session.createQueue("direct://amq.direct/" + queueName + "/" + queueName + "?durable='true'");
-
- session.createConsumer(queue).close();
-
- // Stop the broker so that we can test recovery
- stopBroker();
-
- int COUNT = 0;
- testDurableRecoveryCount(COUNT, queueName);
- }
-
- /**
- * Description:
- * On recovery all the persistent messages that are stored on disk must be returned to the queue. MST-1005 will report the number of messages that have been recovered from disk.
- * Input:
- *
- * 1. Default persistent configuration
- * 2. Persistent queue with multiple messages enqueued
- * Output:
- *
- * <date> MST-1005 : Recovered <count> messages for queue <queue.name>
- *
- * Validation Steps:
- * 3. The MST ID is correct
- * 4. This must occur after the queue recovery start MST-1004 has been logged.
- * 5. The count is > 1
- * 6. 'messages' is correctly printed
- * 7. The queue.name is non-empty
- */
- public void testMessageStoreQueueRecoveryCountPlural() throws Exception
- {
- assertLoggingNotYetOccured(MESSAGES_STORE_PREFIX);
-
- String queueName = getTestQueueName();
-
- int COUNT = 10;
-
- testDurableRecoveryCount(COUNT, queueName);
- }
-
- /**
- * Send a set number of messages to a new durable queue, as specified. Then
- * restart the broker and validate that they are restored.
- *
- * @param COUNT - the count to send
- * @param queueName - the new queue name
- * @throws Exception - if a problem occured.
- */
- private void testDurableRecoveryCount(int COUNT, String queueName) throws Exception
- {
- startBroker();
- Connection connetion = getConnection();
- Session session = connetion.createSession(false, Session.AUTO_ACKNOWLEDGE);
- Queue queue = session.createQueue("direct://amq.direct/" + queueName + "/" + queueName + "?durable='true'");
-
- session.createConsumer(queue).close();
-
- sendMessage(session, queue, COUNT);
- try
- {
- connetion.close();
-
- stopBroker();
-
- // Clear our monitor
- _monitor.reset();
-
- startBroker();
-
- List<String> results = waitAndFindMatches(MESSAGES_STORE_PREFIX);
-
- // Validation
-
- assertTrue("MST messages not logged", results.size() > 0);
-
- // Load VirtualHost list from file.
- ServerConfiguration configuration = new ServerConfiguration(_configFile);
- configuration.initialise();
- List<String> vhosts = configuration.getConfig().getList("virtualhosts.virtualhost.name");
-
- //Validate each vhost logs a creation
- results = waitAndFindMatches("MST-1004 : Recovery Start : " + queueName);
-
- assertEquals("Recovered test queue not found.", 1, results.size());
-
- String result = getLogMessage(results, 0);
-
- validateMessageID("MST-1004", result);
-
- assertTrue("MST-1004 does end with queue '" + queueName + "':" + getMessageString(result),
- getMessageString(result).endsWith(queueName));
-
- results = waitAndFindMatches("MST-1005");
-
- assertTrue("Insufficient MST-1005 logged.", results.size()>0);
-
- result = null;
-
- // If the first message is not our queue the second one will be
- for(String resultEntry : results)
- {
- // Look for first match and set that to result
- if (resultEntry.contains(queueName))
- {
- result = getLog(resultEntry);
- break;
- }
- }
-
- assertNotNull("MST-1005 entry for queue:" + queueName + ". Not found", result);
-
- // getSlize will return extract the vhost from vh(/test) -> '/test'
- // so remove the '/' to get the name
- String vhostName = AbstractTestLogSubject.getSlice("vh", result).substring(1);
-
- // To get the store class used in the configuration we need to know
- // the virtualhost name, found above. AND
- // the index that the virtualhost is within the configuration.
- // we can retrive that from the vhosts list previously extracted.
- String fullStoreName = configuration.getConfig().getString("virtualhosts.virtualhost(" + vhosts.indexOf(vhostName) + ")." + vhostName + ".store.class");
-
- // Get the Simple class name from the expected class name of o.a.q.s.s.MMS
- String storeName = fullStoreName.substring(fullStoreName.lastIndexOf(".") + 1);
-
- assertTrue("MST-1005 does end with queue 'test-queue':" + getMessageString(result),
- getMessageString(result).endsWith(queueName));
-
- assertTrue("MST-1005 does end show correct count:" + getMessageString(result),
- getMessageString(result).contains("Recovered " + COUNT + " messages"));
-
- assertEquals("The store name does not match expected value",
- storeName, AbstractTestLogSubject.getSlice("ms", fromSubject(result)));
- }
- finally
- {
- //Ensure we attempt to drain the queue.
- assertEquals("Unable to drain queue", COUNT, drainQueue(queue));
- }
- }
-
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/server/logging/DurableQueueLoggingTest.java b/java/systests/src/main/java/org/apache/qpid/server/logging/DurableQueueLoggingTest.java
deleted file mode 100644
index 32adc49521..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/server/logging/DurableQueueLoggingTest.java
+++ /dev/null
@@ -1,307 +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.logging;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.framing.AMQShortString;
-
-import javax.jms.Connection;
-import javax.jms.JMSException;
-import javax.jms.Queue;
-import javax.jms.Session;
-import javax.naming.NamingException;
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * The Queue test suite validates that the follow log messages as specified in
- * the Functional Specification.
- *
- * This suite of tests validate that the Queue messages occur correctly and
- * according to the following format:
- *
- * QUE-1001 : Create : [AutoDelete] [Durable|Transient] [Priority:<levels>] [Owner:<name>]
- */
-public class DurableQueueLoggingTest extends AbstractTestLogging
-{
- protected String DURABLE = "Durable";
- protected String TRANSIENT = "Transient";
- protected boolean _durable;
-
- protected Connection _connection;
- protected Session _session;
- private static final String QUEUE_PREFIX = "QUE-";
- private static int PRIORITIES = 6;
-
- public void setUp() throws Exception
- {
- super.setUp();
- //Ensure we only have logs from our test
- _monitor.reset();
-
- _connection = getConnection();
- _session = _connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- _durable = true;
- }
-
- /**
- * Description:
- * When a simple transient queue is created then a QUE-1001 create message
- * is expected to be logged.
- * Input:
- * 1. Running broker
- * 2. Persistent Queue is created from a client
- * Output:
- *
- * <date> QUE-1001 : Create : Owner: '<name>' Durable
- *
- * Validation Steps:
- * 3. The QUE ID is correct
- * 4. The Durable tag is present in the message
- * 5. The Owner is as expected
- *
- * @throws javax.jms.JMSException
- * @throws javax.naming.NamingException
- * @throws java.io.IOException
- */
- public void testQueueCreateDurableExclusive() throws NamingException, JMSException, IOException
- {
- String queueName= getTestQueueName();
- // To force a queue Creation Event we need to create a consumer.
- Queue queue = (Queue) _session.createQueue("direct://amq.direct/" + queueName + "/" + queueName + "?durable='" + _durable + "'&exclusive='true'");
-
- _session.createConsumer(queue);
-
- List<String> results = waitForMesssage();
-
- String clientID = _connection.getClientID();
- assertNotNull("clientID should not be null", clientID);
-
- validateQueueProperties(results, false, false, clientID);
- }
-
- /**
- * Description:
- * When a simple transient queue is created then a QUE-1001 create message
- * is expected to be logged.
- * Input:
- * 1. Running broker
- * 2. Persistent Queue is created from a client
- * Output:
- *
- * <date> QUE-1001 : Create : Owner: '<name>' Durable
- *
- * Validation Steps:
- * 3. The QUE ID is correct
- * 4. The Durable tag is present in the message
- * 5. The Owner is as expected
- *
- * @throws javax.jms.JMSException
- * @throws javax.naming.NamingException
- * @throws java.io.IOException
- */
- public void testQueueCreateDurable() throws NamingException, JMSException, IOException
- {
- String queueName = getTestQueueName();
-
- // To force a queue Creation Event we need to create a consumer.
- Queue queue = (Queue) _session.createQueue("direct://amq.direct/" + queueName + "/" + queueName + "?durable='" + _durable + "'");
-
- _session.createConsumer(queue);
-
- List<String> results = waitForMesssage();
-
- validateQueueProperties(results, false, false, null);
- }
-
- /**
- * Description:
- * When a simple transient queue is created then a QUE-1001 create message
- * is expected to be logged.
- * Input:
- * 1. Running broker
- * 2. AutoDelete Persistent Queue is created from a client
- * Output:
- *
- * <date> QUE-1001 : Create : Owner: '<name>' AutoDelete Durable
- *
- * Validation Steps:
- * 3. The QUE ID is correct
- * 4. The Durable tag is present in the message
- * 5. The Owner is as expected
- * 6. The AutoDelete tag is present in the message
- *
- * @throws javax.jms.JMSException
- * @throws javax.naming.NamingException
- * @throws java.io.IOException
- */
- public void testQueueCreatePersistentAutoDelete() throws NamingException, JMSException, IOException
- {
- String queueName = getTestQueueName();
- // To force a queue Creation Event we need to create a consumer.
- Queue queue = (Queue) _session.createQueue("direct://amq.direct/"+queueName+"/"+queueName+"?durable='"+_durable+"'&autodelete='true'");
-
- _session.createConsumer(queue);
-
- List<String> results = waitForMesssage();
-
- validateQueueProperties(results, false, true, null);
- }
-
- /**
- * Description:
- * When a simple transient queue is created then a QUE-1001 create message
- * is expected to be logged.
- * Input:
- * 1. Running broker
- * 2. Persistent Queue is created from a client
- * Output:
- *
- * <date> QUE-1001 : Create : Owner: '<name>' Durable Priority:<levels>
- *
- * Validation Steps:
- * 3. The QUE ID is correct
- * 4. The Durable tag is present in the message
- * 5. The Owner is as expected
- * 6. The Priority level is correctly set
- *
- * @throws javax.jms.JMSException
- * @throws javax.naming.NamingException
- * @throws java.io.IOException
- */
- public void testCreateQueuePersistentPriority() throws NamingException, JMSException, IOException, AMQException
- {
- // To Create a Priority queue we need to use AMQSession specific code
- final Map<String, Object> arguments = new HashMap<String, Object>();
- arguments.put("x-qpid-priorities", PRIORITIES);
- // Need to create a queue that does not exist so use test name
- final String queueName = getTestQueueName();
- ((AMQSession) _session).createQueue(new AMQShortString(queueName), false, _durable, false, arguments);
-
- Queue queue = (Queue) _session.createQueue("direct://amq.direct/"+queueName+"/"+queueName+"?durable='"+_durable+"'&autodelete='false'");
-
-
- //Need to create a Consumer to ensure that the log has had time to write
- // as the above Create is Asynchronous
- _session.createConsumer(queue);
-
- List<String> results = waitForMesssage();
-
- // Only 1 Queue message should hav been logged
- assertEquals("Result set size not as expected", 1, results.size());
-
- validateQueueProperties(results, true, false, null);
- }
-
- /**
- * Description:
- * When a simple transient queue is created then a QUE-1001 create message
- * is expected to be logged.
- * Input:
- * 1. Running broker
- * 2. AutoDelete Persistent Queue is created from a client
- * Output:
- *
- * <date> QUE-1001 : Create : Owner: '<name>' Durable Priority:<levels>
- *
- * Validation Steps:
- * 3. The QUE ID is correct
- * 4. The Durable tag is present in the message
- * 5. The Owner is as expected
- * 6. The AutoDelete tag is present in the message
- * 7. The Priority level is correctly set
- *
- * @throws javax.jms.JMSException
- * @throws javax.naming.NamingException
- * @throws java.io.IOException
- */
- public void testCreateQueuePersistentAutoDeletePriority() throws NamingException, JMSException, IOException, AMQException
- {
- // To Create a Priority queue we need to use AMQSession specific code
- final Map<String, Object> arguments = new HashMap<String, Object>();
- arguments.put("x-qpid-priorities", PRIORITIES);
- // Need to create a queue that does not exist so use test name
- final String queueName = getTestQueueName() + "-autoDeletePriority";
- ((AMQSession) _session).createQueue(new AMQShortString(queueName), true, _durable, false, arguments);
-
- Queue queue = (Queue) _session.createQueue("direct://amq.direct/"+queueName+"/"+queueName+"?durable='"+_durable+"'&autodelete='true'");
-
-
- //Need to create a Consumer to ensure that the log has had time to write
- // as the above Create is Asynchronous
- _session.createConsumer(queue);
-
- List<String> results = waitForMesssage();
-
- validateQueueProperties(results, true, true, null);
- }
-
- private List<String> waitForMesssage() throws IOException
- {
- // Validation
- // Ensure we have received the QUE log msg.
- waitForMessage("QUE-1001");
-
- List<String> results = findMatches(QUEUE_PREFIX);
-
- // Only 1 Queue message should hav been logged
- assertEquals("Result set size not as expected", 1, results.size());
-
- return results;
- }
-
- public void validateQueueProperties(List<String> results, boolean hasPriority, boolean hasAutodelete, String clientID)
- {
- String log = getLogMessage(results, 0);
-
- // Message Should be a QUE-1001
- validateMessageID("QUE-1001", log);
-
- // Queue is Durable
- assertEquals(DURABLE + " keyword not correct in log entry",
- _durable, fromMessage(log).contains(DURABLE));
-
- assertEquals(TRANSIENT + " keyword not correct in log entry.",
- !_durable, fromMessage(log).contains(TRANSIENT));
-
- // Queue is Priority
- assertEquals("Unexpected priority status:" + fromMessage(log), hasPriority,
- fromMessage(log).contains("Priority: " + PRIORITIES));
-
- // Queue is AutoDelete
- assertEquals("Unexpected AutoDelete status:" + fromMessage(log), hasAutodelete,
- fromMessage(log).contains("AutoDelete"));
-
- if(clientID != null)
- {
- assertTrue("Queue does not have correct owner value:" + fromMessage(log),
- fromMessage(log).contains("Owner: " + clientID));
- }
- else
- {
- assertFalse("Queue should not contain Owner tag:" + fromMessage(log),
- fromMessage(log).contains("Owner"));
- }
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/server/logging/ExchangeLoggingTest.java b/java/systests/src/main/java/org/apache/qpid/server/logging/ExchangeLoggingTest.java
deleted file mode 100644
index 1e48f34f99..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/server/logging/ExchangeLoggingTest.java
+++ /dev/null
@@ -1,217 +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.logging;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQSession_0_10;
-import org.apache.qpid.framing.AMQFrame;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.ExchangeDeleteBody;
-import org.apache.qpid.framing.ExchangeDeleteOkBody;
-import org.apache.qpid.framing.amqp_8_0.MethodRegistry_8_0;
-
-import javax.jms.Connection;
-import javax.jms.JMSException;
-import javax.jms.Queue;
-import javax.jms.Session;
-import java.io.IOException;
-import java.util.List;
-
-/**
- * Exchange
- *
- * The Exchange test suite validates that the follow log messages as specified in the Functional Specification.
- *
- * This suite of tests validate that the Exchange messages occur correctly and according to the following format:
- *
- * EXH-1001 : Create : [Durable] Type:<value> Name:<value>
- * EXH-1002 : Deleted
- */
-public class ExchangeLoggingTest extends AbstractTestLogging
-{
-
- static final String EXH_PREFIX = "EXH-";
-
- Connection _connection;
- Session _session;
- Queue _queue;
- String _name;
- String _type;
-
- @Override
- public void setUp() throws Exception
- {
- super.setUp();
-
- _connection = getConnection();
-
- _session = _connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- _type = "direct";
- _name = getTestQueueName()+ "-exchange";
-
- _queue = _session.createQueue(_type + "://" + _name + "/queue/queue");
-
- }
-
- /**
- * Description:
- * When a durable exchange is created an EXH-1001 message is logged with the Durable tag. This will be the first message from this exchange.
- * Input:
- *
- * 1. Running broker
- * 2. Client requests a durable exchange be created.
- * Output:
- *
- * <date> EXH-1001 : Create : Durable Type:<value> Name:<value>
- *
- * Validation Steps:
- * 3. The EXH ID is correct
- * 4. The Durable tag is present in the message
- */
-
- public void testExchangeCreateDurable() throws JMSException, IOException
- {
- // The client cannot create durable exchanges lets just look at the
- // ones the broker creates at startup.
-
- // They should all be durable
-
- // Ensure we have received the EXH log msg.
- waitForMessage("EXH-1001");
-
- List<String> results = findMatches(EXH_PREFIX);
-
- assertTrue("No Results found for Exchange.", results.size()>0);
-
- validateExchangeCreate(results, true, false);
- }
-
- /**
- * Description:
- * When an exchange is created an EXH-1001 message is logged. This will be the first message from this exchange.
- * Input:
- *
- * 1. Running broker
- * 2. Client requests an exchange be created.
- * Output:
- *
- * <date> EXH-1001 : Create : Type:<value> Name:<value>
- *
- * Validation Steps:
- * 3. The EXH ID is correct
- */
- public void testExchangeCreate() throws JMSException, IOException
- {
- //Ignore broker startup messages
- _monitor.reset();
-
- _session.createConsumer(_queue);
- // Ensure we have received the EXH log msg.
- waitForMessage("EXH-1001");
-
- List<String> results = findMatches(EXH_PREFIX);
-
- assertEquals("Result set larger than expected.", 1, results.size());
-
- validateExchangeCreate(results, false, true);
- }
-
- private void validateExchangeCreate(List<String> results, boolean durable, boolean checkNameAndType)
- {
- String log = getLogMessage(results, 0);
- String message = getMessageString(fromMessage(log));
-
- validateMessageID("EXH-1001", log);
-
- assertTrue("Log Message does not start with create:" + message,
- message.startsWith("Create"));
-
- assertEquals("Unexpected Durable state:" + message, durable,
- message.contains("Durable"));
-
- if(checkNameAndType)
- {
- assertTrue("Log Message does not contain Type:" + message,
- message.contains("Type: " + _type));
- assertTrue("Log Message does not contain Name:" + message,
- message.contains("Name: " + _name));
- }
- }
-
- /**
- * Description:
- * An Exchange can be deleted through an AMQP ExchangeDelete method. When this is successful an EXH-1002 Delete message will be logged. This will be the last message from this exchange.
- * Input:
- *
- * 1. Running broker
- * 2. A new Exchange has been created
- * 3. Client requests that the new exchange be deleted.
- * Output:
- *
- * <date> EXH-1002 : Deleted
- *
- * Validation Steps:
- * 4. The EXH ID is correct
- * 5. There is a corresponding EXH-1001 Create message logged.
- */
- public void testExchangeDelete() throws Exception, IOException
- {
- //Ignore broker startup messages
- _monitor.reset();
-
- //create the exchange by creating a consumer
- _session.createConsumer(_queue);
-
- //now delete the exchange
- if(isBroker010())
- {
- ((AMQSession_0_10) _session).sendExchangeDelete(_name, false);
- }
- else
- {
- MethodRegistry_8_0 registry = new MethodRegistry_8_0();
-
- ExchangeDeleteBody body = registry.createExchangeDeleteBody(0, new AMQShortString(_name), false, true);
-
- AMQFrame exchangeDeclare = body.generateFrame(0);
-
- ((AMQConnection) _connection).getProtocolHandler().syncWrite(exchangeDeclare, ExchangeDeleteOkBody.class);
- }
-
- //Wait and ensure we get our last EXH-1002 msg
- waitForMessage("EXH-1002");
-
- List<String> results = findMatches(EXH_PREFIX);
-
- assertEquals("Result set larger than expected.", 2, results.size());
-
- validateExchangeCreate(results, false, false);
-
- String log = getLogMessage(results, 1);
- validateMessageID("EXH-1002", log);
-
- String message = getMessageString(fromMessage(log));
- assertEquals("Log Message not as expected", "Deleted", message);
-
- }
-
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/server/logging/ManagementLoggingTest.java b/java/systests/src/main/java/org/apache/qpid/server/logging/ManagementLoggingTest.java
deleted file mode 100644
index 595c0d5f35..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/server/logging/ManagementLoggingTest.java
+++ /dev/null
@@ -1,305 +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.logging;
-
-import junit.framework.AssertionFailedError;
-
-import org.apache.qpid.util.LogMonitor;
-
-import java.util.List;
-import java.io.File;
-
-/**
- * Management Console Test Suite
- *
- * The Management Console test suite validates that the follow log messages as specified in the Functional Specification.
- *
- * This suite of tests validate that the management console messages occur correctly and according to the following format:
- *
- * MNG-1001 : Startup
- * MNG-1002 : Starting : <service> : Listening on port <Port>
- * MNG-1003 : Shutting down : <service> : port <Port>
- * MNG-1004 : Ready
- * MNG-1005 : Stopped
- * MNG-1006 : Using SSL Keystore : <path>
- */
-public class ManagementLoggingTest extends AbstractTestLogging
-{
- private static final String MNG_PREFIX = "MNG-";
-
- public void setUp() throws Exception
- {
- setLogMessagePrefix();
-
- // We either do this here or have a null check in tearDown.
- // As when this test is run against profiles other than java it will NPE
- _monitor = new LogMonitor(_outputFile);
- //We explicitly do not call super.setUp as starting up the broker is
- //part of the test case.
-
- }
-
- /**
- * Description:
- * Using the startup configuration validate that the management startup
- * message is logged correctly.
- * Input:
- * Standard configuration with management enabled
- * Output:
- *
- * <date> MNG-1001 : Startup
- *
- * Constraints:
- * This is the FIRST message logged by MNG
- * Validation Steps:
- *
- * 1. The BRK ID is correct
- * 2. This is the FIRST message logged by MNG
- */
- public void testManagementStartupEnabled() throws Exception
- {
- // This test only works on external java brokers due to the fact that
- // Management is disabled on InVM brokers.
- if (isJavaBroker() && isExternalBroker())
- {
- startBrokerAndCreateMonitor(true, false);
-
- // Ensure we have received the MNG log msg.
- waitForMessage("MNG-1001");
-
- List<String> results = findMatches(MNG_PREFIX);
-
- try
- {
- // Validation
-
- assertTrue("MNGer message not logged", results.size() > 0);
-
- String log = getLogMessage(results, 0);
-
- //1
- validateMessageID("MNG-1001", log);
-
- //2
- //There will be 2 copies of the startup message (one via SystemOut, and one via Log4J)
- results = findMatches("MNG-1001");
- assertEquals("Unexpected startup message count.",
- 2, results.size());
-
- //3
- assertEquals("Startup log message is not 'Startup'.", "Startup",
- getMessageString(log));
- }
- catch (AssertionFailedError afe)
- {
- dumpLogs(results, _monitor);
- throw afe;
- }
- }
- }
-
- /**
- * Description:
- * Verify that when management is disabled in the configuration file the
- * startup message is not logged.
- * Input:
- * Standard configuration with management disabled
- * Output:
- * NO MNG messages
- * Validation Steps:
- *
- * 1. Validate that no MNG messages are produced.
- */
- public void testManagementStartupDisabled() throws Exception
- {
- // This test only works on external java brokers due to the fact that
- // Management is disabled on InVM brokers.
- if (isJavaBroker() && isExternalBroker())
- {
- startBrokerAndCreateMonitor(false, false);
-
- List<String> results = findMatches(MNG_PREFIX);
- try
- {
- // Validation
-
- assertEquals("MNGer messages logged", 0, results.size());
- }
- catch (AssertionFailedError afe)
- {
- dumpLogs(results, _monitor);
- throw afe;
- }
- }
- }
-
- /**
- * The two MNG-1002 messages are logged at the same time so lets test them
- * at the same time.
- *
- * Description:
- * Using the default configuration validate that the RMI Registry socket is
- * correctly reported as being opened
- *
- * Input:
- * The default configuration file
- * Output:
- *
- * <date> MESSAGE MNG-1002 : Starting : RMI Registry : Listening on port 8999
- *
- * Constraints:
- * The RMI ConnectorServer and Registry log messages do not have a prescribed order
- * Validation Steps:
- *
- * 1. The MNG ID is correct
- * 2. The specified port is the correct '8999'
- *
- * Description:
- * Using the default configuration validate that the RMI ConnectorServer
- * socket is correctly reported as being opened
- *
- * Input:
- * The default configuration file
- * Output:
- *
- * <date> MESSAGE MNG-1002 : Starting : RMI ConnectorServer : Listening on port 9099
- *
- * Constraints:
- * The RMI ConnectorServer and Registry log messages do not have a prescribed order
- * Validation Steps:
- *
- * 1. The MNG ID is correct
- * 2. The specified port is the correct '9099'
- */
- public void testManagementStartupRMIEntries() throws Exception
- {
- // This test only works on external java brokers due to the fact that
- // Management is disabled on InVM brokers.
- if (isJavaBroker() && isExternalBroker())
- {
- startBrokerAndCreateMonitor(true, false);
-
- List<String> results = waitAndFindMatches("MNG-1002");
- try
- {
- // Validation
-
- //There will be 4 startup messages (two via SystemOut, and two via Log4J)
- assertEquals("Unexpected MNG-1002 message count", 4, results.size());
-
- String log = getLogMessage(results, 0);
-
- //1
- validateMessageID("MNG-1002", log);
-
- //Check the RMI Registry port is as expected
- int mPort = getPort() + (DEFAULT_MANAGEMENT_PORT - DEFAULT_PORT);
- assertTrue("RMI Registry port not as expected(" + mPort + ").:" + getMessageString(log),
- getMessageString(log).endsWith(String.valueOf(mPort)));
-
- log = getLogMessage(results, 2);
-
- //1
- validateMessageID("MNG-1002", log);
-
- // We expect the RMI Registry port (the defined 'management port') to be
- // 100 lower than the JMX RMIConnector Server Port (the actual JMX server)
- int jmxPort = mPort + 100;
- assertTrue("JMX RMIConnectorServer port not as expected(" + jmxPort + ").:" + getMessageString(log),
- getMessageString(log).endsWith(String.valueOf(jmxPort)));
- }
- catch (AssertionFailedError afe)
- {
- dumpLogs(results, _monitor);
- throw afe;
- }
- }
- }
-
- /**
- * Description:
- * Using the default configuration with SSL enabled for the management port the SSL Keystore path should be reported via MNG-1006
- * Input:
- * Management SSL enabled default configuration.
- * Output:
- *
- * <date> MESSAGE MNG-1006 : Using SSL Keystore : test_resources/ssl/keystore.jks
- *
- * Validation Steps:
- *
- * 1. The MNG ID is correct
- * 2. The keystore path is as specified in the configuration
- */
- public void testManagementStartupSSLKeystore() throws Exception
- {
- // This test only works on external java brokers due to the fact that
- // Management is disabled on InVM brokers.
- if (isJavaBroker() && isExternalBroker())
- {
- startBrokerAndCreateMonitor(true, true);
-
- List<String> results = waitAndFindMatches("MNG-1006");
- try
- {
- // Validation
-
- assertTrue("MNGer message not logged", results.size() > 0);
-
- String log = getLogMessage(results, 0);
-
- //1
- validateMessageID("MNG-1006", log);
-
- // Validate we only have two MNG-1002 (one via stdout, one via log4j)
- results = findMatches("MNG-1006");
- assertEquals("Upexpected SSL Keystore message count",
- 2, results.size());
-
- // Validate the keystore path is as expected
- assertTrue("SSL Keystore entry expected.:" + getMessageString(log),
- getMessageString(log).endsWith(new File(getConfigurationStringProperty("management.ssl.keyStorePath")).getName()));
- }
- catch (AssertionFailedError afe)
- {
- dumpLogs(results, _monitor);
- throw afe;
- }
- }
-
- }
-
- private void startBrokerAndCreateMonitor(boolean managementEnabled, boolean useManagementSSL) throws Exception
- {
- //Ensure management is on
- setConfigurationProperty("management.enabled", String.valueOf(managementEnabled));
-
- if(useManagementSSL)
- {
- // This test requires we have an ssl connection
- setConfigurationProperty("management.ssl.enabled", "true");
- }
-
- startBroker();
-
- // Now we can create the monitor as _outputFile will now be defined
- _monitor = new LogMonitor(_outputFile);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/server/logging/MemoryMessageStoreLoggingTest.java b/java/systests/src/main/java/org/apache/qpid/server/logging/MemoryMessageStoreLoggingTest.java
deleted file mode 100644
index 34d9e1f057..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/server/logging/MemoryMessageStoreLoggingTest.java
+++ /dev/null
@@ -1,186 +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.logging;
-
-import java.util.Arrays;
-import java.util.List;
-
-import org.apache.qpid.server.configuration.ServerConfiguration;
-import org.apache.qpid.server.logging.subjects.AbstractTestLogSubject;
-import org.apache.qpid.util.LogMonitor;
-
-/**
- * The MessageStore test suite validates that the follow log messages as
- * specified in the Functional Specification.
- *
- * This suite of tests validate that the MessageStore messages occur correctly
- * and according to the following format:
- *
- * MST-1001 : Created : <name>
- * MST-1003 : Closed
- *
- * NOTE: Only for Persistent Stores
- * MST-1002 : Store location : <path>
- * MST-1004 : Recovery Start [: <queue.name>]
- * MST-1005 : Recovered <count> messages for queue <queue.name>
- * MST-1006 : Recovery Complete [: <queue.name>]
- */
-public class MemoryMessageStoreLoggingTest extends AbstractTestLogging
-{
- protected static final String MESSAGES_STORE_PREFIX = "MST-";
-
- public void setUp() throws Exception
- {
- //We explicitly do not call super.setUp as starting up the broker is
- //part of the test case.
- // So we have to make the new Log Monitor here
-
- _monitor = new LogMonitor(_outputFile);
- }
-
- /**
- * Description:
- * During Virtualhost startup a MessageStore will be created. The first MST
- * message that must be logged is the MST-1001 MessageStore creation.
- * Input:
- * Default configuration
- * Output:
- * <date> MST-1001 : Created : <name>
- *
- * Validation Steps:
- *
- * 1. The MST ID is correct
- * 2. The <name> is the correct MessageStore type as specified in the Default configuration
- *
- * @throws Exception caused by broker startup
- */
- public void testMessageStoreCreation() throws Exception
- {
- assertLoggingNotYetOccured(MESSAGES_STORE_PREFIX);
-
- super.setUp();
-
- List<String> results = waitAndFindMatches(MESSAGES_STORE_PREFIX);
-
- // Validation
-
- assertTrue("MST messages not logged", results.size() > 0);
-
- String log = getLogMessage(results, 0);
- //1
- assertEquals("MST-1001 is not the first MST message", "MST-1001", getMessageID(fromMessage(log)));
-
- //Validate each vhost logs a creation
- results = waitAndFindMatches("MST-1001");
-
- // Load VirtualHost list from file.
- List<String> vhosts = Arrays.asList(getServerConfig().getVirtualHosts());
-
- assertEquals("Each vhost did not create a store.", vhosts.size(), results.size());
-
- for (int index = 0; index < results.size(); index++)
- {
- String result = getLogMessage(results, index);
-
- // getSlice will return extract the vhost from vh(/test) -> '/test'
- // so remove the '/' to get the name
- String vhostName = AbstractTestLogSubject.getSlice("vh", result).substring(1);
-
- // Get the store class used in the configuration for the virtualhost.
- String fullStoreName = getServerConfig().getVirtualHostConfig(vhostName).getMessageStoreClass();
-
- // Get the Simple class name from the expected class name of o.a.q.s.s.MMS
- String storeName = fullStoreName.substring(fullStoreName.lastIndexOf(".") + 1);
-
- assertTrue("MST-1001 does not contains correct store name:"
- + storeName + ":" + result, getMessageString(result).endsWith(storeName));
-
- assertEquals("The store name does not match expected value",
- storeName, AbstractTestLogSubject.getSlice("ms", fromSubject(result)));
- }
- }
-
- /**
- * Description:
- * During shutdown the MessageStore will also cleanly close. When this has
- * completed a MST-1003 closed message will be logged. No further messages
- * from this MessageStore will be logged after this message.
- *
- * Input:
- * Default configuration
- * Output:
- * <date> MST-1003 : Closed
- *
- * Validation Steps:
- *
- * 1. The MST ID is correct
- * 2. This is teh last log message from this MessageStore
- *
- * @throws Exception caused by broker startup
- */
- public void testMessageStoreClose() throws Exception
- {
- assertLoggingNotYetOccured(MESSAGES_STORE_PREFIX);
-
- super.setUp();
-
- //Stop the broker so we get the close messages.
- stopBroker();
-
- List<String> results = waitAndFindMatches(MESSAGES_STORE_PREFIX);
-
- // Validation
-
- assertTrue("MST messages not logged", results.size() > 0);
-
- // Load VirtualHost list from file.
- ServerConfiguration configuration = new ServerConfiguration(_configFile);
- configuration.initialise();
- List<String> vhosts = Arrays.asList(configuration.getVirtualHosts());
-
- //Validate each vhost logs a creation
- results = waitAndFindMatches("MST-1003");
-
- assertEquals("Each vhost did not close its store.", vhosts.size(), results.size());
-
- for (int index = 0; index < results.size(); index++)
- {
- String result = getLogMessage(results, index);
-
- // getSlice will return extract the vhost from vh(/test) -> '/test'
- // so remove the '/' to get the name
- String vhostName = AbstractTestLogSubject.getSlice("vh", result).substring(1);
-
- // Get the store class used in the configuration for the virtualhost.
- String fullStoreName = configuration.getVirtualHostConfig(vhostName).getMessageStoreClass();
-
- // Get the Simple class name from the expected class name of o.a.q.s.s.MMS
- String storeName = fullStoreName.substring(fullStoreName.lastIndexOf(".") + 1);
-
- assertEquals("MST-1003 does not close:",
- "Closed", getMessageString(result));
-
- assertEquals("The store name does not match expected value",
- storeName, AbstractTestLogSubject.getSlice("ms", fromSubject(result)));
- }
- }
-
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/server/logging/QueueLoggingTest.java b/java/systests/src/main/java/org/apache/qpid/server/logging/QueueLoggingTest.java
deleted file mode 100644
index b8a42c0ab3..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/server/logging/QueueLoggingTest.java
+++ /dev/null
@@ -1,183 +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.logging;
-
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.client.failover.FailoverException;
-import org.apache.qpid.server.logging.subjects.AbstractTestLogSubject;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.AMQException;
-
-import javax.jms.Connection;
-import javax.jms.Session;
-import javax.jms.Queue;
-import javax.jms.JMSException;
-import javax.naming.NamingException;
-import java.util.List;
-import java.io.IOException;
-
-/**
- * The Queue test suite validates that the follow log messages as specified in
- * the Functional Specification.
- *
- * This suite of tests validate that the Queue messages occur correctly and
- * according to the following format:
- *
- * QUE-1002 : Deleted
- */
-public class QueueLoggingTest extends AbstractTestLogging
-{
- protected Connection _connection;
- protected Session _session;
- private static final String QUEUE_PREFIX = "QUE-";
-
- public void setUp() throws Exception
- {
- super.setUp();
- //Remove broker startup logging messages
- _monitor.reset();
-
- _connection = getConnection();
- _session = _connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- }
-
- /**
- * Description:
- * An explict QueueDelete request must result in a QUE-1002 Deleted message
- * being logged. This can be done via an explict AMQP QueueDelete method.
- * Input:
- *
- * 1. Running Broker
- * 2. Queue created on the broker with no subscribers
- * 3. Client requests the queue be deleted via a QueueDelete
- * Output:
- *
- * <date> QUE-1002 : Deleted
- *
- * Validation Steps:
- *
- * 4. The QUE ID is correct
- *
- * @throws java.io.IOException
- * @throws javax.jms.JMSException
- * @throws javax.naming.NamingException
- */
- public void testQueueDelete() throws NamingException, JMSException, IOException, FailoverException, AMQException
- {
- // To force a queue Creation Event we need to create a consumer.
- Queue queue = _session.createQueue(getTestQueueName());
-
- _session.createConsumer(queue);
-
- // Delete Queue
- ((AMQSession)_session).sendQueueDelete(new AMQShortString(queue.getQueueName()));
-
- //Perform a synchronous action to ensure that the above log will be on disk
- _session.close();
-
- // Validation
- //Ensure that we wait for the QUE log message
- waitAndFindMatches("QUE-1002");
-
- List<String> results = findMatches(QUEUE_PREFIX);
-
- // Only 1 Queue message should hav been logged
- assertEquals("Result set size not as expected", 2, results.size());
-
- String log = getLogMessage(results, 0);
-
- // Message Should be a QUE-1001
- validateMessageID("QUE-1001", log);
-
- String createdQueueName = AbstractTestLogSubject.getSlice("qu", fromSubject(log));
-
- log = getLogMessage(results, 1);
- // Message Should be a QUE-1002
- validateMessageID("QUE-1002", log);
-
- assertEquals("Log Message is incorrect ", "Deleted", getMessageString(fromMessage(log)));
-
- assertEquals("Queue Delete not for created queue:", createdQueueName,
- AbstractTestLogSubject.getSlice("qu", fromSubject(log)));
- }
-
-
- /**
- * Description:
- * An explict QueueDelete request must result in a QUE-1002 Deleted message
- * being logged. This can be done via an explict AMQP QueueDelete method.
- * Input:
- *
- * 1. Running Broker
- * 2. Queue created on the broker with no subscribers
- * 3. Client creates a temporary queue then disconnects
- * Output:
- *
- * <date> QUE-1002 : Deleted
- *
- * Validation Steps:
- *
- * 4. The QUE ID is correct
- *
- * @throws java.io.IOException
- * @throws javax.jms.JMSException
- * @throws javax.naming.NamingException
- */
- public void testQueueAutoDelete() throws NamingException, JMSException, IOException
- {
- // Create a temporary queue so that when we consume from it and
- // then close the consumer it will be autoDeleted.
- _session.createConsumer(_session.createTemporaryQueue()).close();
-
- if(isBroker010())
- {
- //auto-delete is at session close for 0-10
- _session.close();
- }
-
- // Validation
- //Ensure that we wait for the QUE log message
- waitAndFindMatches("QUE-1002");
-
- List<String> results = findMatches(QUEUE_PREFIX);
-
- // Only 1 Queue message should hav been logged
- assertEquals("Result set size not as expected", 2, results.size());
-
- String log = getLogMessage(results, 0);
-
- // Message Should be a QUE-1001
- validateMessageID("QUE-1001", log);
-
- String createdQueueName = AbstractTestLogSubject.getSlice("qu", fromSubject(log));
-
- log = getLogMessage(results, 1);
- // Message Should be a QUE-1002
- validateMessageID("QUE-1002", log);
-
- assertEquals("Log Message is incorrect ", "Deleted", getMessageString(fromMessage(log)));
-
- assertEquals("Queue Delete not for created queue:", createdQueueName,
- AbstractTestLogSubject.getSlice("qu", fromSubject(log)));
-
- }
-
-} \ No newline at end of file
diff --git a/java/systests/src/main/java/org/apache/qpid/server/logging/SubscriptionLoggingTest.java b/java/systests/src/main/java/org/apache/qpid/server/logging/SubscriptionLoggingTest.java
deleted file mode 100644
index 6e156f091e..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/server/logging/SubscriptionLoggingTest.java
+++ /dev/null
@@ -1,458 +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.logging;
-
-import junit.framework.AssertionFailedError;
-import org.apache.qpid.client.AMQConnection;
-
-import javax.jms.Connection;
-import javax.jms.JMSException;
-import javax.jms.MessageConsumer;
-import javax.jms.Queue;
-import javax.jms.Session;
-import javax.jms.Topic;
-import javax.jms.Message;
-import java.io.IOException;
-import java.util.List;
-
-/**
- * Subscription
- *
- * The Subscription test suite validates that the follow log messages as specified in the Functional Specification.
- *
- * This suite of tests validate that the Subscription messages occur correctly and according to the following format:
- *
- * SUB-1001 : Create : [Durable] [Arguments : <key=value>]
- * SUB-1002 : Close
- * SUB-1003 : State : <state>
- */
-public class SubscriptionLoggingTest extends AbstractTestLogging
-{
- static final String SUB_PREFIX = "SUB-";
-
- Connection _connection;
- Session _session;
- Queue _queue;
- Topic _topic;
-
- @Override
- public void setUp() throws Exception
- {
- super.setUp();
- //Remove broker startup logging messages
- _monitor.reset();
-
- _connection = getConnection();
-
- _session = _connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- _queue = (Queue) getInitialContext().lookup(QUEUE);
- _topic = (Topic) getInitialContext().lookup(TOPIC);
- }
-
- /**
- * Description:
- * When a Subscription is created it will be logged. This test validates that Subscribing to a transient queue is correctly logged.
- * Input:
- *
- * 1. Running Broker
- * 2. Create a new Subscription to a transient queue/topic.
- * Output: 6
- *
- * <date> SUB-1001 : Create
- *
- * Validation Steps:
- * 3. The SUB ID is correct
- *
- * @throws java.io.IOException - if there is a problem getting the matches
- * @throws javax.jms.JMSException - if there is a problem creating the consumer
- */
- public void testSubscriptionCreate() throws JMSException, IOException
- {
- _session.createConsumer(_queue);
-
- //Validate
-
- //Ensure that we wait for the SUB log message
- waitAndFindMatches("SUB-1001");
-
- List<String> results = findMatches(SUB_PREFIX);
-
- assertEquals("Result set larger than expected.", 1, results.size());
-
- String log = getLogMessage(results, 0);
-
- validateMessageID("SUB-1001", log);
-
- assertEquals("Log Message not as expected", "Create", getMessageString(fromMessage(log)));
- }
-
- /**
- * Description:
- * The creation of a Durable Subscription, such as a JMS DurableTopicSubscriber will result in an extra Durable tag being included in the Create log message
- * Input:
- *
- * 1. Running Broker
- * 2. Creation of a JMS DurableTopicSubiber
- * Output:
- *
- * <date> SUB-1001 : Create : Durable
- *
- * Validation Steps:
- * 3. The SUB ID is correct
- * 4. The Durable tag is present in the message
- * NOTE: A Subscription is not Durable, the queue it consumes from is.
- *
- * @throws java.io.IOException - if there is a problem getting the matches
- * @throws javax.jms.JMSException - if there is a problem creating the consumer
- */
- public void testSubscriptionCreateDurable() throws JMSException, IOException
- {
- _session.createDurableSubscriber(_topic, getName());
-
- //Validate
- //Ensure that we wait for the SUB log message
- waitAndFindMatches("SUB-1001");
-
- List<String> results = findMatches(SUB_PREFIX);
-
- assertEquals("Result set not as expected.", 1, results.size());
-
- String log = getLogMessage(results, 0);
-
- validateMessageID("SUB-1001", log);
-
- String message = getMessageString(fromMessage(log));
- assertTrue("Durable not on log message:" + message, message.contains("Durable"));
- }
-
- /**
- * Description:
- * The creation of a QueueBrowser will provides a number arguments and so should form part of the SUB-1001 Create message.
- * Input:
- *
- * 1. Running Broker
- * 2. Java Client creates a QueueBroweser
- * Output:
- *
- * <date> SUB-1001 : Create : Arguments : <key=value>
- *
- * Validation Steps:
- * 3. The SUB ID is correct
- * 4. The Arguments are present in the message
- * 5. Arguments keys include AutoClose and Browser.
- *
- * @throws java.io.IOException - if there is a problem getting the matches
- * @throws javax.jms.JMSException - if there is a problem creating the consumer
- */
- public void testSubscriptionCreateQueueBrowser() throws JMSException, IOException
- {
- _session.createBrowser(_queue);
-
- //Validate
- //Ensure that we wait for the SUB log message
- waitAndFindMatches("SUB-1001");
-
- List<String> results = findMatches(SUB_PREFIX);
-
- assertEquals("Result set larger than expected.", 2, results.size());
-
- String log = getLogMessage(results, 0);
-
- validateMessageID("SUB-1001", log);
-
- String message = getMessageString(fromMessage(log));
- assertTrue("Browser not on log message:" + message, message.contains("Browser"));
- if(!isBroker010())
- {
- assertTrue("AutoClose not on log message:" + message, message.contains("AutoClose"));
- }
-
- // Beacause it is an auto close and we have no messages on the queue we
- // will get a close message
- log = getLogMessage(results, 1);
- validateMessageID("SUB-1002", log);
-
- }
-
- /**
- * Description:
- * The creation of a Subscriber with a JMS Selector will result in the Argument field being populated. These argument key/value pairs are then shown in the log message.
- * Input:
- *
- * 1. Running Broker
- * 2. Subscriber created with a JMS Selector.
- * Output:
- *
- * <date> SUB-1001 : Create : Arguments : <key=value>
- *
- * Validation Steps:
- * 3. The SUB ID is correct
- * 4. Argument tag is present in the message
- *
- * @throws java.io.IOException - if there is a problem getting the matches
- * @throws javax.jms.JMSException - if there is a problem creating the consumer
- */
- public void testSubscriptionCreateWithArguments() throws JMSException, IOException
- {
- final String SELECTOR = "Selector='True'";
- _session.createConsumer(_queue, SELECTOR);
-
- //Validate
-
- //Ensure that we wait for the SUB log message
- waitAndFindMatches("SUB-1001");
-
- List<String> results = findMatches(SUB_PREFIX);
-
- assertEquals("Result set larger than expected.", 1, results.size());
-
- String log = getLogMessage(results, 0);
-
- validateMessageID("SUB-1001", log);
-
- String message = getMessageString(fromMessage(log));
- assertTrue("Selector not on log message:" + message, message.contains(SELECTOR));
- }
-
- /**
- * Description:
- * The final combination of SUB-1001 Create messages involves the creation of a Durable Subscription that also contains a set of Arguments, such as those provided via a JMS Selector.
- * Input:
- *
- * 1. Running Broker
- * 2. Java Client creates a Durable Subscription with Selector
- * Output:
- *
- * <date> SUB-1001 : Create : Durable Arguments : <key=value>
- *
- * Validation Steps:
- * 3. The SUB ID is correct
- * 4. The tag Durable is present in the message
- * 5. The Arguments are present in the message
- *
- * @throws java.io.IOException - if there is a problem getting the matches
- * @throws javax.jms.JMSException - if there is a problem creating the consumer
- */
- public void testSubscriptionCreateDurableWithArguments() throws JMSException, IOException
- {
- final String SELECTOR = "Selector='True'";
- _session.createDurableSubscriber(_topic, getName(), SELECTOR, false);
-
- //Validate
-
- //Ensure that we wait for the SUB log message
- waitAndFindMatches("SUB-1001");
-
- List<String> results = findMatches(SUB_PREFIX);
-
- assertEquals("Result set larger than expected.", 1, results.size());
-
- String log = getLogMessage(results, 0);
-
- validateMessageID("SUB-1001", log);
-
- String message = getMessageString(fromMessage(log));
- assertTrue("Durable not on log message:" + message, message.contains("Durable"));
- assertTrue("Selector not on log message:" + message, message.contains(SELECTOR));
- }
-
- /**
- * Description:
- * When a Subscription is closed it will log this so that it can be correlated with the Create.
- * Input:
- *
- * 1. Running Broker
- * 2. Client with a subscription.
- * 3. The subscription is then closed.
- * Output:
- *
- * <date> SUB-1002 : Close
- *
- * Validation Steps:
- * 1. The SUB ID is correct
- * 2. There must be a SUB-1001 Create message preceding this message
- * 3. This must be the last message from the given Subscription
- *
- * @throws java.io.IOException - if there is a problem getting the matches
- * @throws javax.jms.JMSException - if there is a problem creating the consumer
- */
- public void testSubscriptionClose() throws JMSException, IOException
- {
- _session.createConsumer(_queue).close();
-
- //Validate
- //Ensure that we wait for the SUB log message
- waitAndFindMatches("SUB-1002");
-
- List<String> results = findMatches(SUB_PREFIX);
-
- //3
- assertEquals("Result set larger than expected.", 2, results.size());
-
- // 2
- String log = getLogMessage(results, 0);
- validateMessageID("SUB-1001", log);
- // 1
- log = getLogMessage(results, 1);
- validateMessageID("SUB-1002", log);
-
- String message = getMessageString(fromMessage(log));
- assertEquals("Log message is not close", "Close", message);
-
- }
-
- /**
- * Description:
- * When a Subscription fills its prefetch it will become suspended. This
- * will be logged as a SUB-1003 message.
- * Input:
- *
- * 1. Running broker
- * 2. Message Producer to put more data on the queue than the client's prefetch
- * 3. Client that ensures that its prefetch becomes full
- * Output:
- *
- * <date> SUB-1003 : State : <state>
- *
- * Validation Steps:
- * 1. The SUB ID is correct
- * 2. The state is correct
- *
- * @throws java.io.IOException - if there is a problem getting the matches
- * @throws javax.jms.JMSException - if there is a problem creating the consumer
- */
- public void testSubscriptionSuspend() throws Exception, IOException
- {
- //Close session with large prefetch
- _connection.createSession(false, Session.AUTO_ACKNOWLEDGE).close();
-
- int PREFETCH = 15;
-
- //Create new session with small prefetch
- _session = ((AMQConnection) _connection).createSession(true, Session.SESSION_TRANSACTED, PREFETCH);
-
- MessageConsumer consumer = _session.createConsumer(_queue);
-
- _connection.start();
-
- //Start the dispatcher & Unflow the channel.
- consumer.receiveNoWait();
-
- //Fill the prefetch and two extra so that our receive bellow allows the
- // subscription to become active
- // Previously we set this to 17 so that it would return to a suspended
- // state. However, testing has shown that the state change can occur
- // sufficiently quickly that logging does not occur consistently enough
- // for testing.
- int SEND_COUNT = 16;
- sendMessage(_session, _queue, SEND_COUNT);
- _session.commit();
- // Retreive the first message, and start the flow of messages
- Message msg = consumer.receive(1000);
- assertNotNull("First message not retreived", msg);
- _session.commit();
-
- // Drain the queue to ensure there is time for the ACTIVE log message
- // Check that we can received all the messages
- int receivedCount = 0;
- while (msg != null)
- {
- receivedCount++;
- msg = consumer.receive(1000);
- _session.commit();
- }
-
- //Validate we received all the messages
- assertEquals("Not all sent messages received.", SEND_COUNT, receivedCount);
-
- // Fill the queue again to suspend the consumer
- sendMessage(_session, _queue, SEND_COUNT);
- _session.commit();
-
- //Validate
- List<String> results = waitAndFindMatches("SUB-1003");
-
- try
- {
- // Validation expects three messages.
- // The Actor can be any one of the following depending on the exactly what is going on on the broker.
- // Ideally we would test that we can get all of them but setting up
- // the timing to do this in a consistent way is not benefitial.
- // Ensuring the State is as expected is sufficient.
-// INFO - MESSAGE [vh(/test)/qu(example.queue)] [sub:6(qu(example.queue))] SUB-1003 : State :
-// INFO - MESSAGE [con:6(guest@anonymous(26562441)/test)/ch:3] [sub:6(qu(example.queue))] SUB-1003 : State :
-// INFO - MESSAGE [sub:6(vh(test)/qu(example.queue))] [sub:6(qu(example.queue))] SUB-1003 : State :
-
- assertEquals("Result set not expected size:", 3, results.size());
-
- // Validate Initial Suspension
- String expectedState = "SUSPENDED";
- String log = getLogMessage(results, 0);
- validateSubscriptionState(log, expectedState);
-
- // After being suspended the subscription should become active.
- expectedState = "ACTIVE";
- log = getLogMessage(results, 1);
- validateSubscriptionState(log, expectedState);
-
- // Validate that it was re-suspended
- expectedState = "SUSPENDED";
- log = getLogMessage(results, 2);
- validateSubscriptionState(log, expectedState);
- // We only need validate the state.
- }
- catch (AssertionFailedError afe)
- {
- System.err.println("Log Dump:");
- for (String log : results)
- {
- System.err.println(log);
- }
- throw afe;
- }
- _connection.close();
-
- //Ensure the queue is drained before the test ends
- drainQueue(_queue);
-
- }
-
- /**
- * Validate that the given log statement is a well formatted SUB-1003
- * message. That means the ID and expected state are correct.
- *
- * @param log the log to test
- * @param expectedState the state that should be logged.
- */
- private void validateSubscriptionState(String log, String expectedState)
- {
- validateMessageID("SUB-1003", log);
- String logMessage = getMessageString(fromMessage(log));
- assertTrue("Log Message does not start with 'State'" + logMessage,
- logMessage.startsWith("State"));
-
- assertTrue("Log Message does not have expected State of '"
- + expectedState + "'" + logMessage,
- logMessage.endsWith(expectedState));
- }
-
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/server/logging/TransientQueueLoggingTest.java b/java/systests/src/main/java/org/apache/qpid/server/logging/TransientQueueLoggingTest.java
deleted file mode 100644
index 29f74c5818..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/server/logging/TransientQueueLoggingTest.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.
- *
- */
-package org.apache.qpid.server.logging;
-
-public class TransientQueueLoggingTest extends DurableQueueLoggingTest
-{
- public void setUp() throws Exception
- {
- super.setUp();
- _durable = false;
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/server/logging/VirtualHostLoggingTest.java b/java/systests/src/main/java/org/apache/qpid/server/logging/VirtualHostLoggingTest.java
deleted file mode 100644
index a23e40ecce..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/server/logging/VirtualHostLoggingTest.java
+++ /dev/null
@@ -1,134 +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.logging;
-
-import java.util.Arrays;
-import java.util.List;
-
-import junit.framework.AssertionFailedError;
-
-import org.apache.qpid.server.configuration.ServerConfiguration;
-
-/**
- * Virtualhost Test Cases
- * The virtualhost test suite validates that the follow log messages as specified in the Functional Specification.
- * <p/>
- * This suite of tests validate that the management console messages occur correctly and according to the following format:
- * <p/>
- * VHT-1001 : Created : <name>
- * VHT-1002 : Work directory : <path>
- * VHT-1003 : Closed
- */
-public class VirtualHostLoggingTest extends AbstractTestLogging
-{
- private static final String VHT_PREFIX = "VHT-";
-
- /**
- * Description:
- * Testing can be performed using the default configuration. The goal is to validate that for each virtualhost defined in the configuration file a VHT-1001 Created message is provided.
- * Input:
- * The default configuration file
- * Output:
- * <p/>
- * <date> VHT-1001 : Created : <name>
- * Validation Steps:
- * <p/>
- * The VHT ID is correct
- * A VHT-1001 is printed for each virtualhost defined in the configuration file.
- * This must be the first message for the specified virtualhost.
- *
- * @throws Exception caused by broker startup
- */
- public void testVirtualhostCreation() throws Exception
- {
- //Wait for the correct VHT message to arrive.
- waitForMessage(VHT_PREFIX + "1001");
-
- //Validate each vhost logs a creation
- List<String> results = findMatches(VHT_PREFIX + "1001");
-
- try
- {
- List<String> vhosts = Arrays.asList(getServerConfig().getVirtualHosts());
-
- assertEquals("Each vhost did not create a store.", vhosts.size(), results.size());
-
- for (int index = 0; index < results.size(); index++)
- {
- // Retrieve the vhostname from the log entry message 'Created : <vhostname>'
- String result = getLogMessage(results, index);
- String vhostName = getMessageString(fromMessage(result)).split(" ")[2];
-
- assertTrue("Virtualhost named in log not found in config file:" + vhostName + ":" + vhosts, vhosts.contains(vhostName));
- }
- }
- catch (AssertionFailedError afe)
- {
- dumpLogs(results, _monitor);
-
- throw afe;
- }
- }
-
- /**
- * Description:
- * Testing can be performed using the default configuration. During broker shutdown a VHT-1002 Closed message will be printed for each of the configured virtualhosts. For every virtualhost that was started a close must be logged. After the close message has been printed no further logging will be performed by this virtualhost.
- * Input:
- * The default configuration file
- * Output:
- * <p/>
- * <date> VHT-1002 : Closed
- * Validation Steps:
- * <p/>
- * The VHT ID is correct
- * This is the last VHT message for the given virtualhost.
- *
- * @throws Exception caused by broker startup
- */
- public void testVirtualhostClosure() throws Exception
- {
- stopBroker();
-
- // Wait for the correct VHT message to arrive.
- waitForMessage(VHT_PREFIX + "1002");
-
- // Validate each vhost logs a closure
- List<String> results = findMatches(VHT_PREFIX + "1002");
-
- try
- {
- // Load VirtualHost list from file.
- ServerConfiguration configuration = new ServerConfiguration(_configFile);
- configuration.initialise();
- List<String> vhosts = Arrays.asList(configuration.getVirtualHosts());
-
- assertEquals("Each vhost did not close their store.", vhosts.size(), results.size());
- }
- catch (AssertionFailedError afe)
- {
- dumpLogs(results, _monitor);
-
- throw afe;
- }
- }
-
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/server/persistent/NoLocalAfterRecoveryTest.java b/java/systests/src/main/java/org/apache/qpid/server/persistent/NoLocalAfterRecoveryTest.java
deleted file mode 100644
index a5aec3edce..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/server/persistent/NoLocalAfterRecoveryTest.java
+++ /dev/null
@@ -1,246 +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.persistent;
-
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.jms.ConnectionListener;
-import org.apache.qpid.jms.BrokerDetails;
-import org.apache.qpid.jms.ConnectionURL;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-import org.apache.qpid.server.registry.ConfigurationFileApplicationRegistry;
-import org.apache.qpid.server.store.DerbyMessageStore;
-import org.apache.commons.configuration.XMLConfiguration;
-
-import javax.jms.Connection;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.Session;
-import javax.jms.Topic;
-import javax.jms.TopicSubscriber;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.TimeUnit;
-
-import java.util.concurrent.CountDownLatch;
-import java.io.File;
-
-/**
- * QPID-1813 : We do not store the client id with a message so on store restart
- * that information is lost and we are unable to perform no local checks.
- *
- * QPID-1813 highlights the lack of testing here as the broker will NPE as it
- * assumes that the client id of the publisher will always exist
- */
-public class NoLocalAfterRecoveryTest extends QpidBrokerTestCase implements ConnectionListener
-{
- protected final String MY_TOPIC_SUBSCRIPTION_NAME = this.getName();
- protected static final int SEND_COUNT = 10;
- private CountDownLatch _failoverComplete = new CountDownLatch(1);
-
- protected ConnectionURL _connectionURL;
-
- @Override
- protected void setUp() throws Exception
- {
-
- XMLConfiguration configuration = new XMLConfiguration(_configFile);
- configuration.setProperty("virtualhosts.virtualhost.test.store.class", "org.apache.qpid.server.store.DerbyMessageStore");
- configuration.setProperty("virtualhosts.virtualhost.test.store."+ DerbyMessageStore.ENVIRONMENT_PATH_PROPERTY,
- System.getProperty("QPID_WORK", System.getProperty("java.io.tmpdir")) + File.separator + "derbyDB-NoLocalAfterRecoveryTest");
-
- File tmpFile = File.createTempFile("configFile", "test");
- tmpFile.deleteOnExit();
- configuration.save(tmpFile);
-
- _configFile = tmpFile;
- _connectionURL = getConnectionURL();
-
- BrokerDetails details = _connectionURL.getBrokerDetails(0);
-
- // Due to the problem with SingleServer delaying on all connection
- // attempts. So using a high retry value.
- if (_broker.equals(VM))
- {
- // Local testing suggests InVM restart takes under a second
- details.setProperty(BrokerDetails.OPTIONS_RETRY, "5");
- details.setProperty(BrokerDetails.OPTIONS_CONNECT_DELAY, "200");
- }
- else
- {
- // This will attempt to failover for 3 seconds.
- // Local testing suggests failover takes 2 seconds
- details.setProperty(BrokerDetails.OPTIONS_RETRY, "10");
- details.setProperty(BrokerDetails.OPTIONS_CONNECT_DELAY, "500");
- }
-
- super.setUp();
- }
-
- public void test() throws Exception
- {
-
- Connection connection = getConnection(_connectionURL);
- Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
-
- Topic topic = (Topic) getInitialContext().lookup("topic");
-
- TopicSubscriber noLocalSubscriber = session.
- createDurableSubscriber(topic, MY_TOPIC_SUBSCRIPTION_NAME + "-NoLocal",
- null, true);
-
- TopicSubscriber normalSubscriber = session.
- createDurableSubscriber(topic, MY_TOPIC_SUBSCRIPTION_NAME + "-Normal",
- null, false);
-
- List<Message> sent = sendMessage(session, topic, SEND_COUNT);
-
- session.commit();
-
- assertEquals("Incorrect number of messages sent",
- SEND_COUNT, sent.size());
-
-
- // Check messages can be received as expected.
- connection.start();
-
- assertTrue("No Local Subscriber is not a no-local subscriber",
- noLocalSubscriber.getNoLocal());
-
- assertFalse("Normal Subscriber is a no-local subscriber",
- normalSubscriber.getNoLocal());
-
-
- List<Message> received = receiveMessage(noLocalSubscriber, SEND_COUNT);
- assertEquals("No Local Subscriber Received messages", 0, received.size());
-
- received = receiveMessage(normalSubscriber, SEND_COUNT);
- assertEquals("Normal Subscriber Received no messages",
- SEND_COUNT, received.size());
-
-
- ((AMQConnection)connection).setConnectionListener(this);
-
- restartBroker();
-
-
- //Await
- if (!_failoverComplete.await(4000L, TimeUnit.MILLISECONDS))
- {
- fail("Failover Failed to compelete");
- }
-
- session.rollback();
-
- //Failover will restablish our clients
- assertTrue("No Local Subscriber is not a no-local subscriber",
- noLocalSubscriber.getNoLocal());
-
- assertFalse("Normal Subscriber is a no-local subscriber",
- normalSubscriber.getNoLocal());
-
-
- // NOTE : here that the NO-local subscriber actually now gets ALL the
- // messages as the connection has failed and they are consuming on a
- // different connnection to the one that was published on.
- received = receiveMessage(noLocalSubscriber, SEND_COUNT);
- assertEquals("No Local Subscriber Received messages", SEND_COUNT, received.size());
-
- received = receiveMessage(normalSubscriber, SEND_COUNT);
- assertEquals("Normal Subscriber Received no messages",
- SEND_COUNT, received.size());
-
- //leave the store in a clean state.
- session.commit();
- }
-
- protected List<Message> assertReceiveMessage(MessageConsumer messageConsumer,
- int count) throws JMSException
- {
-
- List<Message> receivedMessages = new ArrayList<Message>(count);
- for (int i = 0; i < count; i++)
- {
- Message received = messageConsumer.receive(1000);
-
- if (received != null)
- {
- receivedMessages.add(received);
- }
- else
- {
- fail("Only "
- + receivedMessages.size() + "/" + count + " received.");
- }
- }
-
- return receivedMessages;
- }
-
- protected List<Message> receiveMessage(MessageConsumer messageConsumer,
- int count) throws JMSException
- {
-
- List<Message> receivedMessages = new ArrayList<Message>(count);
- for (int i = 0; i < count; i++)
- {
- Message received = messageConsumer.receive(1000);
-
- if (received != null)
- {
- receivedMessages.add(received);
- }
- else
- {
- break;
- }
- }
-
- return receivedMessages;
- }
-
- public void bytesSent(long count)
- {
-
- }
-
- public void bytesReceived(long count)
- {
-
- }
-
- public boolean preFailover(boolean redirect)
- {
- return true;
- }
-
- public boolean preResubscribe()
- {
- return true;
- }
-
- public void failoverComplete()
- {
- _failoverComplete.countDown();
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/server/queue/ConflationQueueTest.java b/java/systests/src/main/java/org/apache/qpid/server/queue/ConflationQueueTest.java
deleted file mode 100644
index ae7be6f7f4..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/server/queue/ConflationQueueTest.java
+++ /dev/null
@@ -1,435 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.qpid.server.queue;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.client.AMQDestination;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.apache.qpid.url.AMQBindingURL;
-
-import javax.jms.Connection;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-import javax.jms.Queue;
-import javax.jms.Session;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-public class ConflationQueueTest extends QpidBrokerTestCase
-{
- private static final int TIMEOUT = 1500;
-
-
- private static final Logger _logger = Logger.getLogger(ConflationQueueTest.class);
-
-
-
- protected final String VHOST = "/test";
- protected final String QUEUE = "ConflationQueue";
-
- private static final int MSG_COUNT = 400;
-
- private Connection producerConnection;
- private MessageProducer producer;
- private Session producerSession;
- private Queue queue;
- private Connection consumerConnection;
- private Session consumerSession;
-
-
- private MessageConsumer consumer;
-
- protected void setUp() throws Exception
- {
- super.setUp();
-
- producerConnection = getConnection();
- producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- producerConnection.start();
-
-
- }
-
- protected void tearDown() throws Exception
- {
- producerConnection.close();
- consumerConnection.close();
- super.tearDown();
- }
-
- public void testConflation() throws Exception
- {
- consumerConnection = getConnection();
- consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
-
- final Map<String,Object> arguments = new HashMap<String, Object>();
- arguments.put("qpid.last_value_queue_key","key");
- ((AMQSession) producerSession).createQueue(new AMQShortString(QUEUE), false, true, false, arguments);
- queue = new org.apache.qpid.client.AMQQueue("amq.direct",QUEUE);
- ((AMQSession) producerSession).declareAndBind((AMQDestination)queue);
- producer = producerSession.createProducer(queue);
-
- for (int msg = 0; msg < MSG_COUNT; msg++)
- {
- producer.send(nextMessage(msg, producerSession));
- }
-
- producer.close();
- producerSession.close();
- producerConnection.close();
-
- consumer = consumerSession.createConsumer(queue);
- consumerConnection.start();
- Message received;
-
- List<Message> messages = new ArrayList<Message>();
- while((received = consumer.receive(1000))!=null)
- {
- messages.add(received);
- }
-
- assertEquals("Unexpected number of messages received",10,messages.size());
-
- for(int i = 0 ; i < 10; i++)
- {
- Message msg = messages.get(i);
- assertEquals("Unexpected message number received", MSG_COUNT - 10 + i, msg.getIntProperty("msg"));
- }
-
-
- }
-
-
- public void testConflationWithRelease() throws Exception
- {
- consumerConnection = getConnection();
- consumerSession = consumerConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
-
-
- final Map<String,Object> arguments = new HashMap<String, Object>();
- arguments.put("qpid.last_value_queue_key","key");
- ((AMQSession) producerSession).createQueue(new AMQShortString(QUEUE), false, true, false, arguments);
- queue = new org.apache.qpid.client.AMQQueue("amq.direct",QUEUE);
- ((AMQSession) producerSession).declareAndBind((AMQDestination)queue);
- producer = producerSession.createProducer(queue);
-
- for (int msg = 0; msg < MSG_COUNT/2; msg++)
- {
- producer.send(nextMessage(msg, producerSession));
-
- }
-
- // HACK to do something synchronous
- ((AMQSession)producerSession).sync();
-
- consumer = consumerSession.createConsumer(queue);
- consumerConnection.start();
- Message received;
- List<Message> messages = new ArrayList<Message>();
- while((received = consumer.receive(1000))!=null)
- {
- messages.add(received);
- }
-
- assertEquals("Unexpected number of messages received",10,messages.size());
-
- for(int i = 0 ; i < 10; i++)
- {
- Message msg = messages.get(i);
- assertEquals("Unexpected message number received", MSG_COUNT/2 - 10 + i, msg.getIntProperty("msg"));
- }
-
- consumerSession.close();
- consumerConnection.close();
-
-
- consumerConnection = getConnection();
- consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
-
- for (int msg = MSG_COUNT/2; msg < MSG_COUNT; msg++)
- {
- producer.send(nextMessage(msg, producerSession));
- }
-
-
- // HACK to do something synchronous
- ((AMQSession)producerSession).sync();
-
- consumer = consumerSession.createConsumer(queue);
- consumerConnection.start();
-
- messages = new ArrayList<Message>();
- while((received = consumer.receive(1000))!=null)
- {
- messages.add(received);
- }
-
- assertEquals("Unexpected number of messages received",10,messages.size());
-
- for(int i = 0 ; i < 10; i++)
- {
- Message msg = messages.get(i);
- assertEquals("Unexpected message number received", MSG_COUNT - 10 + i, msg.getIntProperty("msg"));
- }
-
- }
-
-
-
- public void testConflationWithReleaseAfterNewPublish() throws Exception
- {
- consumerConnection = getConnection();
- consumerSession = consumerConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
-
-
- final Map<String,Object> arguments = new HashMap<String, Object>();
- arguments.put("qpid.last_value_queue_key","key");
- ((AMQSession) producerSession).createQueue(new AMQShortString(QUEUE), false, true, false, arguments);
- queue = new org.apache.qpid.client.AMQQueue("amq.direct",QUEUE);
- ((AMQSession) producerSession).declareAndBind((AMQDestination)queue);
- producer = producerSession.createProducer(queue);
-
- for (int msg = 0; msg < MSG_COUNT/2; msg++)
- {
- producer.send(nextMessage(msg, producerSession));
- }
-
- // HACK to do something synchronous
- ((AMQSession)producerSession).sync();
-
- consumer = consumerSession.createConsumer(queue);
- consumerConnection.start();
- Message received;
- List<Message> messages = new ArrayList<Message>();
- while((received = consumer.receive(1000))!=null)
- {
- messages.add(received);
- }
-
- assertEquals("Unexpected number of messages received",10,messages.size());
-
- for(int i = 0 ; i < 10; i++)
- {
- Message msg = messages.get(i);
- assertEquals("Unexpected message number received", MSG_COUNT/2 - 10 + i, msg.getIntProperty("msg"));
- }
-
- consumer.close();
-
- for (int msg = MSG_COUNT/2; msg < MSG_COUNT; msg++)
- {
- producer.send(nextMessage(msg, producerSession));
- }
-
- // HACK to do something synchronous
- ((AMQSession)producerSession).sync();
-
-
- // this causes the "old" messages to be released
- consumerSession.close();
- consumerConnection.close();
-
-
- consumerConnection = getConnection();
- consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
-
-
- consumer = consumerSession.createConsumer(queue);
- consumerConnection.start();
-
- messages = new ArrayList<Message>();
- while((received = consumer.receive(1000))!=null)
- {
- messages.add(received);
- }
-
- assertEquals("Unexpected number of messages received",10,messages.size());
-
- for(int i = 0 ; i < 10; i++)
- {
- Message msg = messages.get(i);
- assertEquals("Unexpected message number received", MSG_COUNT - 10 + i, msg.getIntProperty("msg"));
- }
-
- }
-
- public void testConflationBrowser() throws Exception
- {
- consumerConnection = getConnection();
- consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
-
- final Map<String,Object> arguments = new HashMap<String, Object>();
- arguments.put("qpid.last_value_queue_key","key");
- ((AMQSession) producerSession).createQueue(new AMQShortString(QUEUE), false, true, false, arguments);
- queue = new org.apache.qpid.client.AMQQueue("amq.direct",QUEUE);
- ((AMQSession) producerSession).declareAndBind((AMQDestination)queue);
- producer = producerSession.createProducer(queue);
-
- for (int msg = 0; msg < MSG_COUNT; msg++)
- {
- producer.send(nextMessage(msg, producerSession));
-
- }
-
- ((AMQSession)producerSession).sync();
-
- AMQBindingURL url = new AMQBindingURL("direct://amq.direct//"+QUEUE+"?browse='true'&durable='true'");
- AMQQueue browseQueue = new AMQQueue(url);
-
- consumer = consumerSession.createConsumer(browseQueue);
- consumerConnection.start();
- Message received;
- List<Message> messages = new ArrayList<Message>();
- while((received = consumer.receive(1000))!=null)
- {
- messages.add(received);
- }
-
- assertEquals("Unexpected number of messages received",10,messages.size());
-
- for(int i = 0 ; i < 10; i++)
- {
- Message msg = messages.get(i);
- assertEquals("Unexpected message number received", MSG_COUNT - 10 + i, msg.getIntProperty("msg"));
- }
-
- messages.clear();
-
- producer.send(nextMessage(MSG_COUNT, producerSession));
-
- ((AMQSession)producerSession).sync();
-
- while((received = consumer.receive(1000))!=null)
- {
- messages.add(received);
- }
- assertEquals("Unexpected number of messages received",1,messages.size());
- assertEquals("Unexpected message number received", MSG_COUNT, messages.get(0).getIntProperty("msg"));
-
-
- producer.close();
- producerSession.close();
- producerConnection.close();
-
-
-
- }
-
-
- public void testConflation2Browsers() throws Exception
- {
- consumerConnection = getConnection();
- consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
-
- final Map<String,Object> arguments = new HashMap<String, Object>();
- arguments.put("qpid.last_value_queue_key","key");
- ((AMQSession) producerSession).createQueue(new AMQShortString(QUEUE), false, true, false, arguments);
- queue = new org.apache.qpid.client.AMQQueue("amq.direct",QUEUE);
- ((AMQSession) producerSession).declareAndBind((AMQDestination)queue);
- producer = producerSession.createProducer(queue);
-
- for (int msg = 0; msg < MSG_COUNT; msg++)
- {
- producer.send(nextMessage(msg, producerSession));
-
- }
-
- ((AMQSession)producerSession).sync();
-
- AMQBindingURL url = new AMQBindingURL("direct://amq.direct//"+QUEUE+"?browse='true'&durable='true'");
- AMQQueue browseQueue = new AMQQueue(url);
-
- consumer = consumerSession.createConsumer(browseQueue);
- MessageConsumer consumer2 = consumerSession.createConsumer(browseQueue);
- consumerConnection.start();
- List<Message> messages = new ArrayList<Message>();
- List<Message> messages2 = new ArrayList<Message>();
- Message received = consumer.receive(1000);
- Message received2 = consumer2.receive(1000);
-
- while(received!=null || received2!=null)
- {
- if(received != null)
- {
- messages.add(received);
- }
- if(received2 != null)
- {
- messages2.add(received2);
- }
-
-
- received = consumer.receive(1000);
- received2 = consumer2.receive(1000);
-
- }
-
- assertEquals("Unexpected number of messages received on first browser",10,messages.size());
- assertEquals("Unexpected number of messages received on second browser",10,messages2.size());
-
- for(int i = 0 ; i < 10; i++)
- {
- Message msg = messages.get(i);
- assertEquals("Unexpected message number received on first browser", MSG_COUNT - 10 + i, msg.getIntProperty("msg"));
- msg = messages2.get(i);
- assertEquals("Unexpected message number received on second browser", MSG_COUNT - 10 + i, msg.getIntProperty("msg"));
- }
-
-
- producer.close();
- producerSession.close();
- producerConnection.close();
-
-
-
- }
-
-
-
- private Message nextMessage(int msg, Session producerSession) throws JMSException
- {
- Message send = producerSession.createTextMessage("Message: " + msg);
-
- send.setStringProperty("key", String.valueOf(msg % 10));
- send.setIntProperty("msg", msg);
-
- return send;
- }
-
-
-}
-
-
diff --git a/java/systests/src/main/java/org/apache/qpid/server/queue/DeepQueueConsumeWithSelector.java b/java/systests/src/main/java/org/apache/qpid/server/queue/DeepQueueConsumeWithSelector.java
deleted file mode 100644
index 4ac0d2c4d6..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/server/queue/DeepQueueConsumeWithSelector.java
+++ /dev/null
@@ -1,159 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.queue;
-
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.apache.qpid.client.AMQConnection;
-
-import javax.jms.Connection;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageListener;
-import javax.jms.Queue;
-import javax.jms.Session;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-/**
- * Test DeapQueueConsumerWithSelector
- * Summary:
- * Prior to M4 the broker had a different queue model which pre-processed the
- * messages on the queue for any connecting subscription that had a selector.
- *
- * If the queue had a lot of data then this may take a long time to process
- * to such an extent that the subscription creation may time out. During this
- * pre-process phase the virtualhost would be come unresposive.
- *
- * Our solution was to allow the timeout to be adjusted QPID-1119, which allowed
- * the subscription to connect but did not address the unresponsiveness.
- *
- * The new queue model introduced in M4 resolved this.
- *
- * This test is to validate that the new queueing model does indeed remove the
- * long pre-processing phase and allow immediate subscription so that there is
- * no unresponsive period.
- *
- * Test Strategy:
- *
- * Add 100k messages to the queue with a numberic header property that will
- * allow later subscribers to use as in a selector.
- *
- * Connect the subscriber and time how long it takes to connect.
- *
- * Finally consume all the messages from the queue to clean up.
- */
-public class DeepQueueConsumeWithSelector extends QpidBrokerTestCase implements MessageListener
-{
-
- private static final int MESSAGE_COUNT = 10000;
- private static final int BATCH_SIZE = MESSAGE_COUNT / 10;
-
- private CountDownLatch _receviedLatch = new CountDownLatch(MESSAGE_COUNT);
-
- protected long SYNC_WRITE_TIMEOUT = 120000L;
-
-
- public void setUp() throws Exception
- {
- //Set the syncWrite timeout to be just larger than the delay on the commitTran.
- setSystemProperty("amqj.default_syncwrite_timeout", String.valueOf(SYNC_WRITE_TIMEOUT));
-
- super.setUp();
- }
-
- public void test() throws Exception
- {
- // Create Connection
- Connection connection = getConnection();
- Session session = ((AMQConnection)connection).createSession(true, Session.SESSION_TRANSACTED, 100000);
-
- Queue queue = (Queue) getInitialContext().lookup("queue");
-
- // Validate that the destination exists
- session.createConsumer(queue).close();
-
- // Send Messages
- sendMessage(session, queue, MESSAGE_COUNT, BATCH_SIZE);
-
- session.close();
-
- session = ((AMQConnection) connection).createSession(false, Session.AUTO_ACKNOWLEDGE);//, 100000);
-
-
- // Setup Selector to perform a few calculations which will slow it down
- String selector = "((\"" + INDEX + "\" % 1) = 0) AND ('" + INDEX + "' IS NOT NULL) AND ('" + INDEX + "' <> -1)";
-
- // Setup timing
- long start = System.nanoTime();
-
- System.err.println("Create Consumer");
- // Connect Consumer
- MessageConsumer consumer = session.createConsumer(queue, selector);
- consumer.setMessageListener(this);
-
- // Validate timing details
- long end = System.nanoTime();
-
- System.err.println("Subscription time took:" + (end - start));
-
- // Consume Messages
- connection.start();
-
-
-
- assertTrue("Messages took to long to be received :"+_receviedLatch.getCount(),
- _receviedLatch.await(SYNC_WRITE_TIMEOUT, TimeUnit.MILLISECONDS ));
-
- }
-
- @Override
- public Message createNextMessage(Session session, int msgCount) throws JMSException
- {
- Message message = super.createNextMessage(session,msgCount);
-
- if ((msgCount % BATCH_SIZE) == 0 )
- {
- System.err.println("Sent:"+msgCount);
- }
-
- return message;
- }
-
- public void onMessage(Message message)
- {
- _receviedLatch.countDown();
- int msgCount = 0;
- try
- {
- msgCount = message.getIntProperty(INDEX);
- }
- catch (JMSException e)
- {
- //ignore
- }
- if ((msgCount % BATCH_SIZE) == 0 )
- {
- System.err.println("Received:"+msgCount);
- }
-
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/server/queue/ModelTest.java b/java/systests/src/main/java/org/apache/qpid/server/queue/ModelTest.java
deleted file mode 100644
index e3fd042560..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/server/queue/ModelTest.java
+++ /dev/null
@@ -1,343 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.queue;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.management.common.mbeans.ManagedBroker;
-import org.apache.qpid.management.common.mbeans.ManagedQueue;
-import org.apache.qpid.test.utils.JMXTestUtils;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-import javax.jms.Connection;
-import javax.jms.JMSException;
-import javax.jms.Session;
-import javax.management.JMException;
-import javax.management.MBeanException;
-import java.io.IOException;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.UndeclaredThrowableException;
-
-/**
- * This Test validates the Queue Model on the broker.
- * Currently it has some basic queue creation / deletion tests.
- * However, it should be expanded to include other tests that relate to the
- * model. i.e.
- *
- * The Create and Delete tests should ensure that the requisite logging is
- * performed.
- *
- * Additions to this suite would be to complete testing of creations, validating
- * fields such as owner/exclusive, autodelete and priority are correctly set.
- *
- * Currently this test uses the JMX interface to validate that the queue has
- * been declared as expected so these tests cannot run against a CPP broker.
- *
- *
- * Tests should ensure that they clean up after themselves.
- * e,g. Durable queue creation test should perform a queue delete.
- */
-public class ModelTest extends QpidBrokerTestCase
-{
-
- private static final String USER = "admin";
- private JMXTestUtils _jmxUtils;
- private static final String VIRTUALHOST_NAME = "test";
-
- @Override
- public void setUp() throws Exception
- {
- // Create a JMX Helper
- _jmxUtils = new JMXTestUtils(this, USER, USER);
- _jmxUtils.setUp();
- super.setUp();
-
- // Open the JMX Connection
- _jmxUtils.open();
- }
-
- @Override
- public void tearDown() throws Exception
- {
- // Close the JMX Connection
- _jmxUtils.close();
- super.tearDown();
- }
-
- /**
- * Test that an exclusive transient queue can be created via AMQP.
- *
- * @throws Exception On unexpected error
- */
- public void testExclusiveQueueCreationTransientViaAMQP() throws Exception
- {
- Connection connection = getConnection();
-
- String queueName = getTestQueueName();
- boolean durable = false;
- boolean autoDelete = false;
- boolean exclusive = true;
-
- createViaAMQPandValidateViaJMX(connection, queueName, durable,
- autoDelete, exclusive);
- }
-
-
-
- /**
- * Test that a transient queue can be created via AMQP.
- *
- * @throws Exception On unexpected error
- */
- public void testQueueCreationTransientViaAMQP() throws Exception
- {
- Connection connection = getConnection();
-
- String queueName = getTestQueueName();
- boolean durable = false;
- boolean autoDelete = false;
- boolean exclusive = true;
-
- createViaAMQPandValidateViaJMX(connection, queueName, durable,
- autoDelete, exclusive);
- }
-
- /**
- * Test that a durable exclusive queue can be created via AMQP.
- *
- * @throws Exception On unexpected error
- */
-
- public void testExclusiveQueueCreationDurableViaAMQP() throws Exception
- {
- Connection connection = getConnection();
-
- String queueName = getTestQueueName();
- boolean durable = true;
- boolean autoDelete = false;
- boolean exclusive = true;
-
- createViaAMQPandValidateViaJMX(connection, queueName, durable,
- autoDelete, exclusive);
-
- // Clean up
- ManagedBroker managedBroker =
- _jmxUtils.getManagedBroker(VIRTUALHOST_NAME);
- managedBroker.deleteQueue(queueName);
- }
-
- /**
- * Test that a durable queue can be created via AMQP.
- *
- * @throws Exception On unexpected error
- */
-
- public void testQueueCreationDurableViaAMQP() throws Exception
- {
- Connection connection = getConnection();
-
- String queueName = getTestQueueName();
- boolean durable = true;
- boolean autoDelete = false;
- boolean exclusive = false;
-
- createViaAMQPandValidateViaJMX(connection, queueName, durable,
- autoDelete, exclusive);
-
- // Clean up
- ManagedBroker managedBroker =
- _jmxUtils.getManagedBroker(VIRTUALHOST_NAME);
- managedBroker.deleteQueue(queueName);
- }
-
-
- /**
- * Test that a transient queue can be created via JMX.
- *
- * @throws IOException if there is a problem via the JMX connection
- * @throws javax.management.JMException if there is a problem with the JMX command
- */
- public void testCreationTransientViaJMX() throws IOException, JMException
- {
- String name = getName();
- String owner = null;
- boolean durable = false;
-
- createViaJMXandValidateViaJMX(name, owner, durable);
- }
-
- /**
- * Test that a durable queue can be created via JMX.
- *
- * @throws IOException if there is a problem via the JMX connection
- * @throws javax.management.JMException if there is a problem with the JMX command
- */
- public void testCreationDurableViaJMX() throws IOException, JMException
- {
- String name = getName();
- String owner = null;
- boolean durable = true;
-
- createViaJMXandValidateViaJMX(name, owner, durable);
-
- // Clean up
- ManagedBroker managedBroker =
- _jmxUtils.getManagedBroker(VIRTUALHOST_NAME);
- managedBroker.deleteQueue(name);
- }
-
- /**
- * Test that a transient queue can be deleted via JMX.
- *
- * @throws IOException if there is a problem via the JMX connection
- * @throws javax.management.JMException if there is a problem with the JMX command
- */
- public void testDeletionTransientViaJMX() throws IOException, JMException
- {
- String name = getName();
-
- _jmxUtils.createQueue(VIRTUALHOST_NAME, name, null, false);
-
- ManagedBroker managedBroker = _jmxUtils.
- getManagedBroker(VIRTUALHOST_NAME);
-
- try
- {
- managedBroker.deleteQueue(name);
- }
- catch (UndeclaredThrowableException e)
- {
- fail(((MBeanException) ((InvocationTargetException)
- e.getUndeclaredThrowable()).getTargetException()).getTargetException().getMessage());
- }
- }
-
- /**
- * Test that a durable queue can be created via JMX.
- *
- * @throws IOException if there is a problem via the JMX connection
- * @throws javax.management.JMException if there is a problem with the JMX command
- */
- public void testDeletionDurableViaJMX() throws IOException, JMException
- {
- String name = getName();
-
- _jmxUtils.createQueue(VIRTUALHOST_NAME, name, null, true);
-
- ManagedBroker managedBroker = _jmxUtils.
- getManagedBroker(VIRTUALHOST_NAME);
-
- try
- {
- managedBroker.deleteQueue(name);
- }
- catch (UndeclaredThrowableException e)
- {
- fail(((MBeanException) ((InvocationTargetException)
- e.getUndeclaredThrowable()).getTargetException()).getTargetException().getMessage());
- }
- }
-
- /*
- * Helper Methods
- */
-
- /**
- * Using the provided JMS Connection create a queue using the AMQP extension
- * with the given properties and then validate it was created correctly via
- * the JMX Connection
- *
- * @param connection Qpid JMS Connection
- * @param queueName String the desired QueueName
- * @param durable boolean if the queue should be durable
- * @param autoDelete boolean if the queue is an autoDelete queue
- * @param exclusive boolean if the queue is exclusive
- *
- * @throws AMQException if there is a problem with the createQueue call
- * @throws JMException if there is a problem with the JMX validatation
- * @throws IOException if there is a problem with the JMX connection
- * @throws JMSException if there is a problem creating the JMS Session
- */
- private void createViaAMQPandValidateViaJMX(Connection connection,
- String queueName,
- boolean durable,
- boolean autoDelete,
- boolean exclusive)
- throws AMQException, JMException, IOException, JMSException
- {
- AMQSession session = (AMQSession) connection.createSession(false,
- Session.AUTO_ACKNOWLEDGE);
-
- session.createQueue(new AMQShortString(queueName),
- autoDelete, durable, exclusive);
-
- validateQueueViaJMX(queueName, exclusive ? connection.getClientID() : null, durable, autoDelete);
- }
-
- /**
- * Use the JMX Helper to create a queue with the given properties and then
- * validate it was created correctly via the JMX Connection
- *
- * @param queueName String the desired QueueName
- * @param owner String the owner value that should be set
- * @param durable boolean if the queue should be durable
- * @param autoDelete boolean if the queue is an autoDelete queue
- *
- * @throws JMException if there is a problem with the JMX validatation
- * @throws IOException if there is a problem with the JMX connection
- */
- private void createViaJMXandValidateViaJMX(String queueName, String owner,
- boolean durable)
- throws JMException, IOException
- {
- _jmxUtils.createQueue(VIRTUALHOST_NAME, queueName, owner, durable);
-
- validateQueueViaJMX(queueName, owner, durable, false);
- }
-
- /**
- * Validate that a queue with the given properties exists on the broker
- *
- * @param queueName String the desired QueueName
- * @param owner String the owner value that should be set
- * @param durable boolean if the queue should be durable
- * @param autoDelete boolean if the queue is an autoDelete queue
- *
- * @throws JMException if there is a problem with the JMX validatation
- * @throws IOException if there is a problem with the JMX connection
- */
- private void validateQueueViaJMX(String queueName, String owner, boolean durable, boolean autoDelete)
- throws JMException, IOException
- {
- ManagedQueue managedQueue = _jmxUtils.
- getManagedObject(ManagedQueue.class,
- _jmxUtils.getQueueObjectName(VIRTUALHOST_NAME,
- queueName));
-
- assertEquals(queueName, managedQueue.getName());
- assertEquals(String.valueOf(owner), managedQueue.getOwner());
- assertEquals(durable, managedQueue.isDurable());
- assertEquals(autoDelete, managedQueue.isAutoDelete());
- }
-
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/server/queue/MultipleTransactedBatchProducerTest.java b/java/systests/src/main/java/org/apache/qpid/server/queue/MultipleTransactedBatchProducerTest.java
deleted file mode 100644
index 460270e188..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/server/queue/MultipleTransactedBatchProducerTest.java
+++ /dev/null
@@ -1,246 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.queue;
-
-import java.util.Random;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-import javax.jms.Connection;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageListener;
-import javax.jms.Session;
-
-import org.apache.log4j.Logger;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-public class MultipleTransactedBatchProducerTest extends QpidBrokerTestCase
-{
- private static final Logger _logger = Logger.getLogger(MultipleTransactedBatchProducerTest.class);
-
- private static final int MESSAGE_COUNT = 1000;
- private static final int BATCH_SIZE = 50;
- private static final int NUM_PRODUCERS = 2;
- private static final int NUM_CONSUMERS = 3;
- private static final Random RANDOM = new Random();
-
- private CountDownLatch _receivedLatch;
- private String _queueName;
-
- private volatile String _failMsg;
-
- public void setUp() throws Exception
- {
- //debug level logging often makes this test pass artificially, turn the level down to info.
- setSystemProperty("amqj.server.logging.level", "INFO");
- _receivedLatch = new CountDownLatch(MESSAGE_COUNT * NUM_PRODUCERS);
- setConfigurationProperty("management.enabled", "true");
- super.setUp();
- _queueName = getTestQueueName();
- _failMsg = null;
- }
-
- /**
- * When there are multiple producers submitting batches of messages to a given
- * queue using transacted sessions, it is highly probable that concurrent
- * enqueue() activity will occur and attempt delivery of their message to the
- * same subscription. In this scenario it is likely that one of the attempts
- * will succeed and the other will result in use of the deliverAsync() method
- * to start a queue Runner and ensure delivery of the message.
- *
- * A defect within the processQueue() method used by the Runner would mean that
- * delivery of these messages may not occur, should the Runner stop before all
- * messages have been processed. Such a defect was discovered and found to be
- * most visible when Selectors are used such that one and only one subscription
- * can/will accept any given message, but multiple subscriptions are present,
- * and one of the earlier subscriptions receives more messages than the others.
- *
- * This test is to validate that the processQueue() method is able to correctly
- * deliver all of the messages present for asynchronous delivery to subscriptions,
- * by utilising multiple batch transacted producers to create the scenario and
- * ensure all messages are received by a consumer.
- */
- public void testMultipleBatchedProducersWithMultipleConsumersUsingSelectors() throws Exception
- {
- String selector1 = ("(\"" + _queueName +"\" % " + NUM_CONSUMERS + ") = 0");
- String selector2 = ("(\"" + _queueName +"\" % " + NUM_CONSUMERS + ") = 1");
- String selector3 = ("(\"" + _queueName +"\" % " + NUM_CONSUMERS + ") = 2");
-
- //create consumers
- Connection conn1 = getConnection();
- conn1.setExceptionListener(new ExceptionHandler("conn1"));
- Session sess1 = conn1.createSession(true, Session.SESSION_TRANSACTED);
- MessageConsumer cons1 = sess1.createConsumer(sess1.createQueue(_queueName), selector1);
- cons1.setMessageListener(new Cons(sess1,"consumer1"));
-
- Connection conn2 = getConnection();
- conn2.setExceptionListener(new ExceptionHandler("conn2"));
- Session sess2 = conn2.createSession(true, Session.SESSION_TRANSACTED);
- MessageConsumer cons2 = sess2.createConsumer(sess2.createQueue(_queueName), selector2);
- cons2.setMessageListener(new Cons(sess2,"consumer2"));
-
- Connection conn3 = getConnection();
- conn3.setExceptionListener(new ExceptionHandler("conn3"));
- Session sess3 = conn3.createSession(true, Session.SESSION_TRANSACTED);
- MessageConsumer cons3 = sess3.createConsumer(sess3.createQueue(_queueName), selector3);
- cons3.setMessageListener(new Cons(sess3,"consumer3"));
-
- conn1.start();
- conn2.start();
- conn3.start();
-
- //create producers
- Connection connA = getConnection();
- connA.setExceptionListener(new ExceptionHandler("connA"));
- Connection connB = getConnection();
- connB.setExceptionListener(new ExceptionHandler("connB"));
- Thread producer1 = new Thread(new ProducerThread(connA, _queueName, "producer1"));
- Thread producer2 = new Thread(new ProducerThread(connB, _queueName, "producer2"));
-
- producer1.start();
- Thread.sleep(10);
- producer2.start();
-
- //await delivery of the messages
- boolean result = _receivedLatch.await(75, TimeUnit.SECONDS);
-
- assertNull("Test failed because: " + String.valueOf(_failMsg), _failMsg);
- assertTrue("Some of the messages were not all recieved in the given timeframe, remaining count was: "+_receivedLatch.getCount(),
- result);
-
- }
-
- @Override
- public Message createNextMessage(Session session, int msgCount) throws JMSException
- {
- Message message = super.createNextMessage(session,msgCount);
-
- //bias at least 50% of the messages to the first consumers selector because
- //the issue presents itself primarily when an earlier subscription completes
- //delivery after the later subscriptions
- int val;
- if (msgCount % 2 == 0)
- {
- val = 0;
- }
- else
- {
- val = RANDOM.nextInt(Integer.MAX_VALUE);
- }
-
- message.setIntProperty(_queueName, val);
-
- return message;
- }
-
- private class Cons implements MessageListener
- {
- private Session _sess;
- private String _desc;
-
- public Cons(Session sess, String desc)
- {
- _sess = sess;
- _desc = desc;
- }
-
- public void onMessage(Message message)
- {
- _receivedLatch.countDown();
- int msgCount = 0;
- int msgID = 0;
- try
- {
- msgCount = message.getIntProperty(INDEX);
- msgID = message.getIntProperty(_queueName);
- }
- catch (JMSException e)
- {
- _logger.error(_desc + " received exception: " + e.getMessage(), e);
- failAsyncTest(e.getMessage());
- }
-
- _logger.info("Consumer received message:"+ msgCount + " with ID: " + msgID);
-
- try
- {
- _sess.commit();
- }
- catch (JMSException e)
- {
- _logger.error(_desc + " received exception: " + e.getMessage(), e);
- failAsyncTest(e.getMessage());
- }
- }
- }
-
- private class ProducerThread implements Runnable
- {
- private Connection _conn;
- private String _dest;
- private String _desc;
-
- public ProducerThread(Connection conn, String dest, String desc)
- {
- _conn = conn;
- _dest = dest;
- _desc = desc;
- }
-
- public void run()
- {
- try
- {
- Session session = _conn.createSession(true, Session.SESSION_TRANSACTED);
- sendMessage(session, session.createQueue(_dest), MESSAGE_COUNT, BATCH_SIZE);
- }
- catch (Exception e)
- {
- _logger.error(_desc + " received exception: " + e.getMessage(), e);
- failAsyncTest(e.getMessage());
- }
- }
- }
-
- private class ExceptionHandler implements javax.jms.ExceptionListener
- {
- private String _desc;
-
- public ExceptionHandler(String description)
- {
- _desc = description;
- }
-
- public void onException(JMSException e)
- {
- _logger.error(_desc + " received exception: " + e.getMessage(), e);
- failAsyncTest(e.getMessage());
- }
- }
-
- private void failAsyncTest(String msg)
- {
- _logger.error("Failing test because: " + msg);
- _failMsg = msg;
- }
-} \ No newline at end of file
diff --git a/java/systests/src/main/java/org/apache/qpid/server/queue/PersistentTestManual.java b/java/systests/src/main/java/org/apache/qpid/server/queue/PersistentTestManual.java
deleted file mode 100644
index c4e744573f..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/server/queue/PersistentTestManual.java
+++ /dev/null
@@ -1,276 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- *
- */
-package org.apache.qpid.server.queue;
-
-import org.apache.log4j.Logger;
-import org.apache.qpid.AMQChannelClosedException;
-import org.apache.qpid.AMQConnectionClosedException;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.url.URLSyntaxException;
-import org.apache.qpid.util.CommandLineParser;
-
-import javax.jms.JMSException;
-import javax.jms.MessageProducer;
-import javax.jms.Queue;
-import javax.jms.Session;
-import javax.jms.TextMessage;
-import java.io.IOException;
-import java.util.Properties;
-
-public class PersistentTestManual
-{
- private static final Logger _logger = Logger.getLogger(PersistentTestManual.class);
-
-
- private static final String QUEUE = "direct://amq.direct//PersistentTest-Queue2?durable='true',exclusive='true'";
-
- protected AMQConnection _connection;
-
- protected Session _session;
-
- protected Queue _queue;
- private Properties properties;
-
- private String _brokerDetails;
- private String _username;
- private String _password;
- private String _virtualpath;
-
- public PersistentTestManual(Properties overrides)
- {
- properties = new Properties(defaults);
- properties.putAll(overrides);
-
- _brokerDetails = properties.getProperty(BROKER_PROPNAME);
- _username = properties.getProperty(USERNAME_PROPNAME);
- _password = properties.getProperty(PASSWORD_PROPNAME);
- _virtualpath = properties.getProperty(VIRTUAL_HOST_PROPNAME);
-
- createConnection();
- }
-
- protected void createConnection()
- {
- try
- {
- _connection = new AMQConnection(_brokerDetails, _username, _password, "PersistentTest", _virtualpath);
-
- _session = _connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- _connection.start();
- }
- catch (Exception e)
- {
- _logger.error("Unable to create test class due to:" + e.getMessage(), e);
- System.exit(0);
- }
- }
-
- public void test() throws AMQException, URLSyntaxException
- {
-
- //Create the Durable Queue
- try
- {
- _session.createConsumer(_session.createQueue(QUEUE)).close();
- }
- catch (JMSException e)
- {
- _logger.error("Unable to create Queue due to:" + e.getMessage(), e);
- System.exit(0);
- }
-
- try
- {
- if (testQueue())
- {
- // close connection
- _connection.close();
- // wait
- System.out.println("Restart Broker Now");
- try
- {
- System.in.read();
- }
- catch (IOException e)
- {
- //
- }
- finally
- {
- System.out.println("Continuing....");
- }
-
- //Test queue is still there.
- AMQConnection connection = new AMQConnection(_brokerDetails, _username, _password, "DifferentClientID", _virtualpath);
-
- AMQSession session = (AMQSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- try
- {
- session.createConsumer(session.createQueue(QUEUE));
- _logger.error("Create consumer succeeded." +
- " This shouldn't be allowed as this means the queue didn't exist when it should");
-
- connection.close();
-
- exit();
- }
- catch (JMSException e)
- {
- try
- {
- connection.close();
- }
- catch (JMSException cce)
- {
- if (cce.getLinkedException() instanceof AMQConnectionClosedException)
- {
- _logger.error("Channel Close Bug still present QPID-432, should see an 'Error closing session'");
- }
- else
- {
- exit(cce);
- }
- }
-
- if (e.getLinkedException() instanceof AMQChannelClosedException)
- {
- _logger.info("AMQChannelClosedException received as expected");
- }
- else
- {
- exit(e);
- }
- }
- }
- }
- catch (JMSException e)
- {
- _logger.error("Unable to test Queue due to:" + e.getMessage(), e);
- System.exit(0);
- }
- }
-
- private void exit(JMSException e)
- {
- _logger.error("JMSException received:" + e.getMessage());
- e.printStackTrace();
- exit();
- }
-
- private void exit()
- {
- try
- {
- _connection.close();
- }
- catch (JMSException e)
- {
- //
- }
- System.exit(0);
- }
-
- private boolean testQueue() throws JMSException
- {
- String TEST_TEXT = "init";
-
- //Create a new session to send producer
- Session session = _connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- Queue q = session.createQueue(QUEUE);
- MessageProducer producer = session.createProducer(q);
-
- producer.send(session.createTextMessage(TEST_TEXT));
-
- //create a new consumer on the original session
- TextMessage m = (TextMessage) _session.createConsumer(q).receive();
-
-
- if ((m != null) && m.getText().equals(TEST_TEXT))
- {
- return true;
- }
- else
- {
- _logger.error("Incorrect values returned from Queue Test:" + m);
- System.exit(0);
- return false;
- }
- }
-
- /** Holds the name of the property to get the test broker url from. */
- public static final String BROKER_PROPNAME = "broker";
-
- /** Holds the default broker url for the test. */
- public static final String BROKER_DEFAULT = "tcp://localhost:5672";
-
- /** Holds the name of the property to get the test broker virtual path. */
- public static final String VIRTUAL_HOST_PROPNAME = "virtualHost";
-
- /** Holds the default virtual path for the test. */
- public static final String VIRTUAL_HOST_DEFAULT = "";
-
- /** Holds the name of the property to get the broker access username from. */
- public static final String USERNAME_PROPNAME = "username";
-
- /** Holds the default broker log on username. */
- public static final String USERNAME_DEFAULT = "guest";
-
- /** Holds the name of the property to get the broker access password from. */
- public static final String PASSWORD_PROPNAME = "password";
-
- /** Holds the default broker log on password. */
- public static final String PASSWORD_DEFAULT = "guest";
-
- /** Holds the default configuration properties. */
- public static Properties defaults = new Properties();
-
- static
- {
- defaults.setProperty(BROKER_PROPNAME, BROKER_DEFAULT);
- defaults.setProperty(USERNAME_PROPNAME, USERNAME_DEFAULT);
- defaults.setProperty(PASSWORD_PROPNAME, PASSWORD_DEFAULT);
- defaults.setProperty(VIRTUAL_HOST_PROPNAME, VIRTUAL_HOST_DEFAULT);
- }
-
- public static void main(String[] args)
- {
- PersistentTestManual test;
-
- Properties options =
- CommandLineParser.processCommandLine(args, new CommandLineParser(new String[][]{}), System.getProperties());
-
- test = new PersistentTestManual(options);
- try
- {
- test.test();
- System.out.println("Test was successfull.");
- }
- catch (Exception e)
- {
- _logger.error("Unable to test due to:" + e.getMessage(), e);
- }
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/server/queue/PriorityTest.java b/java/systests/src/main/java/org/apache/qpid/server/queue/PriorityTest.java
deleted file mode 100644
index 6203e8a194..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/server/queue/PriorityTest.java
+++ /dev/null
@@ -1,212 +0,0 @@
-/*
-*
-* Licensed to the Apache Software Foundation (ASF) under one
-* or more contributor license agreements. See the NOTICE file
-* distributed with this work for additional information
-* regarding copyright ownership. The ASF licenses this file
-* to you under the Apache License, Version 2.0 (the
-* "License"); you may not use this file except in compliance
-* with the License. You may obtain a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing,
-* software distributed under the License is distributed on an
-* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-* KIND, either express or implied. See the License for the
-* specific language governing permissions and limitations
-* under the License.
-*
-*/
-package org.apache.qpid.server.queue;
-
-import junit.framework.TestCase;
-import junit.framework.Assert;
-import org.apache.log4j.Logger;
-import org.apache.qpid.client.transport.TransportConnection;
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.client.AMQDestination;
-import org.apache.qpid.jndi.PropertiesFileInitialContextFactory;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.apache.qpid.url.URLSyntaxException;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.FieldTable;
-
-import javax.jms.*;
-import javax.naming.NamingException;
-import javax.naming.Context;
-import javax.naming.spi.InitialContextFactory;
-import java.util.Hashtable;
-import java.util.HashMap;
-import java.util.Map;
-
-public class PriorityTest extends QpidBrokerTestCase
-{
- private static final int TIMEOUT = 1500;
-
-
- private static final Logger _logger = Logger.getLogger(PriorityTest.class);
-
- protected final String QUEUE = "PriorityQueue";
-
- private static final int MSG_COUNT = 50;
-
- private Connection producerConnection;
- private MessageProducer producer;
- private Session producerSession;
- private Queue queue;
- private Connection consumerConnection;
- private Session consumerSession;
-
-
- private MessageConsumer consumer;
-
- protected void setUp() throws Exception
- {
- super.setUp();
-
- producerConnection = getConnection();
- producerSession = producerConnection.createSession(true, Session.AUTO_ACKNOWLEDGE);
-
- producerConnection.start();
-
- consumerConnection = getConnection();
- consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- }
-
- protected void tearDown() throws Exception
- {
- producerConnection.close();
- consumerConnection.close();
- super.tearDown();
- }
-
- public void testPriority() throws JMSException, NamingException, AMQException
- {
- final Map<String,Object> arguments = new HashMap<String, Object>();
- arguments.put("x-qpid-priorities",10);
- ((AMQSession) producerSession).createQueue(new AMQShortString(QUEUE), true, false, false, arguments);
- queue = (Queue) producerSession.createQueue("direct://amq.direct/"+QUEUE+"/"+QUEUE+"?durable='false'&autodelete='true'");
-
- ((AMQSession) producerSession).declareAndBind((AMQDestination)queue);
- producer = producerSession.createProducer(queue);
-
- for (int msg = 0; msg < MSG_COUNT; msg++)
- {
- producer.setPriority(msg % 10);
- producer.send(nextMessage(msg, false, producerSession, producer));
- }
- producerSession.commit();
- producer.close();
- producerSession.close();
- producerConnection.close();
-
- consumer = consumerSession.createConsumer(queue);
- consumerConnection.start();
- Message received;
- int receivedCount = 0;
- Message previous = null;
- int messageCount = 0;
- while((received = consumer.receive(1000))!=null)
- {
- messageCount++;
- if(previous != null)
- {
- assertTrue("Messages arrived in unexpected order " + messageCount + " " + previous.getIntProperty("msg") + " " + received.getIntProperty("msg") + " " + previous.getJMSPriority() + " " + received.getJMSPriority(), (previous.getJMSPriority() > received.getJMSPriority()) || ((previous.getJMSPriority() == received.getJMSPriority()) && previous.getIntProperty("msg") < received.getIntProperty("msg")) );
- }
-
- previous = received;
- receivedCount++;
- }
-
- assertEquals("Incorrect number of message received", 50, receivedCount);
- }
-
- public void testOddOrdering() throws AMQException, JMSException
- {
- final Map<String,Object> arguments = new HashMap<String, Object>();
- arguments.put("x-qpid-priorities",3);
- ((AMQSession) producerSession).createQueue(new AMQShortString(QUEUE), true, false, false, arguments);
- queue = producerSession.createQueue("direct://amq.direct/"+QUEUE+"/"+QUEUE+"?durable='false'&autodelete='true'");
-
- ((AMQSession) producerSession).declareAndBind((AMQDestination)queue);
- producer = producerSession.createProducer(queue);
-
- // In order ABC
- producer.setPriority(9);
- producer.send(nextMessage(1, false, producerSession, producer));
- producer.setPriority(4);
- producer.send(nextMessage(2, false, producerSession, producer));
- producer.setPriority(1);
- producer.send(nextMessage(3, false, producerSession, producer));
-
- // Out of order BAC
- producer.setPriority(4);
- producer.send(nextMessage(4, false, producerSession, producer));
- producer.setPriority(9);
- producer.send(nextMessage(5, false, producerSession, producer));
- producer.setPriority(1);
- producer.send(nextMessage(6, false, producerSession, producer));
-
- // Out of order BCA
- producer.setPriority(4);
- producer.send(nextMessage(7, false, producerSession, producer));
- producer.setPriority(1);
- producer.send(nextMessage(8, false, producerSession, producer));
- producer.setPriority(9);
- producer.send(nextMessage(9, false, producerSession, producer));
-
- // Reverse order CBA
- producer.setPriority(1);
- producer.send(nextMessage(10, false, producerSession, producer));
- producer.setPriority(4);
- producer.send(nextMessage(11, false, producerSession, producer));
- producer.setPriority(9);
- producer.send(nextMessage(12, false, producerSession, producer));
- producerSession.commit();
-
- consumer = consumerSession.createConsumer(queue);
- consumerConnection.start();
-
- Message msg = consumer.receive(TIMEOUT);
- assertEquals(1, msg.getIntProperty("msg"));
- msg = consumer.receive(TIMEOUT);
- assertEquals(5, msg.getIntProperty("msg"));
- msg = consumer.receive(TIMEOUT);
- assertEquals(9, msg.getIntProperty("msg"));
- msg = consumer.receive(TIMEOUT);
- assertEquals(12, msg.getIntProperty("msg"));
-
- msg = consumer.receive(TIMEOUT);
- assertEquals(2, msg.getIntProperty("msg"));
- msg = consumer.receive(TIMEOUT);
- assertEquals(4, msg.getIntProperty("msg"));
- msg = consumer.receive(TIMEOUT);
- assertEquals(7, msg.getIntProperty("msg"));
- msg = consumer.receive(TIMEOUT);
- assertEquals(11, msg.getIntProperty("msg"));
-
- msg = consumer.receive(TIMEOUT);
- assertEquals(3, msg.getIntProperty("msg"));
- msg = consumer.receive(TIMEOUT);
- assertEquals(6, msg.getIntProperty("msg"));
- msg = consumer.receive(TIMEOUT);
- assertEquals(8, msg.getIntProperty("msg"));
- msg = consumer.receive(TIMEOUT);
- assertEquals(10, msg.getIntProperty("msg"));
- }
-
- private Message nextMessage(int msg, boolean first, Session producerSession, MessageProducer producer) throws JMSException
- {
- Message send = producerSession.createTextMessage("Message: " + msg);
- send.setIntProperty("msg", msg);
-
- return send;
- }
-
-
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/server/queue/ProducerFlowControlTest.java b/java/systests/src/main/java/org/apache/qpid/server/queue/ProducerFlowControlTest.java
deleted file mode 100644
index f78b327209..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/server/queue/ProducerFlowControlTest.java
+++ /dev/null
@@ -1,496 +0,0 @@
-/*
-*
-* Licensed to the Apache Software Foundation (ASF) under one
-* or more contributor license agreements. See the NOTICE file
-* distributed with this work for additional information
-* regarding copyright ownership. The ASF licenses this file
-* to you under the Apache License, Version 2.0 (the
-* "License"); you may not use this file except in compliance
-* with the License. You may obtain a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing,
-* software distributed under the License is distributed on an
-* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-* KIND, either express or implied. See the License for the
-* specific language governing permissions and limitations
-* under the License.
-*
-*/
-package org.apache.qpid.server.queue;
-
-import org.apache.log4j.Logger;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.client.AMQDestination;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.management.common.mbeans.ManagedQueue;
-import org.apache.qpid.server.logging.AbstractTestLogging;
-import org.apache.qpid.test.utils.JMXTestUtils;
-import org.apache.qpid.framing.AMQShortString;
-
-import javax.jms.*;
-import javax.naming.NamingException;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.List;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.io.IOException;
-
-public class ProducerFlowControlTest extends AbstractTestLogging
-{
- private static final int TIMEOUT = 10000;
-
- private static final Logger _logger = Logger.getLogger(ProducerFlowControlTest.class);
-
- private Connection producerConnection;
- private MessageProducer producer;
- private Session producerSession;
- private Queue queue;
- private Connection consumerConnection;
- private Session consumerSession;
-
- private MessageConsumer consumer;
- private final AtomicInteger _sentMessages = new AtomicInteger();
-
- private JMXTestUtils _jmxUtils;
- private boolean _jmxUtilConnected;
- private static final String USER = "admin";
-
- public void setUp() throws Exception
- {
- _jmxUtils = new JMXTestUtils(this, USER , USER);
- _jmxUtils.setUp();
- _jmxUtilConnected=false;
- super.setUp();
-
- _monitor.reset();
-
- producerConnection = getConnection();
- producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- producerConnection.start();
-
- consumerConnection = getConnection();
- consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- }
-
- public void tearDown() throws Exception
- {
- if(_jmxUtilConnected)
- {
- try
- {
- _jmxUtils.close();
- }
- catch (IOException e)
- {
- e.printStackTrace();
- }
- }
- producerConnection.close();
- consumerConnection.close();
- super.tearDown();
- }
-
- public void testCapacityExceededCausesBlock()
- throws JMSException, NamingException, AMQException, InterruptedException
- {
- String queueName = getTestQueueName();
-
- final Map<String,Object> arguments = new HashMap<String, Object>();
- arguments.put("x-qpid-capacity",1000);
- arguments.put("x-qpid-flow-resume-capacity",800);
- ((AMQSession) producerSession).createQueue(new AMQShortString(queueName), true, false, false, arguments);
- queue = producerSession.createQueue("direct://amq.direct/"+queueName+"/"+queueName+"?durable='false'&autodelete='true'");
- ((AMQSession) producerSession).declareAndBind((AMQDestination)queue);
- producer = producerSession.createProducer(queue);
-
- _sentMessages.set(0);
-
-
- // try to send 5 messages (should block after 4)
- sendMessagesAsync(producer, producerSession, 5, 50L);
-
- Thread.sleep(5000);
-
- assertEquals("Incorrect number of message sent before blocking", 4, _sentMessages.get());
-
- consumer = consumerSession.createConsumer(queue);
- consumerConnection.start();
-
-
- consumer.receive();
-
- Thread.sleep(1000);
-
- assertEquals("Message incorrectly sent after one message received", 4, _sentMessages.get());
-
-
- consumer.receive();
-
- Thread.sleep(1000);
-
- assertEquals("Message not sent after two messages received", 5, _sentMessages.get());
-
- }
-
- public void testBrokerLogMessages()
- throws JMSException, NamingException, AMQException, InterruptedException, IOException
- {
- String queueName = getTestQueueName();
-
- final Map<String,Object> arguments = new HashMap<String, Object>();
- arguments.put("x-qpid-capacity",1000);
- arguments.put("x-qpid-flow-resume-capacity",800);
- ((AMQSession) producerSession).createQueue(new AMQShortString(queueName), true, false, false, arguments);
- queue = producerSession.createQueue("direct://amq.direct/"+queueName+"/"+queueName+"?durable='false'&autodelete='true'");
- ((AMQSession) producerSession).declareAndBind((AMQDestination)queue);
- producer = producerSession.createProducer(queue);
-
- _sentMessages.set(0);
-
-
- // try to send 5 messages (should block after 4)
- sendMessagesAsync(producer, producerSession, 5, 50L);
-
- Thread.sleep(5000);
- List<String> results = waitAndFindMatches("QUE-1003");
-
- assertEquals("Did not find correct number of QUE-1003 queue overfull messages", 1, results.size());
-
- consumer = consumerSession.createConsumer(queue);
- consumerConnection.start();
-
-
- while(consumer.receive(1000) != null);
-
- results = waitAndFindMatches("QUE-1004");
-
- assertEquals("Did not find correct number of UNDERFULL queue underfull messages", 1, results.size());
-
-
-
- }
-
-
- public void testClientLogMessages()
- throws JMSException, NamingException, AMQException, InterruptedException, IOException
- {
- String queueName = getTestQueueName();
-
- setTestClientSystemProperty("qpid.flow_control_wait_failure","3000");
- setTestClientSystemProperty("qpid.flow_control_wait_notify_period","1000");
-
- Session session = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
-
- final Map<String,Object> arguments = new HashMap<String, Object>();
- arguments.put("x-qpid-capacity",1000);
- arguments.put("x-qpid-flow-resume-capacity",800);
- ((AMQSession) session).createQueue(new AMQShortString(queueName), true, false, false, arguments);
- queue = producerSession.createQueue("direct://amq.direct/"+queueName+"/"+queueName+"?durable='false'&autodelete='true'");
- ((AMQSession) session).declareAndBind((AMQDestination)queue);
- producer = session.createProducer(queue);
-
- _sentMessages.set(0);
-
-
- // try to send 5 messages (should block after 4)
- MessageSender sender = sendMessagesAsync(producer, producerSession, 5, 50L);
-
- Thread.sleep(TIMEOUT);
- List<String> results = waitAndFindMatches("Message send delayed by", TIMEOUT);
- assertTrue("No delay messages logged by client",results.size()!=0);
- results = findMatches("Message send failed due to timeout waiting on broker enforced flow control");
- assertEquals("Incorrect number of send failure messages logged by client",1,results.size());
-
-
-
- }
-
-
- public void testFlowControlOnCapacityResumeEqual()
- throws JMSException, NamingException, AMQException, InterruptedException
- {
- String queueName = getTestQueueName();
-
- final Map<String,Object> arguments = new HashMap<String, Object>();
- arguments.put("x-qpid-capacity",1000);
- arguments.put("x-qpid-flow-resume-capacity",1000);
- ((AMQSession) producerSession).createQueue(new AMQShortString(queueName), true, false, false, arguments);
- queue = producerSession.createQueue("direct://amq.direct/"+queueName+"/"+queueName+"?durable='false'&autodelete='true'");
- ((AMQSession) producerSession).declareAndBind((AMQDestination)queue);
- producer = producerSession.createProducer(queue);
-
- _sentMessages.set(0);
-
- // try to send 5 messages (should block after 4)
- sendMessagesAsync(producer, producerSession, 5, 50L);
-
- Thread.sleep(5000);
-
- assertEquals("Incorrect number of message sent before blocking", 4, _sentMessages.get());
-
- consumer = consumerSession.createConsumer(queue);
- consumerConnection.start();
-
-
- consumer.receive();
-
- Thread.sleep(1000);
-
- assertEquals("Message incorrectly sent after one message received", 5, _sentMessages.get());
-
-
- }
-
-
- public void testFlowControlSoak()
- throws Exception, NamingException, AMQException, InterruptedException
- {
- String queueName = getTestQueueName();
-
- _sentMessages.set(0);
- final int numProducers = 10;
- final int numMessages = 100;
-
- final Map<String,Object> arguments = new HashMap<String, Object>();
- arguments.put("x-qpid-capacity",6000);
- arguments.put("x-qpid-flow-resume-capacity",3000);
-
- ((AMQSession) consumerSession).createQueue(new AMQShortString(queueName), false, false, false, arguments);
-
- queue = producerSession.createQueue("direct://amq.direct/"+queueName+"/"+queueName+"?durable='false'&autodelete='false'");
- ((AMQSession) consumerSession).declareAndBind((AMQDestination)queue);
- consumerConnection.start();
-
- Connection[] producers = new Connection[numProducers];
- for(int i = 0 ; i < numProducers; i ++)
- {
-
- producers[i] = getConnection();
- producers[i].start();
- Session session = producers[i].createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- MessageProducer myproducer = session.createProducer(queue);
- MessageSender sender = sendMessagesAsync(myproducer, session, numMessages, 50L);
- }
-
- consumer = consumerSession.createConsumer(queue);
- consumerConnection.start();
-
- for(int j = 0; j < numProducers * numMessages; j++)
- {
-
- Message msg = consumer.receive(5000);
- Thread.sleep(50L);
- assertNotNull("Message not received("+j+"), sent: "+_sentMessages.get(), msg);
-
- }
-
-
-
- Message msg = consumer.receive(500);
- assertNull("extra message received", msg);
-
-
- for(int i = 0; i < numProducers; i++)
- {
- producers[i].close();
- }
-
- }
-
-
-
- public void testSendTimeout()
- throws JMSException, NamingException, AMQException, InterruptedException
- {
- String queueName = getTestQueueName();
-
- setTestClientSystemProperty("qpid.flow_control_wait_failure","3000");
- Session session = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
-
- final Map<String,Object> arguments = new HashMap<String, Object>();
- arguments.put("x-qpid-capacity",1000);
- arguments.put("x-qpid-flow-resume-capacity",800);
- ((AMQSession) session).createQueue(new AMQShortString(queueName), true, false, false, arguments);
- queue = producerSession.createQueue("direct://amq.direct/"+queueName+"/"+queueName+"?durable='false'&autodelete='true'");
- ((AMQSession) session).declareAndBind((AMQDestination)queue);
- producer = session.createProducer(queue);
-
- _sentMessages.set(0);
-
-
- // try to send 5 messages (should block after 4)
- MessageSender sender = sendMessagesAsync(producer, producerSession, 5, 50L);
-
- Thread.sleep(10000);
-
- Exception e = sender.getException();
-
- assertNotNull("No timeout exception on sending", e);
-
- }
-
-
- public void testFlowControlAttributeModificationViaJMX()
- throws JMSException, NamingException, AMQException, InterruptedException, Exception
- {
- _jmxUtils.open();
- _jmxUtilConnected = true;
-
- String queueName = getTestQueueName();
-
- //create queue
- final Map<String,Object> arguments = new HashMap<String, Object>();
- arguments.put("x-qpid-capacity",0);
- arguments.put("x-qpid-flow-resume-capacity",0);
- ((AMQSession) producerSession).createQueue(new AMQShortString(queueName), true, false, false, arguments);
-
- queue = producerSession.createQueue("direct://amq.direct/"+queueName+"/"+queueName+"?durable='false'&autodelete='true'");
-
- ((AMQSession) producerSession).declareAndBind((AMQDestination)queue);
- producer = producerSession.createProducer(queue);
-
- Thread.sleep(1000);
-
- //Create a JMX MBean proxy for the queue
- ManagedQueue queueMBean = _jmxUtils.getManagedObject(ManagedQueue.class, _jmxUtils.getQueueObjectName("test", queueName));
- assertNotNull(queueMBean);
-
- //check current attribute values are 0 as expected
- assertTrue("Capacity was not the expected value", queueMBean.getCapacity() == 0L);
- assertTrue("FlowResumeCapacity was not the expected value", queueMBean.getFlowResumeCapacity() == 0L);
-
- //set new values that will cause flow control to be active, and the queue to become overfull after 1 message is sent
- queueMBean.setCapacity(250L);
- queueMBean.setFlowResumeCapacity(250L);
- assertTrue("Capacity was not the expected value", queueMBean.getCapacity() == 250L);
- assertTrue("FlowResumeCapacity was not the expected value", queueMBean.getFlowResumeCapacity() == 250L);
- assertFalse("Queue should not be overfull", queueMBean.isFlowOverfull());
-
- // try to send 2 messages (should block after 1)
- _sentMessages.set(0);
- sendMessagesAsync(producer, producerSession, 2, 50L);
-
- Thread.sleep(2000);
-
- //check only 1 message was sent, and queue is overfull
- assertEquals("Incorrect number of message sent before blocking", 1, _sentMessages.get());
- assertTrue("Queue should be overfull", queueMBean.isFlowOverfull());
-
- //raise the attribute values, causing the queue to become underfull and allow the second message to be sent.
- queueMBean.setCapacity(300L);
- queueMBean.setFlowResumeCapacity(300L);
-
- Thread.sleep(2000);
-
- //check second message was sent, and caused the queue to become overfull again
- assertEquals("Second message was not sent after lifting FlowResumeCapacity", 2, _sentMessages.get());
- assertTrue("Queue should be overfull", queueMBean.isFlowOverfull());
-
- //raise capacity above queue depth, check queue remains overfull as FlowResumeCapacity still exceeded
- queueMBean.setCapacity(700L);
- assertTrue("Queue should be overfull", queueMBean.isFlowOverfull());
-
- //receive a message, check queue becomes underfull
-
- consumer = consumerSession.createConsumer(queue);
- consumerConnection.start();
-
- consumer.receive();
-
- //perform a synchronous op on the connection
- ((AMQSession) consumerSession).sync();
-
- assertFalse("Queue should not be overfull", queueMBean.isFlowOverfull());
-
- consumer.receive();
- }
-
- private MessageSender sendMessagesAsync(final MessageProducer producer,
- final Session producerSession,
- final int numMessages,
- long sleepPeriod)
- {
- MessageSender sender = new MessageSender(producer, producerSession, numMessages,sleepPeriod);
- new Thread(sender).start();
- return sender;
- }
-
- private void sendMessages(MessageProducer producer, Session producerSession, int numMessages, long sleepPeriod)
- throws JMSException
- {
-
- for (int msg = 0; msg < numMessages; msg++)
- {
- producer.send(nextMessage(msg, producerSession));
- _sentMessages.incrementAndGet();
-
-
- try
- {
- ((AMQSession)producerSession).sync();
- }
- catch (AMQException e)
- {
- e.printStackTrace();
- throw new RuntimeException(e);
- }
- }
- }
-
- private static final byte[] BYTE_300 = new byte[300];
-
-
- private Message nextMessage(int msg, Session producerSession) throws JMSException
- {
- BytesMessage send = producerSession.createBytesMessage();
- send.writeBytes(BYTE_300);
- send.setIntProperty("msg", msg);
-
- return send;
- }
-
-
- private class MessageSender implements Runnable
- {
- private final MessageProducer _producer;
- private final Session _producerSession;
- private final int _numMessages;
-
-
-
- private JMSException _exception;
- private long _sleepPeriod;
-
- public MessageSender(MessageProducer producer, Session producerSession, int numMessages, long sleepPeriod)
- {
- _producer = producer;
- _producerSession = producerSession;
- _numMessages = numMessages;
- _sleepPeriod = sleepPeriod;
- }
-
- public void run()
- {
- try
- {
- sendMessages(_producer, _producerSession, _numMessages, _sleepPeriod);
- }
- catch (JMSException e)
- {
- _exception = e;
- }
- }
-
- public JMSException getException()
- {
- return _exception;
- }
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/server/queue/QueueDepthWithSelectorTest.java b/java/systests/src/main/java/org/apache/qpid/server/queue/QueueDepthWithSelectorTest.java
deleted file mode 100644
index 74f50e8659..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/server/queue/QueueDepthWithSelectorTest.java
+++ /dev/null
@@ -1,176 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.qpid.server.queue;
-
-import javax.jms.Connection;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-import javax.jms.Queue;
-import javax.jms.Session;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.AMQDestination;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-/**
- * Test Case to ensure that messages are correctly returned.
- * This includes checking:
- * - The message is returned.
- * - The broker doesn't leak memory.
- * - The broker's state is correct after test.
- */
-public class QueueDepthWithSelectorTest extends QpidBrokerTestCase
-{
- protected final String VHOST = "test";
- protected final String QUEUE = this.getClass().getName();
-
- protected Connection _clientConnection;
- protected Connection _producerConnection;
- private Session _clientSession;
- protected Session _producerSession;
- protected MessageProducer _producer;
- private MessageConsumer _consumer;
-
- protected static int MSG_COUNT = 50;
-
- protected Message[] _messages = new Message[MSG_COUNT];
-
- protected Queue _queue;
-
- @Override
- public void setUp() throws Exception
- {
- super.setUp();
-
- _messages = new Message[MSG_COUNT];
- _queue = getTestQueue();
-
- //Create Producer
- _producerConnection = getConnection();
- _producerConnection.start();
- _producerSession = _producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- _producer = _producerSession.createProducer(_queue);
-
- // Create consumer
- _clientConnection = getConnection();
- _clientConnection.start();
- _clientSession = _clientConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- _consumer = _clientSession.createConsumer(_queue, "key = 23");
- }
-
- public void test() throws Exception
- {
- //Send messages
- _logger.info("Starting to send messages");
- for (int msg = 0; msg < MSG_COUNT; msg++)
- {
- _producer.send(nextMessage(msg));
- }
- _logger.info("Closing connection");
- //Close the connection.. .giving the broker time to clean up its state.
- _producerConnection.close();
-
- //Verify we get all the messages.
- _logger.info("Verifying messages");
- verifyAllMessagesRecevied(50);
- verifyBrokerState(0);
-
- //Close the connection.. .giving the broker time to clean up its state.
- _clientConnection.close();
-
- //Verify Broker state
- _logger.info("Verifying broker state");
- verifyBrokerState(0);
- }
-
- protected void verifyBrokerState(int expectedDepth)
- {
- try
- {
- Connection connection = getConnection();
- Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- Thread.sleep(2000);
- long queueDepth = ((AMQSession) session).getQueueDepth((AMQDestination) _queue);
- assertEquals("Session reports Queue depth not as expected", expectedDepth, queueDepth);
-
- connection.close();
- }
- catch (InterruptedException e)
- {
- fail(e.getMessage());
- }
- catch (AMQException e)
- {
- fail(e.getMessage());
- }
- catch (Exception e)
- {
- fail(e.getMessage());
- }
- }
-
- protected void verifyAllMessagesRecevied(int expectedDepth) throws Exception
- {
- boolean[] msgIdRecevied = new boolean[MSG_COUNT];
-
- for (int i = 0; i < expectedDepth; i++)
- {
- _messages[i] = _consumer.receive(1000);
- assertNotNull("should have received a message but didn't", _messages[i]);
- }
-
- //Check received messages
- int msgId = 0;
- for (Message msg : _messages)
- {
- assertNotNull("Message should not be null", msg);
- assertEquals("msgId was wrong", msgId, msg.getIntProperty("ID"));
- assertFalse("Already received msg id " + msgId, msgIdRecevied[msgId]);
- msgIdRecevied[msgId] = true;
- msgId++;
- }
-
- //Check all received
- for (msgId = 0; msgId < expectedDepth; msgId++)
- {
- assertTrue("Message " + msgId + " not received.", msgIdRecevied[msgId]);
- }
- }
-
- /**
- * Get the next message putting the given count into the intProperties as ID.
- *
- * @param msgNo the message count to store as ID.
- * @throws JMSException
- */
- protected Message nextMessage(int msgNo) throws JMSException
- {
- Message send = _producerSession.createTextMessage("MessageReturnTest");
- send.setIntProperty("ID", msgNo);
- send.setIntProperty("key", 23);
- return send;
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/server/queue/SubscriptionTestHelper.java b/java/systests/src/main/java/org/apache/qpid/server/queue/SubscriptionTestHelper.java
deleted file mode 100644
index 1152797dbf..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/server/queue/SubscriptionTestHelper.java
+++ /dev/null
@@ -1,294 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.queue;
-
-import org.apache.qpid.server.AMQChannel;
-import org.apache.qpid.server.logging.LogActor;
-import org.apache.qpid.server.subscription.Subscription;
-import org.apache.qpid.framing.AMQShortString;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Queue;
-
-public class SubscriptionTestHelper implements Subscription
-{
- private final List<QueueEntry> messages;
- private final Object key;
- private boolean isSuspended;
- private AMQQueue.Context _queueContext;
-
- public SubscriptionTestHelper(Object key)
- {
- this(key, new ArrayList<QueueEntry>());
- }
-
- public SubscriptionTestHelper(final Object key, final boolean isSuspended)
- {
- this(key);
- setSuspended(isSuspended);
- }
-
- SubscriptionTestHelper(Object key, List<QueueEntry> messages)
- {
- this.key = key;
- this.messages = messages;
- }
-
- List<QueueEntry> getMessages()
- {
- return messages;
- }
-
- public void setQueue(AMQQueue queue, boolean exclusive)
- {
-
- }
-
- public void setNoLocal(boolean noLocal)
- {
-
- }
-
- public void send(QueueEntry msg)
- {
- messages.add(msg);
- }
-
- public void setSuspended(boolean suspended)
- {
- isSuspended = suspended;
- }
-
- public boolean isSuspended()
- {
- return isSuspended;
- }
-
- public boolean wouldSuspend(QueueEntry msg)
- {
- return isSuspended;
- }
-
- public void addToResendQueue(QueueEntry msg)
- {
- //no-op
- }
-
- public void getSendLock()
- {
- return;
- }
-
- public void releaseSendLock()
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void resend(final QueueEntry entry)
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void onDequeue(final QueueEntry queueEntry)
- {
-
- }
-
- public void restoreCredit(QueueEntry queueEntry)
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void setStateListener(final StateListener listener)
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public State getState()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public AMQQueue.Context getQueueContext()
- {
- return _queueContext;
- }
-
- public void setQueueContext(AMQQueue.Context queueContext)
- {
- _queueContext = queueContext;
- }
-
- public boolean setLastSeenEntry(QueueEntry expected, QueueEntry newValue)
- {
- return false; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public AMQChannel getChannel()
- {
- return null;
- }
-
- public void start()
- {
- //no-op
- }
-
- public AMQShortString getConsumerTag()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public long getSubscriptionID()
- {
- return 0; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean isActive()
- {
- return false; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void confirmAutoClose()
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void set(String key, Object value)
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public Object get(String key)
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public LogActor getLogActor()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean isTransient()
- {
- return false;
- }
-
- public AMQQueue getQueue()
- {
- return null;
- }
-
- public QueueEntry.SubscriptionAcquiredState getOwningState()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public QueueEntry.SubscriptionAssignedState getAssignedState()
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void queueDeleted(AMQQueue queue)
- {
- }
-
- public boolean filtersMessages()
- {
- return false;
- }
-
- public boolean hasInterest(QueueEntry msg)
- {
- return true;
- }
-
- public boolean isAutoClose()
- {
- return false;
- }
-
- public Queue<QueueEntry> getPreDeliveryQueue()
- {
- return null;
- }
-
- public Queue<QueueEntry> getResendQueue()
- {
- return null;
- }
-
- public Queue<QueueEntry> getNextQueue(Queue<QueueEntry> messages)
- {
- return messages;
- }
-
- public void enqueueForPreDelivery(QueueEntry msg, boolean deliverFirst)
- {
- //no-op
- }
-
- public void close()
- {
- //no-op
- }
-
- public boolean isClosed()
- {
- return false;
- }
-
- public boolean acquires()
- {
- return true;
- }
-
- public boolean seesRequeues()
- {
- return true;
- }
-
- public boolean isBrowser()
- {
- return false;
- }
-
- public int hashCode()
- {
- return key.hashCode();
- }
-
- public boolean equals(Object o)
- {
- return o instanceof SubscriptionTestHelper && ((SubscriptionTestHelper) o).key.equals(key);
- }
-
- public String toString()
- {
- return key.toString();
- }
-
- public boolean isSessionTransactional()
- {
- return false;
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/server/queue/TimeToLiveTest.java b/java/systests/src/main/java/org/apache/qpid/server/queue/TimeToLiveTest.java
deleted file mode 100644
index abb0781536..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/server/queue/TimeToLiveTest.java
+++ /dev/null
@@ -1,370 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.qpid.server.queue;
-
-import java.util.concurrent.locks.Condition;
-import java.util.concurrent.locks.ReentrantLock;
-
-import javax.jms.Connection;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-import javax.jms.Queue;
-import javax.jms.Session;
-import javax.jms.TopicSubscriber;
-
-import junit.framework.Assert;
-
-import org.apache.log4j.Logger;
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQDestination;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.client.AMQTopic;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-public class TimeToLiveTest extends QpidBrokerTestCase
-{
- private static final Logger _logger = Logger.getLogger(TimeToLiveTest.class);
-
- protected final String QUEUE = "TimeToLiveQueue";
-
- private final long TIME_TO_LIVE = 100L;
-
- private static final int MSG_COUNT = 50;
- private static final long SERVER_TTL_TIMEOUT = 60000L;
-
- public void testPassiveTTL() throws Exception
- {
- //Create Client 1
- Connection clientConnection = getConnection();
-
- Session clientSession = clientConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- Queue queue = clientSession.createQueue(QUEUE);
-
- // Create then close the consumer so the queue is actually created
- // Closing it then reopening it ensures that the consumer shouldn't get messages
- // which should have expired and allows a shorter sleep period. See QPID-1418
-
- MessageConsumer consumer = clientSession.createConsumer(queue);
- consumer.close();
-
- //Create Producer
- Connection producerConnection = getConnection();
-
- producerConnection.start();
-
- // Move to a Transacted session to ensure that all messages have been delivered to broker before
- // we start waiting for TTL
- Session producerSession = producerConnection.createSession(true, Session.SESSION_TRANSACTED);
-
- MessageProducer producer = producerSession.createProducer(queue);
-
- //Set TTL
- int msg = 0;
- producer.send(nextMessage(String.valueOf(msg), true, producerSession, producer));
-
- producer.setTimeToLive(TIME_TO_LIVE);
-
- for (; msg < MSG_COUNT - 2; msg++)
- {
- producer.send(nextMessage(String.valueOf(msg), false, producerSession, producer));
- }
-
- //Reset TTL
- producer.setTimeToLive(0L);
- producer.send(nextMessage(String.valueOf(msg), false, producerSession, producer));
-
- producerSession.commit();
-
- consumer = clientSession.createConsumer(queue);
-
- // Ensure we sleep the required amount of time.
- ReentrantLock waitLock = new ReentrantLock();
- Condition wait = waitLock.newCondition();
- final long MILLIS = 1000000L;
-
- long waitTime = TIME_TO_LIVE * MILLIS;
- while (waitTime > 0)
- {
- try
- {
- waitLock.lock();
-
- waitTime = wait.awaitNanos(waitTime);
- }
- catch (InterruptedException e)
- {
- //Stop if we are interrupted
- fail(e.getMessage());
- }
- finally
- {
- waitLock.unlock();
- }
-
- }
-
- clientConnection.start();
-
- //Receive Message 0
- // Set 5s receive time for messages we expect to receive.
- Message receivedFirst = consumer.receive(5000);
- Message receivedSecond = consumer.receive(5000);
- Message receivedThird = consumer.receive(1000);
-
- // Log the messages to help diagnosis incase of failure
- _logger.info("First:"+receivedFirst);
- _logger.info("Second:"+receivedSecond);
- _logger.info("Third:"+receivedThird);
-
- // Only first and last messages sent should survive expiry
- Assert.assertNull("More messages received", receivedThird);
-
- Assert.assertNotNull("First message not received", receivedFirst);
- Assert.assertTrue("First message doesn't have first set.", receivedFirst.getBooleanProperty("first"));
- Assert.assertEquals("First message has incorrect TTL.", 0L, receivedFirst.getLongProperty("TTL"));
-
- Assert.assertNotNull("Final message not received", receivedSecond);
- Assert.assertFalse("Final message has first set.", receivedSecond.getBooleanProperty("first"));
- Assert.assertEquals("Final message has incorrect TTL.", 0L, receivedSecond.getLongProperty("TTL"));
-
- clientConnection.close();
-
- producerConnection.close();
- }
-
- private Message nextMessage(String msg, boolean first, Session producerSession, MessageProducer producer) throws JMSException
- {
- Message send = producerSession.createTextMessage("Message " + msg);
- send.setBooleanProperty("first", first);
- send.setStringProperty("testprop", "TimeToLiveTest");
- send.setLongProperty("TTL", producer.getTimeToLive());
- return send;
- }
-
-
- /**
- * Tests the expired messages get actively deleted even on queues which have no consumers
- * @throws Exception
- */
- public void testActiveTTL() throws Exception
- {
- Connection producerConnection = getConnection();
- AMQSession producerSession = (AMQSession) producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- Queue queue = producerSession.createTemporaryQueue();
- producerSession.declareAndBind((AMQDestination) queue);
- MessageProducer producer = producerSession.createProducer(queue);
- producer.setTimeToLive(1000L);
-
- // send Messages
- for(int i = 0; i < MSG_COUNT; i++)
- {
- producer.send(producerSession.createTextMessage("Message: "+i));
- }
- long failureTime = System.currentTimeMillis() + 2 * SERVER_TTL_TIMEOUT;
-
- // check Queue depth for up to TIMEOUT seconds after the Queue Depth hasn't changed for 100ms.
- long messageCount = MSG_COUNT;
- long lastPass;
-
- do
- {
- lastPass = messageCount;
- Thread.sleep(100);
- messageCount = producerSession.getQueueDepth((AMQDestination) queue);
-
- // If we have received messages in the last loop then extend the timeout time.
- // if we get messages stuck that are not expiring then the failureTime will occur
- // failing the test. This will help with the scenario when the broker does not
- // have enough CPU cycles to process the TTLs.
- if (lastPass != messageCount)
- {
- failureTime = System.currentTimeMillis() + 2 * SERVER_TTL_TIMEOUT;
- }
- }
- while(messageCount > 0L && System.currentTimeMillis() < failureTime);
-
- assertEquals("Messages not automatically expired: ", 0L, messageCount);
-
- producer.close();
- producerSession.close();
- producerConnection.close();
- }
-
- public void testPassiveTTLwithDurableSubscription() throws Exception
- {
- //Create Client 1
- Connection clientConnection = getConnection();
-
- Session clientSession = clientConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- // Create and close the durable subscriber
- AMQTopic topic = new AMQTopic((AMQConnection) clientConnection, getTestQueueName());
- TopicSubscriber durableSubscriber = clientSession.createDurableSubscriber(topic, getTestQueueName(),"testprop='TimeToLiveTest'", false);
- durableSubscriber.close();
-
- //Create Producer
- Connection producerConnection = getConnection();
-
- producerConnection.start();
-
- // Move to a Transacted session to ensure that all messages have been delivered to broker before
- // we start waiting for TTL
- Session producerSession = producerConnection.createSession(true, Session.SESSION_TRANSACTED);
-
- MessageProducer producer = producerSession.createProducer(topic);
-
- //Set TTL
- int msg = 0;
- producer.send(nextMessage(String.valueOf(msg), true, producerSession, producer));
-
- producer.setTimeToLive(TIME_TO_LIVE);
-
- for (; msg < MSG_COUNT - 2; msg++)
- {
- producer.send(nextMessage(String.valueOf(msg), false, producerSession, producer));
- }
-
- //Reset TTL
- producer.setTimeToLive(0L);
- producer.send(nextMessage(String.valueOf(msg), false, producerSession, producer));
-
- producerSession.commit();
-
- //resubscribe
- durableSubscriber = clientSession.createDurableSubscriber(topic, getTestQueueName(),"testprop='TimeToLiveTest'", false);
-
- // Ensure we sleep the required amount of time.
- ReentrantLock waitLock = new ReentrantLock();
- Condition wait = waitLock.newCondition();
- final long MILLIS = 1000000L;
-
- long waitTime = TIME_TO_LIVE * MILLIS;
- while (waitTime > 0)
- {
- try
- {
- waitLock.lock();
-
- waitTime = wait.awaitNanos(waitTime);
- }
- catch (InterruptedException e)
- {
- //Stop if we are interrupted
- fail(e.getMessage());
- }
- finally
- {
- waitLock.unlock();
- }
-
- }
-
- clientConnection.start();
-
- //Receive Message 0
- // Set 5s receive time for messages we expect to receive.
- Message receivedFirst = durableSubscriber.receive(5000);
- Message receivedSecond = durableSubscriber.receive(5000);
- Message receivedThird = durableSubscriber.receive(1000);
-
- // Log the messages to help diagnosis incase of failure
- _logger.info("First:"+receivedFirst);
- _logger.info("Second:"+receivedSecond);
- _logger.info("Third:"+receivedThird);
-
- // Only first and last messages sent should survive expiry
- Assert.assertNull("More messages received", receivedThird);
-
- Assert.assertNotNull("First message not received", receivedFirst);
- Assert.assertTrue("First message doesn't have first set.", receivedFirst.getBooleanProperty("first"));
- Assert.assertEquals("First message has incorrect TTL.", 0L, receivedFirst.getLongProperty("TTL"));
-
- Assert.assertNotNull("Final message not received", receivedSecond);
- Assert.assertFalse("Final message has first set.", receivedSecond.getBooleanProperty("first"));
- Assert.assertEquals("Final message has incorrect TTL.", 0L, receivedSecond.getLongProperty("TTL"));
-
- clientSession.unsubscribe(getTestQueueName());
- clientConnection.close();
-
- producerConnection.close();
- }
-
- public void testActiveTTLwithDurableSubscription() throws Exception
- {
- //Create Client 1
- Connection clientConnection = getConnection();
- Session clientSession = clientConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- // Create and close the durable subscriber
- AMQTopic topic = new AMQTopic((AMQConnection) clientConnection, getTestQueueName());
- TopicSubscriber durableSubscriber = clientSession.createDurableSubscriber(topic, "MyDurableTTLSubscription","testprop='TimeToLiveTest'", false);
- durableSubscriber.close();
-
- //Create Producer
- Connection producerConnection = getConnection();
- AMQSession producerSession = (AMQSession) producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- MessageProducer producer = producerSession.createProducer(topic);
- producer.setTimeToLive(1000L);
-
- // send Messages
- for(int i = 0; i < MSG_COUNT; i++)
- {
- producer.send(producerSession.createTextMessage("Message: "+i));
- }
- long failureTime = System.currentTimeMillis() + 2 * SERVER_TTL_TIMEOUT;
-
- // check Queue depth for up to TIMEOUT seconds after the Queue Depth hasn't changed for 100ms.
- long messageCount = MSG_COUNT;
- long lastPass;
- AMQQueue subcriptionQueue = new AMQQueue("amq.topic","clientid" + ":" + "MyDurableTTLSubscription");
- do
- {
- lastPass = messageCount;
- Thread.sleep(100);
- messageCount = producerSession.getQueueDepth((AMQDestination) subcriptionQueue);
-
- // If we have received messages in the last loop then extend the timeout time.
- // if we get messages stuck that are not expiring then the failureTime will occur
- // failing the test. This will help with the scenario when the broker does not
- // have enough CPU cycles to process the TTLs.
- if (lastPass != messageCount)
- {
- failureTime = System.currentTimeMillis() + 2 * SERVER_TTL_TIMEOUT;
- }
- }
- while(messageCount > 0L && System.currentTimeMillis() < failureTime);
-
- assertEquals("Messages not automatically expired: ", 0L, messageCount);
-
- producer.close();
- producerSession.close();
- producerConnection.close();
-
- clientSession.unsubscribe("MyDurableTTLSubscription");
- clientSession.close();
- clientConnection.close();
- }
-
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/server/security/acl/AbstractACLTestCase.java b/java/systests/src/main/java/org/apache/qpid/server/security/acl/AbstractACLTestCase.java
deleted file mode 100644
index f845ff1214..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/server/security/acl/AbstractACLTestCase.java
+++ /dev/null
@@ -1,285 +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.acl;
-
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.util.Collections;
-import java.util.List;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-import javax.jms.Connection;
-import javax.jms.ExceptionListener;
-import javax.jms.JMSException;
-import javax.naming.NamingException;
-
-import org.apache.commons.configuration.ConfigurationException;
-import org.apache.commons.lang.StringUtils;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQConnectionURL;
-import org.apache.qpid.jms.ConnectionListener;
-import org.apache.qpid.protocol.AMQConstant;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.apache.qpid.url.URLSyntaxException;
-
-/**
- * Abstract test case for ACLs.
- *
- * This base class contains convenience methods to mange ACL files and implements a mechanism that allows each
- * test method to run its own setup code before the broker starts.
- *
- * TODO move the pre broker-startup setup method invocation code to {@link QpidBrokerTestCase}
- *
- * @see SimpleACLTest
- * @see ExternalACLTest
- * @see ExternalACLFileTest
- * @see ExternalACLJMXTest
- * @see ExternalAdminACLTest
- * @see ExhaustiveACLTest
- */
-public abstract class AbstractACLTestCase extends QpidBrokerTestCase implements ConnectionListener
-{
- /** Used to synchronise {@link #tearDown()} when exceptions are thrown */
- protected CountDownLatch _exceptionReceived;
-
- /** Override this to return the name of the configuration XML file. */
- public String getConfig()
- {
- return "config-systests-acl.xml";
- }
-
- /** Override this to setup external ACL files for virtual hosts. */
- public List<String> getHostList()
- {
- return Collections.emptyList();
- }
-
- /**
- * This setup method checks {@link #getConfig()} and {@link #getHostList()} to initialise the broker with specific
- * ACL configurations and then runs an optional per-test setup method, which is simply a method with the same name
- * as the test, but starting with {@code setUp} rather than {@code test}.
- *
- * @see #setUpACLFile(String)
- * @see org.apache.qpid.test.utils.QpidBrokerTestCase#setUp()
- */
- @Override
- public void setUp() throws Exception
- {
- if (QpidHome == null)
- {
- fail("QPID_HOME not set");
- }
-
- // Initialise ACLs.
- _configFile = new File(QpidHome, "etc" + File.separator + getConfig());
-
- // Initialise ACL files
- for (String virtualHost : getHostList())
- {
- setUpACLFile(virtualHost);
- }
-
- // run test specific setup
- String testSetup = StringUtils.replace(getName(), "test", "setUp");
- try
- {
- Method setup = getClass().getDeclaredMethod(testSetup);
- setup.invoke(this);
- }
- catch (NoSuchMethodException e)
- {
- // Ignore
- }
- catch (InvocationTargetException e)
- {
- throw (Exception) e.getTargetException();
- }
-
- super.setUp();
- }
-
- @Override
- public void tearDown() throws Exception
- {
- try
- {
- super.tearDown();
- }
- catch (JMSException e)
- {
- //we're throwing this away as it can happen in this test as the state manager remembers exceptions
- //that we provoked with authentication failures, where the test passes - we can ignore on con close
- }
- }
-
- /**
- * Configures specific ACL files for a virtual host.
- *
- * This method checks for ACL files that exist on the filesystem. If dynamically generatyed ACL files are required in a test,
- * then it is easier to use the {@code setUp} prefix on a method to generate the ACL file. In order, this method looks
- * for three files:
- * <ol>
- * <li><em>virtualhost</em>-<em>class</em>-<em>test</em>.txt
- * <li><em>virtualhost</em>-<em>class</em>.txt
- * <li><em>virtualhost</em>-default.txt
- * </ol>
- * The <em>class</em> and <em>test</em> parts are the test class and method names respectively, with the word {@code test}
- * removed and the rest of the text converted to lowercase. For example, the test class and method named
- * {@code org.apache.qpid.test.AccessExampleTest#testExampleMethod} on the {@code testhost} virtualhost would use
- * one of the following files:
- * <ol>
- * <li>testhost-accessexample-examplemethod.txt
- * <li>testhost-accessexample.txt
- * <li>testhost-default.txt
- * </ol>
- * These files should be copied to the <em>${QPID_HOME}/etc</em> directory when the test is run.
- *
- * @see #writeACLFile(String, String...)
- */
- public void setUpACLFile(String virtualHost) throws IOException, ConfigurationException
- {
- String path = QpidHome + File.separator + "etc";
- String className = StringUtils.substringBeforeLast(getClass().getSimpleName().toLowerCase(), "test");
- String testName = StringUtils.substringAfter(getName(), "test").toLowerCase();
-
- File aclFile = new File(path, virtualHost + "-" + className + "-" + testName + ".txt");
- if (!aclFile.exists())
- {
- aclFile = new File(path, virtualHost + "-" + className + ".txt");
- if (!aclFile.exists())
- {
- aclFile = new File(path, virtualHost + "-" + "default.txt");
- }
- }
-
- // Set the ACL file configuration property
- if (virtualHost.equals("global"))
- {
- setConfigurationProperty("security.aclv2", aclFile.getAbsolutePath());
- }
- else
- {
- setConfigurationProperty("virtualhosts.virtualhost." + virtualHost + ".security.aclv2", aclFile.getAbsolutePath());
- }
- }
-
- public void writeACLFile(String vhost, String...rules) throws ConfigurationException, IOException
- {
- File aclFile = File.createTempFile(getClass().getSimpleName(), getName());
- aclFile.deleteOnExit();
-
- if ("global".equals(vhost))
- {
- setConfigurationProperty("security.aclv2", aclFile.getAbsolutePath());
- }
- else
- {
- setConfigurationProperty("virtualhosts.virtualhost." + vhost + ".security.aclv2", aclFile.getAbsolutePath());
- }
-
- PrintWriter out = new PrintWriter(new FileWriter(aclFile));
- out.println(String.format("# %s", _testName));
- for (String line : rules)
- {
- out.println(line);
- }
- out.close();
- }
-
- /**
- * Creates a connection to the broker, and sets a connection listener to prevent failover and an exception listener
- * with a {@link CountDownLatch} to synchronise in the {@link #check403Exception(Throwable)} method and allow the
- * {@link #tearDown()} method to complete properly.
- */
- public Connection getConnection(String vhost, String username, String password) throws NamingException, JMSException, URLSyntaxException
- {
- AMQConnection connection = (AMQConnection) getConnection(createConnectionURL(vhost, username, password));
-
- //Prevent Failover
- connection.setConnectionListener(this);
-
- //QPID-2081: use a latch to sync on exception causing connection close, to work
- //around the connection close race during tearDown() causing sporadic failures
- _exceptionReceived = new CountDownLatch(1);
-
- connection.setExceptionListener(new ExceptionListener()
- {
- public void onException(JMSException e)
- {
- _exceptionReceived.countDown();
- }
- });
-
- return (Connection) connection;
- }
-
- // Connection Listener Interface - Used here to block failover
-
- public void bytesSent(long count)
- {
- }
-
- public void bytesReceived(long count)
- {
- }
-
- public boolean preFailover(boolean redirect)
- {
- //Prevent failover.
- return false;
- }
-
- public boolean preResubscribe()
- {
- return false;
- }
-
- public void failoverComplete()
- {
- }
-
- /**
- * Convenience method to build an {@link AMQConnectionURL} with the right parameters.
- */
- public AMQConnectionURL createConnectionURL(String vhost, String username, String password) throws URLSyntaxException
- {
- String url = "amqp://" + username + ":" + password + "@clientid/" + vhost + "?brokerlist='" + getBroker() + "?retries='0''";
- return new AMQConnectionURL(url);
- }
-
- /**
- * Convenience method to validate a JMS exception with a linked {@link AMQConstant#ACCESS_REFUSED} 403 error code exception.
- */
- public void check403Exception(Throwable t) throws Exception
- {
- assertNotNull("There was no linked exception", t);
- assertTrue("Wrong linked exception type", t instanceof AMQException);
- assertEquals("Incorrect error code received", 403, ((AMQException) t).getErrorCode().getCode());
-
- //use the latch to ensure the control thread waits long enough for the exception thread
- //to have done enough to mark the connection closed before teardown commences
- assertTrue("Timed out waiting for conneciton to report close", _exceptionReceived.await(2, TimeUnit.SECONDS));
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/server/security/acl/ExhaustiveACLTest.java b/java/systests/src/main/java/org/apache/qpid/server/security/acl/ExhaustiveACLTest.java
deleted file mode 100644
index 1b2c98d30a..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/server/security/acl/ExhaustiveACLTest.java
+++ /dev/null
@@ -1,195 +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.acl;
-
-import java.util.Arrays;
-import java.util.List;
-
-import javax.jms.Connection;
-import javax.jms.Session;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.protocol.AMQConstant;
-
-/**
- * ACL version 2/3 file testing to verify that ACL entries control queue creation with specific properties.
- *
- * Tests have their own ACL files that setup specific permissions, and then try to create queues with every possible combination
- * of properties to show that rule matching works correctly. For example, a rule that specified {@code autodelete="true"} for
- * queues with {@link name="temp.true.*"} as well should not affect queues that have names that do not match, or queues that
- * are not autodelete, or both. Also checks that ACL entries only affect the specified users and virtual hosts.
- */
-public class ExhaustiveACLTest extends AbstractACLTestCase
-{
- @Override
- public String getConfig()
- {
- return "config-systests-aclv2.xml";
- }
-
- @Override
- public List<String> getHostList()
- {
- return Arrays.asList("test", "test2");
- }
-
- /**
- * Creates a queue.
- *
- * Connects to the broker as a particular user and create the named queue on a virtual host, with the provided
- * parameters. Uses a new {@link Connection} and {@link Session} and closes them afterwards.
- */
- private void createQueue(String vhost, String user, String name, boolean autoDelete, boolean durable) throws Exception
- {
- Connection conn = getConnection(vhost, user, "guest");
- Session sess = conn.createSession(true, Session.SESSION_TRANSACTED);
- conn.start();
- ((AMQSession<?, ?>) sess).createQueue(new AMQShortString(name), autoDelete, durable, false);
- sess.commit();
- conn.close();
- }
-
- /**
- * Calls {@link #createQueue(String, String, String, boolean, boolean)} with the provided parameters and checks that
- * no exceptions were thrown.
- */
- private void createQueueSuccess(String vhost, String user, String name, boolean autoDelete, boolean durable) throws Exception
- {
- try
- {
- createQueue(vhost, user, name, autoDelete, durable);
- }
- catch (AMQException e)
- {
- fail(String.format("Create queue should have worked for \"%s\" for user %s@%s, autoDelete=%s, durable=%s",
- name, user, vhost, Boolean.toString(autoDelete), Boolean.toString(durable)));
- }
- }
-
- /**
- * Calls {@link #createQueue(String, String, String, boolean, boolean)} with the provided parameters and checks that
- * the exception thrown was an {@link AMQConstant#ACCESS_REFUSED} or 403 error code.
- */
- private void createQueueFailure(String vhost, String user, String name, boolean autoDelete, boolean durable) throws Exception
- {
- try
- {
- createQueue(vhost, user, name, autoDelete, durable);
- fail(String.format("Create queue should have failed for \"%s\" for user %s@%s, autoDelete=%s, durable=%s",
- name, user, vhost, Boolean.toString(autoDelete), Boolean.toString(durable)));
- }
- catch (AMQException e)
- {
- assertEquals("Should be an ACCESS_REFUSED error", 403, e.getErrorCode().getCode());
- }
- }
-
- public void setUpAuthoriseCreateQueueAutodelete() throws Exception
- {
- writeACLFile("test",
- "acl allow client access virtualhost",
- "acl allow server access virtualhost",
- "acl allow client create queue name=\"temp.true.*\" autodelete=true",
- "acl allow client create queue name=\"temp.false.*\" autodelete=false",
- "acl deny client create queue",
- "acl allow client delete queue",
- "acl deny all create queue"
- );
- }
-
- /**
- * Test creation of temporary queues, with the autodelete property set to true.
- */
- public void testAuthoriseCreateQueueAutodelete() throws Exception
- {
- createQueueSuccess("test", "client", "temp.true.00", true, false);
- createQueueSuccess("test", "client", "temp.true.01", true, false);
- createQueueSuccess("test", "client", "temp.true.02", true, true);
- createQueueSuccess("test", "client", "temp.false.03", false, false);
- createQueueSuccess("test", "client", "temp.false.04", false, false);
- createQueueSuccess("test", "client", "temp.false.05", false, true);
- createQueueFailure("test", "client", "temp.true.06", false, false);
- createQueueFailure("test", "client", "temp.false.07", true, false);
- createQueueFailure("test", "server", "temp.true.08", true, false);
- createQueueFailure("test", "client", "temp.other.09", false, false);
- createQueueSuccess("test2", "guest", "temp.true.01", false, false);
- createQueueSuccess("test2", "guest", "temp.false.02", true, false);
- createQueueSuccess("test2", "guest", "temp.true.03", true, false);
- createQueueSuccess("test2", "guest", "temp.false.04", false, false);
- createQueueSuccess("test2", "guest", "temp.other.05", false, false);
- }
-
- public void setUpAuthoriseCreateQueue() throws Exception
- {
- writeACLFile("test",
- "acl allow client access virtualhost",
- "acl allow server access virtualhost",
- "acl allow client create queue name=\"create.*\""
- );
- }
-
- /**
- * Tests creation of named queues.
- *
- * If a named queue is specified
- */
- public void testAuthoriseCreateQueue() throws Exception
- {
- createQueueSuccess("test", "client", "create.00", true, true);
- createQueueSuccess("test", "client", "create.01", true, false);
- createQueueSuccess("test", "client", "create.02", false, true);
- createQueueSuccess("test", "client", "create.03", true, false);
- createQueueFailure("test", "server", "create.04", true, true);
- createQueueFailure("test", "server", "create.05", true, false);
- createQueueFailure("test", "server", "create.06", false, true);
- createQueueFailure("test", "server", "create.07", true, false);
- createQueueSuccess("test2", "guest", "create.00", true, true);
- createQueueSuccess("test2", "guest", "create.01", true, false);
- createQueueSuccess("test2", "guest", "create.02", false, true);
- createQueueSuccess("test2", "guest", "create.03", true, false);
- }
-
- public void setUpAuthoriseCreateQueueBoth() throws Exception
- {
- writeACLFile("test",
- "acl allow all access virtualhost",
- "acl allow client create queue name=\"create.*\"",
- "acl allow all create queue temporary=true"
- );
- }
-
- /**
- * Tests creation of named queues.
- *
- * If a named queue is specified
- */
- public void testAuthoriseCreateQueueBoth() throws Exception
- {
- createQueueSuccess("test", "client", "create.00", true, false);
- createQueueSuccess("test", "client", "create.01", false, false);
- createQueueFailure("test", "server", "create.02", false, false);
- createQueueFailure("test", "guest", "create.03", false, false);
- createQueueSuccess("test", "client", "tmp.00", true, false);
- createQueueSuccess("test", "server", "tmp.01", true, false);
- createQueueSuccess("test", "guest", "tmp.02", true, false);
- createQueueSuccess("test2", "guest", "create.02", false, false);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/server/security/acl/ExternalACLFileTest.java b/java/systests/src/main/java/org/apache/qpid/server/security/acl/ExternalACLFileTest.java
deleted file mode 100644
index 1d08015669..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/server/security/acl/ExternalACLFileTest.java
+++ /dev/null
@@ -1,184 +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.acl;
-
-import java.util.Arrays;
-import java.util.List;
-
-import javax.jms.Connection;
-import javax.jms.Session;
-
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.framing.AMQShortString;
-
-/**
- * Tests that ACL version 2/3 files following the specification work correctly.
- *
- * ACL lines that are identical in meaning apart from differences allowed by the specification, such as whitespace or case
- * of tokens are set up for numbered queues and the queues are then created to show that the meaning is correctly parsed by
- * the plugin.
- *
- * TODO move this to the access-control plugin unit tests instead
- */
-public class ExternalACLFileTest extends AbstractACLTestCase
-{
- @Override
- public String getConfig()
- {
- return "config-systests-aclv2.xml";
- }
-
- @Override
- public List<String> getHostList()
- {
- return Arrays.asList("test");
- }
-
- private void createQueuePrefixList(String prefix, int count)
- {
- try
- {
- Connection conn = getConnection("test", "client", "guest");
- Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
- conn.start();
-
- //Create n queues
- for (int n = 0; n < count; n++)
- {
- AMQShortString queueName = new AMQShortString(String.format("%s.%03d", prefix, n));
- ((AMQSession<?, ?>) sess).createQueue(queueName, false, false, false);
- }
-
- conn.close();
- }
- catch (Exception e)
- {
- fail("Test failed due to:" + e.getMessage());
- }
- }
-
- private void createQueueNameList(String...queueNames)
- {
- try
- {
- Connection conn = getConnection("test", "client", "guest");
- Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
- conn.start();
-
- //Create all queues
- for (String queueName : queueNames)
- {
- ((AMQSession<?, ?>) sess).createQueue(new AMQShortString(queueName), false, false, false);
- }
-
- conn.close();
- }
- catch (Exception e)
- {
- fail("Test failed due to:" + e.getMessage());
- }
- }
-
- public void setUpCreateQueueMixedCase() throws Exception
- {
- writeACLFile(
- "test",
- "acl allow client create queue name=mixed.000",
- "ACL ALLOW client CREATE QUEUE NAME=mixed.001",
- "Acl Allow client Create Queue Name=mixed.002",
- "aCL aLLOW client cREATE qUEUE nAME=mixed.003",
- "aCl AlLoW client cReAtE qUeUe NaMe=mixed.004"
- );
- }
-
- public void testCreateQueueMixedCase()
- {
- createQueuePrefixList("mixed", 5);
- }
-
- public void setUpCreateQueueContinuation() throws Exception
- {
- writeACLFile(
- "test",
- "acl allow client create queue name=continuation.000",
- "acl allow client create queue \\",
- " name=continuation.001",
- "acl allow client \\",
- " create queue \\",
- " name=continuation.002",
- "acl allow \\",
- " client \\",
- " create queue \\",
- " name=continuation.003",
- "acl \\",
- " allow \\",
- " client \\",
- " create queue \\",
- " name=continuation.004"
- );
- }
-
- public void testCreateQueueContinuation()
- {
- createQueuePrefixList("continuation", 5);
- }
-
- public void setUpCreateQueueWhitespace() throws Exception
- {
- writeACLFile(
- "test",
- "acl allow client create queue name=whitespace.000",
- "acl\tallow\tclient\tcreate\tqueue\tname=whitespace.001",
- "acl allow client create queue name = whitespace.002",
- "acl\tallow\tclient\tcreate\tqueue\tname\t=\twhitespace.003",
- "acl allow\t\tclient\t \tcreate\t\t queue\t \t name \t =\t \twhitespace.004"
- );
- }
-
- public void testCreateQueueWhitespace()
- {
- createQueuePrefixList("whitespace", 5);
- }
-
- public void setUpCreateQueueQuoting() throws Exception
- {
- writeACLFile(
- "test",
- "acl allow client create queue name='quoting.ABC.000'",
- "acl allow client create queue name='quoting.*.000'",
- "acl allow client create queue name='quoting.#.000'",
- "acl allow client create queue name='quoting. .000'",
- "acl allow client create queue name='quoting.!@$%.000'"
- );
- }
-
- public void testCreateQueueQuoting()
- {
- createQueueNameList(
- "quoting.ABC.000",
- "quoting.*.000",
- "quoting.#.000",
- "quoting. .000",
- "quoting.!@$%.000"
- );
- }
-}
-
-
-
diff --git a/java/systests/src/main/java/org/apache/qpid/server/security/acl/ExternalACLJMXTest.java b/java/systests/src/main/java/org/apache/qpid/server/security/acl/ExternalACLJMXTest.java
deleted file mode 100644
index b823690002..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/server/security/acl/ExternalACLJMXTest.java
+++ /dev/null
@@ -1,244 +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.acl;
-
-import java.util.Arrays;
-import java.util.List;
-
-import org.apache.qpid.AMQConnectionClosedException;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.AMQSecurityException;
-import org.apache.qpid.protocol.AMQConstant;
-import org.apache.qpid.test.utils.JMXTestUtils;
-
-/**
- * Tests that ACL entries that apply to AMQP objects also apply when those objects are accessed via JMX.
- */
-public class ExternalACLJMXTest extends AbstractACLTestCase
-{
- private JMXTestUtils _jmx;
-
- private static final String QUEUE_NAME = "kipper";
- private static final String EXCHANGE_NAME = "amq.kipper";
-
- @Override
- public String getConfig()
- {
- return "config-systests-aclv2.xml";
- }
-
- @Override
- public List<String> getHostList()
- {
- return Arrays.asList("test");
- }
-
- @Override
- public void setUp() throws Exception
- {
- _jmx = new JMXTestUtils(this, "admin", "admin");
- _jmx.setUp();
- super.setUp();
- _jmx.open();
- }
-
- @Override
- public void tearDown() throws Exception
- {
- _jmx.close();
- super.tearDown();
- }
-
- // test-externalacljmx.txt
- // create queue owner=client # success
- public void testCreateClientQueueSuccess() throws Exception
- {
- //Queue Parameters
- String queueOwner = "client";
-
- _jmx.createQueue("test", QUEUE_NAME, queueOwner, true);
- }
-
- // test-externalacljmx.txt
- // create queue owner=client # failure
- public void testCreateServerQueueFailure() throws Exception
- {
- //Queue Parameters
- String queueOwner = "server";
-
- try
- {
- _jmx.createQueue("test", QUEUE_NAME, queueOwner, true);
-
- fail("Queue create should fail");
- }
- catch (Exception e)
- {
- assertNotNull("Cause is not set", e.getCause());
- assertEquals("Cause message incorrect",
- "org.apache.qpid.AMQSecurityException: Permission denied: queue-name 'kipper' [error code 403: access refused]", e.getCause().getMessage());
- }
- }
-
- // no create queue acl in file # failure
- public void testCreateQueueFailure() throws Exception
- {
- //Queue Parameters
- String queueOwner = "guest";
-
- try
- {
- _jmx.createQueue("test", QUEUE_NAME, queueOwner, true);
-
- fail("Queue create should fail");
- }
- catch (Exception e)
- {
- assertNotNull("Cause is not set", e.getCause());
- assertEquals("Cause message incorrect",
- "org.apache.qpid.AMQSecurityException: Permission denied: queue-name 'kipper' [error code 403: access refused]", e.getCause().getMessage());
- }
- }
-
- // test-externalacljmx.txt
- // allow create exchange name=amq.kipper.success
- public void testCreateExchangeSuccess() throws Exception
- {
- _jmx.createExchange("test", EXCHANGE_NAME + ".success", "direct", true);
- }
-
- // test-externalacljmx.txt
- // deny create exchange name=amq.kipper.failure
- public void testCreateExchangeFailure() throws Exception
- {
- try
- {
- _jmx.createExchange("test", EXCHANGE_NAME + ".failure", "direct", true);
-
- fail("Exchange create should fail");
- }
- catch (Exception e)
- {
- assertNotNull("Cause is not set", e.getCause());
- assertEquals("Cause message incorrect",
- "org.apache.qpid.AMQSecurityException: Permission denied: exchange-name 'amq.kipper.failure' [error code 403: access refused]", e.getCause().getMessage());
- }
- }
-
- // test-externalacljmx.txt
- // allow create exchange name=amq.kipper.success
- // allow delete exchange name=amq.kipper.success
- public void testDeleteExchangeSuccess() throws Exception
- {
- _jmx.createExchange("test", EXCHANGE_NAME + ".success", "direct", true);
- _jmx.unregisterExchange("test", EXCHANGE_NAME + ".success");
- }
-
- // test-externalacljmx-deleteexchangefailure.txt
- // allow create exchange name=amq.kipper.delete
- // deny delete exchange name=amq.kipper.delete
- public void testDeleteExchangeFailure() throws Exception
- {
- _jmx.createExchange("test", EXCHANGE_NAME + ".delete", "direct", true);
- try
- {
- _jmx.unregisterExchange("test", EXCHANGE_NAME + ".delete");
-
- fail("Exchange delete should fail");
- }
- catch (Exception e)
- {
- assertNotNull("Cause is not set", e.getCause());
- assertEquals("Cause message incorrect",
- "org.apache.qpid.AMQSecurityException: Permission denied [error code 403: access refused]", e.getCause().getMessage());
- }
- }
-
- /**
- * admin user has JMX right but not AMQP
- */
- public void setUpCreateQueueJMXRights() throws Exception
- {
- writeACLFile("test",
- "ACL ALLOW admin EXECUTE METHOD component=\"VirtualHost.VirtualHostManager\" name=\"createNewQueue\"",
- "ACL DENY admin CREATE QUEUE");
- }
-
- public void testCreateQueueJMXRights() throws Exception
- {
- try
- {
- _jmx.createQueue("test", QUEUE_NAME, "admin", true);
-
- fail("Queue create should fail");
- }
- catch (Exception e)
- {
- assertNotNull("Cause is not set", e.getCause());
- assertEquals("Cause message incorrect",
- "org.apache.qpid.AMQSecurityException: Permission denied: queue-name 'kipper' [error code 403: access refused]", e.getCause().getMessage());
- }
- }
-
- /**
- * admin user has AMQP right but not JMX
- */
- public void setUpCreateQueueAMQPRights() throws Exception
- {
- writeACLFile("test",
- "ACL DENY admin EXECUTE METHOD component=\"VirtualHost.VirtualHostManager\" name=\"createNewQueue\"",
- "ACL ALLOW admin CREATE QUEUE");
- }
-
- public void testCreateQueueAMQPRights() throws Exception
- {
- try
- {
- _jmx.createQueue("test", QUEUE_NAME, "admin", true);
-
- fail("Queue create should fail");
- }
- catch (Exception e)
- {
- assertEquals("Cause message incorrect", "Permission denied: Execute createNewQueue", e.getMessage());
- }
- }
-
- /**
- * admin has both JMX and AMQP rights
- */
- public void setUpCreateQueueJMXAMQPRights() throws Exception
- {
- writeACLFile("test",
- "ACL ALLOW admin EXECUTE METHOD component=\"VirtualHost.VirtualHostManager\" name=\"createNewQueue\"",
- "ACL ALLOW admin CREATE QUEUE");
- }
-
- public void testCreateQueueJMXAMQPRights() throws Exception
- {
- try
- {
- _jmx.createQueue("test", QUEUE_NAME, "admin", true);
- }
- catch (Exception e)
- {
- fail("Queue create should succeed: " + e.getCause().getMessage());
- }
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/server/security/acl/ExternalACLTest.java b/java/systests/src/main/java/org/apache/qpid/server/security/acl/ExternalACLTest.java
deleted file mode 100644
index 4603cc1862..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/server/security/acl/ExternalACLTest.java
+++ /dev/null
@@ -1,37 +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.acl;
-
-import java.util.Arrays;
-import java.util.List;
-
-public class ExternalACLTest extends SimpleACLTest
-{
- @Override
- public String getConfig()
- {
- return "config-systests-aclv2.xml";
- }
-
- @Override
- public List<String> getHostList()
- {
- return Arrays.asList("test", "test2");
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/server/security/acl/ExternalAdminACLTest.java b/java/systests/src/main/java/org/apache/qpid/server/security/acl/ExternalAdminACLTest.java
deleted file mode 100644
index 290cbfdc14..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/server/security/acl/ExternalAdminACLTest.java
+++ /dev/null
@@ -1,186 +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.acl;
-
-import java.io.BufferedWriter;
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.List;
-
-import org.apache.qpid.server.logging.management.LoggingManagementMBean;
-import org.apache.qpid.test.utils.JMXTestUtils;
-
-/**
- * Tests that ACLs can be applied to mangement operations that do not correspond to a specific AMQP object.
- *
- * Theses tests use the logging component, exposed as the {@link LoggingManagementMBean}, to get and set properties.
- */
-public class ExternalAdminACLTest extends AbstractACLTestCase
-{
- private static final String CATEGORY_PRIORITY = "LogManMBeanTest.category.priority";
- private static final String CATEGORY_LEVEL = "LogManMBeanTest.category.level";
- private static final String LOGGER_LEVEL = "LogManMBeanTest.logger.level";
-
- private static final String NEWLINE = System.getProperty("line.separator");
-
- private JMXTestUtils _jmx;
- private File _testConfigFile;
-
- @Override
- public String getConfig()
- {
- return "config-systests-aclv2.xml";
- }
-
- @Override
- public List<String> getHostList()
- {
- return Arrays.asList("global");
- }
-
- @Override
- public void setUp() throws Exception
- {
- _testConfigFile = createTempTestLog4JConfig();
-
- _jmx = new JMXTestUtils(this, "admin", "admin");
- _jmx.setUp();
- super.setUp();
- _jmx.open();
- }
-
- @Override
- public void tearDown() throws Exception
- {
- _jmx.close();
- super.tearDown();
- }
-
- private File createTempTestLog4JConfig()
- {
- File tmpFile = null;
- try
- {
- tmpFile = File.createTempFile("LogManMBeanTestLog4jConfig", ".tmp");
- tmpFile.deleteOnExit();
-
- FileWriter fstream = new FileWriter(tmpFile);
- BufferedWriter writer = new BufferedWriter(fstream);
-
- writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+NEWLINE);
- writer.write("<!DOCTYPE log4j:configuration SYSTEM \"log4j.dtd\">"+NEWLINE);
-
- writer.write("<log4j:configuration xmlns:log4j=\"http://jakarta.apache.org/log4j/\" debug=\"null\" " +
- "threshold=\"null\">"+NEWLINE);
-
- writer.write(" <appender class=\"org.apache.log4j.ConsoleAppender\" name=\"STDOUT\">"+NEWLINE);
- writer.write(" <layout class=\"org.apache.log4j.PatternLayout\">"+NEWLINE);
- writer.write(" <param name=\"ConversionPattern\" value=\"%d %-5p [%t] %C{2} (%F:%L) - %m%n\"/>"+NEWLINE);
- writer.write(" </layout>"+NEWLINE);
- writer.write(" </appender>"+NEWLINE);
-
- //Example of a 'category' with a 'priority'
- writer.write(" <category additivity=\"true\" name=\"" + CATEGORY_PRIORITY +"\">"+NEWLINE);
- writer.write(" <priority value=\"info\"/>"+NEWLINE);
- writer.write(" <appender-ref ref=\"STDOUT\"/>"+NEWLINE);
- writer.write(" </category>"+NEWLINE);
-
- //Example of a 'category' with a 'level'
- writer.write(" <category additivity=\"true\" name=\"" + CATEGORY_LEVEL +"\">"+NEWLINE);
- writer.write(" <level value=\"warn\"/>"+NEWLINE);
- writer.write(" <appender-ref ref=\"STDOUT\"/>"+NEWLINE);
- writer.write(" </category>"+NEWLINE);
-
- //Example of a 'logger' with a 'level'
- writer.write(" <logger additivity=\"true\" name=\"" + LOGGER_LEVEL + "\">"+NEWLINE);
- writer.write(" <level value=\"error\"/>"+NEWLINE);
- writer.write(" <appender-ref ref=\"STDOUT\"/>"+NEWLINE);
- writer.write(" </logger>"+NEWLINE);
-
- //'root' logger
- writer.write(" <root>"+NEWLINE);
- writer.write(" <priority value=\"info\"/>"+NEWLINE);
- writer.write(" <appender-ref ref=\"STDOUT\"/>"+NEWLINE);
- writer.write(" </root>"+NEWLINE);
-
- writer.write("</log4j:configuration>"+NEWLINE);
-
- writer.flush();
- writer.close();
- }
- catch (IOException e)
- {
- fail("Unable to create temporary test log4j configuration");
- }
-
- return tmpFile;
- }
-
- public void testGetAllLoggerLevels() throws Exception
- {
- String[] levels = _jmx.getAvailableLoggerLevels();
- for (int i = 0; i < levels.length; i++)
- {
- System.out.println(levels[i]);
- }
- assertEquals("Got incorrect number of log levels", 9, levels.length);
- }
-
- public void testGetAllLoggerLevelsDenied() throws Exception
- {
- try
- {
- _jmx.getAvailableLoggerLevels();
- fail("Got list of log levels");
- }
- catch (Exception e)
- {
- // Exception throws
- e.printStackTrace();
- assertEquals("Permission denied: Access getAvailableLoggerLevels", e.getMessage());
- }
- }
-
- public void testChangeLoggerLevel() throws Exception
- {
- String oldLevel = _jmx.getRuntimeRootLoggerLevel();
- System.out.println("old level = " + oldLevel);
- _jmx.setRuntimeRootLoggerLevel("DEBUG");
- String newLevel = _jmx.getRuntimeRootLoggerLevel();
- System.out.println("new level = " + newLevel);
- assertEquals("Logging level was not changed", "DEBUG", newLevel);
- }
-
- public void testChangeLoggerLevelDenied() throws Exception
- {
- try
- {
- _jmx.setRuntimeRootLoggerLevel("DEBUG");
- fail("Logging level was changed");
- }
- catch (Exception e)
- {
- assertEquals("Permission denied: Update setRuntimeRootLoggerLevel", e.getMessage());
- }
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/server/security/acl/SimpleACLTest.java b/java/systests/src/main/java/org/apache/qpid/server/security/acl/SimpleACLTest.java
deleted file mode 100644
index a50817e659..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/server/security/acl/SimpleACLTest.java
+++ /dev/null
@@ -1,644 +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.acl;
-
-import java.io.IOException;
-
-import javax.jms.Connection;
-import javax.jms.DeliveryMode;
-import javax.jms.IllegalStateException;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-import javax.jms.Queue;
-import javax.jms.Session;
-import javax.jms.TextMessage;
-import javax.jms.Topic;
-import javax.jms.TopicSubscriber;
-import javax.naming.NamingException;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.protocol.AMQConstant;
-import org.apache.qpid.url.URLSyntaxException;
-
-/**
- * Basic access control list tests.
- *
- * These tests require an access control security plugin to be configured in the broker, and carry out various broker
- * operations that will succeed or fail depending on the user and virtual host. See the {@code config-systests-acl-setup.xml}
- * configuration file for the SimpleXML version of the ACLs used by the Java broker only, or the various {@code .txt}
- * files in the system tests directory for the external version 3 ACL files used by both the Java and C++ brokers.
- * <p>
- * This class can be extended and the {@link #getConfig()} method overridden to run the same tests with a different type
- * of access control mechanism. Extension classes should differ only in the configuration file used, but extra tests can be
- * added that are specific to a particular configuration.
- * <p>
- * The tests perform basic AMQP operations like creating queues or excahnges and publishing and consuming messages, using
- * JMS to contact the broker.
- *
- * @see ExternalACLTest
- */
-public class SimpleACLTest extends AbstractACLTestCase
-{
- public void testAccessAuthorizedSuccess() throws AMQException, URLSyntaxException, Exception
- {
- try
- {
- Connection conn = getConnection("test", "client", "guest");
- Session sess = conn.createSession(true, Session.SESSION_TRANSACTED);
- conn.start();
-
- //Do something to show connection is active.
- sess.rollback();
-
- conn.close();
- }
- catch (Exception e)
- {
- fail("Connection was not created due to:" + e);
- }
- }
-
- public void testAccessVhostAuthorisedGuestSuccess() throws IOException, Exception
- {
- //The 'guest' user has no access to the 'test' vhost, as tested below in testAccessNoRights(), and so
- //is unable to perform actions such as connecting (and by extension, creating a queue, and consuming
- //from a queue etc). In order to test the vhost-wide 'access' ACL right, the 'guest' user has been given
- //this right in the 'test2' vhost.
-
- try
- {
- //get a connection to the 'test2' vhost using the guest user and perform various actions.
- Connection conn = getConnection("test2", "guest", "guest");
- Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
- conn.start();
-
- //create Queues and consumers for each
- Queue namedQueue = sess.createQueue("vhostAccessCreatedQueue" + getTestQueueName());
- Queue tempQueue = sess.createTemporaryQueue();
- MessageConsumer consumer = sess.createConsumer(namedQueue);
- MessageConsumer tempConsumer = sess.createConsumer(tempQueue);
-
- //send a message to each queue (also causing an exchange declare)
- MessageProducer sender = ((AMQSession<?, ?>) sess).createProducer(null);
- ((org.apache.qpid.jms.MessageProducer) sender).send(namedQueue, sess.createTextMessage("test"),
- DeliveryMode.NON_PERSISTENT, 0, 0L, false, false, true);
- ((org.apache.qpid.jms.MessageProducer) sender).send(tempQueue, sess.createTextMessage("test"),
- DeliveryMode.NON_PERSISTENT, 0, 0L, false, false, true);
-
- //consume the messages from the queues
- consumer.receive(2000);
- tempConsumer.receive(2000);
-
- conn.close();
- }
- catch (Exception e)
- {
- fail("Test failed due to:" + e.getMessage());
- }
- }
-
- public void testAccessNoRightsFailure() throws Exception
- {
- try
- {
- Connection conn = getConnection("test", "guest", "guest");
- Session sess = conn.createSession(true, Session.SESSION_TRANSACTED);
- conn.start();
- sess.rollback();
-
- fail("Connection was created.");
- }
- catch (JMSException e)
- {
- // JMSException -> linkedException -> cause = AMQException (403 or 320)
- Exception linkedException = e.getLinkedException();
- assertNotNull("There was no linked exception", linkedException);
- Throwable cause = linkedException.getCause();
- assertNotNull("Cause was null", cause);
- assertTrue("Wrong linked exception type", cause instanceof AMQException);
- AMQConstant errorCode = isBroker010() ? AMQConstant.CONTEXT_IN_USE : AMQConstant.ACCESS_REFUSED;
- assertEquals("Incorrect error code received", errorCode, ((AMQException) cause).getErrorCode());
- }
- }
-
- public void testClientDeleteQueueSuccess() throws Exception
- {
- try
- {
- Connection conn = getConnection("test", "client", "guest");
- Session sess = conn.createSession(true, Session.SESSION_TRANSACTED);
- conn.start();
-
- // create kipper
- Topic kipper = sess.createTopic("kipper");
- TopicSubscriber subscriber = sess.createDurableSubscriber(kipper, "kipper");
-
- subscriber.close();
- sess.unsubscribe("kipper");
-
- //Do something to show connection is active.
- sess.rollback();
- conn.close();
- }
- catch (Exception e)
- {
- fail("Test failed due to:" + e.getMessage());
- }
- }
-
- public void testServerDeleteQueueFailure() throws Exception
- {
- try
- {
- Connection conn = getConnection("test", "server", "guest");
- Session sess = conn.createSession(true, Session.SESSION_TRANSACTED);
- conn.start();
-
- // create kipper
- Topic kipper = sess.createTopic("kipper");
- TopicSubscriber subscriber = sess.createDurableSubscriber(kipper, "kipper");
-
- subscriber.close();
- sess.unsubscribe("kipper");
-
- //Do something to show connection is active.
- sess.rollback();
- conn.close();
- }
- catch (JMSException e)
- {
- // JMSException -> linedException = AMQException.403
- check403Exception(e.getLinkedException());
- }
- }
-
- public void testClientConsumeFromTempQueueSuccess() throws AMQException, URLSyntaxException, Exception
- {
- try
- {
- Connection conn = getConnection("test", "client", "guest");
-
- Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- conn.start();
-
- sess.createConsumer(sess.createTemporaryQueue());
-
- conn.close();
- }
- catch (Exception e)
- {
- fail("Test failed due to:" + e.getMessage());
- }
- }
-
- public void testClientConsumeFromNamedQueueFailure() throws NamingException, Exception
- {
- try
- {
- Connection conn = getConnection("test", "client", "guest");
-
- Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- conn.start();
-
- sess.createConsumer(sess.createQueue("IllegalQueue"));
-
- fail("Test failed as consumer was created.");
- }
- catch (JMSException e)
- {
- check403Exception(e.getLinkedException());
- }
- }
-
- public void testClientCreateTemporaryQueueSuccess() throws JMSException, URLSyntaxException, Exception
- {
- try
- {
- Connection conn = getConnection("test", "client", "guest");
-
- Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- conn.start();
-
- //Create Temporary Queue - can't use the createTempQueue as QueueName is null.
- ((AMQSession<?, ?>) sess).createQueue(new AMQShortString("doesnt_matter_as_autodelete_means_tmp"),
- true, false, false);
-
- conn.close();
- }
- catch (Exception e)
- {
- fail("Test failed due to:" + e.getMessage());
- }
- }
-
- public void testClientCreateNamedQueueFailure() throws NamingException, JMSException, AMQException, Exception
- {
- try
- {
- Connection conn = getConnection("test", "client", "guest");
-
- Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- conn.start();
-
- //Create a Named Queue
- ((AMQSession<?, ?>) sess).createQueue(new AMQShortString("IllegalQueue"), false, false, false);
-
- fail("Test failed as Queue creation succeded.");
- //conn will be automatically closed
- }
- catch (AMQException e)
- {
- check403Exception(e);
- }
- }
-
- public void testClientPublishUsingTransactionSuccess() throws AMQException, URLSyntaxException, Exception
- {
- try
- {
- Connection conn = getConnection("test", "client", "guest");
-
- Session sess = conn.createSession(true, Session.SESSION_TRANSACTED);
-
- conn.start();
-
- MessageProducer sender = sess.createProducer(sess.createQueue("example.RequestQueue"));
-
- sender.send(sess.createTextMessage("test"));
-
- //Send the message using a transaction as this will allow us to retrieve any errors that occur on the broker.
- sess.commit();
-
- conn.close();
- }
- catch (Exception e)
- {
- fail("Test publish failed:" + e);
- }
- }
-
- public void testClientPublishValidQueueSuccess() throws AMQException, URLSyntaxException, Exception
- {
- try
- {
- Connection conn = getConnection("test", "client", "guest");
-
- Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- conn.start();
-
- MessageProducer sender = ((AMQSession<?, ?>) sess).createProducer(null);
-
- Queue queue = sess.createQueue("example.RequestQueue");
-
- // Send a message that we will wait to be sent, this should give the broker time to process the msg
- // before we finish this test. Message is set !immed !mand as the queue is invalid so want to test ACLs not
- // queue existence.
- ((org.apache.qpid.jms.MessageProducer) sender).send(queue, sess.createTextMessage("test"),
- DeliveryMode.NON_PERSISTENT, 0, 0L, false, false, true);
-
- conn.close();
- }
- catch (Exception e)
- {
- fail("Test publish failed:" + e);
- }
- }
-
- public void testClientPublishInvalidQueueSuccess() throws AMQException, URLSyntaxException, JMSException, NamingException, Exception
- {
- try
- {
- Connection conn = getConnection("test", "client", "guest");
-
- Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- conn.start();
-
- MessageProducer sender = ((AMQSession<?, ?>) session).createProducer(null);
-
- Queue queue = session.createQueue("Invalid");
-
- // Send a message that we will wait to be sent, this should give the broker time to close the connection
- // before we finish this test. Message is set !immed !mand as the queue is invalid so want to test ACLs not
- // queue existence.
- ((org.apache.qpid.jms.MessageProducer) sender).send(queue, session.createTextMessage("test"),
- DeliveryMode.NON_PERSISTENT, 0, 0L, false, false, true);
-
- // Test the connection with a valid consumer
- // This may fail as the session may be closed before the queue or the consumer created.
- Queue temp = session.createTemporaryQueue();
-
- session.createConsumer(temp).close();
-
- //Connection should now be closed and will throw the exception caused by the above send
- conn.close();
-
- fail("Close is not expected to succeed.");
- }
- catch (IllegalStateException e)
- {
- _logger.info("QPID-2345: Session became closed and we got that error rather than the authentication error.");
- }
- catch (JMSException e)
- {
- check403Exception(e.getLinkedException());
- }
- }
-
- public void testServerConsumeFromNamedQueueValid() throws AMQException, URLSyntaxException, Exception
- {
- try
- {
- Connection conn = getConnection("test", "server", "guest");
-
- Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- conn.start();
-
- sess.createConsumer(sess.createQueue("example.RequestQueue"));
-
- conn.close();
- }
- catch (Exception e)
- {
- fail("Test failed due to:" + e.getMessage());
- }
- }
-
- public void testServerConsumeFromNamedQueueInvalid() throws AMQException, URLSyntaxException, NamingException, Exception
- {
- try
- {
- Connection conn = getConnection("test", "client", "guest");
-
- Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- conn.start();
-
- sess.createConsumer(sess.createQueue("Invalid"));
-
- fail("Test failed as consumer was created.");
- }
- catch (JMSException e)
- {
- check403Exception(e.getLinkedException());
- }
- }
-
- public void testServerConsumeFromTemporaryQueue() throws AMQException, URLSyntaxException, NamingException, Exception
- {
- try
- {
- Connection conn = getConnection("test", "server", "guest");
-
- Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- conn.start();
-
- sess.createConsumer(sess.createTemporaryQueue());
-
- fail("Test failed as consumer was created.");
- }
- catch (JMSException e)
- {
- check403Exception(e.getLinkedException());
- }
- }
-
- public void testServerCreateNamedQueueValid() throws JMSException, URLSyntaxException, Exception
- {
- try
- {
- Connection conn = getConnection("test", "server", "guest");
-
- Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- conn.start();
-
- //Create Temporary Queue
- ((AMQSession<?, ?>) sess).createQueue(new AMQShortString("example.RequestQueue"), false, false, false);
-
- conn.close();
- }
- catch (Exception e)
- {
- fail("Test failed due to:" + e.getMessage());
- }
- }
-
- public void testServerCreateNamedQueueInvalid() throws JMSException, URLSyntaxException, AMQException, NamingException, Exception
- {
- try
- {
- Connection conn = getConnection("test", "server", "guest");
-
- Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- conn.start();
-
- //Create a Named Queue
- ((AMQSession<?, ?>) sess).createQueue(new AMQShortString("IllegalQueue"), false, false, false);
-
- fail("Test failed as creation succeded.");
- }
- catch (Exception e)
- {
- check403Exception(e);
- }
- }
-
- public void testServerCreateTemporaryQueueInvalid() throws NamingException, Exception
- {
- try
- {
- Connection conn = getConnection("test", "server", "guest");
- Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- conn.start();
-
- session.createTemporaryQueue();
-
- fail("Test failed as creation succeded.");
- }
- catch (JMSException e)
- {
- check403Exception(e.getLinkedException());
- }
- }
-
- public void testServerCreateAutoDeleteQueueInvalid() throws NamingException, JMSException, AMQException, Exception
- {
- try
- {
- Connection connection = getConnection("test", "server", "guest");
-
- Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- connection.start();
-
- ((AMQSession<?, ?>) session).createQueue(new AMQShortString("again_ensure_auto_delete_queue_for_temporary"),
- true, false, false);
-
- fail("Test failed as creation succeded.");
- }
- catch (Exception e)
- {
- check403Exception(e);
- }
- }
-
- /**
- * This test uses both the cilent and sender to validate that the Server is able to publish to a temporary queue.
- * The reason the client must be involved is that the Server is unable to create its own Temporary Queues.
- *
- * @throws AMQException
- * @throws URLSyntaxException
- * @throws JMSException
- */
- public void testServerPublishUsingTransactionSuccess() throws AMQException, URLSyntaxException, JMSException, NamingException, Exception
- {
- //Set up the Server
- Connection serverConnection = getConnection("test", "server", "guest");
-
- Session serverSession = serverConnection.createSession(true, Session.SESSION_TRANSACTED);
-
- Queue requestQueue = serverSession.createQueue("example.RequestQueue");
-
- MessageConsumer server = serverSession.createConsumer(requestQueue);
-
- serverConnection.start();
-
- //Set up the consumer
- Connection clientConnection = getConnection("test", "client", "guest");
-
- //Send a test mesage
- Session clientSession = clientConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- Queue responseQueue = clientSession.createTemporaryQueue();
-
- MessageConsumer clientResponse = clientSession.createConsumer(responseQueue);
-
- clientConnection.start();
-
- Message request = clientSession.createTextMessage("Request");
-
- assertNotNull("Response Queue is null", responseQueue);
-
- request.setJMSReplyTo(responseQueue);
-
- clientSession.createProducer(requestQueue).send(request);
-
- try
- {
- Message msg = null;
-
- msg = server.receive(2000);
-
- while (msg != null && !((TextMessage) msg).getText().equals("Request"))
- {
- msg = server.receive(2000);
- }
-
- assertNotNull("Message not received", msg);
-
- assertNotNull("Reply-To is Null", msg.getJMSReplyTo());
-
- MessageProducer sender = serverSession.createProducer(msg.getJMSReplyTo());
-
- sender.send(serverSession.createTextMessage("Response"));
-
- //Send the message using a transaction as this will allow us to retrieve any errors that occur on the broker.
- serverSession.commit();
-
- //Ensure Response is received.
- Message clientResponseMsg = clientResponse.receive(2000);
- assertNotNull("Client did not receive response message,", clientResponseMsg);
- assertEquals("Incorrect message received", "Response", ((TextMessage) clientResponseMsg).getText());
-
- }
- catch (Exception e)
- {
- fail("Test publish failed:" + e);
- }
- finally
- {
- try
- {
- serverConnection.close();
- }
- finally
- {
- clientConnection.close();
- }
- }
- }
-
- public void testServerPublishInvalidQueueSuccess() throws AMQException, URLSyntaxException, JMSException, NamingException, Exception
- {
- try
- {
- Connection conn = getConnection("test", "server", "guest");
-
- ((AMQConnection) conn).setConnectionListener(this);
-
- Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- conn.start();
-
- MessageProducer sender = ((AMQSession<?, ?>) session).createProducer(null);
-
- Queue queue = session.createQueue("Invalid");
-
- // Send a message that we will wait to be sent, this should give the broker time to close the connection
- // before we finish this test. Message is set !immed !mand as the queue is invalid so want to test ACLs not
- // queue existence.
- ((org.apache.qpid.jms.MessageProducer) sender).send(queue, session.createTextMessage("test"),
- DeliveryMode.NON_PERSISTENT, 0, 0L, false, false, true);
-
- // Test the connection with a valid consumer
- // This may not work as the session may be closed before the queue or consumer creation can occur.
- // The correct JMSexception with linked error will only occur when the close method is recevied whilst in
- // the failover safe block
- session.createConsumer(session.createQueue("example.RequestQueue")).close();
-
- //Connection should now be closed and will throw the exception caused by the above send
- conn.close();
-
- fail("Close is not expected to succeed.");
- }
- catch (IllegalStateException e)
- {
- _logger.info("QPID-2345: Session became closed and we got that error rather than the authentication error.");
- }
- catch (JMSException e)
- {
- check403Exception(e.getLinkedException());
- }
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/server/security/firewall/FirewallConfigTest.java b/java/systests/src/main/java/org/apache/qpid/server/security/firewall/FirewallConfigTest.java
deleted file mode 100644
index f40e95885d..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/server/security/firewall/FirewallConfigTest.java
+++ /dev/null
@@ -1,298 +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.firewall;
-
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
-
-import javax.jms.Connection;
-import javax.jms.JMSException;
-
-import org.apache.qpid.client.AMQConnectionURL;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-public class FirewallConfigTest extends QpidBrokerTestCase
-{
- private File _tmpConfig, _tmpVirtualhosts;
-
- @Override
- protected void setUp() throws Exception
- {
- // do setup
- final String QPID_HOME = System.getProperty("QPID_HOME");
-
- if (QPID_HOME == null)
- {
- fail("QPID_HOME not set");
- }
-
- // Setup initial config file.
- _configFile = new File(QPID_HOME, "etc/config-systests-firewall.xml");
-
- // Setup temporary config file
- _tmpConfig = File.createTempFile("config-systests-firewall", ".xml");
- setSystemProperty("QPID_FIREWALL_CONFIG_SETTINGS", _tmpConfig.getAbsolutePath());
- _tmpConfig.deleteOnExit();
-
- // Setup temporary virtualhosts file
- _tmpVirtualhosts = File.createTempFile("virtualhosts-systests-firewall", ".xml");
- setSystemProperty("QPID_FIREWALL_VIRTUALHOSTS_SETTINGS", _tmpVirtualhosts.getAbsolutePath());
- _tmpVirtualhosts.deleteOnExit();
- }
-
- private void writeFirewallFile(boolean allow, boolean inVhost) throws IOException
- {
- FileWriter out = new FileWriter(inVhost ? _tmpVirtualhosts : _tmpConfig);
- String ipAddr = "127.0.0.1"; // FIXME: get this from InetAddress.getLocalHost().getAddress() ?
- if (inVhost)
- {
- out.write("<virtualhosts><virtualhost><test>");
- }
- else
- {
- out.write("<broker>");
- }
- out.write("<security><firewall>");
- out.write("<rule access=\""+((allow) ? "allow" : "deny")+"\" network=\""+ipAddr +"\"/>");
- out.write("</firewall></security>");
- if (inVhost)
- {
- out.write("</test></virtualhost></virtualhosts>");
- }
- else
- {
- out.write("</broker>");
- }
- out.close();
- }
-
- public void testVhostAllowBrokerDeny() throws Exception
- {
- if (_broker.equals(VM))
- {
- //No point running this test with an InVM broker as the
- //firewall plugin only functions for TCP connections.
- return;
- }
-
- _configFile = new File(System.getProperty("QPID_HOME"), "etc/config-systests-firewall-2.xml");
-
- super.setUp();
-
- Connection conn = null;
- try
- {
- //Try to get a connection to the 'test2' vhost
- //This is expected to succeed as it is allowed at the vhost level
- conn = getConnection(new AMQConnectionURL("amqp://guest:guest@clientid/test2?brokerlist='" + getBroker() + "'"));
- }
- catch (JMSException e)
- {
- e.getLinkedException().printStackTrace();
- fail("The connection was expected to succeed: " + e.getMessage());
- }
-
- conn = null;
- try
- {
- //Try to get a connection to the 'test' vhost
- //This is expected to fail as it is denied at the broker level
- conn = getConnection();
- fail("We expected the connection to fail");
- }
- catch (JMSException e)
- {
- //ignore
- }
- }
-
- public void testVhostDenyBrokerAllow() throws Exception
- {
- if (_broker.equals(VM))
- {
- //No point running this test with an InVM broker as the
- //firewall plugin only functions for TCP connections.
- return;
- }
-
- _configFile = new File(System.getProperty("QPID_HOME"), "etc/config-systests-firewall-3.xml");
-
- super.setUp();
-
- Connection conn = null;
- try
- {
- //Try to get a connection to the 'test2' vhost
- //This is expected to fail as it is denied at the vhost level
- conn = getConnection(new AMQConnectionURL("amqp://guest:guest@clientid/test2?brokerlist='" + getBroker() + "'"));
- fail("The connection was expected to fail");
- }
- catch (JMSException e)
- {
- //ignore
- }
-
- conn = null;
- try
- {
- //Try to get a connection to the 'test' vhost
- //This is expected to succeed as it is allowed at the broker level
- conn = getConnection();
- }
- catch (JMSException e)
- {
- e.getLinkedException().printStackTrace();
- fail("The connection was expected to succeed: " + e.getMessage());
- }
- }
-
- public void testDenyOnRestart() throws Exception
- {
- testDeny(false, new Runnable() {
-
- public void run()
- {
- try
- {
- restartBroker();
- } catch (Exception e)
- {
- fail(e.getMessage());
- }
- }
- });
- }
-
- public void testDenyOnRestartInVhost() throws Exception
- {
- testDeny(true, new Runnable() {
-
- public void run()
- {
- try
- {
- restartBroker();
- } catch (Exception e)
- {
- fail(e.getMessage());
- }
- }
- });
- }
-
- public void testAllowOnReloadInVhost() throws Exception
- {
- testFirewall(false, true, new Runnable() {
-
- public void run()
- {
- try
- {
- reloadBrokerSecurityConfig();
- } catch (Exception e)
- {
- fail(e.getMessage());
- }
- }
- });
- }
-
- public void testDenyOnReload() throws Exception
- {
- testDeny(false, new Runnable() {
-
- public void run()
- {
- try
- {
- reloadBrokerSecurityConfig();
- } catch (Exception e)
- {
- fail(e.getMessage());
- }
- }
- }
- );
- }
-
- public void testDenyOnReloadInVhost() throws Exception
- {
- testDeny(true, new Runnable() {
-
- public void run()
- {
- try
- {
- reloadBrokerSecurityConfig();
- } catch (Exception e)
- {
- fail(e.getMessage());
- }
- }
- }
- );
-
- }
-
- private void testDeny(boolean inVhost, Runnable restartOrReload) throws Exception
- {
- testFirewall(true, inVhost, restartOrReload);
- }
-
- /*
- * Check we can get a connection
- */
- private boolean checkConnection() throws Exception
- {
- Exception exception = null;
- Connection conn = null;
- try
- {
- conn = getConnection();
- }
- catch (JMSException e)
- {
- exception = e;
- }
-
- return conn != null;
- }
-
- private void testFirewall(boolean initial, boolean inVhost, Runnable restartOrReload) throws Exception
- {
- if (_broker.equals(VM))
- {
- // No point running this test in a vm broker
- return;
- }
-
- writeFirewallFile(initial, inVhost);
- setConfigurationProperty("management.enabled", String.valueOf(true));
- super.setUp();
-
- assertEquals("Initial connection check failed", initial, checkConnection());
-
- // Reload changed firewall file after restart or reload
- writeFirewallFile(!initial, inVhost);
- restartOrReload.run();
-
- assertEquals("Second connection check failed", !initial, checkConnection());
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/server/store/PersistentStoreTest.java b/java/systests/src/main/java/org/apache/qpid/server/store/PersistentStoreTest.java
deleted file mode 100644
index bf9d0e0f7b..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/server/store/PersistentStoreTest.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.server.store;
-
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-import javax.jms.Connection;
-import javax.jms.Destination;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-import javax.jms.Queue;
-import javax.jms.Session;
-
-import java.util.ArrayList;
-import java.util.List;
-
-public class PersistentStoreTest extends QpidBrokerTestCase
-{
-
- private static final int NUM_MESSAGES = 100;
- private Connection _con;
- private Session _session;
- private Queue _destination;
- private MessageConsumer _consumer;
-
- public void setUp() throws Exception, JMSException
- {
- super.setUp();
- _con = getConnection();
- _con.start();
- _session = _con.createSession(true, Session.SESSION_TRANSACTED);
- _destination = _session.createQueue(getTestQueueName());
- _consumer = _session.createConsumer(_destination);
- _consumer.close();
-
- sendMessage(_session, _destination, NUM_MESSAGES);
- _session.commit();
- }
-
- /** Checks that a new consumer on a new connection can get NUM_MESSAGES from _destination */
- private void checkMessages() throws Exception, JMSException
- {
- _con = getConnection();
- _session = _con.createSession(false, Session.AUTO_ACKNOWLEDGE);
- _con.start();
- _consumer = _session.createConsumer(_destination);
- for (int i = 1; i <= NUM_MESSAGES; i++)
- {
- Message msg = _consumer.receive(RECEIVE_TIMEOUT);
- assertNotNull("Message " + i + " not received", msg);
- assertEquals("Did not receive the expected message", i, msg.getIntProperty(INDEX));
- }
-
- Message msg = _consumer.receive(100);
- if(msg != null)
- {
- fail("No more messages should be received, but received additional message with index: " + msg.getIntProperty(INDEX));
- }
- }
-
-// /**
-// * starts the server, sends 100 messages, restarts the server and gets 100 messages back
-// * the test formerly referred to as BDB-Qpid-1
-// * @throws Exception
-// */
-// public void testStartStop() throws Exception
-// {
-// restartBroker(); -- Not Currently a gracefull restart so not BDB-Qpid-1
-// checkMessages();
-// }
-
- /**
- * starts the server, sends 100 messages, nukes then starts the server and gets 100 messages back
- * the test formerly referred to as BDB-Qpid-2
- *
- * @throws Exception
- */
- public void testForcibleStartStop() throws Exception
- {
- restartBroker();
- checkMessages();
- }
-
-// /**
-// * starts the server, sends 100 committed messages, 5 uncommited ones,
-// * restarts the server and gets 100 messages back
-// * the test formerly referred to as BDB-Qpid-5
-// * @throws Exception
-// */
-// public void testStartStopMidTransaction() throws Exception
-// {
-// sendMessage(_session, _destination, 5);
-// restartBroker(); -- Not Currently a gracefull restart so not BDB-Qpid-1
-// checkMessages();
-// }
-
- /**
- * starts the server, sends 100 committed messages, 5 uncommited ones,
- * nukes and starts the server and gets 100 messages back
- * the test formerly referred to as BDB-Qpid-6
- *
- * @throws Exception
- */
- public void testForcibleStartStopMidTransaction() throws Exception
- {
- sendMessage(_session, _destination, 5);
- //sync to ensure that the above messages have reached the broker
- ((AMQSession) _session).sync();
- restartBroker();
- checkMessages();
- }
-
- /**
- * starts the server, sends 100 committed messages, 5 uncommited ones,
- * restarts the client and gets 100 messages back.
- * the test formerly referred to as BDB-Qpid-7
- *
- * FIXME: is this a PersistentStoreTest? Seems more like a transaction test to me.. aidan
- *
- * @throws Exception
- */
- public void testClientDeathMidTransaction() throws Exception
- {
- sendMessage(_session, _destination, 5);
- _con.close();
- checkMessages();
- }
-
-// /**
-// * starts the server, sends 50 committed messages, copies $QPID_WORK to a new location,
-// * sends 10 messages, stops the server, nukes the store, restores the copy, starts the server
-// * checks that we get the first 50 back.
-// */
-// public void testHotBackup()
-// {
-// -- removing as this will leave 100msgs on a queue
-// }
-
- /**
- * This test requires that we can send messages without commiting.
- * QTC always commits the messages sent via sendMessages.
- *
- * @param session the session to use for sending
- * @param destination where to send them to
- * @param count no. of messages to send
- *
- * @return the sent messges
- *
- * @throws Exception
- */
- @Override
- public List<Message> sendMessage(Session session, Destination destination,
- int count) throws Exception
- {
- List<Message> messages = new ArrayList<Message>(count);
-
- MessageProducer producer = session.createProducer(destination);
-
- for (int i = 1;i <= (count); i++)
- {
- Message next = createNextMessage(session, i);
-
- producer.send(next);
-
- messages.add(next);
- }
-
- return messages;
- }
-
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/server/store/SlowMessageStore.java b/java/systests/src/main/java/org/apache/qpid/server/store/SlowMessageStore.java
deleted file mode 100644
index a5c38e7e33..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/server/store/SlowMessageStore.java
+++ /dev/null
@@ -1,321 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.store;
-
-import org.apache.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.queue.AMQQueue;
-import org.apache.qpid.server.message.ServerMessage;
-import org.apache.qpid.server.logging.LogSubject;
-
-import java.util.HashMap;
-import java.util.Iterator;
-import java.nio.ByteBuffer;
-
-public class SlowMessageStore implements MessageStore
-{
- private static final Logger _logger = Logger.getLogger(SlowMessageStore.class);
- private static final String DELAYS = "delays";
- private HashMap<String, Long> _preDelays = new HashMap<String, Long>();
- private HashMap<String, Long> _postDelays = new HashMap<String, Long>();
- private long _defaultDelay = 0L;
- private MessageStore _realStore = new MemoryMessageStore();
- private static final String PRE = "pre";
- private static final String POST = "post";
- private String DEFAULT_DELAY = "default";
-
- // ***** MessageStore Interface.
-
- public void configureConfigStore(String name,
- ConfigurationRecoveryHandler recoveryHandler,
- Configuration config,
- LogSubject logSubject) throws Exception
- {
- //To change body of implemented methods use File | Settings | File Templates.
-
- _logger.info("Starting SlowMessageStore on Virtualhost:" + name);
- Configuration delays = config.subset(DELAYS);
-
- configureDelays(delays);
-
- String messageStoreClass = config.getString("realStore");
-
- if (delays.containsKey(DEFAULT_DELAY))
- {
- _defaultDelay = delays.getLong(DEFAULT_DELAY);
- }
-
- if (messageStoreClass != null)
- {
- Class clazz = Class.forName(messageStoreClass);
-
- Object o = clazz.newInstance();
-
- if (!(o instanceof MessageStore))
- {
- throw new ClassCastException("Message store class must implement " + MessageStore.class + ". Class " + clazz +
- " does not.");
- }
- _realStore = (MessageStore) o;
- _realStore.configureConfigStore(name, recoveryHandler, config, logSubject);
- }
- else
- {
- _realStore.configureConfigStore(name, recoveryHandler, config, logSubject);
- }
- }
-
- private void configureDelays(Configuration config)
- {
- Iterator delays = config.getKeys();
-
- while (delays.hasNext())
- {
- String key = (String) delays.next();
- if (key.endsWith(PRE))
- {
- _preDelays.put(key.substring(0, key.length() - PRE.length() - 1), config.getLong(key));
- }
- else if (key.endsWith(POST))
- {
- _postDelays.put(key.substring(0, key.length() - POST.length() - 1), config.getLong(key));
- }
- }
- }
-
- private void doPostDelay(String method)
- {
- long delay = lookupDelay(_postDelays, method);
- doDelay(delay);
- }
-
- private void doPreDelay(String method)
- {
- long delay = lookupDelay(_preDelays, method);
- doDelay(delay);
- }
-
- private long lookupDelay(HashMap<String, Long> delays, String method)
- {
- Long delay = delays.get(method);
- return (delay == null) ? _defaultDelay : delay;
- }
-
- private void doDelay(long delay)
- {
- if (delay > 0)
- {
- long start = System.nanoTime();
- try
- {
-
- Thread.sleep(delay);
- }
- catch (InterruptedException e)
- {
- _logger.warn("Interrupted : " + e);
- }
-
- long slept = (System.nanoTime() - start) / 1000000;
-
- if (slept >= delay)
- {
- _logger.info("Done sleep for:" + slept+":"+delay);
- }
- else
- {
- _logger.info("Only sleep for:" + slept + " re-sleeping");
- doDelay(delay - slept);
- }
- }
- }
-
-
- public void configureMessageStore(String name,
- MessageStoreRecoveryHandler recoveryHandler,
- Configuration config,
- LogSubject logSubject) throws Exception
- {
- _realStore.configureMessageStore(name, recoveryHandler, config, logSubject);
- }
-
- public void close() throws Exception
- {
- doPreDelay("close");
- _realStore.close();
- doPostDelay("close");
- }
-
- public <M extends StorableMessageMetaData> StoredMessage<M> addMessage(M metaData)
- {
- return _realStore.addMessage(metaData);
- }
-
-
- public void createExchange(Exchange exchange) throws AMQStoreException
- {
- doPreDelay("createExchange");
- _realStore.createExchange(exchange);
- doPostDelay("createExchange");
- }
-
- public void removeExchange(Exchange exchange) throws AMQStoreException
- {
- doPreDelay("removeExchange");
- _realStore.removeExchange(exchange);
- doPostDelay("removeExchange");
- }
-
- public void bindQueue(Exchange exchange, AMQShortString routingKey, AMQQueue queue, FieldTable args) throws AMQStoreException
- {
- doPreDelay("bindQueue");
- _realStore.bindQueue(exchange, routingKey, queue, args);
- doPostDelay("bindQueue");
- }
-
- public void unbindQueue(Exchange exchange, AMQShortString routingKey, AMQQueue queue, FieldTable args) throws AMQStoreException
- {
- doPreDelay("unbindQueue");
- _realStore.unbindQueue(exchange, routingKey, queue, args);
- doPostDelay("unbindQueue");
- }
-
- public void createQueue(AMQQueue queue) throws AMQStoreException
- {
- createQueue(queue, null);
- }
-
- public void createQueue(AMQQueue queue, FieldTable arguments) throws AMQStoreException
- {
- doPreDelay("createQueue");
- _realStore.createQueue(queue, arguments);
- doPostDelay("createQueue");
- }
-
- public void removeQueue(AMQQueue queue) throws AMQStoreException
- {
- doPreDelay("removeQueue");
- _realStore.removeQueue(queue);
- doPostDelay("removeQueue");
- }
-
- public void configureTransactionLog(String name,
- TransactionLogRecoveryHandler recoveryHandler,
- Configuration storeConfiguration, LogSubject logSubject)
- throws Exception
- {
- _realStore.configureTransactionLog(name, recoveryHandler, storeConfiguration, logSubject);
- }
-
- public Transaction newTransaction()
- {
- doPreDelay("beginTran");
- Transaction txn = new SlowTransaction(_realStore.newTransaction());
- doPostDelay("beginTran");
- return txn;
- }
-
-
- public boolean isPersistent()
- {
- return _realStore.isPersistent();
- }
-
- public void storeMessageHeader(Long messageNumber, ServerMessage message)
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void storeContent(Long messageNumber, long offset, ByteBuffer body)
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public ServerMessage getMessage(Long messageNumber)
- {
- return null; //To change body of implemented methods use File | Settings | File Templates.
- }
-
- private class SlowTransaction implements Transaction
- {
- private final Transaction _underlying;
-
- private SlowTransaction(Transaction underlying)
- {
- _underlying = underlying;
- }
-
- public void enqueueMessage(TransactionLogResource queue, Long messageId)
- throws AMQStoreException
- {
- doPreDelay("enqueueMessage");
- _underlying.enqueueMessage(queue, messageId);
- doPostDelay("enqueueMessage");
- }
-
- public void dequeueMessage(TransactionLogResource queue, Long messageId)
- throws AMQStoreException
- {
- doPreDelay("dequeueMessage");
- _underlying.dequeueMessage(queue, messageId);
- doPostDelay("dequeueMessage");
- }
-
- public void commitTran()
- throws AMQStoreException
- {
- doPreDelay("commitTran");
- _underlying.commitTran();
- doPostDelay("commitTran");
- }
-
- public StoreFuture commitTranAsync()
- throws AMQStoreException
- {
- doPreDelay("commitTran");
- StoreFuture future = _underlying.commitTranAsync();
- doPostDelay("commitTran");
- return future;
- }
-
- public void abortTran()
- throws AMQStoreException
- {
- doPreDelay("abortTran");
- _underlying.abortTran();
- doPostDelay("abortTran");
- }
- }
-
- public void updateQueue(AMQQueue queue) throws AMQStoreException
- {
- doPreDelay("updateQueue");
- _realStore.updateQueue(queue);
- doPostDelay("updateQueue");
- }
-
-
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/server/util/AveragedRun.java b/java/systests/src/main/java/org/apache/qpid/server/util/AveragedRun.java
deleted file mode 100644
index 1d17985ab5..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/server/util/AveragedRun.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.
- *
- */
-package org.apache.qpid.server.util;
-
-import org.apache.qpid.server.util.TimedRun;
-
-import java.util.concurrent.Callable;
-import java.util.Collection;
-
-public class AveragedRun implements Callable<RunStats>
-{
- private final RunStats stats = new RunStats();
- private final TimedRun test;
- private final int iterations;
-
- public AveragedRun(TimedRun test, int iterations)
- {
- this.test = test;
- this.iterations = iterations;
- }
-
- public RunStats call() throws Exception
- {
- for (int i = 0; i < iterations; i++)
- {
- stats.record(test.call());
- }
- return stats;
- }
-
- public void run() throws Exception
- {
- System.out.println(test + ": " + call());
- }
-
- public String toString()
- {
- return test.toString();
- }
-
- static void run(Collection<AveragedRun> tests) throws Exception
- {
- for(AveragedRun test : tests)
- {
- test.run();
- }
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/server/util/RunStats.java b/java/systests/src/main/java/org/apache/qpid/server/util/RunStats.java
deleted file mode 100644
index ec67fc68b3..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/server/util/RunStats.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.util;
-
-public class RunStats
-{
- private long min = Long.MAX_VALUE;
- private long max;
- private long total;
- private int count;
-
- public void record(long time)
- {
- max = Math.max(time, max);
- min = Math.min(time, min);
- total += time;
- count++;
- }
-
- public long getMin()
- {
- return min;
- }
-
- public long getMax()
- {
- return max;
- }
-
- public long getAverage()
- {
- return total / count;
- }
-
- public String toString()
- {
- return "avg=" + getAverage() + ", min=" + min + ", max=" + max;
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/server/util/TimedRun.java b/java/systests/src/main/java/org/apache/qpid/server/util/TimedRun.java
deleted file mode 100644
index 1291380311..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/server/util/TimedRun.java
+++ /dev/null
@@ -1,52 +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.concurrent.Callable;
-
-public abstract class TimedRun implements Callable<Long>
-{
- private final String description;
-
- public TimedRun(String description)
- {
- this.description = description;
- }
-
- public Long call() throws Exception
- {
- setup();
- long start = System.currentTimeMillis();
- run();
- long stop = System.currentTimeMillis();
- teardown();
- return stop - start;
- }
-
- public String toString()
- {
- return description;
- }
-
- protected void setup() throws Exception{}
- protected void teardown() throws Exception{}
- protected abstract void run() throws Exception;
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/systest/GlobalQueuesTest.java b/java/systests/src/main/java/org/apache/qpid/systest/GlobalQueuesTest.java
deleted file mode 100644
index 9ff143daf3..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/systest/GlobalQueuesTest.java
+++ /dev/null
@@ -1,223 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.systest;
-
-import org.apache.commons.configuration.ConfigurationException;
-
-import javax.jms.Session;
-import javax.naming.NamingException;
-import java.io.IOException;
-
-/**
- * QPID-1447 : Add slow consumer detection and disconnection.
- *
- * Slow consumers should on a topic should expect to receive a
- * 506 : Resource Error if the hit a predefined threshold.
- */
-public class GlobalQueuesTest extends TestingBaseCase
-{
-
- protected String CONFIG_SECTION = ".queues";
-
- /**
- * Queue Configuration
-
- <slow-consumer-detection>
- <!-- The depth before which the policy will be applied-->
- <depth>4235264</depth>
-
- <!-- The message age before which the policy will be applied-->
- <messageAge>600000</messageAge>
-
- <!-- The number of message before which the policy will be applied-->
- <messageCount>50</messageCount>
-
- <!-- Policies configuration -->
- <policy>
- <name>TopicDelete</name>
- <topicDelete>
- <delete-persistent/>
- </topicDelete>
- </policy>
- </slow-consumer-detection>
-
- */
-
-
- /**
- * VirtualHost Plugin Configuration
-
- <slow-consumer-detection>
- <delay>1</delay>
- <timeunit>MINUTES</timeunit>
- </slow-consumer-detection>
-
- */
-
- public void setConfig(String property, String value, boolean deleteDurable) throws NamingException, IOException, ConfigurationException
- {
- setProperty(CONFIG_SECTION + ".slow-consumer-detection." +
- "policy.name", "TopicDelete");
-
- setProperty(CONFIG_SECTION + ".slow-consumer-detection." +
- property, value);
-
- if (deleteDurable)
- {
- setProperty(CONFIG_SECTION + ".slow-consumer-detection." +
- "policy.topicdelete.delete-persistent", "");
- }
- }
-
- /**
- * Test that setting messageCount takes affect on topics
- *
- * We send 10 messages and disconnect at 9
- *
- * @throws Exception
- */
- public void testTopicConsumerMessageCount() throws Exception
- {
- MAX_QUEUE_MESSAGE_COUNT = 10;
-
- setConfig("messageCount", String.valueOf(MAX_QUEUE_MESSAGE_COUNT - 1), false);
-
- //Start the broker
- startBroker();
-
- topicConsumer(Session.AUTO_ACKNOWLEDGE, false);
- }
-
- /**
- * Test that setting depth has an effect on topics
- *
- * Sets the message size for the test
- * Sets the depth to be 9 * the depth
- * Ensure that sending 10 messages causes the disconnection
- *
- * @throws Exception
- */
- public void testTopicConsumerMessageSize() throws Exception
- {
- MAX_QUEUE_MESSAGE_COUNT = 10;
-
- setConfig("depth", String.valueOf(MESSAGE_SIZE * 9), false);
-
- //Start the broker
- startBroker();
-
- setMessageSize(MESSAGE_SIZE);
-
- topicConsumer(Session.AUTO_ACKNOWLEDGE, false);
- }
-
- /**
- * Test that setting messageAge has an effect on topics
- *
- * Sets the messageAge to be half the disconnection wait timeout
- * Send 10 messages and then ensure that we get disconnected as we will
- * wait for the full timeout.
- *
- * @throws Exception
- */
- public void testTopicConsumerMessageAge() throws Exception
- {
- MAX_QUEUE_MESSAGE_COUNT = 10;
-
- setConfig("messageAge", String.valueOf(DISCONNECTION_WAIT / 2), false);
-
- //Start the broker
- startBroker();
-
- topicConsumer(Session.AUTO_ACKNOWLEDGE, false);
- }
-
- /**
- * Test that setting messageCount takes affect on a durable Consumer
- *
- * Ensure we set the delete-persistent option
- *
- * We send 10 messages and disconnect at 9
- *
- * @throws Exception
- */
-
- public void testTopicDurableConsumerMessageCount() throws Exception
- {
- MAX_QUEUE_MESSAGE_COUNT = 10;
-
- setConfig("messageCount", String.valueOf(MAX_QUEUE_MESSAGE_COUNT - 1), true);
-
- //Start the broker
- startBroker();
-
- topicConsumer(Session.AUTO_ACKNOWLEDGE, true);
- }
-
- /**
- * Test that setting depth has an effect on durable consumer topics
- *
- * Ensure we set the delete-persistent option
- *
- * Sets the message size for the test
- * Sets the depth to be 9 * the depth
- * Ensure that sending 10 messages causes the disconnection
- *
- * @throws Exception
- */
- public void testTopicDurableConsumerMessageSize() throws Exception
- {
- MAX_QUEUE_MESSAGE_COUNT = 10;
-
- setConfig("depth", String.valueOf(MESSAGE_SIZE * 9), true);
-
- //Start the broker
- startBroker();
-
- setMessageSize(MESSAGE_SIZE);
-
- topicConsumer(Session.AUTO_ACKNOWLEDGE, true);
- }
-
- /**
- * Test that setting messageAge has an effect on topics
- *
- * Ensure we set the delete-persistent option
- *
- * Sets the messageAge to be 1/5 the disconnection wait timeout (or 1sec)
- * Send 10 messages and then ensure that we get disconnected as we will
- * wait for the full timeout.
- *
- * @throws Exception
- */
- public void testTopicDurableConsumerMessageAge() throws Exception
- {
- MAX_QUEUE_MESSAGE_COUNT = 10;
-
- setConfig("messageAge", String.valueOf(DISCONNECTION_WAIT / 5), true);
-
- //Start the broker
- startBroker();
-
- topicConsumer(Session.AUTO_ACKNOWLEDGE, true);
- }
-
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/systest/GlobalTopicsTest.java b/java/systests/src/main/java/org/apache/qpid/systest/GlobalTopicsTest.java
deleted file mode 100644
index aff5d1b1b8..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/systest/GlobalTopicsTest.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.systest;
-
-import org.apache.commons.configuration.ConfigurationException;
-
-import javax.naming.NamingException;
-import java.io.IOException;
-
-public class GlobalTopicsTest extends GlobalQueuesTest
-{
- @Override
- public void setUp() throws Exception
- {
- CONFIG_SECTION = ".topics";
- super.setUp();
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/systest/MergeConfigurationTest.java b/java/systests/src/main/java/org/apache/qpid/systest/MergeConfigurationTest.java
deleted file mode 100644
index e4efac60f8..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/systest/MergeConfigurationTest.java
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.systest;
-
-import org.apache.commons.configuration.ConfigurationException;
-import org.apache.qpid.AMQChannelClosedException;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.AMQSession_0_10;
-import org.apache.qpid.jms.ConnectionListener;
-import org.apache.qpid.protocol.AMQConstant;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-import javax.jms.Connection;
-import javax.jms.Destination;
-import javax.jms.ExceptionListener;
-import javax.jms.JMSException;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-import javax.jms.Session;
-import javax.jms.Topic;
-import javax.naming.NamingException;
-import java.io.IOException;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-public class MergeConfigurationTest extends TestingBaseCase
-{
-
- protected int topicCount = 0;
-
-
- public void configureTopic(String topic, int msgCount) throws NamingException, IOException, ConfigurationException
- {
-
- setProperty(".topics.topic("+topicCount+").name", topic);
- setProperty(".topics.topic("+topicCount+").slow-consumer-detection.messageCount", String.valueOf(msgCount));
- setProperty(".topics.topic("+topicCount+").slow-consumer-detection.policy.name", "TopicDelete");
- topicCount++;
- }
-
-
- /**
- * Test that setting messageCount takes affect on topics
- *
- * We send 10 messages and disconnect at 9
- *
- * @throws Exception
- */
- public void testTopicConsumerMessageCount() throws Exception
- {
- MAX_QUEUE_MESSAGE_COUNT = 10;
-
- configureTopic(getName(), (MAX_QUEUE_MESSAGE_COUNT * 4) - 1);
-
- //Configure topic as a subscription
- setProperty(".topics.topic("+topicCount+").subscriptionName", "clientid:"+getTestQueueName());
- configureTopic(getName(), (MAX_QUEUE_MESSAGE_COUNT - 1));
-
-
-
- //Start the broker
- startBroker();
-
- topicConsumer(Session.AUTO_ACKNOWLEDGE, true);
- }
-
-
-//
-// public void testMerge() throws ConfigurationException, AMQException
-// {
-//
-// AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(new AMQShortString(getName()+":stockSubscription"), false, new AMQShortString("testowner"),
-// false, false, _virtualHost, null);
-//
-// _virtualHost.getQueueRegistry().registerQueue(queue);
-// Exchange defaultExchange = _virtualHost.getExchangeRegistry().getDefaultExchange();
-// _virtualHost.getBindingFactory().addBinding(getName(), queue, defaultExchange, null);
-//
-//
-// Exchange topicExchange = _virtualHost.getExchangeRegistry().getExchange(ExchangeDefaults.TOPIC_EXCHANGE_NAME);
-// _virtualHost.getBindingFactory().addBinding("stocks.nyse.orcl", queue, topicExchange, null);
-//
-// TopicConfig config = queue.getConfiguration().getConfiguration(TopicConfig.class.getName());
-//
-// assertNotNull("Queue should have topic configuration bound to it.", config);
-// assertEquals("Configuration name not correct", getName() + ":stockSubscription", config.getSubscriptionName());
-//
-// ConfigurationPlugin scdConfig = queue.getConfiguration().getConfiguration(SlowConsumerDetectionQueueConfiguration.class.getName());
-// if (scdConfig instanceof org.apache.qpid.server.configuration.plugin.SlowConsumerDetectionQueueConfiguration)
-// {
-// System.err.println("********************** scd is a SlowConsumerDetectionQueueConfiguration.");
-// }
-// else
-// {
-// System.err.println("********************** Test SCD "+SlowConsumerDetectionQueueConfiguration.class.getClassLoader());
-// System.err.println("********************** Broker SCD "+scdConfig.getClass().getClassLoader());
-// System.err.println("********************** Broker SCD "+scdConfig.getClass().isAssignableFrom(SlowConsumerDetectionQueueConfiguration.class));
-// System.err.println("********************** is a "+scdConfig.getClass());
-// }
-//
-// assertNotNull("Queue should have scd configuration bound to it.", scdConfig);
-// assertEquals("MessageCount is not correct", 10 , ((SlowConsumerDetectionQueueConfiguration)scdConfig).getMessageCount());
-// assertEquals("Policy is not correct", TopicDeletePolicy.class.getName() , ((SlowConsumerDetectionQueueConfiguration)scdConfig).getPolicy().getClass().getName());
-// }
-
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/systest/SubscriptionTest.java b/java/systests/src/main/java/org/apache/qpid/systest/SubscriptionTest.java
deleted file mode 100644
index 9e9375fd44..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/systest/SubscriptionTest.java
+++ /dev/null
@@ -1,146 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.systest;
-
-import org.apache.commons.configuration.ConfigurationException;
-
-import javax.jms.Session;
-import javax.naming.NamingException;
-import java.io.IOException;
-
-/**
- * Test SCD when configured with Subscription details.
- *
- * We run the subscription based tests here to validate that the
- * subscriptionname value is correctly associated with the subscription.
- *
- *
- */
-public class SubscriptionTest extends TestingBaseCase
-{
- private int _count=0;
- protected String CONFIG_SECTION = ".topics.topic";
-
- /**
- * Add configuration for the queue that relates just to this test.
- * We use the getTestQueueName() as our subscription. To ensure the
- * config sections do not overlap we identify each section with a _count
- * value.
- *
- * This would allow each test to configure more than one section.
- *
- * @param property to set
- * @param value the value to set
- * @param deleteDurable should deleteDurable be set.
- * @throws NamingException
- * @throws IOException
- * @throws ConfigurationException
- */
- public void setConfig(String property, String value, boolean deleteDurable) throws NamingException, IOException, ConfigurationException
- {
- setProperty(CONFIG_SECTION + "("+_count+").subscriptionName", "clientid:"+getTestQueueName());
-
- setProperty(CONFIG_SECTION + "("+_count+").slow-consumer-detection." +
- "policy.name", "TopicDelete");
-
- setProperty(CONFIG_SECTION + "("+_count+").slow-consumer-detection." +
- property, value);
-
- if (deleteDurable)
- {
- setProperty(CONFIG_SECTION + "("+_count+").slow-consumer-detection." +
- "policy.topicdelete.delete-persistent", "");
- }
- _count++;
- }
-
-
- /**
- * Test that setting messageCount takes affect on a durable Consumer
- *
- * Ensure we set the delete-persistent option
- *
- * We send 10 messages and disconnect at 9
- *
- * @throws Exception
- */
-
- public void testTopicDurableConsumerMessageCount() throws Exception
- {
- MAX_QUEUE_MESSAGE_COUNT = 10;
-
- setConfig("messageCount", String.valueOf(MAX_QUEUE_MESSAGE_COUNT - 1), true);
-
- //Start the broker
- startBroker();
-
- topicConsumer(Session.AUTO_ACKNOWLEDGE, true);
- }
-
- /**
- * Test that setting depth has an effect on durable consumer topics
- *
- * Ensure we set the delete-persistent option
- *
- * Sets the message size for the test
- * Sets the depth to be 9 * the depth
- * Ensure that sending 10 messages causes the disconnection
- *
- * @throws Exception
- */
- public void testTopicDurableConsumerMessageSize() throws Exception
- {
- MAX_QUEUE_MESSAGE_COUNT = 10;
-
- setConfig("depth", String.valueOf(MESSAGE_SIZE * 9), true);
-
- //Start the broker
- startBroker();
-
- setMessageSize(MESSAGE_SIZE);
-
- topicConsumer(Session.AUTO_ACKNOWLEDGE, true);
- }
-
- /**
- * Test that setting messageAge has an effect on topics
- *
- * Ensure we set the delete-persistent option
- *
- * Sets the messageAge to be 1/5 the disconnection wait timeout (or 1sec)
- * Send 10 messages and then ensure that we get disconnected as we will
- * wait for the full timeout.
- *
- * @throws Exception
- */
- public void testTopicDurableConsumerMessageAge() throws Exception
- {
- MAX_QUEUE_MESSAGE_COUNT = 10;
-
- setConfig("messageAge", String.valueOf(DISCONNECTION_WAIT / 5), true);
-
- //Start the broker
- startBroker();
-
- topicConsumer(Session.AUTO_ACKNOWLEDGE, true);
- }
-
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/systest/TestingBaseCase.java b/java/systests/src/main/java/org/apache/qpid/systest/TestingBaseCase.java
deleted file mode 100644
index 08a7b7a6e5..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/systest/TestingBaseCase.java
+++ /dev/null
@@ -1,241 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.systest;
-
-import org.apache.commons.configuration.ConfigurationException;
-import org.apache.qpid.AMQChannelClosedException;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.AMQSession_0_10;
-import org.apache.qpid.jms.ConnectionListener;
-import org.apache.qpid.protocol.AMQConstant;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-import javax.jms.Connection;
-import javax.jms.Destination;
-import javax.jms.ExceptionListener;
-import javax.jms.JMSException;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-import javax.jms.Session;
-import javax.jms.Topic;
-import javax.naming.NamingException;
-import java.io.IOException;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-public class TestingBaseCase extends QpidBrokerTestCase implements ExceptionListener, ConnectionListener
-{
-
- Topic _destination;
- protected CountDownLatch _disconnectionLatch = new CountDownLatch(1);
- protected int MAX_QUEUE_MESSAGE_COUNT;
- protected int MESSAGE_SIZE = DEFAULT_MESSAGE_SIZE;
-
- private Thread _publisher;
- protected static final long DISCONNECTION_WAIT = 5;
- protected Exception _publisherError = null;
- protected JMSException _connectionException = null;
- private static final long JOIN_WAIT = 5000;
-
- @Override
- public void setUp() throws Exception
- {
-
- setConfigurationProperty("virtualhosts.virtualhost."
- + getConnectionURL().getVirtualHost().substring(1) +
- ".slow-consumer-detection.delay", "1");
-
- setConfigurationProperty("virtualhosts.virtualhost."
- + getConnectionURL().getVirtualHost().substring(1) +
- ".slow-consumer-detection.timeunit", "SECONDS");
-
- }
-
-
- protected void setProperty(String property, String value) throws NamingException, IOException, ConfigurationException
- {
- setConfigurationProperty("virtualhosts.virtualhost." +
- getConnectionURL().getVirtualHost().substring(1) +
- property, value);
- }
-
-
- /**
- * Create and start an asynchrounous publisher that will send MAX_QUEUE_MESSAGE_COUNT
- * messages to the provided destination. Messages are sent in a new connection
- * on a transaction. Any error is captured and the test is signalled to exit.
- *
- * @param destination
- */
- private void startPublisher(final Destination destination)
- {
- _publisher = new Thread(new Runnable()
- {
-
- public void run()
- {
- try
- {
- Connection connection = getConnection();
- Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
-
- MessageProducer publisher = session.createProducer(destination);
-
- for (int count = 0; count < MAX_QUEUE_MESSAGE_COUNT; count++)
- {
- publisher.send(createNextMessage(session, count));
- session.commit();
- }
- }
- catch (Exception e)
- {
- _publisherError = e;
- _disconnectionLatch.countDown();
- }
- }
- });
-
- _publisher.start();
- }
-
-
-
- /**
- * Perform the Main test of a topic Consumer with the given AckMode.
- *
- * Test creates a new connection and sets up the connection to prevent
- * failover
- *
- * A new consumer is connected and started so that it will prefetch msgs.
- *
- * An asynchrounous publisher is started to fill the broker with messages.
- *
- * We then wait to be notified of the disconnection via the ExceptionListener
- *
- * 0-10 does not have the same notification paths but sync() apparently should
- * give us the exception, currently it doesn't, so the test is excluded from 0-10
- *
- * We should ensure that this test has the same path for all protocol versions.
- *
- * Clients should not have to modify their code based on the protocol in use.
- *
- * @param ackMode @see javax.jms.Session
- *
- * @throws Exception
- */
- protected void topicConsumer(int ackMode, boolean durable) throws Exception
- {
- Connection connection = getConnection();
-
- connection.setExceptionListener(this);
-
- Session session = connection.createSession(ackMode == Session.SESSION_TRANSACTED, ackMode);
-
- _destination = session.createTopic(getName());
-
- MessageConsumer consumer;
-
- if (durable)
- {
- consumer = session.createDurableSubscriber(_destination, getTestQueueName());
- }
- else
- {
- consumer = session.createConsumer(_destination);
- }
-
- connection.start();
-
- // Start the consumer pre-fetching
- // Don't care about response as we will fill the broker up with messages
- // after this point and ensure that the client is disconnected at the
- // right point.
- consumer.receiveNoWait();
- startPublisher(_destination);
-
- boolean disconnected = _disconnectionLatch.await(DISCONNECTION_WAIT, TimeUnit.SECONDS);
-
- assertTrue("Client was not disconnected", disconnected);
- assertTrue("Client was not disconnected.", _connectionException != null);
-
- Exception linked = _connectionException.getLinkedException();
-
- _publisher.join(JOIN_WAIT);
-
- assertFalse("Publisher still running", _publisher.isAlive());
-
- //Validate publishing occurred ok
- if (_publisherError != null)
- {
- throw _publisherError;
- }
-
- // NOTE these exceptions will need to be modeled so that they are not
- // 0-8 specific. e.g. JMSSessionClosedException
-
- assertNotNull("No error received onException listener.", _connectionException);
-
- assertNotNull("No linked exception set on:" + _connectionException.getMessage(), linked);
-
- assertTrue("Incorrect linked exception received.", linked instanceof AMQException);
-
- AMQException amqException = (AMQException) linked;
-
- assertEquals("Channel was not closed with correct code.", AMQConstant.RESOURCE_ERROR, amqException.getErrorCode());
- }
-
-
- // Exception Listener
-
- public void onException(JMSException e)
- {
- _connectionException = e;
-
- e.printStackTrace();
-
- _disconnectionLatch.countDown();
- }
-
- /// Connection Listener
-
- public void bytesSent(long count)
- {
- }
-
- public void bytesReceived(long count)
- {
- }
-
- public boolean preFailover(boolean redirect)
- {
- // Prevent Failover
- return false;
- }
-
- public boolean preResubscribe()
- {
- return false;
- }
-
- public void failoverComplete()
- {
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/systest/TopicTest.java b/java/systests/src/main/java/org/apache/qpid/systest/TopicTest.java
deleted file mode 100644
index 09c849cfde..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/systest/TopicTest.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.systest;
-
-import org.apache.commons.configuration.ConfigurationException;
-
-import javax.naming.NamingException;
-import java.io.IOException;
-
-/**
- * This Topic test extends the Global queue test so it will run all the topic
- * and subscription tests.
- *
- * We redefine the CONFIG_SECTION here so that the configuration is written
- * against a topic element.
- *
- * To complete the migration to testing 'topic' elements we also override
- * the setConfig to use the test name as the topic name.
- *
- */
-public class TopicTest extends GlobalQueuesTest
-{
- private int _count=0;
-
- @Override
- public void setUp() throws Exception
- {
- CONFIG_SECTION = ".topics.topic";
- super.setUp();
- }
-
- /**
- * Add configuration for the queue that relates just to this test.
- * We use the getTestQueueName() as our subscription. To ensure the
- * config sections do not overlap we identify each section with a _count
- * value.
- *
- * This would allow each test to configure more than one section.
- *
- * @param property to set
- * @param value the value to set
- * @param deleteDurable should deleteDurable be set.
- * @throws NamingException
- * @throws IOException
- * @throws ConfigurationException
- */
- @Override
- public void setConfig(String property, String value, boolean deleteDurable) throws NamingException, IOException, ConfigurationException
- {
- setProperty(CONFIG_SECTION + "("+_count+").name", getName());
-
- setProperty(CONFIG_SECTION + "("+_count+").slow-consumer-detection." +
- "policy.name", "TopicDelete");
-
- setProperty(CONFIG_SECTION + "("+_count+").slow-consumer-detection." +
- property, value);
-
- if (deleteDurable)
- {
- setProperty(CONFIG_SECTION + "("+_count+").slow-consumer-detection." +
- "policy.topicdelete.delete-persistent", "");
- }
- _count++;
- }
-
-
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/client/CancelTest.java b/java/systests/src/main/java/org/apache/qpid/test/client/CancelTest.java
deleted file mode 100644
index 13a9dd73b8..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/client/CancelTest.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.test.client;
-
-import org.apache.log4j.Logger;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-import javax.jms.Connection;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-import javax.jms.Queue;
-import javax.jms.QueueBrowser;
-import javax.jms.Session;
-import java.util.Enumeration;
-
-public class CancelTest extends QpidBrokerTestCase
-{
- private static final Logger _logger = Logger.getLogger(CancelTest.class);
-
- private Connection _clientConnection;
- private Session _clientSession;
- private Queue _queue;
-
- public void setUp() throws Exception
- {
-
- super.setUp();
-
- _queue = (Queue) getInitialContext().lookup("queue");
-
- //Create Client
- _clientConnection = getConnection();
-
- _clientConnection.start();
-
- _clientSession = _clientConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- //Ensure _queue is created
- _clientSession.createConsumer(_queue).close();
- }
-
- /**
- * Simply
- * This test originally did not assert anything but was just checking
- * that a message could be browsed and consumed without throwing an exception.
- * It now checks that at least a message is browsed and that a message is received.
- */
- public void test() throws Exception
- {
- Connection producerConnection = getConnection();
-
- producerConnection.start();
-
- Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- MessageProducer producer = producerSession.createProducer(_queue);
- producer.send(producerSession.createTextMessage());
- producerConnection.close();
-
-
- QueueBrowser browser = _clientSession.createBrowser(_queue);
- Enumeration e = browser.getEnumeration();
-
- assertTrue(e.hasMoreElements());
-
- int i = 0;
- while (e.hasMoreElements())
- {
- e.nextElement();
- if(++i > 1)
- {
- fail("Two many elemnts to browse!");
- }
- }
-
- browser.close();
-
- MessageConsumer consumer = _clientSession.createConsumer(_queue);
- assertNotNull( consumer.receive() );
- consumer.close();
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/client/DupsOkTest.java b/java/systests/src/main/java/org/apache/qpid/test/client/DupsOkTest.java
deleted file mode 100644
index a94d975a32..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/client/DupsOkTest.java
+++ /dev/null
@@ -1,167 +0,0 @@
-package org.apache.qpid.test.client;
-
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.apache.qpid.client.AMQDestination;
-import org.apache.qpid.client.AMQSession;
-
-import javax.jms.Connection;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageListener;
-import javax.jms.MessageProducer;
-import javax.jms.Queue;
-import javax.jms.Session;
-import javax.jms.TextMessage;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-/*
-*
-* 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 DupsOkTest extends QpidBrokerTestCase
-{
-
- private Queue _queue;
- private static final int MSG_COUNT = 100;
- private CountDownLatch _awaitCompletion = new CountDownLatch(1);
-
- public void setUp() throws Exception
- {
- super.setUp();
-
- _queue = (Queue) getInitialContext().lookup("queue");
-
-
- //Declare the queue
- Connection consumerConnection = getConnection();
- consumerConnection.createSession(false,Session.AUTO_ACKNOWLEDGE).createConsumer(_queue).close();
-
- //Create Producer put some messages on the queue
- Connection producerConnection = getConnection();
-
- producerConnection.start();
-
- Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- MessageProducer producer = producerSession.createProducer(_queue);
-
- for (int count = 1; count <= MSG_COUNT; count++)
- {
- Message msg = producerSession.createTextMessage("Message " + count);
- msg.setIntProperty("count", count);
- producer.send(msg);
- }
-
- producerConnection.close();
- }
-
- /**
- * This test sends x messages and receives them with an async consumer.
- * Waits for all messages to be received or for 60 s
- * and checks whether the queue is empty.
- *
- * @throws Exception
- */
- public void testDupsOK() throws Exception
- {
- //Create Client
- Connection clientConnection = getConnection();
-
- final Session clientSession = clientConnection.createSession(false, Session.DUPS_OK_ACKNOWLEDGE);
-
- MessageConsumer consumer = clientSession.createConsumer(_queue);
-
- assertEquals("The queue should have msgs at start", MSG_COUNT, ((AMQSession) clientSession).getQueueDepth((AMQDestination) _queue));
-
- clientConnection.start();
-
- consumer.setMessageListener(new MessageListener()
- {
- int _msgCount = 0;
-
- public void onMessage(Message message)
- {
- _msgCount++;
- if (message == null)
- {
- fail("Should not get null messages");
- }
-
- if (message instanceof TextMessage)
- {
- try
- {
- if (message.getIntProperty("count") == MSG_COUNT)
- {
- try
- {
- if(_msgCount != MSG_COUNT)
- {
- assertEquals("Wrong number of messages seen.", MSG_COUNT, _msgCount);
- }
- }
- finally
- {
- //This is the last message so release test.
- _awaitCompletion.countDown();
- }
- }
- }
- catch (JMSException e)
- {
- fail("Unable to get int property 'count'");
- }
- }
- else
- {
- fail("Got wrong message type");
- }
- }
- });
-
- try
- {
- if (!_awaitCompletion.await(120, TimeUnit.SECONDS))
- {
- fail("Test did not complete in 120 seconds");
- }
- }
- catch (InterruptedException e)
- {
- fail("Unable to wait for test completion");
- throw e;
- }
-
- //Close consumer to give broker time to process in bound Acks. As The main thread will be released while
- // before the dispatcher has sent the ack back to the broker.
- consumer.close();
-
- clientSession.close();
-
- final Session clientSession2 = clientConnection.createSession(false, Session.DUPS_OK_ACKNOWLEDGE);
-
- assertEquals("The queue should have 0 msgs left", 0, ((AMQSession) clientSession2).getQueueDepth((AMQDestination) _queue));
-
- clientConnection.close();
- }
-
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/client/FlowControlTest.java b/java/systests/src/main/java/org/apache/qpid/test/client/FlowControlTest.java
deleted file mode 100644
index e1f639afb6..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/client/FlowControlTest.java
+++ /dev/null
@@ -1,213 +0,0 @@
-/*
-*
-* Licensed to the Apache Software Foundation (ASF) under one
-* or more contributor license agreements. See the NOTICE file
-* distributed with this work for additional information
-* regarding copyright ownership. The ASF licenses this file
-* to you under the Apache License, Version 2.0 (the
-* "License"); you may not use this file except in compliance
-* with the License. You may obtain a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing,
-* software distributed under the License is distributed on an
-* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-* KIND, either express or implied. See the License for the
-* specific language governing permissions and limitations
-* under the License.
-*
-*/
-package org.apache.qpid.test.client;
-
-import org.apache.qpid.client.AMQSession_0_8;
-import org.apache.qpid.client.message.AbstractJMSMessage;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.apache.log4j.Logger;
-
-import javax.jms.*;
-
-public class FlowControlTest extends QpidBrokerTestCase
-{
- private static final Logger _logger = Logger.getLogger(FlowControlTest.class);
-
- private Connection _clientConnection;
- private Session _clientSession;
- private Queue _queue;
-
- /**
- * Simply
- *
- * @throws Exception
- */
- public void testBasicBytesFlowControl() throws Exception
- {
- _queue = (Queue) getInitialContext().lookup("queue");
-
- //Create Client
- _clientConnection = getConnection();
-
- _clientConnection.start();
-
- _clientSession = _clientConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- //Ensure _queue is created
- _clientSession.createConsumer(_queue).close();
-
- Connection producerConnection = getConnection();
-
- producerConnection.start();
-
- Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- MessageProducer producer = producerSession.createProducer(_queue);
-
- BytesMessage m1 = producerSession.createBytesMessage();
- m1.writeBytes(new byte[128]);
- m1.setIntProperty("msg", 1);
- producer.send(m1);
- BytesMessage m2 = producerSession.createBytesMessage();
- m2.writeBytes(new byte[128]);
- m2.setIntProperty("msg", 2);
- producer.send(m2);
- BytesMessage m3 = producerSession.createBytesMessage();
- m3.writeBytes(new byte[256]);
- m3.setIntProperty("msg", 3);
- producer.send(m3);
-
- producer.close();
- producerSession.close();
- producerConnection.close();
-
- Connection consumerConnection = getConnection();
- Session consumerSession = consumerConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
- ((AMQSession_0_8) consumerSession).setPrefetchLimits(0, 256);
- MessageConsumer recv = consumerSession.createConsumer(_queue);
- consumerConnection.start();
-
- Message r1 = recv.receive(RECEIVE_TIMEOUT);
- assertNotNull("First message not received", r1);
- assertEquals("Messages in wrong order", 1, r1.getIntProperty("msg"));
-
- Message r2 = recv.receive(RECEIVE_TIMEOUT);
- assertNotNull("Second message not received", r2);
- assertEquals("Messages in wrong order", 2, r2.getIntProperty("msg"));
-
- Message r3 = recv.receive(RECEIVE_TIMEOUT);
- assertNull("Third message incorrectly delivered", r3);
-
- ((AbstractJMSMessage)r1).acknowledgeThis();
-
- r3 = recv.receive(RECEIVE_TIMEOUT);
- assertNull("Third message incorrectly delivered", r3);
-
- ((AbstractJMSMessage)r2).acknowledgeThis();
-
- r3 = recv.receive(RECEIVE_TIMEOUT);
- assertNotNull("Third message not received", r3);
- assertEquals("Messages in wrong order", 3, r3.getIntProperty("msg"));
-
- ((AbstractJMSMessage)r3).acknowledgeThis();
- consumerConnection.close();
- }
-
- public void testTwoConsumersBytesFlowControl() throws Exception
- {
- _queue = (Queue) getInitialContext().lookup("queue");
-
- //Create Client
- _clientConnection = getConnection();
-
- _clientConnection.start();
-
- _clientSession = _clientConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- //Ensure _queue is created
- _clientSession.createConsumer(_queue).close();
-
- Connection producerConnection = getConnection();
-
- producerConnection.start();
-
- Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- MessageProducer producer = producerSession.createProducer(_queue);
-
- BytesMessage m1 = producerSession.createBytesMessage();
- m1.writeBytes(new byte[128]);
- m1.setIntProperty("msg", 1);
- producer.send(m1);
- BytesMessage m2 = producerSession.createBytesMessage();
- m2.writeBytes(new byte[256]);
- m2.setIntProperty("msg", 2);
- producer.send(m2);
- BytesMessage m3 = producerSession.createBytesMessage();
- m3.writeBytes(new byte[128]);
- m3.setIntProperty("msg", 3);
- producer.send(m3);
-
- producer.close();
- producerSession.close();
- producerConnection.close();
-
- Connection consumerConnection = getConnection();
- Session consumerSession1 = consumerConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
- ((AMQSession_0_8) consumerSession1).setPrefetchLimits(0, 256);
- MessageConsumer recv1 = consumerSession1.createConsumer(_queue);
-
- consumerConnection.start();
-
- Message r1 = recv1.receive(RECEIVE_TIMEOUT);
- assertNotNull("First message not received", r1);
- assertEquals("Messages in wrong order", 1, r1.getIntProperty("msg"));
-
- Message r2 = recv1.receive(RECEIVE_TIMEOUT);
- assertNull("Second message incorrectly delivered", r2);
-
- Session consumerSession2 = consumerConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
- ((AMQSession_0_8) consumerSession2).setPrefetchLimits(0, 256);
- MessageConsumer recv2 = consumerSession2.createConsumer(_queue);
-
- r2 = recv2.receive(RECEIVE_TIMEOUT);
- assertNotNull("Second message not received", r2);
- assertEquals("Messages in wrong order", 2, r2.getIntProperty("msg"));
-
- Message r3 = recv2.receive(RECEIVE_TIMEOUT);
- assertNull("Third message incorrectly delivered", r3);
-
- r3 = recv1.receive(RECEIVE_TIMEOUT);
- assertNotNull("Third message not received", r3);
- assertEquals("Messages in wrong order", 3, r3.getIntProperty("msg"));
-
- r2.acknowledge();
- r3.acknowledge();
- recv1.close();
- recv2.close();
- consumerSession1.close();
- consumerSession2.close();
- consumerConnection.close();
-
- }
-
- public static void main(String args[]) throws Throwable
- {
- FlowControlTest test = new FlowControlTest();
-
- int run = 0;
- while (true)
- {
- System.err.println("Test Run:" + ++run);
- Thread.sleep(1000);
- try
- {
- test.startBroker();
- test.testBasicBytesFlowControl();
-
- Thread.sleep(1000);
- }
- finally
- {
- test.stopBroker();
- }
- }
- }
-}
-
diff --git a/java/systests/src/main/java/org/apache/qpid/test/client/QueueBrowserAutoAckTest.java b/java/systests/src/main/java/org/apache/qpid/test/client/QueueBrowserAutoAckTest.java
deleted file mode 100644
index 97d825177c..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/client/QueueBrowserAutoAckTest.java
+++ /dev/null
@@ -1,528 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- *
- */
-package org.apache.qpid.test.client;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQDestination;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.test.utils.FailoverBaseCase;
-
-import javax.jms.Connection;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-import javax.jms.Queue;
-import javax.jms.QueueBrowser;
-import javax.jms.Session;
-import javax.jms.TextMessage;
-import javax.naming.NamingException;
-import java.util.Enumeration;
-import java.util.Random;
-
-public class QueueBrowserAutoAckTest extends FailoverBaseCase
-{
- protected Connection _clientConnection;
- protected Session _clientSession;
- protected Queue _queue;
- protected static final String MESSAGE_ID_PROPERTY = "MessageIDProperty";
- protected boolean CLUSTERED = Boolean.getBoolean("profile.clustered");
-
- public void setUp() throws Exception
- {
- super.setUp();
-
- //Create Client
- _clientConnection = getConnection();
- _clientConnection.start();
-
- setupSession();
-
- _queue = _clientSession.createQueue(getTestQueueName());
- _clientSession.createConsumer(_queue).close();
-
- //Ensure there are no messages on the queue to start with.
- checkQueueDepth(0);
- }
-
- protected void setupSession() throws Exception
- {
- _clientSession = _clientConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- }
-
- public void tearDown() throws Exception
- {
- if (_clientConnection != null)
- {
- _clientConnection.close();
- }
-
- super.tearDown();
- }
-
- protected void sendMessages(int num) throws JMSException
- {
- Connection producerConnection = null;
- try
- {
- producerConnection = getConnection();
- }
- catch (Exception e)
- {
- fail("Unable to lookup connection in JNDI.");
- }
-
- sendMessages(producerConnection, num);
- }
-
- protected void sendMessages(String connection, int num) throws JMSException
- {
- Connection producerConnection = null;
- try
- {
- producerConnection = getConnectionFactory(connection).createConnection("guest", "guest");
- }
- catch (Exception e)
- {
- e.printStackTrace();
- fail("Unable to lookup connection in JNDI.");
- }
- sendMessages(producerConnection, num);
- }
-
-
- protected void sendMessages(Connection producerConnection, int messageSendCount) throws JMSException
- {
- producerConnection.start();
-
- Session producerSession = producerConnection.createSession(true, Session.AUTO_ACKNOWLEDGE);
-
- //Ensure _queue is created
- producerSession.createConsumer(_queue).close();
-
- MessageProducer producer = producerSession.createProducer(_queue);
-
- for (int messsageID = 0; messsageID < messageSendCount; messsageID++)
- {
- TextMessage textMsg = producerSession.createTextMessage("Message " + messsageID);
- textMsg.setIntProperty(MESSAGE_ID_PROPERTY, messsageID);
- producer.send(textMsg);
- }
- producerSession.commit();
-
- producerConnection.close();
- }
-
- /**
- * Using the Protocol getQueueDepth method ensure that the correct number of messages are on the queue.
- *
- * Also uses a QueueBrowser as a second method of validating the message count on the queue.
- *
- * @param expectedDepth The expected Queue depth
- * @throws JMSException on error
- */
- protected void checkQueueDepth(int expectedDepth) throws JMSException
- {
-
- // create QueueBrowser
- _logger.info("Creating Queue Browser");
-
- QueueBrowser queueBrowser = _clientSession.createBrowser(_queue);
-
- // check for messages
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Checking for " + expectedDepth + " messages with QueueBrowser");
- }
-
- //Check what the session believes the queue count to be.
- long queueDepth = 0;
-
- try
- {
- queueDepth = ((AMQSession) _clientSession).getQueueDepth((AMQDestination) _queue);
- }
- catch (AMQException e)
- {
- }
-
- assertEquals("Session reports Queue expectedDepth not as expected", expectedDepth, queueDepth);
-
-
-
- // Browse the queue to get a second opinion
- int msgCount = 0;
- Enumeration msgs = queueBrowser.getEnumeration();
-
- while (msgs.hasMoreElements())
- {
- msgs.nextElement();
- msgCount++;
- }
-
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Found " + msgCount + " messages total in browser");
- }
-
- // check to see if all messages found
- assertEquals("Browser did not find all messages", expectedDepth, msgCount);
-
- //Close browser
- queueBrowser.close();
- }
-
- protected void closeBrowserBeforeAfterGetNext(int messageCount) throws JMSException
- {
- QueueBrowser queueBrowser = _clientSession.createBrowser(_queue);
-
- Enumeration msgs = queueBrowser.getEnumeration();
-
- int msgCount = 0;
-
- while (msgs.hasMoreElements() && msgCount < messageCount)
- {
- msgs.nextElement();
- msgCount++;
- }
-
- try
- {
- queueBrowser.close();
- }
- catch (JMSException e)
- {
- fail("Close should happen without error:" + e.getMessage());
- }
- }
-
- /**
- * This method checks that multiple calls to getEnumeration() on a queueBrowser provide the same behaviour.
- *
- * @param sentMessages The number of messages sent
- * @param browserEnumerationCount The number of times to call getEnumeration()
- * @throws JMSException
- */
- protected void checkMultipleGetEnum(int sentMessages, int browserEnumerationCount) throws JMSException
- {
- QueueBrowser queueBrowser = _clientSession.createBrowser(_queue);
-
- for (int count = 0; count < browserEnumerationCount; count++)
- {
- _logger.info("Checking getEnumeration:" + count);
- Enumeration msgs = queueBrowser.getEnumeration();
-
- int msgCount = 0;
-
- while (msgs.hasMoreElements())
- {
- msgs.nextElement();
- msgCount++;
- }
-
- // Verify that the browser can see all the messages sent.
- assertEquals(sentMessages, msgCount);
- }
-
- try
- {
- queueBrowser.close();
- }
- catch (JMSException e)
- {
- fail("Close should happen without error:" + e.getMessage());
- }
- }
-
- protected void checkOverlappingMultipleGetEnum(int expectedMessages, int browserEnumerationCount) throws JMSException
- {
- checkOverlappingMultipleGetEnum(expectedMessages, browserEnumerationCount, null);
- }
-
- protected void checkOverlappingMultipleGetEnum(int expectedMessages, int browserEnumerationCount, String selector) throws JMSException
- {
- QueueBrowser queueBrowser = selector == null ?
- _clientSession.createBrowser(_queue) : _clientSession.createBrowser(_queue);
-// _clientSession.createBrowser(_queue) : _clientSession.createBrowser(_queue, selector);
-
- Enumeration[] msgs = new Enumeration[browserEnumerationCount];
- int[] msgCount = new int[browserEnumerationCount];
-
- //create Enums
- for (int count = 0; count < browserEnumerationCount; count++)
- {
- msgs[count] = queueBrowser.getEnumeration();
- }
-
- //interleave reads
- for (int cnt = 0; cnt < expectedMessages; cnt++)
- {
- for (int count = 0; count < browserEnumerationCount; count++)
- {
- if (msgs[count].hasMoreElements())
- {
- msgs[count].nextElement();
- msgCount[count]++;
- }
- }
- }
-
- //validate all browsers get right message count.
- for (int count = 0; count < browserEnumerationCount; count++)
- {
- assertEquals(msgCount[count], expectedMessages);
- }
-
- try
- {
- queueBrowser.close();
- }
- catch (JMSException e)
- {
- fail("Close should happen without error:" + e.getMessage());
- }
- }
-
- protected void validate(int messages) throws JMSException
- {
- //Create a new connection to validate message content
- Connection connection = null;
-
- try
- {
- connection = getConnection();
- }
- catch (Exception e)
- {
- fail("Unable to make validation connection");
- }
-
- Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- connection.start();
-
- MessageConsumer consumer = session.createConsumer(_queue);
-
- _logger.info("Verify messages are still on the queue");
-
- Message tempMsg;
-
- for (int msgCount = 0; msgCount < messages; msgCount++)
- {
- tempMsg = (TextMessage) consumer.receive(RECEIVE_TIMEOUT);
- if (tempMsg == null)
- {
- fail("Message " + msgCount + " not retrieved from queue");
- }
- }
-
- //Close this new connection
- connection.close();
-
- _logger.info("All messages recevied from queue");
-
- //ensure no message left.
- checkQueueDepth(0);
- }
-
- protected void checkQueueDepthWithSelectors(int totalMessages, int clients) throws JMSException
- {
-
- String selector = MESSAGE_ID_PROPERTY + " % " + clients;
-
- checkOverlappingMultipleGetEnum(totalMessages / clients, clients, selector);
- }
-
-
- /**
- * This tests you can browse an empty queue, see QPID-785
- *
- * @throws Exception
- */
- public void testBrowsingEmptyQueue() throws Exception
- {
- checkQueueDepth(0);
- }
-
- /*
- * Test Messages Remain on Queue
- * Create a queu and send messages to it. Browse them and then receive them all to verify they were still there
- *
- */
- public void testQueueBrowserMsgsRemainOnQueue() throws Exception
- {
- int messages = 10;
-
- sendMessages(messages);
-
- checkQueueDepth(messages);
-
- validate(messages);
- }
-
-
- public void testClosingBrowserMidReceiving() throws NamingException, JMSException
- {
- int messages = 100;
-
- sendMessages(messages);
-
- checkQueueDepth(messages);
-
- closeBrowserBeforeAfterGetNext(10);
-
- validate(messages);
- }
-
- /**
- * This tests that multiple getEnumerations on a QueueBrowser return the required number of messages.
- * @throws NamingException
- * @throws JMSException
- */
- public void testMultipleGetEnum() throws NamingException, JMSException
- {
- int messages = 10;
-
- sendMessages(messages);
-
- checkQueueDepth(messages);
-
- checkMultipleGetEnum(messages, 5);
-
- validate(messages);
- }
-
- public void testMultipleOverlappingGetEnum() throws NamingException, JMSException
- {
- int messages = 25;
-
- sendMessages(messages);
-
- checkQueueDepth(messages);
-
- checkOverlappingMultipleGetEnum(messages, 5);
-
- validate(messages);
- }
-
-
- public void testBrowsingWithSelector() throws JMSException
- {
- int messages = 40;
-
- sendMessages(messages);
-
- checkQueueDepth(messages);
-
- for (int clients = 2; clients <= 10; clients++)
- {
- checkQueueDepthWithSelectors(messages, clients);
- }
-
- validate(messages);
- }
-
- /**
- * Testing that a QueueBrowser doesn't actually consume messages from a broker when it fails over.
- * @throws JMSException
- */
- public void testFailoverWithQueueBrowser() throws JMSException
- {
- int messages = 5;
-
- sendMessages("connection1", messages);
- if (!CLUSTERED)
- {
- sendMessages("connection2", messages);
- }
-
- checkQueueDepth(messages);
-
- _logger.info("Creating Queue Browser");
- QueueBrowser queueBrowser = _clientSession.createBrowser(_queue);
-
- long queueDepth = 0;
-
- try
- {
- queueDepth = ((AMQSession) _clientSession).getQueueDepth((AMQDestination) _queue);
- }
- catch (AMQException e)
- {
- fail("Caught exception getting queue depth: " + e.getMessage());
- }
-
- assertEquals("Session reports Queue depth not as expected", messages, queueDepth);
-
- int msgCount = 0;
- int failPoint = 0;
-
- failPoint = new Random().nextInt(messages) + 1;
-
- Enumeration msgs = queueBrowser.getEnumeration();
- while (msgs.hasMoreElements())
- {
- msgs.nextElement();
- msgCount++;
-
- if (msgCount == failPoint)
- {
- failBroker(getFailingPort());
- }
- }
-
- assertTrue("We should get atleast " + messages + " msgs.", msgCount >= messages);
-
- if (_logger.isDebugEnabled())
- {
- _logger.debug("QBAAT Found " + msgCount + " messages total in browser");
- }
-
- //Close browser
- queueBrowser.close();
-
- _logger.info("Closed Queue Browser, validating messages on broker.");
-
- //Validate all messages still on Broker
- validate(messages);
- }
-
- public void testFailoverAsQueueBrowserCreated() throws JMSException
- {
- // The IoServiceListenerSupport seems to get stuck in with a managedSession that isn't closing when requested.
- // So it hangs waiting for the session.
- int messages = 50;
-
- sendMessages("connection1", messages);
- if (!CLUSTERED)
- {
- sendMessages("connection2", messages);
- }
-
- failBroker(getFailingPort());
-
- checkQueueDepth(messages);
-
- //Validate all messages still on Broker 1
- validate(messages);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/client/QueueBrowserClientAckTest.java b/java/systests/src/main/java/org/apache/qpid/test/client/QueueBrowserClientAckTest.java
deleted file mode 100644
index f30b8043ad..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/client/QueueBrowserClientAckTest.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.client;
-
-import javax.jms.Session;
-
-public class QueueBrowserClientAckTest extends QueueBrowserAutoAckTest
-{
-
-
- protected void setupSession() throws Exception
- {
- _clientSession = _clientConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
- }
-
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/client/QueueBrowserDupsOkTest.java b/java/systests/src/main/java/org/apache/qpid/test/client/QueueBrowserDupsOkTest.java
deleted file mode 100644
index b19809b8f2..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/client/QueueBrowserDupsOkTest.java
+++ /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.
- *
- */
-package org.apache.qpid.test.client;
-
-import javax.jms.Session;
-
-public class QueueBrowserDupsOkTest extends QueueBrowserAutoAckTest
-{
- protected void setupSession() throws Exception
- {
- _clientSession = _clientConnection.createSession(false, Session.DUPS_OK_ACKNOWLEDGE);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/client/QueueBrowserNoAckTest.java b/java/systests/src/main/java/org/apache/qpid/test/client/QueueBrowserNoAckTest.java
deleted file mode 100644
index c97343464c..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/client/QueueBrowserNoAckTest.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.client;
-
-import org.apache.qpid.client.AMQSession;
-
-
-public class QueueBrowserNoAckTest extends QueueBrowserAutoAckTest
-{
-
- protected void setupSession() throws Exception
- {
- _clientSession = _clientConnection.createSession(false, AMQSession.NO_ACKNOWLEDGE);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/client/QueueBrowserPreAckTest.java b/java/systests/src/main/java/org/apache/qpid/test/client/QueueBrowserPreAckTest.java
deleted file mode 100644
index bb1c0d3698..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/client/QueueBrowserPreAckTest.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.client;
-
-import org.apache.qpid.client.AMQSession;
-
-public class QueueBrowserPreAckTest extends QueueBrowserAutoAckTest
-{
-
- protected void setupSession() throws Exception
- {
- _clientSession = _clientConnection.createSession(false, AMQSession.PRE_ACKNOWLEDGE);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/client/QueueBrowserTransactedTest.java b/java/systests/src/main/java/org/apache/qpid/test/client/QueueBrowserTransactedTest.java
deleted file mode 100644
index d79788f017..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/client/QueueBrowserTransactedTest.java
+++ /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.
- *
- */
-package org.apache.qpid.test.client;
-
-import javax.jms.Session;
-
-public class QueueBrowserTransactedTest extends QueueBrowserAutoAckTest
-{
- protected void setupSession() throws Exception
- {
- _clientSession = _clientConnection.createSession(true, Session.SESSION_TRANSACTED);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/client/RollbackOrderTest.java b/java/systests/src/main/java/org/apache/qpid/test/client/RollbackOrderTest.java
deleted file mode 100644
index b944f2ddd2..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/client/RollbackOrderTest.java
+++ /dev/null
@@ -1,194 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.client;
-
-import org.apache.qpid.test.utils.*;
-import javax.jms.*;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import junit.framework.ComparisonFailure;
-import junit.framework.AssertionFailedError;
-
-/**
- * RollbackOrderTest, QPID-1864, QPID-1871
- *
- * Description:
- *
- * The problem that this test is exposing is that the dispatcher used to be capable
- * of holding on to a message when stopped. This ment that when the rollback was
- * called and the dispatcher stopped it may have hold of a message. So after all
- * the local queues(preDeliveryQueue, SynchronousQueue, PostDeliveryTagQueue)
- * have been cleared the client still had a single message, the one the
- * dispatcher was holding on to.
- *
- * As a result the TxRollback operation would run and then release the dispatcher.
- * Whilst the dispatcher would then proceed to reject the message it was holiding
- * the Broker would already have resent that message so the rejection would silently
- * fail.
- *
- * And the client would receieve that single message 'early', depending on the
- * number of messages already recevied when rollback was called.
- *
- *
- * Aims:
- *
- * The tests puts 50 messages on to the queue.
- *
- * The test then tries to cause the dispatcher to stop whilst it is in the process
- * of moving a message from the preDeliveryQueue to a consumers sychronousQueue.
- *
- * To exercise this path we have 50 message flowing to the client to give the
- * dispatcher a bit of work to do moving messages.
- *
- * Then we loop - 10 times
- * - Validating that the first message received is always message 1.
- * - Receive a few more so that there are a few messages to reject.
- * - call rollback, to try and catch the dispatcher mid process.
- *
- * Outcome:
- *
- * The hope is that we catch the dispatcher mid process and cause a BasicReject
- * to fail. Which will be indicated in the log but will also cause that failed
- * rejected message to be the next to be delivered which will not be message 1
- * as expected.
- *
- * We are testing a race condition here but we can check through the log file if
- * the race condition occured. However, performing that check will only validate
- * the problem exists and will not be suitable as part of a system test.
- *
- */
-public class RollbackOrderTest extends QpidBrokerTestCase
-{
-
- private Connection _connection;
- private Queue _queue;
- private Session _session;
- private MessageConsumer _consumer;
-
- @Override public void setUp() throws Exception
- {
- super.setUp();
- _connection = getConnection();
-
- _session = _connection.createSession(true, Session.SESSION_TRANSACTED);
- _queue = _session.createQueue(getTestQueueName());
- _consumer = _session.createConsumer(_queue);
-
- //Send more messages so it is more likely that the dispatcher is
- // processing on rollback.
- sendMessage(_session, _queue, 50);
- _session.commit();
-
- }
-
- public void testOrderingAfterRollback() throws Exception
- {
- //Start the session now so we
- _connection.start();
-
- for (int i = 0; i < 20; i++)
- {
- Message msg = _consumer.receive();
- assertEquals("Incorrect Message Received", 0, msg.getIntProperty(INDEX));
-
- // Pull additional messages through so we have some reject work to do
- for (int m=0; m < 5 ; m++)
- {
- _consumer.receive();
- }
-
- System.err.println("ROT-Rollback");
- _logger.warn("ROT-Rollback");
- _session.rollback();
- }
- }
-
- public void testOrderingAfterRollbackOnMessage() throws Exception
- {
- final CountDownLatch count= new CountDownLatch(20);
- final Exception exceptions[] = new Exception[20];
- final AtomicBoolean failed = new AtomicBoolean(false);
-
- _consumer.setMessageListener(new MessageListener()
- {
-
- public void onMessage(Message message)
- {
-
- Message msg = message;
- try
- {
- count.countDown();
- assertEquals("Incorrect Message Received", 0, msg.getIntProperty(INDEX));
-
- _session.rollback();
- }
- catch (JMSException e)
- {
- System.out.println("Error:" + e.getMessage());
- exceptions[(int)count.getCount()] = e;
- }
- catch (AssertionFailedError cf)
- {
- // End Test if Equality test fails
- while (count.getCount() != 0)
- {
- count.countDown();
- }
-
- System.out.println("Error:" + cf.getMessage());
- System.err.println(cf.getMessage());
- cf.printStackTrace();
- failed.set(true);
- }
- }
- });
- //Start the session now so we
- _connection.start();
-
- count.await();
-
- for (Exception e : exceptions)
- {
- if (e != null)
- {
- System.err.println(e.getMessage());
- e.printStackTrace();
- failed.set(true);
- }
- }
-
-// _consumer.close();
- _connection.close();
-
- assertFalse("Exceptions thrown during test run, Check Std.err.", failed.get());
- }
-
- @Override public void tearDown() throws Exception
- {
-
- drainQueue(_queue);
-
- super.tearDown();
- }
-
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/client/destination/AddressBasedDestinationTest.java b/java/systests/src/main/java/org/apache/qpid/test/client/destination/AddressBasedDestinationTest.java
deleted file mode 100644
index fb389c5345..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/client/destination/AddressBasedDestinationTest.java
+++ /dev/null
@@ -1,1072 +0,0 @@
-package org.apache.qpid.test.client.destination;
-/*
- *
- * 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 java.util.Collections;
-import java.util.HashMap;
-import java.util.Hashtable;
-import java.util.Map;
-import java.util.Properties;
-
-import javax.jms.Connection;
-import javax.jms.Destination;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-import javax.jms.Queue;
-import javax.jms.QueueReceiver;
-import javax.jms.QueueSession;
-import javax.jms.Session;
-import javax.jms.TextMessage;
-import javax.jms.Topic;
-import javax.jms.TopicSession;
-import javax.jms.TopicSubscriber;
-import javax.naming.Context;
-import javax.naming.InitialContext;
-
-import org.apache.qpid.client.AMQAnyDestination;
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQDestination;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.client.AMQSession_0_10;
-import org.apache.qpid.client.messaging.address.Node.ExchangeNode;
-import org.apache.qpid.client.messaging.address.Node.QueueNode;
-import org.apache.qpid.jndi.PropertiesFileInitialContextFactory;
-import org.apache.qpid.messaging.Address;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class AddressBasedDestinationTest extends QpidBrokerTestCase
-{
- private static final Logger _logger = LoggerFactory.getLogger(AddressBasedDestinationTest.class);
- private Connection _connection;
-
- @Override
- public void setUp() throws Exception
- {
- super.setUp();
- _connection = getConnection() ;
- _connection.start();
- }
-
- @Override
- public void tearDown() throws Exception
- {
- _connection.close();
- super.tearDown();
- }
-
- public void testCreateOptions() throws Exception
- {
- Session jmsSession = _connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
- MessageProducer prod;
- MessageConsumer cons;
-
- // default (create never, assert never) -------------------
- // create never --------------------------------------------
- String addr1 = "ADDR:testQueue1";
- AMQDestination dest = new AMQAnyDestination(addr1);
- try
- {
- cons = jmsSession.createConsumer(dest);
- }
- catch(JMSException e)
- {
- assertTrue(e.getMessage().contains("The name 'testQueue1' supplied in the address " +
- "doesn't resolve to an exchange or a queue"));
- }
-
- try
- {
- prod = jmsSession.createProducer(dest);
- }
- catch(JMSException e)
- {
- assertTrue(e.getCause().getCause().getMessage().contains("The name 'testQueue1' supplied in the address " +
- "doesn't resolve to an exchange or a queue"));
- }
-
- assertFalse("Queue should not be created",(
- (AMQSession_0_10)jmsSession).isQueueExist(dest, (QueueNode)dest.getSourceNode() ,true));
-
-
- // create always -------------------------------------------
- addr1 = "ADDR:testQueue1; { create: always }";
- dest = new AMQAnyDestination(addr1);
- cons = jmsSession.createConsumer(dest);
-
- assertTrue("Queue not created as expected",(
- (AMQSession_0_10)jmsSession).isQueueExist(dest,(QueueNode)dest.getSourceNode(), true));
- assertTrue("Queue not bound as expected",(
- (AMQSession_0_10)jmsSession).isQueueBound("",
- dest.getAddressName(),dest.getAddressName(), dest.getSourceNode().getDeclareArgs()));
-
- // create receiver -----------------------------------------
- addr1 = "ADDR:testQueue2; { create: receiver }";
- dest = new AMQAnyDestination(addr1);
- try
- {
- prod = jmsSession.createProducer(dest);
- }
- catch(JMSException e)
- {
- assertTrue(e.getCause().getCause().getMessage().contains("The name 'testQueue2' supplied in the address " +
- "doesn't resolve to an exchange or a queue"));
- }
-
- assertFalse("Queue should not be created",(
- (AMQSession_0_10)jmsSession).isQueueExist(dest,(QueueNode)dest.getSourceNode(), true));
-
-
- cons = jmsSession.createConsumer(dest);
-
- assertTrue("Queue not created as expected",(
- (AMQSession_0_10)jmsSession).isQueueExist(dest,(QueueNode)dest.getSourceNode(), true));
- assertTrue("Queue not bound as expected",(
- (AMQSession_0_10)jmsSession).isQueueBound("",
- dest.getAddressName(),dest.getAddressName(), dest.getSourceNode().getDeclareArgs()));
-
- // create never --------------------------------------------
- addr1 = "ADDR:testQueue3; { create: never }";
- dest = new AMQAnyDestination(addr1);
- try
- {
- cons = jmsSession.createConsumer(dest);
- }
- catch(JMSException e)
- {
- assertTrue(e.getMessage().contains("The name 'testQueue3' supplied in the address " +
- "doesn't resolve to an exchange or a queue"));
- }
-
- try
- {
- prod = jmsSession.createProducer(dest);
- }
- catch(JMSException e)
- {
- assertTrue(e.getCause().getCause().getMessage().contains("The name 'testQueue3' supplied in the address " +
- "doesn't resolve to an exchange or a queue"));
- }
-
- assertFalse("Queue should not be created",(
- (AMQSession_0_10)jmsSession).isQueueExist(dest,(QueueNode)dest.getSourceNode(), true));
-
- // create sender ------------------------------------------
- addr1 = "ADDR:testQueue3; { create: sender }";
- dest = new AMQAnyDestination(addr1);
-
- try
- {
- cons = jmsSession.createConsumer(dest);
- }
- catch(JMSException e)
- {
- assertTrue(e.getMessage().contains("The name 'testQueue3' supplied in the address " +
- "doesn't resolve to an exchange or a queue"));
- }
- assertFalse("Queue should not be created",(
- (AMQSession_0_10)jmsSession).isQueueExist(dest,(QueueNode)dest.getSourceNode(), true));
-
- prod = jmsSession.createProducer(dest);
- assertTrue("Queue not created as expected",(
- (AMQSession_0_10)jmsSession).isQueueExist(dest,(QueueNode)dest.getSourceNode(), true));
- assertTrue("Queue not bound as expected",(
- (AMQSession_0_10)jmsSession).isQueueBound("",
- dest.getAddressName(),dest.getAddressName(), dest.getSourceNode().getDeclareArgs()));
-
- }
-
- public void testCreateQueue() throws Exception
- {
- Session jmsSession = _connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
-
- String addr = "ADDR:my-queue/hello; " +
- "{" +
- "create: always, " +
- "node: " +
- "{" +
- "durable: true ," +
- "x-declare: " +
- "{" +
- "auto-delete: true," +
- "arguments: {" +
- "'qpid.max_size': 1000," +
- "'qpid.max_count': 100" +
- "}" +
- "}, " +
- "x-bindings: [{exchange : 'amq.direct', key : test}, " +
- "{exchange : 'amq.fanout'}," +
- "{exchange: 'amq.match', arguments: {x-match: any, dep: sales, loc: CA}}," +
- "{exchange : 'amq.topic', key : 'a.#'}" +
- "]," +
-
- "}" +
- "}";
- AMQDestination dest = new AMQAnyDestination(addr);
- MessageConsumer cons = jmsSession.createConsumer(dest);
-
- assertTrue("Queue not created as expected",(
- (AMQSession_0_10)jmsSession).isQueueExist(dest,(QueueNode)dest.getSourceNode(), true));
-
- assertTrue("Queue not bound as expected",(
- (AMQSession_0_10)jmsSession).isQueueBound("",
- dest.getAddressName(),dest.getAddressName(), null));
-
- assertTrue("Queue not bound as expected",(
- (AMQSession_0_10)jmsSession).isQueueBound("amq.direct",
- dest.getAddressName(),"test", null));
-
- assertTrue("Queue not bound as expected",(
- (AMQSession_0_10)jmsSession).isQueueBound("amq.fanout",
- dest.getAddressName(),null, null));
-
- assertTrue("Queue not bound as expected",(
- (AMQSession_0_10)jmsSession).isQueueBound("amq.topic",
- dest.getAddressName(),"a.#", null));
-
- Map<String,Object> args = new HashMap<String,Object>();
- args.put("x-match","any");
- args.put("dep","sales");
- args.put("loc","CA");
- assertTrue("Queue not bound as expected",(
- (AMQSession_0_10)jmsSession).isQueueBound("amq.match",
- dest.getAddressName(),null, args));
-
- }
-
- public void testCreateExchange() throws Exception
- {
- Session jmsSession = _connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
-
- String addr = "ADDR:my-exchange/hello; " +
- "{ " +
- "create: always, " +
- "node: " +
- "{" +
- "type: topic, " +
- "x-declare: " +
- "{ " +
- "type:direct, " +
- "auto-delete: true, " +
- "arguments: {" +
- "'qpid.msg_sequence': 1, " +
- "'qpid.ive': 1" +
- "}" +
- "}" +
- "}" +
- "}";
-
- AMQDestination dest = new AMQAnyDestination(addr);
- MessageConsumer cons = jmsSession.createConsumer(dest);
-
- assertTrue("Exchange not created as expected",(
- (AMQSession_0_10)jmsSession).isExchangeExist(dest, (ExchangeNode)dest.getTargetNode() , true));
-
- // The existence of the queue is implicitly tested here
- assertTrue("Queue not bound as expected",(
- (AMQSession_0_10)jmsSession).isQueueBound("my-exchange",
- dest.getQueueName(),"hello", Collections.<String, Object>emptyMap()));
-
- // The client should be able to query and verify the existence of my-exchange (QPID-2774)
- dest = new AMQAnyDestination("ADDR:my-exchange; {create: never}");
- cons = jmsSession.createConsumer(dest);
- }
-
- public void checkQueueForBindings(Session jmsSession, AMQDestination dest,String headersBinding) throws Exception
- {
- assertTrue("Queue not created as expected",(
- (AMQSession_0_10)jmsSession).isQueueExist(dest,(QueueNode)dest.getSourceNode(), true));
-
- assertTrue("Queue not bound as expected",(
- (AMQSession_0_10)jmsSession).isQueueBound("",
- dest.getAddressName(),dest.getAddressName(), null));
-
- assertTrue("Queue not bound as expected",(
- (AMQSession_0_10)jmsSession).isQueueBound("amq.direct",
- dest.getAddressName(),"test", null));
-
- assertTrue("Queue not bound as expected",(
- (AMQSession_0_10)jmsSession).isQueueBound("amq.topic",
- dest.getAddressName(),"a.#", null));
-
- Address a = Address.parse(headersBinding);
- assertTrue("Queue not bound as expected",(
- (AMQSession_0_10)jmsSession).isQueueBound("amq.match",
- dest.getAddressName(),null, a.getOptions()));
- }
-
- /**
- * Test goal: Verifies that a producer and consumer creation triggers the correct
- * behavior for x-bindings specified in node props.
- */
- public void testBindQueueWithArgs() throws Exception
- {
-
- Session jmsSession = _connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
- String headersBinding = "{exchange: 'amq.match', arguments: {x-match: any, dep: sales, loc: CA}}";
-
- String addr = "node: " +
- "{" +
- "durable: true ," +
- "x-declare: " +
- "{ " +
- "auto-delete: true," +
- "arguments: {'qpid.max_count': 100}" +
- "}, " +
- "x-bindings: [{exchange : 'amq.direct', key : test}, " +
- "{exchange : 'amq.topic', key : 'a.#'}," +
- headersBinding +
- "]" +
- "}" +
- "}";
-
-
- AMQDestination dest1 = new AMQAnyDestination("ADDR:my-queue/hello; {create: receiver, " +addr);
- MessageConsumer cons = jmsSession.createConsumer(dest1);
- checkQueueForBindings(jmsSession,dest1,headersBinding);
-
- AMQDestination dest2 = new AMQAnyDestination("ADDR:my-queue2/hello; {create: sender, " +addr);
- MessageProducer prod = jmsSession.createProducer(dest2);
- checkQueueForBindings(jmsSession,dest2,headersBinding);
- }
-
- /**
- * Test goal: Verifies the capacity property in address string is handled properly.
- * Test strategy:
- * Creates a destination with capacity 10.
- * Creates consumer with client ack.
- * Sends 15 messages to the queue, tries to receive 10.
- * Tries to receive the 11th message and checks if its null.
- *
- * Since capacity is 10 and we haven't acked any messages,
- * we should not have received the 11th.
- *
- * Acks the 10th message and verifies we receive the rest of the msgs.
- */
- public void testCapacity() throws Exception
- {
- verifyCapacity("ADDR:my-queue; {create: always, link:{capacity: 10}}");
- }
-
- public void testSourceAndTargetCapacity() throws Exception
- {
- verifyCapacity("ADDR:my-queue; {create: always, link:{capacity: {source:10, target:15} }}");
- }
-
- private void verifyCapacity(String address) throws Exception
- {
- if (!isCppBroker())
- {
- _logger.info("Not C++ broker, exiting test");
- return;
- }
-
- Session jmsSession = _connection.createSession(false,Session.CLIENT_ACKNOWLEDGE);
-
- AMQDestination dest = new AMQAnyDestination(address);
- MessageConsumer cons = jmsSession.createConsumer(dest);
- MessageProducer prod = jmsSession.createProducer(dest);
-
- for (int i=0; i< 15; i++)
- {
- prod.send(jmsSession.createTextMessage("msg" + i) );
- }
-
- for (int i=0; i< 9; i++)
- {
- cons.receive();
- }
- Message msg = cons.receive(RECEIVE_TIMEOUT);
- assertNotNull("Should have received the 10th message",msg);
- assertNull("Shouldn't have received the 11th message as capacity is 10",cons.receive(RECEIVE_TIMEOUT));
- msg.acknowledge();
- for (int i=11; i<16; i++)
- {
- assertNotNull("Should have received the " + i + "th message as we acked the last 10",cons.receive(RECEIVE_TIMEOUT));
- }
- }
-
- /**
- * Test goal: Verifies if the new address format based destinations
- * can be specified and loaded correctly from the properties file.
- *
- */
- public void testLoadingFromPropertiesFile() throws Exception
- {
- Hashtable<String,String> map = new Hashtable<String,String>();
- map.put("destination.myQueue1", "ADDR:my-queue/hello; {create: always, node: " +
- "{x-declare: {auto-delete: true, arguments : {'qpid.max_size': 1000}}}}");
-
- map.put("destination.myQueue2", "ADDR:my-queue2; { create: receiver }");
-
- map.put("destination.myQueue3", "BURL:direct://amq.direct/my-queue3?routingkey='test'");
-
- PropertiesFileInitialContextFactory props = new PropertiesFileInitialContextFactory();
- Context ctx = props.getInitialContext(map);
-
- AMQDestination dest1 = (AMQDestination)ctx.lookup("myQueue1");
- AMQDestination dest2 = (AMQDestination)ctx.lookup("myQueue2");
- AMQDestination dest3 = (AMQDestination)ctx.lookup("myQueue3");
-
- Session jmsSession = _connection.createSession(false,Session.CLIENT_ACKNOWLEDGE);
- MessageConsumer cons1 = jmsSession.createConsumer(dest1);
- MessageConsumer cons2 = jmsSession.createConsumer(dest2);
- MessageConsumer cons3 = jmsSession.createConsumer(dest3);
-
- assertTrue("Destination1 was not created as expected",(
- (AMQSession_0_10)jmsSession).isQueueExist(dest1,(QueueNode)dest1.getSourceNode(), true));
-
- assertTrue("Destination1 was not bound as expected",(
- (AMQSession_0_10)jmsSession).isQueueBound("",
- dest1.getAddressName(),dest1.getAddressName(), null));
-
- assertTrue("Destination2 was not created as expected",(
- (AMQSession_0_10)jmsSession).isQueueExist(dest2,(QueueNode)dest2.getSourceNode(), true));
-
- assertTrue("Destination2 was not bound as expected",(
- (AMQSession_0_10)jmsSession).isQueueBound("",
- dest2.getAddressName(),dest2.getAddressName(), null));
-
- MessageProducer producer = jmsSession.createProducer(dest3);
- producer.send(jmsSession.createTextMessage("Hello"));
- TextMessage msg = (TextMessage)cons3.receive(1000);
- assertEquals("Destination3 was not created as expected.",msg.getText(),"Hello");
- }
-
- /**
- * Test goal: Verifies the subject can be overridden using "qpid.subject" message property.
- * Test strategy: Creates and address with a default subject "topic1"
- * Creates a message with "qpid.subject"="topic2" and sends it.
- * Verifies that the message goes to "topic2" instead of "topic1".
- */
- public void testOverridingSubject() throws Exception
- {
- Session jmsSession = _connection.createSession(false,Session.CLIENT_ACKNOWLEDGE);
-
- AMQDestination topic1 = new AMQAnyDestination("ADDR:amq.topic/topic1; {link:{name: queue1}}");
-
- MessageProducer prod = jmsSession.createProducer(topic1);
-
- Message m = jmsSession.createTextMessage("Hello");
- m.setStringProperty("qpid.subject", "topic2");
-
- MessageConsumer consForTopic1 = jmsSession.createConsumer(topic1);
- MessageConsumer consForTopic2 = jmsSession.createConsumer(new AMQAnyDestination("ADDR:amq.topic/topic2; {link:{name: queue2}}"));
-
- prod.send(m);
- Message msg = consForTopic1.receive(1000);
- assertNull("message shouldn't have been sent to topic1",msg);
-
- msg = consForTopic2.receive(1000);
- assertNotNull("message should have been sent to topic2",msg);
-
- }
-
- /**
- * Test goal: Verifies that session.createQueue method
- * works as expected both with the new and old addressing scheme.
- */
- public void testSessionCreateQueue() throws Exception
- {
- Session ssn = _connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
-
- // Using the BURL method
- Destination queue = ssn.createQueue("my-queue");
- MessageProducer prod = ssn.createProducer(queue);
- MessageConsumer cons = ssn.createConsumer(queue);
- assertTrue("my-queue was not created as expected",(
- (AMQSession_0_10)ssn).isQueueBound("amq.direct",
- "my-queue","my-queue", null));
-
- prod.send(ssn.createTextMessage("test"));
- assertNotNull("consumer should receive a message",cons.receive(1000));
- cons.close();
-
- // Using the ADDR method
- // default case
- queue = ssn.createQueue("ADDR:my-queue2");
- try
- {
- prod = ssn.createProducer(queue);
- fail("The client should throw an exception, since there is no queue present in the broker");
- }
- catch(Exception e)
- {
- String s = "The name 'my-queue2' supplied in the address " +
- "doesn't resolve to an exchange or a queue";
- assertEquals(s,e.getCause().getCause().getMessage());
- }
-
- // explicit create case
- queue = ssn.createQueue("ADDR:my-queue2; {create: sender}");
- prod = ssn.createProducer(queue);
- cons = ssn.createConsumer(queue);
- assertTrue("my-queue2 was not created as expected",(
- (AMQSession_0_10)ssn).isQueueBound("",
- "my-queue2","my-queue2", null));
-
- prod.send(ssn.createTextMessage("test"));
- assertNotNull("consumer should receive a message",cons.receive(1000));
- cons.close();
-
- // Using the ADDR method to create a more complicated queue
- String addr = "ADDR:amq.direct/x512; {create: receiver, " +
- "link : {name : 'MY.RESP.QUEUE', " +
- "x-declare : { auto-delete: true, exclusive: true, " +
- "arguments : {'qpid.max_size': 1000, 'qpid.policy_type': ring} } } }";
- queue = ssn.createQueue(addr);
-
- prod = ssn.createProducer(queue);
- cons = ssn.createConsumer(queue);
- assertTrue("MY.RESP.QUEUE was not created as expected",(
- (AMQSession_0_10)ssn).isQueueBound("amq.direct",
- "MY.RESP.QUEUE","x512", null));
- cons.close();
- }
-
- /**
- * Test goal: Verifies that session.creatTopic method
- * works as expected both with the new and old addressing scheme.
- */
- public void testSessionCreateTopic() throws Exception
- {
- Session ssn = _connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
-
- // Using the BURL method
- Topic topic = ssn.createTopic("ACME");
- MessageProducer prod = ssn.createProducer(topic);
- MessageConsumer cons = ssn.createConsumer(topic);
-
- prod.send(ssn.createTextMessage("test"));
- assertNotNull("consumer should receive a message",cons.receive(1000));
- cons.close();
-
- // Using the ADDR method
- topic = ssn.createTopic("ADDR:ACME");
- prod = ssn.createProducer(topic);
- cons = ssn.createConsumer(topic);
-
- prod.send(ssn.createTextMessage("test"));
- assertNotNull("consumer should receive a message",cons.receive(1000));
- cons.close();
-
- String addr = "ADDR:vehicles/bus; " +
- "{ " +
- "create: always, " +
- "node: " +
- "{" +
- "type: topic, " +
- "x-declare: " +
- "{ " +
- "type:direct, " +
- "auto-delete: true, " +
- "arguments: {" +
- "'qpid.msg_sequence': 1, " +
- "'qpid.ive': 1" +
- "}" +
- "}" +
- "}, " +
- "link: {name : my-topic, " +
- "x-bindings: [{exchange : 'vehicles', key : car}, " +
- "{exchange : 'vehicles', key : van}]" +
- "}" +
- "}";
-
- // Using the ADDR method to create a more complicated topic
- topic = ssn.createTopic(addr);
- prod = ssn.createProducer(topic);
- cons = ssn.createConsumer(topic);
-
- assertTrue("The queue was not bound to vehicle exchange using bus as the binding key",(
- (AMQSession_0_10)ssn).isQueueBound("vehicles",
- "my-topic","bus", null));
-
- assertTrue("The queue was not bound to vehicle exchange using car as the binding key",(
- (AMQSession_0_10)ssn).isQueueBound("vehicles",
- "my-topic","car", null));
-
- assertTrue("The queue was not bound to vehicle exchange using van as the binding key",(
- (AMQSession_0_10)ssn).isQueueBound("vehicles",
- "my-topic","van", null));
-
- Message msg = ssn.createTextMessage("test");
- msg.setStringProperty("qpid.subject", "van");
- prod.send(msg);
- assertNotNull("consumer should receive a message",cons.receive(1000));
- cons.close();
- }
-
- /**
- * Test Goal : Verify the default subjects used for each exchange type.
- * The default for amq.topic is "#" and for the rest it's ""
- */
- public void testDefaultSubjects() throws Exception
- {
- Session ssn = _connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
-
- MessageConsumer queueCons = ssn.createConsumer(new AMQAnyDestination("ADDR:amq.direct"));
- MessageConsumer topicCons = ssn.createConsumer(new AMQAnyDestination("ADDR:amq.topic"));
-
- MessageProducer queueProducer = ssn.createProducer(new AMQAnyDestination("ADDR:amq.direct"));
- MessageProducer topicProducer1 = ssn.createProducer(new AMQAnyDestination("ADDR:amq.topic/usa.weather"));
- MessageProducer topicProducer2 = ssn.createProducer(new AMQAnyDestination("ADDR:amq.topic/sales"));
-
- queueProducer.send(ssn.createBytesMessage());
- assertNotNull("The consumer subscribed to amq.direct " +
- "with empty binding key should have received the message ",queueCons.receive(1000));
-
- topicProducer1.send(ssn.createTextMessage("25c"));
- assertEquals("The consumer subscribed to amq.topic " +
- "with '#' binding key should have received the message ",
- ((TextMessage)topicCons.receive(1000)).getText(),"25c");
-
- topicProducer2.send(ssn.createTextMessage("1000"));
- assertEquals("The consumer subscribed to amq.topic " +
- "with '#' binding key should have received the message ",
- ((TextMessage)topicCons.receive(1000)).getText(),"1000");
- }
-
- /**
- * Test Goal : Verify that 'mode : browse' works as expected using a regular consumer.
- * This indirectly tests ring queues as well.
- */
- public void testBrowseMode() throws Exception
- {
-
- Session ssn = _connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
-
- String addr = "ADDR:my-ring-queue; {create: always, mode: browse, " +
- "node: {x-bindings: [{exchange : 'amq.direct', key : test}], " +
- "x-declare:{arguments : {'qpid.policy_type':ring, 'qpid.max_count':2}}}}";
-
- Destination dest = ssn.createQueue(addr);
- MessageConsumer browseCons = ssn.createConsumer(dest);
- MessageProducer prod = ssn.createProducer(ssn.createQueue("ADDR:amq.direct/test"));
-
- prod.send(ssn.createTextMessage("Test1"));
- prod.send(ssn.createTextMessage("Test2"));
-
- TextMessage msg = (TextMessage)browseCons.receive(1000);
- assertEquals("Didn't receive the first message",msg.getText(),"Test1");
-
- msg = (TextMessage)browseCons.receive(1000);
- assertEquals("Didn't receive the first message",msg.getText(),"Test2");
-
- browseCons.close();
- prod.send(ssn.createTextMessage("Test3"));
- browseCons = ssn.createConsumer(dest);
-
- msg = (TextMessage)browseCons.receive(1000);
- assertEquals("Should receive the second message again",msg.getText(),"Test2");
-
- msg = (TextMessage)browseCons.receive(1000);
- assertEquals("Should receive the third message since it's a ring queue",msg.getText(),"Test3");
-
- assertNull("Should not receive anymore messages",browseCons.receive(500));
- }
-
- /**
- * Test Goal : When the same destination is used when creating two consumers,
- * If the type == topic, verify that unique subscription queues are created,
- * unless subscription queue has a name.
- *
- * If the type == queue, same queue should be shared.
- */
- public void testSubscriptionForSameDestination() throws Exception
- {
- Session ssn = _connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
- Destination dest = ssn.createTopic("ADDR:amq.topic/foo");
- MessageConsumer consumer1 = ssn.createConsumer(dest);
- MessageConsumer consumer2 = ssn.createConsumer(dest);
- MessageProducer prod = ssn.createProducer(dest);
-
- prod.send(ssn.createTextMessage("A"));
- TextMessage m = (TextMessage)consumer1.receive(1000);
- assertEquals("Consumer1 should recieve message A",m.getText(),"A");
- m = (TextMessage)consumer2.receive(1000);
- assertEquals("Consumer2 should recieve message A",m.getText(),"A");
-
- consumer1.close();
- consumer2.close();
-
- dest = ssn.createTopic("ADDR:amq.topic/foo; { link: {name: my-queue}}");
- consumer1 = ssn.createConsumer(dest);
- try
- {
- consumer2 = ssn.createConsumer(dest);
- fail("An exception should be thrown as 'my-queue' already have an exclusive subscriber");
- }
- catch(Exception e)
- {
- }
- _connection.close();
-
- _connection = getConnection() ;
- _connection.start();
- ssn = _connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
- dest = ssn.createTopic("ADDR:my_queue; {create: always}");
- consumer1 = ssn.createConsumer(dest);
- consumer2 = ssn.createConsumer(dest);
- prod = ssn.createProducer(dest);
-
- prod.send(ssn.createTextMessage("A"));
- Message m1 = consumer1.receive(1000);
- Message m2 = consumer2.receive(1000);
-
- if (m1 != null)
- {
- assertNull("Only one consumer should receive the message",m2);
- }
- else
- {
- assertNotNull("Only one consumer should receive the message",m2);
- }
- }
-
- public void testXBindingsWithoutExchangeName() throws Exception
- {
- Session ssn = _connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
- String addr = "ADDR:MRKT; " +
- "{" +
- "create: receiver," +
- "node : {type: topic, x-declare: {type: topic} }," +
- "link:{" +
- "name: my-topic," +
- "x-bindings:[{key:'NYSE.#'},{key:'NASDAQ.#'},{key:'CNTL.#'}]" +
- "}" +
- "}";
-
- // Using the ADDR method to create a more complicated topic
- MessageConsumer cons = ssn.createConsumer(new AMQAnyDestination(addr));
-
- assertTrue("The queue was not bound to MRKT exchange using NYSE.# as the binding key",(
- (AMQSession_0_10)ssn).isQueueBound("MRKT",
- "my-topic","NYSE.#", null));
-
- assertTrue("The queue was not bound to MRKT exchange using NASDAQ.# as the binding key",(
- (AMQSession_0_10)ssn).isQueueBound("MRKT",
- "my-topic","NASDAQ.#", null));
-
- assertTrue("The queue was not bound to MRKT exchange using CNTL.# as the binding key",(
- (AMQSession_0_10)ssn).isQueueBound("MRKT",
- "my-topic","CNTL.#", null));
-
- MessageProducer prod = ssn.createProducer(ssn.createTopic(addr));
- Message msg = ssn.createTextMessage("test");
- msg.setStringProperty("qpid.subject", "NASDAQ.ABCD");
- prod.send(msg);
- assertNotNull("consumer should receive a message",cons.receive(1000));
- cons.close();
- }
-
- public void testXSubscribeOverrides() throws Exception
- {
- Session ssn = _connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
- String str = "ADDR:my_queue; {create:always,link: {x-subscribes:{exclusive: true, arguments: {a:b,x:y}}}}";
- Destination dest = ssn.createTopic(str);
- MessageConsumer consumer1 = ssn.createConsumer(dest);
- try
- {
- MessageConsumer consumer2 = ssn.createConsumer(dest);
- fail("An exception should be thrown as 'my-queue' already have an exclusive subscriber");
- }
- catch(Exception e)
- {
- }
- }
-
- public void testQueueReceiversAndTopicSubscriber() throws Exception
- {
- Queue queue = new AMQAnyDestination("ADDR:my-queue; {create: always}");
- Topic topic = new AMQAnyDestination("ADDR:amq.topic/test");
-
- QueueSession qSession = ((AMQConnection)_connection).createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
- QueueReceiver receiver = qSession.createReceiver(queue);
-
- TopicSession tSession = ((AMQConnection)_connection).createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
- TopicSubscriber sub = tSession.createSubscriber(topic);
-
- Session ssn = _connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- MessageProducer prod1 = ssn.createProducer(ssn.createQueue("ADDR:my-queue"));
- prod1.send(ssn.createTextMessage("test1"));
-
- MessageProducer prod2 = ssn.createProducer(ssn.createTopic("ADDR:amq.topic/test"));
- prod2.send(ssn.createTextMessage("test2"));
-
- Message msg1 = receiver.receive();
- assertNotNull(msg1);
- assertEquals("test1",((TextMessage)msg1).getText());
-
- Message msg2 = sub.receive();
- assertNotNull(msg2);
- assertEquals("test2",((TextMessage)msg2).getText());
- }
-
- public void testDurableSubscriber() throws Exception
- {
- Session ssn = _connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
-
- Properties props = new Properties();
- props.setProperty("java.naming.factory.initial", "org.apache.qpid.jndi.PropertiesFileInitialContextFactory");
- props.setProperty("destination.address1", "ADDR:amq.topic");
- props.setProperty("destination.address2", "ADDR:amq.direct/test");
- String addrStr = "ADDR:amq.topic/test; {link:{name: my-topic," +
- "x-bindings:[{key:'NYSE.#'},{key:'NASDAQ.#'},{key:'CNTL.#'}]}}";
- props.setProperty("destination.address3", addrStr);
- props.setProperty("topic.address4", "hello.world");
- addrStr = "ADDR:my_queue; {create:always,link: {x-subscribes:{exclusive: true, arguments: {a:b,x:y}}}}";
- props.setProperty("destination.address5", addrStr);
-
- Context ctx = new InitialContext(props);
-
- for (int i=1; i < 5; i++)
- {
- Topic topic = (Topic) ctx.lookup("address"+i);
- createDurableSubscriber(ctx,ssn,"address"+i,topic);
- }
-
- Topic topic = ssn.createTopic("ADDR:news.us");
- createDurableSubscriber(ctx,ssn,"my-dest",topic);
-
- Topic namedQueue = (Topic) ctx.lookup("address5");
- try
- {
- createDurableSubscriber(ctx,ssn,"my-queue",namedQueue);
- fail("Exception should be thrown. Durable subscribers cannot be created for Queues");
- }
- catch(JMSException e)
- {
- assertEquals("Durable subscribers can only be created for Topics",
- e.getMessage());
- }
- }
-
- private void createDurableSubscriber(Context ctx,Session ssn,String destName,Topic topic) throws Exception
- {
- MessageConsumer cons = ssn.createDurableSubscriber(topic, destName);
- MessageProducer prod = ssn.createProducer(topic);
-
- Message m = ssn.createTextMessage(destName);
- prod.send(m);
- Message msg = cons.receive(1000);
- assertNotNull(msg);
- assertEquals(destName,((TextMessage)msg).getText());
- ssn.unsubscribe(destName);
- }
-
- public void testDeleteOptions() throws Exception
- {
- Session jmsSession = _connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
- MessageConsumer cons;
-
- // default (create never, assert never) -------------------
- // create never --------------------------------------------
- String addr1 = "ADDR:testQueue1;{create: always, delete: always}";
- AMQDestination dest = new AMQAnyDestination(addr1);
- try
- {
- cons = jmsSession.createConsumer(dest);
- cons.close();
- }
- catch(JMSException e)
- {
- fail("Exception should not be thrown. Exception thrown is : " + e);
- }
-
- assertFalse("Queue not deleted as expected",(
- (AMQSession_0_10)jmsSession).isQueueExist(dest,(QueueNode)dest.getSourceNode(), true));
-
-
- String addr2 = "ADDR:testQueue2;{create: always, delete: receiver}";
- dest = new AMQAnyDestination(addr2);
- try
- {
- cons = jmsSession.createConsumer(dest);
- cons.close();
- }
- catch(JMSException e)
- {
- fail("Exception should not be thrown. Exception thrown is : " + e);
- }
-
- assertFalse("Queue not deleted as expected",(
- (AMQSession_0_10)jmsSession).isQueueExist(dest,(QueueNode)dest.getSourceNode(), true));
-
-
- String addr3 = "ADDR:testQueue3;{create: always, delete: sender}";
- dest = new AMQAnyDestination(addr3);
- try
- {
- cons = jmsSession.createConsumer(dest);
- MessageProducer prod = jmsSession.createProducer(dest);
- prod.close();
- }
- catch(JMSException e)
- {
- fail("Exception should not be thrown. Exception thrown is : " + e);
- }
-
- assertFalse("Queue not deleted as expected",(
- (AMQSession_0_10)jmsSession).isQueueExist(dest,(QueueNode)dest.getSourceNode(), true));
-
-
- }
-
- /**
- * Test Goals : 1. Test if the client sets the correct accept mode for unreliable
- * and at-least-once.
- * 2. Test default reliability modes for Queues and Topics.
- * 3. Test if an exception is thrown if exactly-once is used.
- * 4. Test if an exception is thrown if at-least-once is used with topics.
- *
- * Test Strategy: For goal #1 & #2
- * For unreliable and at-least-once the test tries to receives messages
- * in client_ack mode but does not ack the messages.
- * It will then close the session, recreate a new session
- * and will then try to verify the queue depth.
- * For unreliable the messages should have been taken off the queue.
- * For at-least-once the messages should be put back onto the queue.
- *
- */
-
- public void testReliabilityOptions() throws Exception
- {
- String addr1 = "ADDR:testQueue1;{create: always, delete : receiver, link : {reliability : unreliable}}";
- acceptModeTest(addr1,0);
-
- String addr2 = "ADDR:testQueue2;{create: always, delete : receiver, link : {reliability : at-least-once}}";
- acceptModeTest(addr2,2);
-
- // Default accept-mode for topics
- acceptModeTest("ADDR:amq.topic/test",0);
-
- // Default accept-mode for queues
- acceptModeTest("ADDR:testQueue1;{create: always}",2);
-
- String addr3 = "ADDR:testQueue2;{create: always, delete : receiver, link : {reliability : exactly-once}}";
- try
- {
- AMQAnyDestination dest = new AMQAnyDestination(addr3);
- fail("An exception should be thrown indicating it's an unsupported type");
- }
- catch(Exception e)
- {
- assertTrue(e.getCause().getMessage().contains("The reliability mode 'exactly-once' is not yet supported"));
- }
-
- String addr4 = "ADDR:amq.topic/test;{link : {reliability : at-least-once}}";
- try
- {
- AMQAnyDestination dest = new AMQAnyDestination(addr4);
- Session ssn = _connection.createSession(false,Session.CLIENT_ACKNOWLEDGE);
- MessageConsumer cons = ssn.createConsumer(dest);
- fail("An exception should be thrown indicating it's an unsupported combination");
- }
- catch(Exception e)
- {
- assertTrue(e.getCause().getMessage().contains("AT-LEAST-ONCE is not yet supported for Topics"));
- }
- }
-
- private void acceptModeTest(String address, int expectedQueueDepth) throws Exception
- {
- Session ssn = _connection.createSession(false,Session.CLIENT_ACKNOWLEDGE);
- MessageConsumer cons;
- MessageProducer prod;
-
- AMQDestination dest = new AMQAnyDestination(address);
- cons = ssn.createConsumer(dest);
- prod = ssn.createProducer(dest);
-
- for (int i=0; i < expectedQueueDepth; i++)
- {
- prod.send(ssn.createTextMessage("Msg" + i));
- }
-
- for (int i=0; i < expectedQueueDepth; i++)
- {
- Message msg = cons.receive(1000);
- assertNotNull(msg);
- assertEquals("Msg" + i,((TextMessage)msg).getText());
- }
-
- ssn.close();
- ssn = _connection.createSession(false,Session.CLIENT_ACKNOWLEDGE);
- long queueDepth = ((AMQSession) ssn).getQueueDepth(dest);
- assertEquals(expectedQueueDepth,queueDepth);
- cons.close();
- prod.close();
- }
-
- public void testDestinationOnSend() throws Exception
- {
- Session ssn = _connection.createSession(false,Session.CLIENT_ACKNOWLEDGE);
- MessageConsumer cons = ssn.createConsumer(ssn.createTopic("amq.topic/test"));
- MessageProducer prod = ssn.createProducer(null);
-
- Queue queue = ssn.createQueue("amq.topic/test");
- prod.send(queue,ssn.createTextMessage("A"));
-
- Message msg = cons.receive(1000);
- assertNotNull(msg);
- assertEquals("A",((TextMessage)msg).getText());
- prod.close();
- cons.close();
- }
-
- public void testReplyToWithNamelessExchange() throws Exception
- {
- System.setProperty("qpid.declare_exchanges","false");
- replyToTest("ADDR:my-queue;{create: always}");
- System.setProperty("qpid.declare_exchanges","true");
- }
-
- public void testReplyToWithCustomExchange() throws Exception
- {
- replyToTest("ADDR:hello;{create:always,node:{type:topic}}");
- }
-
- private void replyToTest(String replyTo) throws Exception
- {
- Session session = _connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- Destination replyToDest = AMQDestination.createDestination(replyTo);
- MessageConsumer replyToCons = session.createConsumer(replyToDest);
-
- Destination dest = session.createQueue("amq.direct/test");
-
- MessageConsumer cons = session.createConsumer(dest);
- MessageProducer prod = session.createProducer(dest);
- Message m = session.createTextMessage("test");
- m.setJMSReplyTo(replyToDest);
- prod.send(m);
-
- Message msg = cons.receive();
- MessageProducer prodR = session.createProducer(msg.getJMSReplyTo());
- prodR.send(session.createTextMessage("x"));
-
- Message m1 = replyToCons.receive();
- assertNotNull("The reply to consumer should have received the messsage",m1);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/client/failover/FailoverTest.java b/java/systests/src/main/java/org/apache/qpid/test/client/failover/FailoverTest.java
deleted file mode 100644
index fcbab273e5..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/client/failover/FailoverTest.java
+++ /dev/null
@@ -1,389 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.qpid.test.client.failover;
-
-import java.util.Random;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-import javax.jms.Connection;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-import javax.jms.Queue;
-import javax.jms.Session;
-import javax.jms.TextMessage;
-import javax.naming.NamingException;
-
-import org.apache.log4j.Logger;
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.jms.BrokerDetails;
-import org.apache.qpid.jms.ConnectionListener;
-import org.apache.qpid.jms.ConnectionURL;
-import org.apache.qpid.test.utils.FailoverBaseCase;
-
-public class FailoverTest extends FailoverBaseCase implements ConnectionListener
-{
- private static final Logger _logger = Logger.getLogger(FailoverTest.class);
-
- private static final String QUEUE = "queue";
- private static final int DEFAULT_NUM_MESSAGES = 10;
- private static final int DEFAULT_SEED = 20080921;
- protected int numMessages = 0;
- protected Connection connection;
- private Session producerSession;
- private Queue queue;
- private MessageProducer producer;
- private Session consumerSession;
- private MessageConsumer consumer;
-
- private CountDownLatch failoverComplete;
- private boolean CLUSTERED = Boolean.getBoolean("profile.clustered");
- private int seed;
- private Random rand;
- private int _currentPort = getFailingPort();
-
- @Override
- protected void setUp() throws Exception
- {
- super.setUp();
-
- numMessages = Integer.getInteger("profile.failoverMsgCount",DEFAULT_NUM_MESSAGES);
- seed = Integer.getInteger("profile.failoverRandomSeed",DEFAULT_SEED);
- rand = new Random(seed);
-
- connection = getConnection();
- ((AMQConnection) connection).setConnectionListener(this);
- connection.start();
- failoverComplete = new CountDownLatch(1);
- }
-
- protected void init(boolean transacted, int mode) throws JMSException, NamingException
- {
- consumerSession = connection.createSession(transacted, mode);
- queue = consumerSession.createQueue(getName()+System.currentTimeMillis());
- consumer = consumerSession.createConsumer(queue);
-
- producerSession = connection.createSession(transacted, mode);
- producer = producerSession.createProducer(queue);
- }
-
- @Override
- public void tearDown() throws Exception
- {
- try
- {
- connection.close();
- }
- catch (Exception e)
- {
-
- }
-
- super.tearDown();
- }
-
- private void consumeMessages(int startIndex,int endIndex, boolean transacted) throws JMSException
- {
- Message msg;
- _logger.debug("**************** Receive (Start: " + startIndex + ", End:" + endIndex + ")***********************");
-
- for (int i = startIndex; i < endIndex; i++)
- {
- msg = consumer.receive(1000);
- assertNotNull("Message " + i + " was null!", msg);
-
- _logger.debug("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
- _logger.debug("Received : " + ((TextMessage) msg).getText());
- _logger.debug("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
-
- assertEquals("Invalid message order","message " + i, ((TextMessage) msg).getText());
-
- }
- _logger.debug("***********************************************************");
-
- if (transacted)
- {
- consumerSession.commit();
- }
- }
-
- private void sendMessages(int startIndex,int endIndex, boolean transacted) throws JMSException
- {
- _logger.debug("**************** Send (Start: " + startIndex + ", End:" + endIndex + ")***********************");
-
- for (int i = startIndex; i < endIndex; i++)
- {
- producer.send(producerSession.createTextMessage("message " + i));
-
- _logger.debug("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
- _logger.debug("Sending message"+i);
- _logger.debug("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
- }
-
- _logger.debug("***********************************************************");
-
- if (transacted)
- {
- producerSession.commit();
- }
- }
-
- public void testP2PFailover() throws Exception
- {
- testP2PFailover(numMessages, true,true, false);
- }
-
- public void testP2PFailoverWithMessagesLeftToConsumeAndProduce() throws Exception
- {
- if (CLUSTERED)
- {
- testP2PFailover(numMessages, false,false, false);
- }
- }
-
- public void testP2PFailoverWithMessagesLeftToConsume() throws Exception
- {
- if (CLUSTERED)
- {
- testP2PFailover(numMessages, false,true, false);
- }
- }
-
- public void testP2PFailoverTransacted() throws Exception
- {
- testP2PFailover(numMessages, true,true, false);
- }
-
- public void testP2PFailoverTransactedWithMessagesLeftToConsumeAndProduce() throws Exception
- {
- // Currently the cluster does not support transactions that span a failover
- if (CLUSTERED)
- {
- testP2PFailover(numMessages, false,false, false);
- }
- }
-
- private void testP2PFailover(int totalMessages, boolean consumeAll, boolean produceAll , boolean transacted) throws JMSException, NamingException
- {
- init(transacted, Session.AUTO_ACKNOWLEDGE);
- runP2PFailover(totalMessages,consumeAll, produceAll , transacted);
- }
-
- protected void runP2PFailover(int totalMessages, boolean consumeAll, boolean produceAll , boolean transacted) throws JMSException, NamingException
- {
- Message msg = null;
- int toProduce = totalMessages;
-
- _logger.debug("===================================================================");
- _logger.debug("Total messages used for the test " + totalMessages + " messages");
- _logger.debug("===================================================================");
-
- if (!produceAll)
- {
- toProduce = totalMessages - rand.nextInt(totalMessages);
- }
-
- _logger.debug("==================");
- _logger.debug("Sending " + toProduce + " messages");
- _logger.debug("==================");
-
- sendMessages(0,toProduce, transacted);
-
- // Consume some messages
- int toConsume = toProduce;
- if (!consumeAll)
- {
- toConsume = toProduce - rand.nextInt(toProduce);
- }
-
- consumeMessages(0,toConsume, transacted);
-
- _logger.debug("==================");
- _logger.debug("Consuming " + toConsume + " messages");
- _logger.debug("==================");
-
- _logger.info("Failing over");
-
- causeFailure(_currentPort, DEFAULT_FAILOVER_TIME);
-
- // Check that you produce and consume the rest of messages.
- _logger.debug("==================");
- _logger.debug("Sending " + (totalMessages-toProduce) + " messages");
- _logger.debug("==================");
-
- sendMessages(toProduce,totalMessages, transacted);
- consumeMessages(toConsume,totalMessages, transacted);
-
- _logger.debug("==================");
- _logger.debug("Consuming " + (totalMessages-toConsume) + " messages");
- _logger.debug("==================");
- }
-
- private void causeFailure(int port, long delay)
- {
-
- failBroker(port);
-
- _logger.info("Awaiting Failover completion");
- try
- {
- if (!failoverComplete.await(delay, TimeUnit.MILLISECONDS))
- {
- fail("failover did not complete");
- }
- }
- catch (InterruptedException e)
- {
- //evil ignore IE.
- }
- }
-
- public void testClientAckFailover() throws Exception
- {
- init(false, Session.CLIENT_ACKNOWLEDGE);
- sendMessages(0,1, false);
- Message msg = consumer.receive();
- assertNotNull("Expected msgs not received", msg);
-
- causeFailure(getFailingPort(), DEFAULT_FAILOVER_TIME);
-
- Exception failure = null;
- try
- {
- msg.acknowledge();
- }
- catch (Exception e)
- {
- failure = e;
- }
- assertNotNull("Exception should be thrown", failure);
- }
-
- /**
- * The client used to have a fixed timeout of 4 minutes after which failover would no longer work.
- * Check that this code has not regressed
- *
- * @throws Exception if something unexpected occurs in the test.
- */
-
- public void test4MinuteFailover() throws Exception
- {
- ConnectionURL connectionURL = getConnectionFactory().getConnectionURL();
-
- int RETRIES = 4;
- int DELAY = 60000;
-
- //Set up a long delay on and large number of retries
- BrokerDetails details = connectionURL.getBrokerDetails(1);
- details.setProperty(BrokerDetails.OPTIONS_RETRY, String.valueOf(RETRIES));
- details.setProperty(BrokerDetails.OPTIONS_CONNECT_DELAY, String.valueOf(DELAY));
-
- connection = new AMQConnection(connectionURL, null);
-
- ((AMQConnection) connection).setConnectionListener(this);
-
- //Start the connection
- connection.start();
-
- long FAILOVER_DELAY = ((long)RETRIES * (long)DELAY);
-
- // Use Nano seconds as it is more accurate for comparision.
- long failTime = System.nanoTime() + FAILOVER_DELAY * 1000000;
-
- //Fail the first broker
- causeFailure(getFailingPort(), FAILOVER_DELAY + DEFAULT_FAILOVER_TIME);
-
- //Reconnection should occur
- assertTrue("Failover did not take long enough", System.nanoTime() > failTime);
- }
-
-
- /**
- * The idea is to run a failover test in a loop by failing over
- * to the other broker each time.
- */
- public void testFailoverInALoop() throws Exception
- {
- if (!CLUSTERED)
- {
- return;
- }
-
- int iterations = Integer.getInteger("profile.failoverIterations",0);
- boolean useAltPort = false;
- int altPort = FAILING_PORT;
- int stdPort = DEFAULT_PORT;
- init(false, Session.AUTO_ACKNOWLEDGE);
- for (int i=0; i < iterations; i++)
- {
- _logger.debug("===================================================================");
- _logger.debug("Failover In a loop : iteration number " + i);
- _logger.debug("===================================================================");
-
- runP2PFailover(numMessages, false,false, false);
- startBroker(_currentPort);
- if (useAltPort)
- {
- _currentPort = altPort;
- useAltPort = false;
- }
- else
- {
- _currentPort = stdPort;
- useAltPort = true;
- }
-
- }
- //To prevent any failover logic being initiated when we shutdown the brokers.
- connection.close();
-
- // Shutdown the brokers
- stopBroker(altPort);
- stopBroker(stdPort);
-
- }
-
- public void bytesSent(long count)
- {
- }
-
- public void bytesReceived(long count)
- {
- }
-
- public boolean preFailover(boolean redirect)
- {
- return true;
- }
-
- public boolean preResubscribe()
- {
- return true;
- }
-
- public void failoverComplete()
- {
- failoverComplete.countDown();
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/client/message/JMSDestinationTest.java b/java/systests/src/main/java/org/apache/qpid/test/client/message/JMSDestinationTest.java
deleted file mode 100644
index a7efe4922b..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/client/message/JMSDestinationTest.java
+++ /dev/null
@@ -1,373 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.client.message;
-
-import org.apache.qpid.configuration.ClientProperties;
-import org.apache.qpid.client.AMQAnyDestination;
-import org.apache.qpid.client.AMQDestination;
-import org.apache.qpid.client.AMQTopic;
-import org.apache.qpid.client.CustomJMSXProperty;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.management.common.mbeans.ManagedQueue;
-import org.apache.qpid.test.utils.JMXTestUtils;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-import javax.jms.Connection;
-import javax.jms.Destination;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageListener;
-import javax.jms.MessageProducer;
-import javax.jms.Queue;
-import javax.jms.Session;
-import javax.jms.Topic;
-import javax.management.openmbean.CompositeDataSupport;
-import javax.management.openmbean.TabularData;
-import java.nio.BufferOverflowException;
-import java.util.Iterator;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-/**
- * From the API Docs getJMSDestination:
- *
- * When a message is received, its JMSDestination value must be equivalent to
- * the value assigned when it was sent.
- */
-public class JMSDestinationTest extends QpidBrokerTestCase
-{
-
- private Connection _connection;
- private Session _session;
-
- private static final String USER = "admin";
- private CountDownLatch _receiveMessage;
- private Message _message;
-
- public void setUp() throws Exception
- {
- //Ensure JMX management is enabled for MovedToQueue test
- setConfigurationProperty("management.enabled", "true");
-
- super.setUp();
-
- _connection = getConnection();
-
- _session = _connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- }
-
- /**
- * Test a message sent to a queue comes back with JMSDestination queue
- *
- * @throws Exception
- */
- public void testQueue() throws Exception
- {
-
- Queue queue = _session.createQueue(getTestQueueName());
-
- MessageConsumer consumer = _session.createConsumer(queue);
-
- sendMessage(_session, queue, 1);
-
- _connection.start();
-
- Message message = consumer.receive(10000);
-
- assertNotNull("Message should not be null", message);
-
- Destination destination = message.getJMSDestination();
-
- assertNotNull("JMSDestination should not be null", destination);
-
- assertEquals("Incorrect Destination type", queue.getClass(), destination.getClass());
- }
-
- /**
- * Test a message sent to a topic comes back with JMSDestination topic
- *
- * @throws Exception
- */
- public void testTopic() throws Exception
- {
-
- Topic topic = _session.createTopic(getTestQueueName() + "Topic");
-
- MessageConsumer consumer = _session.createConsumer(topic);
-
- sendMessage(_session, topic, 1);
-
- _connection.start();
-
- Message message = consumer.receive(10000);
-
- assertNotNull("Message should not be null", message);
-
- Destination destination = message.getJMSDestination();
-
- assertNotNull("JMSDestination should not be null", destination);
-
- assertEquals("Incorrect Destination type", topic.getClass(), destination.getClass());
- }
-
- /**
- * Test a message sent to a topic then moved on the broker
- * comes back with JMSDestination queue.
- *
- * i.e. The client is not just setting the value to be the same as the
- * current consumer destination.
- *
- * This test can only be run against the Java broker as it uses JMX to move
- * messages between queues.
- *
- * @throws Exception
- */
- public void testMovedToQueue() throws Exception
- {
- // Setup JMXUtils
- JMXTestUtils jmxUtils = new JMXTestUtils(this, USER, USER);
- jmxUtils.setUp();
- // Open the JMX Connection
- jmxUtils.open();
- try
- {
-
- Queue queue = _session.createQueue(getTestQueueName());
-
- _session.createConsumer(queue).close();
-
- sendMessage(_session, queue, 1);
-
- Topic topic = _session.createTopic(getTestQueueName() + "Topic");
-
- MessageConsumer consumer = _session.createConsumer(topic);
-
- // Use Management to move message.
-
- ManagedQueue managedQueue = jmxUtils.
- getManagedObject(ManagedQueue.class,
- jmxUtils.getQueueObjectName(getConnectionFactory().getVirtualPath().substring(1),
- getTestQueueName()));
-
- // Find the first message on the queue
- TabularData data = managedQueue.viewMessages(1L, 2L);
-
- Iterator values = data.values().iterator();
- assertTrue("No Messages found via JMX", values.hasNext());
-
- // Get its message ID
- Long msgID = (Long) ((CompositeDataSupport) values.next()).get("AMQ MessageId");
-
- // Start the connection and consume message that has been moved to the
- // queue
- _connection.start();
-
- Message message = consumer.receive(1000);
-
- //Validate we don't have a message on the queue before we start
- assertNull("Message should be null", message);
-
- // Move it to from the topic to the queue
- managedQueue.moveMessages(msgID, msgID, ((AMQTopic) topic).getQueueName());
-
- // Retrieve the newly moved message
- message = consumer.receive(1000);
-
- assertNotNull("Message should not be null", message);
-
- Destination destination = message.getJMSDestination();
-
- assertNotNull("JMSDestination should not be null", destination);
-
- assertEquals("Incorrect Destination type", queue.getClass(), destination.getClass());
-
- }
- finally
- {
- jmxUtils.close();
- }
-
- }
-
- /**
- * Test a message sent to a queue comes back with JMSDestination queue
- * when received via a message listener
- *
- * @throws Exception
- */
- public void testQueueAsync() throws Exception
- {
-
- Queue queue = _session.createQueue(getTestQueueName());
-
- MessageConsumer consumer = _session.createConsumer(queue);
-
- sendMessage(_session, queue, 1);
-
- _connection.start();
-
- _message = null;
- _receiveMessage = new CountDownLatch(1);
-
- consumer.setMessageListener(new MessageListener()
- {
- public void onMessage(Message message)
- {
- _message = message;
- _receiveMessage.countDown();
- }
- });
-
- assertTrue("Timed out waiting for message to be received ", _receiveMessage.await(1, TimeUnit.SECONDS));
-
- assertNotNull("Message should not be null", _message);
-
- Destination destination = _message.getJMSDestination();
-
- assertNotNull("JMSDestination should not be null", destination);
-
- assertEquals("Incorrect Destination type", queue.getClass(), destination.getClass());
- }
-
- /**
- * Test a message received without the JMS_QPID_DESTTYPE can be resent
- * and correctly have the property set.
- *
- * To do this we need to create a 0-10 connection and send a message
- * which is then received by a 0-8/9 client.
- *
- * @throws Exception
- */
- public void testReceiveResend() throws Exception
- {
- // Create a 0-10 Connection and send message
- setSystemProperty(ClientProperties.AMQP_VERSION, "0-10");
-
- Connection connection010 = getConnection();
-
- Session session010 = connection010.createSession(true, Session.SESSION_TRANSACTED);
-
- // Create queue for testing
- Queue queue = session010.createQueue(getTestQueueName());
-
- // Ensure queue exists
- session010.createConsumer(queue).close();
-
- sendMessage(session010, queue, 1);
-
- // Close the 010 connection
- connection010.close();
-
- // Create a 0-8 Connection and receive message
- setSystemProperty(ClientProperties.AMQP_VERSION, "0-8");
-
- Connection connection08 = getConnection();
-
- Session session08 = connection08.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- MessageConsumer consumer = session08.createConsumer(queue);
-
- connection08.start();
-
- Message message = consumer.receive(1000);
-
- assertNotNull("Didn't receive 0-10 message.", message);
-
- // Validate that JMS_QPID_DESTTYPE is not set
- try
- {
- message.getIntProperty(CustomJMSXProperty.JMS_QPID_DESTTYPE.toString());
- fail("JMS_QPID_DESTTYPE should not be set, so should throw NumberFormatException");
- }
- catch (NumberFormatException nfe)
- {
-
- }
-
- // Resend message back to queue and validate that
- // a) getJMSDestination works without the JMS_QPID_DESTTYPE
- // b) we can actually send without a BufferOverFlow.
-
- MessageProducer producer = session08.createProducer(queue);
-
- try
- {
- producer.send(message);
- }
- catch (BufferOverflowException bofe)
- {
- // Print the stack trace so we can validate where the execption occured.
- bofe.printStackTrace();
- fail("BufferOverflowException thrown during send");
- }
-
- message = consumer.receive(1000);
-
- assertNotNull("Didn't receive recent 0-8 message.", message);
-
- // Validate that JMS_QPID_DESTTYPE is not set
- assertEquals("JMS_QPID_DESTTYPE should be set to a Queue", AMQDestination.QUEUE_TYPE,
- message.getIntProperty(CustomJMSXProperty.JMS_QPID_DESTTYPE.toString()));
-
- }
-
- /**
- * Send a message to a custom exchange and then verify
- * the message received has the proper destination set
- *
- * @throws Exception
- */
- public void testGetDestinationWithCustomExchange() throws Exception
- {
-
- AMQDestination dest = new AMQAnyDestination(new AMQShortString("my-exchange"),
- new AMQShortString("direct"),
- new AMQShortString("test"),
- false,
- false,
- new AMQShortString("test"),
- false,
- new AMQShortString[]{new AMQShortString("test")});
-
- // to force the creation of my-exchange.
- sendMessage(_session, dest, 1);
-
- MessageProducer prod = _session.createProducer(dest);
-
- MessageConsumer consumer = _session.createConsumer(dest);
-
- _connection.start();
-
- sendMessage(_session, dest, 1);
-
- Message message = consumer.receive(10000);
-
- assertNotNull("Message should not be null", message);
-
- Destination destination = message.getJMSDestination();
-
- assertNotNull("JMSDestination should not be null", destination);
-
- assertEquals("Incorrect Destination name", "my-exchange", dest.getExchangeName().asString());
- assertEquals("Incorrect Destination type", "direct", dest.getExchangeClass().asString());
- assertEquals("Incorrect Routing Key", "test", dest.getRoutingKey().asString());
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/client/message/MessageToStringTest.java b/java/systests/src/main/java/org/apache/qpid/test/client/message/MessageToStringTest.java
deleted file mode 100644
index 1071861d47..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/client/message/MessageToStringTest.java
+++ /dev/null
@@ -1,257 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.client.message;
-
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.apache.qpid.framing.AMQShortString;
-
-import javax.jms.BytesMessage;
-import javax.jms.Connection;
-import javax.jms.ConnectionFactory;
-import javax.jms.JMSException;
-import javax.jms.MapMessage;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-import javax.jms.ObjectMessage;
-import javax.jms.Queue;
-import javax.jms.Session;
-import javax.jms.StreamMessage;
-import javax.jms.TextMessage;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.ObjectOutput;
-import java.io.ObjectOutputStream;
-import java.util.UUID;
-
-public class MessageToStringTest extends QpidBrokerTestCase
-{
- private Connection _connection;
- private Session _session;
- private Queue _queue;
- MessageConsumer _consumer;
- private static final String BYTE_TEST = "MapByteTest";
-
- public void setUp() throws Exception
- {
- super.setUp();
-
- //Create Producer put some messages on the queue
- _connection = getConnection();
-
- //Create Consumer
- _session = _connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- String queueName = getTestQueueName();
-
- //Create Queue
- ((AMQSession) _session).createQueue(new AMQShortString(queueName), true, false, false);
- _queue = _session.createQueue("direct://amq.direct/"+queueName+"/"+queueName+"?durable='false'&autodelete='true'");
-
-
- _consumer = _session.createConsumer(_queue);
-
- _connection.start();
- }
-
- public void tearDown() throws Exception
- {
- //clean up
- _connection.close();
-
- super.tearDown();
- }
-
- public void testBytesMessage() throws JMSException
- {
- //Create Sample Message using UUIDs
- UUID test = UUID.randomUUID();
-
- BytesMessage testMessage = _session.createBytesMessage();
-
- //Convert UUID into bytes for transit
- byte[] testBytes = test.toString().getBytes();
-
- testMessage.writeBytes(testBytes);
-
- sendAndTest(testMessage, testBytes);
- }
-
- public void testMapMessage() throws JMSException, IOException
- {
- //Create Sample Message using UUIDs
- UUID test = UUID.randomUUID();
-
- MapMessage testMessage = _session.createMapMessage();
-
- byte[] testBytes = convertToBytes(test);
-
- testMessage.setBytes(BYTE_TEST, testBytes);
-
- sendAndTest(testMessage, testBytes);
- }
-
- public void testObjectMessage() throws JMSException
- {
- MessageProducer producer = _session.createProducer(_queue);
-
- //Create Sample Message using UUIDs
- UUID test = UUID.randomUUID();
-
- Message testMessage = _session.createObjectMessage(test);
-
- sendAndTest(testMessage, test);
- }
-
- public void testStreamMessage() throws JMSException, IOException
- {
- //Create Sample Message using UUIDs
- UUID test = UUID.randomUUID();
-
- StreamMessage testMessage = _session.createStreamMessage();
-
- byte[] testBytes = convertToBytes(test);
-
- testMessage.writeBytes(testBytes);
-
- sendAndTest(testMessage, testBytes);
- }
-
- public void testTextMessage() throws JMSException, IOException
- {
- //Create Sample Message using UUIDs
- UUID test = UUID.randomUUID();
-
- TextMessage testMessage = _session.createTextMessage();
-
- String stringValue = String.valueOf(test);
- byte[] testBytes = stringValue.getBytes();
-
- testMessage.setText(stringValue);
-
- sendAndTest(testMessage, testBytes);
- }
-
- //***************** Helpers
-
- private void sendAndTest(Message message, Object testBytes) throws JMSException
- {
- MessageProducer producer = _session.createProducer(_queue);
-
- producer.send(message);
-
- Message receivedMessage = _consumer.receive(1000);
-
- assertNotNull("Message was not received.", receivedMessage);
-
- //Ensure that to calling toString doesn't error and that doing this doesn't break next tests.
- assertNotNull("Message returned null from toString", receivedMessage.toString());
-
- byte[] byteResults;
- UUID result;
-
- try
- {
- if (receivedMessage instanceof ObjectMessage)
- {
- result = (UUID) ((ObjectMessage) receivedMessage).getObject();
- assertEquals("UUIDs were not equal", testBytes, result);
- }
- else
- {
- byteResults = getBytes(receivedMessage, ((byte[]) testBytes).length);
- assertBytesEquals("UUIDs were not equal", (byte[]) testBytes, byteResults);
- }
- }
- catch (Exception e)
- {
- fail(e.getMessage());
- }
-
- }
-
- private void assertBytesEquals(String message, byte[] expected, byte[] actual)
- {
- if (expected.length == actual.length)
- {
- int index = 0;
- boolean failed = false;
- for (byte b : expected)
- {
- if (actual[index++] != b)
- {
- failed = true;
- break;
- }
- }
-
- if (!failed)
- {
- return;
- }
-
- }
-
- fail(message);
- }
-
- private byte[] getBytes(Message receivedMessage, int testBytesLength) throws JMSException
- {
- byte[] byteResults = new byte[testBytesLength];
-
- if (receivedMessage instanceof BytesMessage)
- {
- assertEquals(testBytesLength, ((BytesMessage) receivedMessage).readBytes(byteResults));
- }
- else if (receivedMessage instanceof StreamMessage)
- {
- assertEquals(testBytesLength, ((StreamMessage) receivedMessage).readBytes(byteResults));
- }
- else if (receivedMessage instanceof MapMessage)
- {
- byteResults = ((MapMessage) receivedMessage).getBytes(BYTE_TEST);
- assertEquals(testBytesLength, byteResults.length);
- }
- else if (receivedMessage instanceof TextMessage)
- {
- byteResults = ((TextMessage) receivedMessage).getText().getBytes();
- assertEquals(testBytesLength, byteResults.length);
- }
-
-
- return byteResults;
- }
-
- private byte[] convertToBytes(UUID test) throws IOException
- {
- //Convert UUID into bytes for transit
- ObjectOutput out;
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- out = new ObjectOutputStream(bos);
- out.writeObject(test);
- out.close();
-
- return bos.toByteArray();
- }
-
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/client/message/ObjectMessageTest.java b/java/systests/src/main/java/org/apache/qpid/test/client/message/ObjectMessageTest.java
deleted file mode 100644
index 147a03be0c..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/client/message/ObjectMessageTest.java
+++ /dev/null
@@ -1,141 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.client.message;
-
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.apache.qpid.framing.AMQShortString;
-
-import javax.jms.Connection;
-import javax.jms.JMSException;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-import javax.jms.ObjectMessage;
-import javax.jms.Queue;
-import javax.jms.Session;
-import java.util.UUID;
-
-public class ObjectMessageTest extends QpidBrokerTestCase
-{
- private Connection _connection;
- private Session _session;
- MessageConsumer _consumer;
- MessageProducer _producer;
-
- public void setUp() throws Exception
- {
- super.setUp();
-
- //Create Connection
- _connection = getConnection();
-
-
- //Create Session
- _session = _connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- //Create Queue
- String queueName = getTestQueueName();
- ((AMQSession) _session).createQueue(new AMQShortString(queueName), true, false, false);
- Queue queue = _session.createQueue("direct://amq.direct/"+queueName+"/"+queueName+"?durable='false'&autodelete='true'");
-
- //Create Consumer
- _consumer = _session.createConsumer(queue);
-
- //Create Producer
- _producer = _session.createProducer(queue);
-
- _connection.start();
- }
-
- public void tearDown() throws Exception
- {
- //clean up
- _connection.close();
-
- super.tearDown();
- }
-
- public void testGetAndSend() throws JMSException
- {
- //Create Sample Message using UUIDs
- UUID test = UUID.randomUUID();
-
- ObjectMessage testMessage = _session.createObjectMessage(test);
-
- Object o = testMessage.getObject();
-
- assertNotNull("Object was null", o);
-
- sendAndTest(testMessage, test);
- }
-
- public void testSend() throws JMSException
- {
- //Create Sample Message using UUIDs
- UUID test = UUID.randomUUID();
-
- ObjectMessage testMessage = _session.createObjectMessage(test);
-
- sendAndTest(testMessage, test);
- }
-
- public void testTostringAndSend() throws JMSException
- {
- //Create Sample Message using UUIDs
- UUID test = UUID.randomUUID();
-
- ObjectMessage testMessage = _session.createObjectMessage(test);
-
- assertNotNull("Object was null", testMessage.toString());
-
- sendAndTest(testMessage, test);
- }
-
- public void testSendNull() throws JMSException
- {
-
- ObjectMessage testMessage = _session.createObjectMessage(null);
-
- assertNotNull("Object was null", testMessage.toString());
-
- sendAndTest(testMessage, null);
- }
-
- //***************** Helpers
-
- private void sendAndTest(ObjectMessage message, Object sent) throws JMSException
- {
- _producer.send(message);
-
- ObjectMessage receivedMessage = (ObjectMessage) _consumer.receive(1000);
-
- assertNotNull("Message was not received.", receivedMessage);
-
- UUID result = (UUID) receivedMessage.getObject();
-
- assertEquals("First read: UUIDs were not equal", sent, result);
-
- result = (UUID) receivedMessage.getObject();
-
- assertEquals("Second read: UUIDs were not equal", sent, result);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/client/message/SelectorTest.java b/java/systests/src/main/java/org/apache/qpid/test/client/message/SelectorTest.java
deleted file mode 100644
index 49a608190d..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/client/message/SelectorTest.java
+++ /dev/null
@@ -1,310 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.client.message;
-
-import java.util.concurrent.CountDownLatch;
-
-import javax.jms.DeliveryMode;
-import javax.jms.InvalidSelectorException;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageListener;
-import javax.jms.MessageProducer;
-import javax.jms.Session;
-
-import junit.framework.Assert;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQDestination;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.client.BasicMessageProducer;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class SelectorTest extends QpidBrokerTestCase implements MessageListener
-{
- private static final Logger _logger = LoggerFactory.getLogger(SelectorTest.class);
-
- private AMQConnection _connection;
- private AMQDestination _destination;
- private int count;
- public String _connectionString = "vm://:1";
- private static final String INVALID_SELECTOR = "Cost LIKE 5";
- CountDownLatch _responseLatch = new CountDownLatch(1);
-
- private static final String BAD_MATHS_SELECTOR = " 1 % 5";
-
- private static final long RECIEVE_TIMEOUT = 1000;
-
- protected void setUp() throws Exception
- {
- super.setUp();
- init((AMQConnection) getConnection("guest", "guest"));
- }
-
- private void init(AMQConnection connection) throws JMSException
- {
- init(connection, new AMQQueue(connection, getTestQueueName(), true));
- }
-
- private void init(AMQConnection connection, AMQDestination destination) throws JMSException
- {
- _connection = connection;
- _destination = destination;
- connection.start();
- }
-
- public void onMessage(Message message)
- {
- count++;
- _logger.info("Got Message:" + message);
- _responseLatch.countDown();
- }
-
- public void testUsingOnMessage() throws Exception
- {
- String selector = "Cost = 2 AND \"property-with-hyphen\" = 'wibble'";
- // selector = "JMSType = Special AND Cost = 2 AND AMQMessageID > 0 AND JMSDeliveryMode=" + DeliveryMode.NON_PERSISTENT;
-
- Session session = (AMQSession) _connection.createSession(false, AMQSession.NO_ACKNOWLEDGE);
- // _session.createConsumer(destination).setMessageListener(this);
- session.createConsumer(_destination, selector).setMessageListener(this);
-
- try
- {
- Message msg = session.createTextMessage("Message");
- msg.setJMSPriority(1);
- msg.setIntProperty("Cost", 2);
- msg.setStringProperty("property-with-hyphen", "wibble");
- msg.setJMSType("Special");
-
- _logger.info("Sending Message:" + msg);
-
- ((BasicMessageProducer) session.createProducer(_destination)).send(msg, DeliveryMode.NON_PERSISTENT);
- _logger.info("Message sent, waiting for response...");
-
- _responseLatch.await();
-
- if (count > 0)
- {
- _logger.info("Got message");
- }
-
- if (count == 0)
- {
- fail("Did not get message!");
- // throw new RuntimeException("Did not get message!");
- }
- }
- catch (JMSException e)
- {
- _logger.debug("JMS:" + e.getClass().getSimpleName() + ":" + e.getMessage());
- if (!(e instanceof InvalidSelectorException))
- {
- fail("Wrong exception:" + e.getMessage());
- }
- else
- {
- System.out.println("SUCCESS!!");
- }
- }
- catch (InterruptedException e)
- {
- _logger.debug("IE :" + e.getClass().getSimpleName() + ":" + e.getMessage());
- }
-
- }
-
- public void testUnparsableSelectors() throws Exception
- {
- AMQSession session = (AMQSession) _connection.createSession(false, AMQSession.NO_ACKNOWLEDGE);
- boolean caught = false;
-
- //Try Creating a Browser
- try
- {
- session.createBrowser(session.createQueue("Ping"), INVALID_SELECTOR);
- }
- catch (JMSException e)
- {
- _logger.debug("JMS:" + e.getClass().getSimpleName() + ":" + e.getMessage());
- if (!(e instanceof InvalidSelectorException))
- {
- fail("Wrong exception:" + e.getMessage());
- }
- caught = true;
- }
- assertTrue("No exception thrown!", caught);
- caught = false;
-
- //Try Creating a Consumer
- try
- {
- session.createConsumer(session.createQueue("Ping"), INVALID_SELECTOR);
- }
- catch (JMSException e)
- {
- _logger.debug("JMS:" + e.getClass().getSimpleName() + ":" + e.getMessage());
- if (!(e instanceof InvalidSelectorException))
- {
- fail("Wrong exception:" + e.getMessage());
- }
- caught = true;
- }
- assertTrue("No exception thrown!", caught);
- caught = false;
-
- //Try Creating a Receiever
- try
- {
- session.createReceiver(session.createQueue("Ping"), INVALID_SELECTOR);
- }
- catch (JMSException e)
- {
- _logger.debug("JMS:" + e.getClass().getSimpleName() + ":" + e.getMessage());
- if (!(e instanceof InvalidSelectorException))
- {
- fail("Wrong exception:" + e.getMessage());
- }
- caught = true;
- }
- assertTrue("No exception thrown!", caught);
- caught = false;
-
- try
- {
- session.createReceiver(session.createQueue("Ping"), BAD_MATHS_SELECTOR);
- }
- catch (JMSException e)
- {
- _logger.debug("JMS:" + e.getClass().getSimpleName() + ":" + e.getMessage());
- if (!(e instanceof InvalidSelectorException))
- {
- fail("Wrong exception:" + e.getMessage());
- }
- caught = true;
- }
- assertTrue("No exception thrown!", caught);
- caught = false;
-
- }
-
- public void testRuntimeSelectorError() throws JMSException
- {
- Session session = _connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- MessageConsumer consumer = session.createConsumer(_destination , "testproperty % 5 = 1");
- MessageProducer producer = session.createProducer(_destination);
- Message sentMsg = session.createTextMessage();
-
- sentMsg.setIntProperty("testproperty", 1); // 1 % 5
- producer.send(sentMsg);
- Message recvd = consumer.receive(RECIEVE_TIMEOUT);
- assertNotNull(recvd);
-
- sentMsg.setStringProperty("testproperty", "hello"); // "hello" % 5 makes no sense
- producer.send(sentMsg);
- try
- {
- recvd = consumer.receive(RECIEVE_TIMEOUT);
- assertNull(recvd);
- }
- catch (Exception e)
- {
-
- }
- assertTrue("Connection should be closed", _connection.isClosed());
- }
-
- public void testSelectorWithJMSMessageID() throws Exception
- {
- Session session = _connection.createSession(true, Session.SESSION_TRANSACTED);
-
- MessageProducer prod = session.createProducer(_destination);
- MessageConsumer consumer = session.createConsumer(_destination,"JMSMessageID IS NOT NULL");
-
- for (int i=0; i<2; i++)
- {
- Message msg = session.createTextMessage("Msg" + String.valueOf(i));
- prod.send(msg);
- }
- session.commit();
-
- Message msg1 = consumer.receive(1000);
- Message msg2 = consumer.receive(1000);
-
- Assert.assertNotNull("Msg1 should not be null", msg1);
- Assert.assertNotNull("Msg2 should not be null", msg2);
-
- session.commit();
-
- prod.setDisableMessageID(true);
-
- for (int i=0; i<2; i++)
- {
- Message msg = session.createTextMessage("Msg" + String.valueOf(i));
- prod.send(msg);
- }
-
- session.commit();
- Message msg3 = consumer.receive(1000);
- Assert.assertNull("Msg3 should be null", msg3);
- session.commit();
- consumer = session.createConsumer(_destination,"JMSMessageID IS NULL");
-
- Message msg4 = consumer.receive(1000);
- Message msg5 = consumer.receive(1000);
- session.commit();
- Assert.assertNotNull("Msg4 should not be null", msg4);
- Assert.assertNotNull("Msg5 should not be null", msg5);
- }
-
- public static void main(String[] argv) throws Exception
- {
- SelectorTest test = new SelectorTest();
- test._connectionString = (argv.length == 0) ? "localhost:3000" : argv[0];
-
- try
- {
- while (true)
- {
- if (test._connectionString.contains("vm://:1"))
- {
- test.setUp();
- }
- test.testUsingOnMessage();
-
- if (test._connectionString.contains("vm://:1"))
- {
- test.tearDown();
- }
- }
- }
- catch (Exception e)
- {
- System.err.println(e.getMessage());
- e.printStackTrace();
- }
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/client/queue/LVQTest.java b/java/systests/src/main/java/org/apache/qpid/test/client/queue/LVQTest.java
deleted file mode 100644
index 14fbd1deb6..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/client/queue/LVQTest.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.client.queue;
-
-import javax.jms.Connection;
-import javax.jms.Destination;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-import javax.jms.Session;
-import javax.jms.TextMessage;
-
-import org.apache.qpid.test.client.destination.AddressBasedDestinationTest;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class LVQTest extends QpidBrokerTestCase
-{
- private static final Logger _logger = LoggerFactory.getLogger(LVQTest.class);
- private Connection _connection;
-
- @Override
- public void setUp() throws Exception
- {
- super.setUp();
- _connection = getConnection() ;
- _connection.start();
- }
-
- @Override
- public void tearDown() throws Exception
- {
- _connection.close();
- super.tearDown();
- }
-
- public void testLVQQueue() throws Exception
- {
- String addr = "ADDR:my-lvq-queue; {create: always, " +
- "node: {x-bindings: [{exchange : 'amq.direct', key : test}], " +
- "x-declare:{arguments : {'qpid.last_value_queue':1}}}}";
-
- Session ssn = _connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
-
- Destination dest = ssn.createQueue(addr);
- MessageConsumer consumer = ssn.createConsumer(dest);
- MessageProducer prod = ssn.createProducer(ssn.createQueue("ADDR:amq.direct/test"));
-
- for (int i=0; i<40; i++)
- {
- Message msg = ssn.createTextMessage(String.valueOf(i));
- msg.setStringProperty("qpid.LVQ_key", String.valueOf(i%10));
- prod.send(msg);
- }
-
- for (int i=0; i<10; i++)
- {
- TextMessage msg = (TextMessage)consumer.receive(500);
- assertEquals("The last value is not reflected","3" + i,msg.getText());
- }
-
- assertNull("There should not be anymore messages",consumer.receive(500));
- }
-
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/client/queue/QueuePolicyTest.java b/java/systests/src/main/java/org/apache/qpid/test/client/queue/QueuePolicyTest.java
deleted file mode 100644
index e3557efd97..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/client/queue/QueuePolicyTest.java
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
-*
-* Licensed to the Apache Software Foundation (ASF) under one
-* or more contributor license agreements. See the NOTICE file
-* distributed with this work for additional information
-* regarding copyright ownership. The ASF licenses this file
-* to you under the Apache License, Version 2.0 (the
-* "License"); you may not use this file except in compliance
-* with the License. You may obtain a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing,
-* software distributed under the License is distributed on an
-* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-* KIND, either express or implied. See the License for the
-* specific language governing permissions and limitations
-* under the License.
-*
-*/
-package org.apache.qpid.test.client.queue;
-
-import javax.jms.Connection;
-import javax.jms.Destination;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-import javax.jms.Session;
-import javax.jms.TextMessage;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class QueuePolicyTest extends QpidBrokerTestCase
-{
- private static final Logger _logger = LoggerFactory.getLogger(QueuePolicyTest.class);
- private Connection _connection;
-
- @Override
- public void setUp() throws Exception
- {
- super.setUp();
- _connection = getConnection() ;
- _connection.start();
- }
-
- @Override
- public void tearDown() throws Exception
- {
- _connection.close();
- super.tearDown();
- }
-
- public void testRejectPolicy() throws Exception
- {
- String addr = "ADDR:queue; {create: always, " +
- "node: {x-bindings: [{exchange : 'amq.direct', key : test}], " +
- "x-declare:{ arguments : {'qpid.max_count':5} }}}";
-
- Session ssn = _connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
-
- Destination dest = ssn.createQueue(addr);
- MessageConsumer consumer = ssn.createConsumer(dest);
- MessageProducer prod = ssn.createProducer(ssn.createQueue("ADDR:amq.direct/test"));
-
- for (int i=0; i<6; i++)
- {
- prod.send(ssn.createMessage());
- }
-
- try
- {
- prod.send(ssn.createMessage());
- ((AMQSession)ssn).sync();
- fail("The client did not receive an exception after exceeding the queue limit");
- }
- catch (AMQException e)
- {
- assertTrue("The correct error code is not set",e.getErrorCode().toString().contains("506"));
- }
- }
-
- public void testRingPolicy() throws Exception
- {
- Session ssn = _connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
-
- String addr = "ADDR:my-ring-queue; {create: always, " +
- "node: {x-bindings: [{exchange : 'amq.direct', key : test}], " +
- "x-declare:{arguments : {'qpid.policy_type':ring, 'qpid.max_count':2} }}}";
-
- Destination dest = ssn.createQueue(addr);
- MessageConsumer consumer = ssn.createConsumer(dest);
- MessageProducer prod = ssn.createProducer(ssn.createQueue("ADDR:amq.direct/test"));
-
- prod.send(ssn.createTextMessage("Test1"));
- prod.send(ssn.createTextMessage("Test2"));
- prod.send(ssn.createTextMessage("Test3"));
-
- TextMessage msg = (TextMessage)consumer.receive(1000);
- assertEquals("The consumer should receive the msg with body='Test2'",msg.getText(),"Test2");
-
- msg = (TextMessage)consumer.receive(1000);
- assertEquals("The consumer should receive the msg with body='Test3'",msg.getText(),"Test3");
-
- prod.send(ssn.createTextMessage("Test4"));
- assertEquals("The consumer should receive the msg with body='Test4'",msg.getText(),"Test3");
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/client/timeouts/SyncWaitDelayTest.java b/java/systests/src/main/java/org/apache/qpid/test/client/timeouts/SyncWaitDelayTest.java
deleted file mode 100644
index 85565a33b0..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/client/timeouts/SyncWaitDelayTest.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.test.client.timeouts;
-
-import java.io.File;
-
-import javax.jms.Connection;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-import javax.jms.Queue;
-import javax.jms.Session;
-
-import org.apache.commons.configuration.XMLConfiguration;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-import org.apache.qpid.server.registry.ConfigurationFileApplicationRegistry;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * This tests that when the commit takes a long time(due to POST_COMMIT_DELAY) that the commit does not timeout
- * This test must be run in conjunction with SyncWaiteTimeoutDelay or be run with POST_COMMIT_DELAY > 30s to ensure
- * that the default value is being replaced.
- */
-public class SyncWaitDelayTest extends QpidBrokerTestCase
-{
- protected static final Logger _logger = LoggerFactory.getLogger(SyncWaitDelayTest.class);
-
- private String VIRTUALHOST = "test";
- protected long POST_COMMIT_DELAY = 1000L;
- protected long SYNC_WRITE_TIMEOUT = POST_COMMIT_DELAY + 1000;
-
- protected Connection _connection;
- protected Session _session;
- protected Queue _queue;
- protected MessageConsumer _consumer;
-
- public void setUp() throws Exception
- {
-
- setConfigurationProperty("virtualhosts.virtualhost." + VIRTUALHOST+".store.class", "org.apache.qpid.server.store.SlowMessageStore");
- setConfigurationProperty("virtualhosts.virtualhost." + VIRTUALHOST+".store.delays.commitTran.post", String.valueOf(POST_COMMIT_DELAY));
- setConfigurationProperty("management.enabled", "false");
-
-
- super.setUp();
-
- //Set the syncWrite timeout to be just larger than the delay on the commitTran.
- setSystemProperty("amqj.default_syncwrite_timeout", String.valueOf(SYNC_WRITE_TIMEOUT));
-
- _connection = getConnection();
-
- //Create Queue
- _queue = (Queue) getInitialContext().lookup("queue");
-
- //Create Consumer
- _session = _connection.createSession(true, Session.SESSION_TRANSACTED);
-
- //Ensure Queue exists
- _session.createConsumer(_queue).close();
- }
-
-
- public void test() throws JMSException
- {
- MessageProducer producer = _session.createProducer(_queue);
-
- Message message = _session.createTextMessage("Message");
-
- producer.send(message);
-
- long start = System.nanoTime();
-
- _logger.info("Calling Commit");
-
- try
- {
- _session.commit();
- long end = System.nanoTime();
- long time = (end - start);
- // As we are using Nano time ensure to multiply up the millis.
- assertTrue("Commit was quickier than the built in delay:" + time, time > 1000000L * POST_COMMIT_DELAY);
- assertFalse("Commit was slower than the built in default", time > 1000000L * 1000 * 30);
- }
- catch (JMSException e)
- {
- fail(e.getMessage());
- }
-
- }
-
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/client/timeouts/SyncWaitTimeoutDelayTest.java b/java/systests/src/main/java/org/apache/qpid/test/client/timeouts/SyncWaitTimeoutDelayTest.java
deleted file mode 100644
index 1a23eee8ab..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/client/timeouts/SyncWaitTimeoutDelayTest.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.client.timeouts;
-
-import org.apache.log4j.Level;
-import org.apache.log4j.Logger;
-import org.apache.qpid.AMQTimeoutException;
-
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageProducer;
-
-/** This tests that when the syncWrite timeout is set that it will timeout on that time rather than the default 30s. */
-public class SyncWaitTimeoutDelayTest extends SyncWaitDelayTest
-{
- protected static final Logger _logger = Logger.getLogger(SyncWaitTimeoutDelayTest.class);
-
- public void setUp() throws Exception
- {
- POST_COMMIT_DELAY = 1000L;
-
- //Set the syncWrite timeout to be less than the COMMIT Delay so we can validate that it is being applied
- SYNC_WRITE_TIMEOUT = 500L;
-
- super.setUp();
- }
-
- @Override
- public void test() throws JMSException
- {
- MessageProducer producer = _session.createProducer(_queue);
-
- Message message = _session.createTextMessage("Message");
-
- producer.send(message);
-
- _logger.info("Calling Commit");
-
- long start = System.nanoTime();
- try
- {
- _session.commit();
- fail("Commit occured even though syncWait timeout is shorter than delay in commit");
- }
- catch (JMSException e)
- {
- assertTrue("Wrong exception type received.", e.getLinkedException() instanceof AMQTimeoutException);
- assertTrue("Wrong message received on exception.", e.getMessage().startsWith("Failed to commit"));
- // As we are using Nano time ensure to multiply up the millis.
- assertTrue("Timeout was more than 30s default", (System.nanoTime() - start) < (1000000L * 1000 * 30));
- }
-
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/AMQPPublisher.java b/java/systests/src/main/java/org/apache/qpid/test/framework/AMQPPublisher.java
deleted file mode 100644
index 13465741bd..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/AMQPPublisher.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.framework;
-
-import org.apache.qpid.junit.extensions.util.ParsedProperties;
-
-/**
- * An AMQPPublisher represents the status of the publishing side of a test circuit that exposes AMQP specific features.
- * Its provides additional assertions not available through the plain JMS {@link Publisher} interface.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities
- * <tr><td> Provide assertion that the publishers received a no consumers error code on every message.
- * <tr><td> Provide assertion that the publishers received a no route error code on every message.
- * </table>
- */
-public interface AMQPPublisher extends Publisher
-{
- /**
- * Provides an assertion that the publisher got a no consumers exception on every message.
- *
- * @param testProps The test configuration properties.
- *
- * @return An assertion that the publisher got a no consumers exception on every message.
- */
- Assertion noConsumersAssertion(ParsedProperties testProps);
-
- /**
- * Provides an assertion that the publisher got a no rout exception on every message.
- *
- * @param testProps The test configuration properties.
- *
- * @return An assertion that the publisher got a no rout exception on every message.
- */
- Assertion noRouteAssertion(ParsedProperties testProps);
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/Assertion.java b/java/systests/src/main/java/org/apache/qpid/test/framework/Assertion.java
deleted file mode 100644
index 60d54f1f6f..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/Assertion.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.framework;
-
-/**
- * Assertion models an assertion on a test {@link Circuit}.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities
- * <tr><td> Indicate whether or not the assertion passes when applied.
- * </table>
- */
-public interface Assertion
-{
- /**
- * Applies the assertion.
- *
- * @return <tt>true</tt> if the assertion passes, <tt>false</tt> if it fails.
- */
- public boolean apply();
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/AssertionBase.java b/java/systests/src/main/java/org/apache/qpid/test/framework/AssertionBase.java
deleted file mode 100644
index 0bb4911d4c..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/AssertionBase.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.
- *
- */
-package org.apache.qpid.test.framework;
-
-import java.util.LinkedList;
-import java.util.List;
-
-/**
- * AssertionBase is a base class for implenmenting assertions. It provides a mechanism to store error messages, and
- * report all error messages when its {@link #toString()} method is called.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Collect error messages.
- * </table>
- */
-public abstract class AssertionBase implements Assertion
-{
- /** Holds the error messages. */
- List<String> errors = new LinkedList<String>();
-
- /**
- * Adds an error message to the assertion.
- *
- * @param error An error message to add to the assertion.
- */
- public void addError(String error)
- {
- errors.add(error);
- }
-
- /**
- * Prints all of the error messages in the assertion into a string.
- *
- * @return All of the error messages in the assertion as a string.
- */
- public String toString()
- {
- String result = "";
-
- for (String error : errors)
- {
- result += error;
- }
-
- return result;
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/BrokerLifecycleAware.java b/java/systests/src/main/java/org/apache/qpid/test/framework/BrokerLifecycleAware.java
deleted file mode 100644
index 41614f92fc..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/BrokerLifecycleAware.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.framework;
-
-/**
- * BrokerLifecycleAware is an awareness interface implemented by test cases that can run control the life-cycle of
- * the brokers on which they run. Its purpose is to expose additional instrumentation of brokers during testing, that
- * enables tests to use an automated failure mechanism to simulate broker failures, and to re-start failed brokers.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Indicate whether or not a test case is using an in-vm broker.
- * <tr><td> Track which in-vm broker is currently in use.
- * <tr><td> Accept setting of a failure mechanism. <td> {@link CauseFailure}.
- * </table>
- *
- * @todo Need to think about how to present the brokers through this interface. Thinking numbering the available
- * brokers from 1 will do. Then can kill 1 and assume failing onto 2. Restart 1 and kill 2 and fail back onto
- * 1 again?
- */
-public interface BrokerLifecycleAware
-{
- public void setInVmBrokers();
-
- /**
- * Indicates whether or not a test case is using in-vm brokers.
- *
- * @return <tt>true</tt> if the test is using in-vm brokers, <tt>false</tt> otherwise.
- */
- public boolean usingInVmBroker();
-
- /**
- * Sets the currently live in-vm broker.
- *
- * @param i The currently live in-vm broker.
- */
- public void setLiveBroker(int i);
-
- /**
- * Reports the currently live in-vm broker.
- *
- * @return The currently live in-vm broker.
- */
- public int getLiveBroker();
-
- /**
- * Accepts a failure mechanism.
- *
- * @param failureMechanism The failure mechanism.
- */
- public void setFailureMechanism(CauseFailure failureMechanism);
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/CauseFailure.java b/java/systests/src/main/java/org/apache/qpid/test/framework/CauseFailure.java
deleted file mode 100644
index 9bdd5a72c5..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/CauseFailure.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.framework;
-
-/**
- * CauseFailure provides a method to cause a failure in a messaging broker, usually used in conjunction with fail-over
- * or other failure mode testing. In some cases failures may be automated, for example by shutting down an in-vm broker,
- * or by sending a special control signal to a broker over a network connection. In other cases, it may be preferable
- * to ask a user interactively to cause a failure scenario, in which case an implementation may display a prompt or
- * dialog box asking for notification once the failure has been caused. The purpose of this interface is to abstract
- * the exact cause and nature of a failure out of failure test cases.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities
- * <tr><td> Cause messaging broker failure.
- * </table>
- */
-public interface CauseFailure
-{
- /**
- * Causes the active message broker to fail.
- */
- void causeFailure();
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/CauseFailureUserPrompt.java b/java/systests/src/main/java/org/apache/qpid/test/framework/CauseFailureUserPrompt.java
deleted file mode 100644
index 889df4ad07..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/CauseFailureUserPrompt.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.framework;
-
-import org.apache.qpid.test.framework.CauseFailure;
-
-import java.io.IOException;
-
-/**
- * Causes a message broker failure by interactively prompting the user to cause it.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Cause messaging broker failure.
- * </table>
- */
-public class CauseFailureUserPrompt implements CauseFailure
-{
- /**
- * Causes the active message broker to fail.
- */
- public void causeFailure()
- {
- waitForUser("Cause a broker failure now, then press Return.");
- }
-
- /**
- * Outputs a prompt to the console and waits for the user to press return.
- *
- * @param prompt The prompt to display on the console.
- */
- private void waitForUser(String prompt)
- {
- System.out.println(prompt);
-
- try
- {
- System.in.read();
- }
- catch (IOException e)
- {
- // Ignored.
- }
-
- System.out.println("Continuing.");
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/Circuit.java b/java/systests/src/main/java/org/apache/qpid/test/framework/Circuit.java
deleted file mode 100644
index 4f9ab1a273..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/Circuit.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.framework;
-
-import java.util.List;
-
-/**
- * A Circuit is the basic test unit against which test cases are to be written. A circuit consists of two 'ends', an
- * instigating 'publisher' end and a more passive 'receivers' end.
- *
- * <p/>Once created, the life-cycle of a circuit may be controlled by {@link #start()}ing it, or {@link #close()}ing it.
- * Once started, the circuit is ready to send messages over. Once closed the circuit can no longer be used.
- *
- * <p/>The state of the circuit may be taken with the {@link #check()} method, and asserted against by the
- * {@link #applyAssertions(java.util.List)} method.
- *
- * <p/>There is a default test procedure which may be performed against the circuit. The outline of this procedure is:
- *
- * <p/><pre>
- * Start the circuit.
- * Send test messages.
- * Request a status report.
- * Assert conditions on the publishing end of the circuit.
- * Assert conditions on the receiving end of the circuit.
- * Close the circuit.
- * Pass with no failed assertions or fail with a list of failed assertions.
- * </pre>
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities
- * <tr><td> Supply the publishing and receiving ends of a test messaging circuit.
- * <tr><td> Start the circuit running.
- * <tr><td> Close the circuit down.
- * <tr><td> Take a reading of the circuits state.
- * <tr><td> Apply assertions against the circuits state.
- * <tr><td> Send test messages over the circuit.
- * <tr><td> Perform the default test procedue on the circuit.
- * </table>
- */
-public interface Circuit
-{
- /**
- * Gets the interface on the publishing end of the circuit.
- *
- * @return The publishing end of the circuit.
- */
- public Publisher getPublisher();
-
- /**
- * Gets the interface on the receiving end of the circuit.
- *
- * @return The receiving end of the circuit.
- */
- public Receiver getReceiver();
-
- /**
- * Connects and starts the circuit. After this method is called the circuit is ready to send messages.
- */
- public void start();
-
- /**
- * Checks the test circuit. The effect of this is to gather the circuits state, for both ends of the circuit,
- * into a report, against which assertions may be checked.
- */
- public void check();
-
- /**
- * Closes the circuit. All associated resources are closed.
- */
- public void close();
-
- /**
- * Applied a list of assertions against the test circuit. The {@link #check()} method should be called before doing
- * this, to ensure that the circuit has gathered its state into a report to assert against.
- *
- * @param assertions The list of assertions to apply to the circuit.
- *
- * @return Any assertions that failed.
- */
- public List<Assertion> applyAssertions(List<Assertion> assertions);
-
- /**
- * Runs the default test procedure against the circuit, and checks that all of the specified assertions hold.
- *
- * @param numMessages The number of messages to send using the default test procedure.
- * @param assertions The list of assertions to apply.
- *
- * @return Any assertions that failed.
- */
- public List<Assertion> test(int numMessages, List<Assertion> assertions);
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/CircuitEnd.java b/java/systests/src/main/java/org/apache/qpid/test/framework/CircuitEnd.java
deleted file mode 100644
index 824edd7022..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/CircuitEnd.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.test.framework;
-
-import javax.jms.*;
-
-/**
- * A CircuitEnd is a pair consisting of one message producer and one message consumer, that represents one end of a
- * test circuit. It is a standard unit of connectivity allowing a full-duplex conversation to be held, provided both
- * the consumer and producer are instantiated and configured.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities
- * <tr><td> Provide a message producer for sending messages.
- * <tr><td> Provide a message consumer for receiving messages.
- * </table>
- *
- * @todo Update the {@link org.apache.qpid.test.utils.ConversationFactory} so that it accepts these as the basic conversation
- * connection units.
- */
-public interface CircuitEnd
-{
- /**
- * Gets the message producer at this circuit end point.
- *
- * @return The message producer at with this circuit end point.
- */
- public MessageProducer getProducer();
-
- /**
- * Gets the message consumer at this circuit end point.
- *
- * @return The message consumer at this circuit end point.
- */
- public MessageConsumer getConsumer();
-
- /**
- * Send the specified message over the producer at this end point.
- *
- * @param message The message to send.
- *
- * @throws JMSException Any JMS exception occuring during the send is allowed to fall through.
- */
- public void send(Message message) throws JMSException;
-
- /**
- * Gets the JMS Session associated with this circuit end point.
- *
- * @return The JMS Session associated with this circuit end point.
- */
- public Session getSession();
-
- /**
- * Closes the message producers and consumers and the sessions, associated with this circuit end point.
- *
- * @throws JMSException Any JMSExceptions occurring during the close are allowed to fall through.
- */
- public void close() throws JMSException;
-
- /**
- * Returns the message monitor for reporting on received messages on this circuit end.
- *
- * @return The message monitor for this circuit end.
- */
- public MessageMonitor getMessageMonitor();
-
- /**
- * Returns the exception monitor for reporting on exceptions received on this circuit end.
- *
- * @return The exception monitor for this circuit end.
- */
- public ExceptionMonitor getExceptionMonitor();
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/CircuitEndBase.java b/java/systests/src/main/java/org/apache/qpid/test/framework/CircuitEndBase.java
deleted file mode 100644
index d5a33514df..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/CircuitEndBase.java
+++ /dev/null
@@ -1,152 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.framework;
-
-import javax.jms.*;
-
-/**
- * A CircuitEndBase is a pair consisting of one message producer and one message consumer, that represents one end of a
- * test circuit. It is a standard unit of connectivity allowing a full-duplex conversation to be held, provided both
- * the consumer and producer are instantiated and configured.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities
- * <tr><td> Provide a message producer for sending messages.
- * <tr><td> Provide a message consumer for receiving messages.
- * </table>
- */
-public class CircuitEndBase implements CircuitEnd
-{
- /** Holds the single message producer. */
- MessageProducer producer;
-
- /** Holds the single message consumer. */
- MessageConsumer consumer;
-
- /** Holds the controlSession for the circuit end. */
- Session session;
-
- /** Holds the message monitor for the circuit end. */
- MessageMonitor messageMonitor;
-
- /** Holds the exception monitor for the circuit end. */
- ExceptionMonitor exceptionMonitor;
-
- /**
- * Creates a circuit end point on the specified producer, consumer and controlSession. Monitors are also configured
- * for messages and exceptions received by the circuit end.
- *
- * @param producer The message producer for the circuit end point.
- * @param consumer The message consumer for the circuit end point.
- * @param session The controlSession for the circuit end point.
- * @param messageMonitor The monitor to notify of all messages received by the circuit end.
- * @param exceptionMonitor The monitor to notify of all exceptions received by the circuit end.
- */
- public CircuitEndBase(MessageProducer producer, MessageConsumer consumer, Session session, MessageMonitor messageMonitor,
- ExceptionMonitor exceptionMonitor)
- {
- this.producer = producer;
- this.consumer = consumer;
- this.session = session;
-
- this.messageMonitor = messageMonitor;
- this.exceptionMonitor = exceptionMonitor;
- }
-
- /**
- * Gets the message producer at this circuit end point.
- *
- * @return The message producer at with this circuit end point.
- */
- public MessageProducer getProducer()
- {
- return producer;
- }
-
- /**
- * Gets the message consumer at this circuit end point.
- *
- * @return The message consumer at this circuit end point.
- */
- public MessageConsumer getConsumer()
- {
- return consumer;
- }
-
- /**
- * Send the specified message over the producer at this end point.
- *
- * @param message The message to send.
- * @throws javax.jms.JMSException Any JMS exception occuring during the send is allowed to fall through.
- */
- public void send(Message message) throws JMSException
- {
- producer.send(message);
- }
-
- /**
- * Gets the JMS Session associated with this circuit end point.
- *
- * @return The JMS Session associated with this circuit end point.
- */
- public Session getSession()
- {
- return session;
- }
-
- /**
- * Closes the message producers and consumers and the sessions, associated with this circuit end point.
- *
- * @throws javax.jms.JMSException Any JMSExceptions occurring during the close are allowed to fall through.
- */
- public void close() throws JMSException
- {
- if (producer != null)
- {
- producer.close();
- }
-
- if (consumer != null)
- {
- consumer.close();
- }
- }
-
- /**
- * Returns the message monitor for reporting on received messages on this circuit end.
- *
- * @return The message monitor for this circuit end.
- */
- public MessageMonitor getMessageMonitor()
- {
- return messageMonitor;
- }
-
- /**
- * Returns the exception monitor for reporting on exceptions received on this circuit end.
- *
- * @return The exception monitor for this circuit end.
- */
- public ExceptionMonitor getExceptionMonitor()
- {
- return exceptionMonitor;
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/DropInTest.java b/java/systests/src/main/java/org/apache/qpid/test/framework/DropInTest.java
deleted file mode 100644
index 78b5a72c1f..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/DropInTest.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.framework;
-
-import javax.jms.JMSException;
-import javax.jms.Message;
-
-/**
- * A DropIn test is a test case that can accept late joining test clients into a running test. This can be usefull,
- * for interactive experimentation.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities
- * <tr><td> Accept late joining test clients.
- * </table>
- */
-public interface DropInTest
-{
- /**
- * Should accept a late joining client into a running test case. The client will be enlisted with a control message
- * with the 'CONTROL_TYPE' field set to the value 'LATEJOIN'. It should also provide values for the fields:
- *
- * <p/><table>
- * <tr><td> CLIENT_NAME <td> A unique name for the new client.
- * <tr><td> CLIENT_PRIVATE_CONTROL_KEY <td> The key for the route on which the client receives its control messages.
- * </table>
- *
- * @param message The late joiners join message.
- *
- * @throws JMSException Any JMS Exception are allowed to fall through, indicating that the join failed.
- */
- public void lateJoin(Message message) throws JMSException;
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/ExceptionMonitor.java b/java/systests/src/main/java/org/apache/qpid/test/framework/ExceptionMonitor.java
deleted file mode 100644
index 7d06aba1c0..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/ExceptionMonitor.java
+++ /dev/null
@@ -1,205 +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
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.framework;
-
-import org.apache.log4j.Logger;
-
-import javax.jms.ExceptionListener;
-import javax.jms.JMSException;
-
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * An exception monitor, listens for JMS exception on a connection or consumer. It record all exceptions that it receives
- * and provides methods to test the number and type of exceptions received.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Record all exceptions received.
- * </table>
- */
-public class ExceptionMonitor implements ExceptionListener
-{
- /** Used for debugging. */
- private final Logger log = Logger.getLogger(ExceptionMonitor.class);
-
- /** Holds the received exceptions. */
- List<Exception> exceptions = new ArrayList<Exception>();
-
- /**
- * Receives incoming exceptions.
- *
- * @param e The exception to record.
- */
- public synchronized void onException(JMSException e)
- {
- log.debug("public void onException(JMSException e): called", e);
-
- exceptions.add(e);
- }
-
- /**
- * Checks that no exceptions have been received.
- *
- * @return <tt>true</tt> if no exceptions have been received, <tt>false</tt> otherwise.
- */
- public synchronized boolean assertNoExceptions()
- {
- return exceptions.isEmpty();
- }
-
- /**
- * Checks that exactly one exception has been received.
- *
- * @return <tt>true</tt> if exactly one exception been received, <tt>false</tt> otherwise.
- */
- public synchronized boolean assertOneJMSException()
- {
- return exceptions.size() == 1;
- }
-
- /**
- * Checks that exactly one exception, with a linked cause of the specified type, has been received.
- *
- * @param aClass The type of the linked cause.
- *
- * @return <tt>true</tt> if exactly one exception, with a linked cause of the specified type, been received,
- * <tt>false</tt> otherwise.
- */
- public synchronized boolean assertOneJMSExceptionWithLinkedCause(Class aClass)
- {
- if (exceptions.size() == 1)
- {
- Exception e = exceptions.get(0);
-
- if (e instanceof JMSException)
- {
- JMSException jmse = (JMSException) e;
-
- Exception linkedCause = jmse.getLinkedException();
-
- if ((linkedCause != null) && aClass.isInstance(linkedCause))
- {
- return true;
- }
- }
- }
-
- return false;
- }
-
- /**
- * Checks that at least one exception of the the specified type, has been received.
- *
- * @param exceptionClass The type of the exception.
- *
- * @return <tt>true</tt> if at least one exception of the specified type has been received, <tt>false</tt> otherwise.
- */
- public synchronized boolean assertExceptionOfType(Class exceptionClass)
- {
- // Start by assuming that the exception has no been received.
- boolean passed = false;
-
- // Scan all the exceptions for a match.
- for (Exception e : exceptions)
- {
- if (exceptionClass.isInstance(e))
- {
- passed = true;
-
- break;
- }
- }
-
- return passed;
- }
-
- /**
- * Reports the number of exceptions held by this monitor.
- *
- * @return The number of exceptions held by this monitor.
- */
- public synchronized int size()
- {
- return exceptions.size();
- }
-
- /**
- * Clears the record of received exceptions.
- */
- public synchronized void reset()
- {
- exceptions = new ArrayList<Exception>();
- }
-
- /**
- * Provides a dump of the stack traces of all exceptions that this exception monitor was notified of. Mainly
- * use for debugging/test failure reporting purposes.
- *
- * @return A string containing a dump of the stack traces of all exceptions.
- */
- public synchronized String toString()
- {
- String result = "ExceptionMonitor: holds " + exceptions.size() + " exceptions.\n\n";
-
- for (Exception ex : exceptions)
- {
- result += getStackTrace(ex) + "\n";
- }
-
- return result;
- }
-
- /**
- * Prints an exception stack trace into a string.
- *
- * @param t The throwable to get the stack trace from.
- *
- * @return A string containing the throwables stack trace.
- */
- public static String getStackTrace(Throwable t)
- {
- StringWriter sw = new StringWriter();
- PrintWriter pw = new PrintWriter(sw, true);
- t.printStackTrace(pw);
- pw.flush();
- sw.flush();
-
- return sw.toString();
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/FrameworkBaseCase.java b/java/systests/src/main/java/org/apache/qpid/test/framework/FrameworkBaseCase.java
deleted file mode 100644
index f866cd572f..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/FrameworkBaseCase.java
+++ /dev/null
@@ -1,301 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.framework;
-
-import org.apache.log4j.Logger;
-import org.apache.log4j.NDC;
-
-import org.apache.qpid.test.framework.BrokerLifecycleAware;
-import org.apache.qpid.test.framework.sequencers.CircuitFactory;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-import org.apache.qpid.junit.extensions.SetupTaskAware;
-import org.apache.qpid.junit.extensions.SetupTaskHandler;
-import org.apache.qpid.junit.extensions.util.ParsedProperties;
-import org.apache.qpid.junit.extensions.util.TestContextProperties;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * FrameworkBaseCase provides a starting point for writing test cases against the test framework. Its main purpose is
- * to provide some convenience methods for testing.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Create and clean up in-vm brokers on every test case.
- * <tr><td> Produce lists of assertions from assertion creation calls.
- * <tr><td> Produce JUnit failures from assertion failures.
- * <tr><td> Convert failed assertions to error messages.
- * </table>
- */
-public class FrameworkBaseCase extends QpidBrokerTestCase implements FrameworkTestContext, SetupTaskAware,
- BrokerLifecycleAware
-{
- /** Used for debugging purposes. */
- private static final Logger log = Logger.getLogger(FrameworkBaseCase.class);
-
- private CircuitFactory circuitFactory = new LocalAMQPCircuitFactory();
-
- private ParsedProperties testProps;
-
- private SetupTaskHandler taskHandler = new SetupTaskHandler();
-
- private boolean isUsingInVM;
-
- private CauseFailure failureMechanism = new CauseFailureUserPrompt();
-
- /**
- * Creates a new test case with the specified name.
- *
- * @param name The test case name.
- */
- public FrameworkBaseCase(String name)
- {
- super(name);
- }
-
- /** Holds the test sequencer to create and run test circuits with. */ /**
- * Returns the test case sequencer that provides test circuit, and test sequence implementations. The sequencer
- * that this base case returns by default is suitable for running a test circuit with both circuit ends colocated
- * on the same JVM.
- *
- * @return The test case sequencer.
- */
- protected CircuitFactory getCircuitFactory()
- {
- return circuitFactory;
- }
-
- /**
- * Overrides the default test circuit factory. Test decorators can use this to supply distributed test sequencers or
- * other test circuit factory specializations.
- *
- * @param circuitFactory The new test circuit factory.
- */
- public void setCircuitFactory(CircuitFactory circuitFactory)
- {
- this.circuitFactory = circuitFactory;
- }
-
- /**
- * Reports the current test case name.
- *
- * @return The current test case name.
- */
- public TestCaseVector getTestCaseVector()
- {
- return new TestCaseVector(this.getName(), 0);
- }
-
- /**
- * Reports the current test case parameters.
- *
- * @return The current test case parameters.
- */
- public MessagingTestConfigProperties getTestParameters()
- {
- return new MessagingTestConfigProperties(testProps);
- }
-
- /**
- * Creates a list of assertions.
- *
- * @param asserts The assertions to compile in a list.
- *
- * @return A list of assertions.
- */
- protected List<Assertion> assertionList(Assertion... asserts)
- {
- List<Assertion> result = new ArrayList<Assertion>();
-
- for (Assertion assertion : asserts)
- {
- result.add(assertion);
- }
-
- return result;
- }
-
- /**
- * Generates a JUnit assertion exception (failure) if any assertions are passed into this method, also concatenating
- * all of the error messages in the assertions together to form an error message to diagnose the test failure with.
- *
- * @param asserts The list of failed assertions.
- */
- protected static void assertNoFailures(List<Assertion> asserts)
- {
- log.debug("protected void assertNoFailures(List<Assertion> asserts = " + asserts + "): called");
-
- // Check if there are no assertion failures, and return without doing anything if so.
- if ((asserts == null) || asserts.isEmpty())
- {
- return;
- }
-
- // Compile all of the assertion failure messages together.
- String errorMessage = assertionsToString(asserts);
-
- // Fail with the error message from all of the assertions.
- fail(errorMessage);
- }
-
- /**
- * Converts a list of failed assertions into an error message.
- *
- * @param asserts The failed assertions.
- *
- * @return The error message.
- */
- protected static String assertionsToString(List<Assertion> asserts)
- {
- String errorMessage = "";
-
- for (Assertion assertion : asserts)
- {
- errorMessage += assertion.toString() + "\n";
- }
-
- return errorMessage;
- }
-
- /**
- * Ensures that the in-vm broker is created and initialized.
- *
- * @throws Exception Any exceptions allowed to fall through and fail the test.
- */
- protected void setUp() throws Exception
- {
- super.setUp();
- NDC.push(getName());
-
- testProps = TestContextProperties.getInstance(MessagingTestConfigProperties.defaults);
- }
-
- /**
- * Ensures that the in-vm broker is cleaned up after each test run.
- */
- protected void tearDown()
- {
- NDC.pop();
-
- // Process all optional tear down tasks. This may include in-vm broker clean up, if a decorator has added it.
- taskHandler.runTearDownTasks();
- }
-
- /**
- * Adds the specified task to the tests setup.
- *
- * @param task The task to add to the tests setup.
- */
- public void chainSetupTask(Runnable task)
- {
- taskHandler.chainSetupTask(task);
- }
-
- /**
- * Adds the specified task to the tests tear down.
- *
- * @param task The task to add to the tests tear down.
- */
- public void chainTearDownTask(Runnable task)
- {
- taskHandler.chainTearDownTask(task);
- }
-
- /**
- * Should provide a translation from the junit method name of a test to its test case name as known to the test
- * clients that will run the test. The purpose of this is to convert the JUnit method name into the correct test
- * case name to place into the test invite. For example the method "testP2P" might map onto the interop test case
- * name "TC2_BasicP2P".
- *
- * @param methodName The name of the JUnit test method.
- *
- * @return The name of the corresponding interop test case.
- */
- public String getTestCaseNameForTestMethod(String methodName)
- {
- return methodName;
- }
-
- public void setInVmBrokers()
- {
- isUsingInVM = true;
- }
-
- /**
- * Indicates whether or not a test case is using in-vm brokers.
- *
- * @return <tt>true</tt> if the test is using in-vm brokers, <tt>false</tt> otherwise.
- */
- public boolean usingInVmBroker()
- {
- return isUsingInVM;
- }
-
- /**
- * Sets the currently live in-vm broker.
- *
- * @param i The currently live in-vm broker.
- */
- public void setLiveBroker(int i)
- { }
-
- /**
- * Reports the currently live in-vm broker.
- *
- * @return The currently live in-vm broker.
- */
- public int getLiveBroker()
- {
- return 0;
- }
-
- /**
- * Accepts a failure mechanism.
- *
- * @param failureMechanism The failure mechanism.
- */
- public void setFailureMechanism(CauseFailure failureMechanism)
- {
- this.failureMechanism = failureMechanism;
- }
-
- protected ParsedProperties getTestProps()
- {
- return testProps;
- }
-
- protected void setTestProps(ParsedProperties testProps)
- {
- this.testProps = testProps;
- }
-
- protected SetupTaskHandler getTaskHandler()
- {
- return taskHandler;
- }
-
- protected CauseFailure getFailureMechanism()
- {
- return failureMechanism;
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/FrameworkClientBaseCase.java b/java/systests/src/main/java/org/apache/qpid/test/framework/FrameworkClientBaseCase.java
deleted file mode 100644
index 2322955253..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/FrameworkClientBaseCase.java
+++ /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.
- *
- */
-package org.apache.qpid.test.framework;
-
-/**
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td>
- * </table>
- */
-public class FrameworkClientBaseCase
-{
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/FrameworkTestContext.java b/java/systests/src/main/java/org/apache/qpid/test/framework/FrameworkTestContext.java
deleted file mode 100644
index 9a4668e86f..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/FrameworkTestContext.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.framework;
-
-/**
- * A FrameworkTestContext provides context information to test code about the current test case being run; its name, its
- * parameters.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Provide the name of the current test case.
- * <tr><td> Provide the test parameters.
- * </table>
- */
-public interface FrameworkTestContext
-{
- /**
- * Reports the current test case name.
- *
- * @return The current test case name.
- */
- TestCaseVector getTestCaseVector();
-
- /**
- * Reports the current test case parameters.
- *
- * @return The current test case parameters.
- */
- MessagingTestConfigProperties getTestParameters();
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/LocalAMQPCircuitFactory.java b/java/systests/src/main/java/org/apache/qpid/test/framework/LocalAMQPCircuitFactory.java
deleted file mode 100644
index 4c8f301d1c..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/LocalAMQPCircuitFactory.java
+++ /dev/null
@@ -1,168 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.framework;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.test.framework.localcircuit.LocalAMQPPublisherImpl;
-import org.apache.qpid.test.framework.localcircuit.LocalPublisherImpl;
-
-import org.apache.qpid.junit.extensions.util.ParsedProperties;
-
-import javax.jms.*;
-
-/**
- * LocalAMQPCircuitFactory is a test sequencer that creates test circuits with publishing and receiving ends rooted
- * on the same JVM, allowing AMQP/Qpid specific options to be applied to the circuit.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Provide a standard test procedure over a test circuit.
- * <tr><td> Construct test circuits appropriate to a tests context.
- * <tr><td> Construct test circuits the support AMQP specific options.
- * </table>
- */
-public class LocalAMQPCircuitFactory extends LocalCircuitFactory
-{
- /** Used for debugging. */
- private static final Logger log = Logger.getLogger(LocalAMQPCircuitFactory.class);
-
- /**
- * Builds a circuit end suitable for the publishing side of a test circuit, from standard test parameters.
- *
- * @param connection The connection to build the circuit end on.
- * @param testProps The test parameters to configure the circuit end construction.
- * @param uniqueId A unique number to being numbering destinations from, to make this circuit unique.
- *
- * @return A circuit end suitable for the publishing side of a test circuit.
- *
- * @throws javax.jms.JMSException Any underlying JMSExceptions are allowed to fall through and fail the creation.
- */
- public CircuitEndBase createPublisherCircuitEnd(Connection connection, ParsedProperties testProps, long uniqueId)
- throws JMSException
- {
- log.debug(
- "public CircuitEndBase createPublisherCircuitEnd(Connection connection, ParsedProperties testProps, long uniqueId = "
- + uniqueId + "): called");
-
- // Cast the test properties into a typed interface for convenience.
- MessagingTestConfigProperties props = new MessagingTestConfigProperties(testProps);
-
- Session session = connection.createSession(props.getPublisherTransacted(), props.getAckMode());
-
- Destination destination =
- props.getPubsub() ? session.createTopic(props.getSendDestinationNameRoot() + "_" + uniqueId)
- : session.createQueue(props.getSendDestinationNameRoot() + "_" + uniqueId);
-
- MessageProducer producer =
- props.getPublisherProducerBind()
- ? ((props.getImmediate() || props.getMandatory())
- ? ((AMQSession) session).createProducer(destination, props.getMandatory(), props.getImmediate())
- : session.createProducer(destination)) : null;
-
- MessageConsumer consumer =
- props.getPublisherConsumerBind()
- ? session.createConsumer(session.createQueue(props.getReceiveDestinationNameRoot() + "_" + uniqueId)) : null;
-
- MessageMonitor messageMonitor = new MessageMonitor();
-
- if (consumer != null)
- {
- consumer.setMessageListener(messageMonitor);
- }
-
- ExceptionMonitor exceptionMonitor = new ExceptionMonitor();
- connection.setExceptionListener(exceptionMonitor);
-
- if (!props.getPublisherConsumerActive() && (consumer != null))
- {
- consumer.close();
- }
-
- return new CircuitEndBase(producer, consumer, session, messageMonitor, exceptionMonitor);
- }
-
- /**
- * Builds a circuit end suitable for the receiving side of a test circuit, from standard test parameters.
- *
- * @param connection The connection to build the circuit end on.
- * @param testProps The test parameters to configure the circuit end construction.
- * @param uniqueId A unique number to being numbering destinations from, to make this circuit unique.
- *
- * @return A circuit end suitable for the receiving side of a test circuit.
- *
- * @throws JMSException Any underlying JMSExceptions are allowed to fall through and fail the creation.
- */
- public CircuitEndBase createReceiverCircuitEnd(Connection connection, ParsedProperties testProps, long uniqueId)
- throws JMSException
- {
- log.debug(
- "public CircuitEndBase createReceiverCircuitEnd(Connection connection, ParsedProperties testProps, long uniqueId = "
- + uniqueId + "): called");
-
- // Cast the test properties into a typed interface for convenience.
- MessagingTestConfigProperties props = new MessagingTestConfigProperties(testProps);
-
- Session session = connection.createSession(props.getPublisherTransacted(), props.getAckMode());
-
- MessageProducer producer =
- props.getReceiverProducerBind()
- ? session.createProducer(session.createQueue(props.getReceiveDestinationNameRoot() + "_" + uniqueId)) : null;
-
- Destination destination =
- props.getPubsub() ? session.createTopic(props.getSendDestinationNameRoot() + "_" + uniqueId)
- : session.createQueue(props.getSendDestinationNameRoot() + "_" + uniqueId);
-
- MessageConsumer consumer =
- props.getReceiverConsumerBind()
- ? ((props.getDurableSubscription() && props.getPubsub())
- ? session.createDurableSubscriber((Topic) destination, "testsub") : session.createConsumer(destination))
- : null;
-
- MessageMonitor messageMonitor = new MessageMonitor();
-
- if (consumer != null)
- {
- consumer.setMessageListener(messageMonitor);
- }
-
- if (!props.getReceiverConsumerActive() && (consumer != null))
- {
- consumer.close();
- }
-
- return new CircuitEndBase(producer, consumer, session, messageMonitor, null);
- }
-
- /**
- * Creates a local {@link Publisher} from a {@link CircuitEnd}. The publisher implementation provides AMQP
- * specific assertion methods, for testing beyond JMS.
- *
- * @param publisherEnd The publishing circuit end.
- *
- * @return A {@link Receiver}.
- */
- protected LocalPublisherImpl createPublisherFromCircuitEnd(CircuitEndBase publisherEnd)
- {
- return new LocalAMQPPublisherImpl(publisherEnd);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/LocalCircuitFactory.java b/java/systests/src/main/java/org/apache/qpid/test/framework/LocalCircuitFactory.java
deleted file mode 100644
index ec70759cf7..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/LocalCircuitFactory.java
+++ /dev/null
@@ -1,316 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.framework;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.test.framework.localcircuit.LocalCircuitImpl;
-import org.apache.qpid.test.framework.localcircuit.LocalPublisherImpl;
-import org.apache.qpid.test.framework.localcircuit.LocalReceiverImpl;
-import org.apache.qpid.test.framework.sequencers.CircuitFactory;
-import org.apache.qpid.test.utils.ConversationFactory;
-
-import org.apache.qpid.junit.extensions.util.ParsedProperties;
-
-import javax.jms.*;
-
-import java.util.List;
-import java.util.Properties;
-import java.util.concurrent.atomic.AtomicLong;
-
-/**
- * LocalCircuitFactory is a circuit factory that creates test circuits with publishing and receiving ends rooted
- * on the same JVM. The ends of the circuit are presented as {@link Publisher} and {@link Receiver} interfaces, which
- * in turn provide methods to apply assertions to the circuit. The creation of the circuit ends, and the presentation
- * of the ends as publisher/receiver interfaces, are designed to be overriden, so that circuits and assertions that
- * use messaging features not available in JMS can be written. This provides an extension point for writing tests
- * against proprietary features of JMS implementations.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Provide a standard test procedure over a test circuit.
- * <tr><td> Construct test circuits appropriate to a tests context.
- * </table>
- */
-public class LocalCircuitFactory implements CircuitFactory
-{
- /** Used for debugging. */
- private static final Logger log = Logger.getLogger(LocalCircuitFactory.class);
-
- /** Used to create unique destination names for each test. */
- protected static AtomicLong uniqueDestsId = new AtomicLong();
-
- /**
- * Holds a test coordinating conversation with the test clients. This should consist of assigning the test roles,
- * begining the test and gathering the test reports from the participants.
- *
- * @param testCircuit The test circuit.
- * @param assertions The list of assertions to apply to the test circuit.
- * @param testProperties The test case definition.
- */
- public void sequenceTest(Circuit testCircuit, List<Assertion> assertions, Properties testProperties)
- {
- if (testCircuit != null)
- {
- FrameworkBaseCase.assertNoFailures(testCircuit.test(1, assertions));
- }
- }
-
- /**
- * Creates a test circuit for the test, configered by the test parameters specified.
- *
- * @param testProperties The test parameters.
- *
- * @return A test circuit.
- */
- public Circuit createCircuit(Connection connection, ParsedProperties testProperties)
- {
- Circuit result;
-
- // Cast the test properties into a typed interface for convenience.
- MessagingTestConfigProperties props = new MessagingTestConfigProperties(testProperties);
-
- // Create a standard publisher/receivers test client pair on a shared connection, individual sessions.
- try
- {
- // Get a unique offset to append to destination names to make them unique to the connection.
- long uniqueId = uniqueDestsId.incrementAndGet();
-
- // Add the connection exception listener to assert on exception conditions with.
- // ExceptionMonitor exceptionMonitor = new ExceptionMonitor();
- // connection.setExceptionListener(exceptionMonitor);
-
- // Set up the publisher.
- CircuitEndBase publisherEnd = createPublisherCircuitEnd(connection, props, uniqueId);
-
- // Set up the receiver.
- CircuitEndBase receiverEnd = createReceiverCircuitEnd(connection, props, uniqueId);
-
- // Start listening for incoming messages.
- connection.start();
-
- // Package everything up.
- LocalPublisherImpl publisher = createPublisherFromCircuitEnd(publisherEnd);
- LocalReceiverImpl receiver = createReceiverFromCircuitEnd(receiverEnd);
-
- result = new LocalCircuitImpl(testProperties, publisher, receiver, connection, publisher.getExceptionMonitor());
- }
- catch (JMSException e)
- {
- throw new RuntimeException("Could not create publisher/receivers pair due to a JMSException.", e);
- }
-
- return result;
- }
-
- /**
- * Creates a local {@link Receiver} from a {@link CircuitEnd}. Sub-classes may override this to provide more
- * specialized receivers if necessary.
- *
- * @param receiverEnd The receiving circuit end.
- *
- * @return A {@link Receiver}.
- */
- protected LocalReceiverImpl createReceiverFromCircuitEnd(CircuitEndBase receiverEnd)
- {
- return new LocalReceiverImpl(receiverEnd);
- }
-
- /**
- * Creates a local {@link Publisher} from a {@link CircuitEnd}. Sub-classes may override this to provide more
- * specialized receivers if necessary.
- *
- * @param publisherEnd The publishing circuit end.
- *
- * @return A {@link Receiver}.
- */
- protected LocalPublisherImpl createPublisherFromCircuitEnd(CircuitEndBase publisherEnd)
- {
- return new LocalPublisherImpl(publisherEnd);
- }
-
- /**
- * Builds a circuit end suitable for the publishing side of a test circuit, from standard test parameters.
- *
- * @param connection The connection to build the circuit end on.
- * @param testProps The test parameters to configure the circuit end construction.
- * @param uniqueId A unique number to being numbering destinations from, to make this circuit unique.
- *
- * @return A circuit end suitable for the publishing side of a test circuit.
- *
- * @throws JMSException Any underlying JMSExceptions are allowed to fall through and fail the creation.
- */
- public CircuitEndBase createPublisherCircuitEnd(Connection connection, ParsedProperties testProps, long uniqueId)
- throws JMSException
- {
- log.debug(
- "public CircuitEndBase createPublisherCircuitEnd(Connection connection, ParsedProperties testProps, long uniqueId = "
- + uniqueId + "): called");
-
- // Cast the test properties into a typed interface for convenience.
- MessagingTestConfigProperties props = new MessagingTestConfigProperties(testProps);
-
- // Check that the test properties do not contain AMQP/Qpid specific settings, and fail if they do.
- if (props.getImmediate() || props.getMandatory())
- {
- throw new RuntimeException(
- "Cannot create a pure JMS circuit as the test properties require AMQP specific options.");
- }
-
- Session session = connection.createSession(props.getPublisherTransacted(), props.getAckMode());
-
- Destination destination =
- props.getPubsub() ? session.createTopic(props.getSendDestinationNameRoot() + "_" + uniqueId)
- : session.createQueue(props.getSendDestinationNameRoot() + "_" + uniqueId);
-
- MessageProducer producer = props.getPublisherProducerBind() ? session.createProducer(destination) : null;
-
- MessageConsumer consumer =
- props.getPublisherConsumerBind()
- ? session.createConsumer(session.createQueue(props.getReceiveDestinationNameRoot() + "_" + uniqueId)) : null;
-
- MessageMonitor messageMonitor = new MessageMonitor();
-
- if (consumer != null)
- {
- consumer.setMessageListener(messageMonitor);
- }
-
- ExceptionMonitor exceptionMonitor = new ExceptionMonitor();
- connection.setExceptionListener(exceptionMonitor);
-
- if (!props.getPublisherConsumerActive() && (consumer != null))
- {
- consumer.close();
- }
-
- return new CircuitEndBase(producer, consumer, session, messageMonitor, exceptionMonitor);
- }
-
- /**
- * Builds a circuit end suitable for the receiving side of a test circuit, from standard test parameters.
- *
- * @param connection The connection to build the circuit end on.
- * @param testProps The test parameters to configure the circuit end construction.
- * @param uniqueId A unique number to being numbering destinations from, to make this circuit unique.
- *
- * @return A circuit end suitable for the receiving side of a test circuit.
- *
- * @throws JMSException Any underlying JMSExceptions are allowed to fall through and fail the creation.
- */
- public CircuitEndBase createReceiverCircuitEnd(Connection connection, ParsedProperties testProps, long uniqueId)
- throws JMSException
- {
- log.debug(
- "public CircuitEndBase createReceiverCircuitEnd(Connection connection, ParsedProperties testProps, long uniqueId = "
- + uniqueId + "): called");
-
- // Cast the test properties into a typed interface for convenience.
- MessagingTestConfigProperties props = new MessagingTestConfigProperties(testProps);
-
- // Check that the test properties do not contain AMQP/Qpid specific settings, and fail if they do.
- if (props.getImmediate() || props.getMandatory())
- {
- throw new RuntimeException(
- "Cannot create a pure JMS circuit as the test properties require AMQP specific options.");
- }
-
- Session session = connection.createSession(props.getPublisherTransacted(), props.getAckMode());
-
- MessageProducer producer =
- props.getReceiverProducerBind()
- ? session.createProducer(session.createQueue(props.getReceiveDestinationNameRoot() + "_" + uniqueId)) : null;
-
- Destination destination =
- props.getPubsub() ? session.createTopic(props.getSendDestinationNameRoot() + "_" + uniqueId)
- : session.createQueue(props.getSendDestinationNameRoot() + "_" + uniqueId);
-
- MessageConsumer consumer =
- props.getReceiverConsumerBind()
- ? ((props.getDurableSubscription() && props.getPubsub())
- ? session.createDurableSubscriber((Topic) destination, "testsub") : session.createConsumer(destination))
- : null;
-
- MessageMonitor messageMonitor = new MessageMonitor();
-
- if (consumer != null)
- {
- consumer.setMessageListener(messageMonitor);
- }
-
- if (!props.getReceiverConsumerActive() && (consumer != null))
- {
- consumer.close();
- }
-
- return new CircuitEndBase(producer, consumer, session, messageMonitor, null);
- }
-
- /**
- * Sets the sender test client to coordinate the test with.
- *
- * @param sender The contact details of the sending client in the test.
- */
- public void setSender(TestClientDetails sender)
- {
- throw new RuntimeException("Not implemented.");
- }
-
- /**
- * Sets the receiving test client to coordinate the test with.
- *
- * @param receiver The contact details of the sending client in the test.
- */
- public void setReceiver(TestClientDetails receiver)
- {
- throw new RuntimeException("Not implemented.");
- }
-
- /**
- * Supplies the sending test client.
- *
- * @return The sending test client.
- */
- public TestClientDetails getSender()
- {
- throw new RuntimeException("Not implemented.");
- }
-
- /**
- * Supplies the receiving test client.
- *
- * @return The receiving test client.
- */
- public List<TestClientDetails> getReceivers()
- {
- throw new RuntimeException("Not implemented.");
- }
-
- /**
- * Accepts the conversation factory over which to hold the test coordinating conversation.
- *
- * @param conversationFactory The conversation factory to coordinate the test over.
- */
- public void setConversationFactory(ConversationFactory conversationFactory)
- {
- throw new RuntimeException("Not implemented.");
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/MessageIdentityVector.java b/java/systests/src/main/java/org/apache/qpid/test/framework/MessageIdentityVector.java
deleted file mode 100644
index 397c4e9fbd..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/MessageIdentityVector.java
+++ /dev/null
@@ -1,167 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.framework;
-
-/**
- * MessageIdentityVector provides a message identification scheme, that matches individual messages with test cases.
- * Test messages are being sent by a number of test clients, sending messages over a set of routes, and being received
- * by another set of test clients. Each test is itself, being run within a test cycle, of which there could be many. It
- * is the job of the test coordinator to request and receive reports from the available test clients, on what has been
- * sent, what has been received, and what errors may have occurred, and to reconcile this information against the
- * assertions being applied by the test case. In order to be able to figure out which messages belong to which test,
- * there needs to be an identification scheme, that the coordinator can use to correlate messages in senders and
- * receiver reports. Every message sent in a test can be associated with this information.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Identify a test case, a handling client id, a circuit end within the client, and a test cycle number.
- * </table>
- */
-public class MessageIdentityVector
-{
- /** Holds the test case vector component of the message identity vector. */
- private TestCaseVector testCaseVector;
-
- /** The unique client id. */
- private String clientId;
-
- /** The unique circuit end number within the client id. */
- private int circuitEndId;
-
- /**
- * Creates a new identity vector for test messages.
- *
- * @param testCase The name of the test case generating the messages.
- * @param clientId The unique id of the client implementing a circuit end that is handling the messages.
- * @param circuitEndId The unique id number of the circuit end within the client.
- * @param testCycleNumber The cycle iteration number of the test case.
- */
- public MessageIdentityVector(String testCase, String clientId, int circuitEndId, int testCycleNumber)
- {
- this.testCaseVector = new TestCaseVector(testCase, testCycleNumber);
- this.clientId = clientId;
- this.circuitEndId = circuitEndId;
- }
-
- /**
- * Reports the test case vector component of the message identity vector.
- *
- * @return The test case vector component of the message identity vector.
- */
- public TestCaseVector getTestCaseVector()
- {
- return testCaseVector;
- }
-
- /**
- * Reports the name of the test case.
- *
- * @return The name of the test case.
- */
- public String getTestCase()
- {
- return testCaseVector.getTestCase();
- }
-
- /**
- * Reports the test iteration cycle number within the test case.
- *
- * @return The test iteration cycle number within the test case.
- */
- public int getTestCycleNumber()
- {
- return testCaseVector.getTestCycleNumber();
- }
-
- /**
- * Resports the client id.
- *
- * @return The client id.
- */
- public String getClientId()
- {
- return clientId;
- }
-
- /**
- * Reports the circuit end number within the test client.
- *
- * @return The circuit end number within the test client.
- */
- public int getCircuitEndId()
- {
- return circuitEndId;
- }
-
- /**
- * Compares this identity vector with another for equality. All fields must match.
- *
- * @param o The identity vector to compare with.
- *
- * @return <tt>true</tt> if the identity vector is identical to this one by all fields, <tt>false</tt> otherwise.
- */
- public boolean equals(Object o)
- {
- if (this == o)
- {
- return true;
- }
-
- if ((o == null) || (getClass() != o.getClass()))
- {
- return false;
- }
-
- MessageIdentityVector that = (MessageIdentityVector) o;
-
- if (circuitEndId != that.circuitEndId)
- {
- return false;
- }
-
- if ((clientId != null) ? (!clientId.equals(that.clientId)) : (that.clientId != null))
- {
- return false;
- }
-
- if ((testCaseVector != null) ? (!testCaseVector.equals(that.testCaseVector)) : (that.testCaseVector != null))
- {
- return false;
- }
-
- return true;
- }
-
- /**
- * Computes a hash code for this identity vector based on all fields.
- *
- * @return A hash code for this identity vector based on all fields.
- */
- public int hashCode()
- {
- int result;
- result = ((testCaseVector != null) ? testCaseVector.hashCode() : 0);
- result = (31 * result) + ((clientId != null) ? clientId.hashCode() : 0);
- result = (31 * result) + circuitEndId;
-
- return result;
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/MessageMonitor.java b/java/systests/src/main/java/org/apache/qpid/test/framework/MessageMonitor.java
deleted file mode 100644
index 3fac969369..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/MessageMonitor.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.test.framework;
-
-import org.apache.log4j.Logger;
-
-import javax.jms.Message;
-import javax.jms.MessageListener;
-
-import java.util.concurrent.atomic.AtomicInteger;
-
-/**
- * MessageMonitor is used to record information about messages received. This will provide methods to check various
- * properties, such as the type, number and content of messages received in order to verify the correct behaviour of
- * tests.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Count incoming messages.
- * <tr><td> Record time ellapsed since the arrival of the first message.
- * <tr><td> Reset all counts and timings.
- * </table>
- */
-public class MessageMonitor implements MessageListener
-{
- /** Used for debugging. */
- private final Logger log = Logger.getLogger(MessageMonitor.class);
-
- /** Holds the count of messages received since the last query. */
- protected AtomicInteger numMessages = new AtomicInteger();
-
- /** Holds the time of arrival of the first message. */
- protected Long firstMessageTime = null;
-
- /**
- * Handles received messages. Does Nothing.
- *
- * @param message The message. Ignored.
- */
- public void onMessage(Message message)
- {
- // log.debug("public void onMessage(Message message): called");
-
- numMessages.getAndIncrement();
- }
-
- /**
- * Gets the count of messages.
- *
- * @return The count of messages.
- */
- public int getNumMessage()
- {
- if (firstMessageTime == null)
- {
- firstMessageTime = System.nanoTime();
- }
-
- return numMessages.get();
- }
-
- /**
- * Gets the time elapsed since the first message arrived, in nanos, or zero if no messages have arrived yet.
- *
- * @return The time elapsed since the first message arrived, in nanos, or zero if no messages have arrived yet.
- */
- public long getTime()
- {
- if (firstMessageTime != null)
- {
- return System.nanoTime() - firstMessageTime;
- }
- else
- {
- return 0L;
- }
- }
-
- /**
- * Resets the message count and timer to zero.
- */
- public void reset()
- {
- numMessages.set(0);
- firstMessageTime = null;
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/MessagingTestConfigProperties.java b/java/systests/src/main/java/org/apache/qpid/test/framework/MessagingTestConfigProperties.java
deleted file mode 100644
index 6d72402018..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/MessagingTestConfigProperties.java
+++ /dev/null
@@ -1,685 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.framework;
-
-import org.apache.qpid.junit.extensions.util.ParsedProperties;
-
-import javax.jms.Session;
-
-import java.util.Properties;
-
-/**
- * MessagingTestConfigProperties defines a set of property names and default values for specifying a messaging topology,
- * and test parameters for running a messaging test over that topology. A Properties object holding some of these
- * properties, superimposed onto the defaults, is used to establish test topologies and control test behaviour.
- *
- * <p/>A complete list of the parameters, default values and comments on their usage is provided here:
- *
- * <p/><table><caption>Parameters</caption>
- * <tr><th> Parameter <th> Default <th> Comments
- * <tr><td> messageSize <td> 0 <td> Message size in bytes. Not including any headers.
- * <tr><td> destinationName <td> ping <td> The root name to use to generate destination names to ping.
- * <tr><td> persistent <td> false <td> Determines whether peristent delivery is used.
- * <tr><td> transacted <td> false <td> Determines whether messages are sent/received in transactions.
- * <tr><td> broker <td> tcp://localhost:5672 <td> Determines the broker to connect to.
- * <tr><td> virtualHost <td> test <td> Determines the virtual host to send all ping over.
- * <tr><td> rate <td> 0 <td> The maximum rate (in hertz) to send messages at. 0 means no limit.
- * <tr><td> verbose <td> false <td> The verbose flag for debugging. Prints to console on every message.
- * <tr><td> pubsub <td> false <td> Whether to ping topics or queues. Uses p2p by default.
- * <tr><td> username <td> guest <td> The username to access the broker with.
- * <tr><td> password <td> guest <td> The password to access the broker with.
- * <tr><td> selector <td> null <td> Not used. Defines a message selector to filter pings with.
- * <tr><td> destinationCount <td> 1 <td> The number of receivers listening to the pings.
- * <tr><td> timeout <td> 30000 <td> In milliseconds. The timeout to stop waiting for replies.
- * <tr><td> commitBatchSize <td> 1 <td> The number of messages per transaction in transactional mode.
- * <tr><td> uniqueDests <td> true <td> Whether each receivers only listens to one ping destination or all.
- * <tr><td> durableDests <td> false <td> Whether or not durable destinations are used.
- * <tr><td> ackMode <td> AUTO_ACK <td> The message acknowledgement mode. Possible values are:
- * 0 - SESSION_TRANSACTED
- * 1 - AUTO_ACKNOWLEDGE
- * 2 - CLIENT_ACKNOWLEDGE
- * 3 - DUPS_OK_ACKNOWLEDGE
- * 257 - NO_ACKNOWLEDGE
- * 258 - PRE_ACKNOWLEDGE
- * <tr><td> maxPending <td> 0 <td> The maximum size in bytes, of messages sent but not yet received.
- * Limits the volume of messages currently buffered on the client
- * or broker. Can help scale test clients by limiting amount of buffered
- * data to avoid out of memory errors.
- * </table>
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Provide the names and defaults of all test parameters.
- * </table>
- *
- * @todo Put a type-safe wrapper around these properties, but continue to store the parameters as properties. This is
- * simply to ensure that it is a simple matter to serialize/deserialize string/string pairs onto messages.
- */
-public class MessagingTestConfigProperties extends ParsedProperties
-{
- // ====================== Connection Properties ==================================
-
- /** Holds the name of the default connection configuration. */
- public static final String CONNECTION_NAME = "broker";
-
- /** Holds the name of the property to get the initial context factory name from. */
- public static final String INITIAL_CONTEXT_FACTORY_PROPNAME = "java.naming.factory.initial";
-
- /** Defines the class to use as the initial context factory by default. */
- public static final String INITIAL_CONTEXT_FACTORY_DEFAULT = "org.apache.qpid.jndi.PropertiesFileInitialContextFactory";
-
- /** Holds the name of the property to get the test broker url from. */
- public static final String BROKER_PROPNAME = "qpid.test.broker";
-
- /** Holds the default broker url for the test. */
- public static final String BROKER_DEFAULT = "vm://:1";
-
- /** Holds the name of the property to get the test broker virtual path. */
- public static final String VIRTUAL_HOST_PROPNAME = "virtualHost";
-
- /** Holds the default virtual path for the test. */
- public static final String VIRTUAL_HOST_DEFAULT = "test";
-
- /** Holds the name of the property to get the broker access username from. */
- public static final String USERNAME_PROPNAME = "username";
-
- /** Holds the default broker log on username. */
- public static final String USERNAME_DEFAULT = "guest";
-
- /** Holds the name of the property to get the broker access password from. */
- public static final String PASSWORD_PROPNAME = "password";
-
- /** Holds the default broker log on password. */
- public static final String PASSWORD_DEFAULT = "guest";
-
- // ====================== Messaging Topology Properties ==========================
-
- /** Holds the name of the property to get the bind publisher procuder flag from. */
- public static final String PUBLISHER_PRODUCER_BIND_PROPNAME = "publisherProducerBind";
-
- /** Holds the default value of the publisher producer flag. */
- public static final boolean PUBLISHER_PRODUCER_BIND_DEFAULT = true;
-
- /** Holds the name of the property to get the bind publisher procuder flag from. */
- public static final String PUBLISHER_CONSUMER_BIND_PROPNAME = "publisherConsumerBind";
-
- /** Holds the default value of the publisher consumer flag. */
- public static final boolean PUBLISHER_CONSUMER_BIND_DEFAULT = false;
-
- /** Holds the name of the property to get the bind receivers procuder flag from. */
- public static final String RECEIVER_PRODUCER_BIND_PROPNAME = "receiverProducerBind";
-
- /** Holds the default value of the receivers producer flag. */
- public static final boolean RECEIVER_PRODUCER_BIND_DEFAULT = false;
-
- /** Holds the name of the property to get the bind receivers procuder flag from. */
- public static final String RECEIVER_CONSUMER_BIND_PROPNAME = "receiverConsumerBind";
-
- /** Holds the default value of the receivers consumer flag. */
- public static final boolean RECEIVER_CONSUMER_BIND_DEFAULT = true;
-
- /** Holds the name of the property to get the publishers consumer active flag from. */
- public static final String PUBLISHER_CONSUMER_ACTIVE_PROPNAME = "publisherConsumerActive";
-
- /** Holds the default value of the publishers consumer active flag. */
- public static final boolean PUBLISHER_CONSUMER_ACTIVE_DEFAULT = true;
-
- /** Holds the name of the property to get the receivers consumer active flag from. */
- public static final String RECEIVER_CONSUMER_ACTIVE_PROPNAME = "receiverConsumerActive";
-
- /** Holds the default value of the receivers consumer active flag. */
- public static final boolean RECEIVER_CONSUMER_ACTIVE_DEFAULT = true;
-
- /** Holds the name of the property to get the destination name root from. */
- public static final String SEND_DESTINATION_NAME_ROOT_PROPNAME = "sendDestinationRoot";
-
- /** Holds the root of the name of the default destination to send to. */
- public static final String SEND_DESTINATION_NAME_ROOT_DEFAULT = "sendTo";
-
- /** Holds the name of the property to get the destination name root from. */
- public static final String RECEIVE_DESTINATION_NAME_ROOT_PROPNAME = "receiveDestinationRoot";
-
- /** Holds the root of the name of the default destination to send to. */
- public static final String RECEIVE_DESTINATION_NAME_ROOT_DEFAULT = "receiveFrom";
-
- /** Holds the name of the proeprty to get the destination count from. */
- public static final String DESTINATION_COUNT_PROPNAME = "destinationCount";
-
- /** Defines the default number of destinations to ping. */
- public static final int DESTINATION_COUNT_DEFAULT = 1;
-
- /** Holds the name of the property to get the p2p or pub/sub messaging mode from. */
- public static final String PUBSUB_PROPNAME = "pubsub";
-
- /** Holds the pub/sub mode default, true means ping a topic, false means ping a queue. */
- public static final boolean PUBSUB_DEFAULT = false;
-
- // ====================== JMS Options and Flags =================================
-
- /** Holds the name of the property to get the test delivery mode from. */
- public static final String PERSISTENT_MODE_PROPNAME = "persistent";
-
- /** Holds the message delivery mode to use for the test. */
- public static final boolean PERSISTENT_MODE_DEFAULT = false;
-
- /** Holds the name of the property to get the test transactional mode from. */
- public static final String TRANSACTED_PUBLISHER_PROPNAME = "transactedPublisher";
-
- /** Holds the transactional mode to use for the test. */
- public static final boolean TRANSACTED_PUBLISHER_DEFAULT = false;
-
- /** Holds the name of the property to get the test transactional mode from. */
- public static final String TRANSACTED_RECEIVER_PROPNAME = "transactedReceiver";
-
- /** Holds the transactional mode to use for the test. */
- public static final boolean TRANSACTED_RECEIVER_DEFAULT = false;
-
- /** Holds the name of the property to set the no local flag from. */
- public static final String NO_LOCAL_PROPNAME = "noLocal";
-
- /** Defines the default value of the no local flag to use when consuming messages. */
- public static final boolean NO_LOCAL_DEFAULT = false;
-
- /** Holds the name of the property to get the message acknowledgement mode from. */
- public static final String ACK_MODE_PROPNAME = "ackMode";
-
- /** Defines the default message acknowledgement mode. */
- public static final int ACK_MODE_DEFAULT = Session.AUTO_ACKNOWLEDGE;
-
- /** Holds the name of the property to get the durable subscriptions flag from, when doing pub/sub messaging. */
- public static final String DURABLE_SUBSCRIPTION_PROPNAME = "durableSubscription";
-
- /** Defines the default value of the durable subscriptions flag. */
- public static final boolean DURABLE_SUBSCRIPTION_DEFAULT = false;
-
- // ====================== Qpid/AMQP Options and Flags ================================
-
- /** Holds the name of the property to set the exclusive flag from. */
- public static final String EXCLUSIVE_PROPNAME = "exclusive";
-
- /** Defines the default value of the exclusive flag to use when consuming messages. */
- public static final boolean EXCLUSIVE_DEFAULT = false;
-
- /** Holds the name of the property to set the immediate flag from. */
- public static final String IMMEDIATE_PROPNAME = "immediate";
-
- /** Defines the default value of the immediate flag to use when sending messages. */
- public static final boolean IMMEDIATE_DEFAULT = false;
-
- /** Holds the name of the property to set the mandatory flag from. */
- public static final String MANDATORY_PROPNAME = "mandatory";
-
- /** Defines the default value of the mandatory flag to use when sending messages. */
- public static final boolean MANDATORY_DEFAULT = false;
-
- /** Holds the name of the property to get the durable destinations flag from. */
- public static final String DURABLE_DESTS_PROPNAME = "durableDests";
-
- /** Default value for the durable destinations flag. */
- public static final boolean DURABLE_DESTS_DEFAULT = false;
-
- /** Holds the name of the property to set the prefetch size from. */
- public static final String PREFETCH_PROPNAME = "prefetch";
-
- /** Defines the default prefetch size to use when consuming messages. */
- public static final int PREFETCH_DEFAULT = 100;
-
- // ====================== Common Test Parameters ================================
-
- /** Holds the name of the property to get the test message size from. */
- public static final String MESSAGE_SIZE_PROPNAME = "messageSize";
-
- /** Used to set up a default message size. */
- public static final int MESSAGE_SIZE_DEAFULT = 0;
-
- /** Holds the name of the property to get the message rate from. */
- public static final String RATE_PROPNAME = "rate";
-
- /** Defines the default rate (in pings per second) to send pings at. 0 means as fast as possible, no restriction. */
- public static final int RATE_DEFAULT = 0;
-
- /** Holds the name of the proeprty to get the. */
- public static final String SELECTOR_PROPNAME = "selector";
-
- /** Holds the default message selector. */
- public static final String SELECTOR_DEFAULT = "";
-
- /** Holds the name of the property to get the waiting timeout for response messages. */
- public static final String TIMEOUT_PROPNAME = "timeout";
-
- /** Default time to wait before assuming that a ping has timed out. */
- public static final long TIMEOUT_DEFAULT = 30000;
-
- /** Holds the name of the property to get the commit batch size from. */
- public static final String TX_BATCH_SIZE_PROPNAME = "commitBatchSize";
-
- /** Defines the default number of pings to send in each transaction when running transactionally. */
- public static final int TX_BATCH_SIZE_DEFAULT = 1;
-
- /** Holds the name of the property to set the maximum amount of pending message data for a producer to hold. */
- public static final String MAX_PENDING_PROPNAME = "maxPending";
-
- /** Defines the default maximum quantity of pending message data to allow producers to hold. */
- public static final int MAX_PENDING_DEFAULT = 0;
-
- /** Holds the name of the property to get the publisher rollback flag from. */
- public static final String ROLLBACK_PUBLISHER_PROPNAME = "rollbackPublisher";
-
- /** Holds the default publisher roll back setting. */
- public static final boolean ROLLBACK_PUBLISHER_DEFAULT = false;
-
- /** Holds the name of the property to get the publisher rollback flag from. */
- public static final String ROLLBACK_RECEIVER_PROPNAME = "rollbackReceiver";
-
- /** Holds the default publisher roll back setting. */
- public static final boolean ROLLBACK_RECEIVER_DEFAULT = false;
-
- // ====================== Options that control the bahviour of the test framework. =========================
-
- /** Holds the name of the property to get the behavioural mode of not applicable assertions. */
- public static final String NOT_APPLICABLE_ASSERTION_PROPNAME = "notApplicableAssertion";
-
- /** Holds the default behavioral mode of not applicable assertions, which is logging them as a warning. */
- public static final String NOT_APPLICABLE_ASSERTION_DEFAULT = "warn";
-
- /** Holds the name of the property to get the verbose mode proeprty from. */
- public static final String VERBOSE_PROPNAME = "verbose";
-
- /** Holds the default verbose mode. */
- public static final boolean VERBOSE_DEFAULT = false;
-
- /** Holds the default configuration properties. */
- public static ParsedProperties defaults = new ParsedProperties();
-
- static
- {
- defaults.setPropertyIfNull(INITIAL_CONTEXT_FACTORY_PROPNAME, INITIAL_CONTEXT_FACTORY_DEFAULT);
- defaults.setPropertyIfNull(BROKER_PROPNAME, BROKER_DEFAULT);
- defaults.setPropertyIfNull(VIRTUAL_HOST_PROPNAME, VIRTUAL_HOST_DEFAULT);
- defaults.setPropertyIfNull(USERNAME_PROPNAME, USERNAME_DEFAULT);
- defaults.setPropertyIfNull(PASSWORD_PROPNAME, PASSWORD_DEFAULT);
-
- defaults.setPropertyIfNull(PUBLISHER_PRODUCER_BIND_PROPNAME, PUBLISHER_PRODUCER_BIND_DEFAULT);
- defaults.setPropertyIfNull(PUBLISHER_CONSUMER_BIND_PROPNAME, PUBLISHER_CONSUMER_BIND_DEFAULT);
- defaults.setPropertyIfNull(RECEIVER_PRODUCER_BIND_PROPNAME, RECEIVER_PRODUCER_BIND_DEFAULT);
- defaults.setPropertyIfNull(RECEIVER_CONSUMER_BIND_PROPNAME, RECEIVER_CONSUMER_BIND_DEFAULT);
- defaults.setPropertyIfNull(PUBLISHER_CONSUMER_ACTIVE_PROPNAME, PUBLISHER_CONSUMER_ACTIVE_DEFAULT);
- defaults.setPropertyIfNull(RECEIVER_CONSUMER_ACTIVE_PROPNAME, RECEIVER_CONSUMER_ACTIVE_DEFAULT);
- defaults.setPropertyIfNull(SEND_DESTINATION_NAME_ROOT_PROPNAME, SEND_DESTINATION_NAME_ROOT_DEFAULT);
- defaults.setPropertyIfNull(RECEIVE_DESTINATION_NAME_ROOT_PROPNAME, RECEIVE_DESTINATION_NAME_ROOT_DEFAULT);
- defaults.setPropertyIfNull(DESTINATION_COUNT_PROPNAME, DESTINATION_COUNT_DEFAULT);
- defaults.setPropertyIfNull(PUBSUB_PROPNAME, PUBSUB_DEFAULT);
-
- defaults.setPropertyIfNull(PERSISTENT_MODE_PROPNAME, PERSISTENT_MODE_DEFAULT);
- defaults.setPropertyIfNull(TRANSACTED_PUBLISHER_PROPNAME, TRANSACTED_PUBLISHER_DEFAULT);
- defaults.setPropertyIfNull(TRANSACTED_RECEIVER_PROPNAME, TRANSACTED_RECEIVER_DEFAULT);
- defaults.setPropertyIfNull(NO_LOCAL_PROPNAME, NO_LOCAL_DEFAULT);
- defaults.setPropertyIfNull(ACK_MODE_PROPNAME, ACK_MODE_DEFAULT);
- defaults.setPropertyIfNull(DURABLE_SUBSCRIPTION_PROPNAME, DURABLE_SUBSCRIPTION_DEFAULT);
-
- defaults.setPropertyIfNull(EXCLUSIVE_PROPNAME, EXCLUSIVE_DEFAULT);
- defaults.setPropertyIfNull(IMMEDIATE_PROPNAME, IMMEDIATE_DEFAULT);
- defaults.setPropertyIfNull(MANDATORY_PROPNAME, MANDATORY_DEFAULT);
- defaults.setPropertyIfNull(DURABLE_DESTS_PROPNAME, DURABLE_DESTS_DEFAULT);
- defaults.setPropertyIfNull(PREFETCH_PROPNAME, PREFETCH_DEFAULT);
-
- defaults.setPropertyIfNull(MESSAGE_SIZE_PROPNAME, MESSAGE_SIZE_DEAFULT);
- defaults.setPropertyIfNull(RATE_PROPNAME, RATE_DEFAULT);
- defaults.setPropertyIfNull(SELECTOR_PROPNAME, SELECTOR_DEFAULT);
- defaults.setPropertyIfNull(TIMEOUT_PROPNAME, TIMEOUT_DEFAULT);
- defaults.setPropertyIfNull(TX_BATCH_SIZE_PROPNAME, TX_BATCH_SIZE_DEFAULT);
- defaults.setPropertyIfNull(MAX_PENDING_PROPNAME, MAX_PENDING_DEFAULT);
- defaults.setPropertyIfNull(ROLLBACK_PUBLISHER_PROPNAME, ROLLBACK_PUBLISHER_DEFAULT);
- defaults.setPropertyIfNull(ROLLBACK_RECEIVER_PROPNAME, ROLLBACK_RECEIVER_DEFAULT);
-
- defaults.setPropertyIfNull(NOT_APPLICABLE_ASSERTION_PROPNAME, NOT_APPLICABLE_ASSERTION_DEFAULT);
- defaults.setPropertyIfNull(VERBOSE_PROPNAME, VERBOSE_DEFAULT);
- }
-
- /**
- * Creates a test configuration based on the defaults.
- */
- public MessagingTestConfigProperties()
- {
- super(defaults);
- }
-
- /**
- * Creates a test configuration based on the supplied properties.
- *
- * @param properties The test configuration.
- */
- public MessagingTestConfigProperties(Properties properties)
- {
- super(properties);
- }
-
- /**
- * The size of test messages to send.
- *
- * @return The size of test messages to send.
- */
- public int getMessageSize()
- {
- return getPropertyAsInteger(MESSAGE_SIZE_PROPNAME);
- }
-
- /**
- * Flag to indicate that the publishing producer should be set up to publish to a destination.
- *
- * @return Flag to indicate that the publishing producer should be set up to publish to a destination.
- */
- public boolean getPublisherProducerBind()
- {
- return getPropertyAsBoolean(PUBLISHER_PRODUCER_BIND_PROPNAME);
- }
-
- /**
- * Flag to indicate that the publishing consumer should be set up to receive from a destination.
- *
- * @return Flag to indicate that the publishing consumer should be set up to receive from a destination.
- */
- public boolean getPublisherConsumerBind()
- {
- return getPropertyAsBoolean(PUBLISHER_CONSUMER_BIND_PROPNAME);
- }
-
- /**
- * Flag to indicate that the receiving producer should be set up to publish to a destination.
- *
- * @return Flag to indicate that the receiving producer should be set up to publish to a destination.
- */
- public boolean getReceiverProducerBind()
- {
- return getPropertyAsBoolean(RECEIVER_PRODUCER_BIND_PROPNAME);
- }
-
- /**
- * Flag to indicate that the receiving consumer should be set up to receive from a destination.
- *
- * @return Flag to indicate that the receiving consumer should be set up to receive from a destination.
- */
- public boolean getReceiverConsumerBind()
- {
- return getPropertyAsBoolean(RECEIVER_CONSUMER_BIND_PROPNAME);
- }
-
- /**
- * Flag to indicate that the publishing consumer should be created and actively listening.
- *
- * @return Flag to indicate that the publishing consumer should be created.
- */
- public boolean getPublisherConsumerActive()
- {
- return getPropertyAsBoolean(PUBLISHER_CONSUMER_ACTIVE_PROPNAME);
- }
-
- /**
- * Flag to indicate that the receiving consumers should be created and actively listening.
- *
- * @return Flag to indicate that the receiving consumers should be created and actively listening.
- */
- public boolean getReceiverConsumerActive()
- {
- return getPropertyAsBoolean(RECEIVER_CONSUMER_ACTIVE_PROPNAME);
- }
-
- /**
- * A root to create all test destination names from.
- *
- * @return A root to create all test destination names from.
- */
- public String getSendDestinationNameRoot()
- {
- return getProperty(SEND_DESTINATION_NAME_ROOT_PROPNAME);
- }
-
- /**
- * A root to create all receiving destination names from.
- *
- * @return A root to create all receiving destination names from.
- */
- public String getReceiveDestinationNameRoot()
- {
- return getProperty(RECEIVE_DESTINATION_NAME_ROOT_PROPNAME);
- }
-
- /**
- * Flag to indicate that persistent messages should be used.
- *
- * @return Flag to indicate that persistent messages should be used.
- */
- public boolean getPersistentMode()
- {
- return getPropertyAsBoolean(PERSISTENT_MODE_PROPNAME);
- }
-
- /**
- * Flag to indicate that transactional messages should be sent by the publisher.
- *
- * @return Flag to indicate that transactional messages should be sent by the publisher.
- */
- public boolean getPublisherTransacted()
- {
- return getPropertyAsBoolean(TRANSACTED_PUBLISHER_PROPNAME);
- }
-
- /**
- * Flag to indicate that transactional receives should be used by the receiver.
- *
- * @return Flag to indicate that transactional receives should be used by the receiver.
- */
- public boolean getReceiverTransacted()
- {
- return getPropertyAsBoolean(TRANSACTED_PUBLISHER_PROPNAME);
- }
-
- /**
- * The name of the virtual host to run all tests over.
- *
- * @return The name of the virtual host to run all tests over.
- */
- public String getVirtualHost()
- {
- return getProperty(VIRTUAL_HOST_PROPNAME);
- }
-
- /**
- * Limiting rate for each sender in messages per second, or zero for unlimited.
- *
- * @return Limiting rate for each sender in messages per second, or zero for unlimited.
- */
- public String getRate()
- {
- return getProperty(RATE_PROPNAME);
- }
-
- /**
- * Flag to indicate that test messages should be received publish/subscribe style by all receivers.
- *
- * @return Flag to indicate that test messages should be received publish/subscribe style by all receivers.
- */
- public boolean getPubsub()
- {
- return getPropertyAsBoolean(PUBSUB_PROPNAME);
- }
-
- /**
- * The username credentials to run tests with.
- *
- * @return The username credentials to run tests with.
- */
- public String getUsername()
- {
- return getProperty(USERNAME_PROPNAME);
- }
-
- /**
- * The password credentials to run tests with.
- *
- * @return The password credentials to run tests with.
- */
- public String getPassword()
- {
- return getProperty(PASSWORD_PROPNAME);
- }
-
- /**
- * The timeout duration to fail tests on, should they receive no messages within it.
- *
- * @return The timeout duration to fail tests on, should they receive no messages within it.
- */
- public long getTimeout()
- {
- return getPropertyAsLong(TIMEOUT_PROPNAME);
- }
-
- /**
- * The number of messages to batch into each transaction in transational tests.
- *
- * @return The number of messages to batch into each transaction in transational tests.
- */
- public int getTxBatchSize()
- {
- return getPropertyAsInteger(TX_BATCH_SIZE_PROPNAME);
- }
-
- /**
- * Flag to indicate that tests should use durable destinations.
- *
- * @return Flag to indicate that tests should use durable destinations.
- */
- public boolean getDurableDests()
- {
- return getPropertyAsBoolean(DURABLE_DESTS_PROPNAME);
- }
-
- /**
- * The ack mode for message receivers to use.
- *
- * @return The ack mode for message receivers to use.
- */
- public int getAckMode()
- {
- return getPropertyAsInteger(ACK_MODE_PROPNAME);
- }
-
- /**
- * Flag to indicate that tests should use durable subscriptions.
- *
- * @return Flag to indicate that tests should use durable subscriptions.
- */
- public boolean getDurableSubscription()
- {
- return getPropertyAsBoolean(DURABLE_SUBSCRIPTION_PROPNAME);
- }
-
- /**
- * The maximum amount of in-flight data, in bytes, that tests should send at any time.
- *
- * @return The maximum amount of in-flight data, in bytes, that tests should send at any time.
- */
- public int getMaxPending()
- {
- return getPropertyAsInteger(MAX_PENDING_PROPNAME);
- }
-
- /**
- * The size of the prefetch queue to use.
- *
- * @return The size of the prefetch queue to use.
- */
- public int getPrefetch()
- {
- return getPropertyAsInteger(PREFETCH_PROPNAME);
- }
-
- /**
- * Flag to indicate that subscriptions should be no-local.
- *
- * @return Flag to indicate that subscriptions should be no-local.
- */
- public boolean getNoLocal()
- {
- return getPropertyAsBoolean(NO_LOCAL_PROPNAME);
- }
-
- /**
- * Flag to indicate that subscriptions should be exclusive.
- *
- * @return Flag to indicate that subscriptions should be exclusive.
- */
- public boolean getExclusive()
- {
- return getPropertyAsBoolean(EXCLUSIVE_PROPNAME);
- }
-
- /**
- * Flag to indicate that messages must be delivered immediately.
- *
- * @return Flag to indicate that messages must be delivered immediately.
- */
- public boolean getImmediate()
- {
- return getPropertyAsBoolean(IMMEDIATE_PROPNAME);
- }
-
- /**
- * Flag to indicate that messages must be routable.
- *
- * @return Flag to indicate that messages must be routable.
- */
- public boolean getMandatory()
- {
- return getPropertyAsBoolean(MANDATORY_PROPNAME);
- }
-
- /**
- * Gets the value of a flag to indicate that the publisher should rollback all messages sent.
- *
- * @return A flag to indicate that the publisher should rollback all messages sent.
- */
- public boolean getRollbackPublisher()
- {
- return getPropertyAsBoolean(ROLLBACK_PUBLISHER_PROPNAME);
- }
-
- /**
- * Gets the value of a flag to indicate that the receiver should rollback all messages received, then receive them
- * again.
- *
- * @return A flag to indicate that the publisher should rollback all messages received.
- */
- public boolean getRollbackReceiver()
- {
- return getPropertyAsBoolean(ROLLBACK_RECEIVER_PROPNAME);
- }
-
- /**
- * Gets the behavioural mode of not applicable assertions. Should be one of 'quiet', 'warn' or 'fail'.
- *
- * @return The behavioural mode of not applicable assertions.
- */
- public String getNotApplicableAssertionMode()
- {
- return getProperty(NOT_APPLICABLE_ASSERTION_PROPNAME);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/NotApplicableAssertion.java b/java/systests/src/main/java/org/apache/qpid/test/framework/NotApplicableAssertion.java
deleted file mode 100644
index 2a20be12d6..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/NotApplicableAssertion.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.test.framework;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.junit.extensions.util.ParsedProperties;
-
-/**
- * NotApplicableAssertion is a messaging assertion that can be used when an assertion requested by a test-case is not
- * applicable to the testing scenario. For example an assertion may relate to AMQP functionality, but a test case may be
- * being run over a non-AMQP JMS implementation, in which case the request to create the assertion may return this
- * instead of the proper assertion. The test framework is configurable to quietly drop these assertions, log them
- * as warnings to the console, or raise them as test failures.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Quitely pass.
- * <tr><td> Log a warning.
- * <tr><td> Raise a test failure.
- * </table>
- */
-public class NotApplicableAssertion implements Assertion
-{
- /** Used for logging to the console. */
- private static final Logger console = Logger.getLogger("CONSOLE." + NotApplicableAssertion.class.getName());
-
- /** The possible behavioural modes of this assertion. */
- private enum Mode
- {
- /** Quietly ignore the assertion by passing. */
- Quiet,
-
- /** Ignore the assertion by passing but log a warning about it. */
- Warn,
-
- /** Fail the assertion. */
- Fail;
- }
-
- /** The behavioural mode of the assertion. */
- private Mode mode;
-
- /**
- * Creates an assertion that is driven by the value of the 'notApplicableAssertion' property of the test
- * configuration. Its value should match one of 'quiet', 'warn' or 'fail' and if it does not it is automatically
- * read as 'fail'.
- *
- * @param testProperties The test configuration properties.
- */
- public NotApplicableAssertion(ParsedProperties testProperties)
- {
- // Cast the test properties into a typed interface for convenience.
- MessagingTestConfigProperties props = new MessagingTestConfigProperties(testProperties);
-
- String modeName = props.getNotApplicableAssertionMode();
-
- if ("quiet".equals(modeName))
- {
- mode = Mode.Quiet;
- }
- else if ("warn".equals(modeName))
- {
- mode = Mode.Warn;
- }
- else
- {
- mode = Mode.Fail;
- }
- }
-
- /**
- * Applies the assertion.
- *
- * @return <tt>true</tt> if the assertion passes, <tt>false</tt> if it fails.
- */
- public boolean apply()
- {
- switch (mode)
- {
- case Quiet:
- return true;
-
- case Warn:
- console.warn("Warning: Not applicable assertion being ignored.");
-
- return true;
-
- case Fail:
- default:
- return false;
- }
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/Publisher.java b/java/systests/src/main/java/org/apache/qpid/test/framework/Publisher.java
deleted file mode 100644
index 2c8be4f787..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/Publisher.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.framework;
-
-import org.apache.qpid.junit.extensions.util.ParsedProperties;
-
-/**
- * A Publisher represents the status of the publishing side of a test circuit. Its main purpose is to provide assertions
- * that can be applied to test the behaviour of the publishers.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities
- * <tr><td> Provide assertion that the publishers received no exceptions.
- * </table>
- *
- * @todo There are mixtures of AMQP and JMS assertions in this interface. Either keep them here, but quietly (or with a
- * warning or error) drop them from test cases where they are not relevant, or push them down into sub-classes.
- * I am tempted to go with the dropping/warning/error approach, that would imply that it makes sense to pull
- * the assertions back from AMQPPublisher to here.
- */
-public interface Publisher
-{
- // Assertions that are meaningfull to AMQP and to JMS.
-
- /**
- * Provides an assertion that the publisher encountered no exceptions.
- *
- * @param testProps The test configuration properties.
- *
- * @return An assertion that the publisher encountered no exceptions.
- */
- public Assertion noExceptionsAssertion(ParsedProperties testProps);
-
- // Assertions that are meaningfull only to AMQP.
-
- /**
- * Provides an assertion that the AMQP channel was forcibly closed by an error condition.
- *
- * @param testProps The test configuration properties.
- *
- * @return An assertion that the AMQP channel was forcibly closed by an error condition.
- */
- public Assertion channelClosedAssertion(ParsedProperties testProps);
-
- // Assertions that are meaningfull only to Java/JMS.
-
- /**
- * Provides an assertion that the publisher got a given exception during the test.
- *
- * @param testProps The test configuration properties.
- * @param exceptionClass The exception class to check for.
- *
- * @return An assertion that the publisher got a given exception during the test.
- */
- public Assertion exceptionAssertion(ParsedProperties testProps, Class<? extends Exception> exceptionClass);
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/Receiver.java b/java/systests/src/main/java/org/apache/qpid/test/framework/Receiver.java
deleted file mode 100644
index 19dc4d90e7..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/Receiver.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.test.framework;
-
-import org.apache.qpid.junit.extensions.util.ParsedProperties;
-
-/**
- * A Receiver is a {@link CircuitEnd} that represents the status of the receiving side of a test circuit. Its main
- * purpose is to provide assertions that can be applied to check the behaviour of the receivers.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities
- * <tr><td> Provide assertion that the receivers received no exceptions.
- * <tr><td> Provide assertion that the receivers received all test messages sent to it.
- * </table>
- *
- * @todo There are mixtures of AMQP and JMS assertions in this interface. Either keep them here, but quietly (or with a
- * warning or error) drop them from test cases where they are not relevant, or push them down into sub-classes.
- * I am tempted to go with the dropping/warning/error approach.
- */
-public interface Receiver
-{
- // Assertions that are meaningfull to AMQP and to JMS.
-
- /**
- * Provides an assertion that the receivers encountered no exceptions.
- *
- * @param testProps The test configuration properties.
- *
- * @return An assertion that the receivers encountered no exceptions.
- */
- public Assertion noExceptionsAssertion(ParsedProperties testProps);
-
- /**
- * Provides an assertion that the receivers got all messages that were sent to it.
- *
- * @param testProps The test configuration properties.
- *
- * @return An assertion that the receivers got all messages that were sent to it.
- */
- public Assertion allMessagesReceivedAssertion(ParsedProperties testProps);
-
- /**
- * Provides an assertion that the receivers got none of the messages that were sent to it.
- *
- * @param testProps The test configuration properties.
- *
- * @return An assertion that the receivers got none of the messages that were sent to it.
- */
- public Assertion noMessagesReceivedAssertion(ParsedProperties testProps);
-
- // Assertions that are meaningfull only to AMQP.
-
- /**
- * Provides an assertion that the AMQP channel was forcibly closed by an error condition.
- *
- * @param testProps The test configuration properties.
- *
- * @return An assertion that the AMQP channel was forcibly closed by an error condition.
- */
- public Assertion channelClosedAssertion(ParsedProperties testProps);
-
- // Assertions that are meaningfull only to Java/JMS.
-
- /**
- * Provides an assertion that the receiver got a given exception during the test.
- *
- * @param testProps The test configuration properties.
- * @param exceptionClass The exception class to check for.
- *
- * @return An assertion that the receiver got a given exception during the test.
- */
- public Assertion exceptionAssertion(ParsedProperties testProps, Class<? extends Exception> exceptionClass);
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/TestCaseVector.java b/java/systests/src/main/java/org/apache/qpid/test/framework/TestCaseVector.java
deleted file mode 100644
index ad1e70f6f7..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/TestCaseVector.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.test.framework;
-
-/**
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td>
- * </table>
- */
-public class TestCaseVector
-{
- /** The test case name. */
- private String testCase;
-
- /** The test cycle number within the test case. */
- private int testCycleNumber;
-
- public TestCaseVector(String testCase, int testCycleNumber)
- {
- this.testCase = testCase;
- this.testCycleNumber = testCycleNumber;
- }
-
- public String getTestCase()
- {
- return testCase;
- }
-
- public int getTestCycleNumber()
- {
- return testCycleNumber;
- }
-
- public boolean equals(Object o)
- {
- if (this == o)
- {
- return true;
- }
-
- if ((o == null) || (getClass() != o.getClass()))
- {
- return false;
- }
-
- TestCaseVector that = (TestCaseVector) o;
-
- if (testCycleNumber != that.testCycleNumber)
- {
- return false;
- }
-
- if ((testCase != null) ? (!testCase.equals(that.testCase)) : (that.testCase != null))
- {
- return false;
- }
-
- return true;
- }
-
- public int hashCode()
- {
- int result;
- result = ((testCase != null) ? testCase.hashCode() : 0);
- result = (31 * result) + testCycleNumber;
-
- return result;
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/TestClientDetails.java b/java/systests/src/main/java/org/apache/qpid/test/framework/TestClientDetails.java
deleted file mode 100644
index 7498f2b6b5..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/TestClientDetails.java
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.framework;
-
-/**
- * TestClientDetails is used to encapsulate information about an interop test client. It pairs together the unique
- * name of the client, and the route on which it listens to its control messages.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Record test clients control addresses together with their names.
- * </table>
- */
-public class TestClientDetails
-{
- /** The test clients name. */
- public String clientName;
-
- /* The test clients unique sequence number. Not currently used. */
-
- /** The routing key of the test clients control topic. */
- public String privateControlKey;
-
- /**
- * Two TestClientDetails are considered to be equal, iff they have the same client name.
- *
- * @param o The object to compare to.
- *
- * @return <tt>If the object to compare to is a TestClientDetails equal to this one, <tt>false</tt> otherwise.
- */
- public boolean equals(Object o)
- {
- if (this == o)
- {
- return true;
- }
-
- if (!(o instanceof TestClientDetails))
- {
- return false;
- }
-
- final TestClientDetails testClientDetails = (TestClientDetails) o;
-
- return !((clientName != null) ? (!clientName.equals(testClientDetails.clientName))
- : (testClientDetails.clientName != null));
- }
-
- /**
- * Computes a hash code compatible with the equals method; based on the client name alone.
- *
- * @return A hash code for this.
- */
- public int hashCode()
- {
- return ((clientName != null) ? clientName.hashCode() : 0);
- }
-
- /**
- * Outputs the client name and address details. Mostly used for debugging purposes.
- *
- * @return The client name and address.
- */
- public String toString()
- {
- return "TestClientDetails: [ clientName = " + clientName + ", privateControlKey = " + privateControlKey + " ]";
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/TestUtils.java b/java/systests/src/main/java/org/apache/qpid/test/framework/TestUtils.java
deleted file mode 100644
index f1adeead80..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/TestUtils.java
+++ /dev/null
@@ -1,192 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.framework;
-
-import org.apache.log4j.Logger;
-
-import static org.apache.qpid.test.framework.MessagingTestConfigProperties.*;
-
-import org.apache.qpid.junit.extensions.util.ParsedProperties;
-
-import javax.jms.*;
-import javax.naming.Context;
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-
-import java.util.Map;
-
-/**
- * TestUtils provides static helper methods that are usefull for writing tests against QPid.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Create connections from test properties. <td> {@link MessagingTestConfigProperties}
- * <tr><td> Create test messages.
- * <tr><td> Inject a short pause in a test.
- * <tr><td> Serialize properties into a message.
- * </table>
- */
-public class TestUtils
-{
- /** Used for debugging. */
- private static Logger log = Logger.getLogger(TestUtils.class);
-
- /** Some dummy data to stuff all test messages with. */
- private static final byte[] MESSAGE_DATA_BYTES =
- "Test Message -- Test Message -- Test Message -- Test Message -- Test Message -- Test Message -- Test Message -- "
- .getBytes();
-
- /**
- * Establishes a JMS connection using a set of properties and qpids built in JNDI implementation. This is a simple
- * convenience method for code that does not anticipate handling connection failures. All exceptions that indicate
- * that the connection has failed, are wrapped as rutime exceptions, presumably handled by a top level failure
- * handler.
- *
- * <p/>This utility makes use of the following test parameters from {@link MessagingTestConfigProperties} to control
- * the connection creation:
- *
- * <p/><table>
- * <tr><td> {@link MessagingTestConfigProperties#USERNAME_PROPNAME} <td> The username.
- * <tr><td> {@link MessagingTestConfigProperties#PASSWORD_PROPNAME} <td> The password.
- * <tr><td> {@link MessagingTestConfigProperties#VIRTUAL_HOST_PROPNAME} <td> The virtual host name.
- * <tr><td> {@link MessagingTestConfigProperties#BROKER_PROPNAME} <td> The broker URL.
- * <tr><td> {@link MessagingTestConfigProperties#CONNECTION_NAME} <td> The broker name in the initial context.
- *
- * @param messagingProps Connection properties as defined in {@link MessagingTestConfigProperties}.
- *
- * @return A JMS conneciton.
- */
- public static Connection createConnection(ParsedProperties messagingProps)
- {
- log.debug("public static Connection createConnection(ParsedProperties messagingProps = " + messagingProps
- + "): called");
-
- try
- {
- // Extract the configured connection properties from the test configuration.
- String conUsername = messagingProps.getProperty(USERNAME_PROPNAME);
- String conPassword = messagingProps.getProperty(PASSWORD_PROPNAME);
- String virtualHost = messagingProps.getProperty(VIRTUAL_HOST_PROPNAME);
- String brokerUrl = messagingProps.getProperty(BROKER_PROPNAME);
-
- // Create the broker connection url.
- String connectionString =
- "amqp://" + conUsername + ":" + conPassword + "@clientid/" + ((virtualHost != null) ? virtualHost : "")
- + "?brokerlist='" + brokerUrl + "'";
-
- // Create properties to create the initial context from, and inject the connection factory configuration
- // for the defined connection name into it.
- messagingProps.setProperty("connectionfactory." + CONNECTION_NAME, connectionString);
-
- Context ctx = new InitialContext(messagingProps);
-
- ConnectionFactory cf = (ConnectionFactory) ctx.lookup(CONNECTION_NAME);
-
- return cf.createConnection();
- }
- catch (NamingException e)
- {
- throw new RuntimeException("Got JNDI NamingException whilst looking up the connection factory.", e);
- }
- catch (JMSException e)
- {
- throw new RuntimeException("Could not establish connection due to JMSException.", e);
- }
- }
-
- /**
- * Creates a test message of the specified size, on the given JMS session.
- *
- * @param session The JMS session.
- * @param size The size of the message in bytes.
- *
- * @return A bytes message, of the specified size, filled with dummy data.
- *
- * @throws JMSException Any underlying JMSExceptions are allowed to fall through.
- */
- public static Message createTestMessageOfSize(Session session, int size) throws JMSException
- {
- BytesMessage message = session.createBytesMessage();
-
- if (size > 0)
- {
- int div = size / MESSAGE_DATA_BYTES.length;
- int mod = size % MESSAGE_DATA_BYTES.length;
-
- for (int i = 0; i < div; i++)
- {
- message.writeBytes(MESSAGE_DATA_BYTES);
- }
-
- if (mod != 0)
- {
- message.writeBytes(MESSAGE_DATA_BYTES, 0, mod);
- }
- }
-
- return message;
- }
-
- /**
- * Pauses for the specified length of time. In the event of failing to pause for at least that length of time
- * due to interuption of the thread, a RutimeException is raised to indicate the failure. The interupted status
- * of the thread is restores in that case. This method should only be used when it is expected that the pause
- * will be succesfull, for example in test code that relies on inejecting a pause.
- *
- * @param t The minimum time to pause for in milliseconds.
- */
- public static void pause(long t)
- {
- try
- {
- Thread.sleep(t);
- }
- catch (InterruptedException e)
- {
- // Restore the interrupted status
- Thread.currentThread().interrupt();
-
- throw new RuntimeException("Failed to generate the requested pause length.", e);
- }
- }
-
- /**
- * Sets properties of different types on a JMS Message.
- *
- * @param message The message to set properties on.
- * @param properties The property name/value pairs to set.
- *
- * @throws javax.jms.JMSException All underlying JMSExceptions are allowed to fall through.
- *
- * @todo Move this helper method somewhere else. For example, TestUtils.
- */
- public static void setPropertiesOnMessage(Message message, Map<Object, Object> properties) throws JMSException
- {
- for (Map.Entry<Object, Object> entry : properties.entrySet())
- {
- String name = entry.getKey().toString();
- Object value = entry.getValue();
-
- message.setObjectProperty(name, value);
- }
- }
-}
-
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/clocksynch/ClockSynchFailureException.java b/java/systests/src/main/java/org/apache/qpid/test/framework/clocksynch/ClockSynchFailureException.java
deleted file mode 100644
index 00cc2d8966..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/clocksynch/ClockSynchFailureException.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.framework.clocksynch;
-
-/**
- * ClockSynchFailureException represents failure of a {@link ClockSynchronizer} to achieve synchronization. For example,
- * this could be because a reference signal is not available, or because a desired accurracy cannot be attained.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Represent failure to achieve synchronization.
- * </table>
- */
-public class ClockSynchFailureException extends Exception
-{
- /**
- * Creates a clock synch failure exception.
- *
- * @param message The detail message (which is saved for later retrieval by the {@link #getMessage()} method).
- * @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). (A <tt>null</tt>
- * value is permitted, and indicates that the cause is nonexistent or unknown.)
- */
- public ClockSynchFailureException(String message, Throwable cause)
- {
- super(message, cause);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/clocksynch/ClockSynchThread.java b/java/systests/src/main/java/org/apache/qpid/test/framework/clocksynch/ClockSynchThread.java
deleted file mode 100644
index 3d4c4f7d12..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/clocksynch/ClockSynchThread.java
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.framework.clocksynch;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.junit.extensions.ShutdownHookable;
-import org.apache.qpid.junit.extensions.Throttle;
-
-/**
- * ClockSynchThread is a convenient utility for running a thread that periodically synchronizes the clock against
- * a reference. Supply it with a {@link ClockSynchronizer} and a {@link Throttle} and it will continually keep the
- * clock up-to-date at a rate determined by the throttle.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Continually sychronize the clock at a throttled rate.
- * </table>
- */
-public class ClockSynchThread extends Thread implements ShutdownHookable
-{
- /** Used for debugging. */
- private static final Logger log = Logger.getLogger(ClockSynchThread.class);
-
- /** Holds the clock syncher for the synch thread. */
- private ClockSynchronizer clockSyncher;
-
- /** Holds the throttle to limit the synch rate. */
- private Throttle throttle;
-
- /** Flag to indicate that the periodic clock syncher should keep running. */
- boolean doSynch = true;
-
- /**
- * Creates a clock synchronizer thread from a clock synchronizer and a throttle.
- *
- * @param syncher The clock synchronizer.
- * @param throttle The throttle.
- */
- public ClockSynchThread(ClockSynchronizer syncher, Throttle throttle)
- {
- this.clockSyncher = syncher;
- this.throttle = throttle;
- }
-
- /**
- * Terminates the synchronization thread.
- */
- public void terminate()
- {
- doSynch = false;
- }
-
- /**
- * Continually updates the clock, until {@link #terminate()} is called.
- */
- public void run()
- {
- while (doSynch)
- {
- // Perform a clock clockSynch.
- try
- {
- // Wait controlled by the throttle before doing the next synch.
- throttle.throttle();
-
- clockSyncher.synch();
- log.debug("Clock synched, delta = " + clockSyncher.getDelta() + ", epsilon = " + clockSyncher.getEpsilon()
- + ".");
- }
- // Terminate the synch thread if the synchronization cannot be achieved.
- catch (ClockSynchFailureException e)
- {
- log.debug("Cannot synchronize the clock (reference service may be down). Terminating the synch thread.");
- doSynch = false;
- }
- }
- }
-
- /**
- * Gets the clock synchronizer that is kept continually up to date.
- *
- * @return The clock synchronizer that is kept continually up to date.
- */
- public ClockSynchronizer getClockSyncher()
- {
- return clockSyncher;
- }
-
- /**
- * Supplies a shutdown hook, that terminates the synching thread.
- *
- * @return The shut down hook.
- */
- public Thread getShutdownHook()
- {
- return new Thread(new Runnable()
- {
- public void run()
- {
- doSynch = false;
- }
- });
- }
-}
-
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/clocksynch/ClockSynchronizer.java b/java/systests/src/main/java/org/apache/qpid/test/framework/clocksynch/ClockSynchronizer.java
deleted file mode 100644
index a92c551bc2..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/clocksynch/ClockSynchronizer.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.framework.clocksynch;
-
-/**
- * ClockSynchronizer provides an interface through which two nodes may synchronize their clocks. It is expected that one
- * node will act as the reference clock, to which no delta need be applied, and the other node will act as the slave,
- * and which must apply a delta to its local clock to get a clock synchronized with the reference.
- *
- * <p/>The slave side will initiate the computation of a clock delta by calling the {@link #synch} method. This method
- * will not return until the delta has been computed, at which point there is a method to return its value, as well as
- * an estimate of the likely error (usually one standard deviation), in the synchronization. For convenience there is a
- * {@link #nanoTime} method to return the value of System.nanoTime() with the delta added in.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Trigger a clock synchronization.
- * <tr><td> Compute a clock delta to apply to the local clock.
- * <tr><td> Estimate the error in the synchronzation.
- * </table>
- */
-public interface ClockSynchronizer
-{
- /**
- * The slave side should call this to copute a clock delta with the reference.
- *
- * @throws ClockSynchFailureException If synchronization cannot be achieved.
- */
- public void synch() throws ClockSynchFailureException;
-
- /**
- * Gets the clock delta in nano seconds.
- *
- * @return The clock delta in nano seconds.
- */
- public long getDelta();
-
- /**
- * Gets an estimate of the clock error in nan seconds.
- *
- * @return An estimate of the clock error in nan seconds.
- */
- public long getEpsilon();
-
- /**
- * Gets the local clock time with any computed delta added in.
- *
- * @return The local clock time with any computed delta added in.
- */
- public long nanoTime();
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/clocksynch/LocalClockSynchronizer.java b/java/systests/src/main/java/org/apache/qpid/test/framework/clocksynch/LocalClockSynchronizer.java
deleted file mode 100644
index f448d5f23c..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/clocksynch/LocalClockSynchronizer.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.framework.clocksynch;
-
-/**
- * LocalClockSynchronizer is a fake {@link ClockSynchronizer} that simply calls System.nanoTime(). It exists so that
- * the same tests can be run distributed or locally, taking timings against the ClockSynchronizer interface without
- * being aware of how they are being run.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Supply the local clock with no delta.
- * </table>
- */
-public class LocalClockSynchronizer implements ClockSynchronizer
-{
- /**
- * The slave side should call this to copute a clock delta with the reference.
- *
- * @throws org.apache.qpid.test.framework.clocksynch.ClockSynchFailureException
- * If synchronization cannot be achieved.
- */
- public void synch() throws ClockSynchFailureException
- { }
-
- /**
- * Gets the clock delta in nano seconds.
- *
- * @return The clock delta in nano seconds.
- */
- public long getDelta()
- {
- return 0L;
- }
-
- /**
- * Gets an estimate of the clock error in nan seconds.
- *
- * @return An estimate of the clock error in nan seconds.
- */
- public long getEpsilon()
- {
- return 0L;
- }
-
- /**
- * Gets the local clock time with any computed delta added in.
- *
- * @return The local clock time with any computed delta added in.
- */
- public long nanoTime()
- {
- return System.nanoTime();
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/clocksynch/UDPClockReference.java b/java/systests/src/main/java/org/apache/qpid/test/framework/clocksynch/UDPClockReference.java
deleted file mode 100644
index 8bce752f68..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/clocksynch/UDPClockReference.java
+++ /dev/null
@@ -1,165 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.framework.clocksynch;
-
-import org.apache.qpid.junit.extensions.ShutdownHookable;
-
-import java.io.IOException;
-import java.net.*;
-import java.nio.ByteBuffer;
-
-/**
- * UDPClockReference supplies a refernce clock signal (generated from System.nanoTime()).
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Supply a reference clock signal.
- * </table>
- *
- * @todo Port hard coded. Make configurable.
- *
- * @todo Errors rethrown as runtimes, or silently terminate the service. Could add better error handling if needed.
- */
-public class UDPClockReference implements Runnable, ShutdownHookable
-{
- /** Used for debugging. */
- // private static final Logger log = Logger.getLogger(UDPClockReference.class);
-
- /** Defines the timeout to use when polling the socket for time requests. */
- private static final int TIMEOUT = 200;
-
- /** Defines the port to run the clock reference on. */
- public static final int REFERENCE_PORT = 4444;
-
- /** Holds the socket to receive clock reference requests on. */
- protected DatagramSocket socket = null;
-
- /** Flag used to indicate that the time server should keep running. Set to false to terminate. */
- protected boolean publish = true;
-
- /**
- * Creates a clock reference service on the standard port.
- */
- public UDPClockReference()
- {
- try
- {
- socket = new DatagramSocket(REFERENCE_PORT);
- socket.setSoTimeout(TIMEOUT);
- }
- catch (SocketException e)
- {
- throw new RuntimeException(e);
- }
- }
-
- /**
- * Implements the run loop for this reference time server. This waits for incoming time requests, and replies to
- * any, with a message with the local time stamp in it. Periodically (controlled by {@link #TIMEOUT}), the run
- * loop will check if the {@link #publish} flag has been cleared, and terminate the reference time service if so.
- */
- public void run()
- {
- byte[] buf = new byte[256];
- ByteBuffer bbuf = ByteBuffer.wrap(buf);
-
- while (publish)
- {
- try
- {
- // Wait for a reference time request.
- DatagramPacket packet = new DatagramPacket(buf, buf.length);
- boolean timedOut = false;
-
- try
- {
- socket.receive(packet);
- }
- catch (SocketTimeoutException e)
- {
- timedOut = true;
- }
-
- if (!timedOut)
- {
- // Work out from the received packet, where to reply to.
- InetAddress address = packet.getAddress();
- int port = packet.getPort();
-
- // Respond to the time request by sending back the local clock as the reference time.
- bbuf.putLong(System.nanoTime());
- bbuf.flip();
- packet = new DatagramPacket(bbuf.array(), bbuf.capacity(), address, port);
-
- socket.send(packet);
- }
- }
- catch (IOException e)
- {
- publish = false;
- }
- }
-
- socket.close();
- }
-
- /**
- * Supplies a shutdown hook.
- *
- * @return The shut down hook.
- */
- public Thread getShutdownHook()
- {
- return new Thread(new Runnable()
- {
- public void run()
- {
- publish = false;
- }
- });
- }
-
- /**
- * For testing purposes. Runs a reference clock on the default port.
- *
- * @param args None.
- */
- public static void main(String[] args)
- {
- try
- {
- // Create the clock reference service.
- UDPClockReference clock = new UDPClockReference();
-
- // Set up a shutdown hook for it.
- Runtime.getRuntime().addShutdownHook(clock.getShutdownHook());
-
- // Start the service.
- clock.run();
- }
- catch (Exception e)
- {
- e.printStackTrace();
- System.exit(1);
- }
- }
-}
-
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/clocksynch/UDPClockSynchronizer.java b/java/systests/src/main/java/org/apache/qpid/test/framework/clocksynch/UDPClockSynchronizer.java
deleted file mode 100644
index c89112eff8..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/clocksynch/UDPClockSynchronizer.java
+++ /dev/null
@@ -1,463 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.framework.clocksynch;
-
-import org.apache.qpid.junit.extensions.util.CommandLineParser;
-import org.apache.qpid.junit.extensions.util.ParsedProperties;
-
-import java.io.IOException;
-import java.net.*;
-import java.nio.ByteBuffer;
-import java.util.Arrays;
-
-/**
- * UDPClockSynchronizer is a {@link ClockSynchronizer} that sends pings as UDP datagrams, and uses the following simple
- * algorithm to perform clock synchronization:
- *
- * <ol>
- * <li>Slave initiates synchronization with a Reference clock.</li>
- * <li>Slave stamps current local time on a "time request" message and sends to the Reference.</li>
- * <li>Upon receipt by Reference, Reference stamps Reference-time and returns.</li>
- * <li>Upon receipt by Slave, Slave subtracts current time from sent time and divides by two to compute latency. It
- * subtracts current time from Reference time to determine Slave-Reference time delta and adds in the
- * half-latency to get the correct clock delta.</li>
- * <li>The first result is immediately used to update the clock since it will get the local clock into at least
- * the right ballpark.</li>
- * <li>The Slave repeats steps 2 through 4, 15 more times.</li>
- * <li>The results of the packet receipts are accumulated and sorted in lowest-latency to highest-latency order. The
- * median latency is determined by picking the mid-point sample from this ordered list.</li>
- * <li>All samples outside 1 standard-deviation from the median are discarded and the remaining samples
- * are averaged using an arithmetic mean.</li>
- * </ol>
- *
- * <p/>The use of UDP datagrams, instead of TCP based communication eliminates the hidden delays that TCP can introduce,
- * as it can transparently re-order or re-send packets, or introduce delays as packets are naggled.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Trigger a clock synchronziation.
- * <tr><td> Compute a clock delta to apply to the local clock.
- * <tr><td> Estimate the error in the synchronzation.
- * </table>
- */
-public class UDPClockSynchronizer implements ClockSynchronizer
-{
- /** Used for debugging. */
- // private static final Logger log = Logger.getLogger(UDPClockSynchronizer.class);
-
- /** Defines the timeout to use when waiting for responses to time requests. */
- private static final int TIMEOUT = 50;
-
- /** The clock delta. */
- private long delta = 0L;
-
- /** Holds an estimate of the clock error relative to the reference clock. */
- private long epsilon = 0L;
-
- /** Holds the address of the reference clock. */
- private InetAddress referenceAddress;
-
- /** Holds the socket to communicate with the reference service over. */
- private DatagramSocket socket;
-
- /** Used to control the shutdown in the main test loop. */
- private static boolean doSynch = true;
-
- /**
- * Creates a clock synchronizer against the specified address for the reference.
- *
- * @param address The address of the reference service.
- */
- public UDPClockSynchronizer(String address)
- {
- try
- {
- referenceAddress = InetAddress.getByName(address);
- }
- catch (UnknownHostException e)
- {
- throw new RuntimeException(e);
- }
- }
-
- /**
- * The slave side should call this to compute a clock delta with the reference.
- *
- * @throws ClockSynchFailureException If synchronization cannot be achieved, due to unavailability of the reference
- * time service.
- */
- public void synch() throws ClockSynchFailureException
- {
- try
- {
- socket = new DatagramSocket();
- socket.setSoTimeout(TIMEOUT);
-
- // Synchronize on a single ping, to get the clock into the right ball-park.
- synch(1);
-
- // Synchronize on 15 pings.
- synch(15);
-
- // And again, for greater accuracy, on 31.
- synch(31);
-
- socket.close();
- }
- catch (SocketException e)
- {
- throw new RuntimeException(e);
- }
- }
-
- /**
- * Updates the synchronization delta by performing the specified number of reference clock requests.
- *
- * @param n The number of reference clock request cycles to perform.
- *
- * @throws ClockSynchFailureException If synchronization cannot be achieved, due to unavailability of the reference
- * time service.
- */
- protected void synch(int n) throws ClockSynchFailureException
- {
- // log.debug("protected void synch(int n = " + n + "): called");
-
- // Create an array of deltas by performing n reference pings.
- long[] delta = new long[n];
-
- for (int i = 0; i < n; i++)
- {
- delta[i] = ping();
- }
-
- // Reject any deltas that are larger than 1 s.d. above the median.
- long median = median(delta);
- long sd = standardDeviation(delta);
-
- // log.debug("median = " + median);
- // log.debug("sd = " + sd);
-
- long[] tempDeltas = new long[n];
- int count = 0;
-
- for (int i = 0; i < n; i++)
- {
- if ((delta[i] <= (median + sd)) && (delta[i] >= (median - sd)))
- {
- tempDeltas[count] = delta[i];
- count++;
- }
- else
- {
- // log.debug("Rejected: " + delta[i]);
- }
- }
-
- System.arraycopy(tempDeltas, 0, delta, 0, count);
-
- // Estimate the delta as the mean of the remaining deltas.
- this.delta += mean(delta);
-
- // Estimate the error as the standard deviation of the remaining deltas.
- this.epsilon = standardDeviation(delta);
-
- // log.debug("this.delta = " + this.delta);
- // log.debug("this.epsilon = " + this.epsilon);
- }
-
- /**
- * Performs a single reference clock request cycle and returns the estimated delta relative to the local clock.
- * This is computed as the half-latency of the requst cycle, plus the reference clock, minus the local clock.
- *
- * @return The estimated clock delta.
- *
- * @throws ClockSynchFailureException If the reference service is not responding.
- */
- protected long ping() throws ClockSynchFailureException
- {
- // log.debug("protected long ping(): called");
-
- try
- {
- byte[] buf = new byte[256];
-
- boolean timedOut = false;
- long start = 0L;
- long refTime = 0L;
- long localTime = 0L;
- long latency = 0L;
- int failCount = 0;
-
- // Keep trying the ping until it gets a response, or 10 tries in a row all time out.
- do
- {
- // Start timing the request latency.
- start = nanoTime();
-
- // Get the reference time.
- DatagramPacket packet =
- new DatagramPacket(buf, buf.length, referenceAddress, UDPClockReference.REFERENCE_PORT);
- socket.send(packet);
- packet = new DatagramPacket(buf, buf.length);
-
- timedOut = false;
-
- try
- {
- socket.receive(packet);
- }
- catch (SocketTimeoutException e)
- {
- timedOut = true;
- failCount++;
-
- continue;
- }
-
- ByteBuffer bbuf = ByteBuffer.wrap(packet.getData());
- refTime = bbuf.getLong();
-
- // Stop timing the request latency.
- localTime = nanoTime();
- latency = localTime - start;
-
- // log.debug("refTime = " + refTime);
- // log.debug("localTime = " + localTime);
- // log.debug("start = " + start);
- // log.debug("latency = " + latency);
- // log.debug("delta = " + ((latency / 2) + (refTime - localTime)));
-
- }
- while (timedOut && (failCount < 10));
-
- // Fail completely if the fail count is too high.
- if (failCount >= 10)
- {
- throw new ClockSynchFailureException("Clock reference not responding.", null);
- }
-
- // Estimate delta as (ref clock + half-latency) - local clock.
- return (latency / 2) + (refTime - localTime);
- }
- catch (IOException e)
- {
- throw new RuntimeException(e);
- }
- }
-
- /**
- * Gets the clock delta in nano seconds.
- *
- * @return The clock delta in nano seconds.
- */
- public long getDelta()
- {
- return delta;
- }
-
- /**
- * Gets an estimate of the clock error in nan seconds.
- *
- * @return An estimate of the clock error in nan seconds.
- */
- public long getEpsilon()
- {
- return epsilon;
- }
-
- /**
- * Gets the local clock time with any computed delta added in.
- *
- * @return The local clock time with any computed delta added in.
- */
- public long nanoTime()
- {
- return System.nanoTime() + delta;
- }
-
- /**
- * Computes the median of a series of values.
- *
- * @param values The values.
- *
- * @return The median.
- */
- public static long median(long[] values)
- {
- // log.debug("public static long median(long[] values = " + Arrays.toString(values) + "): called");
-
- long median;
-
- // Order the list of values.
- long[] orderedValues = new long[values.length];
- System.arraycopy(values, 0, orderedValues, 0, values.length);
- Arrays.sort(orderedValues);
-
- // Check if the median is computed from a pair of middle value.
- if ((orderedValues.length % 2) == 0)
- {
- int middle = orderedValues.length / 2;
-
- median = (orderedValues[middle] + orderedValues[middle - 1]) / 2;
- }
- // The median is computed from a single middle value.
- else
- {
- median = orderedValues[orderedValues.length / 2];
- }
-
- // log.debug("median = " + median);
-
- return median;
- }
-
- /**
- * Computes the mean of a series of values.
- *
- * @param values The values.
- *
- * @return The mean.
- */
- public static long mean(long[] values)
- {
- // log.debug("public static long mean(long[] values = " + Arrays.toString(values) + "): called");
-
- long total = 0L;
-
- for (long value : values)
- {
- total += value;
- }
-
- long mean = total / values.length;
-
- // log.debug("mean = " + mean);
-
- return mean;
- }
-
- /**
- * Computes the variance of series of values.
- *
- * @param values The values.
- *
- * @return The variance of the values.
- */
- public static long variance(long[] values)
- {
- // log.debug("public static long variance(long[] values = " + Arrays.toString(values) + "): called");
-
- long mean = mean(values);
-
- long totalVariance = 0;
-
- for (long value : values)
- {
- long diff = (value - mean);
- totalVariance += diff * diff;
- }
-
- long variance = totalVariance / values.length;
-
- // log.debug("variance = " + variance);
-
- return variance;
- }
-
- /**
- * Computes the standard deviation of a series of values.
- *
- * @param values The values.
- *
- * @return The standard deviation.
- */
- public static long standardDeviation(long[] values)
- {
- // log.debug("public static long standardDeviation(long[] values = " + Arrays.toString(values) + "): called");
-
- long sd = Double.valueOf(Math.sqrt(variance(values))).longValue();
-
- // log.debug("sd = " + sd);
-
- return sd;
- }
-
- /**
- * For testing purposes. Supply address of reference clock as arg 1.
- *
- * @param args Address of reference clock as arg 1.
- */
- public static void main(String[] args)
- {
- ParsedProperties options =
- new ParsedProperties(CommandLineParser.processCommandLine(args,
- new CommandLineParser(
- new String[][]
- {
- { "1", "Address of clock reference service.", "address", "true" }
- }), System.getProperties()));
-
- String address = options.getProperty("1");
-
- // Create a clock synchronizer.
- UDPClockSynchronizer clockSyncher = new UDPClockSynchronizer(address);
-
- // Set up a shutdown hook for it.
- Runtime.getRuntime().addShutdownHook(new Thread(new Runnable()
- {
- public void run()
- {
- doSynch = false;
- }
- }));
-
- // Repeat the clock synching until the user kills the progam.
- while (doSynch)
- {
- // Perform a clock clockSynch.
- try
- {
- clockSyncher.synch();
-
- // Print out the clock delta and estimate of the error.
- System.out.println("Delta = " + clockSyncher.getDelta());
- System.out.println("Epsilon = " + clockSyncher.getEpsilon());
-
- try
- {
- Thread.sleep(250);
- }
- catch (InterruptedException e)
- {
- // Restore the interrupted status and terminate the loop.
- Thread.currentThread().interrupt();
- doSynch = false;
- }
- }
- // Terminate if the reference time service is unavailable.
- catch (ClockSynchFailureException e)
- {
- doSynch = false;
- }
- }
- }
-}
-
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/distributedcircuit/DistributedCircuitImpl.java b/java/systests/src/main/java/org/apache/qpid/test/framework/distributedcircuit/DistributedCircuitImpl.java
deleted file mode 100644
index f375eda4d1..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/distributedcircuit/DistributedCircuitImpl.java
+++ /dev/null
@@ -1,469 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.framework.distributedcircuit;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.test.framework.*;
-import org.apache.qpid.test.utils.ConversationFactory;
-
-import org.apache.qpid.junit.extensions.TimingController;
-import org.apache.qpid.junit.extensions.TimingControllerAware;
-import org.apache.qpid.junit.extensions.util.ParsedProperties;
-
-import javax.jms.Destination;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.Session;
-
-import java.util.LinkedList;
-import java.util.List;
-
-/**
- * DistributedCircuitImpl is a distributed implementation of the test {@link Circuit}. Many publishers and receivers
- * accross multiple machines may be combined to form a single test circuit. The test circuit extracts reports from
- * all of its publishers and receivers, and applies its assertions to these reports.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Supply the publishing and receiving ends of a test messaging circuit.
- * <tr><td> Start the circuit running.
- * <tr><td> Close the circuit down.
- * <tr><td> Take a reading of the circuits state.
- * <tr><td> Apply assertions against the circuits state.
- * <tr><td> Send test messages over the circuit.
- * <tr><td> Perform the default test procedue on the circuit.
- * </table>
- *
- * @todo There is a short pause after receiving sender reports before asking for receiver reports, because receivers may
- * not have finished receiving all their test messages before the report request arrives. This is going to be a
- * problem for taking test timings and needs to be eliminiated. Suggested solution: have receiver send back reports
- * asynchronously, on test batch size boundaries, and do so automatically rather than having to have the report
- * request sent to them. Number each test run, or otherwise uniquely identify it, when a receiver does not get
- * any more messages on a test run for more than a timeout, it can assume the test is complete and send a final
- * report. On the coordinator end a future will need to be created to wait for all final reports to come in, and
- * to register results and timings for the test. This must work in such a way that a new test cycle can be started
- * without waiting for the results of the old one to come in.
- *
- * @todo Add in setting of timing controller, from timing aware test cases.
- */
-public class DistributedCircuitImpl implements Circuit, TimingControllerAware
-{
- /** Used for debugging purposes. */
- private static final Logger log = Logger.getLogger(DistributedCircuitImpl.class);
-
- /** Holds the conversation factory over which to coordinate the test. */
- protected ConversationFactory conversationFactory;
-
- /** Holds the controlSession over which to hold the control conversation. */
- protected Session controlSession;
-
- /** Holds the sender nodes in the test circuit. */
- protected List<TestClientDetails> senders;
-
- /** Holds the receiver nodes in the test circuit. */
- protected List<TestClientDetails> receivers;
-
- /** Holds the sender control conversations. */
- protected ConversationFactory.Conversation[] senderConversation;
-
- /** Holds the receiver control conversations. */
- protected ConversationFactory.Conversation[] receiverConversation;
-
- /** Holds the control topics for the senders in the test circuit. */
- protected Destination[] senderControlTopic;
-
- /** Holds the control topics for the receivers in the test circuit. */
- protected Destination[] receiverControlTopic;
-
- /** Holds the number of messages to send per test run. */
- protected int numMessages;
-
- /**
- * Holds the timing controller for the circuit. This is used to log test times asynchronously, when reciever nodes
- * return their reports after senders have completed a test case.
- */
- TimingController timingController;
-
- /**
- * Creates a distributed test circuit on the specified senders and receivers.
- *
- * @param session The controlSession for all control conversations.
- * @param senders The senders.
- * @param receivers The receivers.
- * @param senderConversation A control conversation with the senders.
- * @param receiverConversation A control conversation with the receivers.
- * @param senderControlTopic The senders control topic.
- * @param receiverControlTopic The receivers control topic.
- */
- protected DistributedCircuitImpl(Session session, List<TestClientDetails> senders, List<TestClientDetails> receivers,
- ConversationFactory.Conversation[] senderConversation, ConversationFactory.Conversation[] receiverConversation,
- Destination[] senderControlTopic, Destination[] receiverControlTopic)
- {
- this.controlSession = session;
- this.senders = senders;
- this.receivers = receivers;
- this.senderConversation = senderConversation;
- this.receiverConversation = receiverConversation;
- this.senderControlTopic = senderControlTopic;
- this.receiverControlTopic = receiverControlTopic;
- }
-
- /**
- * Creates a distributed test circuit from the specified test parameters, on the senders and receivers
- * given.
- *
- * @param testProps The test parameters.
- * @param senders The sender ends in the test circuit.
- * @param receivers The receiver ends in the test circuit.
- * @param conversationFactory A conversation factory for creating the control conversations with senders and receivers.
- *
- * @return A connected and ready to start, test circuit.
- */
- public static Circuit createCircuit(ParsedProperties testProps, List<TestClientDetails> senders,
- List<TestClientDetails> receivers, ConversationFactory conversationFactory)
- {
- log.debug("public static Circuit createCircuit(ParsedProperties testProps, List<TestClientDetails> senders, "
- + " List<TestClientDetails> receivers, ConversationFactory conversationFactory)");
-
- try
- {
- Session session = conversationFactory.getSession();
-
- // Create control conversations with each of the senders.
- ConversationFactory.Conversation[] senderConversation = new ConversationFactory.Conversation[senders.size()];
- Destination[] senderControlTopic = new Destination[senders.size()];
-
- for (int i = 0; i < senders.size(); i++)
- {
- TestClientDetails sender = senders.get(i);
-
- senderControlTopic[i] = session.createTopic(sender.privateControlKey);
- senderConversation[i] = conversationFactory.startConversation();
- }
-
- log.debug("Sender conversations created.");
-
- // Create control conversations with each of the receivers.
- ConversationFactory.Conversation[] receiverConversation = new ConversationFactory.Conversation[receivers.size()];
- Destination[] receiverControlTopic = new Destination[receivers.size()];
-
- for (int i = 0; i < receivers.size(); i++)
- {
- TestClientDetails receiver = receivers.get(i);
-
- receiverControlTopic[i] = session.createTopic(receiver.privateControlKey);
- receiverConversation[i] = conversationFactory.startConversation();
- }
-
- log.debug("Receiver conversations created.");
-
- // Assign the sender role to each of the sending test clients.
- for (int i = 0; i < senders.size(); i++)
- {
- TestClientDetails sender = senders.get(i);
-
- Message assignSender = conversationFactory.getSession().createMessage();
- TestUtils.setPropertiesOnMessage(assignSender, testProps);
- assignSender.setStringProperty("CONTROL_TYPE", "ASSIGN_ROLE");
- assignSender.setStringProperty("ROLE", "SENDER");
-
- senderConversation[i].send(senderControlTopic[i], assignSender);
- }
-
- log.debug("Sender role assignments sent.");
-
- // Assign the receivers role to each of the receiving test clients.
- for (int i = 0; i < receivers.size(); i++)
- {
- TestClientDetails receiver = receivers.get(i);
-
- Message assignReceiver = session.createMessage();
- TestUtils.setPropertiesOnMessage(assignReceiver, testProps);
- assignReceiver.setStringProperty("CONTROL_TYPE", "ASSIGN_ROLE");
- assignReceiver.setStringProperty("ROLE", "RECEIVER");
-
- receiverConversation[i].send(receiverControlTopic[i], assignReceiver);
- }
-
- log.debug("Receiver role assignments sent.");
-
- // Wait for the senders and receivers to confirm their roles.
- for (int i = 0; i < senders.size(); i++)
- {
- senderConversation[i].receive();
- }
-
- log.debug("Got all sender role confirmations");
-
- for (int i = 0; i < receivers.size(); i++)
- {
- receiverConversation[i].receive();
- }
-
- log.debug("Got all receiver role confirmations");
-
- // Package everything up as a circuit.
- return new DistributedCircuitImpl(session, senders, receivers, senderConversation, receiverConversation,
- senderControlTopic, receiverControlTopic);
- }
- catch (JMSException e)
- {
- throw new RuntimeException("JMSException not handled.");
- }
- }
-
- /**
- * Used by tests cases that can supply a {@link org.apache.qpid.junit.extensions.TimingController} to set the
- * controller on an aware test.
- *
- * @param controller The timing controller.
- */
- public void setTimingController(TimingController controller)
- {
- this.timingController = controller;
- }
-
- /**
- * Gets the interface on the publishing end of the circuit.
- *
- * @return The publishing end of the circuit.
- */
- public Publisher getPublisher()
- {
- throw new RuntimeException("Not Implemented.");
- }
-
- /**
- * Gets the interface on the receiving end of the circuit.
- *
- * @return The receiving end of the circuit.
- */
- public Receiver getReceiver()
- {
- throw new RuntimeException("Not Implemented.");
- }
-
- /**
- * Connects and starts the circuit. After this method is called the circuit is ready to send messages.
- */
- public void start()
- {
- log.debug("public void start(): called");
-
- try
- {
- // Start the test on each of the senders.
- Message start = controlSession.createMessage();
- start.setStringProperty("CONTROL_TYPE", "START");
- start.setIntProperty("MESSAGE_COUNT", numMessages);
-
- for (int i = 0; i < senders.size(); i++)
- {
- senderConversation[i].send(senderControlTopic[i], start);
- }
-
- log.debug("All senders told to start their tests.");
- }
- catch (JMSException e)
- {
- throw new RuntimeException("Unhandled JMSException.", e);
- }
- }
-
- /**
- * Checks the test circuit. The effect of this is to gather the circuits state, for both ends of the circuit,
- * into a report, against which assertions may be checked.
- *
- * @todo Replace the asynch receiver report thread with a choice of direct or asynch executor, so that asynch
- * or synch logging of test timings is optional. Also need to provide an onMessage method that is capable
- * of receiving timing reports that receivers will generate during an ongoing test, on the test sample
- * size boundaries. The message timing logging code should be factored out as a common method that can
- * be called in response to the final report responses, or the onMessage method. Another alternative is
- * to abandon the final report request altogether and just use the onMessage method? I think the two
- * differ though, as the final report is used to apply assertions, and the ongoing report is just for
- * periodic timing results... In which case, maybe there needs to be a way for the onMessage method
- * to process just some of the incoming messages, and forward the rest on to the conversion helper, as
- * a sort of pre-conversation helper filter? Make conversation expose its onMessage method (it should
- * already) and allow another delivery thread to filter the incoming messages to the conversation.
- */
- public void check()
- {
- log.debug("public void check(): called");
-
- try
- {
- // Wait for all the test senders to return their reports.
- for (int i = 0; i < senders.size(); i++)
- {
- Message senderReport = senderConversation[i].receive();
- log.debug("Sender " + senderReport.getStringProperty("CLIENT_NAME") + " reports message count: "
- + senderReport.getIntProperty("MESSAGE_COUNT"));
- log.debug("Sender " + senderReport.getStringProperty("CLIENT_NAME") + " reports message time: "
- + senderReport.getLongProperty("TEST_TIME"));
- }
-
- log.debug("Got all sender test reports.");
-
- // Apply sender assertions to pass/fail the tests.
-
- // Inject a short pause to give the receivers time to finish receiving their test messages.
- TestUtils.pause(500);
-
- // Ask the receivers for their reports.
- Message statusRequest = controlSession.createMessage();
- statusRequest.setStringProperty("CONTROL_TYPE", "STATUS_REQUEST");
-
- for (int i = 0; i < receivers.size(); i++)
- {
- receiverConversation[i].send(receiverControlTopic[i], statusRequest);
- }
-
- log.debug("All receiver test reports requested.");
-
- // Wait for all receiver reports to come in, but do so asynchronously.
- Runnable gatherAllReceiverReports =
- new Runnable()
- {
- public void run()
- {
- try
- {
- // Wait for all the receivers to send their reports.
- for (int i = 0; i < receivers.size(); i++)
- {
- Message receiverReport = receiverConversation[i].receive();
-
- String clientName = receiverReport.getStringProperty("CLIENT_NAME");
- int messageCount = receiverReport.getIntProperty("MESSAGE_COUNT");
- long testTime = receiverReport.getLongProperty("TEST_TIME");
-
- log.debug("Receiver " + clientName + " reports message count: " + messageCount);
- log.debug("Receiver " + receiverReport.getStringProperty("CLIENT_NAME")
- + " reports message time: " + testTime);
-
- // Apply receiver assertions to pass/fail the tests.
-
- // Log the test timings on the asynchronous test timing controller.
- /*try
- {
- timingController.completeTest(true, messageCount, testTime);
- }
- // The timing controll can throw InterruptedException is the current test is to be
- // interrupted.
- catch (InterruptedException e)
- {
- e.printStackTrace();
- }*/
- }
-
- log.debug("All receiver test reports received.");
- }
- catch (JMSException e)
- {
- throw new RuntimeException(e);
- }
- }
- };
-
- Thread receiverReportsThread = new Thread(gatherAllReceiverReports);
- receiverReportsThread.start();
-
- // return new Message[] { senderReport, receiverReport };
-
- }
- catch (JMSException e)
- {
- throw new RuntimeException("Unhandled JMSException.", e);
- }
- }
-
- /**
- * Closes the circuit. All associated resources are closed.
- */
- public void close()
- {
- log.debug("public void close(): called");
-
- // End the current test on all senders and receivers.
- }
-
- /**
- * Applies a list of assertions against the test circuit. The {@link #check()} method should be called before doing
- * this, to ensure that the circuit has gathered its state into a report to assert against.
- *
- * @param assertions The list of assertions to apply.
- *
- * @return Any assertions that failed.
- */
- public List<Assertion> applyAssertions(List<Assertion> assertions)
- {
- log.debug("public List<Assertion> applyAssertions(List<Assertion> assertions = " + assertions + "): called");
-
- List<Assertion> failures = new LinkedList<Assertion>();
-
- for (Assertion assertion : assertions)
- {
- if (!assertion.apply())
- {
- failures.add(assertion);
- }
- }
-
- return failures;
- }
-
- /**
- * Runs the default test procedure against the circuit, and checks that all of the specified assertions hold.
- *
- * @param numMessages The number of messages to send using the default test procedure.
- * @param assertions The list of assertions to apply.
- *
- * @return Any assertions that failed.
- *
- * @todo From check onwards needs to be handled as a future. The future must call back onto the test case to
- * report results asynchronously.
- */
- public List<Assertion> test(int numMessages, List<Assertion> assertions)
- {
- log.debug("public List<Assertion> test(int numMessages = " + numMessages + ", List<Assertion> assertions = "
- + assertions + "): called");
-
- // Keep the number of messages to send per test run, where the send method can reference it.
- this.numMessages = numMessages;
-
- // Start the test running on all sender circuit ends.
- start();
-
- // Request status reports to be handed in.
- check();
-
- // Assert conditions on the publishing end of the circuit.
- // Assert conditions on the receiving end of the circuit.
- List<Assertion> failures = applyAssertions(assertions);
-
- // Close the circuit ending the current test case.
- close();
-
- // Pass with no failed assertions or fail with a list of failed assertions.
- return failures;
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/distributedcircuit/DistributedPublisherImpl.java b/java/systests/src/main/java/org/apache/qpid/test/framework/distributedcircuit/DistributedPublisherImpl.java
deleted file mode 100644
index c51f710494..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/distributedcircuit/DistributedPublisherImpl.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.framework.distributedcircuit;
-
-import org.apache.qpid.test.framework.Assertion;
-import org.apache.qpid.test.framework.Publisher;
-
-import org.apache.qpid.junit.extensions.util.ParsedProperties;
-
-/**
- * DistributedPublisherImpl represents the status of the publishing side of a test circuit. Its main purpose is to
- * provide assertions that can be applied to verify the behaviour of a non-local publisher.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Provide assertion that the publishers received no exceptions.
- * <tr><td> Provide assertion that the publishers received a no consumers error code on every message.
- * <tr><td> Provide assertion that the publishers received a no route error code on every message.
- * </table>
- */
-public class DistributedPublisherImpl implements Publisher
-{
- /**
- * Provides an assertion that the publisher encountered no exceptions.
- *
- * @return An assertion that the publisher encountered no exceptions.
- * @param testProps
- */
- public Assertion noExceptionsAssertion(ParsedProperties testProps)
- {
- throw new RuntimeException("Not implemented.");
- }
-
- /**
- * Provides an assertion that the publisher got a no consumers exception on every message.
- *
- * @return An assertion that the publisher got a no consumers exception on every message.
- */
- public Assertion noConsumersAssertion()
- {
- throw new RuntimeException("Not implemented.");
- }
-
- /**
- * Provides an assertion that the publisher got a no rout exception on every message.
- *
- * @return An assertion that the publisher got a no rout exception on every message.
- */
- public Assertion noRouteAssertion()
- {
- throw new RuntimeException("Not implemented.");
- }
-
- /**
- * Provides an assertion that the AMQP channel was forcibly closed by an error condition.
- *
- * @param testProps The test configuration properties.
- * @return An assertion that the AMQP channel was forcibly closed by an error condition.
- */
- public Assertion channelClosedAssertion(ParsedProperties testProps)
- {
- throw new RuntimeException("Not implemented.");
- }
-
- /**
- * Provides an assertion that the publisher got a given exception during the test.
- *
- * @param testProps The test configuration properties.
- * @param exceptionClass The exception class to check for.
- * @return An assertion that the publisher got a given exception during the test.
- */
- public Assertion exceptionAssertion(ParsedProperties testProps, Class<? extends Exception> exceptionClass)
- {
- throw new RuntimeException("Not implemented.");
- }
-}
-
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/distributedcircuit/DistributedReceiverImpl.java b/java/systests/src/main/java/org/apache/qpid/test/framework/distributedcircuit/DistributedReceiverImpl.java
deleted file mode 100644
index 863921e387..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/distributedcircuit/DistributedReceiverImpl.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.framework.distributedcircuit;
-
-import org.apache.qpid.test.framework.Assertion;
-import org.apache.qpid.test.framework.Receiver;
-
-import org.apache.qpid.junit.extensions.util.ParsedProperties;
-
-/**
- * DistributedReceiverImpl represents the status of the receiving side of a test circuit. Its main purpose is to
- * provide assertions that can be applied to verify the behaviour of a non-local receiver.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Provide assertion that the receivers received no exceptions.
- * <tr><td> Provide assertion that the receivers received all test messages sent to it.
- * </table>
- */
-public class DistributedReceiverImpl implements Receiver
-{
- /**
- * Provides an assertion that the receivers encountered no exceptions.
- *
- * @return An assertion that the receivers encountered no exceptions.
- * @param testProps
- */
- public Assertion noExceptionsAssertion(ParsedProperties testProps)
- {
- throw new RuntimeException("Not implemented.");
- }
-
- /**
- * Provides an assertion that the receivers got all messages that were sent to it.
- *
- * @return An assertion that the receivers got all messages that were sent to it.
- * @param testProps
- */
- public Assertion allMessagesReceivedAssertion(ParsedProperties testProps)
- {
- throw new RuntimeException("Not implemented.");
- }
-
- /**
- * Provides an assertion that the receivers got none of the messages that were sent to it.
- *
- * @return An assertion that the receivers got none of the messages that were sent to it.
- * @param testProps
- */
- public Assertion noMessagesReceivedAssertion(ParsedProperties testProps)
- {
- throw new RuntimeException("Not implemented.");
- }
-
- /**
- * Provides an assertion that the AMQP channel was forcibly closed by an error condition.
- *
- * @param testProps The test configuration properties.
- * @return An assertion that the AMQP channel was forcibly closed by an error condition.
- */
- public Assertion channelClosedAssertion(ParsedProperties testProps)
- {
- throw new RuntimeException("Not implemented.");
- }
-
- /**
- * Provides an assertion that the receiver got a given exception during the test.
- *
- * @param testProps
- *@param exceptionClass The exception class to check for. @return An assertion that the receiver got a given exception during the test.
- */
- public Assertion exceptionAssertion(ParsedProperties testProps, Class<? extends Exception> exceptionClass)
- {
- throw new RuntimeException("Not implemented.");
- }
-}
-
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/distributedcircuit/TestClientCircuitEnd.java b/java/systests/src/main/java/org/apache/qpid/test/framework/distributedcircuit/TestClientCircuitEnd.java
deleted file mode 100644
index dce2706bc4..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/distributedcircuit/TestClientCircuitEnd.java
+++ /dev/null
@@ -1,324 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.framework.distributedcircuit;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.test.framework.*;
-import org.apache.qpid.test.framework.distributedtesting.TestClientControlledTest;
-
-import org.apache.qpid.junit.extensions.util.ParsedProperties;
-import org.apache.qpid.junit.extensions.util.TestContextProperties;
-
-import javax.jms.*;
-
-/**
- * A TestClientCircuitEnd is a {@link CircuitEnd} that may be controlled from a
- * {@link org.apache.qpid.test.framework.distributedtesting.TestClient}, and that forms a single publishing or
- * receiving end point in a distributed test {@link org.apache.qpid.test.framework.Circuit}.
- *
- * <p/>When operating in the SENDER role, this circuit end is capable of acting as part of the default circuit test
- * procedure (described in the class comment for {@link org.apache.qpid.test.framework.Circuit}). That is, it will
- * send the number of test messages required, using the test configuration parameters given in the test invite, and
- * return a report on its activities to the circuit controller.
- *
- * <p/>When operation in the RECEIVER role, this circuit end acts as part of the default circuit test procedure. It will
- * receive test messages, on the setup specified in the test configuration parameters, and keep count of the messages
- * received, and time taken to receive them. When requested by the circuit controller to provide a report, it will
- * return this report of its activities.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Provide a message producer for sending messages.
- * <td> {@link CircuitEnd}, {@link LocalCircuitFactory}, {@link TestUtils}
- * <tr><td> Provide a message consumer for receiving messages.
- * <td> {@link CircuitEnd}, {@link LocalCircuitFactory}, {@link TestUtils}
- * <tr><td> Supply the name of the test case that this implements.
- * <tr><td> Accept/Reject invites based on test parameters. <td> {@link MessagingTestConfigProperties}
- * <tr><td> Adapt to assigned roles. <td> {@link TestClientControlledTest.Roles}
- * <tr><td> Perform test case actions. <td> {@link MessageMonitor}
- * <tr><td> Generate test reports. <td> {@link MessageMonitor}
- * </table>
- */
-public class TestClientCircuitEnd implements CircuitEnd, TestClientControlledTest
-{
- /** Used for debugging. */
- private static final Logger log = Logger.getLogger(TestClientCircuitEnd.class);
-
- /** Holds the test parameters. */
- ParsedProperties testProps;
-
- /** The number of test messages to send. */
- private int numMessages;
-
- /** The role to be played by the test. */
- private Roles role;
-
- /** The connection to send the test messages on. */
- private Connection connection;
-
- /** Holds the circuit end for this test. */
- CircuitEnd circuitEnd;
-
- /**
- * Holds a message monitor for this circuit end, either the monitor on the consumer when in RECEIVER more, or
- * a monitor updated on every message sent, when acting as a SENDER.
- */
- MessageMonitor messageMonitor;
-
- /**
- * Should provide the name of the test case that this class implements. The exact names are defined in the
- * interop testing spec.
- *
- * @return The name of the test case that this implements.
- */
- public String getName()
- {
- return "DEFAULT_CIRCUIT_TEST";
- }
-
- /**
- * Determines whether the test invite that matched this test case is acceptable.
- *
- * @param inviteMessage The invitation to accept or reject.
- * @return <tt>true</tt> to accept the invitation, <tt>false</tt> to reject it.
- *
- * @throws JMSException Any JMSException resulting from reading the message are allowed to fall through.
- */
- public boolean acceptInvite(Message inviteMessage) throws JMSException
- {
- log.debug("public boolean acceptInvite(Message inviteMessage): called");
-
- // Populate the test parameters from the invitation.
- testProps = TestContextProperties.getInstance(MessagingTestConfigProperties.defaults);
-
- for (Object key : testProps.keySet())
- {
- String propName = (String) key;
-
- // If the test parameters is overridden by the invitation, use it instead.
- String inviteValue = inviteMessage.getStringProperty(propName);
-
- if (inviteValue != null)
- {
- testProps.setProperty(propName, inviteValue);
- log.debug("Test invite supplied override to " + propName + " of " + inviteValue);
- }
-
- }
-
- // Accept the invitation.
- return true;
- }
-
- /**
- * Assigns the role to be played by this test case. The test parameters are fully specified in the
- * assignment message. When this method return the test case will be ready to execute.
- *
- * @param role The role to be played; sender or receivers.
- * @param assignRoleMessage The role assingment message, contains the full test parameters.
- *
- * @throws JMSException Any JMSException resulting from reading the message are allowed to fall through.
- */
- public void assignRole(Roles role, Message assignRoleMessage) throws JMSException
- {
- log.debug("public void assignRole(Roles role, Message assignRoleMessage): called");
-
- // Take note of the role to be played.
- this.role = role;
-
- // Extract and retain the test parameters.
- numMessages = 1; // assignRoleMessage.getIntProperty("NUM_MESSAGES");
-
- // Connect using the test parameters.
- connection = TestUtils.createConnection(testProps);
-
- // Create a circuit end that matches the assigned role and test parameters.
- LocalCircuitFactory circuitFactory = new LocalCircuitFactory();
-
- switch (role)
- {
- // Check if the sender role is being assigned, and set up a message producer if so.
- case SENDER:
-
- // Set up the publisher.
- circuitEnd = circuitFactory.createPublisherCircuitEnd(connection, testProps, 0L);
-
- // Create a custom message monitor that will be updated on every message sent.
- messageMonitor = new MessageMonitor();
-
- break;
-
- // Otherwise the receivers role is being assigned, so set this up to listen for messages.
- case RECEIVER:
-
- // Set up the receiver.
- circuitEnd = circuitFactory.createReceiverCircuitEnd(connection, testProps, 0L);
-
- // Use the message monitor from the consumer for stats.
- messageMonitor = getMessageMonitor();
-
- break;
- }
-
- // Reset all messaging stats for the report.
- messageMonitor.reset();
-
- connection.start();
- }
-
- /**
- * Performs the test case actions. Returning from here, indicates that the sending role has completed its test.
- *
- * @param numMessages The number of test messages to send.
- *
- * @throws JMSException Any JMSException resulting from reading the message are allowed to fall through.
- *
- * @todo Add round robin on destinations where multiple destinations being used.
- *
- * @todo Add rate limiting when rate limit specified on publishers.
- *
- * @todo Add Max pending message size protection. The receiver will have to send back some acks once in a while,
- * to notify the publisher that its messages are being consumed. This makes the safety valve harder to
- * implement than in the single VM case. For example, if the limit is 1000 messages, might want to get back
- * an ack every 500, to notify the publisher that it can keep sending. What about pub/sub tests? Will it be
- * necessary to wait for an ack from every receiver? This will have the effect of rate limiting to slow
- * consumers too.
- *
- * @todo Add commits on every commit batch size boundary.
- */
- public void start(int numMessages) throws JMSException
- {
- log.debug("public void start(): called");
-
- // If in the SENDER role, send the specified number of test messages to the circuit destinations.
- if (role.equals(Roles.SENDER))
- {
- Message testMessage = getSession().createMessage();
-
- for (int i = 0; i < numMessages; i++)
- {
- getProducer().send(testMessage);
-
- // Increment the message count and timings.
- messageMonitor.onMessage(testMessage);
- }
- }
- }
-
- /**
- * Gets a report on the actions performed by the test case in its assigned role.
- *
- * @param session The controlSession to create the report message in.
- * @return The report message.
- *
- * @throws JMSException Any JMSExceptions resulting from creating the report are allowed to fall through.
- */
- public Message getReport(Session session) throws JMSException
- {
- Message report = session.createMessage();
- report.setStringProperty("CONTROL_TYPE", "REPORT");
-
- // Add the count of messages sent/received to the report.
- report.setIntProperty("MESSAGE_COUNT", messageMonitor.getNumMessage());
-
- // Add the time to send/receive messages to the report.
- report.setLongProperty("TEST_TIME", messageMonitor.getTime());
-
- // Add any exceptions detected to the report.
-
- return report;
- }
-
- /**
- * Gets the message producer at this circuit end point.
- *
- * @return The message producer at with this circuit end point.
- */
- public MessageProducer getProducer()
- {
- return circuitEnd.getProducer();
- }
-
- /**
- * Gets the message consumer at this circuit end point.
- *
- * @return The message consumer at this circuit end point.
- */
- public MessageConsumer getConsumer()
- {
- return circuitEnd.getConsumer();
- }
-
- /**
- * Send the specified message over the producer at this end point.
- *
- * @param message The message to send.
- *
- * @throws JMSException Any JMS exception occuring during the send is allowed to fall through.
- */
- public void send(Message message) throws JMSException
- {
- // Send the message on the circuit ends producer.
- circuitEnd.send(message);
- }
-
- /**
- * Gets the JMS Session associated with this circuit end point.
- *
- * @return The JMS Session associated with this circuit end point.
- */
- public Session getSession()
- {
- return circuitEnd.getSession();
- }
-
- /**
- * Closes the message producers and consumers and the sessions, associated with this circuit end point.
- *
- * @throws JMSException Any JMSExceptions occurring during the close are allowed to fall through.
- */
- public void close() throws JMSException
- {
- // Close the producer and consumer.
- circuitEnd.close();
- }
-
- /**
- * Returns the message monitor for reporting on received messages on this circuit end.
- *
- * @return The message monitor for this circuit end.
- */
- public MessageMonitor getMessageMonitor()
- {
- return circuitEnd.getMessageMonitor();
- }
-
- /**
- * Returns the exception monitor for reporting on exceptions received on this circuit end.
- *
- * @return The exception monitor for this circuit end.
- */
- public ExceptionMonitor getExceptionMonitor()
- {
- return circuitEnd.getExceptionMonitor();
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/distributedtesting/Coordinator.java b/java/systests/src/main/java/org/apache/qpid/test/framework/distributedtesting/Coordinator.java
deleted file mode 100644
index d532109dc3..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/distributedtesting/Coordinator.java
+++ /dev/null
@@ -1,539 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.framework.distributedtesting;
-
-import java.net.InetAddress;
-import java.util.*;
-import java.util.concurrent.LinkedBlockingQueue;
-
-import javax.jms.*;
-
-import junit.framework.Test;
-import junit.framework.TestResult;
-import junit.framework.TestSuite;
-
-import org.apache.log4j.Logger;
-import org.apache.log4j.NDC;
-import org.apache.qpid.test.framework.FrameworkBaseCase;
-import org.apache.qpid.test.framework.MessagingTestConfigProperties;
-import org.apache.qpid.test.framework.TestClientDetails;
-import org.apache.qpid.test.framework.TestUtils;
-import org.apache.qpid.test.framework.clocksynch.UDPClockReference;
-import org.apache.qpid.test.utils.ConversationFactory;
-
-import org.apache.qpid.junit.extensions.TKTestRunner;
-import org.apache.qpid.junit.extensions.WrappedSuiteTestDecorator;
-import org.apache.qpid.junit.extensions.util.CommandLineParser;
-import org.apache.qpid.junit.extensions.util.MathUtils;
-import org.apache.qpid.junit.extensions.util.ParsedProperties;
-import org.apache.qpid.junit.extensions.util.TestContextProperties;
-
-/**
- * <p/>Implements the coordinator client described in the interop testing specification
- * (http://cwiki.apache.org/confluence/display/qpid/Interop+Testing+Specification). This coordinator is built on
- * top of the JUnit testing framework.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Find out what test clients are available. <td> {@link ConversationFactory}
- * <tr><td> Decorate available tests to run on all available clients. <td> {@link DistributedTestDecorator}
- * <tr><td> Attach XML test result logger.
- * <tr><td> Terminate the interop testing framework.
- * </table>
- *
- * @todo Should accumulate failures over all tests, and return with success or fail code based on all results. May need
- * to write a special TestResult to do this properly. At the moment only the last one used will be tested for
- * errors, as the start method creates a fresh one for each test case run.
- */
-public class Coordinator extends TKTestRunner
-{
- /** Used for debugging. */
- private static final Logger log = Logger.getLogger(Coordinator.class);
-
- /** Used for reporting to the console. */
- private static final Logger console = Logger.getLogger("CONSOLE");
-
- /** Defines the possible distributed test engines available to run coordinated test cases with. */
- public enum TestEngine
- {
- /** Specifies the interop test engine. This tests all available clients in pairs. */
- INTEROP,
-
- /** Specifies the fanout test engine. This sets up one publisher role, and many reciever roles. */
- FANOUT
- }
-
- /**
- * Holds the test context properties that provides the default test parameters, plus command line overrides.
- * This is initialized with the default test parameters, to which command line overrides may be applied.
- */
- protected static ParsedProperties testContextProperties =
- TestContextProperties.getInstance(MessagingTestConfigProperties.defaults);
-
- /** Holds the URL of the broker to coordinate the tests on. */
- protected String brokerUrl;
-
- /** Holds the virtual host to coordinate the tests on. If <tt>null</tt>, then the default virtual host is used. */
- protected String virtualHost;
-
- /** Holds the list of all clients that enlisted, when the compulsory invite was issued. */
- protected Set<TestClientDetails> enlistedClients = new HashSet<TestClientDetails>();
-
- /** Holds the conversation helper for the control conversation. */
- protected ConversationFactory conversationFactory;
-
- /** Holds the connection that the coordinating messages are sent over. */
- protected Connection connection;
-
- /** Holds the path of the directory to output test results too, if one is defined. */
- protected String reportDir;
-
- /** Holds the coordinating test engine type to run the tests through. */
- protected TestEngine engine;
-
- /** Flag that indicates that all test clients should be terminated upon completion of the test cases. */
- protected boolean terminate;
-
- /**
- * Creates an interop test coordinator on the specified broker and virtual host.
- *
- * @param repetitions The number of times to repeat the test, or test batch size.
- * @param duration The length of time to run the tests for. -1 means no duration has been set.
- * @param threads The concurrency levels to ramp up to.
- * @param delay A delay in milliseconds between test runs.
- * @param params The sets of 'size' parameters to pass to test.
- * @param testCaseName The name of the test case to run.
- * @param reportDir The directory to output the test results to.
- * @param runName The name of the test run; used to name the output file.
- * @param verbose Whether to print comments during test run.
- * @param brokerUrl The URL of the broker to connect to.
- * @param virtualHost The virtual host to run all tests on. Optional, may be <tt>null</tt>.
- * @param engine The distributed test engine type to run the tests with.
- * @param terminate <tt>true</tt> if test client nodes should be terminated at the end of the tests.
- * @param csv <tt>true</tt> if the CSV results listener should be attached.
- * @param xml <tt>true</tt> if the XML results listener should be attached.
- * @param decoratorFactories List of factories for user specified decorators.
- */
- public Coordinator(Integer repetitions, Long duration, int[] threads, int delay, int[] params, String testCaseName,
- String reportDir, String runName, boolean verbose, String brokerUrl, String virtualHost, TestEngine engine,
- boolean terminate, boolean csv, boolean xml, List<TestDecoratorFactory> decoratorFactories)
- {
- super(repetitions, duration, threads, delay, params, testCaseName, reportDir, runName, csv, xml, decoratorFactories);
-
- log.debug("public Coordinator(Integer repetitions = " + repetitions + " , Long duration = " + duration
- + ", int[] threads = " + Arrays.toString(threads) + ", int delay = " + delay + ", int[] params = "
- + Arrays.toString(params) + ", String testCaseName = " + testCaseName + ", String reportDir = " + reportDir
- + ", String runName = " + runName + ", boolean verbose = " + verbose + ", String brokerUrl = " + brokerUrl
- + ", String virtualHost =" + virtualHost + ", TestEngine engine = " + engine + ", boolean terminate = "
- + terminate + ", boolean csv = " + csv + ", boolean xml = " + xml + "): called");
-
- // Retain the connection parameters.
- this.brokerUrl = brokerUrl;
- this.virtualHost = virtualHost;
- this.reportDir = reportDir;
- this.engine = engine;
- this.terminate = terminate;
- }
-
- /**
- * The entry point for the interop test coordinator. This client accepts the following command line arguments:
- *
- * <p/><table>
- * <tr><td> -b <td> The broker URL. <td> Mandatory.
- * <tr><td> -h <td> The virtual host. <td> Optional.
- * <tr><td> -o <td> The directory to output test results to. <td> Optional.
- * <tr><td> -e <td> The type of test distribution engine to use. <td> Optional. One of: interop, fanout.
- * <tr><td> ... <td> Free arguments. The distributed test cases to run.
- * <td> Mandatory. At least one must be defined.
- * <tr><td> name=value <td> Trailing argument define name/value pairs. Added to the test contenxt properties.
- * <td> Optional.
- * </table>
- *
- * @param args The command line arguments.
- */
- public static void main(String[] args)
- {
- NDC.push("coordinator");
- log.debug("public static void main(String[] args = " + Arrays.toString(args) + "): called");
- console.info("Qpid Distributed Test Coordinator.");
-
- // Override the default broker url to be localhost:5672.
- testContextProperties.setProperty(MessagingTestConfigProperties.BROKER_PROPNAME, "tcp://localhost:5672");
-
- try
- {
- // Use the command line parser to evaluate the command line with standard handling behaviour (print errors
- // and usage then exist if there are errors).
- // Any options and trailing name=value pairs are also injected into the test context properties object,
- // to override any defaults that may have been set up.
- ParsedProperties options =
- new ParsedProperties(CommandLineParser.processCommandLine(args,
- new CommandLineParser(
- new String[][]
- {
- { "b", "The broker URL.", "broker", "false" },
- { "h", "The virtual host to use.", "virtual host", "false" },
- { "o", "The name of the directory to output test timings to.", "dir", "false" },
- {
- "e", "The test execution engine to use. Default is interop.", "engine", "interop",
- "^interop$|^fanout$", "true"
- },
- { "t", "Terminate test clients on completion of tests.", null, "false" },
- { "-csv", "Output test results in CSV format.", null, "false" },
- { "-xml", "Output test results in XML format.", null, "false" },
- {
- "-trefaddr", "To specify an alternative to hostname for time singal reference.",
- "address", "false"
- },
- {
- "c", "The number of tests to run concurrently.", "num", "false",
- MathUtils.SEQUENCE_REGEXP
- },
- { "r", "The number of times to repeat each test.", "num", "false" },
- {
- "d", "The length of time to run the tests for.", "duration", "false",
- MathUtils.DURATION_REGEXP
- },
- {
- "f", "The maximum rate to call the tests at.", "frequency", "false",
- "^([1-9][0-9]*)/([1-9][0-9]*)$"
- },
- { "s", "The size parameter to run tests with.", "size", "false", MathUtils.SEQUENCE_REGEXP },
- { "v", "Verbose mode.", null, "false" },
- { "n", "A name for this test run, used to name the output file.", "name", "true" },
- {
- "X:decorators", "A list of additional test decorators to wrap the tests in.",
- "\"class.name[:class.name]*\"", "false"
- }
- }), testContextProperties));
-
- // Extract the command line options.
- String brokerUrl = options.getProperty("b");
- String virtualHost = options.getProperty("h");
- String reportDir = options.getProperty("o");
- reportDir = (reportDir == null) ? "." : reportDir;
- String testEngine = options.getProperty("e");
- TestEngine engine = "fanout".equals(testEngine) ? TestEngine.FANOUT : TestEngine.INTEROP;
- boolean terminate = options.getPropertyAsBoolean("t");
- boolean csvResults = options.getPropertyAsBoolean("-csv");
- boolean xmlResults = options.getPropertyAsBoolean("-xml");
- String threadsString = options.getProperty("c");
- Integer repetitions = options.getPropertyAsInteger("r");
- String durationString = options.getProperty("d");
- String paramsString = options.getProperty("s");
- boolean verbose = options.getPropertyAsBoolean("v");
- String testRunName = options.getProperty("n");
- String decorators = options.getProperty("X:decorators");
-
- int[] threads = (threadsString == null) ? null : MathUtils.parseSequence(threadsString);
- int[] params = (paramsString == null) ? null : MathUtils.parseSequence(paramsString);
- Long duration = (durationString == null) ? null : MathUtils.parseDuration(durationString);
-
- // If broker or virtual host settings were specified as command line options, override the defaults in the
- // test context properties with them.
-
- // Collection all of the test cases to be run.
- Collection<Class<? extends FrameworkBaseCase>> testCaseClasses =
- new ArrayList<Class<? extends FrameworkBaseCase>>();
-
- // Create a list of test decorator factories for use specified decorators to be applied.
- List<TestDecoratorFactory> decoratorFactories = parseDecorators(decorators);
-
- // Scan for available test cases using a classpath scanner.
- // ClasspathScanner.getMatches(DistributedTestCase.class, "^Test.*", true);
-
- // Hard code the test classes till the classpath scanner is fixed.
- // Collections.addAll(testCaseClasses, InteropTestCase1DummyRun.class, InteropTestCase2BasicP2P.class,
- // InteropTestCase3BasicPubSub.class);
-
- // Parse all of the free arguments as test cases to run.
- for (int i = 1; true; i++)
- {
- String nextFreeArg = options.getProperty(Integer.toString(i));
-
- // Terminate the loop once all free arguments have been consumed.
- if (nextFreeArg == null)
- {
- break;
- }
-
- try
- {
- Class nextClass = Class.forName(nextFreeArg);
-
- if (FrameworkBaseCase.class.isAssignableFrom(nextClass))
- {
- testCaseClasses.add(nextClass);
- console.info("Found distributed test case: " + nextFreeArg);
- }
- }
- catch (ClassNotFoundException e)
- {
- console.info("Unable to instantiate the test case: " + nextFreeArg + ".");
- }
- }
-
- // Check that some test classes were actually found.
- if (testCaseClasses.isEmpty())
- {
- throw new RuntimeException(
- "No test cases implementing FrameworkBaseCase were specified on the command line.");
- }
-
- // Extract the names of all the test classes, to pass to the start method.
- int i = 0;
- String[] testClassNames = new String[testCaseClasses.size()];
-
- for (Class testClass : testCaseClasses)
- {
- testClassNames[i++] = testClass.getName();
- }
-
- // Create a coordinator and begin its test procedure.
- Coordinator coordinator =
- new Coordinator(repetitions, duration, threads, 0, params, null, reportDir, testRunName, verbose, brokerUrl,
- virtualHost, engine, terminate, csvResults, xmlResults, decoratorFactories);
-
- TestResult testResult = coordinator.start(testClassNames);
-
- // Return different error codes, depending on whether or not there were test failures.
- if (testResult.failureCount() > 0)
- {
- System.exit(FAILURE_EXIT);
- }
- else
- {
- System.exit(SUCCESS_EXIT);
- }
- }
- catch (Exception e)
- {
- log.debug("Top level handler caught execption.", e);
- console.info(e.getMessage());
- e.printStackTrace();
- System.exit(EXCEPTION_EXIT);
- }
- }
-
- /**
- * Starts all of the test classes to be run by this coordinator.
- *
- * @param testClassNames An array of all the coordinating test case implementations.
- *
- * @return A JUnit TestResult to run the tests with.
- *
- * @throws Exception Any underlying exceptions are allowed to fall through, and fail the test process.
- */
- public TestResult start(String[] testClassNames) throws Exception
- {
- log.debug("public TestResult start(String[] testClassNames = " + Arrays.toString(testClassNames) + ": called");
-
- // Connect to the broker.
- connection = TestUtils.createConnection(TestContextProperties.getInstance());
- Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- Destination controlTopic = session.createTopic("iop.control");
- Destination responseQueue = session.createQueue("coordinator");
-
- conversationFactory = new ConversationFactory(connection, responseQueue, LinkedBlockingQueue.class);
- ConversationFactory.Conversation conversation = conversationFactory.startConversation();
-
- connection.start();
-
- // Broadcast the compulsory invitation to find out what clients are available to test.
- Message invite = session.createMessage();
- invite.setStringProperty("CONTROL_TYPE", "INVITE");
- invite.setJMSReplyTo(responseQueue);
-
- conversation.send(controlTopic, invite);
-
- // Wait for a short time, to give test clients an opportunity to reply to the invitation.
- Collection<Message> enlists = conversation.receiveAll(0, 500);
- enlistedClients = extractEnlists(enlists);
-
- for (TestClientDetails client : enlistedClients)
- {
- log.debug("Got enlisted test client: " + client);
- console.info("Test node " + client.clientName + " available.");
- }
-
- // Start the clock reference service running.
- UDPClockReference clockReference = new UDPClockReference();
- Thread clockRefThread = new Thread(clockReference);
- registerShutdownHook(clockReference);
- clockRefThread.start();
-
- // Broadcast to all clients to synchronize their clocks against the coordinators clock reference.
- Message clockSynchRequest = session.createMessage();
- clockSynchRequest.setStringProperty("CONTROL_TYPE", "CLOCK_SYNCH");
-
- String localAddress = InetAddress.getByName(InetAddress.getLocalHost().getHostName()).getHostAddress();
- clockSynchRequest.setStringProperty("ADDRESS", localAddress);
-
- conversation.send(controlTopic, clockSynchRequest);
-
- // Run the test in the suite using JUnit.
- TestResult result = null;
-
- for (String testClassName : testClassNames)
- {
- // Record the current test class, so that the test results can be output to a file incorporating this name.
- this.currentTestClassName = testClassName;
-
- result = super.start(new String[] { testClassName });
- }
-
- // At this point in time, all tests have completed. Broadcast the shutdown message, if the termination option
- // was set on the command line.
- if (terminate)
- {
- Message terminate = session.createMessage();
- terminate.setStringProperty("CONTROL_TYPE", "TERMINATE");
-
- conversation.send(controlTopic, terminate);
- }
-
- return result;
- }
-
- /**
- * For a collection of enlist messages, this method pulls out of the client details for the enlisting clients.
- *
- * @param enlists The enlist messages.
- *
- * @return A set of enlisting clients, extracted from the enlist messages.
- *
- * @throws JMSException Any underlying JMSException is allowed to fall through.
- */
- public static Set<TestClientDetails> extractEnlists(Collection<Message> enlists) throws JMSException
- {
- log.debug("public static Set<TestClientDetails> extractEnlists(Collection<Message> enlists = " + enlists
- + "): called");
-
- Set<TestClientDetails> enlistedClients = new HashSet<TestClientDetails>();
-
- // Retain the list of all available clients.
- for (Message enlist : enlists)
- {
- TestClientDetails clientDetails = new TestClientDetails();
- clientDetails.clientName = enlist.getStringProperty("CLIENT_NAME");
- clientDetails.privateControlKey = enlist.getStringProperty("CLIENT_PRIVATE_CONTROL_KEY");
-
- String replyType = enlist.getStringProperty("CONTROL_TYPE");
-
- if ("ENLIST".equals(replyType))
- {
- enlistedClients.add(clientDetails);
- }
- else if ("DECLINE".equals(replyType))
- {
- log.debug("Test client " + clientDetails.clientName + " declined the invite.");
- }
- else
- {
- log.warn("Got an unknown reply type, " + replyType + ", to the invite.");
- }
- }
-
- return enlistedClients;
- }
-
- /**
- * Runs a test or suite of tests, using the super class implemenation. This method wraps the test to be run
- * in any test decorators needed to add in the coordinators ability to invite test clients to participate in
- * tests.
- *
- * @param test The test to run.
- * @param wait Undocumented. Nothing in the JUnit javadocs to say what this is for.
- *
- * @return The results of the test run.
- */
- public TestResult doRun(Test test, boolean wait)
- {
- log.debug("public TestResult doRun(Test \"" + test + "\", boolean " + wait + "): called");
-
- // Wrap all tests in the test suite with WrappedSuiteTestDecorators. This is quite ugly and a bit baffling,
- // but the reason it is done is because the JUnit implementation of TestDecorator has some bugs in it.
- WrappedSuiteTestDecorator targetTest = null;
-
- if (test instanceof TestSuite)
- {
- log.debug("targetTest is a TestSuite");
-
- TestSuite suite = (TestSuite)test;
-
- int numTests = suite.countTestCases();
- log.debug("There are " + numTests + " in the suite.");
-
- for (int i = 0; i < numTests; i++)
- {
- Test nextTest = suite.testAt(i);
- log.debug("suite.testAt(" + i + ") = " + nextTest);
-
- if (nextTest instanceof FrameworkBaseCase)
- {
- log.debug("nextTest is a FrameworkBaseCase");
- }
- }
-
- targetTest = new WrappedSuiteTestDecorator(suite);
- log.debug("Wrapped with a WrappedSuiteTestDecorator.");
- }
-
- // Apply any optional user specified decorators.
- targetTest = applyOptionalUserDecorators(targetTest);
-
- // Wrap the tests in a suitable distributed test decorator, to perform the invite/test cycle.
- targetTest = newTestDecorator(targetTest, enlistedClients, conversationFactory, connection);
-
- // TestSuite suite = new TestSuite();
- // suite.addTest(targetTest);
-
- // Wrap the tests in a scaled test decorator to them them as a 'batch' in one thread.
- // targetTest = new ScaledTestDecorator(targetTest, new int[] { 1 });
-
- return super.doRun(targetTest, wait);
- }
-
- /**
- * Creates a wrapped test decorator, that is capable of inviting enlisted clients to participate in a specified
- * test. This is the test engine that sets up the roles and sequences a distributed test case.
- *
- * @param targetTest The test decorator to wrap.
- * @param enlistedClients The enlisted clients available to run the test.
- * @param conversationFactory The conversation factory used to build conversation helper over the specified connection.
- * @param connection The connection to talk to the enlisted clients over.
- *
- * @return An invititing test decorator, that invites all the enlisted clients to participate in tests, in pairs.
- */
- protected DistributedTestDecorator newTestDecorator(WrappedSuiteTestDecorator targetTest,
- Set<TestClientDetails> enlistedClients, ConversationFactory conversationFactory, Connection connection)
- {
- switch (engine)
- {
- case FANOUT:
- return new FanOutTestDecorator(targetTest, enlistedClients, conversationFactory, connection);
- case INTEROP:
- default:
- return new InteropTestDecorator(targetTest, enlistedClients, conversationFactory, connection);
- }
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/distributedtesting/DistributedTestDecorator.java b/java/systests/src/main/java/org/apache/qpid/test/framework/distributedtesting/DistributedTestDecorator.java
deleted file mode 100644
index bdcfc996d6..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/distributedtesting/DistributedTestDecorator.java
+++ /dev/null
@@ -1,166 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.framework.distributedtesting;
-
-import junit.framework.TestResult;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.test.framework.FrameworkBaseCase;
-import org.apache.qpid.test.framework.TestClientDetails;
-import org.apache.qpid.test.framework.sequencers.CircuitFactory;
-import org.apache.qpid.test.utils.ConversationFactory;
-
-import org.apache.qpid.junit.extensions.WrappedSuiteTestDecorator;
-
-import javax.jms.Connection;
-import javax.jms.Destination;
-import javax.jms.JMSException;
-import javax.jms.Message;
-
-import java.util.*;
-
-/**
- * DistributedTestDecorator is a base class for writing test decorators that invite test clients to participate in
- * distributed test cases. It provides a helper method, {@link #signupClients}, that broadcasts an invitation and
- * returns the set of test clients that are available to particiapte in the test.
- *
- * <p/>When used to wrap a {@link FrameworkBaseCase} test, it replaces the default {@link CircuitFactory} implementations
- * with a suitable circuit factory for distributed tests. Concrete implementations can use this to configure the sending
- * and receiving roles on the test.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Broadcast test invitations and collect enlists. <td> {@link ConversationFactory}.
- * </table>
- */
-public abstract class DistributedTestDecorator extends WrappedSuiteTestDecorator
-{
- /** Used for debugging. */
- private static final Logger log = Logger.getLogger(DistributedTestDecorator.class);
-
- /** Holds the contact information for all test clients that are available and that may take part in the test. */
- Set<TestClientDetails> allClients;
-
- /** Holds the conversation helper for the control level conversation for coordinating the test through. */
- ConversationFactory conversationFactory;
-
- /** Holds the connection that the control conversation is held over. */
- Connection connection;
-
- /** Holds the underlying test suite that this decorator wraps. */
- WrappedSuiteTestDecorator testSuite;
-
- /** Holds the control topic, on which test invitations are broadcast. */
- protected Destination controlTopic;
-
- /**
- * Creates a wrapped suite test decorator from another one.
- *
- * @param suite The test suite.
- * @param availableClients The list of all clients that responded to the compulsory invite.
- * @param controlConversation The conversation helper for the control level, test coordination conversation.
- * @param controlConnection The connection that the coordination messages are sent over.
- */
- public DistributedTestDecorator(WrappedSuiteTestDecorator suite, Set<TestClientDetails> availableClients,
- ConversationFactory controlConversation, Connection controlConnection)
- {
- super(suite);
-
- log.debug("public DistributedTestDecorator(WrappedSuiteTestDecorator suite, Set<TestClientDetails> allClients = "
- + availableClients + ", ConversationHelper controlConversation = " + controlConversation + "): called");
-
- testSuite = suite;
- allClients = availableClients;
- conversationFactory = controlConversation;
- connection = controlConnection;
-
- // Set up the test control topic.
- try
- {
- controlTopic = conversationFactory.getSession().createTopic("iop.control");
- }
- catch (JMSException e)
- {
- throw new RuntimeException("Unable to create the coordinating control topic to broadcast test invites on.", e);
- }
- }
-
- /**
- * Should run all of the tests in the wrapped test suite.
- *
- * @param testResult The the results object to monitor the test results with.
- */
- public abstract void run(TestResult testResult);
-
- /**
- * Should provide the distributed test sequencer to pass to {@link org.apache.qpid.test.framework.FrameworkBaseCase}
- * tests.
- *
- * @return A distributed test sequencer.
- */
- public abstract CircuitFactory getTestSequencer();
-
- /**
- * Broadcasts an invitation to participate in a coordinating test case to find out what clients are available to
- * run the test case.
- *
- * @param coordTest The coordinating test case to broadcast an inviate for.
- *
- * @return A set of test clients that accepted the invitation.
- */
- protected Set<TestClientDetails> signupClients(FrameworkBaseCase coordTest)
- {
- // Broadcast the invitation to find out what clients are available to test.
- Set<TestClientDetails> enlists;
- try
- {
- Message invite = conversationFactory.getSession().createMessage();
-
- ConversationFactory.Conversation conversation = conversationFactory.startConversation();
-
- invite.setStringProperty("CONTROL_TYPE", "INVITE");
- invite.setStringProperty("TEST_NAME", coordTest.getTestCaseNameForTestMethod(coordTest.getName()));
-
- conversation.send(controlTopic, invite);
-
- // Wait for a short time, to give test clients an opportunity to reply to the invitation.
- Collection<Message> replies = conversation.receiveAll(allClients.size(), 500);
- enlists = Coordinator.extractEnlists(replies);
- }
- catch (JMSException e)
- {
- throw new RuntimeException("There was a JMSException during the invite/enlist conversation.", e);
- }
-
- return enlists;
- }
-
- /**
- * Prints a string summarizing this test decorator, mainly for debugging purposes.
- *
- * @return String representation for debugging purposes.
- */
- public String toString()
- {
- return "DistributedTestDecorator: [ testSuite = " + testSuite + " ]";
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/distributedtesting/FanOutTestDecorator.java b/java/systests/src/main/java/org/apache/qpid/test/framework/distributedtesting/FanOutTestDecorator.java
deleted file mode 100644
index eed9b1f290..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/distributedtesting/FanOutTestDecorator.java
+++ /dev/null
@@ -1,244 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.framework.distributedtesting;
-
-import junit.framework.Test;
-import junit.framework.TestResult;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.test.framework.DropInTest;
-import org.apache.qpid.test.framework.FrameworkBaseCase;
-import org.apache.qpid.test.framework.TestClientDetails;
-import org.apache.qpid.test.framework.sequencers.CircuitFactory;
-import org.apache.qpid.test.framework.sequencers.FanOutCircuitFactory;
-import org.apache.qpid.test.utils.ConversationFactory;
-
-import org.apache.qpid.junit.extensions.WrappedSuiteTestDecorator;
-
-import javax.jms.Connection;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageListener;
-
-import java.util.Iterator;
-import java.util.Set;
-
-/**
- * FanOutTestDecorator is an {@link DistributedTestDecorator} that runs one test client in the sender role, and the remainder
- * in the receivers role. It also has the capability to listen for new test cases joining the test beyond the initial start
- * point. This feature can be usefull when experimenting with adding more load, in the form of more test clients, to assess
- * its impact on a running test.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Execute coordinated test cases. <td> {@link FrameworkBaseCase}
- * <tr><td> Accept test clients joining a running test.
- * </table>
- */
-public class FanOutTestDecorator extends DistributedTestDecorator implements MessageListener
-{
- /** Used for debugging. */
- private static final Logger log = Logger.getLogger(FanOutTestDecorator.class);
-
- /** Holds the currently running test case. */
- FrameworkBaseCase currentTest = null;
-
- /**
- * Creates a wrapped suite test decorator from another one.
- *
- * @param suite The test suite.
- * @param availableClients The list of all clients that responded to the compulsory invite.
- * @param controlConversation The conversation helper for the control level, test coordination conversation.
- * @param controlConnection The connection that the coordination messages are sent over.
- */
- public FanOutTestDecorator(WrappedSuiteTestDecorator suite, Set<TestClientDetails> availableClients,
- ConversationFactory controlConversation, Connection controlConnection)
- {
- super(suite, availableClients, controlConversation, controlConnection);
-
- log.debug("public DistributedTestDecorator(WrappedSuiteTestDecorator suite, Set<TestClientDetails> allClients = "
- + availableClients + ", ConversationHelper controlConversation = " + controlConversation + "): called");
-
- testSuite = suite;
- allClients = availableClients;
- conversationFactory = controlConversation;
- connection = controlConnection;
-
- // Sign available clients up to the test.
- for (Test test : getAllUnderlyingTests())
- {
- FrameworkBaseCase coordTest = (FrameworkBaseCase) test;
-
- // Get all of the clients able to participate in the test.
- Set<TestClientDetails> enlists = signupClients(coordTest);
-
- // Check that there were some clients available.
- if (enlists.size() == 0)
- {
- throw new RuntimeException("No clients to test with");
- }
-
- // Create a distributed test circuit factory for the test.
- CircuitFactory circuitFactory = getTestSequencer();
-
- // Set up the first client in the sender role, and the remainder in the receivers role.
- Iterator<TestClientDetails> clients = enlists.iterator();
- circuitFactory.setSender(clients.next());
-
- while (clients.hasNext())
- {
- // Set the sending and receiving client details on the test case.
- circuitFactory.setReceiver(clients.next());
- }
-
- // Pass down the connection to hold the coordinating conversation over.
- circuitFactory.setConversationFactory(conversationFactory);
-
- // If the current test case is a drop-in test, set it up as the currently running test for late joiners to
- // add in to. Otherwise the current test field is set to null, to indicate that late joiners are not allowed.
- currentTest = (coordTest instanceof DropInTest) ? coordTest : null;
-
- // Execute the test case.
- coordTest.setCircuitFactory(circuitFactory);
- }
- }
-
- /**
- * Broadcasts a test invitation and accepts enlists from participating clients. The wrapped test cases are run
- * with one test client in the sender role, and the remaining test clients in the receiving role.
- *
- * <p/>Any JMSExceptions during the invite/enlist conversation will be allowed to fall through as runtime
- * exceptions, resulting in the non-completion of the test run.
- *
- * @param testResult The the results object to monitor the test results with.
- *
- * @todo Better error recovery for failure of the invite/enlist conversation could be added.
- */
- public void run(TestResult testResult)
- {
- log.debug("public void run(TestResult testResult): called");
-
- // Listen for late joiners on the control topic.
- try
- {
- conversationFactory.getSession().createConsumer(controlTopic).setMessageListener(this);
- }
- catch (JMSException e)
- {
- throw new RuntimeException("Unable to set up the message listener on the control topic.", e);
- }
-
- // Run all of the test cases in the test suite.
- /*for (Test test : getAllUnderlyingTests())
- {
- FrameworkBaseCase coordTest = (FrameworkBaseCase) test;
-
- // Get all of the clients able to participate in the test.
- Set<TestClientDetails> enlists = signupClients(coordTest);
-
- // Check that there were some clients available.
- if (enlists.size() == 0)
- {
- throw new RuntimeException("No clients to test with");
- }
-
- // Create a distributed test circuit factory for the test.
- CircuitFactory circuitFactory = getTestSequencer();
-
- // Set up the first client in the sender role, and the remainder in the receivers role.
- Iterator<TestClientDetails> clients = enlists.iterator();
- circuitFactory.setSender(clients.next());
-
- while (clients.hasNext())
- {
- // Set the sending and receiving client details on the test case.
- circuitFactory.setReceiver(clients.next());
- }
-
- // Pass down the connection to hold the coordinating conversation over.
- circuitFactory.setConversationFactory(conversationFactory);
-
- // If the current test case is a drop-in test, set it up as the currently running test for late joiners to
- // add in to. Otherwise the current test field is set to null, to indicate that late joiners are not allowed.
- currentTest = (coordTest instanceof DropInTest) ? coordTest : null;
-
- // Execute the test case.
- coordTest.setCircuitFactory(circuitFactory);
- }*/
-
- // Run all of the test cases in the test suite.
- for (Test test : getAllUnderlyingTests())
- {
- FrameworkBaseCase coordTest = (FrameworkBaseCase) test;
-
- coordTest.run(testResult);
-
- currentTest = null;
- }
- }
-
- /**
- * Should provide the distributed test sequencer to pass to {@link org.apache.qpid.test.framework.FrameworkBaseCase}
- * tests.
- *
- * @return A distributed test sequencer.
- */
- public CircuitFactory getTestSequencer()
- {
- return new FanOutCircuitFactory();
- }
-
- /**
- * Listens to incoming messages on the control topic. If the messages are 'join' messages, signalling a new
- * test client wishing to join the current test, then the new client will be added to the current test in the
- * receivers role.
- *
- * @param message The incoming control message.
- */
- public void onMessage(Message message)
- {
- try
- {
- // Check if the message is from a test client attempting to join a running test, and join it to the current
- // test case if so.
- if (message.getStringProperty("CONTROL_TYPE").equals("JOIN") && (currentTest != null))
- {
- ((DropInTest) currentTest).lateJoin(message);
- }
- }
- // There is not a lot can be done with this error, so it is deliberately ignored.
- catch (JMSException e)
- {
- log.debug("Unable to process message:" + message);
- }
- }
-
- /**
- * Prints a string summarizing this test decorator, mainly for debugging purposes.
- *
- * @return String representation for debugging purposes.
- */
- public String toString()
- {
- return "FanOutTestDecorator: [ testSuite = " + testSuite + " ]";
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/distributedtesting/InteropTestDecorator.java b/java/systests/src/main/java/org/apache/qpid/test/framework/distributedtesting/InteropTestDecorator.java
deleted file mode 100644
index 413d5558f2..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/distributedtesting/InteropTestDecorator.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.test.framework.distributedtesting;
-
-import junit.framework.Test;
-import junit.framework.TestResult;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.test.framework.FrameworkBaseCase;
-import org.apache.qpid.test.framework.TestClientDetails;
-import org.apache.qpid.test.framework.sequencers.CircuitFactory;
-import org.apache.qpid.test.framework.sequencers.InteropCircuitFactory;
-import org.apache.qpid.test.utils.ConversationFactory;
-
-import org.apache.qpid.junit.extensions.WrappedSuiteTestDecorator;
-
-import javax.jms.Connection;
-
-import java.util.*;
-
-/**
- * DistributedTestDecorator is a test decorator, written to implement the interop test specification. Given a list
- * of enlisted test clients, that are available to run interop tests, this decorator invites them to participate
- * in each test in the wrapped test suite. Amongst all the clients that respond to the invite, all pairs are formed,
- * and each pairing (in both directions, but excluding the reflexive pairings) is split into a sender and receivers
- * role and a test case run between them. Any enlisted combinations that do not accept a test invite are automatically
- * failed.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Broadcast test invitations and collect enlists. <td> {@link org.apache.qpid.test.utils.ConversationFactory}.
- * <tr><td> Output test failures for clients unwilling to run the test case. <td> {@link Coordinator}
- * <tr><td> Execute distributed test cases. <td> {@link FrameworkBaseCase}
- * <tr><td> Fail non-participating pairings. <td> {@link OptOutTestCase}
- * </table>
- */
-public class InteropTestDecorator extends DistributedTestDecorator
-{
- /** Used for debugging. */
- private static final Logger log = Logger.getLogger(InteropTestDecorator.class);
-
- /**
- * Creates a wrapped suite test decorator from another one.
- *
- * @param suite The test suite.
- * @param availableClients The list of all clients that responded to the compulsory invite.
- * @param controlConversation The conversation helper for the control level, test coordination conversation.
- * @param controlConnection The connection that the coordination messages are sent over.
- */
- public InteropTestDecorator(WrappedSuiteTestDecorator suite, Set<TestClientDetails> availableClients,
- ConversationFactory controlConversation, Connection controlConnection)
- {
- super(suite, availableClients, controlConversation, controlConnection);
- }
-
- /**
- * Broadcasts a test invitation and accetps enlisting from participating clients. The wrapped test case is
- * then repeated for every combination of test clients (provided the wrapped test case extends
- * {@link FrameworkBaseCase}.
- *
- * <p/>Any JMSExceptions during the invite/enlist conversation will be allowed to fall through as runtime exceptions,
- * resulting in the non-completion of the test run.
- *
- * @todo Better error recovery for failure of the invite/enlist conversation could be added.
- *
- * @param testResult The the results object to monitor the test results with.
- */
- public void run(TestResult testResult)
- {
- log.debug("public void run(TestResult testResult): called");
-
- Collection<Test> tests = testSuite.getAllUnderlyingTests();
-
- for (Test test : getAllUnderlyingTests())
- {
- FrameworkBaseCase coordTest = (FrameworkBaseCase) test;
-
- // Broadcast the invitation to find out what clients are available to test.
- Set<TestClientDetails> enlists = signupClients(coordTest);
-
- // Compare the list of willing clients to the list of all available.
- Set<TestClientDetails> optOuts = new HashSet<TestClientDetails>(allClients);
- optOuts.removeAll(enlists);
-
- // Output test failures for clients that will not particpate in the test.
- Set<List<TestClientDetails>> failPairs = allPairs(optOuts, allClients);
-
- for (List<TestClientDetails> failPair : failPairs)
- {
- // Create a distributed test circuit factory for the test.
- CircuitFactory circuitFactory = getTestSequencer();
-
- // Create an automatic failure test for the opted out test pair.
- FrameworkBaseCase failTest = new OptOutTestCase("testOptOut");
- circuitFactory.setSender(failPair.get(0));
- circuitFactory.setReceiver(failPair.get(1));
- failTest.setCircuitFactory(circuitFactory);
-
- failTest.run(testResult);
- }
-
- // Loop over all combinations of clients, willing to run the test.
- Set<List<TestClientDetails>> enlistedPairs = allPairs(enlists, enlists);
-
- for (List<TestClientDetails> enlistedPair : enlistedPairs)
- {
- // Create a distributed test circuit factory for the test.
- CircuitFactory circuitFactory = getTestSequencer();
-
- // Set the sending and receiving client details on the test circuitFactory.
- circuitFactory.setSender(enlistedPair.get(0));
- circuitFactory.setReceiver(enlistedPair.get(1));
-
- // Pass down the connection to hold the coordination conversation over.
- circuitFactory.setConversationFactory(conversationFactory);
-
- // Execute the test case.
- coordTest.setCircuitFactory(circuitFactory);
- coordTest.run(testResult);
- }
- }
- }
-
- /**
- * Should provide the distributed test sequencer to pass to {@link org.apache.qpid.test.framework.FrameworkBaseCase}
- * tests.
- *
- * @return A distributed test sequencer.
- */
- public CircuitFactory getTestSequencer()
- {
- return new InteropCircuitFactory();
- }
-
- /**
- * Produces all pairs of combinations of elements from two sets. The ordering of the elements in the pair is
- * important, that is the pair <l, r> is distinct from <r, l>; both pairs are generated. For any element, i, in
- * both the left and right sets, the reflexive pair <i, i> is not generated.
- *
- * @param left The left set.
- * @param right The right set.
- * @param <E> The type of the content of the pairs.
- *
- * @return All pairs formed from the permutations of all elements of the left and right sets.
- */
- private <E> Set<List<E>> allPairs(Set<E> left, Set<E> right)
- {
- log.debug("private <E> Set<List<E>> allPairs(Set<E> left = " + left + ", Set<E> right = " + right + "): called");
-
- Set<List<E>> results = new HashSet<List<E>>();
-
- // Form all pairs from left to right.
- // Form all pairs from right to left.
- for (E le : left)
- {
- for (E re : right)
- {
- if (!le.equals(re))
- {
- results.add(new Pair<E>(le, re));
- results.add(new Pair<E>(re, le));
- }
- }
- }
-
- log.debug("results = " + results);
-
- return results;
- }
-
- /**
- * A simple implementation of a pair, using a list.
- */
- private class Pair<T> extends ArrayList<T>
- {
- /**
- * Creates a new pair of elements.
- *
- * @param first The first element.
- * @param second The second element.
- */
- public Pair(T first, T second)
- {
- super();
- super.add(first);
- super.add(second);
- }
- }
-}
-
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/distributedtesting/OptOutTestCase.java b/java/systests/src/main/java/org/apache/qpid/test/framework/distributedtesting/OptOutTestCase.java
deleted file mode 100644
index 008b89a981..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/distributedtesting/OptOutTestCase.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.framework.distributedtesting;
-
-import org.apache.qpid.test.framework.sequencers.CircuitFactory;
-import org.apache.qpid.test.framework.FrameworkBaseCase;
-
-/**
- * An OptOutTestCase is a test case that automatically fails. It is used when a list of test clients has been generated
- * from a compulsory invite, but only some of those clients have responded to a specific test case invite. The clients
- * that did not respond, may automatically be given a fail for some tests.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Fail the test with a suitable reason.
- * </table>
- */
-public class OptOutTestCase extends FrameworkBaseCase
-{
- /**
- * Creates a new coordinating test case with the specified name.
- *
- * @param name The test case name.
- */
- public OptOutTestCase(String name)
- {
- super(name);
- }
-
- /** Generates an appropriate test failure assertion. */
- public void testOptOut()
- {
- CircuitFactory circuitFactory = getCircuitFactory();
-
- fail("One of " + circuitFactory.getSender() + " and " + getCircuitFactory().getReceivers()
- + " opted out of the test.");
- }
-
- /**
- * Should provide a translation from the junit method name of a test to its test case name as defined in the
- * interop testing specification. For example the method "testP2P" might map onto the interop test case name
- * "TC2_BasicP2P".
- *
- * @param methodName The name of the JUnit test method.
- * @return The name of the corresponding interop test case.
- */
- public String getTestCaseNameForTestMethod(String methodName)
- {
- return "OptOutTest";
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/distributedtesting/TestClient.java b/java/systests/src/main/java/org/apache/qpid/test/framework/distributedtesting/TestClient.java
deleted file mode 100644
index 33770363ce..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/distributedtesting/TestClient.java
+++ /dev/null
@@ -1,499 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.framework.distributedtesting;
-
-import org.apache.log4j.Logger;
-import org.apache.log4j.NDC;
-
-import org.apache.qpid.test.framework.MessagingTestConfigProperties;
-import org.apache.qpid.test.framework.TestUtils;
-import org.apache.qpid.test.framework.clocksynch.ClockSynchThread;
-import org.apache.qpid.test.framework.clocksynch.UDPClockSynchronizer;
-import org.apache.qpid.test.utils.ReflectionUtils;
-import org.apache.qpid.test.utils.ReflectionUtilsException;
-
-import org.apache.qpid.junit.extensions.SleepThrottle;
-import org.apache.qpid.junit.extensions.util.ParsedProperties;
-import org.apache.qpid.junit.extensions.util.TestContextProperties;
-
-import javax.jms.*;
-
-import java.util.*;
-
-/**
- * Implements a test client as described in the interop testing spec
- * (http://cwiki.apache.org/confluence/display/qpid/Interop+Testing+Specification). A test client is an agent that
- * reacts to control message sequences send by the test {@link Coordinator}.
- *
- * <p/><table><caption>Messages Handled by TestClient</caption>
- * <tr><th> Message <th> Action
- * <tr><td> Invite(compulsory) <td> Reply with Enlist.
- * <tr><td> Invite(test case) <td> Reply with Enlist if test case available.
- * <tr><td> AssignRole(test case) <td> Reply with Accept Role if matches an enlisted test. Keep test parameters.
- * <tr><td> Start <td> Send test messages defined by test parameters. Send report on messages sent.
- * <tr><td> Status Request <td> Send report on messages received.
- * <tr><td> Terminate <td> Terminate the test client.
- * <tr><td> ClockSynch <td> Synch clock against the supplied UDP address.
- * </table>
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Handle all incoming control messages. <td> {@link TestClientControlledTest}
- * <tr><td> Configure and look up test cases by name. <td> {@link TestClientControlledTest}
- * </table>
- */
-public class TestClient implements MessageListener
-{
- /** Used for debugging. */
- private static final Logger log = Logger.getLogger(TestClient.class);
-
- /** Used for reporting to the console. */
- private static final Logger console = Logger.getLogger("CONSOLE");
-
- /** Holds the default identifying name of the test client. */
- public static final String CLIENT_NAME = "java";
-
- /**
- * Holds the test context properties that provides the default test parameters, plus command line overrides.
- * This is initialized with the default test parameters, to which command line overrides may be applied.
- */
- public static ParsedProperties testContextProperties =
- TestContextProperties.getInstance(MessagingTestConfigProperties.defaults);
-
- /** Holds all the test cases loaded from the classpath. */
- Map<String, TestClientControlledTest> testCases = new HashMap<String, TestClientControlledTest>();
-
- /** Holds the test case currently being run by this client. */
- protected TestClientControlledTest currentTestCase;
-
- /** Holds the connection to the broker that the test is being coordinated on. */
- protected Connection connection;
-
- /** Holds the message producer to hold the test coordination over. */
- protected MessageProducer producer;
-
- /** Holds the JMS controlSession for the test coordination. */
- protected Session session;
-
- /** Holds the name of this client, with a default value. */
- protected String clientName = CLIENT_NAME;
-
- /** This flag indicates that the test client should attempt to join the currently running test case on start up. */
- protected boolean join;
-
- /** Holds the clock synchronizer for the test node. */
- ClockSynchThread clockSynchThread;
-
- /**
- * Creates a new interop test client, listenting to the specified broker and virtual host, with the specified client
- * identifying name.
- *
- * @param pBrokerUrl The url of the broker to connect to.
- * @param pVirtualHost The virtual host to conect to.
- * @param clientName The client name to use.
- * @param join Flag to indicate that this client should attempt to join running tests.
- */
- public TestClient(String pBrokerUrl, String pVirtualHost, String clientName, boolean join)
- {
- log.debug("public TestClient(String pBrokerUrl = " + pBrokerUrl + ", String pVirtualHost = " + pVirtualHost
- + ", String clientName = " + clientName + ", boolean join = " + join + "): called");
-
- // Retain the connection parameters.
- this.clientName = clientName;
- this.join = join;
-
- // Save properies from command line to defaults
- if (pBrokerUrl != null)
- {
- testContextProperties.setProperty(MessagingTestConfigProperties.BROKER_PROPNAME, pBrokerUrl);
- }
- if (pVirtualHost != null)
- {
- testContextProperties.setProperty(MessagingTestConfigProperties.VIRTUAL_HOST_PROPNAME, pVirtualHost);
- }
- }
-
- /**
- * The entry point for the interop test coordinator. This client accepts the following command line arguments:
- *
- * <p/><table>
- * <tr><td> -b <td> The broker URL. <td> Optional.
- * <tr><td> -h <td> The virtual host. <td> Optional.
- * <tr><td> -n <td> The test client name. <td> Optional.
- * <tr><td> name=value <td> Trailing argument define name/value pairs. Added to system properties. <td> Optional.
- * </table>
- *
- * @param args The command line arguments.
- */
- public static void main(String[] args)
- {
- log.debug("public static void main(String[] args = " + Arrays.toString(args) + "): called");
- console.info("Qpid Distributed Test Client.");
-
- // Override the default broker url to be localhost:5672.
- testContextProperties.setProperty(MessagingTestConfigProperties.BROKER_PROPNAME, "tcp://localhost:5672");
-
- // Use the command line parser to evaluate the command line with standard handling behaviour (print errors
- // and usage then exist if there are errors).
- // Any options and trailing name=value pairs are also injected into the test context properties object,
- // to override any defaults that may have been set up.
- ParsedProperties options =
- new ParsedProperties(org.apache.qpid.junit.extensions.util.CommandLineParser.processCommandLine(args,
- new org.apache.qpid.junit.extensions.util.CommandLineParser(
- new String[][]
- {
- { "b", "The broker URL.", "broker", "false" },
- { "h", "The virtual host to use.", "virtual host", "false" },
- { "o", "The name of the directory to output test timings to.", "dir", "false" },
- { "n", "The name of the test client.", "name", "false" },
- { "j", "Join this test client to running test.", "false" }
- }), testContextProperties));
-
- // Extract the command line options.
- String brokerUrl = options.getProperty("b");
- String virtualHost = options.getProperty("h");
- String clientName = options.getProperty("n");
- clientName = (clientName == null) ? CLIENT_NAME : clientName;
- boolean join = options.getPropertyAsBoolean("j");
-
- // To distinguish logging output set up an NDC on the client name.
- NDC.push(clientName);
-
- // Create a test client and start it running.
- TestClient client = new TestClient(brokerUrl, virtualHost, clientName, join);
-
- // Use a class path scanner to find all the interop test case implementations.
- // Hard code the test classes till the classpath scanner is fixed.
- Collection<Class<? extends TestClientControlledTest>> testCaseClasses =
- new ArrayList<Class<? extends TestClientControlledTest>>();
- // ClasspathScanner.getMatches(TestClientControlledTest.class, "^TestCase.*", true);
- testCaseClasses.addAll(loadTestCases("org.apache.qpid.interop.clienttestcases.TestCase1DummyRun",
- "org.apache.qpid.interop.clienttestcases.TestCase2BasicP2P",
- "org.apache.qpid.interop.clienttestcases.TestCase3BasicPubSub",
- "org.apache.qpid.interop.clienttestcases.TestCase4P2PMessageSize",
- "org.apache.qpid.interop.clienttestcases.TestCase5PubSubMessageSize",
- "org.apache.qpid.test.framework.distributedcircuit.TestClientCircuitEnd"));
-
- try
- {
- client.start(testCaseClasses);
- }
- catch (Exception e)
- {
- log.error("The test client was unable to start.", e);
- console.info(e.getMessage());
- System.exit(1);
- }
- }
-
- /**
- * Parses a list of class names, and loads them if they are available on the class path.
- *
- * @param classNames The names of the classes to load.
- *
- * @return A list of the loaded test case classes.
- */
- public static List<Class<? extends TestClientControlledTest>> loadTestCases(String... classNames)
- {
- List<Class<? extends TestClientControlledTest>> testCases =
- new LinkedList<Class<? extends TestClientControlledTest>>();
-
- for (String className : classNames)
- {
- try
- {
- Class<?> cls = ReflectionUtils.forName(className);
- testCases.add((Class<? extends TestClientControlledTest>) cls);
- }
- catch (ReflectionUtilsException e)
- {
- // Ignore, class could not be found, so test not available.
- console.warn("Requested class " + className + " cannot be found, ignoring it.");
- }
- catch (ClassCastException e)
- {
- // Ignore, class was not of correct type to be a test case.
- console.warn("Requested class " + className + " is not an instance of TestClientControlledTest.");
- }
- }
-
- return testCases;
- }
-
- /**
- * Starts the interop test client running. This causes it to start listening for incoming test invites.
- *
- * @param testCaseClasses The classes of the available test cases. The test case names from these are used to
- * matchin incoming test invites against.
- *
- * @throws JMSException Any underlying JMSExceptions are allowed to fall through.
- */
- protected void start(Collection<Class<? extends TestClientControlledTest>> testCaseClasses) throws JMSException
- {
- log.debug("protected void start(Collection<Class<? extends TestClientControlledTest>> testCaseClasses = "
- + testCaseClasses + "): called");
-
- // Create all the test case implementations and index them by the test names.
- for (Class<? extends TestClientControlledTest> nextClass : testCaseClasses)
- {
- try
- {
- TestClientControlledTest testCase = nextClass.newInstance();
- testCases.put(testCase.getName(), testCase);
- }
- catch (InstantiationException e)
- {
- log.warn("Could not instantiate test case class: " + nextClass.getName(), e);
- // Ignored.
- }
- catch (IllegalAccessException e)
- {
- log.warn("Could not instantiate test case class due to illegal access: " + nextClass.getName(), e);
- // Ignored.
- }
- }
-
- // Open a connection to communicate with the coordinator on.
- connection = TestUtils.createConnection(testContextProperties);
- session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- // Set this up to listen for control messages.
- Topic privateControlTopic = session.createTopic("iop.control." + clientName);
- MessageConsumer consumer = session.createConsumer(privateControlTopic);
- consumer.setMessageListener(this);
-
- Topic controlTopic = session.createTopic("iop.control");
- MessageConsumer consumer2 = session.createConsumer(controlTopic);
- consumer2.setMessageListener(this);
-
- // Create a producer to send replies with.
- producer = session.createProducer(null);
-
- // If the join flag was set, then broadcast a join message to notify the coordinator that a new test client
- // is available to join the current test case, if it supports it. This message may be ignored, or it may result
- // in this test client receiving a test invite.
- if (join)
- {
- Message joinMessage = session.createMessage();
-
- joinMessage.setStringProperty("CONTROL_TYPE", "JOIN");
- joinMessage.setStringProperty("CLIENT_NAME", clientName);
- joinMessage.setStringProperty("CLIENT_PRIVATE_CONTROL_KEY", "iop.control." + clientName);
- producer.send(controlTopic, joinMessage);
- }
-
- // Start listening for incoming control messages.
- connection.start();
- }
-
- /**
- * Handles all incoming control messages.
- *
- * @param message The incoming message.
- */
- public void onMessage(Message message)
- {
- NDC.push(clientName);
- log.debug("public void onMessage(Message message = " + message + "): called");
-
- try
- {
- String controlType = message.getStringProperty("CONTROL_TYPE");
- String testName = message.getStringProperty("TEST_NAME");
-
- log.debug("Received control of type '" + controlType + "' for the test '" + testName + "'");
-
- // Check if the message is a test invite.
- if ("INVITE".equals(controlType))
- {
- // Flag used to indicate that an enlist should be sent. Only enlist to compulsory invites or invites
- // for which test cases exist.
- boolean enlist = false;
-
- if (testName != null)
- {
- log.debug("Got an invite to test: " + testName);
-
- // Check if the requested test case is available.
- TestClientControlledTest testCase = testCases.get(testName);
-
- if (testCase != null)
- {
- log.debug("Found implementing class for test '" + testName + "', enlisting for it.");
-
- // Check if the test case will accept the invitation.
- enlist = testCase.acceptInvite(message);
-
- log.debug("The test case "
- + (enlist ? " accepted the invite, enlisting for it."
- : " did not accept the invite, not enlisting."));
-
- // Make the requested test case the current test case.
- currentTestCase = testCase;
- }
- else
- {
- log.debug("Received an invite to the test '" + testName + "' but this test is not known.");
- }
- }
- else
- {
- log.debug("Got a compulsory invite, enlisting for it.");
-
- enlist = true;
- }
-
- if (enlist)
- {
- // Reply with the client name in an Enlist message.
- Message enlistMessage = session.createMessage();
- enlistMessage.setStringProperty("CONTROL_TYPE", "ENLIST");
- enlistMessage.setStringProperty("CLIENT_NAME", clientName);
- enlistMessage.setStringProperty("CLIENT_PRIVATE_CONTROL_KEY", "iop.control." + clientName);
- enlistMessage.setJMSCorrelationID(message.getJMSCorrelationID());
-
- log.debug("Sending enlist message '" + enlistMessage.getJMSMessageID() + "' to " + message.getJMSReplyTo());
-
- producer.send(message.getJMSReplyTo(), enlistMessage);
- }
- else
- {
- // Reply with the client name in an Decline message.
- Message enlistMessage = session.createMessage();
- enlistMessage.setStringProperty("CONTROL_TYPE", "DECLINE");
- enlistMessage.setStringProperty("CLIENT_NAME", clientName);
- enlistMessage.setStringProperty("CLIENT_PRIVATE_CONTROL_KEY", "iop.control." + clientName);
- enlistMessage.setJMSCorrelationID(message.getJMSCorrelationID());
-
- log.debug("Sending decline message '" + enlistMessage.getJMSMessageID() + "' to " + message.getJMSReplyTo());
-
- producer.send(message.getJMSReplyTo(), enlistMessage);
- }
- }
- else if ("ASSIGN_ROLE".equals(controlType))
- {
- // Assign the role to the current test case.
- String roleName = message.getStringProperty("ROLE");
-
- log.debug("Got a role assignment to role: " + roleName);
-
- TestClientControlledTest.Roles role = Enum.valueOf(TestClientControlledTest.Roles.class, roleName);
-
- currentTestCase.assignRole(role, message);
-
- // Reply by accepting the role in an Accept Role message.
- Message acceptRoleMessage = session.createMessage();
- acceptRoleMessage.setStringProperty("CLIENT_NAME", clientName);
- acceptRoleMessage.setStringProperty("CONTROL_TYPE", "ACCEPT_ROLE");
- acceptRoleMessage.setJMSCorrelationID(message.getJMSCorrelationID());
-
- log.debug("Sending accept role message '" + acceptRoleMessage.getJMSMessageID() + "' to " + message.getJMSReplyTo());
-
- producer.send(message.getJMSReplyTo(), acceptRoleMessage);
- }
- else if ("START".equals(controlType) || "STATUS_REQUEST".equals(controlType))
- {
- if ("START".equals(controlType))
- {
- log.debug("Got a start notification.");
-
- // Extract the number of test messages to send from the start notification.
- int numMessages;
-
- try
- {
- numMessages = message.getIntProperty("MESSAGE_COUNT");
- }
- catch (NumberFormatException e)
- {
- // If the number of messages is not specified, use the default of one.
- numMessages = 1;
- }
-
- // Start the current test case.
- currentTestCase.start(numMessages);
- }
- else
- {
- log.debug("Got a status request.");
- }
-
- // Generate the report from the test case and reply with it as a Report message.
- Message reportMessage = currentTestCase.getReport(session);
- reportMessage.setStringProperty("CLIENT_NAME", clientName);
- reportMessage.setStringProperty("CONTROL_TYPE", "REPORT");
- reportMessage.setJMSCorrelationID(message.getJMSCorrelationID());
-
- log.debug("Sending report message '" + reportMessage.getJMSMessageID() + "' to " + message.getJMSReplyTo());
-
- producer.send(message.getJMSReplyTo(), reportMessage);
- }
- else if ("TERMINATE".equals(controlType))
- {
- console.info("Received termination instruction from coordinator.");
-
- // Is a cleaner shutdown needed?
- connection.close();
- System.exit(0);
- }
- else if ("CLOCK_SYNCH".equals(controlType))
- {
- log.debug("Received clock synch command.");
- String address = message.getStringProperty("ADDRESS");
-
- log.debug("address = " + address);
-
- // Re-create (if necessary) and start the clock synch thread to synch the clock every ten seconds.
- if (clockSynchThread != null)
- {
- clockSynchThread.terminate();
- }
-
- SleepThrottle throttle = new SleepThrottle();
- throttle.setRate(0.1f);
-
- clockSynchThread = new ClockSynchThread(new UDPClockSynchronizer(address), throttle);
- clockSynchThread.start();
- }
- else
- {
- // Log a warning about this but otherwise ignore it.
- log.warn("Got an unknown control message, controlType = " + controlType + ", message = " + message);
- }
- }
- catch (JMSException e)
- {
- // Log a warning about this, but otherwise ignore it.
- log.warn("Got JMSException whilst handling message: " + message, e);
- }
- // Log any runtimes that fall through this message handler. These are fatal errors for the test client.
- catch (RuntimeException e)
- {
- log.error("The test client message handler got an unhandled exception: ", e);
- console.info("The message handler got an unhandled exception, terminating the test client.");
- System.exit(1);
- }
- finally
- {
- NDC.pop();
- }
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/distributedtesting/TestClientControlledTest.java b/java/systests/src/main/java/org/apache/qpid/test/framework/distributedtesting/TestClientControlledTest.java
deleted file mode 100644
index 30fd382333..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/distributedtesting/TestClientControlledTest.java
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.framework.distributedtesting;
-
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageListener;
-import javax.jms.Session;
-
-/**
- * TestClientControlledTest provides an interface that classes implementing test cases to run on a {@link TestClient}
- * node can use. Implementations must be Java beans, that is, to provide a default constructor and to implement the
- * {@link #getName} method.
- *
- * <p/>The methods specified in this interface are called when the {@link TestClient} receives control instructions to
- * apply to the test. There are control instructions to present the test case with the test invite, so that it may
- * choose whether or not to participate in the test, assign the test to play the sender or receiver role, start the
- * test and obtain the test status report.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities
- * <tr><td> Supply the name of the test case that this implements.
- * <tr><td> Accept/Reject invites based on test parameters.
- * <tr><td> Adapt to assigned roles.
- * <tr><td> Perform test case actions.
- * <tr><td> Generate test reports.
- * </table>
- */
-public interface TestClientControlledTest
-{
- /** Defines the possible test case roles that an interop test case can take on. */
- public enum Roles
- {
- /** Specifies the sender role. */
- SENDER,
-
- /** Specifies the receivers role. */
- RECEIVER
- }
-
- /**
- * Should provide the name of the test case that this class implements. The exact names are defined in the
- * interop testing spec.
- *
- * @return The name of the test case that this implements.
- */
- public String getName();
-
- /**
- * Determines whether the test invite that matched this test case is acceptable.
- *
- * @param inviteMessage The invitation to accept or reject.
- *
- * @return <tt>true</tt> to accept the invitation, <tt>false</tt> to reject it.
- *
- * @throws JMSException Any JMSException resulting from reading the message are allowed to fall through.
- */
- public boolean acceptInvite(Message inviteMessage) throws JMSException;
-
- /**
- * Assigns the role to be played by this test case. The test parameters are fully specified in the
- * assignment message. When this method return the test case will be ready to execute.
- *
- * @param role The role to be played; sender or receivers.
- * @param assignRoleMessage The role assingment message, contains the full test parameters.
- *
- * @throws JMSException Any JMSException resulting from reading the message are allowed to fall through.
- */
- public void assignRole(Roles role, Message assignRoleMessage) throws JMSException;
-
- /**
- * Performs the test case actions. Returning from here, indicates that the sending role has completed its test.
- *
- * @param numMessages The number of test messages to send.
- *
- * @throws JMSException Any JMSException resulting from reading the message are allowed to fall through.
- */
- public void start(int numMessages) throws JMSException;
-
- /**
- * Gets a report on the actions performed by the test case in its assigned role.
- *
- * @param session The controlSession to create the report message in.
- *
- * @return The report message.
- *
- * @throws JMSException Any JMSExceptions resulting from creating the report are allowed to fall through.
- */
- public Message getReport(Session session) throws JMSException;
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/listeners/XMLTestListener.java b/java/systests/src/main/java/org/apache/qpid/test/framework/listeners/XMLTestListener.java
deleted file mode 100644
index c79029c99a..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/listeners/XMLTestListener.java
+++ /dev/null
@@ -1,409 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.framework.listeners;
-
-import junit.framework.AssertionFailedError;
-import junit.framework.Test;
-import junit.framework.TestCase;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.junit.extensions.ShutdownHookable;
-import org.apache.qpid.junit.extensions.listeners.TKTestListener;
-
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.io.Writer;
-import java.util.*;
-
-/**
- * Listens for test results for a named test and outputs these in the standard JUnit XML format to the specified
- * writer.
- *
- * <p/>The API for this listener accepts notifications about different aspects of a tests results through different
- * methods, so some assumption needs to be made as to which test result a notification refers to. For example
- * {@link #startTest} will be called, then possibly {@link #timing} will be called, even though the test instance is
- * passed in both cases, it is not enough to distinguish a particular run of the test, as the test case instance may
- * be being shared between multiple threads, or being run a repeated number of times, and can therfore be re-used
- * between calls. The listeners make the assumption that, for every test, a unique thread will call {@link #startTest}
- * and {@link #endTest} to delimit each test. All calls to set test parameters, timings, state and so on, will occur
- * between the start and end and will be given with the same thread id as the start and end, so the thread id provides
- * a unqiue value to identify a particular test run against.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Listen to test lifecycle notifications.
- * <tr><td> Listen to test errors and failures.
- * <tr><td> Listen to test timings.
- * <tr><td> Listen to test memory usages.
- * <tr><td> Listen to parameterized test parameters.
- * <tr><th> Responsibilities
- * </table>
- *
- * @todo Merge this class with CSV test listener, making the collection of results common to both, and only factoring
- * out the results printing code into sub-classes. Provide a simple XML results formatter with the same format as
- * the ant XML formatter, and a more structured one for outputing results with timings and summaries from
- * performance tests.
- */
-public class XMLTestListener implements TKTestListener, ShutdownHookable
-{
- /** Used for debugging. */
- private static final Logger log = Logger.getLogger(XMLTestListener.class);
-
- /** The results file writer. */
- protected Writer writer;
-
- /** Holds the results for individual tests. */
- // protected Map<Result, Result> results = new LinkedHashMap<Result, Result>();
- // protected List<Result> results = new ArrayList<Result>();
-
- /**
- * Map for holding results on a per thread basis as they come in. A ThreadLocal is not used as sometimes an
- * explicit thread id must be used, where notifications come from different threads than the ones that called
- * the test method.
- */
- Map<Long, Result> threadLocalResults = Collections.synchronizedMap(new LinkedHashMap<Long, Result>());
-
- /**
- * Holds results for tests that have ended. Transferring these results here from the per-thread results map, means
- * that the thread id is freed for the thread to generate more results.
- */
- List<Result> results = new ArrayList<Result>();
-
- /** Holds the overall error count. */
- protected int errors = 0;
-
- /** Holds the overall failure count. */
- protected int failures = 0;
-
- /** Holds the overall tests run count. */
- protected int runs = 0;
-
- /** Holds the name of the class that tests are being run for. */
- String testClassName;
-
- /**
- * Creates a new XML results output listener that writes to the specified location.
- *
- * @param writer The location to write results to.
- * @param testClassName The name of the test class to include in the test results.
- */
- public XMLTestListener(Writer writer, String testClassName)
- {
- log.debug("public XMLTestListener(Writer writer, String testClassName = " + testClassName + "): called");
-
- this.writer = writer;
- this.testClassName = testClassName;
- }
-
- /**
- * Resets the test results to the default state of time zero, memory usage zero, parameter zero, test passed.
- *
- * @param test The test to resest any results for.
- * @param threadId Optional thread id if not calling from thread that started the test method. May be null.
- */
- public void reset(Test test, Long threadId)
- {
- log.debug("public void reset(Test test = " + test + ", Long threadId = " + threadId + "): called");
-
- XMLTestListener.Result r =
- (threadId == null) ? threadLocalResults.get(Thread.currentThread().getId()) : threadLocalResults.get(threadId);
-
- r.error = null;
- r.failure = null;
-
- }
-
- /**
- * Notification that a test started.
- *
- * @param test The test that started.
- */
- public void startTest(Test test)
- {
- log.debug("public void startTest(Test test = " + test + "): called");
-
- Result newResult = new Result(test.getClass().getName(), ((TestCase) test).getName());
-
- // Initialize the thread local test results.
- threadLocalResults.put(Thread.currentThread().getId(), newResult);
- runs++;
- }
-
- /**
- * Should be called every time a test completes with the run time of that test.
- *
- * @param test The name of the test.
- * @param nanos The run time of the test in nanoseconds.
- * @param threadId Optional thread id if not calling from thread that started the test method. May be null.
- */
- public void timing(Test test, long nanos, Long threadId)
- { }
-
- /**
- * Optionally called every time a test completes with the second timing test.
- *
- * @param test The name of the test.
- * @param nanos The second timing information of the test in nanoseconds.
- * @param threadId Optional thread id if not calling from thread that started the test method. May be null.
- */
- public void timing2(Test test, Long nanos, Long threadId)
- { }
-
- /**
- * Should be called every time a test completed with the amount of memory used before and after the test was run.
- *
- * @param test The test which memory was measured for.
- * @param memStart The total JVM memory used before the test was run.
- * @param memEnd The total JVM memory used after the test was run.
- * @param threadId Optional thread id if not calling from thread that started the test method. May be null.
- */
- public void memoryUsed(Test test, long memStart, long memEnd, Long threadId)
- { }
-
- /**
- * Should be called every time a parameterized test completed with the int value of its test parameter.
- *
- * @param test The test which memory was measured for.
- * @param parameter The int parameter value.
- * @param threadId Optional thread id if not calling from thread that started the test method. May be null.
- */
- public void parameterValue(Test test, int parameter, Long threadId)
- { }
-
- /**
- * Should be called every time a test completes with the current number of test threads running.
- *
- * @param test The test for which the measurement is being generated.
- * @param threads The number of tests being run concurrently.
- * @param threadId Optional thread id if not calling from thread that started the test method. May be null.
- */
- public void concurrencyLevel(Test test, int threads, Long threadId)
- { }
-
- /**
- * Notifies listeners of the tests read/set properties.
- *
- * @param properties The tests read/set properties.
- */
- public void properties(Properties properties)
- { }
-
- /**
- * Notification that a test ended.
- *
- * @param test The test that ended.
- */
- public void endTest(Test test)
- {
- log.debug("public void endTest(Test test = " + test + "): called");
-
- // Move complete test results into the completed tests list.
- Result r = threadLocalResults.get(Thread.currentThread().getId());
- results.add(r);
-
- // Clear all the test results for the thread.
- threadLocalResults.remove(Thread.currentThread().getId());
- }
-
- /**
- * Called when a test completes. Success, failure and errors. This method should be used when registering an
- * end test from a different thread than the one that started the test.
- *
- * @param test The test which completed.
- * @param threadId Optional thread id if not calling from thread that started the test method. May be null.
- */
- public void endTest(Test test, Long threadId)
- {
- log.debug("public void endTest(Test test = " + test + ", Long threadId = " + threadId + "): called");
-
- // Move complete test results into the completed tests list.
- Result r =
- (threadId == null) ? threadLocalResults.get(Thread.currentThread().getId()) : threadLocalResults.get(threadId);
- results.add(r);
-
- // Clear all the test results for the thread.
- threadLocalResults.remove(Thread.currentThread().getId());
- }
-
- /**
- * An error occurred.
- *
- * @param test The test in which the error occurred.
- * @param t The throwable that resulted from the error.
- */
- public void addError(Test test, Throwable t)
- {
- log.debug("public void addError(Test test = " + test + ", Throwable t = " + t + "): called");
-
- Result r = threadLocalResults.get(Thread.currentThread().getId());
- r.error = t;
- errors++;
- }
-
- /**
- * A failure occurred.
- *
- * @param test The test in which the failure occurred.
- * @param t The JUnit assertions that led to the failure.
- */
- public void addFailure(Test test, AssertionFailedError t)
- {
- log.debug("public void addFailure(Test test = " + test + ", AssertionFailedError t = " + t + "): called");
-
- Result r = threadLocalResults.get(Thread.currentThread().getId());
- r.failure = t;
- failures++;
- }
-
- /**
- * Called when a test completes to mark it as a test fail. This method should be used when registering a
- * failure from a different thread than the one that started the test.
- *
- * @param test The test which failed.
- * @param e The assertion that failed the test.
- * @param threadId Optional thread id if not calling from thread that started the test method. May be null.
- */
- public void addFailure(Test test, AssertionFailedError e, Long threadId)
- {
- log.debug("public void addFailure(Test test, AssertionFailedError e, Long threadId): called");
-
- Result r =
- (threadId == null) ? threadLocalResults.get(Thread.currentThread().getId()) : threadLocalResults.get(threadId);
- r.failure = e;
- failures++;
- }
-
- /**
- * Notifies listeners of the start of a complete run of tests.
- */
- public void startBatch()
- {
- log.debug("public void startBatch(): called");
-
- // Reset all results counts.
- threadLocalResults = Collections.synchronizedMap(new HashMap<Long, Result>());
- errors = 0;
- failures = 0;
- runs = 0;
-
- // Write out the file header.
- try
- {
- writer.write("<?xml version=\"1.0\" ?>\n");
- }
- catch (IOException e)
- {
- throw new RuntimeException("Unable to write the test results.", e);
- }
- }
-
- /**
- * Notifies listeners of the end of a complete run of tests.
- *
- * @param parameters The optional test parameters to log out with the batch results.
- */
- public void endBatch(Properties parameters)
- {
- log.debug("public void endBatch(Properties parameters = " + parameters + "): called");
-
- // Write out the results.
- try
- {
- // writer.write("<?xml version=\"1.0\" ?>\n");
- writer.write("<testsuite errors=\"" + errors + "\" failures=\"" + failures + "\" tests=\"" + runs + "\" name=\""
- + testClassName + "\">\n");
-
- for (Result result : results)
- {
- writer.write(" <testcase classname=\"" + result.testClass + "\" name=\"" + result.testName + "\">\n");
-
- if (result.error != null)
- {
- writer.write(" <error type=\"" + result.error.getClass() + "\">");
- result.error.printStackTrace(new PrintWriter(writer));
- writer.write(" </error>");
- }
- else if (result.failure != null)
- {
- writer.write(" <failure type=\"" + result.failure.getClass() + "\">");
- result.failure.printStackTrace(new PrintWriter(writer));
- writer.write(" </failure>");
- }
-
- writer.write(" </testcase>\n");
- }
-
- writer.write("</testsuite>\n");
- writer.flush();
- }
- catch (IOException e)
- {
- throw new RuntimeException("Unable to write the test results.", e);
- }
- }
-
- /**
- * Supplies the shutdown hook.
- *
- * @return The shut down hook.
- */
- public Thread getShutdownHook()
- {
- return new Thread(new Runnable()
- {
- public void run()
- {
- log.debug("XMLTestListener::ShutdownHook: called");
- }
- });
- }
-
- /**
- * Used to capture the results of a particular test run.
- */
- protected static class Result
- {
- /** Holds the name of the test class. */
- public String testClass;
-
- /** Holds the name of the test method. */
- public String testName;
-
- /** Holds the exception that caused error in this test. */
- public Throwable error;
-
- /** Holds the assertion exception that caused failure in this test. */
- public AssertionFailedError failure;
-
- /**
- * Creates a placeholder for the results of a test.
- *
- * @param testClass The test class.
- * @param testName The name of the test that was run.
- */
- public Result(String testClass, String testName)
- {
- this.testClass = testClass;
- this.testName = testName;
- }
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/localcircuit/LocalAMQPPublisherImpl.java b/java/systests/src/main/java/org/apache/qpid/test/framework/localcircuit/LocalAMQPPublisherImpl.java
deleted file mode 100644
index 4388c7fbd8..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/localcircuit/LocalAMQPPublisherImpl.java
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.framework.localcircuit;
-
-import org.apache.qpid.client.AMQNoConsumersException;
-import org.apache.qpid.client.AMQNoRouteException;
-import org.apache.qpid.test.framework.*;
-
-import org.apache.qpid.junit.extensions.util.ParsedProperties;
-
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-import javax.jms.Session;
-
-/**
- * LocalAMQPPublisherImpl is an extension of {@link LocalPublisherImpl} that adds AMQP specific features. Specifically
- * extra assertions for AMQP features not available through generic JMS.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td>
- * </table>
- */
-public class LocalAMQPPublisherImpl extends LocalPublisherImpl implements AMQPPublisher
-{
- /**
- * Creates a circuit end point on the specified producer, consumer and controlSession. Monitors are also configured
- * for messages and exceptions received by the circuit end.
- *
- * @param producer The message producer for the circuit end point.
- * @param consumer The message consumer for the circuit end point.
- * @param session The controlSession for the circuit end point.
- * @param messageMonitor The monitor to notify of all messages received by the circuit end.
- * @param exceptionMonitor The monitor to notify of all exceptions received by the circuit end.
- */
- public LocalAMQPPublisherImpl(MessageProducer producer, MessageConsumer consumer, Session session,
- MessageMonitor messageMonitor, ExceptionMonitor exceptionMonitor)
- {
- super(producer, consumer, session, messageMonitor, exceptionMonitor);
- }
-
- /**
- * Creates a circuit end point from the producer, consumer and controlSession in a circuit end base implementation.
- *
- * @param end The circuit end base implementation to take producers and consumers from.
- */
- public LocalAMQPPublisherImpl(CircuitEndBase end)
- {
- super(end);
- }
-
- /**
- * Provides an assertion that the publisher got a no consumers exception on every message.
- *
- * @param testProps The test configuration properties.
- *
- * @return An assertion that the publisher got a no consumers exception on every message.
- */
- public Assertion noConsumersAssertion(ParsedProperties testProps)
- {
- return new AssertionBase()
- {
- public boolean apply()
- {
- boolean passed = true;
- ExceptionMonitor connectionExceptionMonitor = circuit.getConnectionExceptionMonitor();
-
- if (!connectionExceptionMonitor.assertOneJMSExceptionWithLinkedCause(AMQNoConsumersException.class))
- {
- passed = false;
-
- addError("Was expecting linked exception type " + AMQNoConsumersException.class.getName()
- + " on the connection.\n");
- addError((connectionExceptionMonitor.size() > 0)
- ? ("Actually got the following exceptions on the connection, " + connectionExceptionMonitor)
- : "Got no exceptions on the connection.");
- }
-
- return passed;
- }
- };
- }
-
- /**
- * Provides an assertion that the publisher got a no rout exception on every message.
- *
- * @param testProps The test configuration properties.
- *
- * @return An assertion that the publisher got a no rout exception on every message.
- */
- public Assertion noRouteAssertion(ParsedProperties testProps)
- {
- return new AssertionBase()
- {
- public boolean apply()
- {
- boolean passed = true;
- ExceptionMonitor connectionExceptionMonitor = circuit.getConnectionExceptionMonitor();
-
- if (!connectionExceptionMonitor.assertOneJMSExceptionWithLinkedCause(AMQNoRouteException.class))
- {
- passed = false;
-
- addError("Was expecting linked exception type " + AMQNoRouteException.class.getName()
- + " on the connection.\n");
- addError((connectionExceptionMonitor.size() > 0)
- ? ("Actually got the following exceptions on the connection, " + connectionExceptionMonitor)
- : "Got no exceptions on the connection.");
- }
-
- return passed;
- }
- };
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/localcircuit/LocalCircuitImpl.java b/java/systests/src/main/java/org/apache/qpid/test/framework/localcircuit/LocalCircuitImpl.java
deleted file mode 100644
index 391091266c..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/localcircuit/LocalCircuitImpl.java
+++ /dev/null
@@ -1,306 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.framework.localcircuit;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.test.framework.*;
-
-import org.apache.qpid.junit.extensions.util.ParsedProperties;
-
-import javax.jms.*;
-
-import java.util.LinkedList;
-import java.util.List;
-
-/**
- * LocalCircuitImpl provides an implementation of the test circuit. This is a local only circuit implementation that
- * supports a single producer/consumer on each end of the circuit, with both ends of the circuit on the same JVM.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Supply the publishing and receiving ends of a test messaging circuit.
- * <td> {@link LocalPublisherImpl}, {@link LocalReceiverImpl}
- * <tr><td> Start the circuit running.
- * <tr><td> Close the circuit down.
- * <tr><td> Take a reading of the circuits state.
- * <tr><td> Apply assertions against the circuits state. <td> {@link Assertion}
- * <tr><td> Send test messages over the circuit.
- * <tr><td> Perform the default test procedure on the circuit.
- * <tr><td> Provide access to connection and controlSession exception monitors. <td> {@link ExceptionMonitor}
- * </table>
- */
-public class LocalCircuitImpl implements Circuit
-{
- /** Used for debugging. */
- private static final Logger log = Logger.getLogger(LocalCircuitImpl.class);
-
- /** Holds the test configuration for the circuit. */
- private ParsedProperties testProps;
-
- /** Holds the publishing end of the circuit. */
- private LocalPublisherImpl publisher;
-
- /** Holds the receiving end of the circuit. */
- private LocalReceiverImpl receiver;
-
- /** Holds the connection for the publishing end of the circuit. */
- private Connection connection;
-
- /** Holds the exception listener for the connection on the publishing end of the circuit. */
- private ExceptionMonitor connectionExceptionMonitor;
-
- /** Holds the exception listener for the controlSession on the publishing end of the circuit. */
- private ExceptionMonitor exceptionMonitor;
-
- /**
- * Creates a test circuit using the specified test parameters. The publisher, receivers, connection and
- * connection monitor must already have been created, to assemble the circuit.
- *
- * @param testProps The test parameters.
- * @param publisher The test publisher.
- * @param receiver The test receivers.
- * @param connection The connection.
- * @param connectionExceptionMonitor The connection exception monitor.
- */
- public LocalCircuitImpl(ParsedProperties testProps, LocalPublisherImpl publisher, LocalReceiverImpl receiver,
- Connection connection, ExceptionMonitor connectionExceptionMonitor)
- {
- this.testProps = testProps;
- this.publisher = publisher;
- this.receiver = receiver;
- this.connection = connection;
- this.connectionExceptionMonitor = connectionExceptionMonitor;
- this.exceptionMonitor = new ExceptionMonitor();
-
- // Set this as the parent circuit on the publisher and receivers.
- publisher.setCircuit(this);
- receiver.setCircuit(this);
- }
-
- /**
- * Gets the interface on the publishing end of the circuit.
- *
- * @return The publishing end of the circuit.
- */
- public Publisher getPublisher()
- {
- return publisher;
- }
-
- /**
- * Gets the local publishing circuit end, for direct manipulation.
- *
- * @return The local publishing circuit end.
- */
- public CircuitEnd getLocalPublisherCircuitEnd()
- {
- return publisher;
- }
-
- /**
- * Gets the interface on the receiving end of the circuit.
- *
- * @return The receiving end of the circuit.
- */
- public Receiver getReceiver()
- {
- return receiver;
- }
-
- /**
- * Gets the local receiving circuit end, for direct manipulation.
- *
- * @return The local receiving circuit end.
- */
- public CircuitEnd getLocalReceiverCircuitEnd()
- {
- return receiver;
- }
-
- /**
- * Checks the test circuit. The effect of this is to gather the circuits state, for both ends of the circuit,
- * into a report, against which assertions may be checked.
- */
- public void check()
- { }
-
- /**
- * Applied a list of assertions against the test circuit. The {@link #check()} method should be called before doing
- * this, to ensure that the circuit has gathered its state into a report to assert against.
- *
- * @param assertions The list of assertions to apply.
- * @return Any assertions that failed.
- */
- public List<Assertion> applyAssertions(List<Assertion> assertions)
- {
- List<Assertion> failures = new LinkedList<Assertion>();
-
- for (Assertion assertion : assertions)
- {
- if (!assertion.apply())
- {
- failures.add(assertion);
- }
- }
-
- return failures;
- }
-
- /**
- * Connects and starts the circuit. After this method is called the circuit is ready to send messages.
- */
- public void start()
- { }
-
- /**
- * Closes the circuit. All associated resources are closed.
- */
- public void close()
- {
- try
- {
- publisher.close();
- receiver.close();
- connection.close();
- }
- catch (JMSException e)
- {
- throw new RuntimeException("Got JMSException during close:" + e.getMessage(), e);
- }
- }
-
- /**
- * Sends a message on the test circuit. The exact nature of the message sent is controlled by the test parameters.
- */
- protected void send()
- {
- // Cast the test properties into a typed interface for convenience.
- MessagingTestConfigProperties props = new MessagingTestConfigProperties(testProps);
-
- boolean transactional = props.getPublisherTransacted();
- boolean rollback = props.getRollbackPublisher();
-
- // Send a message through the publisher and log any exceptions raised.
- try
- {
- CircuitEnd end = getLocalPublisherCircuitEnd();
-
- end.send(createTestMessage(end));
-
- if (rollback)
- {
- end.getSession().rollback();
- }
- else if (transactional)
- {
- end.getSession().commit();
- }
- }
- catch (JMSException e)
- {
- exceptionMonitor.onException(e);
- }
- }
-
- /**
- * Runs the default test procedure against the circuit, and checks that all of the specified assertions hold. The
- * outline of the default test procedure is:
- *
- * <p/><pre>
- * Start the circuit.
- * Send test messages.
- * Request a status report.
- * Assert conditions on the publishing end of the circuit.
- * Assert conditions on the receiving end of the circuit.
- * Close the circuit.
- * Pass with no failed assertions or fail with a list of failed assertions.
- * </pre>
- *
- * @param numMessages The number of messages to send using the default test procedure.
- * @param assertions The list of assertions to apply.
- * @return Any assertions that failed.
- */
- public List<Assertion> test(int numMessages, List<Assertion> assertions)
- {
- // Start the test circuit.
- start();
-
- // Send the requested number of test messages.
- for (int i = 0; i < numMessages; i++)
- {
- send();
- }
-
- // Inject a short pause to allow time for exceptions to come back asynchronously.
- TestUtils.pause(500L);
-
- // Request a status report.
- check();
-
- // Clean up the publisher/receivers/controlSession/connections.
- close();
-
- // Apply all of the requested assertions, keeping record of any that fail.
- List<Assertion> failures = applyAssertions(assertions);
-
- // Return any failed assertions to the caller.
- return failures;
- }
-
- /**
- * Creates a message with the properties defined as per the test parameters.
- *
- * @param client The circuit end to create the message on.
- *
- * @return The test message.
- *
- * @throws JMSException Any JMSException occurring during creation of the message is allowed to fall through.
- */
- private Message createTestMessage(CircuitEnd client) throws JMSException
- {
- // Cast the test properties into a typed interface for convenience.
- MessagingTestConfigProperties props = new MessagingTestConfigProperties(testProps);
-
- return TestUtils.createTestMessageOfSize(client.getSession(), props.getMessageSize());
- }
-
- /**
- * Gets the exception monitor for the publishing ends connection.
- *
- * @return The exception monitor for the publishing ends connection.
- */
- public ExceptionMonitor getConnectionExceptionMonitor()
- {
- return connectionExceptionMonitor;
- }
-
- /**
- * Gets the exception monitor for the publishing ends controlSession.
- *
- * @return The exception monitor for the publishing ends controlSession.
- */
- public ExceptionMonitor getExceptionMonitor()
- {
- return exceptionMonitor;
- }
-}
-
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/localcircuit/LocalPublisherImpl.java b/java/systests/src/main/java/org/apache/qpid/test/framework/localcircuit/LocalPublisherImpl.java
deleted file mode 100644
index 3ec3f62538..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/localcircuit/LocalPublisherImpl.java
+++ /dev/null
@@ -1,170 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.framework.localcircuit;
-
-import org.apache.qpid.test.framework.*;
-
-import org.apache.qpid.junit.extensions.util.ParsedProperties;
-
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-import javax.jms.Session;
-
-/**
- * Provides an implementation of the {@link Publisher} interface and wraps a single message producer and consumer on
- * a single controlSession, as a {@link CircuitEnd}. A local publisher also acts as a circuit end, because for a locally
- * located circuit the assertions may be applied directly, there does not need to be any inter-process messaging
- * between the publisher and its single circuit end, in order to ascertain its status.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Provide a message producer for sending messages.
- * <tr><td> Provide a message consumer for receiving messages.
- * <tr><td> Provide assertion that the publisher received no exceptions.
- * <tr><td> Provide assertion that the publisher received a no consumers error code.
- * <tr><td> Provide assertion that the publisher received a no route error code.
- * </table>
- */
-public class LocalPublisherImpl extends CircuitEndBase implements Publisher
-{
- /** Holds a reference to the containing circuit. */
- protected LocalCircuitImpl circuit;
-
- /**
- * Creates a circuit end point on the specified producer, consumer and controlSession. Monitors are also configured
- * for messages and exceptions received by the circuit end.
- *
- * @param producer The message producer for the circuit end point.
- * @param consumer The message consumer for the circuit end point.
- * @param session The controlSession for the circuit end point.
- * @param messageMonitor The monitor to notify of all messages received by the circuit end.
- * @param exceptionMonitor The monitor to notify of all exceptions received by the circuit end.
- */
- public LocalPublisherImpl(MessageProducer producer, MessageConsumer consumer, Session session,
- MessageMonitor messageMonitor, ExceptionMonitor exceptionMonitor)
- {
- super(producer, consumer, session, messageMonitor, exceptionMonitor);
- }
-
- /**
- * Creates a circuit end point from the producer, consumer and controlSession in a circuit end base implementation.
- *
- * @param end The circuit end base implementation to take producers and consumers from.
- */
- public LocalPublisherImpl(CircuitEndBase end)
- {
- super(end.getProducer(), end.getConsumer(), end.getSession(), end.getMessageMonitor(), end.getExceptionMonitor());
- }
-
- /**
- * Provides an assertion that the publisher encountered no exceptions.
- *
- * @param testProps
- *
- * @return An assertion that the publisher encountered no exceptions.
- */
- public Assertion noExceptionsAssertion(ParsedProperties testProps)
- {
- return new AssertionBase()
- {
- public boolean apply()
- {
- boolean passed = true;
- ExceptionMonitor sessionExceptionMonitor = circuit.getExceptionMonitor();
- ExceptionMonitor connectionExceptionMonitor = circuit.getConnectionExceptionMonitor();
-
- if (!connectionExceptionMonitor.assertNoExceptions())
- {
- passed = false;
-
- addError("Was expecting no exceptions.\n");
- addError("Got the following exceptions on the connection, "
- + circuit.getConnectionExceptionMonitor());
- }
-
- if (!sessionExceptionMonitor.assertNoExceptions())
- {
- passed = false;
-
- addError("Was expecting no exceptions.\n");
- addError("Got the following exceptions on the producer, " + circuit.getExceptionMonitor());
- }
-
- return passed;
- }
- };
- }
-
- /**
- * Provides an assertion that the AMQP channel was forcibly closed by an error condition.
- *
- * @param testProps The test configuration properties.
- *
- * @return An assertion that the AMQP channel was forcibly closed by an error condition.
- */
- public Assertion channelClosedAssertion(ParsedProperties testProps)
- {
- return new NotApplicableAssertion(testProps);
- }
-
- /**
- * Provides an assertion that the publisher got a given exception during the test.
- *
- * @param testProps The test configuration properties.
- * @param exceptionClass The exception class to check for.
- *
- * @return An assertion that the publisher got a given exception during the test.
- */
- public Assertion exceptionAssertion(ParsedProperties testProps, final Class<? extends Exception> exceptionClass)
- {
- return new AssertionBase()
- {
- public boolean apply()
- {
- boolean passed = true;
- ExceptionMonitor connectionExceptionMonitor = circuit.getConnectionExceptionMonitor();
-
- if (!connectionExceptionMonitor.assertExceptionOfType(exceptionClass))
- {
- passed = false;
-
- addError("Was expecting linked exception type " + exceptionClass.getName()
- + " on the connection.\n");
- addError((connectionExceptionMonitor.size() > 0)
- ? ("Actually got the following exceptions on the connection, " + connectionExceptionMonitor)
- : "Got no exceptions on the connection.");
- }
-
- return passed;
- }
- };
- }
-
- /**
- * Sets the contianing circuit.
- *
- * @param circuit The containing circuit.
- */
- public void setCircuit(LocalCircuitImpl circuit)
- {
- this.circuit = circuit;
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/localcircuit/LocalReceiverImpl.java b/java/systests/src/main/java/org/apache/qpid/test/framework/localcircuit/LocalReceiverImpl.java
deleted file mode 100644
index 74f414c974..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/localcircuit/LocalReceiverImpl.java
+++ /dev/null
@@ -1,144 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.framework.localcircuit;
-
-import org.apache.qpid.test.framework.*;
-
-import org.apache.qpid.junit.extensions.util.ParsedProperties;
-
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-import javax.jms.Session;
-
-/**
- * Provides an implementation of the {@link Receiver} interface that wraps a single message producer and consumer on
- * a single controlSession, as a {@link CircuitEnd}. A local receiver also acts as a circuit end, because for a locally
- * located circuit the assertions may be applied directly, there does not need to be any inter process messaging
- * between the publisher and its single circuit end, in order to ascertain its status.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Provide a message producer for sending messages.
- * <tr><td> Provide a message consumer for receiving messages.
- * <tr><td> Provide assertion that the receivers received no exceptions.
- * <tr><td> Provide assertion that the receivers received all test messages sent to it.
- * </table>
- */
-public class LocalReceiverImpl extends CircuitEndBase implements Receiver
-{
- /** Holds a reference to the containing circuit. */
- private LocalCircuitImpl circuit;
-
- /**
- * Creates a circuit end point on the specified producer, consumer and controlSession. Monitors are also configured
- * for messages and exceptions received by the circuit end.
- *
- * @param producer The message producer for the circuit end point.
- * @param consumer The message consumer for the circuit end point.
- * @param session The controlSession for the circuit end point.
- * @param messageMonitor The monitor to notify of all messages received by the circuit end.
- * @param exceptionMonitor The monitor to notify of all exceptions received by the circuit end.
- */
- public LocalReceiverImpl(MessageProducer producer, MessageConsumer consumer, Session session,
- MessageMonitor messageMonitor, ExceptionMonitor exceptionMonitor)
- {
- super(producer, consumer, session, messageMonitor, exceptionMonitor);
- }
-
- /**
- * Creates a circuit end point from the producer, consumer and controlSession in a circuit end base implementation.
- *
- * @param end The circuit end base implementation to take producers and consumers from.
- */
- public LocalReceiverImpl(CircuitEndBase end)
- {
- super(end.getProducer(), end.getConsumer(), end.getSession(), end.getMessageMonitor(), end.getExceptionMonitor());
- }
-
- /**
- * Provides an assertion that the receivers encountered no exceptions.
- *
- * @param testProps The test configuration properties.
- *
- * @return An assertion that the receivers encountered no exceptions.
- */
- public Assertion noExceptionsAssertion(ParsedProperties testProps)
- {
- return new NotApplicableAssertion(testProps);
- }
-
- /**
- * Provides an assertion that the AMQP channel was forcibly closed by an error condition.
- *
- * @param testProps The test configuration properties.
- *
- * @return An assertion that the AMQP channel was forcibly closed by an error condition.
- */
- public Assertion channelClosedAssertion(ParsedProperties testProps)
- {
- return new NotApplicableAssertion(testProps);
- }
-
- /**
- * Provides an assertion that the receivers got all messages that were sent to it.
- *
- * @param testProps The test configuration properties.
- *
- * @return An assertion that the receivers got all messages that were sent to it.
- */
- public Assertion allMessagesReceivedAssertion(ParsedProperties testProps)
- {
- return new NotApplicableAssertion(testProps);
- }
-
- /**
- * Provides an assertion that the receivers got none of the messages that were sent to it.
- *
- * @param testProps The test configuration properties.
- *
- * @return An assertion that the receivers got none of the messages that were sent to it.
- */
- public Assertion noMessagesReceivedAssertion(ParsedProperties testProps)
- {
- return new NotApplicableAssertion(testProps);
- }
-
- /**
- * Provides an assertion that the receiver got a given exception during the test.
- *
- * @param testProps The test configuration properties.
- * @param exceptionClass The exception class to check for. @return An assertion that the receiver got a given exception during the test.
- */
- public Assertion exceptionAssertion(ParsedProperties testProps, Class<? extends Exception> exceptionClass)
- {
- return new NotApplicableAssertion(testProps);
- }
-
- /**
- * Sets the contianing circuit.
- *
- * @param circuit The containing circuit.
- */
- public void setCircuit(LocalCircuitImpl circuit)
- {
- this.circuit = circuit;
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/package.html b/java/systests/src/main/java/org/apache/qpid/test/framework/package.html
deleted file mode 100644
index ac4e30d312..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/package.html
+++ /dev/null
@@ -1,43 +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.
-
--->
-
-<html>
-<body>
-<p/>A framework for testing Qpid, built around a standard 'test circuit' design. The idea behind this framework is the
-use of a test circuit which is configured by a set of test parameters, that may be projected onto a topology of
-test nodes, with tests scripted to run over test circuits, making as few assumptions as possible about the underlying
-topology. The standardization of the design, whilst limiting in some respectes, allows a large variety of test
-scenarios to be written with minimal amounts of coding.
-
-<p/>The standard consruction block for a test, is a test circuit. This consists of a publisher, and a receiver. The
-publisher and receiver may reside on the same machine, or may be distributed. Will use a standard set of properties to
-define the desired circuit topology.
-
-<p/>Tests are always to be controlled from the publishing side only. The receiving end of the circuit is to be exposed
-to the test code through an interface, that abstracts as much as possible the receiving end of the test. The interface
-exposes a set of 'assertions' that may be applied to the receiving end of the test circuit.
-
-<p/>In the case where the receiving end of the circuit resides on the same JVM, the assertions will call the receivers
-code locally. Where the receiving end is distributed accross one or more machines, the assertions will be applied to a
-test report gethered from all of the receivers. Test code will be written to the assertions making as few assumptions
-as possible about the exact test topology.
-</body>
-</html>
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/qpid/AMQPFeatureDecorator.java b/java/systests/src/main/java/org/apache/qpid/test/framework/qpid/AMQPFeatureDecorator.java
deleted file mode 100644
index c11f75e742..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/qpid/AMQPFeatureDecorator.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.framework.qpid;
-
-import junit.framework.Test;
-import junit.framework.TestResult;
-
-import org.apache.qpid.test.framework.FrameworkBaseCase;
-import org.apache.qpid.test.framework.LocalAMQPCircuitFactory;
-
-import org.apache.qpid.junit.extensions.WrappedSuiteTestDecorator;
-
-/**
- * AMQPFeatureDecorator applies decorations to {@link FrameworkBaseCase} tests, so that they may use Qpid/AMQP specific
- * features, not available through JMS. For example, the immediate and mandatory flags. This decorator replaces the
- * standard test circuit factory on the base class with one that allows these features to be used.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Substitute the circuit factory with an AMQP/Qpid specific one.
- * </table>
- *
- * @todo This wrapper substitutes in a LocalAMQPCircuitFactory, which is fine for local tests. For distributed tests
- * the Fanout or Interop factories are substituted in by their decorators instead. These actually use
- * distributed circuit static create methods to build the circuits, which should actually be changed to a factory,
- * so that static methods do not need to be used. The distributed circuit creater delegates the circuit
- * construction to remote test nodes. This decorator should not be used with distributed tests, or should be made
- * aware of them, in which case it might ensure that an AMQP feature (implied already by other properties) flag
- * is passed out to the remote test nodes, and provide a mechansim for them to decorate their circuit creation
- * with AMQP features too. Add factory substituion/decoration mechansim for test clients, here or in a seperate
- * class.
- */
-public class AMQPFeatureDecorator extends WrappedSuiteTestDecorator
-{
- /** The test suite to run. */
- private Test test;
-
- /**
- * Creates a wrapped test test decorator from another one.
- *
- * @param test The test test.
- */
- public AMQPFeatureDecorator(WrappedSuiteTestDecorator test)
- {
- super(test);
- this.test = test;
- }
-
- /**
- * Runs the tests with a LocalAMQPCircuitFactory. Only tests that extend FrameworkBaseCase are decorated.
- *
- * @param testResult The the results object to monitor the test results with.
- */
- public void run(TestResult testResult)
- {
- for (Test test : getAllUnderlyingTests())
- {
- if (test instanceof FrameworkBaseCase)
- {
- FrameworkBaseCase frameworkTest = (FrameworkBaseCase) test;
- frameworkTest.setCircuitFactory(new LocalAMQPCircuitFactory());
- }
- }
-
- // Run the test.
- test.run(testResult);
- }
-
- /**
- * Prints the name of the test for debugging purposes.
- *
- * @return The name of the test.
- */
- public String toString()
- {
- return "AMQPFeatureDecorator: [test = \"" + test + "\"]";
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/qpid/CauseFailureDecorator.java b/java/systests/src/main/java/org/apache/qpid/test/framework/qpid/CauseFailureDecorator.java
deleted file mode 100644
index 2708253d86..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/qpid/CauseFailureDecorator.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.framework.qpid;
-
-import junit.framework.Test;
-import junit.framework.TestResult;
-
-import org.apache.qpid.test.framework.BrokerLifecycleAware;
-import org.apache.qpid.test.framework.CauseFailureUserPrompt;
-
-import org.apache.qpid.junit.extensions.WrappedSuiteTestDecorator;
-
-/**
- * CauseFailureDecorator applies decorations to {@link BrokerLifecycleAware} tests, so that they may use different failure
- * mechanisms. It is capable of detecting when a test case uses in-vm brokers, and setting up an automatic failure
- * for those tests, so that the current live broker can be shut-down by test cases. For external brokers, automatic
- * failure could be implemented, for example by having a kill script. At the moment this sets up the failure to prompt
- * a user interactively to cause a failure, using {@link CauseFailureUserPrompt}.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Setup automatic failures for in-vm brokers. <td> {@link CauseFailureInVM}
- * <tr><td> Setup user generated failures for external brokers. <td> {@link CauseFailureUserPrompt}.
- * <tr><td>
- * </table>
- *
- * @todo Slight problem in that CauseFailureInVM is Qpid specific, whereas CauseFailureUserPrompt is not. Would like the
- * failure decorator to be non-qpid specific so that it can test failure of any JMS implementation too. Either pass
- * in class name of failure mechanism, set it up in the in-vm decorator instead of here but with prompt user as the
- * default for when the in-vm decorator is not used?
- */
-public class CauseFailureDecorator extends WrappedSuiteTestDecorator
-{
- /** The test suite to run. */
- private Test test;
-
- /**
- * Creates a wrapped test test decorator from another one.
- *
- * @param test The test test.
- */
- public CauseFailureDecorator(WrappedSuiteTestDecorator test)
- {
- super(test);
- this.test = test;
- }
-
- /**
- * Runs the tests with a LocalAMQPCircuitFactory. Only tests that extend FrameworkBaseCase are decorated.
- *
- * @param testResult The the results object to monitor the test results with.
- */
- public void run(TestResult testResult)
- {
- for (Test test : getAllUnderlyingTests())
- {
- if (test instanceof BrokerLifecycleAware)
- {
- BrokerLifecycleAware failureTest = (BrokerLifecycleAware) test;
- failureTest.setFailureMechanism(new CauseFailureUserPrompt());
- }
- }
-
- // Run the test.
- test.run(testResult);
- }
-
- /**
- * Prints the name of the test for debugging purposes.
- *
- * @return The name of the test.
- */
- public String toString()
- {
- return "CauseFailureDecorator: [test = \"" + test + "\"]";
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/qpid/CauseFailureInVM.java b/java/systests/src/main/java/org/apache/qpid/test/framework/qpid/CauseFailureInVM.java
deleted file mode 100644
index 3e03ad0872..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/qpid/CauseFailureInVM.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.framework.qpid;
-
-import org.apache.qpid.client.transport.TransportConnection;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-import org.apache.qpid.test.framework.CauseFailure;
-import org.apache.qpid.test.framework.BrokerLifecycleAware;
-
-/**
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Cause messaging broker failure on the active in-vm broker.
- * <td> {@link TransportConnection}, {@link ApplicationRegistry}
- * </table>
- */
-public class CauseFailureInVM implements CauseFailure
-{
- /** Holds the in-vm broker instrumented test case to create failures for. */
- private BrokerLifecycleAware inVMTest;
-
- /**
- * Creates an automated failure mechanism for testing against in-vm brokers. The test to create the mechanism
- * for is specified, and as this failure is for in-vm brokers, the test must be {@link org.apache.qpid.test.framework.BrokerLifecycleAware}. The test
- * must also report that it is currently being run against an in-vm broker, and it is a runtime error if it is not,
- * as the creator of this failure mechanism should already have checked that it is.
- *
- * @param inVMTest The test case to create an automated failure mechanism for.
- */
- public CauseFailureInVM(BrokerLifecycleAware inVMTest)
- {
- // Check that the test is really using in-vm brokers.
- if (!inVMTest.usingInVmBroker())
- {
- throw new RuntimeException(
- "Cannot create in-vm broker failure mechanism for a test that is not using in-vm brokers.");
- }
-
- this.inVMTest = inVMTest;
- }
-
- /**
- * Causes the active message broker to fail.
- */
- public void causeFailure()
- {
- int liveBroker = inVMTest.getLiveBroker();
-
- TransportConnection.killVMBroker(liveBroker);
- ApplicationRegistry.remove(liveBroker);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/qpid/InVMBrokerDecorator.java b/java/systests/src/main/java/org/apache/qpid/test/framework/qpid/InVMBrokerDecorator.java
deleted file mode 100644
index b92a72a654..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/qpid/InVMBrokerDecorator.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.test.framework.qpid;
-
-import junit.framework.Test;
-import junit.framework.TestResult;
-
-import org.apache.qpid.client.transport.TransportConnection;
-import org.apache.qpid.client.vmbroker.AMQVMBrokerCreationException;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-import org.apache.qpid.test.framework.BrokerLifecycleAware;
-import org.apache.qpid.test.framework.FrameworkBaseCase;
-
-import org.apache.qpid.junit.extensions.SetupTaskAware;
-import org.apache.qpid.junit.extensions.WrappedSuiteTestDecorator;
-
-/**
- * InVMBrokerDecorator is a test decorator, that is activated when running tests against an in-vm broker only. Its
- * purpose is to automatically create, and close and delete an in-vm broker, during the set-up and tear-down of
- * each test case. This decorator may only be used in conjunction with tests that extend {@link FrameworkBaseCase}.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Create/Destroy an in-vm broker on every test run.
- * </table>
- *
- * @todo May need to add a more fine grained injection point for the in-vm broker management, as this acts at the
- * suite level, rather than the individual test level.
- *
- * @todo Management of in-vm brokers for failure testing. Failure test setups may need to set their connection url to
- * use multiple broker (vm://:1;vm://:2), with fail-over between them. There is round-robin fail-over, but also
- * retry? A test case using an in-vm broker needs to record which one it is using, so that it can be
- * killed/restarted.
- */
-public class InVMBrokerDecorator extends WrappedSuiteTestDecorator
-{
- /** The test suite to run. */
- private Test test;
-
- /**
- * Creates a wrapped test suite decorator from another one.
- *
- * @param test The test suite.
- */
- public InVMBrokerDecorator(WrappedSuiteTestDecorator test)
- {
- super(test);
- this.test = test;
- }
-
- /**
- * Runs the tests with in-vm broker creation and clean-up added to the tests task stack.
- *
- * @param testResult The the results object to monitor the test results with.
- */
- public void run(TestResult testResult)
- {
- for (Test test : getAllUnderlyingTests())
- {
- // Check that the test to have an in-vm broker setup/teardown task added to it, is actually a framework
- // test that can handle setup tasks.
- if ((test instanceof SetupTaskAware))
- {
- SetupTaskAware frameworkTest = (SetupTaskAware) test;
-
- frameworkTest.chainSetupTask(new Runnable()
- {
- public void run()
- {
- // Ensure that the in-vm broker is created.
- try
- {
- ApplicationRegistry.getInstance(1);
- TransportConnection.createVMBroker(1);
- }
- catch (AMQVMBrokerCreationException e)
- {
- throw new RuntimeException("In-VM broker creation failed: " + e.getMessage(), e);
- }
- }
- });
-
- frameworkTest.chainTearDownTask(new Runnable()
- {
- public void run()
- {
- // Ensure that the in-vm broker is cleaned up so that the next test starts afresh.
- TransportConnection.killVMBroker(1);
- ApplicationRegistry.remove(1);
- }
- });
-
- // Check if the test is aware whether or not it can control the broker life cycle, and if so provide
- // additional instrumentation for it to control the in-vm broker through.
- if (test instanceof BrokerLifecycleAware)
- {
- BrokerLifecycleAware inVMTest = (BrokerLifecycleAware) test;
- inVMTest.setInVmBrokers();
- inVMTest.setLiveBroker(1);
- inVMTest.setFailureMechanism(new CauseFailureInVM(inVMTest));
- }
- }
- }
-
- // Run the test.
- test.run(testResult);
- }
-
- /**
- * Prints the name of the test for debugging purposes.
- *
- * @return The name of the test.
- */
- public String toString()
- {
- return "InVMBrokerDecorator: [test = " + test + "]";
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/sequencers/BaseCircuitFactory.java b/java/systests/src/main/java/org/apache/qpid/test/framework/sequencers/BaseCircuitFactory.java
deleted file mode 100644
index bd27fc3d90..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/sequencers/BaseCircuitFactory.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.test.framework.sequencers;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.test.framework.Circuit;
-import org.apache.qpid.test.framework.TestClientDetails;
-import org.apache.qpid.test.utils.ConversationFactory;
-
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Properties;
-
-/**
- * BaseCircuitFactory provides some functionality common to all {@link CircuitFactory}s, such as the details of
- * all {@link org.apache.qpid.test.framework.distributedtesting.TestClient}s that make up the end-points of
- * the circuits that the factory creates, and an active {@link ConversationFactory} that can be used to generate
- * control conversations with those circuit end-points.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Hold the details of the sending and receiving end-points to create circuits from.
- * <tr><td> Provide a conversation factory to create control conversations with the end-points.
- * </table>
- */
-public abstract class BaseCircuitFactory implements CircuitFactory
-{
-
- /** Used for debugging. */
- private final Logger log = Logger.getLogger(BaseCircuitFactory.class);
-
- /** Holds the contact details for the sending test client. */
- protected TestClientDetails sender;
-
- /** Holds the contact details for the receving test client. */
- protected List<TestClientDetails> receivers = new LinkedList<TestClientDetails>();
-
- /** Holds the conversation factory over which to coordinate the test. */
- protected ConversationFactory conversationFactory;
-
- /**
- * Creates a test circuit for the test, configered by the test parameters specified.
- *
- * @param testProperties The test parameters.
- * @return A test circuit.
- */
- public Circuit createCircuit(Properties testProperties)
- {
- throw new RuntimeException("Not implemented.");
- }
-
- /**
- * Sets the sender test client to coordinate the test with.
- *
- * @param sender The contact details of the sending client in the test.
- */
- public void setSender(TestClientDetails sender)
- {
- log.debug("public void setSender(TestClientDetails sender = " + sender + "): called");
-
- this.sender = sender;
- }
-
- /**
- * Sets the receiving test client to coordinate the test with.
- *
- * @param receiver The contact details of the sending client in the test.
- */
- public void setReceiver(TestClientDetails receiver)
- {
- log.debug("public void setReceiver(TestClientDetails receivers = " + receiver + "): called");
-
- this.receivers.add(receiver);
- }
-
- /**
- * Supplies the sending test client.
- *
- * @return The sending test client.
- */
- public TestClientDetails getSender()
- {
- return sender;
- }
-
- /**
- * Supplies the receiving test client.
- *
- * @return The receiving test client.
- */
- public List<TestClientDetails> getReceivers()
- {
- return receivers;
- }
-
- /**
- * Accepts the conversation factory over which to hold the test coordinating conversation.
- *
- * @param conversationFactory The conversation factory to coordinate the test over.
- */
- public void setConversationFactory(ConversationFactory conversationFactory)
- {
- this.conversationFactory = conversationFactory;
- }
-
- /**
- * Provides the conversation factory for providing the distributed test sequencing conversations over the test
- * connection.
- *
- * @return The conversation factory to create test sequencing conversations with.
- */
- public ConversationFactory getConversationFactory()
- {
- return conversationFactory;
- }
-}
-
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/sequencers/CircuitFactory.java b/java/systests/src/main/java/org/apache/qpid/test/framework/sequencers/CircuitFactory.java
deleted file mode 100644
index e69952918d..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/sequencers/CircuitFactory.java
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.framework.sequencers;
-
-import org.apache.qpid.test.framework.Assertion;
-import org.apache.qpid.test.framework.Circuit;
-import org.apache.qpid.test.framework.TestClientDetails;
-import org.apache.qpid.test.utils.ConversationFactory;
-
-import org.apache.qpid.junit.extensions.util.ParsedProperties;
-
-import javax.jms.Connection;
-import java.util.List;
-import java.util.Properties;
-
-/**
- * A CircuitFactory is responsibile for creating test circuits appropriate to the context that a test case is
- * running in, and providing an implementation of a standard test procedure over a test circuit.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities
- * <tr><td> Provide a standard test procedure over a test circuit.
- * <tr><td> Construct test circuits appropriate to a tests context.
- * </table>
- */
-public interface CircuitFactory
-{
- /**
- * Holds a test coordinating conversation with the test clients. This should consist of assigning the test roles,
- * begining the test, gathering the test reports from the participants, and checking for assertion failures against
- * the test reports.
- *
- * @param testCircuit The test circuit.
- * @param assertions The list of assertions to apply to the test circuit.
- * @param testProperties The test case definition.
- *
- * @deprecated Use test circuits and Circuit.test instead.
- */
- public void sequenceTest(Circuit testCircuit, List<Assertion> assertions, Properties testProperties);
-
- /**
- * Creates a test circuit for the test, configered by the test parameters specified.
- *
- * @param testProperties The test parameters.
- *
- * @return A test circuit.
- */
- public Circuit createCircuit(Connection connection, ParsedProperties testProperties);
-
- /**
- * Sets the sender test client to coordinate the test with.
- *
- * @param sender The contact details of the sending client in the test.
- */
- public void setSender(TestClientDetails sender);
-
- /**
- * Sets the receiving test client to coordinate the test with.
- *
- * @param receiver The contact details of the sending client in the test.
- */
- public void setReceiver(TestClientDetails receiver);
-
- /**
- * Supplies the sending test client.
- *
- * @return The sending test client.
- */
- public TestClientDetails getSender();
-
- /**
- * Supplies the receiving test client.
- *
- * @return The receiving test client.
- */
- public List<TestClientDetails> getReceivers();
-
- /**
- * Accepts the conversation factory over which to hold the test coordinating conversation.
- *
- * @param conversationFactory The conversation factory to coordinate the test over.
- */
- public void setConversationFactory(ConversationFactory conversationFactory);
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/sequencers/FanOutCircuitFactory.java b/java/systests/src/main/java/org/apache/qpid/test/framework/sequencers/FanOutCircuitFactory.java
deleted file mode 100644
index 8a9c48d8e7..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/sequencers/FanOutCircuitFactory.java
+++ /dev/null
@@ -1,198 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.framework.sequencers;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.test.framework.Assertion;
-import org.apache.qpid.test.framework.Circuit;
-import org.apache.qpid.test.framework.TestClientDetails;
-import org.apache.qpid.test.framework.TestUtils;
-import org.apache.qpid.test.framework.distributedcircuit.DistributedCircuitImpl;
-import org.apache.qpid.test.utils.ConversationFactory;
-
-import org.apache.qpid.junit.extensions.util.ParsedProperties;
-
-import javax.jms.*;
-
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Properties;
-
-/**
- * FanOutCircuitFactory is a circuit factory that creates distributed test circuits. Given a set of participating
- * test client nodes, it assigns one node to the SENDER role and the remainder to the RECEIVER role.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Create distributed circuits from one to many test nodes, for fanout style testing.
- * </table>
- *
- * @todo Adapt this to be an n*m topology circuit factory. Need to add circuit topology definitions to the test
- * parameters. Place n senders onto the available test clients, and m receivers. Where n or m is larger than
- * the available nodes, start stacking multiple test clients on each node. There will also be an option that
- * indicates whether nodes can play both roles, and how many nodes out of all available may be assigned to
- * each role.
- *
- * @todo The createCircuit methods on this and InteropCircuitFactory are going to be identical. This is because the
- * partitioning into senders and receivers is already done by the test decorators. Either eliminate these factories
- * as unnesesary, or move the partitioning functionality into the factories, in which case the test decorators
- * can probably be merged or eliminated. There is confusion over the placement of responsibilities between the
- * factories and the test decorators... although the test decorators may well do more than just circuit creation
- * in the future. For example, there may have to be a special decorator for test repetition that does one circuit
- * creation, but the runs many tests over it, in which case the handling of responsibilities becomes clearer.
- */
-public class FanOutCircuitFactory extends BaseCircuitFactory
-{
- /** Used for debugging. */
- Logger log = Logger.getLogger(FanOutCircuitFactory.class);
-
- /**
- * Creates a test circuit for the test, configered by the test parameters specified.
- *
- * @param testProperties The test parameters.
- * @return A test circuit.
- */
- public Circuit createCircuit(Connection connection, ParsedProperties testProperties)
- {
- log.debug("public Circuit createCircuit(ParsedProperties testProperties): called");
-
- List<TestClientDetails> senders = new LinkedList<TestClientDetails>();
- senders.add(getSender());
- List<TestClientDetails> receivers = getReceivers();
- ConversationFactory conversationFactory = getConversationFactory();
-
- return DistributedCircuitImpl.createCircuit(testProperties, senders, receivers, conversationFactory);
- }
-
- /**
- * Holds a test coordinating conversation with the test clients. This should consist of assigning the test roles,
- * begining the test, gathering the test reports from the participants, and checking for assertion failures against
- * the test reports.
- *
- * @param testCircuit The test circuit.
- * @param assertions The list of assertions to apply to the test circuit.
- * @param testProperties The test case definition.
- *
- * @deprecated Scheduled for removal once existing tests converted over to use test circuits.
- */
- public void sequenceTest(Circuit testCircuit, List<Assertion> assertions, Properties testProperties)
- {
- log.debug("protected Message[] sequenceTest(Object... testProperties = " + testProperties + "): called");
-
- TestClientDetails sender = getSender();
- List<TestClientDetails> receivers = getReceivers();
- ConversationFactory conversationFactory = getConversationFactory();
-
- try
- {
- // Create a conversation on the sender clients private control route.
- Session session = conversationFactory.getSession();
- Destination senderControlTopic = session.createTopic(sender.privateControlKey);
- ConversationFactory.Conversation senderConversation = conversationFactory.startConversation();
-
- // Assign the sender role to the sending test client.
- Message assignSender = conversationFactory.getSession().createMessage();
- TestUtils.setPropertiesOnMessage(assignSender, testProperties);
- assignSender.setStringProperty("CONTROL_TYPE", "ASSIGN_ROLE");
- assignSender.setStringProperty("ROLE", "SENDER");
- assignSender.setStringProperty("CLIENT_NAME", "Sustained_SENDER");
-
- senderConversation.send(senderControlTopic, assignSender);
-
- // Wait for the sender to confirm its role.
- senderConversation.receive();
-
- // Assign the receivers roles.
- for (TestClientDetails receiver : receivers)
- {
- assignReceiverRole(receiver, testProperties, true);
- }
-
- // Start the test on the sender.
- Message start = session.createMessage();
- start.setStringProperty("CONTROL_TYPE", "START");
-
- senderConversation.send(senderControlTopic, start);
-
- // Wait for the test sender to return its report.
- Message senderReport = senderConversation.receive();
- TestUtils.pause(500);
-
- // Ask the receivers for their reports.
- Message statusRequest = session.createMessage();
- statusRequest.setStringProperty("CONTROL_TYPE", "STATUS_REQUEST");
-
- // Gather the reports from all of the receiving clients.
-
- // Return all of the test reports, the senders report first.
- // return new Message[] { senderReport };
- }
- catch (JMSException e)
- {
- throw new RuntimeException("Unhandled JMSException.");
- }
- }
-
- /**
- * Assigns the receivers role to the specified test client that is to act as a receivers during the test. This method
- * does not always wait for the receiving clients to confirm their role assignments. This is because this method
- * may be called from an 'onMessage' method, when a client is joining the test at a later point in time, and it
- * is not possible to do a synchronous receive during an 'onMessage' method. There is a flag to indicate whether
- * or not to wait for role confirmations.
- *
- * @param receiver The test client to assign the receivers role to.
- * @param testProperties The test parameters.
- * @param confirm Indicates whether role confirmation should be waited for.
- *
- * @throws JMSException Any JMSExceptions occurring during the conversation are allowed to fall through.
- *
- * @deprecated Scheduled for removal once existing tests converted over to use test circuits.
- */
- protected void assignReceiverRole(TestClientDetails receiver, Properties testProperties, boolean confirm)
- throws JMSException
- {
- log.info("assignReceiverRole(TestClientDetails receivers = " + receiver + ", Map<String, Object> testProperties = "
- + testProperties + "): called");
-
- ConversationFactory conversationFactory = getConversationFactory();
-
- // Create a conversation with the receiving test client.
- Session session = conversationFactory.getSession();
- Destination receiverControlTopic = session.createTopic(receiver.privateControlKey);
- ConversationFactory.Conversation receiverConversation = conversationFactory.startConversation();
-
- // Assign the receivers role to the receiving client.
- Message assignReceiver = session.createMessage();
- TestUtils.setPropertiesOnMessage(assignReceiver, testProperties);
- assignReceiver.setStringProperty("CONTROL_TYPE", "ASSIGN_ROLE");
- assignReceiver.setStringProperty("ROLE", "RECEIVER");
- assignReceiver.setStringProperty("CLIENT_NAME", receiver.clientName);
-
- receiverConversation.send(receiverControlTopic, assignReceiver);
-
- // Wait for the role confirmation to come back.
- if (confirm)
- {
- receiverConversation.receive();
- }
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/sequencers/InteropCircuitFactory.java b/java/systests/src/main/java/org/apache/qpid/test/framework/sequencers/InteropCircuitFactory.java
deleted file mode 100644
index 7df80bbf10..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/framework/sequencers/InteropCircuitFactory.java
+++ /dev/null
@@ -1,152 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.framework.sequencers;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.test.framework.Assertion;
-import org.apache.qpid.test.framework.Circuit;
-import org.apache.qpid.test.framework.TestClientDetails;
-import org.apache.qpid.test.framework.TestUtils;
-import org.apache.qpid.test.framework.distributedcircuit.DistributedCircuitImpl;
-import org.apache.qpid.test.utils.ConversationFactory;
-
-import org.apache.qpid.junit.extensions.util.ParsedProperties;
-
-import javax.jms.*;
-
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Properties;
-
-/**
- * InteropCircuitFactory is a circuit factory that creates distributed test circuits. Given a set of participating
- * test client nodes, it assigns one node to the SENDER role and one the RECEIVER role.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Create distributed circuits from pairs of test nodes, for interop style testing.
- * </table>
- *
- * @todo The partitioning of a set of nodes into sender and receiver roles is actually done by the interop test
- * decorator. See the todo comment in FanOutCircuitFactory about merging the factories with the decorators, or
- * more carefully dividing up responsibilities between them.
- *
- * @todo The squenceTest code is deprecated, but currently still used by the interop tests. It will be removed once it
- * have been fully replaced by the default test procedure.
- */
-public class InteropCircuitFactory extends BaseCircuitFactory
-{
- /** Used for debugging. */
- Logger log = Logger.getLogger(InteropCircuitFactory.class);
-
- /**
- * Creates a test circuit for the test, configered by the test parameters specified.
- *
- * @param testProperties The test parameters.
- * @return A test circuit.
- */
- public Circuit createCircuit(Connection connection, ParsedProperties testProperties)
- {
- log.debug("public Circuit createCircuit(ParsedProperties testProperties): called");
-
- List<TestClientDetails> senders = new LinkedList<TestClientDetails>();
- senders.add(getSender());
- List<TestClientDetails> receivers = getReceivers();
- ConversationFactory conversationFactory = getConversationFactory();
-
- return DistributedCircuitImpl.createCircuit(testProperties, senders, receivers, conversationFactory);
- }
-
- /**
- * Holds a test coordinating conversation with the test clients. This should consist of assigning the test roles,
- * begining the test, gathering the test reports from the participants, and checking for assertion failures against
- * the test reports.
- *
- * @param testCircuit The test circuit.
- * @param assertions The list of assertions to apply to the test circuit.
- * @param testProperties The test case definition.
- */
- public void sequenceTest(Circuit testCircuit, List<Assertion> assertions, Properties testProperties)
- {
- log.debug("protected Message[] sequenceTest(Object... testProperties = " + testProperties + "): called");
-
- TestClientDetails sender = getSender();
- List<TestClientDetails> receivers = getReceivers();
- ConversationFactory conversationFactory = getConversationFactory();
-
- try
- {
- Session session = conversationFactory.getSession();
- Destination senderControlTopic = session.createTopic(sender.privateControlKey);
- Destination receiverControlTopic = session.createTopic(receivers.get(0).privateControlKey);
-
- ConversationFactory.Conversation senderConversation = conversationFactory.startConversation();
- ConversationFactory.Conversation receiverConversation = conversationFactory.startConversation();
-
- Message assignSender = conversationFactory.getSession().createMessage();
- TestUtils.setPropertiesOnMessage(assignSender, testProperties);
- assignSender.setStringProperty("CONTROL_TYPE", "ASSIGN_ROLE");
- assignSender.setStringProperty("ROLE", "SENDER");
-
- senderConversation.send(senderControlTopic, assignSender);
-
- // Assign the receivers role the receiving client.
- Message assignReceiver = session.createMessage();
- TestUtils.setPropertiesOnMessage(assignReceiver, testProperties);
- assignReceiver.setStringProperty("CONTROL_TYPE", "ASSIGN_ROLE");
- assignReceiver.setStringProperty("ROLE", "RECEIVER");
-
- receiverConversation.send(receiverControlTopic, assignReceiver);
-
- // Wait for the senders and receivers to confirm their roles.
- senderConversation.receive();
- receiverConversation.receive();
-
- // Start the test.
- Message start = session.createMessage();
- start.setStringProperty("CONTROL_TYPE", "START");
-
- senderConversation.send(senderControlTopic, start);
-
- // Wait for the test sender to return its report.
- Message senderReport = senderConversation.receive();
- TestUtils.pause(500);
-
- // Ask the receivers for its report.
- Message statusRequest = session.createMessage();
- statusRequest.setStringProperty("CONTROL_TYPE", "STATUS_REQUEST");
-
- receiverConversation.send(receiverControlTopic, statusRequest);
-
- // Wait for the receivers to send its report.
- Message receiverReport = receiverConversation.receive();
-
- // return new Message[] { senderReport, receiverReport };
-
- // Apply assertions.
- }
- catch (JMSException e)
- {
- throw new RuntimeException("JMSException not handled.");
- }
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/testcases/FailoverTest.java b/java/systests/src/main/java/org/apache/qpid/test/testcases/FailoverTest.java
deleted file mode 100644
index a5a0d4e41f..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/testcases/FailoverTest.java
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.testcases;
-
-import org.apache.qpid.test.framework.*;
-import static org.apache.qpid.test.framework.MessagingTestConfigProperties.*;
-import org.apache.qpid.test.framework.localcircuit.LocalCircuitImpl;
-import org.apache.qpid.test.framework.sequencers.CircuitFactory;
-
-import javax.jms.JMSException;
-import javax.jms.MessageProducer;
-import javax.jms.Session;
-
-/**
- * FailoverTest provides testing of fail-over over a local-circuit implementation. The circuit being tested may be
- * against an in-vm broker or against an external broker, with the failure mechanism abstracted out of the test case.
- * Automatic failures can be simulated against an in-vm broker. Currently the test must interact with the user to
- * simulate failures on an external broker.
- *
- * Things to test:
- * In tx, failure duing tx causes tx to error on subsequent sends/receives or commits/rollbacks.
- * Outside of tx, reconnection allows msg flow to continue but there may be loss.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td>
- * </table>
- *
- * @todo This test is designed to be run over a local circuit only. For in-vm using automatic failures, for external
- * brokers by prompting the user (or maybe using a script). Enforce the local-circuit only nature of the tests as
- * well as thinking about how other local-circuit tests might be implemented. For example, could add a method
- * to the framework base case for local only tests to call, that allows them access to the local-circuit
- * implementation and so on.
- *
- * @todo More. Need to really expand the set of fail-over tests.
- */
-public class FailoverTest extends FrameworkBaseCase
-{
- /* Used for debugging purposes. */
- // private static final Logger log = Logger.getLogger(FailoverTest.class);
-
- /**
- * Creates a new test case with the specified name.
- *
- * @param name The test case name.
- */
- public FailoverTest(String name)
- {
- super(name);
- }
-
- /**
- * Checks that all messages sent within a transaction are receieved despite a fail-over occuring outside of
- * the transaction.
- *
- * @throws JMSException Allowed to fall through and fail test.
- */
- public void testTxP2PFailover() throws Exception
- {
- // Set up the test properties to match the test cases requirements.
- getTestProps().setProperty(TRANSACTED_PUBLISHER_PROPNAME, true);
- getTestProps().setProperty(ACK_MODE_PROPNAME, Session.AUTO_ACKNOWLEDGE);
- getTestProps().setProperty(PUBSUB_PROPNAME, false);
-
- // MessagingTestConfigProperties props = this.getTestParameters();
-
- // Create the test circuit from the test configuration parameters.
- CircuitFactory circuitFactory = getCircuitFactory();
- Circuit testCircuit = circuitFactory.createCircuit(getConnection(), getTestProps());
-
- // Create an assertion that all messages are received.
- Assertion allMessagesReceived = testCircuit.getReceiver().allMessagesReceivedAssertion(getTestProps());
-
- // This test case assumes it is using a local circuit.
- LocalCircuitImpl localCircuit = (LocalCircuitImpl) testCircuit;
-
- Session producerSession = localCircuit.getLocalPublisherCircuitEnd().getSession();
- MessageProducer producer = localCircuit.getLocalPublisherCircuitEnd().getProducer();
- // MessageConsumer consumer = localCircuit.getLocalReceiverCircuitEnd().getConsumer();
-
- // Send some test messages.
- for (int i = 0; i < 100; i++)
- {
- producer.send(TestUtils.createTestMessageOfSize(producerSession, 10));
- producerSession.commit();
-
- // Cause a failover.
- if (i == 50)
- {
- getFailureMechanism().causeFailure();
- }
-
- // Wait for the reconnection to complete.
- }
-
- // Check that trying to send within the original transaction fails.
-
- // Check that all messages sent were received.
- assertTrue("All messages sent were not received back again.", allMessagesReceived.apply());
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/testcases/ImmediateMessageTest.java b/java/systests/src/main/java/org/apache/qpid/test/testcases/ImmediateMessageTest.java
deleted file mode 100644
index 3001211eae..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/testcases/ImmediateMessageTest.java
+++ /dev/null
@@ -1,303 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.testcases;
-
-import org.apache.qpid.test.framework.AMQPPublisher;
-import org.apache.qpid.test.framework.Circuit;
-import org.apache.qpid.test.framework.FrameworkBaseCase;
-import org.apache.qpid.test.framework.MessagingTestConfigProperties;
-import static org.apache.qpid.test.framework.MessagingTestConfigProperties.*;
-import org.apache.qpid.test.framework.sequencers.CircuitFactory;
-
-import org.apache.qpid.junit.extensions.util.TestContextProperties;
-
-/**
- * ImmediateMessageTest tests for the desired behaviour of immediate messages. Immediate messages are a non-JMS
- * feature. A message may be marked with an immediate delivery flag, which means that a consumer must be connected
- * to receive the message, through a valid route, when it is sent, or when its transaction is committed in the case
- * of transactional messaging. If this is not the case, the broker should return the message with a NO_CONSUMERS code.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Check that an immediate message is sent succesfully not using transactions when a consumer is connected.
- * <tr><td> Check that an immediate message is committed succesfully in a transaction when a consumer is connected.
- * <tr><td> Check that an immediate message results in no consumers code, not using transactions, when a consumer is
- * disconnected.
- * <tr><td> Check that an immediate message results in no consumers code, in a transaction, when a consumer is
- * disconnected.
- * <tr><td> Check that an immediate message results in no route code, not using transactions, when no outgoing route is
- * connected.
- * <tr><td> Check that an immediate message results in no route code, upon transaction commit, when no outgoing route is
- * connected.
- * <tr><td> Check that an immediate message is sent succesfully not using transactions when a consumer is connected.
- * <tr><td> Check that an immediate message is committed succesfully in a transaction when a consumer is connected.
- * <tr><td> Check that an immediate message results in no consumers code, not using transactions, when a consumer is
- * disconnected.
- * <tr><td> Check that an immediate message results in no consumers code, in a transaction, when a consumer is
- * disconnected.
- * <tr><td> Check that an immediate message results in no route code, not using transactions, when no outgoing route is
- * connected.
- * <tr><td> Check that an immediate message results in no route code, upon transaction commit, when no outgoing route is
- * connected.
- * </table>
- *
- * @todo All of these test cases will be generated by a test generator that thoroughly tests all combinations of test
- * circuits.
- */
-public class ImmediateMessageTest extends FrameworkBaseCase
-{
- /**
- * Creates a new test case with the specified name.
- *
- * @param name The test case name.
- */
- public ImmediateMessageTest(String name)
- {
- super(name);
- }
-
- /** Check that an immediate message is sent succesfully not using transactions when a consumer is connected. */
- public void test_QPID_517_ImmediateOkNoTxP2P() throws Exception
- {
- // Ensure transactional sessions are off.
- getTestProps().setProperty(TRANSACTED_PUBLISHER_PROPNAME, false);
- getTestProps().setProperty(PUBSUB_PROPNAME, false);
-
- // Run the default test sequence over the test circuit checking for no errors.
- CircuitFactory circuitFactory = getCircuitFactory();
- Circuit testCircuit = circuitFactory.createCircuit(getConnection(), getTestProps());
-
- assertNoFailures(testCircuit.test(1, assertionList(testCircuit.getPublisher().noExceptionsAssertion(getTestProps()))));
- }
-
- /** Check that an immediate message is committed succesfully in a transaction when a consumer is connected. */
- public void test_QPID_517_ImmediateOkTxP2P() throws Exception
- {
- // Ensure transactional sessions are off.
- getTestProps().setProperty(TRANSACTED_PUBLISHER_PROPNAME, true);
- getTestProps().setProperty(PUBSUB_PROPNAME, false);
-
- // Send one message with no errors.
- CircuitFactory circuitFactory = getCircuitFactory();
- Circuit testCircuit = circuitFactory.createCircuit(getConnection(), getTestProps());
-
- assertNoFailures(testCircuit.test(1, assertionList(testCircuit.getPublisher().noExceptionsAssertion(getTestProps()))));
- }
-
- /** Check that an immediate message results in no consumers code, not using transactions, when a consumer is disconnected. */
- public void test_QPID_517_ImmediateFailsConsumerDisconnectedNoTxP2P() throws Exception
- {
- // Ensure transactional sessions are off.
- getTestProps().setProperty(TRANSACTED_PUBLISHER_PROPNAME, false);
- getTestProps().setProperty(PUBSUB_PROPNAME, false);
-
- // Disconnect the consumer.
- getTestProps().setProperty(RECEIVER_CONSUMER_ACTIVE_PROPNAME, false);
-
- CircuitFactory circuitFactory = getCircuitFactory();
- Circuit testCircuit = circuitFactory.createCircuit(getConnection(), getTestProps());
-
- // Send one message and get a linked no consumers exception.
- assertNoFailures(testCircuit.test(1,
- assertionList(((AMQPPublisher) testCircuit.getPublisher()).noConsumersAssertion(getTestProps()))));
- }
-
- /** Check that an immediate message results in no consumers code, in a transaction, when a consumer is disconnected. */
- public void test_QPID_517_ImmediateFailsConsumerDisconnectedTxP2P() throws Exception
- {
- // Ensure transactional sessions are on.
- getTestProps().setProperty(TRANSACTED_PUBLISHER_PROPNAME, true);
- getTestProps().setProperty(PUBSUB_PROPNAME, false);
-
- // Disconnect the consumer.
- getTestProps().setProperty(RECEIVER_CONSUMER_ACTIVE_PROPNAME, false);
-
- CircuitFactory circuitFactory = getCircuitFactory();
- Circuit testCircuit = circuitFactory.createCircuit(getConnection(), getTestProps());
-
- // Send one message and get a linked no consumers exception.
- assertNoFailures(testCircuit.test(1,
- assertionList(((AMQPPublisher) testCircuit.getPublisher()).noConsumersAssertion(getTestProps()))));
- }
-
- /** Check that an immediate message results in no route code, not using transactions, when no outgoing route is connected. */
- public void test_QPID_517_ImmediateFailsNoRouteNoTxP2P() throws Exception
- {
- // Ensure transactional sessions are off.
- getTestProps().setProperty(TRANSACTED_PUBLISHER_PROPNAME, false);
- getTestProps().setProperty(PUBSUB_PROPNAME, false);
-
- // Set up the messaging topology so that only the publishers producer is bound (do not set up the receivers to
- // collect its messages).
- getTestProps().setProperty(RECEIVER_CONSUMER_BIND_PROPNAME, false);
-
- // Send one message and get a linked no route exception.
- CircuitFactory circuitFactory = getCircuitFactory();
- Circuit testCircuit = circuitFactory.createCircuit(getConnection(), getTestProps());
-
- assertNoFailures(testCircuit.test(1,
- assertionList(((AMQPPublisher) testCircuit.getPublisher()).noRouteAssertion(getTestProps()))));
- }
-
- /** Check that an immediate message results in no route code, upon transaction commit, when no outgoing route is connected. */
- public void test_QPID_517_ImmediateFailsNoRouteTxP2P() throws Exception
- {
- // Ensure transactional sessions are on.
- getTestProps().setProperty(TRANSACTED_PUBLISHER_PROPNAME, true);
- getTestProps().setProperty(PUBSUB_PROPNAME, false);
-
- // Set up the messaging topology so that only the publishers producer is bound (do not set up the receivers to
- // collect its messages).
- getTestProps().setProperty(RECEIVER_CONSUMER_BIND_PROPNAME, false);
-
- // Send one message and get a linked no route exception.
- CircuitFactory circuitFactory = getCircuitFactory();
- Circuit testCircuit = circuitFactory.createCircuit(getConnection(), getTestProps());
-
- assertNoFailures(testCircuit.test(1,
- assertionList(((AMQPPublisher) testCircuit.getPublisher()).noRouteAssertion(getTestProps()))));
- }
-
- /** Check that an immediate message is sent succesfully not using transactions when a consumer is connected. */
- public void test_QPID_517_ImmediateOkNoTxPubSub() throws Exception
- {
- // Ensure transactional sessions are off.
- getTestProps().setProperty(TRANSACTED_PUBLISHER_PROPNAME, false);
- getTestProps().setProperty(PUBSUB_PROPNAME, true);
-
- // Send one message with no errors.
- CircuitFactory circuitFactory = getCircuitFactory();
- Circuit testCircuit = circuitFactory.createCircuit(getConnection(), getTestProps());
-
- assertNoFailures(testCircuit.test(1,
- assertionList(((AMQPPublisher) testCircuit.getPublisher()).noExceptionsAssertion(getTestProps()))));
- }
-
- /** Check that an immediate message is committed succesfully in a transaction when a consumer is connected. */
- public void test_QPID_517_ImmediateOkTxPubSub() throws Exception
- {
- // Ensure transactional sessions are off.
- getTestProps().setProperty(TRANSACTED_PUBLISHER_PROPNAME, true);
- getTestProps().setProperty(PUBSUB_PROPNAME, true);
-
- // Send one message with no errors.
- CircuitFactory circuitFactory = getCircuitFactory();
- Circuit testCircuit = circuitFactory.createCircuit(getConnection(), getTestProps());
-
- assertNoFailures(testCircuit.test(1,
- assertionList(((AMQPPublisher) testCircuit.getPublisher()).noExceptionsAssertion(getTestProps()))));
- }
-
- /** Check that an immediate message results in no consumers code, not using transactions, when a consumer is disconnected. */
- public void test_QPID_517_ImmediateFailsConsumerDisconnectedNoTxPubSub() throws Exception
- {
- // Ensure transactional sessions are off.
- getTestProps().setProperty(TRANSACTED_PUBLISHER_PROPNAME, false);
- getTestProps().setProperty(PUBSUB_PROPNAME, true);
-
- // Use durable subscriptions, so that the route remains open with no subscribers.
- getTestProps().setProperty(DURABLE_SUBSCRIPTION_PROPNAME, true);
-
- // Disconnect the consumer.
- getTestProps().setProperty(RECEIVER_CONSUMER_ACTIVE_PROPNAME, false);
-
- CircuitFactory circuitFactory = getCircuitFactory();
- Circuit testCircuit = circuitFactory.createCircuit(getConnection(), getTestProps());
-
- // Send one message and get a linked no consumers exception.
- assertNoFailures(testCircuit.test(1,
- assertionList(((AMQPPublisher) testCircuit.getPublisher()).noConsumersAssertion(getTestProps()))));
- }
-
- /** Check that an immediate message results in no consumers code, in a transaction, when a consumer is disconnected. */
- public void test_QPID_517_ImmediateFailsConsumerDisconnectedTxPubSub() throws Exception
- {
- // Ensure transactional sessions are on.
- getTestProps().setProperty(TRANSACTED_PUBLISHER_PROPNAME, true);
- getTestProps().setProperty(PUBSUB_PROPNAME, true);
-
- // Use durable subscriptions, so that the route remains open with no subscribers.
- getTestProps().setProperty(DURABLE_SUBSCRIPTION_PROPNAME, true);
-
- // Disconnect the consumer.
- getTestProps().setProperty(RECEIVER_CONSUMER_ACTIVE_PROPNAME, false);
-
- CircuitFactory circuitFactory = getCircuitFactory();
- Circuit testCircuit = circuitFactory.createCircuit(getConnection(), getTestProps());
-
- // Send one message and get a linked no consumers exception.
- assertNoFailures(testCircuit.test(1,
- assertionList(((AMQPPublisher) testCircuit.getPublisher()).noConsumersAssertion(getTestProps()))));
- }
-
- /** Check that an immediate message results in no route code, not using transactions, when no outgoing route is connected. */
- public void test_QPID_517_ImmediateFailsNoRouteNoTxPubSub() throws Exception
- {
- // Ensure transactional sessions are off.
- getTestProps().setProperty(TRANSACTED_PUBLISHER_PROPNAME, false);
- getTestProps().setProperty(PUBSUB_PROPNAME, true);
-
- // Set up the messaging topology so that only the publishers producer is bound (do not set up the receivers to
- // collect its messages).
- getTestProps().setProperty(RECEIVER_CONSUMER_BIND_PROPNAME, false);
-
- // Send one message and get a linked no route exception.
- CircuitFactory circuitFactory = getCircuitFactory();
- Circuit testCircuit = circuitFactory.createCircuit(getConnection(), getTestProps());
-
- assertNoFailures(testCircuit.test(1,
- assertionList(((AMQPPublisher) testCircuit.getPublisher()).noRouteAssertion(getTestProps()))));
- }
-
- /** Check that an immediate message results in no route code, upon transaction commit, when no outgoing route is connected. */
- public void test_QPID_517_ImmediateFailsNoRouteTxPubSub() throws Exception
- {
- // Ensure transactional sessions are on.
- getTestProps().setProperty(TRANSACTED_PUBLISHER_PROPNAME, true);
- getTestProps().setProperty(PUBSUB_PROPNAME, true);
-
- // Set up the messaging topology so that only the publishers producer is bound (do not set up the receivers to
- // collect its messages).
- getTestProps().setProperty(RECEIVER_CONSUMER_BIND_PROPNAME, false);
-
- // Send one message and get a linked no route exception.
- CircuitFactory circuitFactory = getCircuitFactory();
- Circuit testCircuit = circuitFactory.createCircuit(getConnection(), getTestProps());
-
- assertNoFailures(testCircuit.test(1,
- assertionList(((AMQPPublisher) testCircuit.getPublisher()).noRouteAssertion(getTestProps()))));
- }
-
- protected void setUp() throws Exception
- {
- super.setUp();
-
- setTestProps(TestContextProperties.getInstance(MessagingTestConfigProperties.defaults));
-
- /** All these tests should have the immediate flag on. */
- getTestProps().setProperty(IMMEDIATE_PROPNAME, true);
- getTestProps().setProperty(MANDATORY_PROPNAME, false);
-
- /** Bind the receivers consumer by default. */
- getTestProps().setProperty(RECEIVER_CONSUMER_BIND_PROPNAME, true);
- getTestProps().setProperty(RECEIVER_CONSUMER_ACTIVE_PROPNAME, true);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/testcases/MandatoryMessageTest.java b/java/systests/src/main/java/org/apache/qpid/test/testcases/MandatoryMessageTest.java
deleted file mode 100644
index b4c4eb91b4..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/testcases/MandatoryMessageTest.java
+++ /dev/null
@@ -1,321 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.testcases;
-
-import org.apache.qpid.test.framework.AMQPPublisher;
-import org.apache.qpid.test.framework.Circuit;
-import org.apache.qpid.test.framework.FrameworkBaseCase;
-import org.apache.qpid.test.framework.MessagingTestConfigProperties;
-import static org.apache.qpid.test.framework.MessagingTestConfigProperties.*;
-import org.apache.qpid.test.framework.sequencers.CircuitFactory;
-
-import org.apache.qpid.junit.extensions.util.ParsedProperties;
-import org.apache.qpid.junit.extensions.util.TestContextProperties;
-
-/**
- * MandatoryMessageTest tests for the desired behaviour of mandatory messages. Mandatory messages are a non-JMS
- * feature. A message may be marked with a mandatory delivery flag, which means that a valid route for the message
- * must exist, when it is sent, or when its transaction is committed in the case of transactional messaging. If this
- * is not the case, the broker should return the message with a NO_CONSUMERS code.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Check that an mandatory message is sent succesfully not using transactions when a consumer is connected.
- * <tr><td> Check that an mandatory message is committed succesfully in a transaction when a consumer is connected.
- * <tr><td> Check that a mandatory message is sent succesfully, not using transactions, when a consumer is disconnected
- * but the route exists.
- * <tr><td> Check that a mandatory message is sent succesfully, in a transaction, when a consumer is disconnected but
- * the route exists.
- * <tr><td> Check that an mandatory message results in no route code, not using transactions, when no consumer is
- * connected.
- * <tr><td> Check that an mandatory message results in no route code, upon transaction commit, when a consumer is
- * connected.
- * <tr><td> Check that an mandatory message is sent succesfully not using transactions when a consumer is connected.
- * <tr><td> Check that an mandatory message is committed succesfully in a transaction when a consumer is connected.
- * <tr><td> Check that a mandatory message is sent succesfully, not using transactions, when a consumer is disconnected
- * but the route exists.
- * <tr><td> Check that a mandatory message is sent succesfully, in a transaction, when a consumer is disconnected but
- * the route exists.
- * <tr><td> Check that an mandatory message results in no route code, not using transactions, when no consumer is
- * connected.
- * <tr><td> Check that an mandatory message results in no route code, upon transaction commit, when a consumer is
- * connected.
- * </table>
- *
- * @todo All of these test cases will be generated by a test generator that thoroughly tests all combinations of test
- * circuits.
- */
-public class MandatoryMessageTest extends FrameworkBaseCase
-{
- /** Used to read the tests configurable properties through. */
- ParsedProperties testProps;
-
- /**
- * Creates a new test case with the specified name.
- *
- * @param name The test case name.
- */
- public MandatoryMessageTest(String name)
- {
- super(name);
- }
-
- /** Check that an mandatory message is sent succesfully not using transactions when a consumer is connected. */
- public void test_QPID_508_MandatoryOkNoTxP2P() throws Exception
- {
- // Ensure transactional sessions are off.
- testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, false);
- testProps.setProperty(PUBSUB_PROPNAME, false);
-
- // Run the default test sequence over the test circuit checking for no errors.
- CircuitFactory circuitFactory = getCircuitFactory();
- Circuit testCircuit = circuitFactory.createCircuit(getConnection(), testProps);
-
- assertNoFailures(testCircuit.test(1,
- assertionList(((AMQPPublisher) testCircuit.getPublisher()).noExceptionsAssertion(testProps))));
- }
-
- /** Check that an mandatory message is committed succesfully in a transaction when a consumer is connected. */
- public void test_QPID_508_MandatoryOkTxP2P() throws Exception
- {
- // Ensure transactional sessions are off.
- testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, true);
- testProps.setProperty(PUBSUB_PROPNAME, false);
-
- // Run the default test sequence over the test circuit checking for no errors.
- CircuitFactory circuitFactory = getCircuitFactory();
- Circuit testCircuit = circuitFactory.createCircuit(getConnection(), testProps);
-
- assertNoFailures(testCircuit.test(1,
- assertionList(((AMQPPublisher) testCircuit.getPublisher()).noExceptionsAssertion(testProps))));
- }
-
- /**
- * Check that a mandatory message is sent succesfully, not using transactions, when a consumer is disconnected but
- * the route exists.
- */
- public void test_QPID_517_MandatoryOkConsumerDisconnectedNoTxP2P() throws Exception
- {
- // Ensure transactional sessions are off.
- testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, false);
- testProps.setProperty(PUBSUB_PROPNAME, false);
-
- // Disconnect the consumer.
- testProps.setProperty(RECEIVER_CONSUMER_ACTIVE_PROPNAME, false);
-
- CircuitFactory circuitFactory = getCircuitFactory();
- Circuit testCircuit = circuitFactory.createCircuit(getConnection(), testProps);
-
- // Send one message with no errors.
- assertNoFailures(testCircuit.test(1,
- assertionList(((AMQPPublisher) testCircuit.getPublisher()).noExceptionsAssertion(testProps))));
- }
-
- /**
- * Check that a mandatory message is sent succesfully, in a transaction, when a consumer is disconnected but
- * the route exists.
- */
- public void test_QPID_517_MandatoryOkConsumerDisconnectedTxP2P() throws Exception
- {
- // Ensure transactional sessions are on.
- testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, true);
- testProps.setProperty(PUBSUB_PROPNAME, false);
-
- // Disconnect the consumer.
- testProps.setProperty(RECEIVER_CONSUMER_ACTIVE_PROPNAME, false);
-
- CircuitFactory circuitFactory = getCircuitFactory();
- Circuit testCircuit = circuitFactory.createCircuit(getConnection(), testProps);
-
- // Send one message with no errors.
- assertNoFailures(testCircuit.test(1,
- assertionList(((AMQPPublisher) testCircuit.getPublisher()).noExceptionsAssertion(testProps))));
- }
-
- /** Check that an mandatory message results in no route code, not using transactions, when no consumer is connected. */
- public void test_QPID_508_MandatoryFailsNoRouteNoTxP2P() throws Exception
- {
- // Ensure transactional sessions are off.
- testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, false);
- testProps.setProperty(PUBSUB_PROPNAME, false);
-
- // Set up the messaging topology so that only the publishers producer is bound (do not set up the receivers to
- // collect its messages).
- testProps.setProperty(RECEIVER_CONSUMER_BIND_PROPNAME, false);
-
- // Send one message and get a linked no route exception.
- CircuitFactory circuitFactory = getCircuitFactory();
- Circuit testCircuit = circuitFactory.createCircuit(getConnection(), testProps);
-
- assertNoFailures(testCircuit.test(1,
- assertionList(((AMQPPublisher) testCircuit.getPublisher()).noRouteAssertion(testProps))));
- }
-
- /** Check that an mandatory message results in no route code, upon transaction commit, when a consumer is connected. */
- public void test_QPID_508_MandatoryFailsNoRouteTxP2P() throws Exception
- {
- // Ensure transactional sessions are on.
- testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, true);
- testProps.setProperty(PUBSUB_PROPNAME, false);
-
- // Set up the messaging topology so that only the publishers producer is bound (do not set up the receivers to
- // collect its messages).
- testProps.setProperty(RECEIVER_CONSUMER_BIND_PROPNAME, false);
-
- // Send one message and get a linked no route exception.
- CircuitFactory circuitFactory = getCircuitFactory();
- Circuit testCircuit = circuitFactory.createCircuit(getConnection(), testProps);
-
- assertNoFailures(testCircuit.test(1,
- assertionList(((AMQPPublisher) testCircuit.getPublisher()).noRouteAssertion(testProps))));
- }
-
- /** Check that an mandatory message is sent succesfully not using transactions when a consumer is connected. */
- public void test_QPID_508_MandatoryOkNoTxPubSub() throws Exception
- {
- // Ensure transactional sessions are off.
- testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, false);
- testProps.setProperty(PUBSUB_PROPNAME, true);
-
- // Run the default test sequence over the test circuit checking for no errors.
- CircuitFactory circuitFactory = getCircuitFactory();
- Circuit testCircuit = circuitFactory.createCircuit(getConnection(), testProps);
-
- assertNoFailures(testCircuit.test(1,
- assertionList(((AMQPPublisher) testCircuit.getPublisher()).noExceptionsAssertion(testProps))));
- }
-
- /** Check that an mandatory message is committed succesfully in a transaction when a consumer is connected. */
- public void test_QPID_508_MandatoryOkTxPubSub() throws Exception
- {
- // Ensure transactional sessions are on.
- testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, true);
- testProps.setProperty(PUBSUB_PROPNAME, true);
-
- // Run the default test sequence over the test circuit checking for no errors.
- CircuitFactory circuitFactory = getCircuitFactory();
- Circuit testCircuit = circuitFactory.createCircuit(getConnection(), testProps);
-
- assertNoFailures(testCircuit.test(1,
- assertionList(((AMQPPublisher) testCircuit.getPublisher()).noExceptionsAssertion(testProps))));
- }
-
- /**
- * Check that a mandatory message is sent succesfully, not using transactions, when a consumer is disconnected but
- * the route exists.
- */
- public void test_QPID_517_MandatoryOkConsumerDisconnectedNoTxPubSub() throws Exception
- {
- // Ensure transactional sessions are off.
- testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, false);
- testProps.setProperty(PUBSUB_PROPNAME, true);
-
- // Use durable subscriptions, so that the route remains open with no subscribers.
- testProps.setProperty(DURABLE_SUBSCRIPTION_PROPNAME, true);
-
- // Disconnect the consumer.
- testProps.setProperty(RECEIVER_CONSUMER_ACTIVE_PROPNAME, false);
-
- CircuitFactory circuitFactory = getCircuitFactory();
- Circuit testCircuit = circuitFactory.createCircuit(getConnection(), testProps);
-
- // Send one message with no errors.
- assertNoFailures(testCircuit.test(1,
- assertionList(((AMQPPublisher) testCircuit.getPublisher()).noExceptionsAssertion(testProps))));
- }
-
- /**
- * Check that a mandatory message is sent succesfully, in a transaction, when a consumer is disconnected but
- * the route exists.
- */
- public void test_QPID_517_MandatoryOkConsumerDisconnectedTxPubSub() throws Exception
- {
- // Ensure transactional sessions are on.
- testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, true);
- testProps.setProperty(PUBSUB_PROPNAME, true);
-
- // Use durable subscriptions, so that the route remains open with no subscribers.
- testProps.setProperty(DURABLE_SUBSCRIPTION_PROPNAME, true);
-
- // Disconnect the consumer.
- testProps.setProperty(RECEIVER_CONSUMER_ACTIVE_PROPNAME, false);
-
- CircuitFactory circuitFactory = getCircuitFactory();
- Circuit testCircuit = circuitFactory.createCircuit(getConnection(), testProps);
-
- // Send one message with no errors.
- assertNoFailures(testCircuit.test(1,
- assertionList(((AMQPPublisher) testCircuit.getPublisher()).noExceptionsAssertion(testProps))));
- }
-
- /** Check that an mandatory message results in no route code, not using transactions, when no consumer is connected. */
- public void test_QPID_508_MandatoryFailsNoRouteNoTxPubSub() throws Exception
- {
- // Ensure transactional sessions are off.
- testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, false);
- testProps.setProperty(PUBSUB_PROPNAME, true);
-
- // Set up the messaging topology so that only the publishers producer is bound (do not set up the receivers to
- // collect its messages).
- testProps.setProperty(RECEIVER_CONSUMER_BIND_PROPNAME, false);
-
- // Send one message and get a linked no route exception.
- CircuitFactory circuitFactory = getCircuitFactory();
- Circuit testCircuit = circuitFactory.createCircuit(getConnection(), testProps);
-
- assertNoFailures(testCircuit.test(1,
- assertionList(((AMQPPublisher) testCircuit.getPublisher()).noRouteAssertion(testProps))));
- }
-
- /** Check that an mandatory message results in no route code, upon transaction commit, when a consumer is connected. */
- public void test_QPID_508_MandatoryFailsNoRouteTxPubSub() throws Exception
- {
- // Ensure transactional sessions are on.
- testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, true);
- testProps.setProperty(PUBSUB_PROPNAME, true);
-
- // Set up the messaging topology so that only the publishers producer is bound (do not set up the receivers to
- // collect its messages).
- testProps.setProperty(RECEIVER_CONSUMER_BIND_PROPNAME, false);
-
- // Send one message and get a linked no route exception.
- CircuitFactory circuitFactory = getCircuitFactory();
- Circuit testCircuit = circuitFactory.createCircuit(getConnection(), testProps);
-
- assertNoFailures(testCircuit.test(1,
- assertionList(((AMQPPublisher) testCircuit.getPublisher()).noRouteAssertion(testProps))));
- }
-
- protected void setUp() throws Exception
- {
- super.setUp();
-
- testProps = TestContextProperties.getInstance(MessagingTestConfigProperties.defaults);
-
- /** All these tests should have the mandatory flag on. */
- testProps.setProperty(IMMEDIATE_PROPNAME, false);
- testProps.setProperty(MANDATORY_PROPNAME, true);
-
- /** Bind the receivers consumer by default. */
- testProps.setProperty(RECEIVER_CONSUMER_BIND_PROPNAME, true);
- testProps.setProperty(RECEIVER_CONSUMER_ACTIVE_PROPNAME, true);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/testcases/RollbackTest.java b/java/systests/src/main/java/org/apache/qpid/test/testcases/RollbackTest.java
deleted file mode 100644
index edcde796a8..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/testcases/RollbackTest.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.test.testcases;
-
-import org.apache.qpid.test.framework.Circuit;
-import org.apache.qpid.test.framework.FrameworkBaseCase;
-import org.apache.qpid.test.framework.MessagingTestConfigProperties;
-import static org.apache.qpid.test.framework.MessagingTestConfigProperties.*;
-import org.apache.qpid.test.framework.sequencers.CircuitFactory;
-
-import org.apache.qpid.junit.extensions.util.ParsedProperties;
-import org.apache.qpid.junit.extensions.util.TestContextProperties;
-
-/**
- * RollbackTest tests the rollback ability of transactional messaging.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Check messages sent but rolled back are never received.
- * <tr><td> Check messages received but rolled back are redelivered on subsequent receives.
- * <tr><td> Attempting to rollback outside of a transaction results in an IllegalStateException.
- * </table>
- */
-public class RollbackTest extends FrameworkBaseCase
-{
- /** Used to read the tests configurable properties through. */
- private ParsedProperties testProps;
-
- /**
- * Creates a new test case with the specified name.
- *
- * @param name The test case name.
- */
- public RollbackTest(String name)
- {
- super(name);
- }
-
- /** Check messages sent but rolled back are never received. */
- public void testRolledbackMessageNotDelivered() throws Exception
- {
- // Ensure transactional sessions are on.
- testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, true);
- testProps.setProperty(ROLLBACK_PUBLISHER_PROPNAME, true);
-
- // Run the default test sequence over the test circuit checking for no errors.
- CircuitFactory circuitFactory = getCircuitFactory();
- Circuit testCircuit = circuitFactory.createCircuit(getConnection(), testProps);
-
- assertNoFailures(testCircuit.test(1,
- assertionList(testCircuit.getPublisher().noExceptionsAssertion(testProps),
- testCircuit.getReceiver().noMessagesReceivedAssertion(testProps))));
- }
-
- /** Check messages received but rolled back are redelivered on subsequent receives. */
- public void testRolledbackMessagesSubsequentlyReceived() throws Exception
- {
- // Ensure transactional sessions are on.
- testProps.setProperty(TRANSACTED_RECEIVER_PROPNAME, true);
- testProps.setProperty(ROLLBACK_RECEIVER_PROPNAME, true);
-
- // Run the default test sequence over the test circuit checking for no errors.
- CircuitFactory circuitFactory = getCircuitFactory();
- Circuit testCircuit = circuitFactory.createCircuit(getConnection(), testProps);
-
- assertNoFailures(testCircuit.test(1,
- assertionList(testCircuit.getPublisher().noExceptionsAssertion(testProps),
- testCircuit.getReceiver().allMessagesReceivedAssertion(testProps))));
- }
-
- /** Attempting to rollback outside of a transaction results in an IllegalStateException. */
- public void testRollbackUnavailableOutsideTransactionPublisher() throws Exception
- {
- // Ensure transactional sessions are on.
- testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, false);
- testProps.setProperty(ROLLBACK_PUBLISHER_PROPNAME, true);
-
- // Run the default test sequence over the test circuit checking for no errors.
- CircuitFactory circuitFactory = getCircuitFactory();
- Circuit testCircuit = circuitFactory.createCircuit(getConnection(), testProps);
-
- assertNoFailures(testCircuit.test(1, assertionList(testCircuit.getPublisher().channelClosedAssertion(testProps))));
- }
-
- /** Attempting to rollback outside of a transaction results in an IllegalStateException. */
- public void testRollbackUnavailableOutsideTransactionReceiver() throws Exception
- {
- // Ensure transactional sessions are on.
- testProps.setProperty(TRANSACTED_RECEIVER_PROPNAME, false);
- testProps.setProperty(ROLLBACK_RECEIVER_PROPNAME, true);
-
- // Run the default test sequence over the test circuit checking for no errors.
- CircuitFactory circuitFactory = getCircuitFactory();
- Circuit testCircuit = circuitFactory.createCircuit(getConnection(), testProps);
-
- assertNoFailures(testCircuit.test(1, assertionList(testCircuit.getReceiver().channelClosedAssertion(testProps))));
- }
-
- /**
- * Sets up all tests to have an active outward route and consumer by default.
- *
- * @throws Exception Any exceptions are allowed to fall through and fail the test.
- */
- protected void setUp() throws Exception
- {
- super.setUp();
-
- testProps = TestContextProperties.getInstance(MessagingTestConfigProperties.defaults);
-
- /** Bind the receivers consumer by default. */
- testProps.setProperty(RECEIVER_CONSUMER_BIND_PROPNAME, true);
- testProps.setProperty(RECEIVER_CONSUMER_ACTIVE_PROPNAME, true);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/testcases/TTLTest.java b/java/systests/src/main/java/org/apache/qpid/test/testcases/TTLTest.java
deleted file mode 100644
index d4bab657d7..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/testcases/TTLTest.java
+++ /dev/null
@@ -1,154 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.testcases;
-
-import org.apache.qpid.test.framework.Circuit;
-import org.apache.qpid.test.framework.FrameworkBaseCase;
-import static org.apache.qpid.test.framework.MessagingTestConfigProperties.ACK_MODE_PROPNAME;
-import static org.apache.qpid.test.framework.MessagingTestConfigProperties.PUBSUB_PROPNAME;
-import org.apache.qpid.test.framework.TestUtils;
-import org.apache.qpid.test.framework.localcircuit.LocalCircuitImpl;
-import org.apache.qpid.test.framework.sequencers.CircuitFactory;
-
-import javax.jms.*;
-
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Random;
-
-/**
- * TTLTest checks that time-to-live is applied to messages. The test sends messages with a variety of TTL stamps on them
- * then after a pause attempts to receive those messages. Only messages with a large enough TTL to have survived the pause
- * should be receiveable. This test case also applies an additional assertion against the broker, that the message store
- * is empty at the end of the test.
- *
- * <p/>This test is designed to run over local circuits only, as it must control a timed pause between sending and receiving
- * messages to that TTL can be applied to purge some of the messages.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td>
- * </table>
- *
- * @todo Use an interface or other method to mark this test as local only.
- *
- * @todo Implement the message store assertion for in-vm broker. Could also be done for external broker, for example
- * by using diagnostic exchange.
- *
- * @todo Implement and add a queue depth assertion too. This might already be in another test to copy from.
- *
- * @todo Create variations on test theme, for different ack mode and tx and message sizes etc.
- *
- * @todo Add an allowable margin of error to the test, as ttl may not be precise.
- */
-public class TTLTest extends FrameworkBaseCase
-{
- /**
- * Creates a new test case with the specified name.
- *
- * @param name The test case name.
- */
- public TTLTest(String name)
- {
- super(name);
- }
-
- /**
- * Checks that all messages sent with a TTL shorter than a pause between sending them and attempting to receive them
- * will fail to arrive. Once all messages have been purged by TTL or received, check that they no longer exist on
- * the broker.
- *
- * @throws javax.jms.JMSException Allowed to fall through and fail test.
- */
- public void testTTLP2P() throws Exception
- {
- String errorMessages = "";
- Random r = new Random();
-
- // Used to accumulate correctly received messages in.
- List<Message> receivedMessages = new LinkedList<Message>();
-
- // Set up the test properties to match the test case requirements.
- getTestProps().setProperty(ACK_MODE_PROPNAME, Session.AUTO_ACKNOWLEDGE);
- getTestProps().setProperty(PUBSUB_PROPNAME, false);
-
- // Create the test circuit from the test configuration parameters.
- CircuitFactory circuitFactory = getCircuitFactory();
- Circuit testCircuit = circuitFactory.createCircuit(getConnection(), getTestProps());
-
- // This test case assumes it is using a local circuit.
- LocalCircuitImpl localCircuit = (LocalCircuitImpl) testCircuit;
-
- Session producerSession = localCircuit.getLocalPublisherCircuitEnd().getSession();
- MessageProducer producer = localCircuit.getLocalPublisherCircuitEnd().getProducer();
- MessageConsumer consumer = localCircuit.getLocalReceiverCircuitEnd().getConsumer();
-
- // Send some tests messages, with random TTLs, some shorter and some longer than the pause time.
- for (int i = 0; i < 100; i++)
- {
- Message testMessage = TestUtils.createTestMessageOfSize(producerSession, 10);
-
- // Set the TTL on the message and record its value in the message headers.
- long ttl = 500 + r.nextInt(1500);
- producer.setTimeToLive(ttl);
- testMessage.setLongProperty("testTTL", ttl);
-
- producer.send(testMessage);
- // producerSession.commit();
- }
-
- // Inject a pause to allow some messages to be purged by TTL.
- TestUtils.pause(1000);
-
- // Attempt to receive back all of the messages, confirming by the message time stamps and TTLs that only
- // those received should have avoided being purged by the TTL.
- boolean timedOut = false;
-
-
- Message testMessage = null;
-
- do
- {
- testMessage = consumer.receive(1000);
-
- long ttl = testMessage.getLongProperty("testTTL");
- long timeStamp = testMessage.getJMSTimestamp();
- long now = System.currentTimeMillis();
-
- if ((timeStamp + ttl) < now)
- {
- errorMessages +=
- "Received message [sent: " + timeStamp + ", ttl: " + ttl + ", received: " + now
- + "] which should have been purged by its TTL.\n";
- }
- /*else
- {
- receivedMessages.add(testMessage);
- }*/
- } while (!timedOut && testMessage != null);
-
- // Check that the queue and message store on the broker are empty.
- // assertTrue("Message store is not empty.", messageStoreEmpty.apply());
- // assertTrue("Queue is not empty.", queueEmpty.apply());
-
- assertTrue(errorMessages, "".equals(errorMessages));
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/ack/Acknowledge2ConsumersTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/ack/Acknowledge2ConsumersTest.java
deleted file mode 100644
index 4b45a96c20..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/ack/Acknowledge2ConsumersTest.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.test.unit.ack;
-
-import org.apache.qpid.client.AMQDestination;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.test.utils.FailoverBaseCase;
-
-import javax.jms.Connection;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.Queue;
-import javax.jms.Session;
-
-public class Acknowledge2ConsumersTest extends FailoverBaseCase
-{
- protected static int NUM_MESSAGES = 100;
- protected Connection _con;
- protected Queue _queue;
- private Session _producerSession;
- private Session _consumerSession;
- private MessageConsumer _consumerA;
-
- @Override
- protected void setUp() throws Exception
- {
- super.setUp();
-
- _queue = (Queue) getInitialContext().lookup("queue");
-
- //Create Producer put some messages on the queue
- _con = getConnection();
- }
-
- private void init(boolean transacted, int mode) throws JMSException
- {
- _producerSession = _con.createSession(true, Session.SESSION_TRANSACTED);
- _consumerSession = _con.createSession(transacted, mode);
- _consumerA = _consumerSession.createConsumer(_queue);
- _con.start();
- }
-
- /**
- * Produces Messages that
- *
- * @param transacted
- * @param mode
- *
- * @throws Exception
- */
- private void test2ConsumersAcking(boolean transacted, int mode) throws Exception
- {
- init(transacted, mode);
-
- // These should all end up being prefetched by sessionA
- sendMessage(_producerSession, _queue, NUM_MESSAGES / 2);
-
- //Create a second consumer (consumerB) to consume some of the messages
- MessageConsumer consumerB = _consumerSession.createConsumer(_queue);
-
- // These messages should be roundrobined between A and B
- sendMessage(_producerSession, _queue, NUM_MESSAGES / 2);
-
- int count = 0;
- //Use consumerB to receive messages it has
- Message msg = consumerB.receive(1500);
- while (msg != null)
- {
- if (mode == Session.CLIENT_ACKNOWLEDGE)
- {
- msg.acknowledge();
- }
- count++;
- msg = consumerB.receive(1500);
- }
- if (transacted)
- {
- _consumerSession.commit();
- }
-
- // Close the consumers
- _consumerA.close();
- consumerB.close();
-
- // and close the session to release any prefetched messages.
- _consumerSession.close();
- assertEquals("Wrong number of messages on queue", NUM_MESSAGES - count,
- ((AMQSession) _producerSession).getQueueDepth((AMQDestination) _queue));
-
- // Clean up messages that may be left on the queue
- _consumerSession = _con.createSession(transacted, mode);
- _consumerA = _consumerSession.createConsumer(_queue);
- msg = _consumerA.receive(1500);
- while (msg != null)
- {
- if (mode == Session.CLIENT_ACKNOWLEDGE)
- {
- msg.acknowledge();
- }
- msg = _consumerA.receive(1500);
- }
- _consumerA.close();
- if (transacted)
- {
- _consumerSession.commit();
- }
- _consumerSession.close();
- }
-
- public void test2ConsumersAutoAck() throws Exception
- {
- test2ConsumersAcking(false, Session.AUTO_ACKNOWLEDGE);
- }
-
- public void test2ConsumersClientAck() throws Exception
- {
- test2ConsumersAcking(false, Session.CLIENT_ACKNOWLEDGE);
- }
-
- public void test2ConsumersTx() throws Exception
- {
- test2ConsumersAcking(true, Session.SESSION_TRANSACTED);
- }
-
-
-
-//
-// /**
-// * Check that session level acknowledge does correctly ack all previous
-// * values. Send 3 messages(0,1,2) then ack 1 and 2. If session ack is
-// * working correctly then acking 1 will also ack 0. Acking 2 will not
-// * attempt to re-ack 0 and 1.
-// *
-// * @throws Exception
-// */
-// public void testSessionAck() throws Exception
-// {
-// init(false, Session.CLIENT_ACKNOWLEDGE);
-//
-// sendMessage(_producerSession, _queue, 3);
-// Message msg;
-//
-// // Drop msg 0
-// _consumerA.receive(RECEIVE_TIMEOUT);
-//
-// // Take msg 1
-// msg = _consumerA.receive(RECEIVE_TIMEOUT);
-//
-// assertNotNull("Message 1 not correctly received.", msg);
-// assertEquals("Incorrect message received", 1, msg.getIntProperty(INDEX));
-//
-// // This should also ack msg 0
-// msg.acknowledge();
-//
-// // Take msg 2
-// msg = _consumerA.receive(RECEIVE_TIMEOUT);
-//
-// assertNotNull("Message 2 not correctly received.", msg);
-// assertEquals("Incorrect message received", 2, msg.getIntProperty(INDEX));
-//
-// // This should just ack msg 2
-// msg.acknowledge();
-//
-// _consumerA.close();
-// _consumerSession.close();
-//
-// assertEquals("Queue not empty.", 0,
-// ((AMQSession) _producerSession).getQueueDepth((AMQDestination) _queue));
-// _con.close();
-//
-//
-// }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/ack/AcknowledgeAfterFailoverOnMessageTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/ack/AcknowledgeAfterFailoverOnMessageTest.java
deleted file mode 100644
index d73d012250..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/ack/AcknowledgeAfterFailoverOnMessageTest.java
+++ /dev/null
@@ -1,429 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.ack;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQDestination;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.jms.ConnectionListener;
-import org.apache.qpid.util.FileUtils;
-
-import javax.jms.Connection;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageListener;
-import javax.jms.Session;
-import javax.jms.TransactionRolledBackException;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-import java.io.File;
-
-/**
- * The AcknowlegeAfterFailoverOnMessageTests
- *
- * Extends the OnMessage AcknowledgeTests to validate that after the client has
- * failed over that the client can still receive and ack messages.
- *
- * All the AcknowledgeTest ack modes are exercised here though some are disabled
- * due to know issues (e.g. DupsOk, AutoAck : QPID-143 and the clientAck
- * and dirtyClientAck due to QPID-1816)
- *
- * This class has two main test structures, overrides of AcknowledgeOnMessageTest
- * to perform the clean acking based on session ack mode and a series of dirty
- * ack tests that test what happends if you receive a message then try and ack
- * AFTER you have failed over.
- *
- *
- */
-public class AcknowledgeAfterFailoverOnMessageTest extends AcknowledgeOnMessageTest implements ConnectionListener
-{
-
- protected CountDownLatch _failoverCompleted = new CountDownLatch(1);
- private MessageListener _listener = null;
-
- @Override
- public void setUp() throws Exception
- {
- super.setUp();
- NUM_MESSAGES = 10;
- }
-
- /**
- * Override default init to add connectionListener so we can verify that
- * failover took place
- *
- * @param transacted create a transacted session for this test
- * @param mode if not transacted what ack mode to use for this test
- *
- * @throws Exception if a problem occured during test setup.
- */
- @Override
- public void init(boolean transacted, int mode) throws Exception
- {
- super.init(transacted, mode);
- ((AMQConnection) _connection).setConnectionListener(this);
- // Override the listener for the dirtyAck testing.
- if (_listener != null)
- {
- _consumer.setMessageListener(_listener);
- }
- }
-
- /**
- * Prepare the broker for the next round.
- *
- * Called after acknowledging the messsage this method shuts the current
- * broker down connnects to the new broker and send a new message for the
- * client to failover to and receive.
- *
- * It ends by restarting the orignal broker so that the cycle can repeat.
- *
- * When we are able to cluster the java broker then will not need to do the
- * message repopulation or QPID_WORK clearing. All that we will need to do
- * is send the initial NUM_MESSAGES during startup and then bring the
- * brokers down at the right time to cause the client to fail between them.
- *
- * @param index
- * @throws Exception
- */
- protected void prepBroker(int index) throws Exception
- {
- // Alternate killing the broker based on the message index we are at.
-
- if (index % 2 == 0)
- {
- failBroker(getFailingPort());
- // Clean up the failed broker
- FileUtils.delete(new File(System.getProperty("QPID_WORK") + "/" + getFailingPort()), true);
- }
- else
- {
- failBroker(getPort());
- // Clean up the failed broker
- FileUtils.delete(new File(System.getProperty("QPID_WORK") + "/" + getPort()), true);
- }
-
- _failoverCompleted = new CountDownLatch(1);
-
- _logger.info("AAFOMT: prepNewBroker for message send");
- Connection connection = getConnection();
-
- try
- {
-
- //Stop the connection whilst we repopulate the broker, or the no_ack
- // test will drain the msgs before we can check we put the right number
- // back on again.
-
- Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
- // ensure destination is created.
- session.createConsumer(_queue).close();
-
-
- // If this is the last message then we can skip the send.
- // But we MUST ensure that we have created the queue with the
- // above createConsumer(_queue).close() as the test will end by
- // testing the queue depth which will fail if we don't ensure we
- // declare the queue.
- // index is 0 based so we need to check +1 against NUM_MESSAGES
- if ((index + 1) == NUM_MESSAGES)
- {
- return;
- }
-
-
- sendMessage(session, _queue, 1, index + 1, 0);
-
- // Validate that we have the message on the queue
- // In NoAck mode though the messasge may already have been sent to
- // the client so we have to skip the vaildation.
- if (_consumerSession.getAcknowledgeMode() != AMQSession.NO_ACKNOWLEDGE)
- {
- assertEquals("Wrong number of messages on queue", 1,
- ((AMQSession) session).getQueueDepth((AMQDestination) _queue));
- }
-
-
- }
- catch (Exception e)
- {
- fail("Unable to prep new broker," + e.getMessage());
- }
- finally
- {
- connection.close();
- }
-
- try
- {
-
- //Restart the broker
- if (index % 2 == 0)
- {
- startBroker(getFailingPort());
- }
- else
- {
- startBroker(getPort());
- }
- }
- catch (Exception e)
- {
- fail("Unable to start failover broker," + e.getMessage());
- }
-
- }
-
- @Override
- public void doAcknowlegement(Message msg) throws JMSException
- {
- //Acknowledge current message
- super.doAcknowlegement(msg);
-
- try
- {
- prepBroker(msg.getIntProperty(INDEX));
- }
- catch (Exception e)
- {
- // Provide details of what went wrong with the stack trace
- e.printStackTrace();
- fail("Unable to prep new broker," + e);
- }
- }
-
- // Instance varilable for DirtyAcking test
- int _msgCount = 0;
- boolean _cleaned = false;
-
- class DirtyAckingHandler implements MessageListener
- {
- /**
- * Validate first message but do nothing with it.
- *
- * Failover
- *
- * The receive the message again
- *
- * @param message
- */
- public void onMessage(Message message)
- {
- // Stop processing if we have an error and had to stop running.
- if (_receivedAll.getCount() == 0)
- {
- _logger.debug("Dumping msgs due to error(" + _causeOfFailure.get().getMessage() + "):" + message);
- return;
- }
-
- try
- {
- // Check we have the next message as expected
- assertNotNull("Message " + _msgCount + " not correctly received.", message);
- assertEquals("Incorrect message received", _msgCount, message.getIntProperty(INDEX));
-
- if (_msgCount == 0 && _failoverCompleted.getCount() != 0)
- {
- // This is the first message we've received so lets fail the broker
-
- failBroker(getFailingPort());
-
- repopulateBroker();
-
- _logger.error("Received first msg so failing over");
-
- return;
- }
-
- _msgCount++;
-
- // Don't acknowlege the first message after failover so we can commit
- // them together
- if (_msgCount == 1)
- {
- _logger.error("Received first msg after failover ignoring:" + _msgCount);
-
- // Acknowledge the first message if we are now on the cleaned pass
- if (_cleaned)
- {
- _receivedAll.countDown();
- }
-
- return;
- }
-
- if (_consumerSession.getTransacted())
- {
- try
- {
- _consumerSession.commit();
- if (!_cleaned)
- {
- fail("Session is dirty we should get an TransactionRolledBackException");
- }
- }
- catch (TransactionRolledBackException trbe)
- {
- //expected path
- }
- }
- else
- {
- try
- {
- message.acknowledge();
- if (!_cleaned)
- {
- fail("Session is dirty we should get an IllegalStateException");
- }
- }
- catch (javax.jms.IllegalStateException ise)
- {
- assertEquals("Incorrect Exception thrown", "has failed over", ise.getMessage());
- // Recover the sesion and try again.
- _consumerSession.recover();
- }
- }
-
- // Acknowledge the last message if we are in a clean state
- // this will then trigger test teardown.
- if (_cleaned)
- {
- _receivedAll.countDown();
- }
-
- //Reset message count so we can try again.
- _msgCount = 0;
- _cleaned = true;
- }
- catch (Exception e)
- {
- // If something goes wrong stop and notifiy main thread.
- fail(e);
- }
- }
- }
-
- /**
- * Test that Acking/Committing a message received before failover causes
- * an exception at commit/ack time.
- *
- * Expected behaviour is that in:
- * * tx mode commit() throws a transacted RolledBackException
- * * client ack mode throws an IllegalStateException
- *
- * @param transacted is this session trasacted
- * @param mode What ack mode should be used if not trasacted
- *
- * @throws Exception if something goes wrong.
- */
- protected void testDirtyAcking(boolean transacted, int mode) throws Exception
- {
- NUM_MESSAGES = 2;
- _listener = new DirtyAckingHandler();
-
- super.testAcking(transacted, mode);
- }
-
- public void testDirtyClientAck() throws Exception
- {
- testDirtyAcking(false, Session.CLIENT_ACKNOWLEDGE);
- }
-
- public void testDirtyAckingTransacted() throws Exception
- {
- testDirtyAcking(true, Session.SESSION_TRANSACTED);
- }
-
- private void repopulateBroker() throws Exception
- {
- // Repopulate this new broker so we can test what happends after failover
-
- //Get the connection to the first (main port) broker.
- Connection connection = getConnection();
- // Use a transaction to send messages so we can be sure they arrive.
- Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
- // ensure destination is created.
- session.createConsumer(_queue).close();
-
- sendMessage(session, _queue, NUM_MESSAGES);
-
- assertEquals("Wrong number of messages on queue", NUM_MESSAGES,
- ((AMQSession) session).getQueueDepth((AMQDestination) _queue));
-
- connection.close();
- }
-
- // AMQConnectionListener Interface.. used so we can validate that we
- // actually failed over.
-
- public void bytesSent(long count)
- {
- }
-
- public void bytesReceived(long count)
- {
- }
-
- public boolean preFailover(boolean redirect)
- {
- //Allow failover
- return true;
- }
-
- public boolean preResubscribe()
- {
- //Allow failover
- return true;
- }
-
- public void failoverComplete()
- {
- _failoverCompleted.countDown();
- }
-
- /**
- * Override so we can block until failover has completd
- *
- * @param port
- */
- @Override
- public void failBroker(int port)
- {
- super.failBroker(port);
-
- try
- {
- if (!_failoverCompleted.await(DEFAULT_FAILOVER_TIME, TimeUnit.MILLISECONDS))
- {
- // Use an exception so that we use our local fail() that notifies the main thread of failure
- throw new Exception("Failover did not occur in specified time:" + DEFAULT_FAILOVER_TIME);
- }
-
- }
- catch (Exception e)
- {
- // Use an exception so that we use our local fail() that notifies the main thread of failure
- fail(e);
- }
- }
-
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/ack/AcknowledgeAfterFailoverTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/ack/AcknowledgeAfterFailoverTest.java
deleted file mode 100644
index acc7d5a4c1..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/ack/AcknowledgeAfterFailoverTest.java
+++ /dev/null
@@ -1,317 +0,0 @@
-/*
-*
-* Licensed to the Apache Software Foundation (ASF) under one
-* or more contributor license agreements. See the NOTICE file
-* distributed with this work for additional information
-* regarding copyright ownership. The ASF licenses this file
-* to you under the Apache License, Version 2.0 (the
-* "License"); you may not use this file except in compliance
-* with the License. You may obtain a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing,
-* software distributed under the License is distributed on an
-* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-* KIND, either express or implied. See the License for the
-* specific language governing permissions and limitations
-* under the License.
-*
-*/
-package org.apache.qpid.test.unit.ack;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQDestination;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.jms.ConnectionListener;
-import org.apache.qpid.util.FileUtils;
-
-import javax.jms.Connection;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.Session;
-import javax.jms.TransactionRolledBackException;
-import java.io.File;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-/**
- *
- */
-public class AcknowledgeAfterFailoverTest extends AcknowledgeTest implements ConnectionListener
-{
-
- protected CountDownLatch _failoverCompleted = new CountDownLatch(1);
-
- @Override
- public void setUp() throws Exception
- {
- super.setUp();
- // This must be even for the test to run correctly.
- // Otherwise we will kill the standby broker
- // not the one we are connected to.
- // The test will still pass but it will not be exactly
- // as described.
- NUM_MESSAGES = 6;
- }
-
- /**
- * Override default init to add connectionListener so we can verify that
- * failover took place
- *
- * @param transacted create a transacted session for this test
- * @param mode if not transacted what ack mode to use for this test
- * @throws Exception if a problem occured during test setup.
- */
- @Override
- protected void init(boolean transacted, int mode) throws Exception
- {
- super.init(transacted, mode);
- ((AMQConnection) _connection).setConnectionListener(this);
- }
-
- protected void prepBroker(int index) throws Exception
- {
- // If this is the last message then we can skip the prep.
- if (index == NUM_MESSAGES)
- {
- return;
- }
-
- if (index % 2 == 0)
- {
- failBroker(getFailingPort());
- // Clean up the failed broker
- FileUtils.delete(new File(System.getProperty("QPID_WORK") + "/" + getFailingPort()), true);
- }
- else
- {
- failBroker(getPort());
- // Clean up the failed broker
- FileUtils.delete(new File(System.getProperty("QPID_WORK") + "/" + getPort()), true);
- }
-
- // Ensure we have the right data on the broker
- Connection connection = getConnection();
- Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
- // ensure destination is created.
- session.createConsumer(_queue).close();
-
- sendMessage(session, _queue, 1, index + 1, 0);
-
- if (_consumerSession.getAcknowledgeMode() != AMQSession.NO_ACKNOWLEDGE)
- {
- assertEquals("Wrong number of messages on queue", 1,
- ((AMQSession) session).getQueueDepth((AMQDestination) _queue));
- }
-
- connection.close();
-
- try
- {
- if (index % 2 == 0)
- {
- startBroker(getFailingPort());
- }
- else
- {
- startBroker(getPort());
- }
- }
- catch (Exception e)
- {
- fail("Unable to start failover broker," + e.getMessage());
- }
- }
-
- @Override
- public void doAcknowlegement(Message msg) throws JMSException
- {
- //Acknowledge current message
- super.doAcknowlegement(msg);
-
- try
- {
- prepBroker(msg.getIntProperty(INDEX));
- }
- catch (Exception e)
- {
- fail("Unable to prep new broker," + e.getMessage());
- }
-
- }
-
- /**
- * Test that Acking/Committing a message received before failover causes
- * an exception at commit/ack time.
- * <p/>
- * Expected behaviour is that in:
- * * tx mode commit() throws a transacted RolledBackException
- * * client ack mode throws an IllegalStateException
- *
- * @param transacted is this session trasacted
- * @param mode What ack mode should be used if not trasacted
- * @throws Exception if something goes wrong.
- */
- protected void testDirtyAcking(boolean transacted, int mode) throws Exception
- {
- NUM_MESSAGES = 2;
- //Test Dirty Failover Fails
- init(transacted, mode);
-
- _connection.start();
-
- Message msg = _consumer.receive(1500);
-
- int count = 0;
- assertNotNull("Message " + count + " not correctly received.", msg);
- assertEquals("Incorrect message received", count, msg.getIntProperty(INDEX));
-
- //Don't acknowledge just prep the next broker. Without changing count
- // Prep the new broker to have all all the messages so we can validate
- // that they can all be correctly received.
- try
- {
-
- //Stop the connection so we can validate the number of message count
- // on the queue is correct after failover
- _connection.stop();
- failBroker(getFailingPort());
-
- //Get the connection to the first (main port) broker.
- Connection connection = getConnection();//getConnectionFactory("connection1").getConnectionURL());
- // Use a transaction to send messages so we can be sure they arrive.
- Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
- // ensure destination is created.
- session.createConsumer(_queue).close();
-
- sendMessage(session, _queue, NUM_MESSAGES);
-
- assertEquals("Wrong number of messages on queue", NUM_MESSAGES,
- ((AMQSession) session).getQueueDepth((AMQDestination) _queue));
-
- connection.close();
-
- //restart connection
- _connection.start();
- }
- catch (Exception e)
- {
- fail("Unable to prep new broker," + e.getMessage());
- }
-
- // Consume the next message - don't check what it is as a normal would
- // assume it is msg 1 but as we've fallen over it is msg 0 again.
- msg = _consumer.receive(1500);
-
- if (_consumerSession.getTransacted())
- {
- try
- {
- _consumerSession.commit();
- fail("Session is dirty we should get an TransactionRolledBackException");
- }
- catch (TransactionRolledBackException trbe)
- {
- //expected path
- }
- }
- else
- {
- try
- {
- msg.acknowledge();
- fail("Session is dirty we should get an IllegalStateException");
- }
- catch (javax.jms.IllegalStateException ise)
- {
- assertEquals("Incorrect Exception thrown", "has failed over", ise.getMessage());
- // Recover the sesion and try again.
- _consumerSession.recover();
- }
- }
-
- msg = _consumer.receive(1500);
- // Validate we now get the first message back
- assertEquals(0, msg.getIntProperty(INDEX));
-
- msg = _consumer.receive(1500);
- // and the second message
- assertEquals(1, msg.getIntProperty(INDEX));
-
- // And now verify that we can now commit the clean session
- if (_consumerSession.getTransacted())
- {
- _consumerSession.commit();
- }
- else
- {
- msg.acknowledge();
- }
-
- assertEquals("Wrong number of messages on queue", 0,
- ((AMQSession) _consumerSession).getQueueDepth((AMQDestination) _queue));
- }
-
- public void testDirtyClientAck() throws Exception
- {
- testDirtyAcking(false, Session.CLIENT_ACKNOWLEDGE);
- }
-
- public void testDirtyAckingTransacted() throws Exception
- {
- testDirtyAcking(true, Session.SESSION_TRANSACTED);
- }
-
- // AMQConnectionListener Interface.. used so we can validate that we
- // actually failed over.
-
- public void bytesSent(long count)
- {
- }
-
- public void bytesReceived(long count)
- {
- }
-
- public boolean preFailover(boolean redirect)
- {
- //Allow failover
- return true;
- }
-
- public boolean preResubscribe()
- {
- //Allow failover
- return true;
- }
-
- public void failoverComplete()
- {
- _failoverCompleted.countDown();
- }
-
- /**
- * Override so we can block until failover has completd
- *
- * @param port
- */
- @Override
- public void failBroker(int port)
- {
- super.failBroker(port);
-
- try
- {
- if (!_failoverCompleted.await(DEFAULT_FAILOVER_TIME, TimeUnit.MILLISECONDS))
- {
- fail("Failover did not occur in specified time:" + DEFAULT_FAILOVER_TIME);
- }
- }
- catch (InterruptedException e)
- {
- fail("Failover was interrupted");
- }
- }
-
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/ack/AcknowledgeOnMessageTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/ack/AcknowledgeOnMessageTest.java
deleted file mode 100644
index 1b4407f255..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/ack/AcknowledgeOnMessageTest.java
+++ /dev/null
@@ -1,226 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.ack;
-
-import org.apache.qpid.client.AMQDestination;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.client.JMSAMQException;
-import org.apache.qpid.client.failover.FailoverException;
-
-import javax.jms.Message;
-import javax.jms.MessageListener;
-import javax.jms.Session;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicReference;
-
-/**
- * This test extends the synchronous AcknowledgeTest to use a MessageListener
- * and receive messages asynchronously.
- */
-public class AcknowledgeOnMessageTest extends AcknowledgeTest implements MessageListener
-{
- protected CountDownLatch _receivedAll;
- protected AtomicReference<Exception> _causeOfFailure = new AtomicReference<Exception>(null);
-
- @Override
- public void setUp() throws Exception
- {
- super.setUp();
- }
-
- /**
- * Override the synchronous AcknowledgeTest init to provide the _receivedAll
- * CountDownLatch init and ensure that we set the MessageListener.
- * @param transacted
- * @param mode
- * @throws Exception
- */
- @Override
- public void init(boolean transacted, int mode) throws Exception
- {
- _receivedAll = new CountDownLatch(NUM_MESSAGES);
-
- super.init(transacted, mode);
- _consumer.setMessageListener(this);
- }
-
- /**
- * This test overrides the testAcking from the simple recieve() model to all
- * for asynchronous receiving of messages.
- *
- * Again the transaction/ack mode is provided to this main test run
- *
- * The init method is called which will setup the listener so that we can
- * then sit and await using the _receivedAll CountDownLatch. We wait for up
- * to 10s if no messages have been received in the last 10s then test will
- * fail.
- *
- * If the test fails then it will attempt to retrieve any exception that the
- * asynchronous delivery thread may have recorded.
- *
- * @param transacted
- * @param mode
- *
- * @throws Exception
- */
- @Override
- protected void testAcking(boolean transacted, int mode) throws Exception
- {
- init(transacted, mode);
-
- _connection.start();
-
- // Set the lastCount to NUM_MESSAGES, this ensures that the compare
- // against the receviedAll count is accurate.
- int lastCount = NUM_MESSAGES;
-
- // Wait for messages to arrive
- boolean complete = _receivedAll.await(10000L, TimeUnit.MILLISECONDS);
-
- // If the messasges haven't arrived
- while (!complete)
- {
- // Check how many we have received
- int currentCount = (int) _receivedAll.getCount();
-
- // make sure we have received a message in the last cycle.
- if (lastCount == currentCount)
- {
- // If we didn't receive any messages then stop.
- // Something must have gone wrong.
- System.err.println("Giving up waiting as we didn't receive anything.");
- break;
- }
- // Remember the currentCount as the lastCount for the next cycle.
- // so we can exit if things get locked up.
- lastCount = currentCount;
-
- // Wait again for messages to arrive.
- complete = _receivedAll.await(10000L, TimeUnit.MILLISECONDS);
- }
-
- // If we failed to receive all the messages then fail the test.
- if (!complete)
- {
- // Check to see if we ended due to an exception in the onMessage handler
- Exception cause = _causeOfFailure.get();
- if (cause != null)
- {
- cause.printStackTrace();
- fail(cause.getMessage());
- }
- else
- {
- _logger.info("AOMT: Check QueueDepth:" + _queue);
- long onQueue=((AMQSession) getConnection().createSession(false, Session.AUTO_ACKNOWLEDGE)).getQueueDepth((AMQDestination) _queue);
- fail("All messages not received missing:" + _receivedAll.getCount() + "/" + NUM_MESSAGES+" On Queue:"+onQueue);
-
- }
- }
-
- // Even if we received all the messages.
- // Check to see if we ended due to an exception in the onMessage handler
- Exception cause = _causeOfFailure.get();
- if (cause != null)
- {
- cause.printStackTrace();
- fail(cause.getMessage());
- }
-
- try
- {
- _consumer.close();
- }
- catch (JMSAMQException amqe)
- {
- if (amqe.getLinkedException() instanceof FailoverException)
- {
- fail("QPID-143 : Auto Ack can acknowledge message from previous session after failver. If failover occurs between deliver and ack.");
- }
- // else Rethrow for TestCase to catch.
- throw amqe;
- }
-
- _consumerSession.close();
-
- _logger.info("AOMT: check number of message at end of test.");
- assertEquals("Wrong number of messages on queue", 0,
- ((AMQSession) getConnection().createSession(false, Session.AUTO_ACKNOWLEDGE)).getQueueDepth((AMQDestination) _queue));
- }
-
- /**
- * The MessageListener interface that recieves the message and counts down
- * the _receivedAll CountDownLatch.
- *
- * Again like AcknowledgeTest acknowledgement is actually handled in
- * doAcknowlegement.
- *
- * The message INDEX is validated to ensure the correct message order is
- * preserved.
- *
- * @param message
- */
- public void onMessage(Message message)
- {
- // Log received Message for debugging
- _logger.info("RECEIVED MESSAGE:" + message);
-
- try
- {
- int count = NUM_MESSAGES - (int) _receivedAll.getCount();
-
- assertEquals("Incorrect message received", count, message.getIntProperty(INDEX));
-
- count++;
- if (count < NUM_MESSAGES)
- {
- //Send the next message
- _producer.send(createNextMessage(_consumerSession, count));
- }
-
- doAcknowlegement(message);
-
- _receivedAll.countDown();
- }
- catch (Exception e)
- {
- // This will end the test run by counting down _receivedAll
- fail(e);
- }
- }
-
- /**
- * Pass the given exception back to the waiting thread to fail the test run.
- *
- * @param e The exception that is causing the test to fail.
- */
- protected void fail(Exception e)
- {
- //record the failure
- _causeOfFailure.set(e);
- // End the test.
- while (_receivedAll.getCount() != 0)
- {
- _receivedAll.countDown();
- }
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/ack/AcknowledgeTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/ack/AcknowledgeTest.java
deleted file mode 100644
index efea57e5d2..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/ack/AcknowledgeTest.java
+++ /dev/null
@@ -1,179 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.qpid.test.unit.ack;
-
-import org.apache.qpid.client.AMQDestination;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.test.utils.FailoverBaseCase;
-
-import javax.jms.Connection;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.Queue;
-import javax.jms.Session;
-import javax.jms.MessageProducer;
-
-/**
- * Test the various JMS Acknowledge Modes the single testAcking method does all
- * the work of receiving and validation of acking.
- *
- * The ack mode is provided from the various test methods.
- */
-public class AcknowledgeTest extends FailoverBaseCase
-{
- protected int NUM_MESSAGES;
- protected Connection _connection;
- protected Queue _queue;
- protected Session _consumerSession;
- protected MessageConsumer _consumer;
- protected MessageProducer _producer;
-
- @Override
- protected void setUp() throws Exception
- {
- super.setUp();
- NUM_MESSAGES = 5;
-
- _queue = getTestQueue();
-
- _logger.info("AT: setup");
- //Create Producer put some messages on the queue
- _connection = getConnection();
- }
-
- protected void init(boolean transacted, int mode) throws Exception
- {
- _consumerSession = _connection.createSession(transacted, mode);
- _consumer = _consumerSession.createConsumer(_queue);
- _producer = _consumerSession.createProducer(_queue);
-
- // These should all end up being prefetched by session
- sendMessage(_consumerSession, _queue, 1);
-
- assertEquals("Wrong number of messages on queue", 1,
- ((AMQSession) _consumerSession).getQueueDepth((AMQDestination) _queue));
- }
-
- /**
- * The main test method.
- *
- * Receive the initial message and then proceed to send and ack messages
- * until we have processed NUM_MESSAGES worth of messages.
- *
- * Each message is tagged with an INDEX value and these are used to check
- * that the messages are received in the correct order.
- *
- * The test concludes by validating that the queue depth is 0 as expected.
- *
- * @param transacted
- * @param mode
- *
- * @throws Exception
- */
- protected void testAcking(boolean transacted, int mode) throws Exception
- {
- init(transacted, mode);
-
- _connection.start();
-
- Message msg = _consumer.receive(1500);
-
- int count = 0;
- while (count < NUM_MESSAGES)
- {
- assertNotNull("Message " + count + " not correctly received.", msg);
- assertEquals("Incorrect message received", count, msg.getIntProperty(INDEX));
- count++;
-
- if (count < NUM_MESSAGES)
- {
- //Send the next message
- _producer.send(createNextMessage(_consumerSession, count));
- }
-
- doAcknowlegement(msg);
-
- msg = _consumer.receive(1500);
- }
-
- if (_consumerSession.getTransacted())
- {
- //Acknowledge the last msg if we are testing transacted otherwise queueDepth will be 1
- doAcknowlegement(msg);
- }
-
- assertEquals("Wrong number of messages on queue", 0,
- ((AMQSession) _consumerSession).getQueueDepth((AMQDestination) _queue));
- }
-
- /**
- * Perform the acknowledgement of messages if additionally required.
- *
- * @param msg
- *
- * @throws JMSException
- */
- protected void doAcknowlegement(Message msg) throws JMSException
- {
- if (_consumerSession.getTransacted())
- {
- _consumerSession.commit();
- }
-
- if (_consumerSession.getAcknowledgeMode() == Session.CLIENT_ACKNOWLEDGE)
- {
- msg.acknowledge();
- }
- }
-
- public void testClientAck() throws Exception
- {
- testAcking(false, Session.CLIENT_ACKNOWLEDGE);
- }
-
- public void testAutoAck() throws Exception
- {
- testAcking(false, Session.AUTO_ACKNOWLEDGE);
- }
-
- public void testTransacted() throws Exception
- {
- testAcking(true, Session.SESSION_TRANSACTED);
- }
-
- public void testDupsOk() throws Exception
- {
- testAcking(false, Session.DUPS_OK_ACKNOWLEDGE);
- }
-
- public void testNoAck() throws Exception
- {
- testAcking(false, AMQSession.NO_ACKNOWLEDGE);
- }
-
- public void testPreAck() throws Exception
- {
- testAcking(false, AMQSession.PRE_ACKNOWLEDGE);
- }
-
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/ack/FailoverBeforeConsumingRecoverTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/ack/FailoverBeforeConsumingRecoverTest.java
deleted file mode 100644
index 834b17430b..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/ack/FailoverBeforeConsumingRecoverTest.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.test.unit.ack;
-
-import org.apache.qpid.jms.Session;
-
-import javax.jms.Message;
-import javax.jms.Queue;
-
-public class FailoverBeforeConsumingRecoverTest extends RecoverTest
-{
-
- @Override
- protected void initTest() throws Exception
- {
- super.initTest();
- failBroker(getFailingPort());
-
- Queue queue = _consumerSession.createQueue(getTestQueueName());
- sendMessage(_connection.createSession(false, Session.AUTO_ACKNOWLEDGE), queue, SENT_COUNT);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/ack/QuickAcking.java b/java/systests/src/main/java/org/apache/qpid/test/unit/ack/QuickAcking.java
deleted file mode 100644
index 6c83136511..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/ack/QuickAcking.java
+++ /dev/null
@@ -1,148 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.ack;
-
-import edu.emory.mathcs.backport.java.util.concurrent.CountDownLatch;
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.jms.ConnectionListener;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-import javax.jms.Queue;
-import javax.jms.Session;
-
-/**
- * This is a quick manual test to validate acking after failover with a
- * transacted session.
- *
- * Start an external broker then run this test. Std Err will print.
- * Sent Message: 1
- * Received Message: 1
- *
- * You can then restart the external broker, which will cause failover, which
- * will be complete when the following appears.
- *
- * Failover Complete
- *
- * A second message send/receive cycle is then done to validate that the
- * connection/session are still working.
- *
- */
-public class QuickAcking extends QpidBrokerTestCase implements ConnectionListener
-{
- protected AMQConnection _connection;
- protected Queue _queue;
- protected Session _session;
- protected MessageConsumer _consumer;
- private CountDownLatch _failedOver;
- private static final String INDEX = "INDEX";
- private int _count = 0;
-
- public void setUp()
- {
- // Prevent broker startup. Broker must be run manually.
- }
-
- public void test() throws Exception
- {
- _failedOver = new CountDownLatch(1);
-
- _connection = new AMQConnection("amqp://guest:guest@client/test?brokerlist='localhost?retries='20'&connectdelay='2000''");
-
- _session = _connection.createSession(true, Session.SESSION_TRANSACTED);
- _queue = _session.createQueue("QAtest");
- _consumer = _session.createConsumer(_queue);
- _connection.setConnectionListener(this);
- _connection.start();
-
- sendAndReceive();
-
- _failedOver.await();
-
- sendAndReceive();
-
- }
-
- private void sendAndReceive()
- throws Exception
- {
- sendMessage();
-
- Message message = _consumer.receive();
-
- if (message.getIntProperty(INDEX) != _count)
- {
- throw new Exception("Incorrect message recieved:" + _count);
- }
-
- if (_session.getTransacted())
- {
- _session.commit();
- }
- System.err.println("Recevied Message:" + _count);
- }
-
- private void sendMessage() throws JMSException
- {
- MessageProducer producer = _session.createProducer(_queue);
- Message message = _session.createMessage();
- _count++;
- message.setIntProperty(INDEX, _count);
-
- producer.send(message);
- if (_session.getTransacted())
- {
- _session.commit();
- }
- producer.close();
-
- System.err.println("Sent Message:" + _count);
- }
-
- public void bytesSent(long count)
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void bytesReceived(long count)
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- public boolean preFailover(boolean redirect)
- {
- return true;
- }
-
- public boolean preResubscribe()
- {
- return true;
- }
-
- public void failoverComplete()
- {
- System.err.println("Failover Complete");
- _failedOver.countDown();
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/ack/RecoverTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/ack/RecoverTest.java
deleted file mode 100644
index 5e7ba5482d..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/ack/RecoverTest.java
+++ /dev/null
@@ -1,450 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.ack;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.jms.Session;
-import org.apache.qpid.test.utils.FailoverBaseCase;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.jms.BytesMessage;
-import javax.jms.Connection;
-import javax.jms.Destination;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageListener;
-import javax.jms.MessageProducer;
-import javax.jms.Queue;
-import javax.jms.TextMessage;
-
-import java.util.HashMap;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicInteger;
-
-public class RecoverTest extends FailoverBaseCase
-{
- static final Logger _logger = LoggerFactory.getLogger(RecoverTest.class);
-
- private Exception _error;
- private AtomicInteger count;
-
- protected AMQConnection _connection;
- protected Session _consumerSession;
- protected MessageConsumer _consumer;
- static final int SENT_COUNT = 4;
-
- @Override
- protected void setUp() throws Exception
- {
- super.setUp();
- _error = null;
- count = new AtomicInteger();
- }
-
- protected void initTest() throws Exception
- {
- _connection = (AMQConnection) getConnection("guest", "guest");
-
- _consumerSession = _connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
- Queue queue = _consumerSession.createQueue(getTestQueueName());
-
- _consumer = _consumerSession.createConsumer(queue);
-
- _logger.info("Sending four messages");
- sendMessage(_connection.createSession(false, Session.AUTO_ACKNOWLEDGE), queue, SENT_COUNT);
- _logger.info("Starting connection");
- _connection.start();
- }
-
- protected Message validateNextMessages(int nextCount, int startIndex) throws JMSException
- {
- Message message = null;
- for (int index = 0; index < nextCount; index++)
- {
- message = _consumer.receive(3000);
- assertEquals(startIndex + index, message.getIntProperty(INDEX));
- }
- return message;
- }
-
- protected void validateRemainingMessages(int remaining) throws JMSException
- {
- int index = SENT_COUNT - remaining;
-
- Message message = null;
- while (index != SENT_COUNT)
- {
- message = _consumer.receive(3000);
- assertNotNull(message);
- assertEquals(index++, message.getIntProperty(INDEX));
- }
-
- if (message != null)
- {
- _logger.info("Received redelivery of three messages. Acknowledging last message");
- message.acknowledge();
- }
-
- _logger.info("Calling acknowledge with no outstanding messages");
- // all acked so no messages to be delivered
- _consumerSession.recover();
-
- message = _consumer.receiveNoWait();
- assertNull(message);
- _logger.info("No messages redelivered as is expected");
- }
-
- public void testRecoverResendsMsgs() throws Exception
- {
- initTest();
-
- Message message = validateNextMessages(1, 0);
- message.acknowledge();
- _logger.info("Received and acknowledged first message");
-
- _consumer.receive();
- _consumer.receive();
- _consumer.receive();
- _logger.info("Received all four messages. Calling recover with three outstanding messages");
- // no ack for last three messages so when I call recover I expect to get three messages back
-
- _consumerSession.recover();
-
- validateRemainingMessages(3);
- }
-
- public void testRecoverResendsMsgsAckOnEarlier() throws Exception
- {
- initTest();
-
- Message message = validateNextMessages(2, 0);
- message.acknowledge();
- _logger.info("Received 2 messages, acknowledge() first message, should acknowledge both");
-
- _consumer.receive();
- _consumer.receive();
- _logger.info("Received all four messages. Calling recover with two outstanding messages");
- // no ack for last three messages so when I call recover I expect to get three messages back
- _consumerSession.recover();
-
- Message message2 = _consumer.receive(3000);
- assertNotNull(message2);
- assertEquals(2, message2.getIntProperty(INDEX));
-
- Message message3 = _consumer.receive(3000);
- assertNotNull(message3);
- assertEquals(3, message3.getIntProperty(INDEX));
-
- _logger.info("Received redelivery of two messages. calling acknolwedgeThis() first of those message");
- ((org.apache.qpid.jms.Message) message2).acknowledgeThis();
-
- _logger.info("Calling recover");
- // all acked so no messages to be delivered
- _consumerSession.recover();
-
- message3 = _consumer.receive(3000);
- assertNotNull(message3);
- assertEquals(3, message3.getIntProperty(INDEX));
- ((org.apache.qpid.jms.Message) message3).acknowledgeThis();
-
- // all acked so no messages to be delivered
- validateRemainingMessages(0);
- }
-
- public void testAcknowledgePerConsumer() throws Exception
- {
- AMQConnection con = (AMQConnection) getConnection("guest", "guest");
-
- Session consumerSession = con.createSession(false, Session.CLIENT_ACKNOWLEDGE);
- Queue queue =
- new AMQQueue(consumerSession.getDefaultQueueExchangeName(), new AMQShortString("Q1"), new AMQShortString("Q1"),
- false, true);
- Queue queue2 =
- new AMQQueue(consumerSession.getDefaultQueueExchangeName(), new AMQShortString("Q2"), new AMQShortString("Q2"),
- false, true);
- MessageConsumer consumer = consumerSession.createConsumer(queue);
- MessageConsumer consumer2 = consumerSession.createConsumer(queue2);
-
- AMQConnection con2 = (AMQConnection) getConnection("guest", "guest");
- Session producerSession = con2.createSession(false, Session.CLIENT_ACKNOWLEDGE);
- MessageProducer producer = producerSession.createProducer(queue);
- MessageProducer producer2 = producerSession.createProducer(queue2);
-
- producer.send(producerSession.createTextMessage("msg1"));
- producer2.send(producerSession.createTextMessage("msg2"));
-
- con2.close();
-
- _logger.info("Starting connection");
- con.start();
-
- TextMessage tm2 = (TextMessage) consumer2.receive(2000);
- assertNotNull(tm2);
- assertEquals("msg2", tm2.getText());
-
- tm2.acknowledge();
- consumerSession.recover();
-
- TextMessage tm1 = (TextMessage) consumer.receive(2000);
- assertNotNull(tm1);
- assertEquals("msg1", tm1.getText());
-
- con.close();
-
- }
-
- public void testRecoverInAutoAckListener() throws Exception
- {
- AMQConnection con = (AMQConnection) getConnection("guest", "guest");
-
- final Session consumerSession = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
- Queue queue =
- new AMQQueue(consumerSession.getDefaultQueueExchangeName(), new AMQShortString("Q3"), new AMQShortString("Q3"),
- false, true);
- MessageConsumer consumer = consumerSession.createConsumer(queue);
- MessageProducer producer = consumerSession.createProducer(queue);
- producer.send(consumerSession.createTextMessage("hello"));
-
- final Object lock = new Object();
-
- consumer.setMessageListener(new MessageListener()
- {
-
- public void onMessage(Message message)
- {
- try
- {
- count.incrementAndGet();
- if (count.get() == 1)
- {
- if (message.getJMSRedelivered())
- {
- setError(new Exception("Message marked as redelivered on what should be first delivery attempt"));
- }
-
- consumerSession.recover();
- }
- else if (count.get() == 2)
- {
- if (!message.getJMSRedelivered())
- {
- setError(
- new Exception("Message not marked as redelivered on what should be second delivery attempt"));
- }
- }
- else
- {
- System.err.println(message);
- fail("Message delivered too many times!: " + count);
- }
- }
- catch (JMSException e)
- {
- _logger.error("Error recovering session: " + e, e);
- setError(e);
- }
-
- synchronized (lock)
- {
- lock.notify();
- }
- }
- });
-
- con.start();
-
- long waitTime = 30000L;
- long waitUntilTime = System.currentTimeMillis() + waitTime;
-
- synchronized (lock)
- {
- while ((count.get() <= 1) && (waitTime > 0))
- {
- lock.wait(waitTime);
- if (count.get() <= 1)
- {
- waitTime = waitUntilTime - System.currentTimeMillis();
- }
- }
- }
-
- Thread.sleep(1000);
-
- if (_error != null)
- {
- throw _error;
- }
-
- assertEquals("Message not received the correct number of times.",
- 2, count.get());
- }
-
- private void setError(Exception e)
- {
- _error = e;
- }
-
- private void sendMessages(javax.jms.Session session,Destination dest,int count) throws Exception
- {
- MessageProducer prod = session.createProducer(dest);
- for (int i=0; i<count; i++)
- {
- prod.send(session.createTextMessage("Msg" + i));
- }
- prod.close();
- }
-
- /**
- * Goal : Check if ordering is preserved when doing recovery under reasonable circumstances.
- * Refer QPID-2471 for more details.
- * Test strategy :
- * Send 8 messages to a topic.
- * The consumer will call recover until it sees a message 5 times,
- * at which point it will ack that message.
- * It will continue the above until it acks all the messages.
- * While doing so it will verify that the messages are not
- * delivered out of order.
- */
- public void testOderingWithSyncConsumer() throws Exception
- {
- Connection con = (Connection) getConnection("guest", "guest");
- javax.jms.Session session = con.createSession(false, Session.CLIENT_ACKNOWLEDGE);
- Destination topic = session.createTopic("myTopic");
- MessageConsumer cons = session.createConsumer(topic);
-
- sendMessages(session,topic,8);
- con.start();
-
- int messageSeen = 0;
- int expectedMsg = 0;
-
- long startTime = System.currentTimeMillis();
-
- while(expectedMsg < 8)
- {
- // Based on historical data, on average the test takes about 6 secs to complete.
- if (System.currentTimeMillis() - startTime > 8000)
- {
- fail("Test did not complete on time. Received " +
- expectedMsg + " msgs so far. Please check the logs");
- }
-
- Message message = cons.receive(2000);
- String text=((TextMessage) message).getText();
-
- assertEquals("Received Message Out Of Order","Msg"+expectedMsg,text);
-
- //don't ack the message until we receive it 5 times
- if( messageSeen < 5 )
- {
- _logger.debug("Ignoring message " + text + " and calling recover");
- session.recover();
- messageSeen++;
- }
- else
- {
- messageSeen = 0;
- expectedMsg++;
- message.acknowledge();
- _logger.debug("Acknowledging message " + text);
- }
- }
- }
-
- /**
- * Goal : Same as testOderingWithSyncConsumer
- * Test strategy :
- * Same as testOderingWithSyncConsumer but using a
- * Message Listener instead of a sync receive().
- */
- public void testOderingWithAsyncConsumer() throws Exception
- {
- Connection con = (Connection) getConnection("guest", "guest");
- final javax.jms.Session session = con.createSession(false, Session.CLIENT_ACKNOWLEDGE);
- Destination topic = session.createTopic("myTopic");
- MessageConsumer cons = session.createConsumer(topic);
-
- sendMessages(session,topic,8);
- con.start();
-
- final Object lock = new Object();
- final AtomicBoolean pass = new AtomicBoolean(false); //used as work around for 'final'
- cons.setMessageListener(new MessageListener()
- {
- int messageSeen = 0;
- int expectedMsg = 0;
-
- public void onMessage(Message message)
- {
- try
- {
- String text = ((TextMessage) message).getText();
- assertEquals("Received Message Out Of Order","Msg"+expectedMsg,text);
-
- //don't ack the message until we receive it 5 times
- if( messageSeen < 5 )
- {
- _logger.debug("Ignoring message " + text + " and calling recover");
- session.recover();
- messageSeen++;
- }
- else
- {
- messageSeen = 0;
- expectedMsg++;
- message.acknowledge();
- _logger.debug("Acknowledging message " + text);
- if (expectedMsg == 8)
- {
- pass.set(true);
- synchronized (lock)
- {
- lock.notifyAll();
- }
- }
- }
- }
- catch (JMSException e)
- {
- fail("Exception : " + e.getMessage());
- synchronized (lock)
- {
- lock.notifyAll();
- }
- }
- }
- });
-
- synchronized(lock)
- {
- // Based on historical data, on average the test takes about 6 secs to complete.
- lock.wait(8000);
- }
-
- if (!pass.get())
- {
- fail("Test did not complete on time. Please check the logs");
- }
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/basic/BytesMessageTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/basic/BytesMessageTest.java
deleted file mode 100644
index 59ce64eb4f..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/basic/BytesMessageTest.java
+++ /dev/null
@@ -1,284 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.basic;
-
-import junit.framework.Assert;
-
-import org.apache.mina.common.ByteBuffer;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQDestination;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.client.message.JMSBytesMessage;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.apache.qpid.transport.util.Waiter;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.jms.BytesMessage;
-import javax.jms.Connection;
-import javax.jms.Destination;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageListener;
-import javax.jms.MessageNotReadableException;
-import javax.jms.MessageNotWriteableException;
-import javax.jms.MessageProducer;
-import javax.jms.Session;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-public class BytesMessageTest extends QpidBrokerTestCase implements MessageListener
-{
- private static final Logger _logger = LoggerFactory.getLogger(BytesMessageTest.class);
-
- private Connection _connection;
- private Destination _destination;
- private Session _session;
- private final List<JMSBytesMessage> received = new ArrayList<JMSBytesMessage>();
- private final List<byte[]> messages = new ArrayList<byte[]>();
- private int _count = 100;
- public String _connectionString = "vm://:1";
-
- protected void setUp() throws Exception
- {
- super.setUp();
- init((AMQConnection) getConnection("guest", "guest"));
- }
-
- protected void tearDown() throws Exception
- {
- super.tearDown();
- }
-
- void init(AMQConnection connection) throws Exception
- {
- init(connection, new AMQQueue(connection, randomize("BytesMessageTest"), true));
- }
-
- void init(AMQConnection connection, AMQDestination destination) throws Exception
- {
- _connection = connection;
- _destination = destination;
- _session = connection.createSession(false, AMQSession.NO_ACKNOWLEDGE);
-
- // Set up a slow consumer.
- _session.createConsumer(destination).setMessageListener(this);
- connection.start();
- }
-
- public void test() throws Exception
- {
- try
- {
- send(_count);
- waitFor(_count);
- check();
- _logger.info("Completed without failure");
- }
- finally
- {
- _connection.close();
- }
- }
-
- void send(int count) throws JMSException
- {
- // create a publisher
- MessageProducer producer = _session.createProducer(_destination);
- for (int i = 0; i < count; i++)
- {
- BytesMessage msg = _session.createBytesMessage();
-
- try
- {
- msg.readFloat();
- Assert.fail("Message should not be readable");
- }
- catch (MessageNotReadableException mnwe)
- {
- // normal execution
- }
-
- byte[] data = ("Message " + i).getBytes();
- msg.writeBytes(data);
- messages.add(data);
- producer.send(msg);
- }
- }
-
- void waitFor(int count) throws InterruptedException
- {
- synchronized (received)
- {
- Waiter w = new Waiter(received, 30000);
- while (received.size() < count && w.hasTime())
- {
- w.await();
- }
- }
- }
-
- void check() throws JMSException
- {
- List<byte[]> actual = new ArrayList<byte[]>();
- for (JMSBytesMessage m : received)
- {
- ByteBuffer buffer = m.getData();
- byte[] data = new byte[buffer.remaining()];
- buffer.get(data);
- actual.add(data);
-
- // Check Body Write Status
- try
- {
- m.writeBoolean(true);
- Assert.fail("Message should not be writeable");
- }
- catch (MessageNotWriteableException mnwe)
- {
- // normal execution
- }
-
- m.clearBody();
-
- try
- {
- m.writeBoolean(true);
- }
- catch (MessageNotWriteableException mnwe)
- {
- Assert.fail("Message should be writeable");
- }
-
- // Check property write status
- try
- {
- m.setStringProperty("test", "test");
- Assert.fail("Message should not be writeable");
- }
- catch (MessageNotWriteableException mnwe)
- {
- // normal execution
- }
-
- m.clearProperties();
-
- try
- {
- m.setStringProperty("test", "test");
- }
- catch (MessageNotWriteableException mnwe)
- {
- Assert.fail("Message should be writeable");
- }
-
- }
-
- assertEqual(messages.iterator(), actual.iterator());
- }
-
- private static void assertEqual(Iterator expected, Iterator actual)
- {
- List<String> errors = new ArrayList<String>();
- while (expected.hasNext() && actual.hasNext())
- {
- try
- {
- assertEquivalent((byte[]) expected.next(), (byte[]) actual.next());
- }
- catch (Exception e)
- {
- errors.add(e.getMessage());
- }
- }
- while (expected.hasNext())
- {
- errors.add("Expected " + expected.next() + " but no more actual values.");
- }
- while (actual.hasNext())
- {
- errors.add("Found " + actual.next() + " but no more expected values.");
- }
-
- if (!errors.isEmpty())
- {
- throw new RuntimeException(errors.toString());
- }
- }
-
- private static void assertEquivalent(byte[] expected, byte[] actual)
- {
- if (expected.length != actual.length)
- {
- throw new RuntimeException("Expected length " + expected.length + " got " + actual.length);
- }
-
- for (int i = 0; i < expected.length; i++)
- {
- if (expected[i] != actual[i])
- {
- throw new RuntimeException("Failed on byte " + i + " of " + expected.length);
- }
- }
- }
-
- public void onMessage(Message message)
- {
- synchronized (received)
- {
- received.add((JMSBytesMessage) message);
- received.notify();
- }
- }
-
- private static String randomize(String in)
- {
- return in + System.currentTimeMillis();
- }
-
- public static void main(String[] argv) throws Exception
- {
- final String connectionString;
- final int count;
- if (argv.length == 0)
- {
- connectionString = "vm://:1";
- count = 100;
- }
- else
- {
- connectionString = argv[0];
- count = Integer.parseInt(argv[1]);
- }
-
- System.out.println("connectionString = " + connectionString);
- System.out.println("count = " + count);
-
- BytesMessageTest test = new BytesMessageTest();
- test._connectionString = connectionString;
- test._count = count;
- test.test();
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/basic/FieldTableMessageTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/basic/FieldTableMessageTest.java
deleted file mode 100644
index abf8da799c..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/basic/FieldTableMessageTest.java
+++ /dev/null
@@ -1,163 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.basic;
-
-import org.apache.mina.common.ByteBuffer;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQDestination;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.client.message.JMSBytesMessage;
-import org.apache.qpid.framing.AMQFrameDecodingException;
-import org.apache.qpid.framing.FieldTable;
-import org.apache.qpid.framing.FieldTableFactory;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.jms.BytesMessage;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageListener;
-import javax.jms.MessageProducer;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-public class FieldTableMessageTest extends QpidBrokerTestCase implements MessageListener
-{
- private static final Logger _logger = LoggerFactory.getLogger(FieldTableMessageTest.class);
-
- private AMQConnection _connection;
- private AMQDestination _destination;
- private AMQSession _session;
- private final ArrayList<JMSBytesMessage> received = new ArrayList<JMSBytesMessage>();
- private FieldTable _expected;
- private int _count = 10;
- public String _connectionString = "vm://:1";
- private CountDownLatch _waitForCompletion;
-
- protected void setUp() throws Exception
- {
- super.setUp();
- init( (AMQConnection) getConnection("guest", "guest"));
- }
-
- protected void tearDown() throws Exception
- {
- super.tearDown();
- }
-
- private void init(AMQConnection connection) throws Exception
- {
- init(connection, new AMQQueue(connection, randomize("FieldTableMessageTest"), true));
- }
-
- private void init(AMQConnection connection, AMQDestination destination) throws Exception
- {
- _connection = connection;
- _destination = destination;
- _session = (AMQSession) connection.createSession(false, AMQSession.NO_ACKNOWLEDGE);
-
- // set up a slow consumer
- _session.createConsumer(destination).setMessageListener(this);
- connection.start();
-
- // _expected = new FieldTableTest().load("FieldTableTest2.properties");
- _expected = load();
- }
-
- private FieldTable load() throws IOException
- {
- FieldTable result = FieldTableFactory.newFieldTable();
- result.setLong("one", 1L);
- result.setLong("two", 2L);
- result.setLong("three", 3L);
- result.setLong("four", 4L);
- result.setLong("five", 5L);
-
- return result;
- }
-
- public void test() throws Exception
- {
- int count = _count;
- _waitForCompletion = new CountDownLatch(_count);
- send(count);
- _waitForCompletion.await(20, TimeUnit.SECONDS);
- check();
- _logger.info("Completed without failure");
- _connection.close();
- }
-
- void send(int count) throws JMSException, IOException
- {
- // create a publisher
- MessageProducer producer = _session.createProducer(_destination);
- for (int i = 0; i < count; i++)
- {
- BytesMessage msg = _session.createBytesMessage();
- msg.writeBytes(_expected.getDataAsBytes());
- producer.send(msg);
- }
- }
-
-
- void check() throws JMSException, AMQFrameDecodingException
- {
- for (Object m : received)
- {
- ByteBuffer buffer = ((JMSBytesMessage) m).getData();
- FieldTable actual = FieldTableFactory.newFieldTable(buffer, buffer.remaining());
- for (String key : _expected.keys())
- {
- assertEquals("Values for " + key + " did not match", _expected.getObject(key), actual.getObject(key));
- }
- }
- }
-
- public void onMessage(Message message)
- {
- synchronized (received)
- {
- received.add((JMSBytesMessage) message);
- _waitForCompletion.countDown();
- }
- }
-
- private static String randomize(String in)
- {
- return in + System.currentTimeMillis();
- }
-
- public static void main(String[] argv) throws Exception
- {
- FieldTableMessageTest test = new FieldTableMessageTest();
- test._connectionString = (argv.length == 0) ? "vm://:1" : argv[0];
- test.setUp();
- test._count = (argv.length > 1) ? Integer.parseInt(argv[1]) : 5;
- test.test();
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/basic/InvalidDestinationTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/basic/InvalidDestinationTest.java
deleted file mode 100644
index c9f6a22500..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/basic/InvalidDestinationTest.java
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.qpid.test.unit.basic;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-import javax.jms.Session;
-import javax.jms.QueueSession;
-import javax.jms.Queue;
-import javax.jms.QueueSender;
-import javax.jms.TextMessage;
-import javax.jms.InvalidDestinationException;
-
-public class InvalidDestinationTest extends QpidBrokerTestCase
-{
- private AMQConnection _connection;
-
- protected void setUp() throws Exception
- {
- super.setUp();
- _connection = (AMQConnection) getConnection("guest", "guest");
- }
-
- protected void tearDown() throws Exception
- {
- _connection.close();
- super.tearDown();
- }
-
-
-
- public void testInvalidDestination() throws Exception
- {
- Queue invalidDestination = new AMQQueue("amq.direct","unknownQ");
- AMQQueue validDestination = new AMQQueue("amq.direct","knownQ");
- QueueSession queueSession = _connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
-
- // This is the only easy way to create and bind a queue from the API :-(
- queueSession.createConsumer(validDestination);
-
- QueueSender sender = queueSession.createSender(invalidDestination);
- TextMessage msg = queueSession.createTextMessage("Hello");
- try
- {
- sender.send(msg);
- fail("Expected InvalidDestinationException");
- }
- catch (InvalidDestinationException ex)
- {
- // pass
- }
- sender.close();
-
- sender = queueSession.createSender(null);
- invalidDestination = new AMQQueue("amq.direct","unknownQ");
-
- try
- {
- sender.send(invalidDestination,msg);
- fail("Expected InvalidDestinationException");
- }
- catch (InvalidDestinationException ex)
- {
- // pass
- }
- sender.send(validDestination,msg);
- sender.close();
- validDestination = new AMQQueue("amq.direct","knownQ");
- sender = queueSession.createSender(validDestination);
- sender.send(msg);
-
-
-
-
- }
-
-
- public static junit.framework.Test suite()
- {
-
- return new junit.framework.TestSuite(InvalidDestinationTest.class);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/basic/LargeMessageTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/basic/LargeMessageTest.java
deleted file mode 100644
index d97e22e024..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/basic/LargeMessageTest.java
+++ /dev/null
@@ -1,190 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- *
- */
-package org.apache.qpid.test.unit.basic;
-
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.jms.Destination;
-import javax.jms.JMSException;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-import javax.jms.Session;
-import javax.jms.TextMessage;
-
-public class LargeMessageTest extends QpidBrokerTestCase
-{
- private static final Logger _logger = LoggerFactory.getLogger(LargeMessageTest.class);
-
- private Destination _destination;
- private AMQSession _session;
- private AMQConnection _connection;
-
- protected void setUp() throws Exception
- {
- super.setUp();
- try
- {
- _connection = (AMQConnection) getConnection("guest", "guest");
- init( _connection );
- }
- catch (Exception e)
- {
- fail("Unable to initialilse connection: " + e);
- }
- }
-
- protected void tearDown() throws Exception
- {
- _connection.close();
- super.tearDown();
- }
-
- private void init(AMQConnection connection) throws Exception
- {
- Destination destination = new AMQQueue(connection, "LargeMessageTest", true);
- init(connection, destination);
- }
-
- private void init(AMQConnection connection, Destination destination) throws Exception
- {
- _destination = destination;
- _session = (AMQSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- connection.start();
- }
-
- // Test boundary of 1 packet to 2 packets
- public void test64kminus9()
- {
- checkLargeMessage((64 * 1024) - 9);
- }
-
- public void test64kminus8()
- {
- checkLargeMessage((64 * 1024)-8);
- }
-
- public void test64kminus7()
- {
- checkLargeMessage((64 * 1024)-7);
- }
-
-
- public void test64kplus1()
- {
- checkLargeMessage((64 * 1024) + 1);
- }
-
- // Test packet boundary of 3 packtes
- public void test128kminus1()
- {
- checkLargeMessage((128 * 1024) - 1);
- }
-
- public void test128k()
- {
- checkLargeMessage(128 * 1024);
- }
-
- public void test128kplus1()
- {
- checkLargeMessage((128 * 1024) + 1);
- }
-
- // Testing larger messages
-
- public void test256k()
- {
- checkLargeMessage(256 * 1024);
- }
-
- public void test512k()
- {
- checkLargeMessage(512 * 1024);
- }
-
- public void test1024k()
- {
- checkLargeMessage(1024 * 1024);
- }
-
- protected void checkLargeMessage(int messageSize)
- {
- try
- {
- MessageConsumer consumer = _session.createConsumer(_destination);
- MessageProducer producer = _session.createProducer(_destination);
- _logger.info("Testing message of size:" + messageSize);
-
- String _messageText = buildLargeMessage(messageSize);
-
- _logger.debug("Message built");
-
- producer.send(_session.createTextMessage(_messageText));
-
- TextMessage result = (TextMessage) consumer.receive(10000);
-
- assertNotNull("Null message recevied", result);
- assertEquals("Message Size", _messageText.length(), result.getText().length());
- assertEquals("Message content differes", _messageText, result.getText());
- }
- catch (JMSException e)
- {
- e.printStackTrace();
- fail("Excpetion occured:" + e.getCause());
- }
- }
-
- private String buildLargeMessage(int size)
- {
- StringBuilder builder = new StringBuilder(size);
-
- char ch = 'a';
-
- for (int i = 1; i <= size; i++)
- {
- builder.append(ch);
-
- if ((i % 1000) == 0)
- {
- ch++;
- if (ch == ('z' + 1))
- {
- ch = 'a';
- }
- }
- }
-
- return builder.toString();
- }
-
- public static junit.framework.Test suite()
- {
- return new junit.framework.TestSuite(LargeMessageTest.class);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/basic/MapMessageTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/basic/MapMessageTest.java
deleted file mode 100644
index 9f13ddcfdb..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/basic/MapMessageTest.java
+++ /dev/null
@@ -1,1271 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.basic;
-
-import junit.framework.Assert;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.client.message.JMSMapMessage;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.jms.Destination;
-import javax.jms.JMSException;
-import javax.jms.MapMessage;
-import javax.jms.Message;
-import javax.jms.MessageFormatException;
-import javax.jms.MessageListener;
-import javax.jms.MessageNotWriteableException;
-import javax.jms.MessageProducer;
-import javax.jms.Session;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-public class MapMessageTest extends QpidBrokerTestCase implements MessageListener
-{
- private static final Logger _logger = LoggerFactory.getLogger(MapMessageTest.class);
-
- private AMQConnection _connection;
- private Destination _destination;
- private AMQSession _session;
- private final List<JMSMapMessage> received = new ArrayList<JMSMapMessage>();
-
- private static final String MESSAGE = "Message ";
- private int _count = 100;
- public String _connectionString = "vm://:1";
- private byte[] _bytes = { 99, 98, 97, 96, 95 };
- private static final float _smallfloat = 100.0f;
-
- protected void setUp() throws Exception
- {
- super.setUp();
- try
- {
- init((AMQConnection) getConnection("guest", "guest"));
- }
- catch (Exception e)
- {
- fail("Unable to initialilse connection: " + e);
- }
- }
-
- protected void tearDown() throws Exception
- {
- _logger.info("Tearing Down unit.basic.MapMessageTest");
- super.tearDown();
- }
-
- private void init(AMQConnection connection) throws Exception
- {
- Destination destination = new AMQQueue(connection, randomize("MapMessageTest"), true);
- init(connection, destination);
- }
-
- private void init(AMQConnection connection, Destination destination) throws Exception
- {
- _connection = connection;
- _destination = destination;
- _session = (AMQSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- // set up a slow consumer
- _session.createConsumer(destination).setMessageListener(this);
- connection.start();
- }
-
- public void test() throws Exception
- {
- int count = _count;
- send(count);
- waitFor(count);
- check();
- _connection.close();
- }
-
- void send(int count) throws JMSException
- {
- // create a publisher
- MessageProducer producer = _session.createProducer(_destination);
- for (int i = 0; i < count; i++)
- {
- MapMessage message = _session.createMapMessage();
-
- setMapValues(message, i);
-
- producer.send(message);
- }
- }
-
- private void setMapValues(MapMessage message, int i) throws JMSException
- {
- message.setBoolean("odd", (i / 2) == 0);
- message.setByte("byte",Byte.MAX_VALUE);
- message.setBytes("bytes", _bytes);
- message.setChar("char",'c');
- message.setDouble("double", Double.MAX_VALUE);
- message.setFloat("float", Float.MAX_VALUE);
- message.setFloat("smallfloat", 100);
- message.setInt("messageNumber", i);
- message.setInt("int", Integer.MAX_VALUE);
- message.setLong("long", Long.MAX_VALUE);
- message.setShort("short", Short.MAX_VALUE);
- message.setString("message", MESSAGE + i);
-
- // Test Setting Object Values
- message.setObject("object-bool", true);
- message.setObject("object-byte", Byte.MAX_VALUE);
- message.setObject("object-bytes", _bytes);
- message.setObject("object-char", 'c');
- message.setObject("object-double", Double.MAX_VALUE);
- message.setObject("object-float", Float.MAX_VALUE);
- message.setObject("object-int", Integer.MAX_VALUE);
- message.setObject("object-long", Long.MAX_VALUE);
- message.setObject("object-short", Short.MAX_VALUE);
-
- // Set a null String value
- message.setString("nullString", null);
- // Highlight protocol problem
- message.setString("emptyString", "");
-
- }
-
- void waitFor(int count) throws Exception
- {
- long waitTime = 30000L;
- long waitUntilTime = System.currentTimeMillis() + 30000L;
-
- synchronized (received)
- {
- while ((received.size() < count) && (waitTime > 0))
- {
- if (received.size() < count)
- {
- received.wait(waitTime);
- }
-
- if (received.size() < count)
- {
- waitTime = waitUntilTime - System.currentTimeMillis();
- }
- }
-
- if (received.size() < count)
- {
- throw new Exception("Timed-out. Waiting for " + count + " only got " + received.size());
- }
- }
- }
-
- void check() throws JMSException
- {
- int count = 0;
- for (JMSMapMessage m : received)
- {
- testMapValues(m, count);
-
- testCorrectExceptions(m);
-
- testMessageWriteStatus(m);
-
- testPropertyWriteStatus(m);
-
- count++;
- }
- }
-
- private void testCorrectExceptions(JMSMapMessage m) throws JMSException
- {
- testBoolean(m);
-
- testByte(m);
-
- testBytes(m);
-
- testChar(m);
-
- testDouble(m);
-
- testFloat(m);
-
- testInt(m);
-
- testLong(m);
-
- testShort(m);
-
- testString(m);
- }
-
- private void testString(JMSMapMessage m) throws JMSException
- {
-
- Assert.assertFalse(m.getBoolean("message"));
-
- try
- {
- m.getByte("message");
- fail("Exception Expected.");
- }
- catch (NumberFormatException nfe)
- {
- // normal execution
- }
-
- try
- {
- m.getShort("message");
- fail("Exception Expected.");
- }
- catch (NumberFormatException nfe)
- {
- // normal execution
- }
-
- // Try bad reads
- try
- {
- m.getChar("message");
- fail("Exception Expected.");
- }
- catch (MessageFormatException npe)
- {
- // normal execution
- }
-
- try
- {
- m.getInt("message");
- fail("Exception Expected.");
- }
- catch (NumberFormatException nfe)
- {
- // normal execution
- }
-
- try
- {
- m.getLong("message");
- fail("Exception Expected.");
- }
- catch (NumberFormatException nfe)
- {
- // normal execution
- }
-
- // Try bad reads
- try
- {
- m.getFloat("message");
- fail("Exception Expected.");
- }
- catch (NumberFormatException nfe)
- {
- // normal execution
- }
- // Try bad reads
- try
- {
- m.getDouble("message");
- fail("Exception Expected.");
- }
- catch (NumberFormatException nfe)
- {
- // normal execution
- }
- // Try bad reads
- try
- {
- m.getBytes("message");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
-
- Assert.assertEquals(MESSAGE + m.getInt("messageNumber"), m.getString("message"));
- }
-
- private void testShort(JMSMapMessage m) throws JMSException
- {
-
- // Try bad reads
- try
- {
- m.getBoolean("short");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
-
- try
- {
- m.getByte("short");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
-
- Assert.assertEquals(Short.MAX_VALUE, m.getShort("short"));
-
- // Try bad reads
- try
- {
- m.getChar("short");
- fail("Exception Expected.");
- }
- catch (MessageFormatException npe)
- {
- // normal execution
- }
-
- Assert.assertEquals(Short.MAX_VALUE, m.getInt("short"));
-
- Assert.assertEquals(Short.MAX_VALUE, m.getLong("short"));
-
- // Try bad reads
- try
- {
- m.getFloat("short");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
- // Try bad reads
- try
- {
- m.getDouble("short");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
- // Try bad reads
- try
- {
- m.getBytes("short");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
-
- Assert.assertEquals("" + Short.MAX_VALUE, m.getString("short"));
- }
-
- private void testLong(JMSMapMessage m) throws JMSException
- {
-
- // Try bad reads
- try
- {
- m.getBoolean("long");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
-
- try
- {
- m.getByte("long");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
-
- try
- {
- m.getShort("long");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
-
- // Try bad reads
- try
- {
- m.getChar("long");
- fail("Exception Expected.");
- }
- catch (MessageFormatException npe)
- {
- // normal execution
- }
-
- try
- {
- m.getInt("long");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
-
- Assert.assertEquals(Long.MAX_VALUE, m.getLong("long"));
-
- // Try bad reads
- try
- {
- m.getFloat("long");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
- // Try bad reads
- try
- {
- m.getDouble("long");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
- // Try bad reads
- try
- {
- m.getBytes("long");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
-
- Assert.assertEquals("" + Long.MAX_VALUE, m.getString("long"));
- }
-
- private void testDouble(JMSMapMessage m) throws JMSException
- {
-
- // Try bad reads
- try
- {
- m.getBoolean("double");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
-
- try
- {
- m.getByte("double");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
-
- try
- {
- m.getShort("double");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
-
- // Try bad reads
- try
- {
- m.getChar("double");
- fail("Exception Expected.");
- }
- catch (MessageFormatException npe)
- {
- // normal execution
- }
-
- try
- {
- m.getInt("double");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
-
- try
- {
- m.getLong("double");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
-
- // Try bad reads
- try
- {
- m.getFloat("double");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
-
- Assert.assertEquals(Double.MAX_VALUE, m.getDouble("double"));
-
- // Try bad reads
- try
- {
- m.getBytes("double");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
-
- Assert.assertEquals("" + Double.MAX_VALUE, m.getString("double"));
- }
-
- private void testFloat(JMSMapMessage m) throws JMSException
- {
-
- // Try bad reads
- try
- {
- m.getBoolean("float");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
-
- try
- {
- m.getByte("float");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
-
- try
- {
- m.getShort("float");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
-
- // Try bad reads
- try
- {
- m.getChar("float");
- fail("Exception Expected.");
- }
- catch (MessageFormatException npe)
- {
- // normal execution
- }
-
- try
- {
- m.getInt("float");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
-
- try
- {
- m.getLong("float");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
-
- Assert.assertEquals(Float.MAX_VALUE, m.getFloat("float"));
-
- Assert.assertEquals(_smallfloat, (float) m.getDouble("smallfloat"));
-
- // Try bad reads
- try
- {
- m.getBytes("float");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
-
- Assert.assertEquals("" + Float.MAX_VALUE, m.getString("float"));
- }
-
- private void testInt(JMSMapMessage m) throws JMSException
- {
-
- // Try bad reads
- try
- {
- m.getBoolean("int");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
-
- try
- {
- m.getByte("int");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
-
- try
- {
- m.getShort("int");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
-
- // Try bad reads
- try
- {
- m.getChar("int");
- fail("Exception Expected.");
- }
- catch (MessageFormatException npe)
- {
- // normal execution
- }
-
- Assert.assertEquals(Integer.MAX_VALUE, m.getInt("int"));
-
- Assert.assertEquals(Integer.MAX_VALUE, (int) m.getLong("int"));
-
- // Try bad reads
- try
- {
- m.getFloat("int");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
- // Try bad reads
- try
- {
- m.getDouble("int");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
- // Try bad reads
- try
- {
- m.getBytes("int");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
-
- Assert.assertEquals("" + Integer.MAX_VALUE, m.getString("int"));
- }
-
- private void testChar(JMSMapMessage m) throws JMSException
- {
-
- // Try bad reads
- try
- {
- m.getBoolean("char");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
-
- try
- {
- m.getByte("char");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
-
- try
- {
- m.getShort("char");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
-
- Assert.assertEquals('c', m.getChar("char"));
-
- try
- {
- m.getInt("char");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
-
- try
- {
- m.getLong("char");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
-
- // Try bad reads
- try
- {
- m.getFloat("char");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
- // Try bad reads
- try
- {
- m.getDouble("char");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
- // Try bad reads
- try
- {
- m.getBytes("char");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
-
- Assert.assertEquals("" + 'c', m.getString("char"));
- }
-
- private void testBytes(JMSMapMessage m) throws JMSException
- {
- // Try bad reads
- try
- {
- m.getBoolean("bytes");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
-
- try
- {
- m.getByte("bytes");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
-
- try
- {
- m.getShort("bytes");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
-
- // Try bad reads
- try
- {
- m.getChar("bytes");
- fail("Exception Expected.");
- }
- catch (MessageFormatException npe)
- {
- // normal execution
- }
-
- try
- {
- m.getInt("bytes");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
-
- try
- {
- m.getLong("bytes");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
-
- // Try bad reads
- try
- {
- m.getFloat("bytes");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
- // Try bad reads
- try
- {
- m.getDouble("bytes");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
-
- assertBytesEqual(_bytes, m.getBytes("bytes"));
-
- try
- {
- m.getString("bytes");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
-
- }
-
- private void testByte(JMSMapMessage m) throws JMSException
- {
- // Try bad reads
- try
- {
- m.getBoolean("byte");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
-
- Assert.assertEquals(Byte.MAX_VALUE, m.getByte("byte"));
-
- Assert.assertEquals((short) Byte.MAX_VALUE, m.getShort("byte"));
-
- // Try bad reads
- try
- {
- m.getChar("byte");
- fail("Exception Expected.");
- }
- catch (MessageFormatException npe)
- {
- // normal execution
- }
-
- // Reading a byte as an int is ok
- Assert.assertEquals((short) Byte.MAX_VALUE, m.getInt("byte"));
-
- Assert.assertEquals((short) Byte.MAX_VALUE, m.getLong("byte"));
-
- // Try bad reads
- try
- {
- m.getFloat("byte");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
- // Try bad reads
- try
- {
- m.getDouble("byte");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
- // Try bad reads
- try
- {
- m.getBytes("byte");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
-
- Assert.assertEquals("" + Byte.MAX_VALUE, m.getString("byte"));
-
- }
-
- private void testBoolean(JMSMapMessage m) throws JMSException
- {
-
- Assert.assertEquals((m.getInt("messageNumber") / 2) == 0, m.getBoolean("odd"));
-
- // Try bad reads
- try
- {
- m.getByte("odd");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
-
- // Try bad reads
- try
- {
- m.getShort("odd");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
- // Try bad reads
- try
- {
- m.getChar("odd");
- fail("Exception Expected.");
- }
- catch (MessageFormatException npe)
- {
- // normal execution
- }
- // Try bad reads
- try
- {
- m.getInt("odd");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
- // Try bad reads
- try
- {
- m.getLong("odd");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
- // Try bad reads
- try
- {
- m.getFloat("odd");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
- // Try bad reads
- try
- {
- m.getDouble("odd");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
- // Try bad reads
- try
- {
- m.getBytes("odd");
- fail("Exception Expected.");
- }
- catch (MessageFormatException nfe)
- {
- // normal execution
- }
-
- Assert.assertEquals("" + ((m.getInt("messageNumber") / 2) == 0), m.getString("odd"));
- }
-
- private void testPropertyWriteStatus(JMSMapMessage m) throws JMSException
- {
- // Check property write status
- try
- {
- m.setStringProperty("test", "test");
- Assert.fail("Message should not be writeable");
- }
- catch (MessageNotWriteableException mnwe)
- {
- // normal execution
- }
-
- m.clearProperties();
-
- try
- {
- m.setStringProperty("test", "test");
- }
- catch (MessageNotWriteableException mnwe)
- {
- Assert.fail("Message should be writeable");
- }
- }
-
- private void testMessageWriteStatus(JMSMapMessage m) throws JMSException
- {
- try
- {
- m.setInt("testint", 3);
- fail("Message should not be writeable");
- }
- catch (MessageNotWriteableException mnwe)
- {
- // normal execution
- }
-
- m.clearBody();
-
- try
- {
- m.setInt("testint", 3);
- }
- catch (MessageNotWriteableException mnwe)
- {
- Assert.fail("Message should be writeable");
- }
- }
-
- private void testMapValues(JMSMapMessage m, int count) throws JMSException
- {
- // Test get<Primiative>
-
- // Boolean
- assertEqual((count / 2) == 0, m.getBoolean("odd"));
- assertEqual("" + ((count / 2) == 0), m.getString("odd"));
-
- // Byte
- assertEqual(Byte.MAX_VALUE, m.getByte("byte"));
- assertEqual("" + Byte.MAX_VALUE, m.getString("byte"));
-
- // Bytes
- assertBytesEqual(_bytes, m.getBytes("bytes"));
-
- // Char
- assertEqual('c', m.getChar("char"));
-
- // Double
- assertEqual(Double.MAX_VALUE, m.getDouble("double"));
- assertEqual("" + Double.MAX_VALUE, m.getString("double"));
-
- // Float
- assertEqual(Float.MAX_VALUE, m.getFloat("float"));
- assertEqual(_smallfloat, (float) m.getDouble("smallfloat"));
- assertEqual("" + Float.MAX_VALUE, m.getString("float"));
-
- // Integer
- assertEqual(Integer.MAX_VALUE, m.getInt("int"));
- assertEqual("" + Integer.MAX_VALUE, m.getString("int"));
- assertEqual(count, m.getInt("messageNumber"));
-
- // long
- assertEqual(Long.MAX_VALUE, m.getLong("long"));
- assertEqual("" + Long.MAX_VALUE, m.getString("long"));
-
- // Short
- assertEqual(Short.MAX_VALUE, m.getShort("short"));
- assertEqual("" + Short.MAX_VALUE, m.getString("short"));
- assertEqual((int) Short.MAX_VALUE, m.getInt("short"));
-
- // String
- assertEqual(MESSAGE + count, m.getString("message"));
-
- // Test getObjects
- assertEqual(true, m.getObject("object-bool"));
- assertEqual(Byte.MAX_VALUE, m.getObject("object-byte"));
- assertBytesEqual(_bytes, (byte[]) m.getObject("object-bytes"));
- assertEqual('c', m.getObject("object-char"));
- assertEqual(Double.MAX_VALUE, m.getObject("object-double"));
- assertEqual(Float.MAX_VALUE, m.getObject("object-float"));
- assertEqual(Integer.MAX_VALUE, m.getObject("object-int"));
- assertEqual(Long.MAX_VALUE, m.getObject("object-long"));
- assertEqual(Short.MAX_VALUE, m.getObject("object-short"));
-
- // Check Special values
- assertTrue(m.getString("nullString") == null);
- assertEqual("", m.getString("emptyString"));
- }
-
- private void assertBytesEqual(byte[] expected, byte[] actual)
- {
- Assert.assertEquals(expected.length, actual.length);
-
- for (int index = 0; index < expected.length; index++)
- {
- Assert.assertEquals(expected[index], actual[index]);
- }
- }
-
- private static void assertEqual(Iterator expected, Iterator actual)
- {
- List<String> errors = new ArrayList<String>();
- while (expected.hasNext() && actual.hasNext())
- {
- try
- {
- assertEqual(expected.next(), actual.next());
- }
- catch (Exception e)
- {
- errors.add(e.getMessage());
- }
- }
- while (expected.hasNext())
- {
- errors.add("Expected " + expected.next() + " but no more actual values.");
- }
- while (actual.hasNext())
- {
- errors.add("Found " + actual.next() + " but no more expected values.");
- }
-
- if (!errors.isEmpty())
- {
- throw new RuntimeException(errors.toString());
- }
- }
-
- private static void assertEqual(Object expected, Object actual)
- {
- if (!expected.equals(actual))
- {
- throw new RuntimeException("Expected '" + expected + "' found '" + actual + "'");
- }
- }
-
- public void onMessage(Message message)
- {
- synchronized (received)
- {
- _logger.info("****************** Recevied Messgage:" + message);
- received.add((JMSMapMessage) message);
- received.notify();
- }
- }
-
- private static String randomize(String in)
- {
- return in + System.currentTimeMillis();
- }
-
- public static void main(String[] argv) throws Exception
- {
- MapMessageTest test = new MapMessageTest();
- test._connectionString = (argv.length == 0) ? "vm://:1" : argv[0];
- test.setUp();
- if (argv.length > 1)
- {
- test._count = Integer.parseInt(argv[1]);
- }
-
- test.test();
- }
-
- public static junit.framework.Test suite()
- {
- return new junit.framework.TestSuite(MapMessageTest.class);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/basic/MultipleConnectionTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/basic/MultipleConnectionTest.java
deleted file mode 100644
index 3a5f676ca6..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/basic/MultipleConnectionTest.java
+++ /dev/null
@@ -1,218 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.basic;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQDestination;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.client.AMQTopic;
-import org.apache.qpid.client.transport.TransportConnection;
-import org.apache.qpid.exchange.ExchangeDefaults;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageListener;
-import javax.jms.MessageProducer;
-import javax.jms.Session;
-
-public class MultipleConnectionTest extends QpidBrokerTestCase
-{
- private static final Logger _logger = LoggerFactory.getLogger(MultipleConnectionTest.class);
-
- public static final String _defaultBroker = "vm://:1";
- public String _connectionString = _defaultBroker;
-
- private class Receiver
- {
- private AMQConnection _connection;
- private Session[] _sessions;
- private MessageCounter[] _counters;
-
- Receiver(String broker, AMQDestination dest, int sessions) throws Exception
- {
- this((AMQConnection) getConnection("guest", "guest"), dest, sessions);
- }
-
- Receiver(AMQConnection connection, AMQDestination dest, int sessions) throws Exception
- {
- _connection = connection;
- _sessions = new AMQSession[sessions];
- _counters = new MessageCounter[sessions];
- for (int i = 0; i < sessions; i++)
- {
- _sessions[i] = _connection.createSession(false, AMQSession.NO_ACKNOWLEDGE);
- _counters[i] = new MessageCounter(_sessions[i].toString());
- _sessions[i].createConsumer(dest).setMessageListener(_counters[i]);
- }
-
- _connection.start();
- }
-
- void close() throws JMSException
- {
- _connection.close();
- }
- }
-
- private class Publisher
- {
- private AMQConnection _connection;
- private Session _session;
- private MessageProducer _producer;
-
- Publisher(String broker, AMQDestination dest) throws Exception
- {
- this((AMQConnection) getConnection("guest", "guest"), dest);
- }
-
- Publisher(AMQConnection connection, AMQDestination dest) throws Exception
- {
- _connection = connection;
- _session = _connection.createSession(false, AMQSession.NO_ACKNOWLEDGE);
- _producer = _session.createProducer(dest);
- }
-
- void send(String msg) throws JMSException
- {
- _producer.send(_session.createTextMessage(msg));
- }
-
- void close() throws JMSException
- {
- _connection.close();
- }
- }
-
- private static class MessageCounter implements MessageListener
- {
- private final String _name;
- private int _count;
-
- MessageCounter(String name)
- {
- _name = name;
- }
-
- public synchronized void onMessage(Message message)
- {
- _count++;
- notify();
- }
-
- synchronized boolean waitUntil(int expected, long maxWait) throws InterruptedException
- {
- long start = System.currentTimeMillis();
- while (expected > _count)
- {
- long timeLeft = maxWait - timeSince(start);
- if (timeLeft <= 0)
- {
- break;
- }
-
- wait(timeLeft);
- }
-
- return expected <= _count;
- }
-
- private long timeSince(long start)
- {
- return System.currentTimeMillis() - start;
- }
-
- public synchronized String toString()
- {
- return _name + ": " + _count;
- }
- }
-
- private static void waitForCompletion(int expected, long wait, Receiver[] receivers) throws InterruptedException
- {
- for (int i = 0; i < receivers.length; i++)
- {
- waitForCompletion(expected, wait, receivers[i]._counters);
- }
- }
-
- private static void waitForCompletion(int expected, long wait, MessageCounter[] counters) throws InterruptedException
- {
- for (int i = 0; i < counters.length; i++)
- {
- if (!counters[i].waitUntil(expected, wait))
- {
- throw new RuntimeException("Expected: " + expected + " got " + counters[i]);
- }
- }
- }
-
- private static String randomize(String in)
- {
- return in + System.currentTimeMillis();
- }
-
- public static void main(String[] argv) throws Exception
- {
- String broker = (argv.length > 0) ? argv[0] : _defaultBroker;
-
- MultipleConnectionTest test = new MultipleConnectionTest();
- test._connectionString = broker;
- test.test();
- }
-
- public void test() throws Exception
- {
- String broker = _connectionString;
- int messages = 10;
-
- AMQTopic topic = new AMQTopic(ExchangeDefaults.TOPIC_EXCHANGE_NAME, "amq.topic");
-
- Receiver[] receivers = new Receiver[] { new Receiver(broker, topic, 2), new Receiver(broker, topic, 14) };
-
- Publisher publisher = new Publisher(broker, topic);
- for (int i = 0; i < messages; i++)
- {
- publisher.send("Message " + (i + 1));
- }
-
- try
- {
- waitForCompletion(messages, 5000, receivers);
- _logger.info("All receivers received all expected messages");
- }
- finally
- {
- publisher.close();
- for (int i = 0; i < receivers.length; i++)
- {
- receivers[i].close();
- }
- }
- }
-
- public static junit.framework.Test suite()
- {
- return new junit.framework.TestSuite(MultipleConnectionTest.class);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/basic/ObjectMessageTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/basic/ObjectMessageTest.java
deleted file mode 100644
index c8e7368092..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/basic/ObjectMessageTest.java
+++ /dev/null
@@ -1,278 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.basic;
-
-import junit.framework.Assert;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQDestination;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.client.message.JMSObjectMessage;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageListener;
-import javax.jms.MessageNotWriteableException;
-import javax.jms.MessageProducer;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-public class ObjectMessageTest extends QpidBrokerTestCase implements MessageListener
-{
- private static final Logger _logger = LoggerFactory.getLogger(ObjectMessageTest.class);
-
- private AMQConnection _connection;
- private AMQDestination _destination;
- private AMQSession _session;
- private final List<JMSObjectMessage> received = new ArrayList<JMSObjectMessage>();
- private final List<Payload> messages = new ArrayList<Payload>();
- private int _count = 100;
- public String _connectionString = "vm://:1";
-
- protected void setUp() throws Exception
- {
- super.setUp();
- try
- {
- init( (AMQConnection) getConnection("guest", "guest"));
- }
- catch (Exception e)
- {
- fail("Uable to initialise: " + e);
- }
- }
-
- protected void tearDown() throws Exception
- {
- super.tearDown();
- }
-
- private void init(AMQConnection connection) throws Exception
- {
- init(connection, new AMQQueue(connection, randomize("ObjectMessageTest"), true));
- }
-
- private void init(AMQConnection connection, AMQDestination destination) throws Exception
- {
- _connection = connection;
- _destination = destination;
- _session = (AMQSession) connection.createSession(false, AMQSession.NO_ACKNOWLEDGE);
-
- // set up a slow consumer
- _session.createConsumer(destination).setMessageListener(this);
- connection.start();
- }
-
- public void test() throws Exception
- {
- int count = _count;
- send(count);
- waitFor(count);
- check();
- _logger.info("Completed without failure");
- _connection.close();
- }
-
- void send(int count) throws JMSException
- {
- // create a publisher
- MessageProducer producer = _session.createProducer(_destination);
- for (int i = 0; i < count; i++)
- {
- Payload payload = new Payload("Message " + i);
- messages.add(payload);
- producer.send(_session.createObjectMessage(payload));
- }
- }
-
- void waitFor(int count) throws InterruptedException
- {
- synchronized (received)
- {
- long endTime = System.currentTimeMillis() + 30000L;
- while (received.size() < count)
- {
- received.wait(30000);
- if(received.size() < count && System.currentTimeMillis() > endTime)
- {
- throw new RuntimeException("Only received " + received.size() + " messages, was expecting " + count);
- }
- }
- }
- }
-
- void check() throws JMSException
- {
- List<Object> actual = new ArrayList<Object>();
- for (JMSObjectMessage m : received)
- {
- actual.add(m.getObject());
-
- try
- {
- m.setObject("Test text");
- Assert.fail("Message should not be writeable");
- }
- catch (MessageNotWriteableException mnwe)
- {
- // normal execution
- }
-
- m.clearBody();
-
- try
- {
- m.setObject("Test text");
- }
- catch (MessageNotWriteableException mnwe)
- {
- Assert.fail("Message should be writeable");
- }
-
- // Check property write status
- try
- {
- m.setStringProperty("test", "test");
- Assert.fail("Message should not be writeable");
- }
- catch (MessageNotWriteableException mnwe)
- {
- // normal execution
- }
-
- m.clearProperties();
-
- try
- {
- m.setStringProperty("test", "test");
- }
- catch (MessageNotWriteableException mnwe)
- {
- Assert.fail("Message should be writeable");
- }
-
- }
-
- assertEqual(messages.iterator(), actual.iterator());
-
- }
-
- private static void assertEqual(Iterator expected, Iterator actual)
- {
- List<String> errors = new ArrayList<String>();
- while (expected.hasNext() && actual.hasNext())
- {
- try
- {
- assertEqual(expected.next(), actual.next());
- }
- catch (Exception e)
- {
- errors.add(e.getMessage());
- }
- }
- while (expected.hasNext())
- {
- errors.add("Expected " + expected.next() + " but no more actual values.");
- }
- while (actual.hasNext())
- {
- errors.add("Found " + actual.next() + " but no more expected values.");
- }
-
- if (!errors.isEmpty())
- {
- throw new RuntimeException(errors.toString());
- }
- }
-
- private static void assertEqual(Object expected, Object actual)
- {
- if (!expected.equals(actual))
- {
- throw new RuntimeException("Expected '" + expected + "' found '" + actual + "'");
- }
- }
-
- public void onMessage(Message message)
- {
- synchronized (received)
- {
- received.add((JMSObjectMessage) message);
- received.notify();
- }
- }
-
- private static String randomize(String in)
- {
- return in + System.currentTimeMillis();
- }
-
- private static class Payload implements Serializable
- {
- private final String data;
-
- Payload(String data)
- {
- this.data = data;
- }
-
- public int hashCode()
- {
- return data.hashCode();
- }
-
- public boolean equals(Object o)
- {
- return (o instanceof Payload) && ((Payload) o).data.equals(data);
- }
-
- public String toString()
- {
- return "Payload[" + data + "]";
- }
- }
-
- public static void main(String[] argv) throws Exception
- {
- ObjectMessageTest test = new ObjectMessageTest();
- test._connectionString = (argv.length == 0) ? "vm://:1" : argv[0];
- test.setUp();
- if (argv.length > 1)
- {
- test._count = Integer.parseInt(argv[1]);
- }
-
- test.test();
- }
-
- public static junit.framework.Test suite()
- {
- return new junit.framework.TestSuite(ObjectMessageTest.class);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/basic/PropertyValueTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/basic/PropertyValueTest.java
deleted file mode 100644
index 3b8b4946da..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/basic/PropertyValueTest.java
+++ /dev/null
@@ -1,408 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.basic;
-
-import junit.framework.Assert;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.client.AMQDestination;
-import org.apache.qpid.client.message.JMSTextMessage;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.apache.qpid.url.BindingURL;
-import org.apache.qpid.url.AMQBindingURL;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.jms.Connection;
-import javax.jms.Destination;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageFormatException;
-import javax.jms.MessageListener;
-import javax.jms.MessageProducer;
-import javax.jms.Queue;
-import javax.jms.Session;
-
-import java.math.BigDecimal;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.net.URISyntaxException;
-
-import java.lang.reflect.*;
-
-public class PropertyValueTest extends QpidBrokerTestCase implements MessageListener
-{
- private static final Logger _logger = LoggerFactory.getLogger(PropertyValueTest.class);
-
- private int count = 0;
- private AMQConnection _connection;
- private Destination _destination;
- private AMQSession _session;
- private final List<JMSTextMessage> received = new ArrayList<JMSTextMessage>();
- private final List<String> messages = new ArrayList<String>();
- private int _count = 1;
- public String _connectionString = "vm://:1";
- private static final String USERNAME = "guest";
-
- protected void setUp() throws Exception
- {
- super.setUp();
- }
-
- protected void tearDown() throws Exception
- {
- super.tearDown();
- }
-
- private void init(AMQConnection connection) throws Exception
- {
- Destination destination = new AMQQueue(connection, randomize("PropertyValueTest"), true);
- init(connection, destination);
- }
-
- private void init(AMQConnection connection, Destination destination) throws Exception
- {
- _connection = connection;
- _destination = destination;
- _session = (AMQSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- // set up a slow consumer
- _session.createConsumer(destination).setMessageListener(this);
- connection.start();
- }
-
- private Message getTestMessage() throws Exception
- {
- Connection conn = getConnection();
- Session ssn = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
- return ssn.createTextMessage();
- }
-
- public void testGetNonexistent() throws Exception
- {
- Message m = getTestMessage();
- String s = m.getStringProperty("nonexistent");
- assertNull(s);
- }
-
- private static final String[] NAMES = {
- "setBooleanProperty", "setByteProperty", "setShortProperty",
- "setIntProperty", "setLongProperty", "setFloatProperty",
- "setDoubleProperty", "setObjectProperty"
- };
-
- private static final Class[] TYPES = {
- boolean.class, byte.class, short.class, int.class, long.class,
- float.class, double.class, Object.class
- };
-
- private static final Object[] VALUES = {
- true, (byte) 0, (short) 0, 0, (long) 0, (float) 0, (double) 0,
- new Object()
- };
-
- public void testSetEmptyPropertyName() throws Exception
- {
- Message m = getTestMessage();
-
- for (int i = 0; i < NAMES.length; i++)
- {
- Method meth = m.getClass().getMethod(NAMES[i], String.class, TYPES[i]);
- try
- {
- meth.invoke(m, "", VALUES[i]);
- fail("expected illegal argument exception");
- }
- catch (InvocationTargetException e)
- {
- assertEquals(e.getCause().getClass(), IllegalArgumentException.class);
- }
- }
- }
-
- public void testSetDisallowedClass() throws Exception
- {
- Message m = getTestMessage();
- try
- {
- m.setObjectProperty("foo", new Object());
- fail("expected a MessageFormatException");
- }
- catch (MessageFormatException e)
- {
- // pass
- }
- }
-
- public void testOnce()
- {
- runBatch(1);
- }
-
- public void test50()
- {
- runBatch(50);
- }
-
- private void runBatch(int runSize)
- {
- try
- {
- int run = 0;
- while (run < runSize)
- {
- _logger.error("Run Number:" + run++);
- try
- {
- init( (AMQConnection) getConnection("guest", "guest"));
- }
- catch (Exception e)
- {
- _logger.error("exception:", e);
- fail("Unable to initialilse connection: " + e);
- }
-
- int count = _count;
- send(count);
- waitFor(count);
- check();
- _logger.info("Completed without failure");
-
- Thread.sleep(10);
- _connection.close();
-
- _logger.error("End Run Number:" + (run - 1));
- }
- }
- catch (Exception e)
- {
- _logger.error(e.getMessage(), e);
- e.printStackTrace();
- }
- }
-
- void send(int count) throws JMSException
- {
- // create a publisher
- MessageProducer producer = _session.createProducer(_destination);
- for (int i = 0; i < count; i++)
- {
- String text = "Message " + i;
- messages.add(text);
- Message m = _session.createTextMessage(text);
-
- m.setBooleanProperty("Bool", true);
-
- m.setByteProperty("Byte", (byte) Byte.MAX_VALUE);
- m.setDoubleProperty("Double", (double) Double.MAX_VALUE);
- m.setFloatProperty("Float", (float) Float.MAX_VALUE);
- m.setIntProperty("Int", (int) Integer.MAX_VALUE);
-
- m.setJMSCorrelationID("Correlation");
- // fixme the m.setJMSMessage has no effect
- producer.setPriority(8);
- m.setJMSPriority(3);
-
- // Queue
- Queue q;
-
- if ((i / 2) == 0)
- {
- q = _session.createTemporaryQueue();
- }
- else
- {
- q = new AMQQueue(_connection, "TestReply");
- }
-
- m.setJMSReplyTo(q);
- m.setStringProperty("TempQueue", q.toString());
-
- _logger.debug("Message:" + m);
-
- Assert.assertEquals("Check temp queue has been set correctly", m.getJMSReplyTo().toString(),
- m.getStringProperty("TempQueue"));
-
- m.setJMSType("Test");
- m.setLongProperty("UnsignedInt", (long) 4294967295L);
- m.setLongProperty("Long", (long) Long.MAX_VALUE);
-
- m.setShortProperty("Short", (short) Short.MAX_VALUE);
- m.setStringProperty("String", "Test");
-
- _logger.debug("Sending Msg:" + m);
- producer.send(m);
- }
- }
-
- void waitFor(int count) throws InterruptedException
- {
- synchronized (received)
- {
- while (received.size() < count)
- {
- received.wait();
- }
- }
- }
-
- void check() throws JMSException, URISyntaxException
- {
- List<String> actual = new ArrayList<String>();
- for (JMSTextMessage m : received)
- {
- actual.add(m.getText());
-
- // Check Properties
-
- Assert.assertEquals("Check Boolean properties are correctly transported", true, m.getBooleanProperty("Bool"));
- Assert.assertEquals("Check Byte properties are correctly transported", (byte) Byte.MAX_VALUE,
- m.getByteProperty("Byte"));
- Assert.assertEquals("Check Double properties are correctly transported", (double) Double.MAX_VALUE,
- m.getDoubleProperty("Double"));
- Assert.assertEquals("Check Float properties are correctly transported", (float) Float.MAX_VALUE,
- m.getFloatProperty("Float"));
- Assert.assertEquals("Check Int properties are correctly transported", (int) Integer.MAX_VALUE,
- m.getIntProperty("Int"));
- Assert.assertEquals("Check CorrelationID properties are correctly transported", "Correlation",
- m.getJMSCorrelationID());
- Assert.assertEquals("Check Priority properties are correctly transported", 8, m.getJMSPriority());
-
- // Queue
- Assert.assertEquals("Check ReplyTo properties are correctly transported", AMQDestination.createDestination(new AMQBindingURL(m.getStringProperty("TempQueue"))),
- m.getJMSReplyTo());
-
- Assert.assertEquals("Check Type properties are correctly transported", "Test", m.getJMSType());
-
- Assert.assertEquals("Check Short properties are correctly transported", (short) Short.MAX_VALUE,
- m.getShortProperty("Short"));
- Assert.assertEquals("Check UnsignedInt properties are correctly transported", (long) 4294967295L,
- m.getLongProperty("UnsignedInt"));
- Assert.assertEquals("Check Long properties are correctly transported", (long) Long.MAX_VALUE,
- m.getLongProperty("Long"));
- Assert.assertEquals("Check String properties are correctly transported", "Test", m.getStringProperty("String"));
-/*
- // AMQP Tests Specific values
-
- Assert.assertEquals("Check Timestamp properties are correctly transported", m.getStringProperty("time-str"),
- ((AMQMessage) m).getTimestampProperty(new AMQShortString("time")).toString());
-
- // Decimal
- BigDecimal bd = new BigDecimal(Integer.MAX_VALUE);
-
- Assert.assertEquals("Check decimal properties are correctly transported", bd.setScale(Byte.MAX_VALUE),
- ((AMQMessage) m).getDecimalProperty(new AMQShortString("decimal")));
-
- // Void
- ((AMQMessage) m).setVoidProperty(new AMQShortString("void"));
-
- Assert.assertTrue("Check void properties are correctly transported",
- ((AMQMessage) m).getPropertyHeaders().containsKey("void"));
-*/
- //JMSXUserID
- if (m.getStringProperty("JMSXUserID") != null)
- {
- Assert.assertEquals("Check 'JMSXUserID' is supported ", USERNAME,
- m.getStringProperty("JMSXUserID"));
- }
- }
-
- received.clear();
-
- assertEqual(messages.iterator(), actual.iterator());
-
- messages.clear();
- }
-
- private static void assertEqual(Iterator expected, Iterator actual)
- {
- List<String> errors = new ArrayList<String>();
- while (expected.hasNext() && actual.hasNext())
- {
- try
- {
- assertEqual(expected.next(), actual.next());
- }
- catch (Exception e)
- {
- errors.add(e.getMessage());
- }
- }
- while (expected.hasNext())
- {
- errors.add("Expected " + expected.next() + " but no more actual values.");
- }
- while (actual.hasNext())
- {
- errors.add("Found " + actual.next() + " but no more expected values.");
- }
-
- if (!errors.isEmpty())
- {
- throw new RuntimeException(errors.toString());
- }
- }
-
- private static void assertEqual(Object expected, Object actual)
- {
- if (!expected.equals(actual))
- {
- throw new RuntimeException("Expected '" + expected + "' found '" + actual + "'");
- }
- }
-
- public void onMessage(Message message)
- {
- synchronized (received)
- {
- received.add((JMSTextMessage) message);
- received.notify();
- }
- }
-
- private static String randomize(String in)
- {
- return in + System.currentTimeMillis();
- }
-
- public static void main(String[] argv) throws Exception
- {
- PropertyValueTest test = new PropertyValueTest();
- test._connectionString = (argv.length == 0) ? "vm://:1" : argv[0];
- test.setUp();
- if (argv.length > 1)
- {
- test._count = Integer.parseInt(argv[1]);
- }
-
- test.testOnce();
- }
-
- public static junit.framework.Test suite()
- {
- return new junit.framework.TestSuite(PropertyValueTest.class);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/basic/PubSubTwoConnectionTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/basic/PubSubTwoConnectionTest.java
deleted file mode 100644
index c257dacf76..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/basic/PubSubTwoConnectionTest.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.basic;
-
-import javax.jms.Connection;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-import javax.jms.Session;
-import javax.jms.TextMessage;
-import javax.jms.Topic;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.client.AMQTopic;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-/**
- * @author Apache Software Foundation
- */
-public class PubSubTwoConnectionTest extends QpidBrokerTestCase
-{
- protected void setUp() throws Exception
- {
- super.setUp();
- }
-
- protected void tearDown() throws Exception
- {
- super.tearDown();
- }
-
- /**
- * This tests that a consumer is set up synchronously
- * @throws Exception
- */
- public void testTwoConnections() throws Exception
- {
-
- AMQConnection con1 = (AMQConnection) getConnection("guest", "guest");
-
- Topic topic = new AMQTopic(con1, "MyTopic");
-
- Session session1 = con1.createSession(false, AMQSession.NO_ACKNOWLEDGE);
- MessageProducer producer = session1.createProducer(topic);
-
- Connection con2 = (AMQConnection) getConnection("guest", "guest") ;
- Session session2 = con2.createSession(false, AMQSession.NO_ACKNOWLEDGE);
- MessageConsumer consumer = session2.createConsumer(topic);
- con2.start();
- producer.send(session1.createTextMessage("Hello"));
- TextMessage tm1 = (TextMessage) consumer.receive(2000);
- assertNotNull(tm1);
- assertEquals("Hello", tm1.getText());
- con1.close();
- con2.close();
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/basic/ReceiveTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/basic/ReceiveTest.java
deleted file mode 100644
index bc44617620..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/basic/ReceiveTest.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.basic;
-
-import javax.jms.MessageConsumer;
-import javax.jms.Message;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQDestination;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-public class ReceiveTest extends QpidBrokerTestCase
-{
- private AMQConnection _connection;
- private AMQDestination _destination;
- private AMQSession _session;
- private MessageConsumer _consumer;
-
- protected void setUp() throws Exception
- {
- super.setUp();
- init((AMQConnection) getConnection("guest", "guest"));
- }
-
- protected void tearDown() throws Exception
- {
- super.tearDown();
- }
-
- private void init(AMQConnection connection) throws Exception
- {
- init(connection, new AMQQueue(connection,"ReceiveTest", true));
- }
-
- private void init(AMQConnection connection, AMQDestination destination) throws Exception
- {
- _connection = connection;
- _destination = destination;
- _session = (AMQSession) connection.createSession(true, AMQSession.NO_ACKNOWLEDGE);
- _consumer = _session.createConsumer(_destination);
- _connection.start();
- }
-
- public void test() throws Exception
- {
- Message m = _consumer.receive(5000);
- assertNull("should not have received a message", m);
- _connection.close();
- }
-
-
- public static junit.framework.Test suite()
- {
- // TODO: note that this test doesn't use the VMBrokerSetup
- // test helper class to create and tear down its
- // VMBroker. This is because the main() above seems to
- // indicate that it's also used outside of the surefire test
- // framework. If it isn't, then this test should also be
- // changed to use VMBrokerSetup here.
- return new junit.framework.TestSuite(ReceiveTest.class);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/basic/SessionStartTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/basic/SessionStartTest.java
deleted file mode 100644
index ee837fd41a..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/basic/SessionStartTest.java
+++ /dev/null
@@ -1,115 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.basic;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQDestination;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageListener;
-
-public class SessionStartTest extends QpidBrokerTestCase implements MessageListener
-{
- private static final Logger _logger = LoggerFactory.getLogger(SessionStartTest.class);
-
- private AMQConnection _connection;
- private AMQDestination _destination;
- private AMQSession _session;
- private int count;
- public String _connectionString = "vm://:1";
-
- protected void setUp() throws Exception
- {
- super.setUp();
- init((AMQConnection) getConnection("guest", "guest"));
- }
-
- protected void tearDown() throws Exception
- {
- super.tearDown();
- }
-
- private void init(AMQConnection connection) throws Exception
- {
- init(connection,
- new AMQQueue(connection.getDefaultQueueExchangeName(), new AMQShortString(randomize("SessionStartTest")), true));
- }
-
- private void init(AMQConnection connection, AMQDestination destination) throws Exception
- {
- _connection = connection;
- _destination = destination;
- connection.start();
-
- _session = (AMQSession) connection.createSession(false, AMQSession.NO_ACKNOWLEDGE);
- _session.createConsumer(destination).setMessageListener(this);
- }
-
- public synchronized void test() throws JMSException, InterruptedException
- {
- try
- {
- _session.createProducer(_destination).send(_session.createTextMessage("Message"));
- _logger.info("Message sent, waiting for response...");
- wait(1000);
- if (count > 0)
- {
- _logger.info("Got message");
- }
- else
- {
- throw new RuntimeException("Did not get message!");
- }
- }
- finally
- {
- _session.close();
- _connection.close();
- }
- }
-
- public synchronized void onMessage(Message message)
- {
- count++;
- notify();
- }
-
- private static String randomize(String in)
- {
- return in + System.currentTimeMillis();
- }
-
- public static void main(String[] argv) throws Exception
- {
- SessionStartTest test = new SessionStartTest();
- test._connectionString = (argv.length == 0) ? "localhost:5672" : argv[0];
- test.setUp();
- test.test();
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/basic/TextMessageTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/basic/TextMessageTest.java
deleted file mode 100644
index a87de8ac0c..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/basic/TextMessageTest.java
+++ /dev/null
@@ -1,248 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.basic;
-
-import junit.framework.Assert;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.client.message.JMSTextMessage;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.jms.Destination;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageListener;
-import javax.jms.MessageNotWriteableException;
-import javax.jms.MessageProducer;
-import javax.jms.Session;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-public class TextMessageTest extends QpidBrokerTestCase implements MessageListener
-{
- private static final Logger _logger = LoggerFactory.getLogger(TextMessageTest.class);
-
- private AMQConnection _connection;
- private Destination _destination;
- private AMQSession _session;
- private final List<JMSTextMessage> received = new ArrayList<JMSTextMessage>();
- private final List<String> messages = new ArrayList<String>();
- private int _count = 100;
- public String _connectionString = "vm://:1";
- private CountDownLatch _waitForCompletion;
-
- protected void setUp() throws Exception
- {
- super.setUp();
- try
- {
- init((AMQConnection) getConnection("guest", "guest"));
- }
- catch (Exception e)
- {
- fail("Unable to initialilse connection: " + e);
- }
- }
-
- protected void tearDown() throws Exception
- {
- super.tearDown();
- }
-
- private void init(AMQConnection connection) throws Exception
- {
- Destination destination =
- new AMQQueue(connection.getDefaultQueueExchangeName(), new AMQShortString(randomize("TextMessageTest")), true);
- init(connection, destination);
- }
-
- private void init(AMQConnection connection, Destination destination) throws Exception
- {
- _connection = connection;
- _destination = destination;
- _session = (AMQSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- // set up a slow consumer
- try
- {
- _session.createConsumer(destination).setMessageListener(this);
- }
- catch (Throwable e)
- {
- e.printStackTrace();
- }
- connection.start();
- }
-
- public void test() throws Exception
- {
- int count = _count;
- _waitForCompletion = new CountDownLatch(_count);
- send(count);
- _waitForCompletion.await(20, TimeUnit.SECONDS);
- check();
- _logger.info("Completed without failure");
- _connection.close();
- }
-
- void send(int count) throws JMSException
- {
- // create a publisher
- MessageProducer producer = _session.createProducer(_destination);
- for (int i = 0; i < count; i++)
- {
- String text = "Message " + i;
- messages.add(text);
- Message m = _session.createTextMessage(text);
- //m.setStringProperty("String", "hello");
-
- _logger.info("Sending Msg:" + m);
- producer.send(m);
- }
- _logger.info("sent " + count + " mesages");
- }
-
-
- void check() throws JMSException
- {
- List<String> actual = new ArrayList<String>();
- for (JMSTextMessage m : received)
- {
- actual.add(m.getText());
-
- // Check body write status
- try
- {
- m.setText("Test text");
- Assert.fail("Message should not be writeable");
- }
- catch (MessageNotWriteableException mnwe)
- {
- // normal execution
- }
-
- m.clearBody();
-
- try
- {
- m.setText("Test text");
- }
- catch (MessageNotWriteableException mnwe)
- {
- Assert.fail("Message should be writeable");
- }
-
- // Check property write status
- try
- {
- m.setStringProperty("test", "test");
- Assert.fail("Message should not be writeable");
- }
- catch (MessageNotWriteableException mnwe)
- {
- // normal execution
- }
-
- m.clearProperties();
-
- try
- {
- m.setStringProperty("test", "test");
- }
- catch (MessageNotWriteableException mnwe)
- {
- Assert.fail("Message should be writeable");
- }
-
- }
-
- assertEqual(messages.iterator(), actual.iterator());
- }
-
- private static void assertEqual(Iterator expected, Iterator actual)
- {
- List<String> errors = new ArrayList<String>();
- while (expected.hasNext() && actual.hasNext())
- {
- try
- {
- assertEqual(expected.next(), actual.next());
- }
- catch (Exception e)
- {
- errors.add(e.getMessage());
- }
- }
- while (expected.hasNext())
- {
- errors.add("Expected " + expected.next() + " but no more actual values.");
- }
- while (actual.hasNext())
- {
- errors.add("Found " + actual.next() + " but no more expected values.");
- }
-
- if (!errors.isEmpty())
- {
- throw new RuntimeException(errors.toString());
- }
- }
-
- private static void assertEqual(Object expected, Object actual)
- {
- if (!expected.equals(actual))
- {
- throw new RuntimeException("Expected '" + expected + "' found '" + actual + "'");
- }
- }
-
- public void onMessage(Message message)
- {
- synchronized (received)
- {
- _logger.info("===== received one message");
- received.add((JMSTextMessage) message);
- _waitForCompletion.countDown();
- }
- }
-
- private static String randomize(String in)
- {
- return in + System.currentTimeMillis();
- }
-
-
-
- public static junit.framework.Test suite()
- {
- return new junit.framework.TestSuite(TextMessageTest.class);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/basic/close/CloseTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/basic/close/CloseTest.java
deleted file mode 100644
index c6b8069300..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/basic/close/CloseTest.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- *
- */
-package org.apache.qpid.test.unit.basic.close;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.url.AMQBindingURL;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-import javax.jms.Session;
-
-public class CloseTest extends QpidBrokerTestCase
-{
- private static final Logger _logger = LoggerFactory.getLogger(CloseTest.class);
-
- public void testCloseQueueReceiver() throws Exception
- {
- AMQConnection connection = (AMQConnection) getConnection("guest", "guest");
-
- Session session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
-
- AMQQueue queue = new AMQQueue(new AMQBindingURL("test-queue"));
- MessageConsumer consumer = session.createConsumer(queue);
-
- MessageProducer producer_not_used_but_created_for_testing = session.createProducer(queue);
-
- connection.start();
-
- _logger.info("About to close consumer");
-
- consumer.close();
-
- _logger.info("Closed Consumer");
- connection.close();
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/client/AMQConnectionTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/client/AMQConnectionTest.java
deleted file mode 100644
index 292bcd6039..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/client/AMQConnectionTest.java
+++ /dev/null
@@ -1,405 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.client;
-
-import java.io.BufferedReader;
-import java.io.BufferedWriter;
-import java.io.InputStreamReader;
-import java.io.LineNumberReader;
-import java.io.OutputStreamWriter;
-import java.io.PrintWriter;
-import java.util.Map;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import javax.jms.Connection;
-import javax.jms.ExceptionListener;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-import javax.jms.QueueSession;
-import javax.jms.Session;
-import javax.jms.TextMessage;
-import javax.jms.TopicSession;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQConnectionDelegate_0_10;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.client.AMQTopic;
-import org.apache.qpid.configuration.ClientProperties;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class AMQConnectionTest extends QpidBrokerTestCase
-{
- private static AMQConnection _connection;
- private static AMQTopic _topic;
- private static AMQQueue _queue;
- private static QueueSession _queueSession;
- private static TopicSession _topicSession;
- protected static final Logger _logger = LoggerFactory.getLogger(AMQConnectionTest.class);
-
- protected void setUp() throws Exception
- {
- super.setUp();
- _connection = (AMQConnection) getConnection("guest", "guest");
- _topic = new AMQTopic(_connection.getDefaultTopicExchangeName(), new AMQShortString("mytopic"));
- _queue = new AMQQueue(_connection.getDefaultQueueExchangeName(), new AMQShortString("myqueue"));
- }
-
- protected void tearDown() throws Exception
- {
- _connection.close();
- super.tearDown();
- }
-
- /**
- * Simple tests to check we can create TopicSession and QueueSession ok
- * And that they throw exceptions where appropriate as per JMS spec
- */
-
- public void testCreateQueueSession() throws JMSException
- {
- _queueSession = _connection.createQueueSession(false, AMQSession.NO_ACKNOWLEDGE);
- }
-
- public void testCreateTopicSession() throws JMSException
- {
- _topicSession = _connection.createTopicSession(false, AMQSession.NO_ACKNOWLEDGE);
- }
-
- public void testTopicSessionCreateBrowser() throws JMSException
- {
- try
- {
- _topicSession.createBrowser(_queue);
- fail("expected exception did not occur");
- }
- catch (javax.jms.IllegalStateException s)
- {
- // ok
- }
- catch (Exception e)
- {
- fail("expected javax.jms.IllegalStateException, got " + e);
- }
- }
-
- public void testTopicSessionCreateQueue() throws JMSException
- {
- try
- {
- _topicSession.createQueue("abc");
- fail("expected exception did not occur");
- }
- catch (javax.jms.IllegalStateException s)
- {
- // ok
- }
- catch (Exception e)
- {
- fail("expected javax.jms.IllegalStateException, got " + e);
- }
- }
-
- public void testTopicSessionCreateTemporaryQueue() throws JMSException
- {
- try
- {
- _topicSession.createTemporaryQueue();
- fail("expected exception did not occur");
- }
- catch (javax.jms.IllegalStateException s)
- {
- // ok
- }
- catch (Exception e)
- {
- fail("expected javax.jms.IllegalStateException, got " + e);
- }
- }
-
- public void testQueueSessionCreateTemporaryTopic() throws JMSException
- {
- try
- {
- _queueSession.createTemporaryTopic();
- fail("expected exception did not occur");
- }
- catch (javax.jms.IllegalStateException s)
- {
- // ok
- }
- catch (Exception e)
- {
- fail("expected javax.jms.IllegalStateException, got " + e);
- }
- }
-
- public void testQueueSessionCreateTopic() throws JMSException
- {
- try
- {
- _queueSession.createTopic("abc");
- fail("expected exception did not occur");
- }
- catch (javax.jms.IllegalStateException s)
- {
- // ok
- }
- catch (Exception e)
- {
- fail("expected javax.jms.IllegalStateException, got " + e);
- }
- }
-
- public void testQueueSessionDurableSubscriber() throws JMSException
- {
- try
- {
- _queueSession.createDurableSubscriber(_topic, "abc");
- fail("expected exception did not occur");
- }
- catch (javax.jms.IllegalStateException s)
- {
- // ok
- }
- catch (Exception e)
- {
- fail("expected javax.jms.IllegalStateException, got " + e);
- }
- }
-
- public void testQueueSessionUnsubscribe() throws JMSException
- {
- try
- {
- _queueSession.unsubscribe("abc");
- fail("expected exception did not occur");
- }
- catch (javax.jms.IllegalStateException s)
- {
- // ok
- }
- catch (Exception e)
- {
- fail("expected javax.jms.IllegalStateException, got " + e);
- }
- }
-
- public void testPrefetchSystemProperty() throws Exception
- {
- String oldPrefetch = System.getProperty(ClientProperties.MAX_PREFETCH_PROP_NAME);
- try
- {
- _connection.close();
- System.setProperty(ClientProperties.MAX_PREFETCH_PROP_NAME, new Integer(2).toString());
- _connection = (AMQConnection) getConnection();
- _connection.start();
- // Create two consumers on different sessions
- Session consSessA = _connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
- MessageConsumer consumerA = consSessA.createConsumer(_queue);
-
- Session producerSession = _connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- MessageProducer producer = producerSession.createProducer(_queue);
-
- // Send 3 messages
- for (int i = 0; i < 3; i++)
- {
- producer.send(producerSession.createTextMessage("test"));
- }
-
- MessageConsumer consumerB = null;
- if (isBroker08())
- {
- Session consSessB = _connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
- consumerB = consSessB.createConsumer(_queue);
- }
- else
- {
- consumerB = consSessA.createConsumer(_queue);
- }
-
- Message msg;
- // Check that consumer A has 2 messages
- for (int i = 0; i < 2; i++)
- {
- msg = consumerA.receive(1500);
- assertNotNull("Consumer A should receive 2 messages",msg);
- }
-
- msg = consumerA.receive(1500);
- assertNull("Consumer A should not have received a 3rd message",msg);
-
- // Check that consumer B has the last message
- msg = consumerB.receive(1500);
- assertNotNull("Consumer B should have received the message",msg);
- }
- finally
- {
- if (oldPrefetch == null)
- {
- oldPrefetch = ClientProperties.MAX_PREFETCH_DEFAULT;
- }
- System.setProperty(ClientProperties.MAX_PREFETCH_PROP_NAME, oldPrefetch);
- }
- }
-
- public void testGetChannelID() throws Exception
- {
- long maxChannelID = _connection.getMaximumChannelCount();
- if (isBroker010())
- {
- //Usable numbers are 0 to N-1 when using 0-10
- //and 1 to N for 0-8/0-9
- maxChannelID = maxChannelID-1;
- }
- for (int j = 0; j < 3; j++)
- {
- int i = isBroker010() ? 0 : 1;
- for ( ; i <= maxChannelID; i++)
- {
- int id = _connection.getNextChannelID();
- assertEquals("Unexpected number on iteration "+j, i, id);
- _connection.deregisterSession(id);
- }
- }
- }
-
- /**
- * Test Strategy : Kill -STOP the broker and see
- * if the client terminates the connection with a
- * read timeout.
- * The broker process is cleaned up in the test itself
- * and avoids using process.waitFor() as it hangs.
- */
- public void testHeartBeat() throws Exception
- {
- boolean windows =
- ((String) System.getProperties().get("os.name")).matches("(?i).*windows.*");
-
- if (!isCppBroker() || windows)
- {
- return;
- }
-
- Process process = null;
- int port = getPort(0);
- String pid = null;
- try
- {
- // close the connection and shutdown the broker started by QpidTest
- _connection.close();
- stopBroker(port);
-
- System.setProperty("qpid.heartbeat", "1");
-
- // in case this broker gets stuck, atleast the rest of the tests will not fail.
- port = port + 200;
- String startCmd = getBrokerCommand(port);
-
- // start a broker using a script
- ProcessBuilder pb = new ProcessBuilder(System.getProperty("broker.start"));
- pb.redirectErrorStream(true);
-
- Map<String, String> env = pb.environment();
- env.put("BROKER_CMD",startCmd);
- env.put("BROKER_READY",System.getProperty(BROKER_READY));
-
- Process startScript = pb.start();
- startScript.waitFor();
- startScript.destroy();
-
- Connection con =
- new AMQConnection("amqp://guest:guest@clientid/testpath?brokerlist='tcp://localhost:" + port + "'");
- final AtomicBoolean lock = new AtomicBoolean(false);
-
- String cmd = "/usr/bin/pgrep -f " + port;
- process = Runtime.getRuntime().exec("/bin/bash");
- LineNumberReader reader = new LineNumberReader(new InputStreamReader(process.getInputStream()));
- PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(process.getOutputStream())), true);
- out.println(cmd);
- pid = reader.readLine();
- try
- {
- Integer.parseInt(pid);
- }
- catch (NumberFormatException e)
- {
- // Error! try to read further to gather the error msg.
- String line;
- _logger.debug(pid);
- while ((line = reader.readLine()) != null )
- {
- _logger.debug(line);
- }
- throw new Exception( "Unable to get the brokers pid " + pid);
- }
- _logger.debug("pid : " + pid);
-
- con.setExceptionListener(new ExceptionListener(){
-
- public void onException(JMSException e)
- {
- synchronized(lock) {
- lock.set(true);
- lock.notifyAll();
- }
- }
- });
-
- out.println("kill -STOP " + pid);
-
- synchronized(lock){
- lock.wait(2500);
- }
- out.close();
- reader.close();
- assertTrue("Client did not terminate the connection, check log for details",lock.get());
- }
- catch(Exception e)
- {
- throw e;
- }
- finally
- {
- System.setProperty("qpid.heartbeat", "");
-
- if (process != null)
- {
- process.destroy();
- }
-
- Process killScript = Runtime.getRuntime().exec(System.getProperty("broker.kill") + " " + pid);
- killScript.waitFor();
- killScript.destroy();
- cleanBroker();
- }
- }
-
- public static junit.framework.Test suite()
- {
- return new junit.framework.TestSuite(AMQConnectionTest.class);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/client/AMQSessionTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/client/AMQSessionTest.java
deleted file mode 100644
index 93cceb1048..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/client/AMQSessionTest.java
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.client;
-
-import javax.jms.JMSException;
-import javax.jms.QueueReceiver;
-import javax.jms.TopicSubscriber;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.client.AMQTopic;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-/**
- * Tests for QueueReceiver and TopicSubscriber creation methods on AMQSession
- */
-public class AMQSessionTest extends QpidBrokerTestCase
-{
-
- private static AMQSession _session;
- private static AMQTopic _topic;
- private static AMQQueue _queue;
- private static AMQConnection _connection;
-
- protected void setUp() throws Exception
- {
- super.setUp();
- _connection = (AMQConnection) getConnection("guest", "guest");
- _topic = new AMQTopic(_connection,"mytopic");
- _queue = new AMQQueue(_connection,"myqueue");
- _session = (AMQSession) _connection.createSession(false, AMQSession.NO_ACKNOWLEDGE);
- }
-
- protected void tearDown() throws Exception
- {
- try
- {
- _connection.close();
- }
- catch (JMSException e)
- {
- //just close
- }
- super.tearDown();
- }
-
- public void testCreateSubscriber() throws JMSException
- {
- TopicSubscriber subscriber = _session.createSubscriber(_topic);
- assertEquals("Topic names should match from TopicSubscriber", _topic.getTopicName(), subscriber.getTopic().getTopicName());
-
- subscriber = _session.createSubscriber(_topic, "abc", false);
- assertEquals("Topic names should match from TopicSubscriber with selector", _topic.getTopicName(), subscriber.getTopic().getTopicName());
- }
-
- public void testCreateDurableSubscriber() throws JMSException
- {
- TopicSubscriber subscriber = _session.createDurableSubscriber(_topic, "mysubname");
- assertEquals("Topic names should match from durable TopicSubscriber", _topic.getTopicName(), subscriber.getTopic().getTopicName());
-
- subscriber = _session.createDurableSubscriber(_topic, "mysubname2", "abc", false);
- assertEquals("Topic names should match from durable TopicSubscriber with selector", _topic.getTopicName(), subscriber.getTopic().getTopicName());
- _session.unsubscribe("mysubname");
- _session.unsubscribe("mysubname2");
- }
-
- public void testCreateQueueReceiver() throws JMSException
- {
- QueueReceiver receiver = _session.createQueueReceiver(_queue);
- assertEquals("Queue names should match from QueueReceiver", _queue.getQueueName(), receiver.getQueue().getQueueName());
-
- receiver = _session.createQueueReceiver(_queue, "abc");
- assertEquals("Queue names should match from QueueReceiver with selector", _queue.getQueueName(), receiver.getQueue().getQueueName());
- }
-
- public void testCreateReceiver() throws JMSException
- {
- QueueReceiver receiver = _session.createReceiver(_queue);
- assertEquals("Queue names should match from QueueReceiver", _queue.getQueueName(), receiver.getQueue().getQueueName());
-
- receiver = _session.createReceiver(_queue, "abc");
- assertEquals("Queue names should match from QueueReceiver with selector", _queue.getQueueName(), receiver.getQueue().getQueueName());
- }
-
- public static void stopVmBrokers()
- {
- _queue = null;
- _topic = null;
- _session = null;
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/client/DynamicQueueExchangeCreateTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/client/DynamicQueueExchangeCreateTest.java
deleted file mode 100644
index 8577fb5b6a..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/client/DynamicQueueExchangeCreateTest.java
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.client;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.protocol.AMQConstant;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-import javax.jms.Connection;
-import javax.jms.JMSException;
-import javax.jms.Queue;
-import javax.jms.Session;
-
-/**
- * QPID-155
- *
- * Test to validate that setting the respective qpid.declare_queues,
- * qpid.declare_exchanges system properties functions as expected.
- */
-public class DynamicQueueExchangeCreateTest extends QpidBrokerTestCase
-{
- public void testQueueDeclare() throws Exception
- {
- setSystemProperty("qpid.declare_queues", "false");
-
- Connection connection = getConnection();
-
- Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- Queue queue = session.createQueue(getTestQueueName());
-
- try
- {
- session.createConsumer(queue);
- fail("JMSException should be thrown as the queue does not exist");
- }
- catch (JMSException e)
- {
- checkExceptionErrorCode(e, AMQConstant.NOT_FOUND);
- }
- }
-
- public void testExchangeDeclare() throws Exception
- {
- setSystemProperty("qpid.declare_exchanges", "false");
-
- Connection connection = getConnection();
-
- Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- String EXCHANGE_TYPE = "test.direct";
- Queue queue = session.createQueue("direct://" + EXCHANGE_TYPE + "/queue/queue");
-
- try
- {
- session.createConsumer(queue);
- fail("JMSException should be thrown as the exchange does not exist");
- }
- catch (JMSException e)
- {
- checkExceptionErrorCode(e, AMQConstant.NOT_FOUND);
- }
- }
-
- private void checkExceptionErrorCode(JMSException original, AMQConstant code)
- {
- Exception linked = original.getLinkedException();
- assertNotNull("Linked exception should have been set", linked);
- assertTrue("Linked exception should be an AMQException", linked instanceof AMQException);
- assertEquals("Error code should be " + code.getCode(), code, ((AMQException) linked).getErrorCode());
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/client/channelclose/ChannelCloseOkTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/client/channelclose/ChannelCloseOkTest.java
deleted file mode 100644
index 79e2ff8148..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/client/channelclose/ChannelCloseOkTest.java
+++ /dev/null
@@ -1,239 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.client.channelclose;
-
-import junit.textui.TestRunner;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.client.transport.TransportConnection;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.jms.Destination;
-import javax.jms.ExceptionListener;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageListener;
-import javax.jms.MessageProducer;
-import javax.jms.Session;
-import javax.jms.TextMessage;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Due to bizarre exception handling all sessions are closed if you get
- * a channel close request and no exception listener is registered.
- * <p/>
- * JIRA issue IBTBLZ-10.
- * <p/>
- * Simulate by:
- * <p/>
- * 0. Create two sessions with no exception listener.
- * 1. Publish message to queue/topic that does not exist (wrong routing key).
- * 2. This will cause a channel close.
- * 3. Since client does not have an exception listener, currently all sessions are
- * closed.
- */
-public class ChannelCloseOkTest extends QpidBrokerTestCase
-{
- private AMQConnection _connection;
- private Destination _destination1;
- private Destination _destination2;
- private Session _session1;
- private Session _session2;
- private final List<Message> _received1 = new ArrayList<Message>();
- private final List<Message> _received2 = new ArrayList<Message>();
-
- private static final Logger _log = LoggerFactory.getLogger(ChannelCloseOkTest.class);
-
- protected void setUp() throws Exception
- {
- super.setUp();
-
- _connection = (AMQConnection) getConnection("guest", "guest");
-
- _destination1 = new AMQQueue(_connection, "q1", true);
- _destination2 = new AMQQueue(_connection, "q2", true);
- _session1 = _connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- _session1.createConsumer(_destination1).setMessageListener(new MessageListener()
- {
- public void onMessage(Message message)
- {
- _log.debug("consumer 1 got message [" + getTextMessage(message) + "]");
- synchronized (_received1)
- {
- _received1.add(message);
- _received1.notify();
- }
- }
- });
- _session2 = _connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- _session2.createConsumer(_destination2).setMessageListener(new MessageListener()
- {
- public void onMessage(Message message)
- {
- _log.debug("consumer 2 got message [" + getTextMessage(message) + "]");
- synchronized (_received2)
- {
- _received2.add(message);
- _received2.notify();
- }
- }
- });
-
- _connection.start();
- }
-
- private String getTextMessage(Message message)
- {
- TextMessage tm = (TextMessage) message;
- try
- {
- return tm.getText();
- }
- catch (JMSException e)
- {
- return "oops " + e;
- }
- }
-
- protected void tearDown() throws Exception
- {
- closeConnection();
- super.tearDown();
- }
-
- public void closeConnection() throws JMSException
- {
- if (_connection != null)
- {
- _log.info(">>>>>>>>>>>>>>.. closing");
- _connection.close();
- }
- }
-
- public void testWithoutExceptionListener() throws Exception
- {
- doTest();
- }
-
- public void testWithExceptionListener() throws Exception
- {
- _connection.setExceptionListener(new ExceptionListener()
- {
- public void onException(JMSException jmsException)
- {
- _log.warn("onException - " + jmsException.getMessage());
- }
- });
-
- doTest();
- }
-
- public void doTest() throws Exception
- {
- // Check both sessions are ok.
- sendAndWait(_session1, _destination1, "first", _received1, 1);
- sendAndWait(_session2, _destination2, "second", _received2, 1);
- assertEquals(1, _received1.size());
- assertEquals(1, _received2.size());
-
- // Now send message to incorrect destination on session 1.
- Destination destination = new AMQQueue(_connection, "incorrect");
- send(_session1, destination, "third"); // no point waiting as message will never be received.
-
- // Ensure both sessions are still ok.
- // Send a bunch of messages as this give time for the sessions to be erroneously closed.
- final int num = 300;
- for (int i = 0; i < num; ++i)
- {
- send(_session1, _destination1, "" + i);
- send(_session2, _destination2, "" + i);
- }
-
- waitFor(_received1, num + 1);
- waitFor(_received2, num + 1);
-
- // Note that the third message is never received as it is sent to an incorrect destination.
- assertEquals(num + 1, _received1.size());
- assertEquals(num + 1, _received2.size());
- }
-
- private void sendAndWait(Session session, Destination destination, String message, List<Message> received, int count)
- throws JMSException, InterruptedException
- {
- send(session, destination, message);
- waitFor(received, count);
- }
-
- private void send(Session session, Destination destination, String message) throws JMSException
- {
- _log.debug("sending message " + message);
- MessageProducer producer1 = session.createProducer(destination);
- producer1.send(session.createTextMessage(message));
- }
-
- private void waitFor(List<Message> received, int count) throws InterruptedException
- {
- long timeout = 20000;
-
- synchronized (received)
- {
- long start = System.currentTimeMillis();
- while (received.size() < count)
- {
- if (System.currentTimeMillis() - start > timeout)
- {
- fail("timeout expired waiting for messages");
- }
- try
- {
- received.wait(timeout);
- }
- catch (InterruptedException e)
- {
- _log.info("Interrupted: " + e);
- throw e;
- }
-
- }
- }
- }
-
- private static String randomize(String in)
- {
- return in + System.currentTimeMillis();
- }
-
- public static void main(String[] args)
- {
- TestRunner.run(ChannelCloseOkTest.class);
- }
-
- public static junit.framework.Test suite()
- {
- return new junit.framework.TestSuite(ChannelCloseOkTest.class);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/client/channelclose/ChannelCloseTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/client/channelclose/ChannelCloseTest.java
deleted file mode 100644
index b6232b1734..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/client/channelclose/ChannelCloseTest.java
+++ /dev/null
@@ -1,394 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- *
- */
-package org.apache.qpid.test.unit.client.channelclose;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.failover.FailoverException;
-import org.apache.qpid.client.protocol.AMQProtocolHandler;
-import org.apache.qpid.client.transport.TransportConnection;
-import org.apache.qpid.framing.*;
-import org.apache.qpid.jms.ConnectionListener;
-import org.apache.qpid.protocol.AMQConstant;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.jms.Connection;
-import javax.jms.ExceptionListener;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-import javax.jms.Queue;
-import javax.jms.Session;
-import javax.jms.TextMessage;
-
-public class ChannelCloseTest extends QpidBrokerTestCase implements ExceptionListener, ConnectionListener
-{
- private static final Logger _logger = LoggerFactory.getLogger(ChannelCloseTest.class);
-
- Connection _connection;
- private Session _session;
- private static final long SYNC_TIMEOUT = 500;
- private int TEST = 0;
-
- /**
- * Close channel, use chanel with same id ensure error.
- *
- * This test is only valid for non 0-10 connection .
- */
- public void testReusingChannelAfterFullClosure() throws Exception
- {
- _connection=newConnection();
-
- // Create Producer
- try
- {
- _connection.start();
-
- createChannelAndTest(1);
-
- // Cause it to close
- try
- {
- _logger.info("Testing invalid exchange");
- declareExchange(1, "", "name_that_will_lookup_to_null", false);
- fail("Exchange name is empty so this should fail ");
- }
- catch (AMQException e)
- {
- assertEquals("Exchange should not be found", AMQConstant.NOT_FOUND, e.getErrorCode());
- }
-
- // Check that
- try
- {
- _logger.info("Testing valid exchange should fail");
- declareExchange(1, "topic", "amq.topic", false);
- fail("This should not succeed as the channel should be closed ");
- }
- catch (AMQException e)
- {
- if (_logger.isInfoEnabled())
- {
- _logger.info("Exception occured was:" + e.getErrorCode());
- }
-
- assertEquals("Connection should be closed", AMQConstant.CHANNEL_ERROR, e.getErrorCode());
-
- _connection=newConnection();
- }
-
- checkSendingMessage();
-
- _session.close();
- _connection.close();
-
- }
- catch (JMSException e)
- {
- e.printStackTrace();
- fail(e.getMessage());
- }
- }
-
- /*
- close channel and send guff then send ok no errors
- REMOVE TEST - The behaviour after server has sent close is undefined.
- the server should be free to fail as it may wish to reclaim its resources
- immediately after close.
- */
- /*public void testSendingMethodsAfterClose() throws Exception
- {
- // this is testing an 0.8 connection
- if(isBroker08())
- {
- try
- {
- _connection=new AMQConnection("amqp://guest:guest@CCTTest/test?brokerlist='" + _brokerlist + "'");
-
- ((AMQConnection) _connection).setConnectionListener(this);
-
- _connection.setExceptionListener(this);
-
- // Change the StateManager for one that doesn't respond with Close-OKs
- AMQStateManager oldStateManager=((AMQConnection) _connection).getProtocolHandler().getStateManager();
-
- _session=_connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
-
- _connection.start();
-
- // Test connection
- checkSendingMessage();
-
- // Set StateManager to manager that ignores Close-oks
- AMQProtocolSession protocolSession=
- ((AMQConnection) _connection).getProtocolHandler().getProtocolSession();
-
- MethodDispatcher d = protocolSession.getMethodDispatcher();
-
- MethodDispatcher wrappedDispatcher = (MethodDispatcher)
- Proxy.newProxyInstance(d.getClass().getClassLoader(),
- d.getClass().getInterfaces(),
- new MethodDispatcherProxyHandler(
- (ClientMethodDispatcherImpl) d));
-
- protocolSession.setMethodDispatcher(wrappedDispatcher);
-
-
- AMQStateManager newStateManager=new NoCloseOKStateManager(protocolSession);
- newStateManager.changeState(oldStateManager.getCurrentState());
-
- ((AMQConnection) _connection).getProtocolHandler().setStateManager(newStateManager);
-
- final int TEST_CHANNEL=1;
- _logger.info("Testing Channel(" + TEST_CHANNEL + ") Creation");
-
- createChannelAndTest(TEST_CHANNEL);
-
- // Cause it to close
- try
- {
- _logger.info("Closing Channel - invalid exchange");
- declareExchange(TEST_CHANNEL, "", "name_that_will_lookup_to_null", false);
- fail("Exchange name is empty so this should fail ");
- }
- catch (AMQException e)
- {
- assertEquals("Exchange should not be found", AMQConstant.NOT_FOUND, e.getErrorCode());
- }
-
- try
- {
- // Send other methods that should be ignored
- // send them no wait as server will ignore them
- _logger.info("Tested known exchange - should ignore");
- declareExchange(TEST_CHANNEL, "topic", "amq.topic", true);
-
- _logger.info("Tested known invalid exchange - should ignore");
- declareExchange(TEST_CHANNEL, "", "name_that_will_lookup_to_null", true);
-
- _logger.info("Tested known invalid exchange - should ignore");
- declareExchange(TEST_CHANNEL, "", "name_that_will_lookup_to_null", true);
-
- // Send sync .. server will igore and timy oue
- _logger.info("Tested known invalid exchange - should ignore");
- declareExchange(TEST_CHANNEL, "", "name_that_will_lookup_to_null", false);
- }
- catch (AMQTimeoutException te)
- {
- assertEquals("Request should timeout", AMQConstant.REQUEST_TIMEOUT, te.getErrorCode());
- }
- catch (AMQException e)
- {
- fail("This should not fail as all requests should be ignored");
- }
-
- _logger.info("Sending Close");
- // Send Close-ok
- sendClose(TEST_CHANNEL);
-
- _logger.info("Re-opening channel");
-
- createChannelAndTest(TEST_CHANNEL);
-
- // Test connection is still ok
-
- checkSendingMessage();
-
- }
- catch (JMSException e)
- {
- e.printStackTrace();
- fail(e.getMessage());
- }
- catch (AMQException e)
- {
- fail(e.getMessage());
-
- }
- catch (URLSyntaxException e)
- {
- fail(e.getMessage());
- }
- finally
- {
- try
- {
- _session.close();
- _connection.close();
- }
- catch (JMSException e)
- {
- e.printStackTrace();
- fail(e.getMessage());
- }
- }
- }
- }
-*/
- private void createChannelAndTest(int channel) throws FailoverException
- {
- // Create A channel
- try
- {
- createChannel(channel);
- }
- catch (AMQException e)
- {
- fail(e.getMessage());
- }
-
- // Test it is ok
- try
- {
- declareExchange(channel, "topic", "amq.topic", false);
- _logger.info("Tested known exchange");
- }
- catch (AMQException e)
- {
- fail("This should not fail as this is the default exchange details");
- }
- }
-
- private void sendClose(int channel)
- {
- ChannelCloseOkBody body =
- ((AMQConnection) _connection).getProtocolHandler().getMethodRegistry().createChannelCloseOkBody();
- AMQFrame frame = body.generateFrame(channel);
-
- ((AMQConnection) _connection).getProtocolHandler().writeFrame(frame);
- }
-
- private void checkSendingMessage() throws JMSException
- {
- TEST++;
- _logger.info("Test creating producer which will use channel id 1");
-
- Queue queue = _session.createQueue("CCT_test_validation_queue" + TEST);
-
- MessageConsumer consumer = _session.createConsumer(queue);
-
- MessageProducer producer = _session.createProducer(queue);
-
- final String MESSAGE = "CCT_Test_Message";
- producer.send(_session.createTextMessage(MESSAGE));
-
- Message msg = consumer.receive(2000);
-
- assertNotNull("Received messages should not be null.", msg);
- assertEquals("Message received not what we sent", MESSAGE, ((TextMessage) msg).getText());
- }
-
- private Connection newConnection()
- {
- Connection connection = null;
- try
- {
- connection = getConnection();
-
- ((AMQConnection) connection).setConnectionListener(this);
-
- _session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
-
- connection.start();
-
- }
- catch (Exception e)
- {
- fail("Creating new connection when:" + e.getMessage());
- }
-
- return connection;
- }
-
- private void declareExchange(int channelId, String _type, String _name, boolean nowait)
- throws AMQException, FailoverException
- {
- ExchangeDeclareBody body =
- ((AMQConnection) _connection).getProtocolHandler()
- .getMethodRegistry()
- .createExchangeDeclareBody(0,
- new AMQShortString(_name),
- new AMQShortString(_type),
- true,
- false,
- false,
- false,
- nowait,
- null);
- AMQFrame exchangeDeclare = body.generateFrame(channelId);
- AMQProtocolHandler protocolHandler = ((AMQConnection) _connection).getProtocolHandler();
-
-
- if (nowait)
- {
- protocolHandler.writeFrame(exchangeDeclare);
- }
- else
- {
- protocolHandler.syncWrite(exchangeDeclare, ExchangeDeclareOkBody.class, SYNC_TIMEOUT);
- }
-
-// return null;
-// }
-// }, (AMQConnection)_connection).execute();
-
- }
-
- private void createChannel(int channelId) throws AMQException, FailoverException
- {
- ChannelOpenBody body =
- ((AMQConnection) _connection).getProtocolHandler().getMethodRegistry().createChannelOpenBody(null);
-
- ((AMQConnection) _connection).getProtocolHandler().syncWrite(body.generateFrame(channelId), // outOfBand
- ChannelOpenOkBody.class);
-
- }
-
- public void onException(JMSException jmsException)
- {
- // _logger.info("CCT" + jmsException);
- fail(jmsException.getMessage());
- }
-
- public void bytesSent(long count)
- { }
-
- public void bytesReceived(long count)
- { }
-
- public boolean preFailover(boolean redirect)
- {
- return false;
- }
-
- public boolean preResubscribe()
- {
- return false;
- }
-
- public void failoverComplete()
- { }
-
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/client/channelclose/CloseWithBlockingReceiveTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/client/channelclose/CloseWithBlockingReceiveTest.java
deleted file mode 100644
index 56d03dc4a7..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/client/channelclose/CloseWithBlockingReceiveTest.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.client.channelclose;
-
-import javax.jms.MessageConsumer;
-import javax.jms.Session;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQTopic;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-/**
- * @author Apache Software Foundation
- */
-public class CloseWithBlockingReceiveTest extends QpidBrokerTestCase
-{
-
-
- protected void setUp() throws Exception
- {
- super.setUp();
- }
-
- protected void tearDown() throws Exception
- {
- super.tearDown();
- }
-
-
- public void testReceiveReturnsNull() throws Exception
- {
- final AMQConnection connection = (AMQConnection) getConnection("guest", "guest");
- Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- MessageConsumer consumer = session.createConsumer(new AMQTopic(connection, "banana"));
- connection.start();
-
- Runnable r = new Runnable()
- {
-
- public void run()
- {
- try
- {
- Thread.sleep(1000);
- connection.close();
- }
- catch (Exception e)
- {
- }
- }
- };
- long startTime = System.currentTimeMillis();
- new Thread(r).start();
- consumer.receive(10000);
- assertTrue(System.currentTimeMillis() - startTime < 10000);
- }
-
- public static junit.framework.Test suite()
- {
- return new junit.framework.TestSuite(CloseWithBlockingReceiveTest.class);
- }
-
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/client/connection/CloseAfterConnectionFailureTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/client/connection/CloseAfterConnectionFailureTest.java
deleted file mode 100644
index dc2f59c384..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/client/connection/CloseAfterConnectionFailureTest.java
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.client.connection;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQConnectionURL;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.apache.qpid.url.URLSyntaxException;
-
-import javax.jms.ExceptionListener;
-import javax.jms.JMSException;
-import javax.jms.MessageConsumer;
-import javax.jms.Session;
-import java.util.concurrent.CountDownLatch;
-
-public class CloseAfterConnectionFailureTest extends QpidBrokerTestCase implements ExceptionListener
-{
- private int sessionCount = 0;
- AMQConnection connection;
- Session session;
- MessageConsumer consumer;
- private CountDownLatch _latch = new CountDownLatch(1);
- private JMSException _fail;
-
- public void testNoFailover() throws URLSyntaxException, Exception,
- InterruptedException, JMSException
- {
- //This test uses hard coded connection string so only runs on InVM case
- if (!isExternalBroker())
- {
- String connectionString = "amqp://guest:guest@/test?brokerlist='vm://:1?connectdelay='500',retries='3'',failover='nofailover'";
-
- AMQConnectionURL url = new AMQConnectionURL(connectionString);
-
- try
- {
- //Start the connection so it will use the retries
- connection = new AMQConnection(url, null);
-
- connection.setExceptionListener(this);
-
- session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- consumer = session.createConsumer(session.createQueue(this.getName()));
-
- //Kill connection
- stopBroker();
-
- _latch.await();
-
- if (_fail != null)
- {
- _fail.printStackTrace(System.out);
- fail("Exception thrown:" + _fail.getMessage());
- }
- }
- catch (AMQException e)
- {
- fail(e.getMessage());
- }
- }
- }
-
- public void onException(JMSException e)
- {
- System.out.println("Connection isClosed after connection Falure?:" + connection.isClosed());
- try
- {
- consumer.close();
- }
- catch (JMSException jmse)
- {
- System.out.println("Consumer close failed with:" + jmse.getMessage());
- _fail = jmse;
- }
- System.out.println("Connection isClosed after connection Falure?:" + connection.isClosed());
- try
- {
- //Note that if we actually do session.close() we will lock up as the session will never receive a frame
- // from the
- ((AMQSession) session).close(10);
- }
- catch (JMSException jmse)
- {
- System.out.println("Session close failed with:" + jmse.getMessage());
- _fail = jmse;
- }
- System.out.println("Connection isClosed after connection Falure?:" + connection.isClosed());
-
- try
- {
- connection.close();
- }
- catch (JMSException jmse)
- {
- System.out.println("Session close failed with:" + jmse.getMessage());
- _fail = jmse;
- }
- System.out.println("Connection isClosed after connection Falure?:" + connection.isClosed());
-
- _latch.countDown();
-
- }
-
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/client/connection/ConnectionCloseTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/client/connection/ConnectionCloseTest.java
deleted file mode 100644
index 6d1b6de238..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/client/connection/ConnectionCloseTest.java
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.client.connection;
-
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.apache.qpid.transport.util.Logger;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.jms.Connection;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-import javax.jms.Queue;
-import javax.jms.Session;
-import javax.jms.TextMessage;
-
-/**
- * ConnectionCloseTest
- *
- */
-
-public class ConnectionCloseTest extends QpidBrokerTestCase
-{
-
- private static final Logger log = Logger.get(ConnectionCloseTest.class);
-
- public void testSendReceiveClose() throws Exception
- {
- Map<Thread,StackTraceElement[]> before = Thread.getAllStackTraces();
-
- for (int i = 0; i < 50; i++)
- {
- if ((i % 10) == 0)
- {
- log.warn("%d messages sent and received", i);
- }
-
- Connection receiver = getConnection();
- receiver.start();
- Session rssn = receiver.createSession(false, Session.AUTO_ACKNOWLEDGE);
- Queue queue = rssn.createQueue("connection-close-test-queue");
- MessageConsumer cons = rssn.createConsumer(queue);
-
- Connection sender = getConnection();
- sender.start();
- Session sssn = sender.createSession(false, Session.AUTO_ACKNOWLEDGE);
- MessageProducer prod = sssn.createProducer(queue);
- prod.send(sssn.createTextMessage("test"));
- sender.close();
-
- TextMessage m = (TextMessage) cons.receive(2000);
- assertNotNull("message was lost", m);
- assertEquals(m.getText(), "test");
- receiver.close();
- }
-
- // The finalizer is notifying connector thread waiting on a selector key.
- // This should leave the finalizer enough time to notify those threads
- synchronized (this)
- {
- this.wait(10000);
- }
-
- Map<Thread,StackTraceElement[]> after = Thread.getAllStackTraces();
-
- Map<Thread,StackTraceElement[]> delta = new HashMap<Thread,StackTraceElement[]>(after);
- for (Thread t : before.keySet())
- {
- delta.remove(t);
- }
-
- dumpStacks(delta);
-
- int deltaThreshold = (isExternalBroker()? 1 : 2) //InVM creates more thread pools in the same VM
- * (Runtime.getRuntime().availableProcessors() + 1) + 5;
-
- assertTrue("Spurious thread creation exceeded threshold, " +
- delta.size() + " threads created.",
- delta.size() < deltaThreshold);
- }
-
- private void dumpStacks(Map<Thread,StackTraceElement[]> map)
- {
- for (Map.Entry<Thread,StackTraceElement[]> entry : map.entrySet())
- {
- Throwable t = new Throwable();
- t.setStackTrace(entry.getValue());
- log.warn(t, entry.getKey().toString());
- }
- }
-
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/client/connection/ConnectionStartTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/client/connection/ConnectionStartTest.java
deleted file mode 100644
index ac14f8e50e..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/client/connection/ConnectionStartTest.java
+++ /dev/null
@@ -1,158 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.client.connection;
-
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageListener;
-import javax.jms.MessageProducer;
-import javax.jms.Session;
-import javax.jms.TextMessage;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-public class ConnectionStartTest extends QpidBrokerTestCase
-{
-
- String _broker = "vm://:1";
-
- AMQConnection _connection;
- private Session _consumerSess;
- private MessageConsumer _consumer;
-
- protected void setUp() throws Exception
- {
- super.setUp();
- try
- {
-
-
- AMQConnection pubCon = (AMQConnection) getConnection("guest", "guest");
-
- AMQQueue queue = new AMQQueue(pubCon,"ConnectionStartTest");
-
- Session pubSess = pubCon.createSession(false, AMQSession.AUTO_ACKNOWLEDGE);
-
- MessageProducer pub = pubSess.createProducer(queue);
-
- _connection = (AMQConnection) getConnection("guest", "guest");
-
- _consumerSess = _connection.createSession(false, AMQSession.AUTO_ACKNOWLEDGE);
-
- _consumer = _consumerSess.createConsumer(queue);
-
- //publish after queue is created to ensure it can be routed as expected
- pub.send(pubSess.createTextMessage("Initial Message"));
-
- pubCon.close();
-
- }
- catch (Exception e)
- {
- e.printStackTrace();
- fail("Connection to " + _broker + " should succeed. Reason: " + e);
- }
- }
-
- protected void tearDown() throws Exception
- {
- _connection.close();
- super.tearDown();
- }
-
- public void testSimpleReceiveConnection()
- {
- try
- {
- assertTrue("Connection should not be started", !_connection.started());
- //Note that this next line will start the dispatcher in the session
- // should really not be called before _connection start
- //assertTrue("There should not be messages waiting for the consumer", _consumer.receiveNoWait() == null);
- _connection.start();
- assertTrue("There should be messages waiting for the consumer", _consumer.receive(10*1000) != null);
- assertTrue("Connection should be started", _connection.started());
-
- }
- catch (JMSException e)
- {
- fail("An error occured during test because:" + e);
- }
-
- }
-
- public void testMessageListenerConnection()
- {
- final CountDownLatch _gotMessage = new CountDownLatch(1);
-
- try
- {
- assertTrue("Connection should not be started", !_connection.started());
- _consumer.setMessageListener(new MessageListener()
- {
- public void onMessage(Message message)
- {
- try
- {
- assertTrue("Connection should be started", _connection.started());
- assertEquals("Mesage Received", "Initial Message", ((TextMessage) message).getText());
- _gotMessage.countDown();
- }
- catch (JMSException e)
- {
- fail("Couldn't get message text because:" + e.getCause());
- }
- }
- });
-
- assertTrue("Connection should not be started", !_connection.started());
- _connection.start();
- assertTrue("Connection should be started", _connection.started());
-
- try
- {
- assertTrue("Listener was never called", _gotMessage.await(10 * 1000, TimeUnit.MILLISECONDS));
- }
- catch (InterruptedException e)
- {
- fail("Timed out awaiting message via onMessage");
- }
-
- }
- catch (JMSException e)
- {
- fail("Failed because:" + e.getCause());
- }
-
- }
-
-
- public static junit.framework.Test suite()
- {
- return new junit.framework.TestSuite(ConnectionStartTest.class);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/client/connection/ConnectionTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/client/connection/ConnectionTest.java
deleted file mode 100644
index 04fc611cd1..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/client/connection/ConnectionTest.java
+++ /dev/null
@@ -1,301 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.client.connection;
-
-import org.apache.qpid.AMQConnectionFailureException;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.AMQUnresolvedAddressException;
-import org.apache.qpid.server.exchange.Exchange;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.apache.qpid.client.AMQAuthenticationException;
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.client.AMQTopic;
-import org.apache.qpid.client.AMQConnectionURL;
-import org.apache.qpid.exchange.ExchangeDefaults;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.jms.Session;
-import org.apache.qpid.jms.ConnectionURL;
-import org.apache.qpid.jms.BrokerDetails;
-
-import javax.jms.Connection;
-import javax.jms.QueueSession;
-import javax.jms.TopicSession;
-import javax.naming.NamingException;
-
-public class ConnectionTest extends QpidBrokerTestCase
-{
-
- String _broker_NotRunning = "vm://:2";
- String _broker_BadDNS = "tcp://hg3sgaaw4lgihjs";
-
- public void testSimpleConnection() throws Exception
- {
- AMQConnection conn = null;
- try
- {
- conn = new AMQConnection(getBroker().toString(), "guest", "guest", "fred", "test");
- }
- catch (Exception e)
- {
- fail("Connection to " + getBroker() + " should succeed. Reason: " + e);
- }
- finally
- {
- if(conn != null)
- {
- conn.close();
- }
- }
- }
-
- public void testDefaultExchanges() throws Exception
- {
- AMQConnection conn = null;
- try
- {
- BrokerDetails broker = getBroker();
- broker.setProperty(BrokerDetails.OPTIONS_RETRY, "1");
- ConnectionURL url = new AMQConnectionURL("amqp://guest:guest@clientid/test?brokerlist='"
- + broker
- + "'&defaultQueueExchange='test.direct'"
- + "&defaultTopicExchange='test.topic'"
- + "&temporaryQueueExchange='tmp.direct'"
- + "&temporaryTopicExchange='tmp.topic'");
-
- System.err.println(url.toString());
- conn = new AMQConnection(url, null);
-
-
- AMQSession sess = (AMQSession) conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- sess.declareExchange(new AMQShortString("test.direct"),
- ExchangeDefaults.DIRECT_EXCHANGE_CLASS, false);
-
- sess.declareExchange(new AMQShortString("tmp.direct"),
- ExchangeDefaults.DIRECT_EXCHANGE_CLASS, false);
-
- sess.declareExchange(new AMQShortString("tmp.topic"),
- ExchangeDefaults.TOPIC_EXCHANGE_CLASS, false);
-
- sess.declareExchange(new AMQShortString("test.topic"),
- ExchangeDefaults.TOPIC_EXCHANGE_CLASS, false);
-
- QueueSession queueSession = conn.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
-
- AMQQueue queue = (AMQQueue) queueSession.createQueue("MyQueue");
-
- assertEquals(queue.getExchangeName().toString(), "test.direct");
-
- AMQQueue tempQueue = (AMQQueue) queueSession.createTemporaryQueue();
-
- assertEquals(tempQueue.getExchangeName().toString(), "tmp.direct");
-
- queueSession.close();
-
- TopicSession topicSession = conn.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
-
- AMQTopic topic = (AMQTopic) topicSession.createTopic("silly.topic");
-
- assertEquals(topic.getExchangeName().toString(), "test.topic");
-
- AMQTopic tempTopic = (AMQTopic) topicSession.createTemporaryTopic();
-
- assertEquals(tempTopic.getExchangeName().toString(), "tmp.topic");
-
- topicSession.close();
-
- }
- catch (Exception e)
- {
- fail("Connection to " + getBroker() + " should succeed. Reason: " + e);
- }
- finally
- {
- conn.close();
- }
- }
-
- public void testPasswordFailureConnection() throws Exception
- {
- AMQConnection conn = null;
- try
- {
- BrokerDetails broker = getBroker();
- broker.setProperty(BrokerDetails.OPTIONS_RETRY, "0");
- conn = new AMQConnection("amqp://guest:rubbishpassword@clientid/test?brokerlist='" + broker + "'");
- fail("Connection should not be established password is wrong.");
- }
- catch (AMQConnectionFailureException amqe)
- {
- assertNotNull("No cause set:" + amqe.getMessage(), amqe.getCause());
- assertTrue("Exception was wrong type", amqe.getCause() instanceof AMQException);
- }
- finally
- {
- if (conn != null)
- {
- conn.close();
- }
- }
- }
-
- public void testConnectionFailure() throws Exception
- {
- AMQConnection conn = null;
- try
- {
- conn = new AMQConnection("amqp://guest:guest@clientid/testpath?brokerlist='" + _broker_NotRunning + "?retries='0''");
- fail("Connection should not be established");
- }
- catch (AMQException amqe)
- {
- if (!(amqe instanceof AMQConnectionFailureException))
- {
- fail("Correct exception not thrown. Excpected 'AMQConnectionException' got: " + amqe);
- }
- }
- finally
- {
- if (conn != null)
- {
- conn.close();
- }
- }
-
- }
-
- public void testUnresolvedHostFailure() throws Exception
- {
- AMQConnection conn = null;
- try
- {
- conn = new AMQConnection("amqp://guest:guest@clientid/testpath?brokerlist='" + _broker_BadDNS + "?retries='0''");
- fail("Connection should not be established");
- }
- catch (AMQException amqe)
- {
- if (!(amqe instanceof AMQUnresolvedAddressException))
- {
- fail("Correct exception not thrown. Excpected 'AMQUnresolvedAddressException' got: " + amqe);
- }
- }
- finally
- {
- if (conn != null)
- {
- conn.close();
- }
- }
-
- }
-
- public void testUnresolvedVirtualHostFailure() throws Exception
- {
- AMQConnection conn = null;
- try
- {
- BrokerDetails broker = getBroker();
- broker.setProperty(BrokerDetails.OPTIONS_RETRY, "0");
- conn = new AMQConnection("amqp://guest:guest@clientid/rubbishhost?brokerlist='" + broker + "'");
- fail("Connection should not be established");
- }
- catch (AMQException amqe)
- {
- if (!(amqe instanceof AMQConnectionFailureException))
- {
- fail("Correct exception not thrown. Excpected 'AMQConnectionFailureException' got: " + amqe);
- }
- }
- finally
- {
- if (conn != null)
- {
- conn.close();
- }
- }
- }
-
- public void testClientIdCannotBeChanged() throws Exception
- {
- Connection connection = new AMQConnection(getBroker().toString(), "guest", "guest",
- "fred", "test");
- try
- {
- connection.setClientID("someClientId");
- fail("No IllegalStateException thrown when resetting clientid");
- }
- catch (javax.jms.IllegalStateException e)
- {
- // PASS
- }
- finally
- {
- if (connection != null)
- {
- connection.close();
- }
- }
- }
-
- public void testClientIdIsPopulatedAutomatically() throws Exception
- {
- Connection connection = new AMQConnection(getBroker().toString(), "guest", "guest",
- null, "test");
- try
- {
- assertNotNull(connection.getClientID());
- }
- finally
- {
- connection.close();
- }
- connection.close();
- }
-
- public void testUnsupportedSASLMechanism() throws Exception
- {
- BrokerDetails broker = getBroker();
- broker.setProperty(BrokerDetails.OPTIONS_SASL_MECHS, "MY_MECH");
-
- try
- {
- Connection connection = new AMQConnection(broker.toString(), "guest", "guest",
- null, "test");
- connection.close();
- fail("The client should throw a ConnectionException stating the" +
- " broker does not support the SASL mech specified by the client");
- }
- catch (Exception e)
- {
- assertTrue("Incorrect exception thrown",
- e.getMessage().contains("The following SASL mechanisms " +
- "[MY_MECH]" +
- " specified by the client are not supported by the broker"));
- }
- }
-
- public static junit.framework.Test suite()
- {
- return new junit.framework.TestSuite(ConnectionTest.class);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/client/connection/ExceptionListenerTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/client/connection/ExceptionListenerTest.java
deleted file mode 100644
index cec9d292cf..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/client/connection/ExceptionListenerTest.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.client.connection;
-
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-import javax.jms.Connection;
-import javax.jms.ExceptionListener;
-import javax.jms.JMSException;
-
-/**
- * ExceptionListenerTest
- *
- */
-
-public class ExceptionListenerTest extends QpidBrokerTestCase
-{
-
- public void testBrokerDeath() throws Exception
- {
- Connection conn = getConnection("guest", "guest");
-
- conn.start();
-
- final CountDownLatch fired = new CountDownLatch(1);
- conn.setExceptionListener(new ExceptionListener()
- {
- public void onException(JMSException e)
- {
- fired.countDown();
- }
- });
-
- stopBroker();
-
- if (!fired.await(3, TimeUnit.SECONDS))
- {
- fail("exception listener was not fired");
- }
- }
-
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/client/forwardall/Client.java b/java/systests/src/main/java/org/apache/qpid/test/unit/client/forwardall/Client.java
deleted file mode 100644
index b60fe76b76..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/client/forwardall/Client.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.
- *
- */
-package org.apache.qpid.test.unit.client.forwardall;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageListener;
-import javax.jms.MessageProducer;
-
-/**
- * Declare a private temporary response queue,
- * send a message to amq.direct with a well known routing key with the
- * private response queue as the reply-to destination
- * consume responses.
- */
-public class Client implements MessageListener
-{
- private static final Logger _logger = LoggerFactory.getLogger(Client.class);
-
- private final AMQConnection _connection;
- private final AMQSession _session;
- private final int _expected;
- private int _count;
- private static QpidBrokerTestCase _qct;
-
- Client(String broker, int expected) throws Exception
- {
- this(connect(broker), expected);
- }
-
- public static void setQTC(QpidBrokerTestCase qtc)
- {
- _qct = qtc;
- }
- Client(AMQConnection connection, int expected) throws Exception
- {
- _connection = connection;
- _expected = expected;
- _session = (AMQSession) _connection.createSession(true, AMQSession.NO_ACKNOWLEDGE);
- AMQQueue response =
- new AMQQueue(_connection.getDefaultQueueExchangeName(), new AMQShortString("ResponseQueue"), true);
- _session.createConsumer(response).setMessageListener(this);
- _connection.start();
- // AMQQueue service = new SpecialQueue(_connection, "ServiceQueue");
- AMQQueue service = (AMQQueue) _session.createQueue("ServiceQueue") ;
- Message request = _session.createTextMessage("Request!");
- request.setJMSReplyTo(response);
- MessageProducer prod = _session.createProducer(service);
- prod.send(request);
- _session.commit();
- }
-
- void shutdownWhenComplete() throws Exception
- {
- waitUntilComplete();
- _connection.close();
- }
-
- public synchronized void onMessage(Message response)
- {
-
- _logger.info("Received " + (++_count) + " of " + _expected + " responses.");
- if (_count == _expected)
- {
-
- notifyAll();
- }
- try
- {
- _session.commit();
- }
- catch (JMSException e)
- {
-
- }
-
- }
-
- synchronized void waitUntilComplete() throws Exception
- {
-
- if (_count < _expected)
- {
- wait(60000);
- }
-
- if (_count < _expected)
- {
- throw new Exception("Didn't receive all messages... got " + _count + " expected " + _expected);
- }
- }
-
- static AMQConnection connect(String broker) throws Exception
- {
- //return new AMQConnection(broker, "guest", "guest", "Client" + System.currentTimeMillis(), "test");
- return (AMQConnection) _qct.getConnection("guest", "guest") ;
- }
-
- public static void main(String[] argv) throws Exception
- {
- final String connectionString;
- final int expected;
- if (argv.length == 0)
- {
- connectionString = "localhost:5672";
- expected = 100;
- }
- else
- {
- connectionString = argv[0];
- expected = Integer.parseInt(argv[1]);
- }
-
- new Client(connect(connectionString), expected).shutdownWhenComplete();
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/client/forwardall/CombinedTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/client/forwardall/CombinedTest.java
deleted file mode 100644
index 45945eb8fc..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/client/forwardall/CombinedTest.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.client.forwardall;
-
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Runs the Service's and Client parts of the test in the same process
- * as the broker
- */
-public class CombinedTest extends QpidBrokerTestCase
-{
- private static final Logger _logger = LoggerFactory.getLogger(CombinedTest.class);
- private int run = 0;
-
- protected void setUp() throws Exception
- {
- super.setUp();
- Service.setQTC(this);
- Client.setQTC(this);
- }
-
- protected void tearDown() throws Exception
- {
- ServiceCreator.closeAll();
- super.tearDown();
- }
-
- public void testForwardAll() throws Exception
- {
- while (run < 10)
- {
- int services =1;
- ServiceCreator.start("vm://:1", services);
-
- _logger.info("Starting " + ++run + " client...");
-
- new Client("vm://:1", services).shutdownWhenComplete();
-
-
- _logger.info("Completed " + run + " successfully!");
- }
- }
-
- public static junit.framework.Test suite()
- {
- return new junit.framework.TestSuite(CombinedTest.class);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/client/forwardall/Service.java b/java/systests/src/main/java/org/apache/qpid/test/unit/client/forwardall/Service.java
deleted file mode 100644
index 160700bdda..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/client/forwardall/Service.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.client.forwardall;
-
-import javax.jms.Destination;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageListener;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-/**
- * Declare a queue and bind it to amq.direct with a 'well known' routing key,
- * register a consumer for this queue and send a response to every message received.
- */
-public class Service implements MessageListener
-{
- private final AMQConnection _connection;
- private final AMQSession _session;
-
- private static QpidBrokerTestCase _qct;
-
-
- public static void setQTC(QpidBrokerTestCase qtc)
- {
- _qct = qtc;
- }
- Service(String broker) throws Exception
- {
- this(connect(broker));
- }
-
- Service(AMQConnection connection) throws Exception
- {
- _connection = connection;
- //AMQQueue queue = new SpecialQueue(connection, "ServiceQueue");
- _session = (AMQSession) _connection.createSession(true, AMQSession.NO_ACKNOWLEDGE);
- AMQQueue queue = (AMQQueue) _session.createQueue("ServiceQueue") ;
- _session.createConsumer(queue).setMessageListener(this);
- _connection.start();
- }
-
- public void onMessage(Message request)
- {
- try
- {
- Message response = _session.createTextMessage("Response!");
- Destination replyTo = request.getJMSReplyTo();
- _session.createProducer(replyTo).send(response);
- _session.commit();
- }
- catch (Exception e)
- {
- e.printStackTrace(System.out);
- }
- }
-
- public void close() throws JMSException
- {
- _connection.close();
- }
-
- static AMQConnection connect(String broker) throws Exception
- {
- //return new AMQConnection(broker, "guest", "guest", "Client" + System.currentTimeMillis(), "test");
- return (AMQConnection) _qct.getConnection("guest", "guest") ;
- }
-
-// public static void main(String[] argv) throws Exception
-// {
-// String broker = argv.length == 0? "localhost:5672" : argv[0];
-// new Service(broker);
-// }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/client/forwardall/ServiceCreator.java b/java/systests/src/main/java/org/apache/qpid/test/unit/client/forwardall/ServiceCreator.java
deleted file mode 100644
index be16f6b7ae..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/client/forwardall/ServiceCreator.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.test.unit.client.forwardall;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.jms.JMSException;
-
-public class ServiceCreator implements Runnable
-{
- private static final Logger _logger = LoggerFactory.getLogger(ServiceCreator.class);
-
- private static Thread[] threads;
- private static ServiceCreator[] _services;
-
- private final String broker;
- private Service service;
-
- ServiceCreator(String broker)
- {
- this.broker = broker;
- }
-
- public void run()
- {
- try
- {
- service = new Service(broker);
- }
- catch (Exception e)
- {
- e.printStackTrace(System.out);
- }
- }
-
- public void closeSC() throws JMSException
- {
- service.close();
- }
-
- static void closeAll()
- {
- for (int i = 0; i < _services.length; i++)
- {
- try
- {
- _services[i].closeSC();
- }
- catch (JMSException e)
- {
- // ignore
- }
- }
- }
-
- static void start(String broker, int services) throws InterruptedException
- {
- threads = new Thread[services];
- _services = new ServiceCreator[services];
- ServiceCreator runner = new ServiceCreator(broker);
- // start services
- _logger.info("Starting " + services + " services...");
- for (int i = 0; i < services; i++)
- {
- threads[i] = new Thread(runner);
- _services[i] = runner;
- threads[i].start();
- }
-
- for (int i = 0; i < threads.length; i++)
- {
- threads[i].join();
- }
- }
-
- public static void main(String[] argv) throws Exception
- {
- final String connectionString;
- final int services;
- if (argv.length == 0)
- {
- connectionString = "localhost:5672";
- services = 100;
- }
- else
- {
- connectionString = argv[0];
- services = Integer.parseInt(argv[1]);
- }
-
- start(connectionString, services);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/client/forwardall/SpecialQueue.java b/java/systests/src/main/java/org/apache/qpid/test/unit/client/forwardall/SpecialQueue.java
deleted file mode 100644
index 27371b0397..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/client/forwardall/SpecialQueue.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.client.forwardall;
-
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.framing.AMQShortString;
-
-/**
- * Queue that allows several private queues to be registered and bound
- * to an exchange with the same routing key.
- *
- */
-class SpecialQueue extends AMQQueue
-{
- private final AMQShortString name;
-
- SpecialQueue(AMQConnection con, String name)
- {
- super(con, name, true);
- this.name = new AMQShortString(name);
- }
-
- public AMQShortString getRoutingKey()
- {
- return name;
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/client/message/ObjectMessageTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/client/message/ObjectMessageTest.java
deleted file mode 100644
index fd28b86762..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/client/message/ObjectMessageTest.java
+++ /dev/null
@@ -1,335 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.client.message;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQDestination;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageListener;
-import javax.jms.MessageProducer;
-import javax.jms.ObjectMessage;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-
-public class ObjectMessageTest extends QpidBrokerTestCase implements MessageListener
-{
- private static final Logger _logger = LoggerFactory.getLogger(ObjectMessageTest.class);
-
- private AMQConnection connection;
- private AMQDestination destination;
- private AMQSession session;
- private MessageProducer producer;
- private Serializable[] data;
- private volatile boolean waiting;
- private int received;
- private final ArrayList items = new ArrayList();
-
- private String _broker = "vm://:1";
-
- protected void setUp() throws Exception
- {
- super.setUp();
- connection = (AMQConnection) getConnection("guest", "guest");
- destination = new AMQQueue(connection, randomize("LatencyTest"), true);
- session = (AMQSession) connection.createSession(false, AMQSession.NO_ACKNOWLEDGE);
-
- // set up a consumer
- session.createConsumer(destination).setMessageListener(this);
- connection.start();
-
- // create a publisher
- producer = session.createProducer(destination, false, false, true);
- A a1 = new A(1, "A");
- A a2 = new A(2, "a");
- B b = new B(1, "B");
- C c = new C();
- c.put("A1", a1);
- c.put("a2", a2);
- c.put("B", b);
- c.put("String", "String");
-
- data = new Serializable[] { a1, a2, b, c, "Hello World!", new Integer(1001) };
- }
-
- protected void tearDown() throws Exception
- {
- close();
- super.tearDown();
- }
-
- public ObjectMessageTest()
- { }
-
- ObjectMessageTest(String broker) throws Exception
- {
- _broker = broker;
- }
-
- public void testSendAndReceive() throws Exception
- {
- try
- {
- send();
- waitUntilReceived(data.length);
- check();
- _logger.info("All " + data.length + " items matched.");
- }
- catch (Exception e)
- {
- e.printStackTrace();
- fail("This Test should succeed but failed due to: " + e);
- }
- }
-
- public void testSetObjectPropertyForString() throws Exception
- {
- String testStringProperty = "TestStringProperty";
- ObjectMessage msg = session.createObjectMessage(data[0]);
- msg.setObjectProperty("TestStringProperty", testStringProperty);
- assertEquals(testStringProperty, msg.getObjectProperty("TestStringProperty"));
- }
-
- public void testSetObjectPropertyForBoolean() throws Exception
- {
- ObjectMessage msg = session.createObjectMessage(data[0]);
- msg.setObjectProperty("TestBooleanProperty", Boolean.TRUE);
- assertEquals(Boolean.TRUE, msg.getObjectProperty("TestBooleanProperty"));
- }
-
- public void testSetObjectPropertyForByte() throws Exception
- {
- ObjectMessage msg = session.createObjectMessage(data[0]);
- msg.setObjectProperty("TestByteProperty", Byte.MAX_VALUE);
- assertEquals(Byte.MAX_VALUE, msg.getObjectProperty("TestByteProperty"));
- }
-
- public void testSetObjectPropertyForShort() throws Exception
- {
- ObjectMessage msg = session.createObjectMessage(data[0]);
- msg.setObjectProperty("TestShortProperty", Short.MAX_VALUE);
- assertEquals(Short.MAX_VALUE, msg.getObjectProperty("TestShortProperty"));
- }
-
- public void testSetObjectPropertyForInteger() throws Exception
- {
- ObjectMessage msg = session.createObjectMessage(data[0]);
- msg.setObjectProperty("TestIntegerProperty", Integer.MAX_VALUE);
- assertEquals(Integer.MAX_VALUE, msg.getObjectProperty("TestIntegerProperty"));
- }
-
- public void testSetObjectPropertyForDouble() throws Exception
- {
- ObjectMessage msg = session.createObjectMessage(data[0]);
- msg.setObjectProperty("TestDoubleProperty", Double.MAX_VALUE);
- assertEquals(Double.MAX_VALUE, msg.getObjectProperty("TestDoubleProperty"));
- }
-
- public void testSetObjectPropertyForFloat() throws Exception
- {
- ObjectMessage msg = session.createObjectMessage(data[0]);
- msg.setObjectProperty("TestFloatProperty", Float.MAX_VALUE);
- assertEquals(Float.MAX_VALUE, msg.getObjectProperty("TestFloatProperty"));
- }
-
- public void testSetObjectPropertyForByteArray() throws Exception
- {
- byte[] array = { 1, 2, 3, 4, 5 };
- ObjectMessage msg = session.createObjectMessage(data[0]);
- msg.setObjectProperty("TestByteArrayProperty", array);
- assertTrue(Arrays.equals(array, (byte[]) msg.getObjectProperty("TestByteArrayProperty")));
- }
-
- public void testSetObjectForNull() throws Exception
- {
- ObjectMessage msg = session.createObjectMessage();
- msg.setObject(null);
- assertNull(msg.getObject());
- }
-
- private void send() throws Exception
- {
- for (int i = 0; i < data.length; i++)
- {
- ObjectMessage msg;
- if ((i % 2) == 0)
- {
- msg = session.createObjectMessage(data[i]);
- }
- else
- {
- msg = session.createObjectMessage();
- msg.setObject(data[i]);
- }
-
- producer.send(msg);
- }
- }
-
- public void check() throws Exception
- {
- Object[] actual = (Object[]) items.toArray();
- if (actual.length != data.length)
- {
- throw new Exception("Expected " + data.length + " objects, got " + actual.length);
- }
-
- for (int i = 0; i < data.length; i++)
- {
- if (actual[i] instanceof Exception)
- {
- throw new Exception("Error on receive of " + data[i], ((Exception) actual[i]));
- }
-
- if (actual[i] == null)
- {
- throw new Exception("Expected " + data[i] + " got null");
- }
-
- if (!data[i].equals(actual[i]))
- {
- throw new Exception("Expected " + data[i] + " got " + actual[i]);
- }
- }
- }
-
- private void close() throws Exception
- {
- session.close();
- connection.close();
- }
-
- private synchronized void waitUntilReceived(int count) throws InterruptedException
- {
- waiting = true;
- while (received < count)
- {
- wait();
- }
-
- waiting = false;
- }
-
- public void onMessage(Message message)
- {
-
- try
- {
- if (message instanceof ObjectMessage)
- {
- items.add(((ObjectMessage) message).getObject());
- }
- else
- {
- _logger.error("ERROR: Got " + message.getClass().getName() + " not ObjectMessage");
- items.add(message);
- }
- }
- catch (JMSException e)
- {
- e.printStackTrace();
- items.add(e);
- }
-
- synchronized (this)
- {
- received++;
- notify();
- }
- }
-
- public static void main(String[] argv) throws Exception
- {
- String broker = (argv.length > 0) ? argv[0] : "vm://:1";
- if ("-help".equals(broker))
- {
- System.out.println("Usage: <broker>");
- }
-
- new ObjectMessageTest(broker).testSendAndReceive();
- }
-
- private static class A implements Serializable
- {
- private String sValue;
- private int iValue;
-
- A(int i, String s)
- {
- sValue = s;
- iValue = i;
- }
-
- public int hashCode()
- {
- return iValue;
- }
-
- public boolean equals(Object o)
- {
- return (o instanceof A) && equals((A) o);
- }
-
- protected boolean equals(A a)
- {
- return areEqual(a.sValue, sValue) && (a.iValue == iValue);
- }
- }
-
- private static class B extends A
- {
- private long time;
-
- B(int i, String s)
- {
- super(i, s);
- time = System.currentTimeMillis();
- }
-
- protected boolean equals(A a)
- {
- return super.equals(a) && (a instanceof B) && (time == ((B) a).time);
- }
- }
-
- private static class C extends HashMap implements Serializable
- { }
-
- private static boolean areEqual(Object a, Object b)
- {
- return (a == null) ? (b == null) : a.equals(b);
- }
-
- private static String randomize(String in)
- {
- return in + System.currentTimeMillis();
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/client/protocol/AMQProtocolSessionTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/client/protocol/AMQProtocolSessionTest.java
deleted file mode 100644
index 278b9e9c04..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/client/protocol/AMQProtocolSessionTest.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.test.unit.client.protocol;
-
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.SocketAddress;
-import java.net.UnknownHostException;
-
-import org.apache.mina.transport.vmpipe.VmPipeAddress;
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.protocol.AMQProtocolHandler;
-import org.apache.qpid.client.protocol.AMQProtocolSession;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.apache.qpid.transport.TestNetworkDriver;
-
-public class AMQProtocolSessionTest extends QpidBrokerTestCase
-{
- private static class AMQProtSession extends AMQProtocolSession
- {
-
- public AMQProtSession(AMQProtocolHandler protocolHandler, AMQConnection connection)
- {
- super(protocolHandler,connection);
- }
-
- public TestNetworkDriver getNetworkDriver()
- {
- return (TestNetworkDriver) _protocolHandler.getNetworkDriver();
- }
-
- public AMQShortString genQueueName()
- {
- return generateQueueName();
- }
- }
-
- private AMQProtSession _testSession;
-
- protected void setUp() throws Exception
- {
- super.setUp();
-
- AMQConnection con = (AMQConnection) getConnection("guest", "guest");
- AMQProtocolHandler protocolHandler = new AMQProtocolHandler(con);
- protocolHandler.setNetworkDriver(new TestNetworkDriver());
-
- //don't care about the values set here apart from the dummy IoSession
- _testSession = new AMQProtSession(protocolHandler , con);
- }
-
- public void testTemporaryQueueWildcard() throws UnknownHostException
- {
- checkTempQueueName(new InetSocketAddress(1234), "tmp_0_0_0_0_0_0_0_0_1234_1");
- }
-
- public void testTemporaryQueueLocalhostAddr() throws UnknownHostException
- {
- checkTempQueueName(new InetSocketAddress(InetAddress.getByName("127.0.0.1"), 1234), "tmp_127_0_0_1_1234_1");
- }
-
- public void testTemporaryQueueLocalhostName() throws UnknownHostException
- {
- checkTempQueueName(new InetSocketAddress(InetAddress.getByName("localhost"), 1234), "tmp_localhost_127_0_0_1_1234_1");
- }
-
- public void testTemporaryQueueInet4() throws UnknownHostException
- {
- checkTempQueueName(new InetSocketAddress(InetAddress.getByName("192.168.1.2"), 1234), "tmp_192_168_1_2_1234_1");
- }
-
- public void testTemporaryQueueInet6() throws UnknownHostException
- {
- checkTempQueueName(new InetSocketAddress(InetAddress.getByName("1080:0:0:0:8:800:200C:417A"), 1234), "tmp_1080_0_0_0_8_800_200c_417a_1234_1");
- }
-
- public void testTemporaryQueuePipe() throws UnknownHostException
- {
- checkTempQueueName(new VmPipeAddress(1), "tmp_vm_1_1");
- }
-
- private void checkTempQueueName(SocketAddress address, String queueName)
- {
- _testSession.getNetworkDriver().setLocalAddress(address);
- assertEquals("Wrong queue name", queueName, _testSession.genQueueName().asString());
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/client/temporaryqueue/TemporaryQueueTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/client/temporaryqueue/TemporaryQueueTest.java
deleted file mode 100644
index 8c806fa2da..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/client/temporaryqueue/TemporaryQueueTest.java
+++ /dev/null
@@ -1,258 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.qpid.test.unit.client.temporaryqueue;
-
-import javax.jms.Connection;
-import javax.jms.ExceptionListener;
-import javax.jms.JMSException;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-import javax.jms.Session;
-import javax.jms.TemporaryQueue;
-import javax.jms.TextMessage;
-import junit.framework.Assert;
-
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.jms.ConnectionListener;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.LinkedList;
-
-public class TemporaryQueueTest extends QpidBrokerTestCase implements ExceptionListener
-{
- private List<Exception> _exceptions = new ArrayList<Exception>();
-
- protected void setUp() throws Exception
- {
- super.setUp();
- }
-
- protected void tearDown() throws Exception
- {
- super.tearDown();
- }
-
- protected Connection createConnection() throws Exception
- {
- return getConnection("guest", "guest");
- }
-
- public void testTemporaryQueue() throws Exception
- {
- Connection conn = createConnection();
- Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
- TemporaryQueue queue = session.createTemporaryQueue();
- assertNotNull(queue);
- MessageProducer producer = session.createProducer(queue);
- MessageConsumer consumer = session.createConsumer(queue);
- conn.start();
- producer.send(session.createTextMessage("hello"));
- TextMessage tm = (TextMessage) consumer.receive(2000);
- assertNotNull(tm);
- assertEquals("hello", tm.getText());
-
- try
- {
- queue.delete();
- fail("Expected JMSException : should not be able to delete while there are active consumers");
- }
- catch (JMSException je)
- {
- ; //pass
- }
-
- consumer.close();
-
- try
- {
- queue.delete();
- }
- catch (JMSException je)
- {
- fail("Unexpected Exception: " + je.getMessage());
- }
-
- conn.close();
- }
-
- public void tUniqueness() throws Exception
- {
- int numProcs = Runtime.getRuntime().availableProcessors();
- final int threadsProc = 5;
-
- runUniqueness(1, 10);
- runUniqueness(numProcs * threadsProc, 10);
- runUniqueness(numProcs * threadsProc, 100);
- runUniqueness(numProcs * threadsProc, 500);
- }
-
- void runUniqueness(int makers, int queues) throws Exception
- {
- Connection connection = createConnection();
-
- Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
-
- List<TempQueueMaker> tqList = new LinkedList<TempQueueMaker>();
-
- //Create Makers
- for (int m = 0; m < makers; m++)
- {
- tqList.add(new TempQueueMaker(session, queues));
- }
-
-
- List<Thread> threadList = new LinkedList<Thread>();
-
- //Create Makers
- for (TempQueueMaker maker : tqList)
- {
- threadList.add(new Thread(maker));
- }
-
- //Start threads
- for (Thread thread : threadList)
- {
- thread.start();
- }
-
- // Join Threads
- for (Thread thread : threadList)
- {
- try
- {
- thread.join();
- }
- catch (InterruptedException e)
- {
- fail("Couldn't correctly join threads");
- }
- }
-
-
- List<AMQQueue> list = new LinkedList<AMQQueue>();
-
- // Test values
- for (TempQueueMaker maker : tqList)
- {
- check(maker, list);
- }
-
- Assert.assertEquals("Not enough queues made.", makers * queues, list.size());
-
- connection.close();
- }
-
- private void check(TempQueueMaker tq, List<AMQQueue> list)
- {
- for (AMQQueue q : tq.getList())
- {
- if (list.contains(q))
- {
- fail(q + " already exists.");
- }
- else
- {
- list.add(q);
- }
- }
- }
-
-
- class TempQueueMaker implements Runnable
- {
- List<AMQQueue> _queues;
- Session _session;
- private int _count;
-
-
- TempQueueMaker(Session session, int queues) throws JMSException
- {
- _queues = new LinkedList<AMQQueue>();
-
- _count = queues;
-
- _session = session;
- }
-
- public void run()
- {
- int i = 0;
- try
- {
- for (; i < _count; i++)
- {
- _queues.add((AMQQueue) _session.createTemporaryQueue());
- }
- }
- catch (JMSException jmse)
- {
- //stop
- }
- }
-
- List<AMQQueue> getList()
- {
- return _queues;
- }
- }
-
- public void testQPID1217() throws Exception
- {
- Connection conA = getConnection();
- conA.setExceptionListener(this);
- Session sessA = conA.createSession(false, Session.AUTO_ACKNOWLEDGE);
- TemporaryQueue temp = sessA.createTemporaryQueue();
-
- MessageProducer prod = sessA.createProducer(temp);
- prod.send(sessA.createTextMessage("hi"));
-
- Thread.sleep(500);
- assertTrue("Exception received", _exceptions.isEmpty());
-
- Connection conB = getConnection();
- Session sessB = conB.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- JMSException ex = null;
- try
- {
- MessageConsumer consB = sessB.createConsumer(temp);
- }
- catch (JMSException e)
- {
- ex = e;
- }
- assertNotNull(ex);
- }
-
- public static junit.framework.Test suite()
- {
- return new junit.framework.TestSuite(TemporaryQueueTest.class);
- }
-
- public void onException(JMSException arg0)
- {
- _exceptions.add(arg0);
- }
-
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/close/CloseBeforeAckTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/close/CloseBeforeAckTest.java
deleted file mode 100644
index 039a172e4d..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/close/CloseBeforeAckTest.java
+++ /dev/null
@@ -1,142 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.close;
-
-import junit.framework.Assert;
-
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import org.apache.qpid.junit.concurrency.TestRunnable;
-import org.apache.qpid.junit.concurrency.ThreadTestCoordinator;
-
-import javax.jms.Connection;
-import javax.jms.Message;
-import javax.jms.MessageListener;
-import javax.jms.Session;
-
-/**
- * This test forces the situation where a session is closed whilst a message consumer is still in its onMessage method.
- * Running in AUTO_ACK mode, the close call ought to wait until the onMessage method completes, and the ack is sent
- * before closing the connection.
- *
- * <p><table id="crc"><caption>CRC Card</caption> <tr><th> Responsibilities <th> Collaborations <tr><td> Check that
- * closing a connection whilst handling a message, blocks till completion of the handler. </table>
- */
-public class CloseBeforeAckTest extends QpidBrokerTestCase
-{
- private static final Logger log = LoggerFactory.getLogger(CloseBeforeAckTest.class);
-
- Connection connection;
- Session session;
- public static final String TEST_QUEUE_NAME = "TestQueue";
- private int TEST_COUNT = 25;
-
- class TestThread1 extends TestRunnable implements MessageListener
- {
- public void runWithExceptions() throws Exception
- {
- // Set this up to listen for message on the test session.
- session.createConsumer(session.createQueue(TEST_QUEUE_NAME)).setMessageListener(this);
- }
-
- public void onMessage(Message message)
- {
- // Give thread 2 permission to close the session.
- allow(new int[] { 1 });
-
- // Wait until thread 2 has closed the connection, or is blocked waiting for this to complete.
- waitFor(new int[] { 1 }, true);
- }
- }
-
- TestThread1 testThread1 = new TestThread1();
-
- TestRunnable testThread2 =
- new TestRunnable()
- {
- public void runWithExceptions() throws Exception
- {
- // Send a message to be picked up by thread 1.
- session.createProducer(null).send(session.createQueue(TEST_QUEUE_NAME),
- session.createTextMessage("Hi there thread 1!"));
-
- // Wait for thread 1 to pick up the message and give permission to continue.
- waitFor(new int[] { 0 }, false);
-
- // Close the connection.
- session.close();
-
- // Allow thread 1 to continue to completion, if it is erronously still waiting.
- allow(new int[] { 1 });
- }
- };
-
- public void testCloseBeforeAutoAck_QPID_397() throws Exception
- {
- // Create a session in auto acknowledge mode. This problem shows up in auto acknowledge if the client acks
- // message at the end of the onMessage method, after a close has been sent.
- session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- ThreadTestCoordinator tt = new ThreadTestCoordinator(2);
-
- tt.addTestThread(testThread1, 0);
- tt.addTestThread(testThread2, 1);
- tt.setDeadlockTimeout(500);
- tt.run();
-
- String errorMessage = tt.joinAndRetrieveMessages();
-
- // Print any error messages or exceptions.
- log.debug(errorMessage);
-
- if (!tt.getExceptions().isEmpty())
- {
- for (Exception e : tt.getExceptions())
- {
- log.debug("Exception thrown during test thread: ", e);
- }
- }
-
- Assert.assertTrue(errorMessage, "".equals(errorMessage));
- }
-
- public void closeBeforeAutoAckManyTimes() throws Exception
- {
- for (int i = 0; i < TEST_COUNT; i++)
- {
- testCloseBeforeAutoAck_QPID_397();
- }
- }
-
- protected void setUp() throws Exception
- {
- super.setUp();
- connection = getConnection("guest", "guest");
- }
-
- protected void tearDown() throws Exception
- {
- super.tearDown();
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/close/JavaServerCloseRaceConditionTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/close/JavaServerCloseRaceConditionTest.java
deleted file mode 100644
index 6bc6c591ae..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/close/JavaServerCloseRaceConditionTest.java
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.close;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQDestination;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.framing.AMQFrame;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.ExchangeDeclareBody;
-import org.apache.qpid.framing.ExchangeDeclareOkBody;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-import javax.jms.Session;
-
-/** QPID-1809
- *
- * Race condition on error handling and close logic.
- *
- * See most often with SimpleACLTest as this test is the expects the server to
- * shut the connection/channels. This sort of testing is not performed by many,
- * if any, of the other system tests.
- *
- * The problem is that we have two threads
- *
- * MainThread Exception(Mina)Thread
- * | |
- * Performs |
- * ACtion |
- * | Receives Server
- * | Close
- * Blocks for |
- * Response |
- * | Starts To Notify
- * | client
- * | |
- * | <----- Notify Main Thread
- * Notification |
- * wakes client |
- * | |
- * Client then |
- * processes Error. |
- * | |
- * Potentially Attempting Close Channel/Connection
- * Connection Close
- *
- * The two threads both attempt to close the connection but the main thread does
- * so assuming that the connection is open and valid.
- *
- * The Exception thread must modify the connection so that no furter syncWait
- * commands are performed.
- *
- * This test sends an ExchangeDeclare that is Asynchronous and will fail and
- * so cause a ChannelClose error but we perform a syncWait so that we can be
- * sure to test that the BlockingWaiter is correctly awoken.
- *
- */
-public class JavaServerCloseRaceConditionTest extends QpidBrokerTestCase
-{
- private static final String EXCHANGE_NAME = "NewExchangeNametoFailLookup";
-
- public void test() throws Exception
- {
-
- AMQConnection connection = (AMQConnection) getConnection();
-
- AMQSession session = (AMQSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- // Set no wait true so that we block the connection
- // Also set a different exchange class string so the attempt to declare
- // the exchange causes an exchange.
- ExchangeDeclareBody body = session.getMethodRegistry().createExchangeDeclareBody(session.getTicket(), new AMQShortString(EXCHANGE_NAME), null,
- true, false, false, false, true, null);
-
- AMQFrame exchangeDeclare = body.generateFrame(session.getChannelId());
-
- try
- {
- // block our thread so that can times out
- connection.getProtocolHandler().syncWrite(exchangeDeclare, ExchangeDeclareOkBody.class);
- }
- catch (Exception e)
- {
- assertTrue("Exception should say the exchange is not known.", e.getMessage().contains("Unknown exchange: " + EXCHANGE_NAME));
- }
-
- try
- {
- // Depending on if the notification thread has closed the connection
- // or not we may get an exception here when we attempt to close the
- // connection. If we do get one then it should be the same as above
- // an AMQAuthenticationException.
- connection.close();
- }
- catch (Exception e)
- {
- assertTrue("Exception should say the exchange is not known.", e.getMessage().contains("Unknown exchange: " + EXCHANGE_NAME));
- }
-
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/close/MessageRequeueTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/close/MessageRequeueTest.java
deleted file mode 100644
index de092fc893..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/close/MessageRequeueTest.java
+++ /dev/null
@@ -1,373 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- *
- */
-package org.apache.qpid.test.unit.close;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.apache.qpid.test.utils.QpidClientConnection;
-import org.apache.qpid.client.message.AbstractJMSMessage;
-import org.apache.qpid.url.URLSyntaxException;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.jms.Connection;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.Queue;
-import javax.jms.Session;
-
-import java.util.concurrent.atomic.AtomicInteger;
-
-public class MessageRequeueTest extends QpidBrokerTestCase
-{
- private static final Logger _logger = LoggerFactory.getLogger(MessageRequeueTest.class);
-
- protected static AtomicInteger consumerIds = new AtomicInteger(0);
- protected final Integer numTestMessages = 150;
-
- protected final int consumeTimeout = 3000;
-
- protected final String queue = "direct://amq.direct//message-requeue-test-queue";
- protected String payload = "Message:";
-
- //protected final String BROKER = "vm://:1";
- protected final String BROKER = "tcp://127.0.0.1:5672";
- private boolean testReception = true;
-
- private long[] receieved = new long[numTestMessages + 1];
- private boolean passed = false;
- QpidClientConnection conn;
-
-
- protected void setUp() throws Exception
- {
- super.setUp();
-
- conn = new QpidClientConnection(BROKER);
-
- conn.connect();
- // clear queue
- conn.consume(queue, consumeTimeout);
- // load test data
- _logger.info("creating test data, " + numTestMessages + " messages");
- conn.put(queue, payload, numTestMessages);
- // close this connection
- conn.disconnect();
- }
-
- protected void tearDown() throws Exception
- {
-
- if (!passed) // clean up
- {
- QpidClientConnection conn = new QpidClientConnection(BROKER);
-
- conn.connect();
- // clear queue
- conn.consume(queue, consumeTimeout);
-
- conn.disconnect();
- }
-
- super.tearDown();
- }
-
- /**
- * multiple consumers
- *
- * @throws javax.jms.JMSException if a JMS problem occurs
- * @throws InterruptedException on timeout
- */
- public void testDrain() throws Exception
- {
- QpidClientConnection conn = new QpidClientConnection(BROKER);
-
- conn.connect();
-
- _logger.info("consuming queue " + queue);
- Queue q = conn.getSession().createQueue(queue);
-
- final MessageConsumer consumer = conn.getSession().createConsumer(q);
- int messagesReceived = 0;
-
- long[] messageLog = new long[numTestMessages + 1];
-
- _logger.info("consuming...");
- Message msg = consumer.receive(1000);
- while (msg != null)
- {
- messagesReceived++;
-
- long dt = ((AbstractJMSMessage) msg).getDeliveryTag();
-
- int msgindex = msg.getIntProperty("index");
- if (messageLog[msgindex] != 0)
- {
- _logger.error("Received Message(" + msgindex + ":" + ((AbstractJMSMessage) msg).getDeliveryTag()
- + ") more than once.");
- }
-
- if (_logger.isInfoEnabled())
- {
- _logger.info("Received Message(" + System.identityHashCode(msgindex) + ") " + "DT:" + dt + "IN:" + msgindex);
- }
-
- if (dt == 0)
- {
- _logger.error("DT is zero for msg:" + msgindex);
- }
-
- messageLog[msgindex] = dt;
-
- // get Next message
- msg = consumer.receive(1000);
- }
-
- _logger.info("consuming done.");
- conn.getSession().commit();
- consumer.close();
-
- int index = 0;
- StringBuilder list = new StringBuilder();
- list.append("Failed to receive:");
- int failed = 0;
-
- _logger.info("consumed: " + messagesReceived);
-
- assertEquals("number of consumed messages does not match initial data", (int) numTestMessages, messagesReceived);
- // wit 0_10 we can have a delivery tag of 0
- if (conn.isBroker08())
- {
- for (long b : messageLog)
- {
- if ((b == 0) && (index != 0)) // delivery tag of zero shouldn't exist
- {
- _logger.error("Index: " + index + " was not received.");
- list.append(" ");
- list.append(index);
- list.append(":");
- list.append(b);
- failed++;
- }
-
- index++;
- }
-
- assertEquals(list.toString(), 0, failed);
- }
-
- conn.disconnect();
- passed = true;
- }
-
- /** multiple consumers
- * Based on code subbmitted by client FT-304
- */
- public void testTwoCompetingConsumers()
- {
- Consumer c1 = new Consumer();
- Consumer c2 = new Consumer();
- Consumer c3 = new Consumer();
- Consumer c4 = new Consumer();
-
- Thread t1 = new Thread(c1);
- Thread t2 = new Thread(c2);
- Thread t3 = new Thread(c3);
- Thread t4 = new Thread(c4);
-
- t1.start();
- t2.start();
- t3.start();
- // t4.start();
-
- try
- {
- t1.join();
- t2.join();
- t3.join();
- t4.join();
- }
- catch (InterruptedException e)
- {
- fail("Unable to join to Consumer theads");
- }
-
- _logger.info("consumer 1 count is " + c1.getCount());
- _logger.info("consumer 2 count is " + c2.getCount());
- _logger.info("consumer 3 count is " + c3.getCount());
- _logger.info("consumer 4 count is " + c4.getCount());
-
- Integer totalConsumed = c1.getCount() + c2.getCount() + c3.getCount() + c4.getCount();
-
- // Check all messages were correctly delivered
- int index = 0;
- StringBuilder list = new StringBuilder();
- list.append("Failed to receive:");
- int failed = 0;
- if (conn.isBroker08())
- {
- for (long b : receieved)
- {
- if ((b == 0) && (index != 0)) // delivery tag of zero shouldn't exist (and we don't have msg 0)
- {
- _logger.error("Index: " + index + " was not received.");
- list.append(" ");
- list.append(index);
- list.append(":");
- list.append(b);
- failed++;
- }
-
- index++;
- }
-
- assertEquals(list.toString() + "-" + numTestMessages + "-" + totalConsumed, 0, failed);
- }
- assertEquals("number of consumed messages does not match initial data", numTestMessages, totalConsumed);
- passed = true;
- }
-
- class Consumer implements Runnable
- {
- private Integer count = 0;
- private Integer id;
-
- public Consumer()
- {
- id = consumerIds.addAndGet(1);
- }
-
- public void run()
- {
- try
- {
- _logger.info("consumer-" + id + ": starting");
- QpidClientConnection conn = new QpidClientConnection(BROKER);
-
- conn.connect();
-
- _logger.info("consumer-" + id + ": connected, consuming...");
- Message result;
- do
- {
- result = conn.getNextMessage(queue, consumeTimeout);
- if (result != null)
- {
-
- long dt = ((AbstractJMSMessage) result).getDeliveryTag();
-
- if (testReception)
- {
- int msgindex = result.getIntProperty("index");
- if (receieved[msgindex] != 0)
- {
- _logger.error("Received Message(" + msgindex + ":"
- + ((AbstractJMSMessage) result).getDeliveryTag() + ") more than once.");
- }
-
- if (_logger.isInfoEnabled())
- {
- _logger.info("Received Message(" + System.identityHashCode(msgindex) + ") " + "DT:" + dt
- + "IN:" + msgindex);
- }
-
- if (dt == 0)
- {
- _logger.error("DT is zero for msg:" + msgindex);
- }
-
- receieved[msgindex] = dt;
- }
-
- count++;
- if ((count % 100) == 0)
- {
- _logger.info("consumer-" + id + ": got " + result + ", new count is " + count);
- }
- }
- }
- while (result != null);
-
- _logger.info("consumer-" + id + ": complete");
- conn.disconnect();
-
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
- }
-
- public Integer getCount()
- {
- return count;
- }
-
- public Integer getId()
- {
- return id;
- }
- }
-
- public void testRequeue() throws JMSException, AMQException, URLSyntaxException
- {
- int run = 0;
- // while (run < 10)
- {
- run++;
-
- if (_logger.isInfoEnabled())
- {
- _logger.info("testRequeue run " + run);
- }
-
- String virtualHost = "/test";
- String brokerlist = BROKER;
- String brokerUrl = "amqp://guest:guest@" + virtualHost + "?brokerlist='" + brokerlist + "'";
- QpidClientConnection qpc = new QpidClientConnection(BROKER);
- qpc.connect();
- Connection conn = qpc. getConnection();
-
- Session session = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE);
- Queue q = session.createQueue(queue);
-
- _logger.debug("Create Consumer");
- MessageConsumer consumer = session.createConsumer(q);
-
- conn.start();
-
- _logger.debug("Receiving msg");
- Message msg = consumer.receive(2000);
-
- assertNotNull("Message should not be null", msg);
-
- // As we have not ack'd message will be requeued.
- _logger.debug("Close Consumer");
- consumer.close();
-
- _logger.debug("Close Connection");
- conn.close();
- }
- }
-
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/close/TopicPublisherCloseTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/close/TopicPublisherCloseTest.java
deleted file mode 100644
index 8a6dfb86ee..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/close/TopicPublisherCloseTest.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */package org.apache.qpid.test.unit.close;
-
-import javax.jms.Session;
-import javax.jms.Topic;
-import javax.jms.TopicPublisher;
-import javax.jms.TopicSession;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQTopic;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-/**
- * @author Apache Software Foundation
- */
-public class TopicPublisherCloseTest extends QpidBrokerTestCase
-{
-
- protected void setUp() throws Exception
- {
- super.setUp();
- }
-
-
- protected void tearDown() throws Exception
- {
- super.tearDown();
- }
-
- public void testAllMethodsThrowAfterConnectionClose() throws Exception
- {
- // give external brokers a chance to start up
- Thread.sleep(3000);
-
- AMQConnection connection = (AMQConnection) getConnection("guest", "guest");
-
- Topic destination1 = new AMQTopic(connection, "t1");
- TopicSession session1 = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
- TopicPublisher pub = session1.createPublisher(destination1);
- connection.close();
- try
- {
- pub.getDeliveryMode();
- fail("Expected exception not thrown");
- }
- catch (javax.jms.IllegalStateException e)
- {
- // PASS
- }
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/close/VerifyAckingOkDuringClose.java b/java/systests/src/main/java/org/apache/qpid/test/unit/close/VerifyAckingOkDuringClose.java
deleted file mode 100644
index 3b30b7d63f..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/close/VerifyAckingOkDuringClose.java
+++ /dev/null
@@ -1,160 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.close;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQConnectionFactory;
-import org.apache.qpid.jndi.PropertiesFileInitialContextFactory;
-
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-import javax.jms.Queue;
-import javax.jms.Session;
-import javax.naming.InitialContext;
-import java.util.ArrayList;
-
-/**
- * QPID-1791
- *
- * The threading model in the Java broker (at least till 0.5) allows for the
- * close to be handled immediately even if the broker is still processing state
- * for that Session.
- *
- * This test verifys that QPID-1791 is has been handled.
- *
- * The problem was that the whilst the Session is busy processing Acks from the
- * client the Close frame jumps in and clears the unAcknowledgeMap in an
- * attempt to start processing them for closing the connection.
- *
- * If the session had a consumer consuming from a temporary queue. The closing
- * thread dequeues and deletes the message that were on the uncknowledgedMap.
- *
- * However, the Acking thread currently does:
- * queuEntry = unackedMap.get(messageID)
- *
- * dequeueAndDelete(queueEntry)
- *
- * unackedMap.remove(messageID)
- *
- * As a result the queueEntry is sitting in the unackedMap whilst it is being
- * dequeuedAndDeleted which leaves the opportunity for the close thread to
- * remove contents of the unackedMap for processing. The close thread will then
- * dequeueAndDelete all these values one of which the acking thread is currently
- * processing.
- *
- *
- * Test Approach
- *
- * Send a lot of persistent messages (5000), the goal of which is to fill the
- * pretch and to provide the broker with a lot of acks to process
- *
- * Using client ack and prefetch buffer of 5000 use receive to get 2500
- * Use AMQMessage.acknowledgeThis() to send a single ack frame back to the
- * broker per message so 2500 ack frames.
- * This will give the broker a lot to process,
- * Immediately send the consumer close after the acks are all gone.
- * This will cause the remaining 2500 prefetched messages plus any that have
- * not yet had their acks processed
- * to be collected by the requeue() process potentially
- */
-public class VerifyAckingOkDuringClose
-{
-
- static final int MESSAGE_SENT = 5000;
-
- public static void main(String[] args) throws Exception
- {
- //Check that we have the InitialContext Configured
-
- if (System.getProperty(InitialContext.INITIAL_CONTEXT_FACTORY) == null)
- {
- System.setProperty(InitialContext.INITIAL_CONTEXT_FACTORY, PropertiesFileInitialContextFactory.class.getName());
- }
-
- if (System.getProperty(InitialContext.PROVIDER_URL) == null)
- {
- System.err.println(InitialContext.PROVIDER_URL + ": Is not set and is required to contain a 'default' ConnectionFactory.");
- System.exit(1);
- }
-
- //Retreive the local factory from the properties file
- // when used with perftest.properties this will be localhost:5672
- AMQConnectionFactory factory = (AMQConnectionFactory) new InitialContext().lookup("default");
-
- AMQConnection connection = (AMQConnection) factory.createConnection("guest", "guest");
-
- //Use the AMQConnection Interface to set the prefetch to the number
- // we are sending
- Session session = connection.createSession(false,
- Session.CLIENT_ACKNOWLEDGE,
- MESSAGE_SENT);
-
- Queue queue = session.createTemporaryQueue();
-
- MessageConsumer consumer = session.createConsumer(queue);
- connection.start();
-
- MessageProducer producer = session.createProducer(queue);
-
- Message message = session.createTextMessage("Close");
-
- for (int i = 0; i < MESSAGE_SENT; i++)
- {
- message.setIntProperty("SequenceNumber", i);
-
- producer.send(message);
- }
-
- // Put a reasonable about of data on the queue.
-
- //Receive all the messags
- ArrayList<Message> received = new ArrayList<Message>();
-
- message = consumer.receive(2000);
-
- while (message != null)
- {
- received.add(message);
- message = consumer.receive(2000);
- }
-
- //Check we have all the messages
- if (received.size() != MESSAGE_SENT)
- {
- System.err.println("Test Failed Not all the messages received:" + received.size());
- System.exit(1);
- }
-
- //individually ack the first half then close
- for (int i = 0; i < MESSAGE_SENT / 2; i++)
- {
- ((org.apache.qpid.jms.Message) received.get(i)).acknowledgeThis();
- }
-
- // Close the Session to force a requeue on the server of the unackedMsgs
-
- System.out.println("Killing client to force requeue on broker");
-
- System.exit(1);
- }
-
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/ct/DurableSubscriberTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/ct/DurableSubscriberTest.java
deleted file mode 100644
index 989ac98747..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/ct/DurableSubscriberTest.java
+++ /dev/null
@@ -1,506 +0,0 @@
-/* Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.qpid.test.unit.ct;
-
-import javax.jms.Connection;
-import javax.jms.Message;
-import javax.jms.MessageProducer;
-import javax.jms.Session;
-import javax.jms.TextMessage;
-import javax.jms.Topic;
-import javax.jms.TopicConnection;
-import javax.jms.TopicConnectionFactory;
-import javax.jms.TopicPublisher;
-import javax.jms.TopicSession;
-import javax.jms.TopicSubscriber;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.client.AMQTopic;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-/**
- * Crash Recovery tests for durable subscription
- *
- */
-public class DurableSubscriberTest extends QpidBrokerTestCase
-{
- private final String _topicName = "durableSubscriberTopic";
-
- /**
- * test strategy:
- * create and register a durable subscriber then close it
- * create a publisher and send a persistant message followed by a non persistant message
- * crash and restart the broker
- * recreate the durable subscriber and check that only the first message is received
- */
- public void testDurSubRestoredAfterNonPersistentMessageSent() throws Exception
- {
- if (isBrokerStorePersistent() || !isBroker08())
- {
- TopicConnectionFactory factory = getConnectionFactory();
- Topic topic = (Topic) getInitialContext().lookup(_topicName);
- //create and register a durable subscriber then close it
- TopicConnection durConnection = factory.createTopicConnection("guest", "guest");
- TopicSession durSession = durConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
- TopicSubscriber durSub1 = durSession.createDurableSubscriber(topic, "dursub");
- durConnection.start();
- durSub1.close();
- durSession.close();
- durConnection.stop();
-
- //create a publisher and send a persistant message followed by a non persistant message
- TopicConnection pubConnection = factory.createTopicConnection("guest", "guest");
- TopicSession pubSession = pubConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
- TopicPublisher publisher = pubSession.createPublisher(topic);
- Message message = pubSession.createMessage();
- message.setIntProperty("count", 1);
- publisher.publish(message, javax.jms.DeliveryMode.PERSISTENT, javax.jms.Message.DEFAULT_PRIORITY,
- javax.jms.Message.DEFAULT_TIME_TO_LIVE);
- message.setIntProperty("count", 2);
- publisher.publish(message, javax.jms.DeliveryMode.NON_PERSISTENT, javax.jms.Message.DEFAULT_PRIORITY,
- javax.jms.Message.DEFAULT_TIME_TO_LIVE);
- publisher.close();
- pubSession.close();
- //now stop the server
- try
- {
- restartBroker();
- }
- catch (Exception e)
- {
- _logger.error("problems restarting broker: " + e);
- throw e;
- }
- //now recreate the durable subscriber and check the received messages
- factory = getConnectionFactory();
- topic = (Topic) getInitialContext().lookup(_topicName);
- TopicConnection durConnection2 = factory.createTopicConnection("guest", "guest");
- TopicSession durSession2 = durConnection2.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
- TopicSubscriber durSub2 = durSession2.createDurableSubscriber(topic, "dursub");
- durConnection2.start();
- Message m1 = durSub2.receive(1000);
- if (m1 == null)
- {
- assertTrue("testDurSubRestoredAfterNonPersistentMessageSent test failed. no message was returned",
- false);
- }
- assertTrue("testDurSubRestoredAfterNonPersistentMessageSent test failed. Wrong message was returned.",
- m1.getIntProperty("count") == 1);
- durSession2.unsubscribe("dursub");
- durConnection2.close();
- }
- }
-
- /**
- * create and register a durable subscriber with a message selector and then close it
- * crash the broker
- * create a publisher and send 5 right messages and 5 wrong messages
- * recreate the durable subscriber and check we receive the 5 expected messages
- */
- public void testDurSubRestoresMessageSelector() throws Exception
- {
- if (isBrokerStorePersistent() || !isBroker08())
- {
- TopicConnectionFactory factory = getConnectionFactory();
- Topic topic = (Topic) getInitialContext().lookup(_topicName);
- //create and register a durable subscriber with a message selector and then close it
- TopicConnection durConnection = factory.createTopicConnection("guest", "guest");
- TopicSession durSession = durConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
- TopicSubscriber durSub1 = durSession.createDurableSubscriber(topic, "dursub", "testprop='true'", false);
- durConnection.start();
- durSub1.close();
- durSession.close();
- durConnection.stop();
- //now stop the server
- try
- {
- restartBroker();
- }
- catch (Exception e)
- {
- _logger.error("problems restarting broker: " + e);
- throw e;
- }
- topic = (Topic) getInitialContext().lookup(_topicName);
- factory = getConnectionFactory();
- TopicConnection pubConnection = factory.createTopicConnection("guest", "guest");
- TopicSession pubSession = pubConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
- TopicPublisher publisher = pubSession.createPublisher(topic);
- for (int i = 0; i < 5; i++)
- {
- Message message = pubSession.createMessage();
- message.setStringProperty("testprop", "true");
- publisher.publish(message);
- message = pubSession.createMessage();
- message.setStringProperty("testprop", "false");
- publisher.publish(message);
- }
- publisher.close();
- pubSession.close();
-
- //now recreate the durable subscriber and check the received messages
- TopicConnection durConnection2 = factory.createTopicConnection("guest", "guest");
- TopicSession durSession2 = durConnection2.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
- TopicSubscriber durSub2 = durSession2.createDurableSubscriber(topic, "dursub", "testprop='true'", false);
- durConnection2.start();
- for (int i = 0; i < 5; i++)
- {
- Message message = durSub2.receive(1000);
- if (message == null)
- {
- assertTrue("testDurSubRestoresMessageSelector test failed. no message was returned", false);
- }
- else
- {
- assertTrue("testDurSubRestoresMessageSelector test failed. message selector not reset",
- message.getStringProperty("testprop").equals("true"));
- }
- }
- durSession2.unsubscribe("dursub");
- durConnection2.close();
- }
- }
-
- /**
- * create and register a durable subscriber without a message selector and then unsubscribe it
- * create and register a durable subscriber with a message selector and then close it
- * restart the broker
- * send matching and non matching messages
- * recreate and register the durable subscriber with a message selector
- * verify only the matching messages are received
- */
- public void testDurSubChangedToHaveSelectorThenRestart() throws Exception
- {
- if (! isBrokerStorePersistent())
- {
- _logger.warn("Test skipped due to requirement of a persistent store");
- return;
- }
-
- final String SUB_NAME=getTestQueueName();
-
- TopicConnectionFactory factory = getConnectionFactory();
- Topic topic = (Topic) getInitialContext().lookup(_topicName);
-
- //create and register a durable subscriber then unsubscribe it
- TopicConnection durConnection = factory.createTopicConnection("guest", "guest");
- TopicSession durSession = durConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
- TopicSubscriber durSub1 = durSession.createDurableSubscriber(topic, SUB_NAME);
- durConnection.start();
- durSub1.close();
- durSession.unsubscribe(SUB_NAME);
- durSession.close();
- durConnection.close();
-
- //create and register a durable subscriber with a message selector and then close it
- TopicConnection durConnection2 = factory.createTopicConnection("guest", "guest");
- TopicSession durSession2 = durConnection2.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
- TopicSubscriber durSub2 = durSession2.createDurableSubscriber(topic, SUB_NAME, "testprop='true'", false);
- durConnection2.start();
- durSub2.close();
- durSession2.close();
- durConnection2.close();
-
- //now restart the server
- try
- {
- restartBroker();
- }
- catch (Exception e)
- {
- _logger.error("problems restarting broker: " + e);
- throw e;
- }
-
- //send messages matching and not matching the selector
- TopicConnection pubConnection = factory.createTopicConnection("guest", "guest");
- TopicSession pubSession = pubConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
- TopicPublisher publisher = pubSession.createPublisher(topic);
- for (int i = 0; i < 5; i++)
- {
- Message message = pubSession.createMessage();
- message.setStringProperty("testprop", "true");
- publisher.publish(message);
- message = pubSession.createMessage();
- message.setStringProperty("testprop", "false");
- publisher.publish(message);
- }
- publisher.close();
- pubSession.close();
-
- //now recreate the durable subscriber with selector to check there are no exceptions generated
- //and then verify the messages are received correctly
- TopicConnection durConnection3 = (TopicConnection) factory.createConnection("guest", "guest");
- TopicSession durSession3 = (TopicSession) durConnection3.createSession(false, Session.AUTO_ACKNOWLEDGE);
- TopicSubscriber durSub3 = durSession3.createDurableSubscriber(topic, SUB_NAME, "testprop='true'", false);
- durConnection3.start();
-
- for (int i = 0; i < 5; i++)
- {
- Message message = durSub3.receive(2000);
- if (message == null)
- {
- fail("testDurSubChangedToHaveSelectorThenRestart test failed. Expected message " + i + " was not returned");
- }
- else
- {
- assertTrue("testDurSubChangedToHaveSelectorThenRestart test failed. Got message not matching selector",
- message.getStringProperty("testprop").equals("true"));
- }
- }
-
- durSub3.close();
- durSession3.unsubscribe(SUB_NAME);
- durSession3.close();
- durConnection3.close();
- }
-
-
- /**
- * create and register a durable subscriber with a message selector and then unsubscribe it
- * create and register a durable subscriber without a message selector and then close it
- * restart the broker
- * send matching and non matching messages
- * recreate and register the durable subscriber without a message selector
- * verify ALL the sent messages are received
- */
- public void testDurSubChangedToNotHaveSelectorThenRestart() throws Exception
- {
- if (! isBrokerStorePersistent())
- {
- _logger.warn("Test skipped due to requirement of a persistent store");
- return;
- }
-
- final String SUB_NAME=getTestQueueName();
-
- TopicConnectionFactory factory = getConnectionFactory();
- Topic topic = (Topic) getInitialContext().lookup(_topicName);
-
- //create and register a durable subscriber with selector then unsubscribe it
- TopicConnection durConnection = factory.createTopicConnection("guest", "guest");
- TopicSession durSession = durConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
- TopicSubscriber durSub1 = durSession.createDurableSubscriber(topic, SUB_NAME, "testprop='true'", false);
- durConnection.start();
- durSub1.close();
- durSession.unsubscribe(SUB_NAME);
- durSession.close();
- durConnection.close();
-
- //create and register a durable subscriber without the message selector and then close it
- TopicConnection durConnection2 = factory.createTopicConnection("guest", "guest");
- TopicSession durSession2 = durConnection2.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
- TopicSubscriber durSub2 = durSession2.createDurableSubscriber(topic, SUB_NAME);
- durConnection2.start();
- durSub2.close();
- durSession2.close();
- durConnection2.close();
-
- //now restart the server
- try
- {
- restartBroker();
- }
- catch (Exception e)
- {
- _logger.error("problems restarting broker: " + e);
- throw e;
- }
-
- //send messages matching and not matching the original used selector
- TopicConnection pubConnection = factory.createTopicConnection("guest", "guest");
- TopicSession pubSession = pubConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
- TopicPublisher publisher = pubSession.createPublisher(topic);
- for (int i = 1; i <= 5; i++)
- {
- Message message = pubSession.createMessage();
- message.setStringProperty("testprop", "true");
- publisher.publish(message);
- message = pubSession.createMessage();
- message.setStringProperty("testprop", "false");
- publisher.publish(message);
- }
- publisher.close();
- pubSession.close();
-
- //now recreate the durable subscriber without selector to check there are no exceptions generated
- //then verify ALL messages sent are received
- TopicConnection durConnection3 = (TopicConnection) factory.createConnection("guest", "guest");
- TopicSession durSession3 = (TopicSession) durConnection3.createSession(false, Session.AUTO_ACKNOWLEDGE);
- TopicSubscriber durSub3 = durSession3.createDurableSubscriber(topic, SUB_NAME);
- durConnection3.start();
-
- for (int i = 1; i <= 10; i++)
- {
- Message message = durSub3.receive(2000);
- if (message == null)
- {
- fail("testDurSubChangedToNotHaveSelectorThenRestart test failed. Expected message " + i + " was not received");
- }
- }
-
- durSub3.close();
- durSession3.unsubscribe(SUB_NAME);
- durSession3.close();
- durConnection3.close();
- }
-
-
- public void testResubscribeWithChangedSelectorAndRestart() throws Exception
- {
- if (! isBrokerStorePersistent())
- {
- _logger.warn("Test skipped due to requirement of a persistent store");
- return;
- }
-
- Connection conn = getConnection();
- conn.start();
- Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
- AMQTopic topic = new AMQTopic((AMQConnection) conn, "testResubscribeWithChangedSelectorAndRestart");
- MessageProducer producer = session.createProducer(topic);
-
- // Create durable subscriber that matches A
- TopicSubscriber subA = session.createDurableSubscriber(topic,
- "testResubscribeWithChangedSelector",
- "Match = True", false);
-
- // Send 1 matching message and 1 non-matching message
- TextMessage msg = session.createTextMessage("testResubscribeWithChangedSelectorAndRestart1");
- msg.setBooleanProperty("Match", true);
- producer.send(msg);
- msg = session.createTextMessage("testResubscribeWithChangedSelectorAndRestart2");
- msg.setBooleanProperty("Match", false);
- producer.send(msg);
-
- Message rMsg = subA.receive(1000);
- assertNotNull(rMsg);
- assertEquals("Content was wrong",
- "testResubscribeWithChangedSelectorAndRestart1",
- ((TextMessage) rMsg).getText());
-
- // Queue has no messages left
- AMQQueue subQueueTmp = new AMQQueue("amq.topic", "clientid" + ":" + "testResubscribeWithChangedSelectorAndRestart");
- assertEquals("Msg count should be 0", 0, ((AMQSession<?, ?>) session).getQueueDepth(subQueueTmp));
-
- rMsg = subA.receive(1000);
- assertNull(rMsg);
-
- // Send another 1 matching message and 1 non-matching message
- msg = session.createTextMessage("testResubscribeWithChangedSelectorAndRestart1");
- msg.setBooleanProperty("Match", true);
- producer.send(msg);
- msg = session.createTextMessage("testResubscribeWithChangedSelectorAndRestart2");
- msg.setBooleanProperty("Match", false);
- producer.send(msg);
-
- // Disconnect subscriber without receiving the message to
- //leave it on the underlying queue
- subA.close();
-
- // Reconnect with new selector that matches B
- TopicSubscriber subB = session.createDurableSubscriber(topic,
- "testResubscribeWithChangedSelectorAndRestart",
- "Match = false", false);
-
- //verify no messages are now present on the queue as changing selector should have issued
- //an unsubscribe and thus deleted the previous durable backing queue for the subscription.
- //check the dur sub's underlying queue now has msg count 0
- AMQQueue subQueue = new AMQQueue("amq.topic", "clientid" + ":" + "testResubscribeWithChangedSelectorAndRestart");
- assertEquals("Msg count should be 0", 0, ((AMQSession<?, ?>) session).getQueueDepth(subQueue));
-
- // Check that new messages are received properly
- msg = session.createTextMessage("testResubscribeWithChangedSelectorAndRestart1");
- msg.setBooleanProperty("Match", true);
- producer.send(msg);
- msg = session.createTextMessage("testResubscribeWithChangedSelectorAndRestart2");
- msg.setBooleanProperty("Match", false);
- producer.send(msg);
-
- rMsg = subB.receive(1000);
- assertNotNull(rMsg);
- assertEquals("Content was wrong",
- "testResubscribeWithChangedSelectorAndRestart2",
- ((TextMessage) rMsg).getText());
-
- rMsg = subB.receive(1000);
- assertNull(rMsg);
-
- //check the dur sub's underlying queue now has msg count 0
- subQueue = new AMQQueue("amq.topic", "clientid" + ":" + "testResubscribeWithChangedSelectorAndRestart");
- assertEquals("Msg count should be 0", 0, ((AMQSession<?, ?>) session).getQueueDepth(subQueue));
-
- //now restart the server
- try
- {
- restartBroker();
- }
- catch (Exception e)
- {
- _logger.error("problems restarting broker: " + e);
- throw e;
- }
-
- // Reconnect to broker
- Connection connection = getConnectionFactory().createConnection("guest", "guest");
- connection.start();
- session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- topic = new AMQTopic((AMQConnection) connection, "testResubscribeWithChangedSelectorAndRestart");
- producer = session.createProducer(topic);
-
- //verify no messages now present on the queue after we restart the broker
- //check the dur sub's underlying queue now has msg count 0
- subQueue = new AMQQueue("amq.topic", "clientid" + ":" + "testResubscribeWithChangedSelectorAndRestart");
- assertEquals("Msg count should be 0", 0, ((AMQSession<?, ?>) session).getQueueDepth(subQueue));
-
- // Reconnect with new selector that matches B
- TopicSubscriber subC = session.createDurableSubscriber(topic,
- "testResubscribeWithChangedSelectorAndRestart",
- "Match = False", false);
-
- // Check that new messages are still sent and recieved properly
- msg = session.createTextMessage("testResubscribeWithChangedSelectorAndRestart1");
- msg.setBooleanProperty("Match", true);
- producer.send(msg);
- msg = session.createTextMessage("testResubscribeWithChangedSelectorAndRestart2");
- msg.setBooleanProperty("Match", false);
- producer.send(msg);
-
- //check the dur sub's underlying queue now has msg count 1
- subQueue = new AMQQueue("amq.topic", "clientid" + ":" + "testResubscribeWithChangedSelectorAndRestart");
- assertEquals("Msg count should be 1", 1, ((AMQSession<?, ?>) session).getQueueDepth(subQueue));
-
- rMsg = subC.receive(1000);
- assertNotNull(rMsg);
- assertEquals("Content was wrong",
- "testResubscribeWithChangedSelectorAndRestart2",
- ((TextMessage) rMsg).getText());
-
- rMsg = subC.receive(1000);
- assertNull(rMsg);
-
- session.unsubscribe("testResubscribeWithChangedSelectorAndRestart");
-
- subC.close();
- session.close();
- connection.close();
- }
-}
-
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/message/JMSPropertiesTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/message/JMSPropertiesTest.java
deleted file mode 100644
index 8caeaa55c0..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/message/JMSPropertiesTest.java
+++ /dev/null
@@ -1,204 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.message;
-
-import org.apache.qpid.AMQPInvalidClassException;
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.client.message.NonQpidObjectMessage;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.jms.Connection;
-import javax.jms.Destination;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageFormatException;
-import javax.jms.MessageProducer;
-import javax.jms.ObjectMessage;
-import javax.jms.Queue;
-import javax.jms.Session;
-import javax.jms.Topic;
-
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * @author Apache Software Foundation
- */
-public class JMSPropertiesTest extends QpidBrokerTestCase
-{
-
- private static final Logger _logger = LoggerFactory.getLogger(JMSPropertiesTest.class);
-
- public String _connectionString = "vm://:1";
-
- public static final String JMS_CORR_ID = "QPIDID_01";
- public static final int JMS_DELIV_MODE = 1;
- public static final String JMS_TYPE = "test.jms.type";
- protected static final String NULL_OBJECT_PROPERTY = "NullObject";
- protected static final String INVALID_OBJECT_PROPERTY = "InvalidObject";
-
- protected void setUp() throws Exception
- {
- super.setUp();
- }
-
- protected void tearDown() throws Exception
- {
- super.tearDown();
- }
-
- public void testJMSProperties() throws Exception
- {
- AMQConnection con = (AMQConnection) getConnection("guest", "guest");
- AMQSession consumerSession = (AMQSession) con.createSession(false, Session.CLIENT_ACKNOWLEDGE);
- Queue queue =
- new AMQQueue(con.getDefaultQueueExchangeName(), new AMQShortString("someQ"), new AMQShortString("someQ"), false,
- true);
- MessageConsumer consumer = consumerSession.createConsumer(queue);
-
- AMQConnection con2 = (AMQConnection) getConnection("guest", "guest");
- Session producerSession = con2.createSession(false, Session.CLIENT_ACKNOWLEDGE);
- MessageProducer producer = producerSession.createProducer(queue);
- Destination JMS_REPLY_TO = new AMQQueue(con2, "my.replyto");
- // create a test message to send
- ObjectMessage sentMsg = new NonQpidObjectMessage(producerSession);
- sentMsg.setJMSCorrelationID(JMS_CORR_ID);
- sentMsg.setJMSDeliveryMode(JMS_DELIV_MODE);
- sentMsg.setJMSType(JMS_TYPE);
- sentMsg.setJMSReplyTo(JMS_REPLY_TO);
-
- String JMSXGroupID_VALUE = "group";
- sentMsg.setStringProperty("JMSXGroupID", JMSXGroupID_VALUE);
-
- int JMSXGroupSeq_VALUE = 1;
- sentMsg.setIntProperty("JMSXGroupSeq", JMSXGroupSeq_VALUE);
-
- try
- {
- sentMsg.setObjectProperty(NULL_OBJECT_PROPERTY, null);
- fail("Null Object Property value set");
- }
- catch (MessageFormatException mfe)
- {
- // Check the error message
- assertEquals("Incorrect error message", AMQPInvalidClassException.INVALID_OBJECT_MSG + "null", mfe.getMessage());
- }
-
- try
- {
- sentMsg.setObjectProperty(INVALID_OBJECT_PROPERTY, new Exception());
- fail("Non primitive Object Property value set");
- }
- catch (MessageFormatException mfe)
- {
- // Check the error message
- assertEquals("Incorrect error message: " + mfe.getMessage(), AMQPInvalidClassException.INVALID_OBJECT_MSG + Exception.class, mfe.getMessage());
- }
-
- // send it
- producer.send(sentMsg);
-
- con2.close();
-
- con.start();
-
- // get message and check JMS properties
- ObjectMessage rm = (ObjectMessage) consumer.receive(2000);
- assertNotNull(rm);
-
- assertEquals("JMS Correlation ID mismatch", sentMsg.getJMSCorrelationID(), rm.getJMSCorrelationID());
- // TODO: Commented out as always overwritten by send delivery mode value - prob should not set in conversion
- // assertEquals("JMS Delivery Mode mismatch",sentMsg.getJMSDeliveryMode(),rm.getJMSDeliveryMode());
- assertEquals("JMS Type mismatch", sentMsg.getJMSType(), rm.getJMSType());
- assertEquals("JMS Reply To mismatch", sentMsg.getJMSReplyTo(), rm.getJMSReplyTo());
- assertTrue("JMSMessageID Does not start ID:", rm.getJMSMessageID().startsWith("ID:"));
- assertEquals("JMS Default priority should be 4",Message.DEFAULT_PRIORITY,rm.getJMSPriority());
-
- //Validate that the JMSX values are correct
- assertEquals("JMSXGroupID is not as expected:", JMSXGroupID_VALUE, rm.getStringProperty("JMSXGroupID"));
- assertEquals("JMSXGroupSeq is not as expected:", JMSXGroupSeq_VALUE, rm.getIntProperty("JMSXGroupSeq"));
-
- boolean JMSXGroupID_Available = false;
- boolean JMSXGroupSeq_Available = false;
- Enumeration props = con.getMetaData().getJMSXPropertyNames();
- while (props.hasMoreElements())
- {
- String name = (String) props.nextElement();
- if (name.equals("JMSXGroupID"))
- {
- JMSXGroupID_Available = true;
- }
- if (name.equals("JMSXGroupSeq"))
- {
- JMSXGroupSeq_Available = true;
- }
- }
-
- assertTrue("JMSXGroupID not available.",JMSXGroupID_Available);
- assertTrue("JMSXGroupSeq not available.",JMSXGroupSeq_Available);
-
- // Check that the NULL_OBJECT_PROPERTY was not set or transmitted.
- assertFalse(NULL_OBJECT_PROPERTY + " was not set.", rm.propertyExists(NULL_OBJECT_PROPERTY));
-
- con.close();
- }
-
- /**
- * Test Goal : test if the message properties can be retrieved properly with out an error
- * and also test if unsupported properties are filtered out. See QPID-2930.
- */
- public void testGetPropertyNames() throws Exception
- {
- Connection con = getConnection("guest", "guest");
- Session ssn = (AMQSession) con.createSession(false, Session.CLIENT_ACKNOWLEDGE);
- con.start();
-
- Topic topic = ssn.createTopic("test");
- MessageConsumer consumer = ssn.createConsumer(topic);
- MessageProducer prod = ssn.createProducer(topic);
- Message m = ssn.createMessage();
- m.setObjectProperty("x-amqp-0-10.routing-key", "routing-key".getBytes());
- m.setObjectProperty("routing-key", "routing-key");
- prod.send(m);
-
- Message msg = consumer.receive(1000);
- assertNotNull(msg);
-
- Enumeration<String> enu = msg.getPropertyNames();
- Map<String,String> map = new HashMap<String,String>();
- while (enu.hasMoreElements())
- {
- String name = enu.nextElement();
- String value = msg.getStringProperty(name);
- map.put(name, value);
- }
-
- assertFalse("Property 'x-amqp-0-10.routing-key' should have been filtered out",map.containsKey("x-amqp-0-10.routing-key"));
- assertTrue("Property routing-key should be present",map.containsKey("routing-key"));
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/message/StreamMessageTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/message/StreamMessageTest.java
deleted file mode 100644
index 0f799073b4..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/message/StreamMessageTest.java
+++ /dev/null
@@ -1,162 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.message;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQHeadersExchange;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.configuration.ClientProperties;
-import org.apache.qpid.exchange.ExchangeDefaults;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.FieldTable;
-import org.apache.qpid.url.AMQBindingURL;
-import org.apache.qpid.url.BindingURL;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.jms.Connection;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageEOFException;
-import javax.jms.MessageListener;
-import javax.jms.MessageProducer;
-import javax.jms.Session;
-import javax.jms.StreamMessage;
-
-/**
- * @author Apache Software Foundation
- */
-public class StreamMessageTest extends QpidBrokerTestCase
-{
-
- private static final Logger _logger = LoggerFactory.getLogger(StreamMessageTest.class);
-
- public String _connectionString = "vm://:1";
-
- protected void setUp() throws Exception
- {
- super.setUp();
- }
-
- protected void tearDown() throws Exception
- {
- super.tearDown();
- }
-
- public void testStreamMessageEOF() throws Exception
- {
- Connection con = (AMQConnection) getConnection("guest", "guest");
- AMQSession consumerSession = (AMQSession) con.createSession(false, Session.CLIENT_ACKNOWLEDGE);
-
- AMQHeadersExchange queue =
- new AMQHeadersExchange(new AMQBindingURL(
- ExchangeDefaults.HEADERS_EXCHANGE_CLASS + "://" + ExchangeDefaults.HEADERS_EXCHANGE_NAME
- + "/test/queue1?" + BindingURL.OPTION_ROUTING_KEY + "='F0000=1'"));
- FieldTable ft = new FieldTable();
- ft.setString("x-match", "any");
- ft.setString("F1000", "1");
- MessageConsumer consumer =
- consumerSession.createConsumer(queue, Integer.parseInt(ClientProperties.MAX_PREFETCH_DEFAULT), Integer.parseInt(ClientProperties.MAX_PREFETCH_DEFAULT), false, false, (String) null, ft);
-
- // force synch to ensure the consumer has resulted in a bound queue
- // ((AMQSession) consumerSession).declareExchangeSynch(ExchangeDefaults.HEADERS_EXCHANGE_NAME, ExchangeDefaults.HEADERS_EXCHANGE_CLASS);
- // This is the default now
-
- Connection con2 = (AMQConnection) getConnection("guest", "guest");
-
- AMQSession producerSession = (AMQSession) con2.createSession(false, Session.CLIENT_ACKNOWLEDGE);
-
- // Need to start the "producer" connection in order to receive bounced messages
- _logger.info("Starting producer connection");
- con2.start();
-
- MessageProducer mandatoryProducer = producerSession.createProducer(queue);
-
- // Third test - should be routed
- _logger.info("Sending isBound message");
- StreamMessage msg = producerSession.createStreamMessage();
-
- msg.setStringProperty("F1000", "1");
-
- msg.writeByte((byte) 42);
-
- mandatoryProducer.send(msg);
-
- _logger.info("Starting consumer connection");
- con.start();
-
- StreamMessage msg2 = (StreamMessage) consumer.receive(2000);
- assertNotNull(msg2);
-
- msg2.readByte();
- try
- {
- msg2.readByte();
- }
- catch (Exception e)
- {
- assertTrue("Expected MessageEOFException: " + e, e instanceof MessageEOFException);
- }
- con.close();
- con2.close();
- }
-
- public void testModifyReceivedMessageExpandsBuffer() throws Exception
- {
- AMQConnection con = (AMQConnection) getConnection("guest", "guest");
- AMQSession consumerSession = (AMQSession) con.createSession(false, Session.CLIENT_ACKNOWLEDGE);
- AMQQueue queue = new AMQQueue(con.getDefaultQueueExchangeName(), new AMQShortString("testQ"));
- MessageConsumer consumer = consumerSession.createConsumer(queue);
- consumer.setMessageListener(new MessageListener()
- {
-
- public void onMessage(Message message)
- {
- StreamMessage sm = (StreamMessage) message;
- try
- {
- sm.clearBody();
- sm.writeString("dfgjshfslfjshflsjfdlsjfhdsljkfhdsljkfhsd");
- }
- catch (JMSException e)
- {
- _logger.error("Error when writing large string to received msg: " + e, e);
- fail("Error when writing large string to received msg" + e);
- }
- }
- });
-
- Connection con2 = (AMQConnection) getConnection("guest", "guest");
- AMQSession producerSession = (AMQSession) con2.createSession(false, Session.CLIENT_ACKNOWLEDGE);
- MessageProducer mandatoryProducer = producerSession.createProducer(queue);
- con.start();
- StreamMessage sm = producerSession.createStreamMessage();
- sm.writeInt(42);
- mandatoryProducer.send(sm);
- Thread.sleep(2000);
- con.close();
- con2.close();
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/message/UTF8En b/java/systests/src/main/java/org/apache/qpid/test/unit/message/UTF8En
deleted file mode 100644
index c9734b1988..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/message/UTF8En
+++ /dev/null
@@ -1,4 +0,0 @@
-exhangeName
-queueName
-routingkey
-data \ No newline at end of file
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/message/UTF8Jp b/java/systests/src/main/java/org/apache/qpid/test/unit/message/UTF8Jp
deleted file mode 100644
index ae10752dab..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/message/UTF8Jp
+++ /dev/null
@@ -1,4 +0,0 @@
-設定がそのように構成されていなければな
-的某些更新没有出现在这个 README 中。你可以访问下面的
-的发行版本包括多张光盘,其中包括安装光盘和源码光盘
-目のインストール CD は、ほとんどの最近のシス \ No newline at end of file
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/message/UTF8Test.java b/java/systests/src/main/java/org/apache/qpid/test/unit/message/UTF8Test.java
deleted file mode 100644
index fe929b4965..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/message/UTF8Test.java
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.message;
-
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.apache.qpid.transport.Connection;
-import org.apache.qpid.transport.Session;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.naming.InitialContext;
-import javax.jms.*;
-import java.util.Properties;
-import java.io.*;
-
-
-/**
- * This test makes sure that utf8 characters can be used for
- * specifying exchange, queue name and routing key.
- *
- * those tests are related to qpid-1384
- */
-public class UTF8Test extends QpidBrokerTestCase
-{
- private static final Logger _logger = LoggerFactory.getLogger(UTF8Test.class);
-
- public void testPlainEn() throws Exception
- {
- invoke("UTF8En");
- }
-
-
- public void testUTF8Jp() throws Exception
- {
- invoke("UTF8Jp");
- }
-
- private void invoke(String name) throws Exception
- {
- String path = System.getProperties().getProperty("QPID_HOME");
- path = path + "/../systests/src/main/java/org/apache/qpid/test/unit/message/" + name;
- BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(path), "UTF8"));
- runTest(in.readLine(), in.readLine(), in.readLine(), in.readLine());
- in.close();
- }
-
- private void runTest(String exchangeName, String queueName, String routingKey, String data) throws Exception
- {
- _logger.info("Running test for exchange: " + exchangeName
- + " queue Name: " + queueName
- + " routing key: " + routingKey);
- declareQueue(exchangeName, routingKey, queueName);
-
- javax.jms.Connection con = getConnection();
- javax.jms.Session sess = con.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
- Destination dest = getDestination(exchangeName, routingKey, queueName);
- // Send data
- MessageProducer msgProd = sess.createProducer(dest);
- TextMessage message = sess.createTextMessage(data);
- msgProd.send(message);
- // consume data
- MessageConsumer msgCons = sess.createConsumer(dest);
- con.start();
- TextMessage m = (TextMessage) msgCons.receive(RECEIVE_TIMEOUT);
- assertNotNull(m);
- assertEquals(m.getText(), data);
- }
-
- private void declareQueue(String exch, String routkey, String qname) throws Exception
- {
- Connection conn = new Connection();
- conn.connect("localhost", QpidBrokerTestCase.DEFAULT_PORT, "test", "guest", "guest",false);
- Session sess = conn.createSession(0);
- sess.exchangeDeclare(exch, "direct", null, null);
- sess.queueDeclare(qname, null, null);
- sess.exchangeBind(qname, exch, routkey, null);
- sess.sync();
- conn.close();
- }
-
- private Destination getDestination(String exch, String routkey, String qname) throws Exception
- {
- Properties props = new Properties();
- props.setProperty("destination.directUTF8Queue",
- "direct://" + exch + "//" + qname + "?autodelete='false'&durable='false'"
- + "&routingkey='" + routkey + "'");
-
- // Get our connection context
- InitialContext ctx = new InitialContext(props);
- return (Destination) ctx.lookup("directUTF8Queue");
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/publish/DirtyTransactedPublishTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/publish/DirtyTransactedPublishTest.java
deleted file mode 100644
index 3ec7937812..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/publish/DirtyTransactedPublishTest.java
+++ /dev/null
@@ -1,403 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.publish;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQDestination;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.jms.ConnectionListener;
-import org.apache.qpid.test.utils.FailoverBaseCase;
-
-import javax.jms.Connection;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageListener;
-import javax.jms.MessageProducer;
-import javax.jms.Queue;
-import javax.jms.Session;
-import javax.jms.TransactionRolledBackException;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicReference;
-
-/**
- * QPID-1816 : Whilst testing Acknoledgement after failover this completes testing
- * of the client after failover. When we have a dirty session we should receive
- * an error if we attempt to publish. This test ensures that both in the synchronous
- * and asynchronous message delivery paths we receive the expected exceptions at
- * the expected time.
- */
-public class DirtyTransactedPublishTest extends FailoverBaseCase implements ConnectionListener
-{
- protected CountDownLatch _failoverCompleted = new CountDownLatch(1);
-
- protected int NUM_MESSAGES;
- protected Connection _connection;
- protected Queue _queue;
- protected Session _consumerSession;
- protected MessageConsumer _consumer;
- protected MessageProducer _producer;
-
- private static final String MSG = "MSG";
- private static final String SEND_FROM_ON_MESSAGE_TEXT = "sendFromOnMessage";
- protected CountDownLatch _receviedAll;
- protected AtomicReference<Exception> _causeOfFailure = new AtomicReference<Exception>(null);
-
- @Override
- protected void setUp() throws Exception
- {
- super.setUp();
- NUM_MESSAGES = 10;
-
- _queue = getTestQueue();
-
- //Create Producer put some messages on the queue
- _connection = getConnection();
- }
-
- /**
- * Initialise the test variables
- * @param transacted is this a transacted test
- * @param mode if not trasacted then what ack mode to use
- * @throws Exception if there is a setup issue.
- */
- protected void init(boolean transacted, int mode) throws Exception
- {
- _consumerSession = _connection.createSession(transacted, mode);
- _consumer = _consumerSession.createConsumer(_queue);
- _producer = _consumerSession.createProducer(_queue);
-
- // These should all end up being prefetched by session
- sendMessage(_consumerSession, _queue, 1);
-
- assertEquals("Wrong number of messages on queue", 1,
- ((AMQSession) _consumerSession).getQueueDepth((AMQDestination) _queue));
- }
-
- /**
- * If a transacted session has failed over whilst it has uncommitted sent
- * data then we need to throw a TransactedRolledbackException on commit()
- *
- * The alternative would be to maintain a replay buffer so that the message
- * could be resent. This is not currently implemented
- *
- * @throws Exception if something goes wrong.
- */
- public void testDirtySendingSynchronousTransacted() throws Exception
- {
- Session producerSession = _connection.createSession(true, Session.SESSION_TRANSACTED);
-
- // Ensure we get failover notifications
- ((AMQConnection) _connection).setConnectionListener(this);
-
- MessageProducer producer = producerSession.createProducer(_queue);
-
- // Create and send message 0
- Message msg = producerSession.createMessage();
- msg.setIntProperty(INDEX, 0);
- producer.send(msg);
-
- // DON'T commit message .. fail connection
-
- failBroker(getFailingPort());
-
- // Ensure destination exists for sending
- producerSession.createConsumer(_queue).close();
-
- // Send the next message
- msg.setIntProperty(INDEX, 1);
- try
- {
- producer.send(msg);
- fail("Should fail with Qpid as we provide early warning of the dirty session via a JMSException.");
- }
- catch (JMSException jmse)
- {
- assertEquals("Early warning of dirty session not correct",
- "Failover has occurred and session is dirty so unable to send.", jmse.getMessage());
- }
-
- // Ignore that the session is dirty and attempt to commit to validate the
- // exception is thrown. AND that the above failure notification did NOT
- // clean up the session.
-
- try
- {
- producerSession.commit();
- fail("Session is dirty we should get an TransactionRolledBackException");
- }
- catch (TransactionRolledBackException trbe)
- {
- // Normal path.
- }
-
- // Resending of messages should now work ok as the commit was forcilbly rolledback
- msg.setIntProperty(INDEX, 0);
- producer.send(msg);
- msg.setIntProperty(INDEX, 1);
- producer.send(msg);
-
- producerSession.commit();
-
- assertEquals("Wrong number of messages on queue", 2,
- ((AMQSession) producerSession).getQueueDepth((AMQDestination) _queue));
- }
-
- /**
- * If a transacted session has failed over whilst it has uncommitted sent
- * data then we need to throw a TransactedRolledbackException on commit()
- *
- * The alternative would be to maintain a replay buffer so that the message
- * could be resent. This is not currently implemented
- *
- * @throws Exception if something goes wrong.
- */
- public void testDirtySendingOnMessageTransacted() throws Exception
- {
- NUM_MESSAGES = 1;
- _receviedAll = new CountDownLatch(NUM_MESSAGES);
- ((AMQConnection) _connection).setConnectionListener(this);
-
- init(true, Session.SESSION_TRANSACTED);
-
- _consumer.setMessageListener(new MessageListener()
- {
-
- public void onMessage(Message message)
- {
- try
- {
- // Create and send message 0
- Message msg = _consumerSession.createMessage();
- msg.setIntProperty(INDEX, 0);
- _producer.send(msg);
-
- // DON'T commit message .. fail connection
-
- failBroker(getFailingPort());
-
- // rep
- repopulateBroker();
-
- // Destination will exist as this failBroker will populate
- // the queue with 1 message
-
- // Send the next message
- msg.setIntProperty(INDEX, 1);
- try
- {
- _producer.send(msg);
- fail("Should fail with Qpid as we provide early warning of the dirty session via a JMSException.");
- }
- catch (JMSException jmse)
- {
- assertEquals("Early warning of dirty session not correct",
- "Failover has occurred and session is dirty so unable to send.", jmse.getMessage());
- }
-
- // Ignore that the session is dirty and attempt to commit to validate the
- // exception is thrown. AND that the above failure notification did NOT
- // clean up the session.
-
- try
- {
- _consumerSession.commit();
- fail("Session is dirty we should get an TransactionRolledBackException");
- }
- catch (TransactionRolledBackException trbe)
- {
- // Normal path.
- }
-
- // Resend messages
- msg.setIntProperty(INDEX, 0);
- msg.setStringProperty(MSG, SEND_FROM_ON_MESSAGE_TEXT);
- _producer.send(msg);
- msg.setIntProperty(INDEX, 1);
- msg.setStringProperty(MSG, SEND_FROM_ON_MESSAGE_TEXT);
- _producer.send(msg);
-
- _consumerSession.commit();
-
- // Stop this consumer .. can't do _consumer.stop == DEADLOCK
- // this doesn't seem to stop dispatcher running
- _connection.stop();
-
- // Signal that the onMessage send part of test is complete
- // main thread can validate that messages are correct
- _receviedAll.countDown();
-
- }
- catch (Exception e)
- {
- fail(e);
- }
-
- }
-
- });
-
- _connection.start();
-
- if (!_receviedAll.await(10000L, TimeUnit.MILLISECONDS))
- {
- // Check to see if we ended due to an exception in the onMessage handler
- Exception cause = _causeOfFailure.get();
- if (cause != null)
- {
- cause.printStackTrace();
- fail(cause.getMessage());
- }
- else
- {
- fail("All messages not received:" + _receviedAll.getCount() + "/" + NUM_MESSAGES);
- }
- }
-
- // Check to see if we ended due to an exception in the onMessage handler
- Exception cause = _causeOfFailure.get();
- if (cause != null)
- {
- cause.printStackTrace();
- fail(cause.getMessage());
- }
-
- _consumer.close();
- _consumerSession.close();
-
- _consumerSession = _connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- _connection.start();
-
- // Validate that we could send the messages as expected.
- assertEquals("Wrong number of messages on queue", 3,
- ((AMQSession) _consumerSession).getQueueDepth((AMQDestination) _queue));
-
- MessageConsumer consumer = _consumerSession.createConsumer(_queue);
-
- //Validate the message sent to setup the failed over broker.
- Message message = consumer.receive(1000);
- assertNotNull("Message " + 0 + " not received.", message);
- assertEquals("Incorrect message received", 0, message.getIntProperty(INDEX));
-
- // Validate the two messages sent from within the onMessage
- for (int index = 0; index <= 1; index++)
- {
- message = consumer.receive(1000);
- assertNotNull("Message " + index + " not received.", message);
- assertEquals("Incorrect message received", index, message.getIntProperty(INDEX));
- assertEquals("Incorrect message text for message:" + index, SEND_FROM_ON_MESSAGE_TEXT, message.getStringProperty(MSG));
- }
-
- assertNull("Extra message received.", consumer.receiveNoWait());
-
- _consumerSession.close();
-
- assertEquals("Wrong number of messages on queue", 0,
- ((AMQSession) getConnection().createSession(false, Session.AUTO_ACKNOWLEDGE)).getQueueDepth((AMQDestination) _queue));
- }
-
- private void repopulateBroker() throws Exception
- {
- // Repopulate this new broker so we can test what happends after failover
-
- //Get the connection to the first (main port) broker.
- Connection connection = getConnection();
- // Use a transaction to send messages so we can be sure they arrive.
- Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
- // ensure destination is created.
- session.createConsumer(_queue).close();
-
- sendMessage(session, _queue, NUM_MESSAGES);
-
- assertEquals("Wrong number of messages on queue", NUM_MESSAGES,
- ((AMQSession) session).getQueueDepth((AMQDestination) _queue));
-
- connection.close();
- }
-
- // AMQConnectionListener Interface.. used so we can validate that we
- // actually failed over.
-
- public void bytesSent(long count)
- {
- }
-
- public void bytesReceived(long count)
- {
- }
-
- public boolean preFailover(boolean redirect)
- {
- //Allow failover
- return true;
- }
-
- public boolean preResubscribe()
- {
- //Allow failover
- return true;
- }
-
- public void failoverComplete()
- {
- _failoverCompleted.countDown();
- }
-
- /**
- * Override so we can block until failover has completd
- *
- * @param port int the port of the broker to fail.
- */
- @Override
- public void failBroker(int port)
- {
- super.failBroker(port);
-
- try
- {
- if (!_failoverCompleted.await(DEFAULT_FAILOVER_TIME, TimeUnit.MILLISECONDS))
- {
- fail("Failover did not occur in specified time:" + DEFAULT_FAILOVER_TIME);
- }
- }
- catch (InterruptedException e)
- {
- fail("Failover was interuppted");
- }
- }
-
- /**
- * Pass the given exception back to the waiting thread to fail the test run.
- *
- * @param e The exception that is causing the test to fail.
- */
- protected void fail(Exception e)
- {
- _causeOfFailure.set(e);
- // End the test.
- while (_receviedAll.getCount() != 0)
- {
- _receviedAll.countDown();
- }
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/topic/DurableSubscriptionTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/topic/DurableSubscriptionTest.java
deleted file mode 100644
index d799b141c0..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/topic/DurableSubscriptionTest.java
+++ /dev/null
@@ -1,844 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.topic;
-
-import java.io.IOException;
-import java.util.Set;
-
-import javax.jms.Connection;
-import javax.jms.InvalidDestinationException;
-import javax.jms.InvalidSelectorException;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-import javax.jms.Session;
-import javax.jms.TextMessage;
-import javax.jms.Topic;
-import javax.jms.TopicSubscriber;
-import javax.management.MBeanServerConnection;
-import javax.management.ObjectName;
-import javax.management.remote.JMXConnector;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.client.AMQTopic;
-import org.apache.qpid.management.common.JMXConnnectionFactory;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * @todo Code to check that a consumer gets only one particular method could be factored into a re-usable method (as
- * a static on a base test helper class, e.g. TestUtils.
- *
- * @todo Code to create test end-points using session per connection, or all sessions on one connection, to be factored
- * out to make creating this test variation simpler. Want to make this variation available through LocalCircuit,
- * driven by the test model.
- */
-public class DurableSubscriptionTest extends QpidBrokerTestCase
-{
- private static final Logger _logger = LoggerFactory.getLogger(DurableSubscriptionTest.class);
-
- /** Timeout for receive() if we are expecting a message */
- private static final long POSITIVE_RECEIVE_TIMEOUT = 2000;
-
- /** Timeout for receive() if we are not expecting a message */
- private static final long NEGATIVE_RECEIVE_TIMEOUT = 1000;
-
- private JMXConnector _jmxc;
- private MBeanServerConnection _mbsc;
- private static final String USER = "admin";
- private static final String PASSWORD = "admin";
- private boolean _jmxConnected;
-
- public void setUp() throws Exception
- {
- setConfigurationProperty("management.enabled", "true");
- _jmxConnected=false;
- super.setUp();
- }
-
- public void tearDown() throws Exception
- {
- if(_jmxConnected)
- {
- try
- {
- _jmxc.close();
- }
- catch (IOException e)
- {
- e.printStackTrace();
- }
- }
-
- super.tearDown();
- }
-
- public void testUnsubscribe() throws Exception
- {
- AMQConnection con = (AMQConnection) getConnection("guest", "guest");
- AMQTopic topic = new AMQTopic(con, "MyDurableSubscriptionTestTopic");
- _logger.info("Create Session 1");
- Session session1 = con.createSession(false, AMQSession.NO_ACKNOWLEDGE);
- _logger.info("Create Consumer on Session 1");
- MessageConsumer consumer1 = session1.createConsumer(topic);
- _logger.info("Create Producer on Session 1");
- MessageProducer producer = session1.createProducer(topic);
-
- _logger.info("Create Session 2");
- Session session2 = con.createSession(false, AMQSession.NO_ACKNOWLEDGE);
- _logger.info("Create Durable Subscriber on Session 2");
- TopicSubscriber consumer2 = session2.createDurableSubscriber(topic, "MySubscription");
-
- _logger.info("Starting connection");
- con.start();
-
- _logger.info("Producer sending message A");
- producer.send(session1.createTextMessage("A"));
-
- ((AMQSession<?, ?>) session1).sync();
-
- //check the dur sub's underlying queue now has msg count 1
- AMQQueue subQueue = new AMQQueue("amq.topic", "clientid" + ":" + "MySubscription");
- assertEquals("Msg count should be 1", 1, ((AMQSession<?, ?>) session1).getQueueDepth(subQueue));
-
- Message msg;
- _logger.info("Receive message on consumer 1:expecting A");
- msg = consumer1.receive(POSITIVE_RECEIVE_TIMEOUT);
- assertNotNull("Message should have been received",msg);
- assertEquals("A", ((TextMessage) msg).getText());
- _logger.info("Receive message on consumer 1 :expecting null");
- msg = consumer1.receive(NEGATIVE_RECEIVE_TIMEOUT);
- assertEquals(null, msg);
-
- _logger.info("Receive message on consumer 2:expecting A");
- msg = consumer2.receive(POSITIVE_RECEIVE_TIMEOUT);
- assertNotNull("Message should have been received",msg);
- assertEquals("A", ((TextMessage) msg).getText());
- msg = consumer2.receive(NEGATIVE_RECEIVE_TIMEOUT);
- _logger.info("Receive message on consumer 1 :expecting null");
- assertEquals(null, msg);
-
- ((AMQSession<?, ?>) session2).sync();
-
- //check the dur sub's underlying queue now has msg count 0
- assertEquals("Msg count should be 0", 0, ((AMQSession<?, ?>) session2).getQueueDepth(subQueue));
-
- consumer2.close();
- _logger.info("Unsubscribe session2/consumer2");
- session2.unsubscribe("MySubscription");
-
- ((AMQSession<?, ?>) session2).sync();
-
- if(isJavaBroker() && isExternalBroker())
- {
- //Verify that the queue was deleted by querying for its JMX MBean
- _jmxc = JMXConnnectionFactory.getJMXConnection(5000, "127.0.0.1",
- getManagementPort(getPort()), USER, PASSWORD);
-
- _jmxConnected = true;
- _mbsc = _jmxc.getMBeanServerConnection();
-
- //must replace the occurrence of ':' in queue name with '-'
- String queueObjectNameText = "clientid" + "-" + "MySubscription";
-
- ObjectName objName = new ObjectName("org.apache.qpid:type=VirtualHost.Queue,name="
- + queueObjectNameText + ",*");
-
- Set<ObjectName> objectInstances = _mbsc.queryNames(objName, null);
-
- if(objectInstances.size() != 0)
- {
- fail("Queue MBean was found. Expected queue to have been deleted");
- }
- else
- {
- _logger.info("Underlying dueue for the durable subscription was confirmed deleted.");
- }
- }
-
- //verify unsubscribing the durable subscriber did not affect the non-durable one
- _logger.info("Producer sending message B");
- producer.send(session1.createTextMessage("B"));
-
- _logger.info("Receive message on consumer 1 :expecting B");
- msg = consumer1.receive(POSITIVE_RECEIVE_TIMEOUT);
- assertNotNull("Message should have been received",msg);
- assertEquals("B", ((TextMessage) msg).getText());
- _logger.info("Receive message on consumer 1 :expecting null");
- msg = consumer1.receive(NEGATIVE_RECEIVE_TIMEOUT);
- assertEquals(null, msg);
-
- _logger.info("Close connection");
- con.close();
- }
-
- public void testDurabilityNOACK() throws Exception
- {
- durabilityImpl(AMQSession.NO_ACKNOWLEDGE, false);
- }
-
- public void testDurabilityAUTOACK() throws Exception
- {
- durabilityImpl(Session.AUTO_ACKNOWLEDGE, false);
- }
-
- public void testDurabilityAUTOACKwithRestartIfPersistent() throws Exception
- {
- if(!isBrokerStorePersistent())
- {
- System.out.println("The broker store is not persistent, skipping this test.");
- return;
- }
-
- durabilityImpl(Session.AUTO_ACKNOWLEDGE, true);
- }
-
- public void testDurabilityNOACKSessionPerConnection() throws Exception
- {
- durabilityImplSessionPerConnection(AMQSession.NO_ACKNOWLEDGE);
- }
-
- public void testDurabilityAUTOACKSessionPerConnection() throws Exception
- {
- durabilityImplSessionPerConnection(Session.AUTO_ACKNOWLEDGE);
- }
-
- private void durabilityImpl(int ackMode, boolean restartBroker) throws Exception
- {
- AMQConnection con = (AMQConnection) getConnection("guest", "guest");
- AMQTopic topic = new AMQTopic(con, "MyTopic");
- Session session1 = con.createSession(false, ackMode);
- MessageConsumer consumer1 = session1.createConsumer(topic);
-
- Session sessionProd = con.createSession(false, ackMode);
- MessageProducer producer = sessionProd.createProducer(topic);
-
- Session session2 = con.createSession(false, ackMode);
- TopicSubscriber consumer2 = session2.createDurableSubscriber(topic, "MySubscription");
-
- con.start();
-
- //send message A and check both consumers receive
- producer.send(session1.createTextMessage("A"));
-
- Message msg;
- _logger.info("Receive message on consumer 1 :expecting A");
- msg = consumer1.receive(POSITIVE_RECEIVE_TIMEOUT);
- assertNotNull("Message should have been received",msg);
- assertEquals("A", ((TextMessage) msg).getText());
- msg = consumer1.receive(NEGATIVE_RECEIVE_TIMEOUT);
- assertEquals(null, msg);
-
- _logger.info("Receive message on consumer 2 :expecting A");
- msg = consumer2.receive(POSITIVE_RECEIVE_TIMEOUT);
- assertNotNull("Message should have been received",msg);
- assertEquals("A", ((TextMessage) msg).getText());
- msg = consumer2.receive(NEGATIVE_RECEIVE_TIMEOUT);
- assertEquals(null, msg);
-
- //send message B, receive with consumer 1, and disconnect consumer 2 to leave the message behind (if not NO_ACK)
- producer.send(session1.createTextMessage("B"));
-
- _logger.info("Receive message on consumer 1 :expecting B");
- msg = consumer1.receive(500);
- assertNotNull("Consumer 1 should get message 'B'.", msg);
- assertEquals("Incorrect Message received on consumer1.", "B", ((TextMessage) msg).getText());
- _logger.info("Receive message on consumer 1 :expecting null");
- msg = consumer1.receive(500);
- assertNull("There should be no more messages for consumption on consumer1.", msg);
-
- consumer2.close();
- session2.close();
-
- //Send message C, then connect consumer 3 to durable subscription and get
- //message B if not using NO_ACK, then receive C with consumer 1 and 3
- producer.send(session1.createTextMessage("C"));
-
- Session session3 = con.createSession(false, ackMode);
- MessageConsumer consumer3 = session3.createDurableSubscriber(topic, "MySubscription");
-
- if(ackMode == AMQSession.NO_ACKNOWLEDGE)
- {
- //Do nothing if NO_ACK was used, as prefetch means the message was dropped
- //when we didn't call receive() to get it before closing consumer 2
- }
- else
- {
- _logger.info("Receive message on consumer 3 :expecting B");
- msg = consumer3.receive(500);
- assertNotNull("Consumer 3 should get message 'B'.", msg);
- assertEquals("Incorrect Message received on consumer3.", "B", ((TextMessage) msg).getText());
- }
-
- _logger.info("Receive message on consumer 1 :expecting C");
- msg = consumer1.receive(500);
- assertNotNull("Consumer 1 should get message 'C'.", msg);
- assertEquals("Incorrect Message received on consumer1.", "C", ((TextMessage) msg).getText());
- _logger.info("Receive message on consumer 1 :expecting null");
- msg = consumer1.receive(500);
- assertNull("There should be no more messages for consumption on consumer1.", msg);
-
- _logger.info("Receive message on consumer 3 :expecting C");
- msg = consumer3.receive(500);
- assertNotNull("Consumer 3 should get message 'C'.", msg);
- assertEquals("Incorrect Message received on consumer3.", "C", ((TextMessage) msg).getText());
- _logger.info("Receive message on consumer 3 :expecting null");
- msg = consumer3.receive(500);
- assertNull("There should be no more messages for consumption on consumer3.", msg);
-
- consumer1.close();
- consumer3.close();
-
- session3.unsubscribe("MySubscription");
-
- con.close();
-
- if(restartBroker)
- {
- try
- {
- restartBroker();
- }
- catch (Exception e)
- {
- fail("Error restarting the broker");
- }
- }
- }
-
- private void durabilityImplSessionPerConnection(int ackMode) throws Exception
- {
- Message msg;
- // Create producer.
- AMQConnection con0 = (AMQConnection) getConnection("guest", "guest");
- con0.start();
- Session session0 = con0.createSession(false, ackMode);
-
- AMQTopic topic = new AMQTopic(con0, "MyTopic");
-
- Session sessionProd = con0.createSession(false, ackMode);
- MessageProducer producer = sessionProd.createProducer(topic);
-
- // Create consumer 1.
- AMQConnection con1 = (AMQConnection) getConnection("guest", "guest");
- con1.start();
- Session session1 = con1.createSession(false, ackMode);
-
- MessageConsumer consumer1 = session1.createConsumer(topic);
-
- // Create consumer 2.
- AMQConnection con2 = (AMQConnection) getConnection("guest", "guest");
- con2.start();
- Session session2 = con2.createSession(false, ackMode);
-
- TopicSubscriber consumer2 = session2.createDurableSubscriber(topic, "MySubscription");
-
- // Send message and check that both consumers get it and only it.
- producer.send(session0.createTextMessage("A"));
-
- msg = consumer1.receive(500);
- assertNotNull("Message should be available", msg);
- assertEquals("Message Text doesn't match", "A", ((TextMessage) msg).getText());
- msg = consumer1.receive(500);
- assertNull("There should be no more messages for consumption on consumer1.", msg);
-
- msg = consumer2.receive(POSITIVE_RECEIVE_TIMEOUT);
- assertNotNull("Message should have been received",msg);
- assertEquals("Consumer 2 should also received the first msg.", "A", ((TextMessage) msg).getText());
- msg = consumer2.receive(NEGATIVE_RECEIVE_TIMEOUT);
- assertNull("There should be no more messages for consumption on consumer2.", msg);
-
- // Send message and receive on consumer 1.
- producer.send(session0.createTextMessage("B"));
-
- _logger.info("Receive message on consumer 1 :expecting B");
- msg = consumer1.receive(POSITIVE_RECEIVE_TIMEOUT);
- assertEquals("B", ((TextMessage) msg).getText());
- _logger.info("Receive message on consumer 1 :expecting null");
- msg = consumer1.receive(NEGATIVE_RECEIVE_TIMEOUT);
- assertEquals(null, msg);
-
- // Detach the durable subscriber.
- consumer2.close();
- session2.close();
- con2.close();
-
- // Send message C and receive on consumer 1
- producer.send(session0.createTextMessage("C"));
-
- _logger.info("Receive message on consumer 1 :expecting C");
- msg = consumer1.receive(POSITIVE_RECEIVE_TIMEOUT);
- assertEquals("C", ((TextMessage) msg).getText());
- _logger.info("Receive message on consumer 1 :expecting null");
- msg = consumer1.receive(NEGATIVE_RECEIVE_TIMEOUT);
- assertEquals(null, msg);
-
- // Re-attach a new consumer to the durable subscription, and check that it gets message B it left (if not NO_ACK)
- // and also gets message C sent after it was disconnected.
- AMQConnection con3 = (AMQConnection) getConnection("guest", "guest");
- con3.start();
- Session session3 = con3.createSession(false, ackMode);
-
- TopicSubscriber consumer3 = session3.createDurableSubscriber(topic, "MySubscription");
-
- if(ackMode == AMQSession.NO_ACKNOWLEDGE)
- {
- //Do nothing if NO_ACK was used, as prefetch means the message was dropped
- //when we didn't call receive() to get it before closing consumer 2
- }
- else
- {
- _logger.info("Receive message on consumer 3 :expecting B");
- msg = consumer3.receive(POSITIVE_RECEIVE_TIMEOUT);
- assertNotNull(msg);
- assertEquals("B", ((TextMessage) msg).getText());
- }
-
- _logger.info("Receive message on consumer 3 :expecting C");
- msg = consumer3.receive(POSITIVE_RECEIVE_TIMEOUT);
- assertNotNull("Consumer 3 should get message 'C'.", msg);
- assertEquals("Incorrect Message recevied on consumer3.", "C", ((TextMessage) msg).getText());
- _logger.info("Receive message on consumer 3 :expecting null");
- msg = consumer3.receive(NEGATIVE_RECEIVE_TIMEOUT);
- assertNull("There should be no more messages for consumption on consumer3.", msg);
-
- consumer1.close();
- consumer3.close();
-
- session3.unsubscribe("MySubscription");
-
- con0.close();
- con1.close();
- con3.close();
- }
-
- /**
- * This tests the fix for QPID-1085
- * Creates a durable subscriber with an invalid selector, checks that the
- * exception is thrown correctly and that the subscription is not created.
- * @throws Exception
- */
- public void testDurableWithInvalidSelector() throws Exception
- {
- Connection conn = getConnection();
- conn.start();
- Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
- AMQTopic topic = new AMQTopic((AMQConnection) conn, "MyTestDurableWithInvalidSelectorTopic");
- MessageProducer producer = session.createProducer(topic);
- producer.send(session.createTextMessage("testDurableWithInvalidSelector1"));
- try
- {
- TopicSubscriber deadSubscriber = session.createDurableSubscriber(topic, "testDurableWithInvalidSelectorSub",
- "=TEST 'test", true);
- assertNull("Subscriber should not have been created", deadSubscriber);
- }
- catch (JMSException e)
- {
- assertTrue("Wrong type of exception thrown", e instanceof InvalidSelectorException);
- }
- TopicSubscriber liveSubscriber = session.createDurableSubscriber(topic, "testDurableWithInvalidSelectorSub");
- assertNotNull("Subscriber should have been created", liveSubscriber);
-
- producer.send(session.createTextMessage("testDurableWithInvalidSelector2"));
-
- Message msg = liveSubscriber.receive(POSITIVE_RECEIVE_TIMEOUT);
- assertNotNull ("Message should have been received", msg);
- assertEquals ("testDurableWithInvalidSelector2", ((TextMessage) msg).getText());
- assertNull("Should not receive subsequent message", liveSubscriber.receive(200));
- liveSubscriber.close();
- session.unsubscribe("testDurableWithInvalidSelectorSub");
- }
-
- /**
- * This tests the fix for QPID-1085
- * Creates a durable subscriber with an invalid destination, checks that the
- * exception is thrown correctly and that the subscription is not created.
- * @throws Exception
- */
- public void testDurableWithInvalidDestination() throws Exception
- {
- Connection conn = getConnection();
- conn.start();
- Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
- AMQTopic topic = new AMQTopic((AMQConnection) conn, "testDurableWithInvalidDestinationTopic");
- try
- {
- TopicSubscriber deadSubscriber = session.createDurableSubscriber(null, "testDurableWithInvalidDestinationsub");
- assertNull("Subscriber should not have been created", deadSubscriber);
- }
- catch (InvalidDestinationException e)
- {
- // This was expected
- }
- MessageProducer producer = session.createProducer(topic);
- producer.send(session.createTextMessage("testDurableWithInvalidSelector1"));
-
- TopicSubscriber liveSubscriber = session.createDurableSubscriber(topic, "testDurableWithInvalidDestinationsub");
- assertNotNull("Subscriber should have been created", liveSubscriber);
-
- producer.send(session.createTextMessage("testDurableWithInvalidSelector2"));
- Message msg = liveSubscriber.receive(POSITIVE_RECEIVE_TIMEOUT);
- assertNotNull ("Message should have been received", msg);
- assertEquals ("testDurableWithInvalidSelector2", ((TextMessage) msg).getText());
- assertNull("Should not receive subsequent message", liveSubscriber.receive(200));
-
- session.unsubscribe("testDurableWithInvalidDestinationsub");
- }
-
- /**
- * Creates a durable subscription with a selector, then changes that selector on resubscription
- * <p>
- * QPID-1202, QPID-2418
- */
- public void testResubscribeWithChangedSelector() throws Exception
- {
- Connection conn = getConnection();
- conn.start();
- Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
- AMQTopic topic = new AMQTopic((AMQConnection) conn, "testResubscribeWithChangedSelector");
- MessageProducer producer = session.createProducer(topic);
-
- // Create durable subscriber that matches A
- TopicSubscriber subA = session.createDurableSubscriber(topic,
- "testResubscribeWithChangedSelector",
- "Match = True", false);
-
- // Send 1 matching message and 1 non-matching message
- sendMatchingAndNonMatchingMessage(session, producer);
-
- Message rMsg = subA.receive(NEGATIVE_RECEIVE_TIMEOUT);
- assertNotNull(rMsg);
- assertEquals("Content was wrong",
- "testResubscribeWithChangedSelector1",
- ((TextMessage) rMsg).getText());
-
- rMsg = subA.receive(NEGATIVE_RECEIVE_TIMEOUT);
- assertNull(rMsg);
-
- // Disconnect subscriber
- subA.close();
-
- // Reconnect with new selector that matches B
- TopicSubscriber subB = session.createDurableSubscriber(topic,
- "testResubscribeWithChangedSelector","Match = False", false);
-
- //verify no messages are now recieved.
- rMsg = subB.receive(NEGATIVE_RECEIVE_TIMEOUT);
- assertNull("Should not have received message as the selector was changed", rMsg);
-
- // Check that new messages are received properly
- sendMatchingAndNonMatchingMessage(session, producer);
- rMsg = subB.receive(POSITIVE_RECEIVE_TIMEOUT);
-
- assertNotNull("Message should have been received", rMsg);
- assertEquals("Content was wrong",
- "testResubscribeWithChangedSelector2",
- ((TextMessage) rMsg).getText());
-
-
- rMsg = subB.receive(NEGATIVE_RECEIVE_TIMEOUT);
- assertNull("Message should not have been received",rMsg);
- session.unsubscribe("testResubscribeWithChangedSelector");
- }
-
- public void testDurableSubscribeWithTemporaryTopic() throws Exception
- {
- Connection conn = getConnection();
- conn.start();
- Session ssn = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
- Topic topic = ssn.createTemporaryTopic();
- try
- {
- ssn.createDurableSubscriber(topic, "test");
- fail("expected InvalidDestinationException");
- }
- catch (InvalidDestinationException ex)
- {
- // this is expected
- }
- try
- {
- ssn.createDurableSubscriber(topic, "test", null, false);
- fail("expected InvalidDestinationException");
- }
- catch (InvalidDestinationException ex)
- {
- // this is expected
- }
- }
-
- private void sendMatchingAndNonMatchingMessage(Session session, MessageProducer producer) throws JMSException
- {
- TextMessage msg = session.createTextMessage("testResubscribeWithChangedSelector1");
- msg.setBooleanProperty("Match", true);
- producer.send(msg);
- msg = session.createTextMessage("testResubscribeWithChangedSelector2");
- msg.setBooleanProperty("Match", false);
- producer.send(msg);
- }
-
-
- /**
- * create and register a durable subscriber with a message selector and then close it
- * create a publisher and send 5 right messages and 5 wrong messages
- * create another durable subscriber with the same selector and name
- * check messages are still there
- * <p>
- * QPID-2418
- */
- public void testDurSubSameMessageSelector() throws Exception
- {
- Connection conn = getConnection();
- conn.start();
- Session session = conn.createSession(true, Session.SESSION_TRANSACTED);
- AMQTopic topic = new AMQTopic((AMQConnection) conn, "sameMessageSelector");
-
- //create and register a durable subscriber with a message selector and then close it
- TopicSubscriber subOne = session.createDurableSubscriber(topic, "sameMessageSelector", "testprop = TRUE", false);
- subOne.close();
-
- MessageProducer producer = session.createProducer(topic);
- for (int i = 0; i < 5; i++)
- {
- Message message = session.createMessage();
- message.setBooleanProperty("testprop", true);
- producer.send(message);
- message = session.createMessage();
- message.setBooleanProperty("testprop", false);
- producer.send(message);
- }
- session.commit();
- producer.close();
-
- // should be 5 or 10 messages on queue now
- // (5 for the java broker due to use of server side selectors, and 10 for the cpp broker due to client side selectors only)
- AMQQueue queue = new AMQQueue("amq.topic", "clientid" + ":" + "sameMessageSelector");
- assertEquals("Queue depth is wrong", isJavaBroker() ? 5 : 10, ((AMQSession<?, ?>) session).getQueueDepth(queue));
-
- // now recreate the durable subscriber and check the received messages
- TopicSubscriber subTwo = session.createDurableSubscriber(topic, "sameMessageSelector", "testprop = TRUE", false);
-
- for (int i = 0; i < 5; i++)
- {
- Message message = subTwo.receive(1000);
- if (message == null)
- {
- fail("sameMessageSelector test failed. no message was returned");
- }
- else
- {
- assertEquals("sameMessageSelector test failed. message selector not reset",
- "true", message.getStringProperty("testprop"));
- }
- }
-
- session.commit();
-
- // Check queue has no messages
- if (isJavaBroker())
- {
- assertEquals("Queue should be empty", 0, ((AMQSession<?, ?>) session).getQueueDepth(queue));
- }
- else
- {
- assertTrue("At most the queue should have only 1 message", ((AMQSession<?, ?>) session).getQueueDepth(queue) <= 1);
- }
-
- // Unsubscribe
- session.unsubscribe("sameMessageSelector");
-
- conn.close();
- }
-
- /**
- * <ul>
- * <li>create and register a durable subscriber with a message selector
- * <li>create another durable subscriber with a different selector and same name
- * <li>check first subscriber is now closed
- * <li>create a publisher and send messages
- * <li>check messages are received correctly
- * </ul>
- * <p>
- * QPID-2418
- */
- public void testResubscribeWithChangedSelectorNoClose() throws Exception
- {
- Connection conn = getConnection();
- conn.start();
- Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
- AMQTopic topic = new AMQTopic((AMQConnection) conn, "testResubscribeWithChangedSelectorNoClose");
-
- // Create durable subscriber that matches A
- TopicSubscriber subA = session.createDurableSubscriber(topic,
- "testResubscribeWithChangedSelectorNoClose",
- "Match = True", false);
-
- // Reconnect with new selector that matches B
- TopicSubscriber subB = session.createDurableSubscriber(topic,
- "testResubscribeWithChangedSelectorNoClose",
- "Match = false", false);
-
- // First subscription has been closed
- try
- {
- subA.receive(1000);
- fail("First subscription was not closed");
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
-
- conn.stop();
-
- // Send 1 matching message and 1 non-matching message
- MessageProducer producer = session.createProducer(topic);
- TextMessage msg = session.createTextMessage("testResubscribeWithChangedSelectorAndRestart1");
- msg.setBooleanProperty("Match", true);
- producer.send(msg);
- msg = session.createTextMessage("testResubscribeWithChangedSelectorAndRestart2");
- msg.setBooleanProperty("Match", false);
- producer.send(msg);
-
- // should be 1 or 2 messages on queue now
- // (1 for the java broker due to use of server side selectors, and 2 for the cpp broker due to client side selectors only)
- AMQQueue queue = new AMQQueue("amq.topic", "clientid" + ":" + "testResubscribeWithChangedSelectorNoClose");
- assertEquals("Queue depth is wrong", isJavaBroker() ? 1 : 2, ((AMQSession<?, ?>) session).getQueueDepth(queue));
-
- conn.start();
-
- Message rMsg = subB.receive(1000);
- assertNotNull(rMsg);
- assertEquals("Content was wrong",
- "testResubscribeWithChangedSelectorAndRestart2",
- ((TextMessage) rMsg).getText());
-
- rMsg = subB.receive(1000);
- assertNull(rMsg);
-
- // Check queue has no messages
- assertEquals("Queue should be empty", 0, ((AMQSession<?, ?>) session).getQueueDepth(queue));
-
- conn.close();
- }
-
- /**
- * <ul>
- * <li>create and register a durable subscriber with no message selector
- * <li>create another durable subscriber with a selector and same name
- * <li>check first subscriber is now closed
- * <li>create a publisher and send messages
- * <li>check messages are recieved correctly
- * </ul>
- * <p>
- * QPID-2418
- */
- public void testDurSubAddMessageSelectorNoClose() throws Exception
- {
- Connection conn = getConnection();
- conn.start();
- Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
- AMQTopic topic = new AMQTopic((AMQConnection) conn, "subscriptionName");
-
- // create and register a durable subscriber with no message selector
- TopicSubscriber subOne = session.createDurableSubscriber(topic, "subscriptionName", null, false);
-
- // now create a durable subscriber with a selector
- TopicSubscriber subTwo = session.createDurableSubscriber(topic, "subscriptionName", "testprop = TRUE", false);
-
- // First subscription has been closed
- try
- {
- subOne.receive(1000);
- fail("First subscription was not closed");
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
-
- conn.stop();
-
- // Send 1 matching message and 1 non-matching message
- MessageProducer producer = session.createProducer(topic);
- TextMessage msg = session.createTextMessage("testResubscribeWithChangedSelectorAndRestart1");
- msg.setBooleanProperty("testprop", true);
- producer.send(msg);
- msg = session.createTextMessage("testResubscribeWithChangedSelectorAndRestart2");
- msg.setBooleanProperty("testprop", false);
- producer.send(msg);
-
- // should be 1 or 2 messages on queue now
- // (1 for the java broker due to use of server side selectors, and 2 for the cpp broker due to client side selectors only)
- AMQQueue queue = new AMQQueue("amq.topic", "clientid" + ":" + "subscriptionName");
- assertEquals("Queue depth is wrong", isJavaBroker() ? 1 : 2, ((AMQSession<?, ?>) session).getQueueDepth(queue));
-
- conn.start();
-
- Message rMsg = subTwo.receive(1000);
- assertNotNull(rMsg);
- assertEquals("Content was wrong",
- "testResubscribeWithChangedSelectorAndRestart1",
- ((TextMessage) rMsg).getText());
-
- rMsg = subTwo.receive(1000);
- assertNull(rMsg);
-
- // Check queue has no messages
- assertEquals("Queue should be empty", 0, ((AMQSession<?, ?>) session).getQueueDepth(queue));
-
- conn.close();
- }
-
- /**
- * <ul>
- * <li>create and register a durable subscriber with no message selector
- * <li>try to create another durable with the same name, should fail
- * </ul>
- * <p>
- * QPID-2418
- */
- public void testDurSubNoSelectorResubscribeNoClose() throws Exception
- {
- Connection conn = getConnection();
- conn.start();
- Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
- AMQTopic topic = new AMQTopic((AMQConnection) conn, "subscriptionName");
-
- // create and register a durable subscriber with no message selector
- session.createDurableSubscriber(topic, "subscriptionName", null, false);
-
- // try to recreate the durable subscriber
- try
- {
- session.createDurableSubscriber(topic, "subscriptionName", null, false);
- fail("Subscription should not have been created");
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/topic/TopicPublisherTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/topic/TopicPublisherTest.java
deleted file mode 100644
index 5874133ab1..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/topic/TopicPublisherTest.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.topic;
-
-import javax.jms.MessageConsumer;
-import javax.jms.TextMessage;
-import javax.jms.TopicPublisher;
-import javax.jms.TopicSession;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.client.AMQTopic;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-/**
- * @author Apache Software Foundation
- */
-public class TopicPublisherTest extends QpidBrokerTestCase
-{
- protected void setUp() throws Exception
- {
- super.setUp();
- }
-
- protected void tearDown() throws Exception
- {
- super.tearDown();
- }
-
- public void testUnidentifiedProducer() throws Exception
- {
-
- AMQConnection con = (AMQConnection) getConnection("guest", "guest");
- AMQTopic topic = new AMQTopic(con,"MyTopic");
- TopicSession session1 = con.createTopicSession(false, AMQSession.NO_ACKNOWLEDGE);
- TopicPublisher publisher = session1.createPublisher(null);
- MessageConsumer consumer1 = session1.createConsumer(topic);
- con.start();
- publisher.publish(topic, session1.createTextMessage("Hello"));
- TextMessage m = (TextMessage) consumer1.receive(2000);
- assertNotNull(m);
- try
- {
- publisher.publish(session1.createTextMessage("Goodbye"));
- fail("Did not throw UnsupportedOperationException");
- }
- catch (UnsupportedOperationException e)
- {
- // PASS
- }
- con.close();
- }
-
- public static junit.framework.Test suite()
- {
- return new junit.framework.TestSuite(TopicPublisherTest.class);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/topic/TopicSessionTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/topic/TopicSessionTest.java
deleted file mode 100644
index eee232e113..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/topic/TopicSessionTest.java
+++ /dev/null
@@ -1,453 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.topic;
-
-import javax.jms.InvalidDestinationException;
-import javax.jms.JMSException;
-import javax.jms.MessageConsumer;
-import javax.jms.Session;
-import javax.jms.TemporaryTopic;
-import javax.jms.TextMessage;
-import javax.jms.TopicPublisher;
-import javax.jms.TopicSession;
-import javax.jms.TopicSubscriber;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.client.AMQTopic;
-import org.apache.qpid.client.AMQTopicSessionAdaptor;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-
-/** @author Apache Software Foundation */
-public class TopicSessionTest extends QpidBrokerTestCase
-{
-
- protected void setUp() throws Exception
- {
- super.setUp();
- }
-
- protected void tearDown() throws Exception
- {
- super.tearDown();
- }
-
-
- public void testTopicSubscriptionUnsubscription() throws Exception
- {
-
- AMQConnection con = (AMQConnection) getConnection("guest", "guest");
- AMQTopic topic = new AMQTopic(con.getDefaultTopicExchangeName(), "MyTopic");
- TopicSession session1 = con.createTopicSession(true, AMQSession.NO_ACKNOWLEDGE);
- TopicSubscriber sub = session1.createDurableSubscriber(topic, "subscription0");
- TopicPublisher publisher = session1.createPublisher(topic);
-
- con.start();
-
- TextMessage tm = session1.createTextMessage("Hello");
- publisher.publish(tm);
- session1.commit();
-
- tm = (TextMessage) sub.receive(2000);
- assertNotNull(tm);
- session1.commit();
- session1.unsubscribe("subscription0");
-
- try
- {
- session1.unsubscribe("not a subscription");
- fail("expected InvalidDestinationException when unsubscribing from unknown subscription");
- }
- catch (InvalidDestinationException e)
- {
- ; // PASS
- }
- catch (Exception e)
- {
- fail("expected InvalidDestinationException when unsubscribing from unknown subscription, got: " + e);
- }
-
- con.close();
- }
-
- public void testSubscriptionNameReuseForDifferentTopicSingleConnection() throws Exception
- {
- subscriptionNameReuseForDifferentTopic(false);
- }
-
- public void testSubscriptionNameReuseForDifferentTopicTwoConnections() throws Exception
- {
- subscriptionNameReuseForDifferentTopic(true);
- }
-
- private void subscriptionNameReuseForDifferentTopic(boolean shutdown) throws Exception
- {
- AMQConnection con = (AMQConnection) getConnection("guest", "guest");
- AMQTopic topic = new AMQTopic(con, "MyTopic1" + String.valueOf(shutdown));
- AMQTopic topic2 = new AMQTopic(con, "MyOtherTopic1" + String.valueOf(shutdown));
-
- TopicSession session1 = con.createTopicSession(true, AMQSession.AUTO_ACKNOWLEDGE);
- TopicSubscriber sub = session1.createDurableSubscriber(topic, "subscription0");
- TopicPublisher publisher = session1.createPublisher(null);
-
- con.start();
-
- publisher.publish(topic, session1.createTextMessage("hello"));
- session1.commit();
- TextMessage m = (TextMessage) sub.receive(2000);
- assertNotNull(m);
- session1.commit();
-
- if (shutdown)
- {
- session1.close();
- con.close();
- con = (AMQConnection) getConnection("guest", "guest");
- con.start();
- session1 = con.createTopicSession(true, AMQSession.NO_ACKNOWLEDGE);
- publisher = session1.createPublisher(null);
- }
- sub.close();
- TopicSubscriber sub2 = session1.createDurableSubscriber(topic2, "subscription0");
- publisher.publish(topic, session1.createTextMessage("hello"));
- session1.commit();
- if (!shutdown)
- {
- m = (TextMessage) sub2.receive(2000);
- assertNull(m);
- session1.commit();
- }
- publisher.publish(topic2, session1.createTextMessage("goodbye"));
- session1.commit();
- m = (TextMessage) sub2.receive(2000);
- assertNotNull(m);
- assertEquals("goodbye", m.getText());
- session1.unsubscribe("subscription0");
- con.close();
- }
-
- public void testUnsubscriptionAfterConnectionClose() throws Exception
- {
- AMQConnection con1 = (AMQConnection) getClientConnection("guest", "guest", "clientid");
- AMQTopic topic = new AMQTopic(con1, "MyTopic3");
-
- TopicSession session1 = con1.createTopicSession(true, AMQSession.AUTO_ACKNOWLEDGE);
- TopicPublisher publisher = session1.createPublisher(topic);
-
- AMQConnection con2 = (AMQConnection) getClientConnection("guest", "guest", "clientid");
- TopicSession session2 = con2.createTopicSession(true, AMQSession.AUTO_ACKNOWLEDGE);
- TopicSubscriber sub = session2.createDurableSubscriber(topic, "subscription0");
-
- con2.start();
-
- publisher.publish(session1.createTextMessage("Hello"));
- session1.commit();
- TextMessage tm = (TextMessage) sub.receive(2000);
- session2.commit();
- assertNotNull(tm);
- con2.close();
- publisher.publish(session1.createTextMessage("Hello2"));
- session1.commit();
- con2 = (AMQConnection) getClientConnection("guest", "guest", "clientid");
- session2 = con2.createTopicSession(true, AMQSession.NO_ACKNOWLEDGE);
- sub = session2.createDurableSubscriber(topic, "subscription0");
- con2.start();
- tm = (TextMessage) sub.receive(2000);
- session2.commit();
- assertNotNull(tm);
- assertEquals("Hello2", tm.getText());
- session2.unsubscribe("subscription0");
- con1.close();
- con2.close();
- }
-
- public void testTextMessageCreation() throws Exception
- {
-
- AMQConnection con = (AMQConnection) getConnection("guest", "guest");
- AMQTopic topic = new AMQTopic(con, "MyTopic4");
- TopicSession session1 = con.createTopicSession(true, AMQSession.AUTO_ACKNOWLEDGE);
- TopicPublisher publisher = session1.createPublisher(topic);
- MessageConsumer consumer1 = session1.createConsumer(topic);
- con.start();
- TextMessage tm = session1.createTextMessage("Hello");
- publisher.publish(tm);
- session1.commit();
- tm = (TextMessage) consumer1.receive(10000L);
- assertNotNull(tm);
- String msgText = tm.getText();
- assertEquals("Hello", msgText);
- tm = session1.createTextMessage();
- msgText = tm.getText();
- assertNull(msgText);
- publisher.publish(tm);
- session1.commit();
- tm = (TextMessage) consumer1.receive(10000L);
- assertNotNull(tm);
- session1.commit();
- msgText = tm.getText();
- assertNull(msgText);
- tm.clearBody();
- tm.setText("Now we are not null");
- publisher.publish(tm);
- session1.commit();
- tm = (TextMessage) consumer1.receive(2000);
- assertNotNull(tm);
- session1.commit();
- msgText = tm.getText();
- assertEquals("Now we are not null", msgText);
-
- tm = session1.createTextMessage("");
- msgText = tm.getText();
- assertEquals("Empty string not returned", "", msgText);
- publisher.publish(tm);
- session1.commit();
- tm = (TextMessage) consumer1.receive(2000);
- session1.commit();
- assertNotNull(tm);
- assertEquals("Empty string not returned", "", msgText);
- con.close();
- }
-
- public void testSendingSameMessage() throws Exception
- {
- AMQConnection conn = (AMQConnection) getConnection("guest", "guest");
- TopicSession session = conn.createTopicSession(true, Session.AUTO_ACKNOWLEDGE);
- TemporaryTopic topic = session.createTemporaryTopic();
- assertNotNull(topic);
- TopicPublisher producer = session.createPublisher(topic);
- MessageConsumer consumer = session.createConsumer(topic);
- conn.start();
- TextMessage sentMessage = session.createTextMessage("Test Message");
- producer.send(sentMessage);
- session.commit();
- TextMessage receivedMessage = (TextMessage) consumer.receive(2000);
- assertNotNull(receivedMessage);
- assertEquals(sentMessage.getText(), receivedMessage.getText());
- producer.send(sentMessage);
- session.commit();
- receivedMessage = (TextMessage) consumer.receive(2000);
- assertNotNull(receivedMessage);
- assertEquals(sentMessage.getText(), receivedMessage.getText());
- session.commit();
- conn.close();
-
- }
-
- public void testTemporaryTopic() throws Exception
- {
- AMQConnection conn = (AMQConnection) getConnection("guest", "guest");
- TopicSession session = conn.createTopicSession(true, Session.AUTO_ACKNOWLEDGE);
- TemporaryTopic topic = session.createTemporaryTopic();
- assertNotNull(topic);
- TopicPublisher producer = session.createPublisher(topic);
- MessageConsumer consumer = session.createConsumer(topic);
- conn.start();
- producer.send(session.createTextMessage("hello"));
- session.commit();
- TextMessage tm = (TextMessage) consumer.receive(2000);
- assertNotNull(tm);
- assertEquals("hello", tm.getText());
- session.commit();
- try
- {
- topic.delete();
- fail("Expected JMSException : should not be able to delete while there are active consumers");
- }
- catch (JMSException je)
- {
- ; //pass
- }
-
- consumer.close();
-
- try
- {
- topic.delete();
- }
- catch (JMSException je)
- {
- fail("Unexpected Exception: " + je.getMessage());
- }
-
- TopicSession session2 = conn.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
- try
- {
- session2.createConsumer(topic);
- fail("Expected a JMSException when subscribing to a temporary topic created on adifferent session");
- }
- catch (JMSException je)
- {
- ; // pass
- }
-
-
- conn.close();
- }
-
-
- public void testNoLocal() throws Exception
- {
-
- AMQConnection con = (AMQConnection) getConnection("guest", "guest");
-
- AMQTopic topic = new AMQTopic(con, "testNoLocal");
-
- TopicSession session1 = con.createTopicSession(true, AMQSession.AUTO_ACKNOWLEDGE);
- TopicSubscriber noLocal = session1.createSubscriber(topic, "", true);
-
- TopicSubscriber select = session1.createSubscriber(topic, "Selector = 'select'", false);
- TopicSubscriber normal = session1.createSubscriber(topic);
-
-
- TopicPublisher publisher = session1.createPublisher(topic);
-
- con.start();
- TextMessage m;
- TextMessage message;
-
- //send message to all consumers
- publisher.publish(session1.createTextMessage("hello-new2"));
- session1.commit();
- //test normal subscriber gets message
- m = (TextMessage) normal.receive(1000);
- assertNotNull(m);
- session1.commit();
-
- //test selector subscriber doesn't message
- m = (TextMessage) select.receive(1000);
- assertNull(m);
- session1.commit();
-
- //test nolocal subscriber doesn't message
- m = (TextMessage) noLocal.receive(1000);
- if (m != null)
- {
- System.out.println("Message:" + m.getText());
- }
- assertNull(m);
-
- //send message to all consumers
- message = session1.createTextMessage("hello2");
- message.setStringProperty("Selector", "select");
-
- publisher.publish(message);
- session1.commit();
-
- //test normal subscriber gets message
- m = (TextMessage) normal.receive(1000);
- assertNotNull(m);
- session1.commit();
-
- //test selector subscriber does get message
- m = (TextMessage) select.receive(1000);
- assertNotNull(m);
- session1.commit();
-
- //test nolocal subscriber doesn't message
- m = (TextMessage) noLocal.receive(100);
- assertNull(m);
-
- AMQConnection con2 = (AMQConnection) getClientConnection("guest", "guest", "foo");
- TopicSession session2 = con2.createTopicSession(true, AMQSession.AUTO_ACKNOWLEDGE);
- TopicPublisher publisher2 = session2.createPublisher(topic);
-
-
- message = session2.createTextMessage("hello2");
- message.setStringProperty("Selector", "select");
-
- publisher2.publish(message);
- session2.commit();
-
- //test normal subscriber gets message
- m = (TextMessage) normal.receive(1000);
- assertNotNull(m);
- session1.commit();
-
- //test selector subscriber does get message
- m = (TextMessage) select.receive(1000);
- assertNotNull(m);
- session1.commit();
-
- //test nolocal subscriber does message
- m = (TextMessage) noLocal.receive(1000);
- assertNotNull(m);
-
-
- con.close();
- con2.close();
- }
-
- /**
- * This tests QPID-1191, where messages which are sent to a topic but are not consumed by a subscriber
- * due to a selector can be leaked.
- * @throws Exception
- */
- public void testNonMatchingMessagesDoNotFillQueue() throws Exception
- {
- AMQConnection con = (AMQConnection) getConnection("guest", "guest");
-
- // Setup Topic
- AMQTopic topic = new AMQTopic(con, "testNoLocal");
-
- TopicSession session = con.createTopicSession(true, AMQSession.NO_ACKNOWLEDGE);
-
- // Setup subscriber with selector
- TopicSubscriber selector = session.createSubscriber(topic, "Selector = 'select'", false);
- TopicPublisher publisher = session.createPublisher(topic);
-
- con.start();
- TextMessage m;
- TextMessage message;
-
- // Send non-matching message
- message = session.createTextMessage("non-matching 1");
- publisher.publish(message);
- session.commit();
-
- // Send and consume matching message
- message = session.createTextMessage("hello");
- message.setStringProperty("Selector", "select");
-
- publisher.publish(message);
- session.commit();
-
- m = (TextMessage) selector.receive(1000);
- assertNotNull("should have received message", m);
- assertEquals("Message contents were wrong", "hello", m.getText());
-
- // Send non-matching message
- message = session.createTextMessage("non-matching 2");
- publisher.publish(message);
- session.commit();
-
- // Assert queue count is 0
- long depth = ((AMQTopicSessionAdaptor) session).getSession().getQueueDepth(topic);
- assertEquals("Queue depth was wrong", 0, depth);
-
- }
-
- public static junit.framework.Test suite()
- {
- return new junit.framework.TestSuite(TopicSessionTest.class);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/transacted/CommitRollbackTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/transacted/CommitRollbackTest.java
deleted file mode 100644
index bc2cbe714f..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/transacted/CommitRollbackTest.java
+++ /dev/null
@@ -1,572 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- *
- */
-package org.apache.qpid.test.unit.transacted;
-
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.apache.qpid.client.AMQConnection;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.jms.*;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-/**
- * This class tests a number of commits and roll back scenarios
- *
- * Assumptions; - Assumes empty Queue
- */
-public class CommitRollbackTest extends QpidBrokerTestCase
-{
- protected AMQConnection conn;
- protected String queue = "direct://amq.direct//Qpid.Client.Transacted.CommitRollback.queue";
- protected static int testMethod = 0;
- protected String payload = "xyzzy";
- private Session _session;
- private MessageProducer _publisher;
- private Session _pubSession;
- private MessageConsumer _consumer;
- Queue _jmsQueue;
-
- private static final Logger _logger = LoggerFactory.getLogger(CommitRollbackTest.class);
- private boolean _gotone = false;
- private boolean _gottwo = false;
- private boolean _gottwoRedelivered = false;
-
- protected void setUp() throws Exception
- {
- super.setUp();
- testMethod++;
- queue += testMethod;
- newConnection();
- }
-
- private void newConnection() throws Exception
- {
- conn = (AMQConnection) getConnection("guest", "guest");
-
- _session = conn.createSession(true, Session.CLIENT_ACKNOWLEDGE);
-
- _jmsQueue = _session.createQueue(queue);
- _consumer = _session.createConsumer(_jmsQueue);
-
- _pubSession = conn.createSession(true, Session.CLIENT_ACKNOWLEDGE);
-
- _publisher = _pubSession.createProducer(_pubSession.createQueue(queue));
-
- conn.start();
- }
-
- protected void tearDown() throws Exception
- {
- conn.close();
- super.tearDown();
- }
-
- /**
- * PUT a text message, disconnect before commit, confirm it is gone.
- *
- * @throws Exception On error
- */
- public void testPutThenDisconnect() throws Exception
- {
- assertTrue("session is not transacted", _session.getTransacted());
- assertTrue("session is not transacted", _pubSession.getTransacted());
-
- _logger.info("sending test message");
- String MESSAGE_TEXT = "testPutThenDisconnect";
- _publisher.send(_pubSession.createTextMessage(MESSAGE_TEXT));
-
- _logger.info("reconnecting without commit");
- conn.close();
-
- newConnection();
-
- _logger.info("receiving result");
- Message result = _consumer.receive(1000);
-
- // commit to ensure message is removed from queue
- _session.commit();
-
- assertNull("test message was put and disconnected before commit, but is still present", result);
- }
-
- /**
- * PUT a text message, disconnect before commit, confirm it is gone.
- *
- * @throws Exception On error
- */
- public void testPutThenCloseDisconnect() throws Exception
- {
- assertTrue("session is not transacted", _session.getTransacted());
- assertTrue("session is not transacted", _pubSession.getTransacted());
-
- _logger.info("sending test message");
- String MESSAGE_TEXT = "testPutThenDisconnect";
- _publisher.send(_pubSession.createTextMessage(MESSAGE_TEXT));
-
- _logger.info("closing publisher without commit");
- _publisher.close();
-
- _logger.info("reconnecting without commit");
- conn.close();
-
- newConnection();
-
- _logger.info("receiving result");
- Message result = _consumer.receive(1000);
-
- // commit to ensure message is removed from queue
- _session.commit();
-
- assertNull("test message was put and disconnected before commit, but is still present", result);
- }
-
- /**
- * PUT a text message, rollback, confirm message is gone. The consumer is on the same connection but different
- * session as producer
- *
- * @throws Exception On error
- */
- public void testPutThenRollback() throws Exception
- {
- assertTrue("session is not transacted", _session.getTransacted());
- assertTrue("session is not transacted", _pubSession.getTransacted());
-
- _logger.info("sending test message");
- String MESSAGE_TEXT = "testPutThenRollback";
- _publisher.send(_pubSession.createTextMessage(MESSAGE_TEXT));
-
- _logger.info("rolling back");
- _pubSession.rollback();
-
- _logger.info("receiving result");
- Message result = _consumer.receive(1000);
-
- assertNull("test message was put and rolled back, but is still present", result);
- }
-
- /**
- * GET a text message, disconnect before commit, confirm it is still there. The consumer is on a new connection
- *
- * @throws Exception On error
- */
- public void testGetThenDisconnect() throws Exception
- {
- assertTrue("session is not transacted", _session.getTransacted());
- assertTrue("session is not transacted", _pubSession.getTransacted());
-
- _logger.info("sending test message");
- String MESSAGE_TEXT = "testGetThenDisconnect";
- _publisher.send(_pubSession.createTextMessage(MESSAGE_TEXT));
-
- _pubSession.commit();
-
- _logger.info("getting test message");
-
- Message msg = _consumer.receive(1000);
- assertNotNull("retrieved message is null", msg);
-
- _logger.info("closing connection");
- conn.close();
-
- newConnection();
-
- _logger.info("receiving result");
- Message result = _consumer.receive(1000);
-
- _session.commit();
-
- assertNotNull("test message was consumed and disconnected before commit, but is gone", result);
- assertEquals("test message was correct message", MESSAGE_TEXT, ((TextMessage) result).getText());
- }
-
- /**
- * GET a text message, close consumer, disconnect before commit, confirm it is still there. The consumer is on the
- * same connection but different session as producer
- *
- * @throws Exception On error
- */
- public void testGetThenCloseDisconnect() throws Exception
- {
- assertTrue("session is not transacted", _session.getTransacted());
- assertTrue("session is not transacted", _pubSession.getTransacted());
-
- _logger.info("sending test message");
- String MESSAGE_TEXT = "testGetThenCloseDisconnect";
- _publisher.send(_pubSession.createTextMessage(MESSAGE_TEXT));
-
- _pubSession.commit();
-
- _logger.info("getting test message");
-
- Message msg = _consumer.receive(1000);
- assertNotNull("retrieved message is null", msg);
- assertEquals("test message was correct message", MESSAGE_TEXT, ((TextMessage) msg).getText());
-
- _logger.info("reconnecting without commit");
- _consumer.close();
- conn.close();
-
- newConnection();
-
- _logger.info("receiving result");
- Message result = _consumer.receive(1000);
-
- _session.commit();
-
- assertNotNull("test message was consumed and disconnected before commit, but is gone", result);
- assertEquals("test message was correct message", MESSAGE_TEXT, ((TextMessage) result).getText());
- }
-
- /**
- * GET a text message, rollback, confirm it is still there. The consumer is on the same connection but differnt
- * session to the producer
- *
- * @throws Exception On error
- */
- public void testGetThenRollback() throws Exception
- {
- assertTrue("session is not transacted", _session.getTransacted());
- assertTrue("session is not transacted", _pubSession.getTransacted());
-
- _logger.info("sending test message");
- String MESSAGE_TEXT = "testGetThenRollback";
- _publisher.send(_pubSession.createTextMessage(MESSAGE_TEXT));
-
- _pubSession.commit();
-
- _logger.info("getting test message");
-
- Message msg = _consumer.receive(1000);
-
- assertNotNull("retrieved message is null", msg);
- assertEquals("test message was correct message", MESSAGE_TEXT, ((TextMessage) msg).getText());
-
- _logger.info("rolling back");
-
- _session.rollback();
-
- _logger.info("receiving result");
-
- Message result = _consumer.receive(1000);
-
- _session.commit();
- assertNotNull("test message was consumed and rolled back, but is gone", result);
- assertEquals("test message was correct message", MESSAGE_TEXT, ((TextMessage) result).getText());
- assertTrue("Message is not marked as redelivered", result.getJMSRedelivered());
- }
-
- /**
- * GET a text message, close message producer, rollback, confirm it is still there. The consumer is on the same
- * connection but different session as producer
- *
- * @throws Exception On error
- */
- public void testGetThenCloseRollback() throws Exception
- {
- assertTrue("session is not transacted", _session.getTransacted());
- assertTrue("session is not transacted", _pubSession.getTransacted());
-
- _logger.info("sending test message");
- String MESSAGE_TEXT = "testGetThenCloseRollback";
- _publisher.send(_pubSession.createTextMessage(MESSAGE_TEXT));
-
- _pubSession.commit();
-
- _logger.info("getting test message");
-
- Message msg = _consumer.receive(1000);
-
- assertNotNull("retrieved message is null", msg);
- assertEquals("test message was correct message", MESSAGE_TEXT, ((TextMessage) msg).getText());
-
- _logger.info("Closing consumer");
- _consumer.close();
-
- _logger.info("rolling back");
- _session.rollback();
-
- _logger.info("receiving result");
-
- _consumer = _session.createConsumer(_jmsQueue);
-
- Message result = _consumer.receive(1000);
-
- _session.commit();
- assertNotNull("test message was consumed and rolled back, but is gone", result);
- assertEquals("test message was correct message", MESSAGE_TEXT, ((TextMessage) result).getText());
- assertTrue("Message is not marked as redelivered", result.getJMSRedelivered());
- }
-
- /**
- * Test that rolling back a session purges the dispatcher queue, and the messages arrive in the correct order
- *
- * @throws Exception On error
- */
- public void testSend2ThenRollback() throws Exception
- {
- int run = 0;
- while (run < 10)
- {
- run++;
- _logger.info("Run:" + run);
- assertTrue("session is not transacted", _session.getTransacted());
- assertTrue("session is not transacted", _pubSession.getTransacted());
-
- _logger.info("sending two test messages");
- _publisher.send(_pubSession.createTextMessage("1"));
- _publisher.send(_pubSession.createTextMessage("2"));
- _pubSession.commit();
-
- _logger.info("getting test message");
- assertEquals("1", ((TextMessage) _consumer.receive(1000)).getText());
-
- _logger.info("rolling back");
- _session.rollback();
-
- _logger.info("receiving result");
- Message result = _consumer.receive(1000);
-
- assertNotNull("test message was consumed and rolled back, but is gone", result);
-
- // Message Order is:
-
- // Send 1 , 2
- // Retrieve 1 and then rollback
- // Receieve 1 (redelivered) , 2 (may or may not be redelivered??)
-
- verifyMessages(result);
-
- // Occassionally get message 2 first!
-// assertEquals("Should get message one first", "1", ((TextMessage) result).getText());
-// assertTrue("Message is not marked as redelivered", result.getJMSRedelivered());
-//
-// result = _consumer.receive(1000);
-// assertEquals("Second message should be message 2", "2", ((TextMessage) result).getText());
-// assertTrue("Message is not marked as redelivered", result.getJMSRedelivered());
-//
-// result = _consumer.receive(1000);
-// assertNull("There should be no more messages", result);
-
- _session.commit();
- }
- }
-
- private void verifyMessages(Message result) throws JMSException
- {
-
- if (result == null)
- {
- assertTrue("Didn't receive redelivered message one", _gotone);
- assertTrue("Didn't receive message two at all", _gottwo | _gottwoRedelivered);
- _gotone = false;
- _gottwo = false;
- _gottwoRedelivered = false;
- return;
- }
-
- if (((TextMessage) result).getText().equals("1"))
- {
- _logger.info("Got 1 redelivered");
- assertTrue("Message is not marked as redelivered", result.getJMSRedelivered());
- assertFalse("Already received message one", _gotone);
- _gotone = true;
-
- }
- else
- {
- assertEquals("2", ((TextMessage) result).getText());
-
- if (result.getJMSRedelivered())
- {
- _logger.info("Got 2 redelivered, message was prefetched");
- assertFalse("Already received message redelivered two", _gottwoRedelivered);
-
- _gottwoRedelivered = true;
- }
- else
- {
- _logger.warn("Got 2, message prefetched wasn't cleared or messages was in transit when rollback occured");
- assertFalse("Already received message two", _gottwo);
- assertFalse("Already received message redelivered two", _gottwoRedelivered);
- _gottwo = true;
- }
- }
-
- verifyMessages(_consumer.receive(1000));
- }
-
- /**
- * This test sends two messages receives on of them but doesn't ack it.
- * The consumer is then closed
- * the first message should be returned as redelivered.
- * the second message should be delivered normally.
- * @throws Exception
- */
- public void testSend2ThenCloseAfter1andTryAgain() throws Exception
- {
- assertTrue("session is not transacted", _session.getTransacted());
- assertTrue("session is not transacted", _pubSession.getTransacted());
-
- _logger.info("sending two test messages");
- _publisher.send(_pubSession.createTextMessage("1"));
- _publisher.send(_pubSession.createTextMessage("2"));
- _pubSession.commit();
-
- _logger.info("getting test message");
- Message result = _consumer.receive(5000);
-
- assertNotNull("Message received should not be null", result);
- assertEquals("1", ((TextMessage) result).getText());
- assertTrue("Messasge is marked as redelivered" + result, !result.getJMSRedelivered());
-
- _logger.info("Closing Consumer");
-
- _consumer.close();
-
- _logger.info("Creating New consumer");
- _consumer = _session.createConsumer(_jmsQueue);
-
- _logger.info("receiving result");
-
-
- // Message 2 may be marked as redelivered if it was prefetched.
- result = _consumer.receive(5000);
- assertNotNull("Second message was not consumed, but is gone", result);
-
- // The first message back will be 2, message 1 has been received but not committed
- // Closing the consumer does not commit the session.
-
- // if this is message 1 then it should be marked as redelivered
- if("1".equals(((TextMessage) result).getText()))
- {
- fail("First message was recieved again");
- }
-
- result = _consumer.receive(1000);
- assertNull("test message should be null:" + result, result);
-
- _session.commit();
- }
-
- public void testPutThenRollbackThenGet() throws Exception
- {
- assertTrue("session is not transacted", _session.getTransacted());
- assertTrue("session is not transacted", _pubSession.getTransacted());
-
- _logger.info("sending test message");
- String MESSAGE_TEXT = "testPutThenRollbackThenGet";
-
- _publisher.send(_pubSession.createTextMessage(MESSAGE_TEXT));
- _pubSession.commit();
-
- assertNotNull(_consumer.receive(1000));
-
- _publisher.send(_pubSession.createTextMessage(MESSAGE_TEXT));
-
- _logger.info("rolling back");
- _pubSession.rollback();
-
- _logger.info("receiving result");
- Message result = _consumer.receive(1000);
- assertNull("test message was put and rolled back, but is still present", result);
-
- _publisher.send(_pubSession.createTextMessage(MESSAGE_TEXT));
-
- _pubSession.commit();
-
- assertNotNull(_consumer.receive(100));
-
- _session.commit();
- }
-
- /**
- * Qpid-1163
- * Check that when commt is called inside onMessage then
- * the last message is nor redelivered.
- *
- * @throws Exception
- */
- public void testCommitWhithinOnMessage() throws Exception
- {
- Queue queue = (Queue) getInitialContext().lookup("queue");
- // create a consumer
- MessageConsumer cons = _session.createConsumer(queue);
- MessageProducer prod = _session.createProducer(queue);
- Message message = _session.createTextMessage("Message");
- message.setJMSCorrelationID("m1");
- prod.send(message);
- _session.commit();
- _logger.info("Sent message to queue");
- CountDownLatch cd = new CountDownLatch(1);
- cons.setMessageListener(new CommitWhithinOnMessageListener(cd));
- conn.start();
- cd.await(30, TimeUnit.SECONDS);
- if( cd.getCount() > 0 )
- {
- fail("Did not received message");
- }
- // Check that the message has been dequeued
- _session.close();
- conn.close();
- conn = (AMQConnection) getConnection("guest", "guest");
- conn.start();
- Session session = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE);
- cons = session.createConsumer(queue);
- message = cons.receiveNoWait();
- if(message != null)
- {
- if(message.getJMSCorrelationID().equals("m1"))
- {
- fail("received message twice");
- }
- else
- {
- fail("queue should have been empty, received message: " + message);
- }
- }
- }
-
- private class CommitWhithinOnMessageListener implements MessageListener
- {
- private CountDownLatch _cd;
- private CommitWhithinOnMessageListener(CountDownLatch cd)
- {
- _cd = cd;
- }
- public void onMessage(Message message)
- {
- try
- {
- _logger.info("received message " + message);
- assertEquals("Wrong message received", message.getJMSCorrelationID(), "m1");
- _logger.info("commit session");
- _session.commit();
- _cd.countDown();
- }
- catch (JMSException e)
- {
- e.printStackTrace();
- }
- }
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/transacted/TransactedTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/transacted/TransactedTest.java
deleted file mode 100644
index 045deab052..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/transacted/TransactedTest.java
+++ /dev/null
@@ -1,348 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.transacted;
-
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.jms.Session;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-import javax.jms.TextMessage;
-
-public class TransactedTest extends QpidBrokerTestCase
-{
- private AMQQueue queue1;
-
- private AMQConnection con;
- private Session session;
- private MessageConsumer consumer1;
- private MessageProducer producer2;
-
- private AMQConnection prepCon;
- private Session prepSession;
- private MessageProducer prepProducer1;
-
- private AMQConnection testCon;
- private Session testSession;
- private MessageConsumer testConsumer1;
- private MessageConsumer testConsumer2;
- private static final Logger _logger = LoggerFactory.getLogger(TransactedTest.class);
-
- protected void setUp() throws Exception
- {
- try
- {
- super.setUp();
- _logger.info("Create Connection");
- con = (AMQConnection) getConnection("guest", "guest");
- _logger.info("Create Session");
- session = con.createSession(true, Session.SESSION_TRANSACTED);
- _logger.info("Create Q1");
- queue1 = new AMQQueue(session.getDefaultQueueExchangeName(), new AMQShortString("Q1"),
- new AMQShortString("Q1"), false, true);
- _logger.info("Create Q2");
- AMQQueue queue2 = new AMQQueue(session.getDefaultQueueExchangeName(), new AMQShortString("Q2"), false);
-
- _logger.info("Create Consumer of Q1");
- consumer1 = session.createConsumer(queue1);
- // Dummy just to create the queue.
- _logger.info("Create Consumer of Q2");
- MessageConsumer consumer2 = session.createConsumer(queue2);
- _logger.info("Close Consumer of Q2");
- consumer2.close();
-
- _logger.info("Create producer to Q2");
- producer2 = session.createProducer(queue2);
-
- _logger.info("Start Connection");
- con.start();
-
- _logger.info("Create prep connection");
- prepCon = (AMQConnection) getConnection("guest", "guest");
-
- _logger.info("Create prep session");
- prepSession = prepCon.createSession(false, AMQSession.AUTO_ACKNOWLEDGE);
-
- _logger.info("Create prep producer to Q1");
- prepProducer1 = prepSession.createProducer(queue1);
-
- _logger.info("Create prep connection start");
- prepCon.start();
-
- _logger.info("Create test connection");
- testCon = (AMQConnection) getConnection("guest", "guest");
- _logger.info("Create test session");
- testSession = testCon.createSession(false, AMQSession.AUTO_ACKNOWLEDGE);
- _logger.info("Create test consumer of q2");
- testConsumer2 = testSession.createConsumer(queue2);
- }
- catch (Exception e)
- {
- e.printStackTrace();
- stopBroker();
- throw e;
- }
- }
-
- protected void tearDown() throws Exception
- {
- try
- {
- _logger.info("Close connection");
- con.close();
- _logger.info("Close test connection");
- testCon.close();
- _logger.info("Close prep connection");
- prepCon.close();
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
- finally
- {
- super.tearDown();
- }
- }
-
- public void testCommit() throws Exception
- {
- try
- {
-// add some messages
- _logger.info("Send prep A");
- prepProducer1.send(prepSession.createTextMessage("A"));
- _logger.info("Send prep B");
- prepProducer1.send(prepSession.createTextMessage("B"));
- _logger.info("Send prep C");
- prepProducer1.send(prepSession.createTextMessage("C"));
-
- // send and receive some messages
- _logger.info("Send X to Q2");
- producer2.send(session.createTextMessage("X"));
- _logger.info("Send Y to Q2");
- producer2.send(session.createTextMessage("Y"));
- _logger.info("Send Z to Q2");
- producer2.send(session.createTextMessage("Z"));
-
- _logger.info("Read A from Q1");
- expect("A", consumer1.receive(1000));
- _logger.info("Read B from Q1");
- expect("B", consumer1.receive(1000));
- _logger.info("Read C from Q1");
- expect("C", consumer1.receive(1000));
-
- // commit
- _logger.info("session commit");
- session.commit();
- _logger.info("Start test Connection");
- testCon.start();
-
- // ensure sent messages can be received and received messages are gone
- _logger.info("Read X from Q2");
- expect("X", testConsumer2.receive(1000));
- _logger.info("Read Y from Q2");
- expect("Y", testConsumer2.receive(1000));
- _logger.info("Read Z from Q2");
- expect("Z", testConsumer2.receive(1000));
-
- _logger.info("create test session on Q1");
- testConsumer1 = testSession.createConsumer(queue1);
- _logger.info("Read null from Q1");
- assertTrue(null == testConsumer1.receive(1000));
- _logger.info("Read null from Q2");
- assertTrue(null == testConsumer2.receive(1000));
- }
- catch (Throwable e)
- {
- e.printStackTrace();
- fail(e.getMessage());
- }
- }
-
- public void testRollback() throws Exception
- {
- try
- {
-// add some messages
- _logger.info("Send prep RB_A");
- prepProducer1.send(prepSession.createTextMessage("RB_A"));
- _logger.info("Send prep RB_B");
- prepProducer1.send(prepSession.createTextMessage("RB_B"));
- _logger.info("Send prep RB_C");
- prepProducer1.send(prepSession.createTextMessage("RB_C"));
-
- _logger.info("Sending RB_X RB_Y RB_Z");
- producer2.send(session.createTextMessage("RB_X"));
- producer2.send(session.createTextMessage("RB_Y"));
- producer2.send(session.createTextMessage("RB_Z"));
- _logger.info("Receiving RB_A RB_B");
- expect("RB_A", consumer1.receive(1000));
- expect("RB_B", consumer1.receive(1000));
- // Don't consume 'RB_C' leave it in the prefetch cache to ensure rollback removes it.
- // Quick sleep to ensure 'RB_C' gets pre-fetched
- Thread.sleep(500);
-
- // rollback
- _logger.info("rollback");
- session.rollback();
-
- _logger.info("Receiving RB_A RB_B RB_C");
- // ensure sent messages are not visible and received messages are requeued
- expect("RB_A", consumer1.receive(1000), true);
- expect("RB_B", consumer1.receive(1000), true);
- expect("RB_C", consumer1.receive(1000), true);
- _logger.info("Starting new connection");
- testCon.start();
- testConsumer1 = testSession.createConsumer(queue1);
- _logger.info("Testing we have no messages left");
- assertTrue(null == testConsumer1.receive(1000));
- assertTrue(null == testConsumer2.receive(1000));
-
- session.commit();
-
- _logger.info("Testing we have no messages left after commit");
- assertTrue(null == testConsumer1.receive(1000));
- assertTrue(null == testConsumer2.receive(1000));
- }
- catch (Throwable e)
- {
- e.printStackTrace();
- fail(e.getMessage());
- }
- }
-
- public void testResendsMsgsAfterSessionClose() throws Exception
- {
- try
- {
- AMQConnection con = (AMQConnection) getConnection("guest", "guest");
-
- Session consumerSession = con.createSession(true, Session.SESSION_TRANSACTED);
- AMQQueue queue3 = new AMQQueue(consumerSession.getDefaultQueueExchangeName(), new AMQShortString("Q3"), false);
- MessageConsumer consumer = consumerSession.createConsumer(queue3);
-
- AMQConnection con2 = (AMQConnection) getConnection("guest", "guest");
- Session producerSession = con2.createSession(true, Session.SESSION_TRANSACTED);
- MessageProducer producer = producerSession.createProducer(queue3);
-
- _logger.info("Sending four messages");
- producer.send(producerSession.createTextMessage("msg1"));
- producer.send(producerSession.createTextMessage("msg2"));
- producer.send(producerSession.createTextMessage("msg3"));
- producer.send(producerSession.createTextMessage("msg4"));
-
- producerSession.commit();
-
- _logger.info("Starting connection");
- con.start();
- TextMessage tm = (TextMessage) consumer.receive();
- assertNotNull(tm);
- assertEquals("msg1", tm.getText());
-
- consumerSession.commit();
-
- _logger.info("Received and committed first message");
- tm = (TextMessage) consumer.receive(1000);
- assertNotNull(tm);
- assertEquals("msg2", tm.getText());
-
- tm = (TextMessage) consumer.receive(1000);
- assertNotNull(tm);
- assertEquals("msg3", tm.getText());
-
- tm = (TextMessage) consumer.receive(1000);
- assertNotNull(tm);
- assertEquals("msg4", tm.getText());
-
- _logger.info("Received all four messages. Closing connection with three outstanding messages");
-
- consumerSession.close();
-
- consumerSession = con.createSession(true, Session.SESSION_TRANSACTED);
-
- consumer = consumerSession.createConsumer(queue3);
-
- // no ack for last three messages so when I call recover I expect to get three messages back
- tm = (TextMessage) consumer.receive(3000);
- assertNotNull(tm);
- assertEquals("msg2", tm.getText());
- assertTrue("Message is not redelivered", tm.getJMSRedelivered());
-
- tm = (TextMessage) consumer.receive(3000);
- assertNotNull(tm);
- assertEquals("msg3", tm.getText());
- assertTrue("Message is not redelivered", tm.getJMSRedelivered());
-
- tm = (TextMessage) consumer.receive(3000);
- assertNotNull(tm);
- assertEquals("msg4", tm.getText());
- assertTrue("Message is not redelivered", tm.getJMSRedelivered());
-
- _logger.info("Received redelivery of three messages. Committing");
-
- consumerSession.commit();
-
- _logger.info("Called commit");
-
- tm = (TextMessage) consumer.receive(1000);
- assertNull(tm);
-
- _logger.info("No messages redelivered as is expected");
-
- con.close();
- con2.close();
- }
- catch (Throwable e)
- {
- e.printStackTrace();
- fail(e.getMessage());
- }
- }
-
- private void expect(String text, Message msg) throws JMSException
- {
- expect(text, msg, false);
- }
-
- private void expect(String text, Message msg, boolean requeued) throws JMSException
- {
- assertNotNull("Message should not be null", msg);
- assertTrue("Message should be a text message", msg instanceof TextMessage);
- assertEquals("Message content does not match expected", text, ((TextMessage) msg).getText());
- assertEquals("Message should " + (requeued ? "" : "not") + " be requeued", requeued, msg.getJMSRedelivered());
- }
-
- public static junit.framework.Test suite()
- {
- return new junit.framework.TestSuite(TransactedTest.class);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/transacted/TransactionTimeoutConfigurationTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/transacted/TransactionTimeoutConfigurationTest.java
deleted file mode 100644
index 36bac3b715..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/transacted/TransactionTimeoutConfigurationTest.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.transacted;
-
-/**
- * This verifies that changing the {@code transactionTimeout} configuration will alter
- * the behaviour of the transaction open and idle logging, and that when the connection
- * will be closed.
- */
-public class TransactionTimeoutConfigurationTest extends TransactionTimeoutTestCase
-{
- @Override
- protected void configure() throws Exception
- {
- // Setup housekeeping every second
- setConfigurationProperty("virtualhosts.virtualhost." + VIRTUALHOST + ".housekeeping.expiredMessageCheckPeriod", "100");
-
- // Set transaction timout properties.
- setConfigurationProperty("virtualhosts.virtualhost." + VIRTUALHOST + ".transactionTimeout.openWarn", "200");
- setConfigurationProperty("virtualhosts.virtualhost." + VIRTUALHOST + ".transactionTimeout.openClose", "1000");
- setConfigurationProperty("virtualhosts.virtualhost." + VIRTUALHOST + ".transactionTimeout.idleWarn", "100");
- setConfigurationProperty("virtualhosts.virtualhost." + VIRTUALHOST + ".transactionTimeout.idleClose", "500");
- }
-
- public void testProducerIdleCommit() throws Exception
- {
- try
- {
- send(5, 0);
-
- sleep(2.0f);
-
- _psession.commit();
- fail("should fail");
- }
- catch (Exception e)
- {
- _exception = e;
- }
-
- monitor(5, 0);
-
- check(IDLE);
- }
-
- public void testProducerOpenCommit() throws Exception
- {
- try
- {
- send(5, 0.3f);
-
- _psession.commit();
- fail("should fail");
- }
- catch (Exception e)
- {
- _exception = e;
- }
-
- monitor(6, 3);
-
- check(OPEN);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/transacted/TransactionTimeoutDisabledTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/transacted/TransactionTimeoutDisabledTest.java
deleted file mode 100644
index 71b89bf911..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/transacted/TransactionTimeoutDisabledTest.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.transacted;
-
-/**
- * This verifies that the default behaviour is not to time out transactions.
- */
-public class TransactionTimeoutDisabledTest extends TransactionTimeoutTestCase
-{
- @Override
- protected void configure() throws Exception
- {
- // Setup housekeeping every second
- setConfigurationProperty("virtualhosts.virtualhost." + VIRTUALHOST + ".housekeeping.expiredMessageCheckPeriod", "100");
- }
-
- public void testProducerIdleCommit() throws Exception
- {
- try
- {
- send(5, 0);
-
- sleep(2.0f);
-
- _psession.commit();
- }
- catch (Exception e)
- {
- fail("Should have succeeded");
- }
-
- assertTrue("Listener should not have received exception", _caught.getCount() == 1);
-
- monitor(0, 0);
- }
-
- public void testProducerOpenCommit() throws Exception
- {
- try
- {
- send(5, 0.3f);
-
- _psession.commit();
- }
- catch (Exception e)
- {
- fail("Should have succeeded");
- }
-
- assertTrue("Listener should not have received exception", _caught.getCount() == 1);
-
- monitor(0, 0);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/transacted/TransactionTimeoutTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/transacted/TransactionTimeoutTest.java
deleted file mode 100644
index c912d6a323..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/transacted/TransactionTimeoutTest.java
+++ /dev/null
@@ -1,335 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.transacted;
-
-/**
- * This tests the behaviour of transactional sessions when the {@code transactionTimeout} configuration
- * is set for a virtual host.
- *
- * A producer that is idle for too long or open for too long will have its connection closed and
- * any further operations will fail with a 408 resource timeout exception. Consumers will not
- * be affected by the transaction timeout configuration.
- */
-public class TransactionTimeoutTest extends TransactionTimeoutTestCase
-{
- public void testProducerIdle() throws Exception
- {
- try
- {
- sleep(2.0f);
-
- _psession.commit();
- }
- catch (Exception e)
- {
- fail("Should have succeeded");
- }
-
- assertTrue("Listener should not have received exception", _caught.getCount() == 1);
-
- monitor(0, 0);
- }
-
- public void testProducerIdleCommit() throws Exception
- {
- try
- {
- send(5, 0);
-
- sleep(2.0f);
-
- _psession.commit();
- fail("should fail");
- }
- catch (Exception e)
- {
- _exception = e;
- }
-
- monitor(5, 0);
-
- check(IDLE);
- }
-
- public void testProducerOpenCommit() throws Exception
- {
- try
- {
- send(6, 0.5f);
-
- _psession.commit();
- fail("should fail");
- }
- catch (Exception e)
- {
- _exception = e;
- }
-
- monitor(0, 10);
-
- check(OPEN);
- }
-
- public void testProducerIdleCommitTwice() throws Exception
- {
- try
- {
- send(5, 0);
-
- sleep(1.0f);
-
- _psession.commit();
-
- send(5, 0);
-
- sleep(2.0f);
-
- _psession.commit();
- fail("should fail");
- }
- catch (Exception e)
- {
- _exception = e;
- }
-
- monitor(10, 0);
-
- check(IDLE);
- }
-
- public void testProducerOpenCommitTwice() throws Exception
- {
- try
- {
- send(5, 0);
-
- sleep(1.0f);
-
- _psession.commit();
-
- send(6, 0.5f);
-
- _psession.commit();
- fail("should fail");
- }
- catch (Exception e)
- {
- _exception = e;
- }
-
- // the presistent store generates more idle messages?
- monitor(isBrokerStorePersistent() ? 10 : 5, 10);
-
- check(OPEN);
- }
-
- public void testProducerIdleRollback() throws Exception
- {
- try
- {
- send(5, 0);
-
- sleep(2.0f);
-
- _psession.rollback();
- fail("should fail");
- }
- catch (Exception e)
- {
- _exception = e;
- }
-
- monitor(5, 0);
-
- check(IDLE);
- }
-
- public void testProducerIdleRollbackTwice() throws Exception
- {
- try
- {
- send(5, 0);
-
- sleep(1.0f);
-
- _psession.rollback();
-
- send(5, 0);
-
- sleep(2.0f);
-
- _psession.rollback();
- fail("should fail");
- }
- catch (Exception e)
- {
- _exception = e;
- }
-
- monitor(10, 0);
-
- check(IDLE);
- }
-
- public void testConsumerCommitClose() throws Exception
- {
- try
- {
- send(1, 0);
-
- _psession.commit();
-
- expect(1, 0);
-
- _csession.commit();
-
- sleep(3.0f);
-
- _csession.close();
- }
- catch (Exception e)
- {
- fail("should have succeeded: " + e.getMessage());
- }
-
- assertTrue("Listener should not have received exception", _caught.getCount() == 1);
-
- monitor(0, 0);
- }
-
- public void testConsumerIdleReceiveCommit() throws Exception
- {
- try
- {
- send(1, 0);
-
- _psession.commit();
-
- sleep(2.0f);
-
- expect(1, 0);
-
- sleep(2.0f);
-
- _csession.commit();
- }
- catch (Exception e)
- {
- fail("Should have succeeded");
- }
-
- assertTrue("Listener should not have received exception", _caught.getCount() == 1);
-
- monitor(0, 0);
- }
-
- public void testConsumerIdleCommit() throws Exception
- {
- try
- {
- send(1, 0);
-
- _psession.commit();
-
- expect(1, 0);
-
- sleep(2.0f);
-
- _csession.commit();
- }
- catch (Exception e)
- {
- fail("Should have succeeded");
- }
-
- assertTrue("Listener should not have received exception", _caught.getCount() == 1);
-
- monitor(0, 0);
- }
-
- public void testConsumerIdleRollback() throws Exception
- {
- try
- {
- send(1, 0);
-
- _psession.commit();
-
- expect(1, 0);
-
- sleep(2.0f);
-
- _csession.rollback();
- }
- catch (Exception e)
- {
- fail("Should have succeeded");
- }
-
- assertTrue("Listener should not have received exception", _caught.getCount() == 1);
-
- monitor(0, 0);
- }
-
- public void testConsumerOpenCommit() throws Exception
- {
- try
- {
- send(1, 0);
-
- _psession.commit();
-
- sleep(3.0f);
-
- _csession.commit();
- }
- catch (Exception e)
- {
- fail("Should have succeeded");
- }
-
- assertTrue("Listener should not have received exception", _caught.getCount() == 1);
-
- monitor(0, 0);
- }
-
- public void testConsumerOpenRollback() throws Exception
- {
- try
- {
- send(1, 0);
-
- _psession.commit();
-
- sleep(3.0f);
-
- _csession.rollback();
- }
- catch (Exception e)
- {
- fail("Should have succeeded");
- }
-
- assertTrue("Listener should not have received exception", _caught.getCount() == 1);
-
- monitor(0, 0);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/transacted/TransactionTimeoutTestCase.java b/java/systests/src/main/java/org/apache/qpid/test/unit/transacted/TransactionTimeoutTestCase.java
deleted file mode 100644
index 637f43fb2c..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/transacted/TransactionTimeoutTestCase.java
+++ /dev/null
@@ -1,253 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.unit.transacted;
-
-import java.util.List;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-import javax.jms.DeliveryMode;
-import javax.jms.ExceptionListener;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-import javax.jms.Queue;
-import javax.jms.TextMessage;
-
-import junit.framework.TestCase;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQConnectionURL;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.jms.ConnectionURL;
-import org.apache.qpid.jms.Session;
-import org.apache.qpid.protocol.AMQConstant;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.apache.qpid.util.LogMonitor;
-
-/**
- * The {@link TestCase} for transaction timeout testing.
- */
-public class TransactionTimeoutTestCase extends QpidBrokerTestCase implements ExceptionListener
-{
- public static final String VIRTUALHOST = "test";
- public static final String TEXT = "0123456789abcdefghiforgettherest";
- public static final String CHN_OPEN_TXN = "CHN-1007";
- public static final String CHN_IDLE_TXN = "CHN-1008";
- public static final String IDLE = "Idle";
- public static final String OPEN = "Open";
-
- protected LogMonitor _monitor;
- protected AMQConnection _con;
- protected Session _psession, _csession;
- protected Queue _queue;
- protected MessageConsumer _consumer;
- protected MessageProducer _producer;
- protected CountDownLatch _caught = new CountDownLatch(1);
- protected String _message;
- protected Exception _exception;
- protected AMQConstant _code;
-
- protected void configure() throws Exception
- {
- // Setup housekeeping every second
- setConfigurationProperty("virtualhosts.virtualhost." + VIRTUALHOST + ".housekeeping.expiredMessageCheckPeriod", "100");
-
- /*
- * Set transaction timout properties. The XML in the virtualhosts configuration is as follows:
- *
- * <transactionTimeout>
- * <openWarn>1000</openWarn>
- * <openClose>2000</openClose>
- * <idleWarn>500</idleWarn>
- * <idleClose>1500</idleClose>
- * </transactionTimeout>
- */
- setConfigurationProperty("virtualhosts.virtualhost." + VIRTUALHOST + ".transactionTimeout.openWarn", "1000");
- setConfigurationProperty("virtualhosts.virtualhost." + VIRTUALHOST + ".transactionTimeout.openClose", "2000");
- setConfigurationProperty("virtualhosts.virtualhost." + VIRTUALHOST + ".transactionTimeout.idleWarn", "500");
- setConfigurationProperty("virtualhosts.virtualhost." + VIRTUALHOST + ".transactionTimeout.idleClose", "1000");
- }
-
- protected void setUp() throws Exception
- {
- // Configure timeouts
- configure();
-
- // Monitor log file
- _monitor = new LogMonitor(_outputFile);
-
- // Start broker
- super.setUp();
-
- // Connect to broker
- String broker = _broker.equals(VM) ? ("vm://:" + DEFAULT_VM_PORT) : ("tcp://localhost:" + DEFAULT_PORT);
- ConnectionURL url = new AMQConnectionURL("amqp://guest:guest@clientid/test?brokerlist='" + broker + "'&maxprefetch='1'");
- _con = (AMQConnection) getConnection(url);
- _con.setExceptionListener(this);
- _con.start();
-
- // Create queue
- Session qsession = _con.createSession(true, Session.SESSION_TRANSACTED);
- AMQShortString queueName = new AMQShortString("test");
- _queue = new AMQQueue(qsession.getDefaultQueueExchangeName(), queueName, queueName, false, true);
- qsession.close();
-
- // Create producer and consumer
- producer();
- consumer();
- }
-
- protected void tearDown() throws Exception
- {
- try
- {
- _con.close();
- }
- finally
- {
- super.tearDown();
- }
- }
-
- /**
- * Create a transacted persistent message producer session.
- */
- protected void producer() throws Exception
- {
- _psession = _con.createSession(true, Session.SESSION_TRANSACTED);
- _producer = _psession.createProducer(_queue);
- _producer.setDeliveryMode(DeliveryMode.PERSISTENT);
- }
-
- /**
- * Create a transacted message consumer session.
- */
- protected void consumer() throws Exception
- {
- _csession = _con.createSession(true, Session.SESSION_TRANSACTED);
- _consumer = _csession.createConsumer(_queue);
- }
-
- /**
- * Send a number of messages to the queue, optionally pausing after each.
- */
- protected void send(int count, float delay) throws Exception
- {
- for (int i = 0; i < count; i++)
- {
- sleep(delay);
- Message msg = _psession.createTextMessage(TEXT);
- msg.setIntProperty("i", i);
- _producer.send(msg);
- }
- }
-
- /**
- * Sleep for a number of seconds.
- */
- protected void sleep(float seconds) throws Exception
- {
- try
- {
- Thread.sleep((long) (seconds * 1000.0f));
- }
- catch (InterruptedException ie)
- {
- throw new RuntimeException("Interrupted");
- }
- }
-
- /**
- * Check for idle and open messages.
- *
- * Either exactly zero messages, or +-2 error accepted around the specified number.
- */
- protected void monitor(int idle, int open) throws Exception
- {
- List<String> idleMsgs = _monitor.findMatches(CHN_IDLE_TXN);
- List<String> openMsgs = _monitor.findMatches(CHN_OPEN_TXN);
-
- String idleErr = "Expected " + idle + " but found " + idleMsgs.size() + " txn idle messages";
- String openErr = "Expected " + open + " but found " + openMsgs.size() + " txn open messages";
-
- if (idle == 0)
- {
- assertTrue(idleErr, idleMsgs.isEmpty());
- }
- else
- {
- assertTrue(idleErr, idleMsgs.size() >= idle - 2 && idleMsgs.size() <= idle + 2);
- }
-
- if (open == 0)
- {
- assertTrue(openErr, openMsgs.isEmpty());
- }
- else
- {
- assertTrue(openErr, openMsgs.size() >= open - 2 && openMsgs.size() <= open + 2);
- }
- }
-
- /**
- * Receive a number of messages, optionally pausing after each.
- */
- protected void expect(int count, float delay) throws Exception
- {
- for (int i = 0; i < count; i++)
- {
- sleep(delay);
- Message msg = _consumer.receive(1000);
- assertNotNull("Message should not be null", msg);
- assertTrue("Message should be a text message", msg instanceof TextMessage);
- assertEquals("Message content does not match expected", TEXT, ((TextMessage) msg).getText());
- assertEquals("Message order is incorrect", i, msg.getIntProperty("i"));
- }
- }
-
- /**
- * Checks that the correct exception was thrown and was received
- * by the listener with a 506 error code.
- */
- protected void check(String reason)throws InterruptedException
- {
- assertTrue("Should have caught exception in listener", _caught.await(1, TimeUnit.SECONDS));
- assertNotNull("Should have thrown exception to client", _exception);
- assertTrue("Exception message should contain '" + reason + "': " + _message, _message.contains(reason + " transaction timed out"));
- assertNotNull("Exception should have an error code", _code);
- assertEquals("Error code should be 506", AMQConstant.RESOURCE_ERROR, _code);
- }
-
- /** @see javax.jms.ExceptionListener#onException(javax.jms.JMSException) */
- public void onException(JMSException jmse)
- {
- _caught.countDown();
- _message = jmse.getLinkedException().getMessage();
- if (jmse.getLinkedException() instanceof AMQException)
- {
- _code = ((AMQException) jmse.getLinkedException()).getErrorCode();
- }
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/xa/AbstractXATestCase.java b/java/systests/src/main/java/org/apache/qpid/test/unit/xa/AbstractXATestCase.java
deleted file mode 100644
index f39f640d04..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/xa/AbstractXATestCase.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.test.unit.xa;
-
-import org.apache.qpid.dtx.XidImpl;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-import javax.transaction.xa.Xid;
-import javax.transaction.xa.XAResource;
-import javax.jms.*;
-import java.util.Random;
-
-/**
- *
- *
- */
-public abstract class AbstractXATestCase extends QpidBrokerTestCase
-{
- protected static final String _sequenceNumberPropertyName = "seqNumber";
-
- /**
- * the xaResource associated with the standard session
- */
- protected static XAResource _xaResource = null;
-
- /**
- * producer registered with the standard session
- */
- protected static MessageProducer _producer = null;
-
- /**
- * consumer registered with the standard session
- */
- protected static MessageConsumer _consumer = null;
-
- /**
- * a standard message
- */
- protected static TextMessage _message = null;
-
- /**
- * xid counter
- */
- private static int _xidCounter = (new Random()).nextInt(1000000);
-
-
- protected void setUp() throws Exception
- {
- super.setUp();
- init();
- }
-
- public abstract void init() throws Exception;
-
-
-
- /**
- * construct a new Xid
- *
- * @return a new Xid
- */
- protected Xid getNewXid()
- {
- byte[] branchQualifier;
- byte[] globalTransactionID;
- int format = _xidCounter;
- String branchQualifierSt = "branchQualifier" + _xidCounter;
- String globalTransactionIDSt = "globalTransactionID" + _xidCounter;
- branchQualifier = branchQualifierSt.getBytes();
- globalTransactionID = globalTransactionIDSt.getBytes();
- _xidCounter++;
- return new XidImpl(branchQualifier, format, globalTransactionID);
- }
-
- public void init(XASession session, Destination destination)
- {
- // get the xaResource
- try
- {
- _xaResource = session.getXAResource();
- }
- catch (Exception e)
- {
- fail("cannot access the xa resource: " + e.getMessage());
- }
- // create standard producer
- try
- {
- _producer = session.createProducer(destination);
- _producer.setDeliveryMode(DeliveryMode.PERSISTENT);
- }
- catch (JMSException e)
- {
- e.printStackTrace();
- fail("cannot create message producer: " + e.getMessage());
- }
- // create standard consumer
- try
- {
- _consumer = session.createConsumer(destination);
- }
- catch (JMSException e)
- {
- fail("cannot create message consumer: " + e.getMessage());
- }
- // create a standard message
- try
- {
- _message = session.createTextMessage();
- _message.setText("test XA");
- }
- catch (JMSException e)
- {
- fail("cannot create standard message: " + e.getMessage());
- }
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/xa/FaultTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/xa/FaultTest.java
deleted file mode 100644
index 47705f8105..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/xa/FaultTest.java
+++ /dev/null
@@ -1,409 +0,0 @@
-package org.apache.qpid.test.unit.xa;
-/*
- *
- * 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.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.jms.*;
-import javax.transaction.xa.Xid;
-import javax.transaction.xa.XAResource;
-import javax.transaction.xa.XAException;
-
-import junit.framework.TestSuite;
-
-
-public class FaultTest extends AbstractXATestCase
-{
- /* this clas logger */
- private static final Logger _logger = LoggerFactory.getLogger(FaultTest.class);
-
- /**
- * the queue use by all the tests
- */
- private static Queue _queue = null;
- /**
- * the queue connection factory used by all tests
- */
- private static XAQueueConnectionFactory _queueFactory = null;
-
- /**
- * standard xa queue connection
- */
- private static XAQueueConnection _xaqueueConnection = null;
-
- /**
- * standard xa queue connection
- */
- private static QueueConnection _queueConnection = null;
-
-
- /**
- * standard queue session created from the standard connection
- */
- private static QueueSession _nonXASession = null;
-
- /**
- * the queue name
- */
- private static final String QUEUENAME = "xaQueue";
-
- /** ----------------------------------------------------------------------------------- **/
- /**
- * ----------------------------- JUnit support ----------------------------------------- *
- */
-
- /**
- * Gets the test suite tests
- *
- * @return the test suite tests
- */
- public static TestSuite getSuite()
- {
- return new TestSuite(QueueTest.class);
- }
-
- /**
- * Run the test suite.
- *
- * @param args Any command line arguments specified to this class.
- */
- public static void main(String args[])
- {
- junit.textui.TestRunner.run(getSuite());
- }
-
- public void tearDown() throws Exception
- {
- if (!isBroker08())
- {
- _xaqueueConnection.close();
- _queueConnection.close();
- }
- super.tearDown();
- }
-
- /**
- * Initialize standard actors
- */
- public void init() throws Exception
- {
- if (!isBroker08())
- {
- _queue = (Queue) getInitialContext().lookup(QUEUENAME);
- _queueFactory = getConnectionFactory();
- _xaqueueConnection = _queueFactory.createXAQueueConnection("guest", "guest");
- XAQueueSession session = _xaqueueConnection.createXAQueueSession();
- _queueConnection = _queueFactory.createQueueConnection();
- _nonXASession = _queueConnection.createQueueSession(true, Session.AUTO_ACKNOWLEDGE);
- init(session, _queue);
- }
- }
-
- /** -------------------------------------------------------------------------------------- **/
- /** ----------------------------- Test Suite -------------------------------------------- **/
- /** -------------------------------------------------------------------------------------- **/
-
- /**
- * Strategy:
- * Invoke start twice with the same xid on an XA resource.
- * Check that the second
- * invocation is throwing the expected XA exception.
- */
- public void testSameXID() throws Exception
- {
- Xid xid = getNewXid();
- _xaResource.start(xid, XAResource.TMNOFLAGS);
- // we now exepct this operation to fail
- try
- {
- _xaResource.start(xid, XAResource.TMNOFLAGS);
- fail("We managed to start a transaction with the same xid");
- }
- catch (XAException e)
- {
- assertEquals("Wrong error code: ", XAException.XAER_DUPID, e.errorCode);
- }
- }
-
- /**
- * Strategy:
- * Invoke start on a XA resource with flag other than TMNOFLAGS, TMJOIN, or TMRESUME.
- * Check that a XA Exception is thrown.
- */
- public void testWrongStartFlag()
- {
- Xid xid = getNewXid();
- try
- {
- _xaResource.start(xid, XAResource.TMONEPHASE);
- fail("We managed to start a transaction with a wrong flag");
- }
- catch (XAException e)
- {
- assertEquals("Wrong error code: ", XAException.XAER_INVAL, e.errorCode);
- }
- }
-
- /**
- * Strategy:
- * Check that a XA exception is thrown when:
- * A non started xid is ended
- */
- public void testEnd()
- {
- Xid xid = getNewXid();
- try
- {
- _xaResource.end(xid, XAResource.TMSUCCESS);
- fail("We managed to end a transaction before it is started");
- }
- catch (XAException e)
- {
- assertEquals("Wrong error code: ", XAException.XAER_PROTO, e.errorCode);
- }
- }
-
-
- /**
- * Strategy:
- * Check that a XA exception is thrown when:
- * Call forget on an unknown xid
- * call forget on a started xid
- * A non started xid is prepared
- * A non ended xis is prepared
- */
- public void testForget()
- {
- Xid xid = getNewXid();
- try
- {
- _xaResource.forget(xid);
- fail("We managed to forget an unknown xid");
- }
- catch (XAException e)
- {
- // assertEquals("Wrong error code: ", XAException.XAER_NOTA, e.errorCode);
- }
- xid = getNewXid();
- try
- {
- _xaResource.start(xid, XAResource.TMNOFLAGS);
- _xaResource.forget(xid);
- fail("We managed to forget a started xid");
- }
- catch (XAException e)
- {
- assertEquals("Wrong error code: ", XAException.XAER_PROTO, e.errorCode);
- }
- }
-
- /**
- * Strategy:
- * Check that a XA exception is thrown when:
- * A non started xid is prepared
- * A non ended xid is prepared
- */
- public void testPrepare()
- {
- Xid xid = getNewXid();
- try
- {
- _xaResource.prepare(xid);
- fail("We managed to prepare an unknown xid");
- }
- catch (XAException e)
- {
- assertEquals("Wrong error code: ", XAException.XAER_NOTA, e.errorCode);
- }
- xid = getNewXid();
- try
- {
- _xaResource.start(xid, XAResource.TMNOFLAGS);
- _xaResource.prepare(xid);
- fail("We managed to prepare a started xid");
- }
- catch (XAException e)
- {
- assertEquals("Wrong error code: ", XAException.XAER_PROTO, e.errorCode);
- }
- }
-
- /**
- * Strategy:
- * Check that the expected XA exception is thrown when:
- * A non started xid is committed
- * A non ended xid is committed
- * A non prepared xid is committed with one phase set to false.
- * A prepared xid is committed with one phase set to true.
- */
- public void testCommit() throws Exception
- {
- Xid xid = getNewXid();
- try
- {
- _xaResource.commit(xid, true);
- fail("We managed to commit an unknown xid");
- }
- catch (XAException e)
- {
- assertEquals("Wrong error code: ", XAException.XAER_NOTA, e.errorCode);
- }
- xid = getNewXid();
- try
- {
- _xaResource.start(xid, XAResource.TMNOFLAGS);
- _xaResource.commit(xid, true);
- fail("We managed to commit a not ended xid");
- }
- catch (XAException e)
- {
- assertEquals("Wrong error code: ", XAException.XAER_PROTO, e.errorCode);
- }
- xid = getNewXid();
- try
- {
- _xaResource.start(xid, XAResource.TMNOFLAGS);
- _xaResource.end(xid, XAResource.TMSUCCESS);
- _xaResource.commit(xid, false);
- fail("We managed to commit a not prepared xid");
- }
- catch (XAException e)
- {
- assertEquals("Wrong error code: ", XAException.XAER_PROTO, e.errorCode);
- }
- xid = getNewXid();
- try
- {
- _xaResource.start(xid, XAResource.TMNOFLAGS);
- _xaResource.end(xid, XAResource.TMSUCCESS);
- _xaResource.prepare(xid);
- _xaResource.commit(xid, true);
- fail("We managed to commit a prepared xid");
- }
- catch (XAException e)
- {
- assertEquals("Wrong error code: ", XAException.XAER_PROTO, e.errorCode);
- }
- finally
- {
- _xaResource.commit(xid, false);
- }
- }
-
- /**
- * Strategy:
- * Check that the expected XA exception is thrown when:
- * A non started xid is rolled back
- * A non ended xid is rolled back
- */
- public void testRollback()
- {
- Xid xid = getNewXid();
- try
- {
- _xaResource.rollback(xid);
- fail("We managed to rollback an unknown xid");
- }
- catch (XAException e)
- {
- assertEquals("Wrong error code: ", XAException.XAER_NOTA, e.errorCode);
- }
- xid = getNewXid();
- try
- {
- _xaResource.start(xid, XAResource.TMNOFLAGS);
- _xaResource.rollback(xid);
- fail("We managed to rollback a not ended xid");
- }
- catch (XAException e)
- {
- assertEquals("Wrong error code: ", XAException.XAER_PROTO, e.errorCode);
- }
- }
-
- /**
- * Strategy:
- * Check that the timeout is set correctly
- */
- public void testTransactionTimeoutvalue() throws Exception
- {
- Xid xid = getNewXid();
- _xaResource.start(xid, XAResource.TMNOFLAGS);
- assertEquals("Wrong timeout", _xaResource.getTransactionTimeout(), 0);
- _xaResource.setTransactionTimeout(1000);
- assertEquals("Wrong timeout", _xaResource.getTransactionTimeout(), 1000);
- _xaResource.end(xid, XAResource.TMSUCCESS);
- xid = getNewXid();
- _xaResource.start(xid, XAResource.TMNOFLAGS);
- assertEquals("Wrong timeout", _xaResource.getTransactionTimeout(), 1000);
- }
-
- /**
- * Strategy:
- * Check that a transaction timeout as expected
- * - set timeout to 10ms
- * - sleep 1000ms
- * - call end and check that the expected exception is thrown
- */
- public void testTransactionTimeout() throws Exception
- {
- Xid xid = getNewXid();
- try
- {
- _xaResource.start(xid, XAResource.TMNOFLAGS);
- assertEquals("Wrong timeout", _xaResource.getTransactionTimeout(), 0);
- _xaResource.setTransactionTimeout(10);
- Thread.sleep(1000);
- _xaResource.end(xid, XAResource.TMSUCCESS);
- }
- catch (XAException e)
- {
- assertEquals("Wrong error code: ", XAException.XA_RBTIMEOUT, e.errorCode);
- }
- }
-
- /**
- * Strategy:
- * Set the transaction timeout to 1000
- */
- public void testTransactionTimeoutAfterCommit() throws Exception
- {
- Xid xid = getNewXid();
-
- _xaResource.start(xid, XAResource.TMNOFLAGS);
- _xaResource.setTransactionTimeout(1000);
- assertEquals("Wrong timeout", 1000,_xaResource.getTransactionTimeout());
-
- //_xaResource.prepare(xid);
- _xaResource.end(xid, XAResource.TMSUCCESS);
- _xaResource.commit(xid, true);
-
- _xaResource.setTransactionTimeout(2000);
- assertEquals("Wrong timeout", 2000,_xaResource.getTransactionTimeout());
-
- xid = getNewXid();
- _xaResource.start(xid, XAResource.TMNOFLAGS);
- assertEquals("Wrong timeout", 2000, _xaResource.getTransactionTimeout());
- }
-
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/xa/QueueTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/xa/QueueTest.java
deleted file mode 100644
index d2abc0eac1..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/xa/QueueTest.java
+++ /dev/null
@@ -1,657 +0,0 @@
-/* Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.qpid.test.unit.xa;
-
-import javax.jms.*;
-import javax.transaction.xa.XAResource;
-import javax.transaction.xa.Xid;
-import javax.transaction.xa.XAException;
-
-import junit.framework.TestSuite;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class QueueTest extends AbstractXATestCase
-{
- /* this clas logger */
- private static final Logger _logger = LoggerFactory.getLogger(QueueTest.class);
-
- /**
- * the queue use by all the tests
- */
- private static Queue _queue = null;
- /**
- * the queue connection factory used by all tests
- */
- private static XAQueueConnectionFactory _queueFactory = null;
-
- /**
- * standard xa queue connection
- */
- private static XAQueueConnection _xaqueueConnection= null;
-
- /**
- * standard xa queue connection
- */
- private static QueueConnection _queueConnection=null;
-
-
- /**
- * standard queue session created from the standard connection
- */
- private static QueueSession _nonXASession = null;
-
- /**
- * the queue name
- */
- private static final String QUEUENAME = "xaQueue";
-
- /** ----------------------------------------------------------------------------------- **/
- /**
- * ----------------------------- JUnit support ----------------------------------------- *
- */
-
- /**
- * Gets the test suite tests
- *
- * @return the test suite tests
- */
- public static TestSuite getSuite()
- {
- return new TestSuite(QueueTest.class);
- }
-
- /**
- * Run the test suite.
- *
- * @param args Any command line arguments specified to this class.
- */
- public static void main(String args[])
- {
- junit.textui.TestRunner.run(getSuite());
- }
-
- public void tearDown() throws Exception
- {
- if (!isBroker08())
- {
- try
- {
- _xaqueueConnection.close();
- _queueConnection.close();
- }
- catch (Exception e)
- {
- fail("Exception thrown when cleaning standard connection: " + e.getStackTrace());
- }
- }
- super.tearDown();
- }
-
- /**
- * Initialize standard actors
- */
- public void init()
- {
- if (!isBroker08())
- {
- // lookup test queue
- try
- {
- _queue = (Queue) getInitialContext().lookup(QUEUENAME);
- }
- catch (Exception e)
- {
- fail("cannot lookup test queue " + e.getMessage());
- }
-
- // lookup connection factory
- try
- {
- _queueFactory = getConnectionFactory();
- }
- catch (Exception e)
- {
- fail("enable to lookup connection factory ");
- }
- // create standard connection
- try
- {
- _xaqueueConnection= getNewQueueXAConnection();
- }
- catch (JMSException e)
- {
- fail("cannot create queue connection: " + e.getMessage());
- }
- // create xa session
- XAQueueSession session = null;
- try
- {
- session = _xaqueueConnection.createXAQueueSession();
- }
- catch (JMSException e)
- {
- fail("cannot create queue session: " + e.getMessage());
- }
- // create a standard session
- try
- {
- _queueConnection = _queueFactory.createQueueConnection();
- _nonXASession = _queueConnection.createQueueSession(true, Session.AUTO_ACKNOWLEDGE);
- }
- catch (JMSException e)
- {
- fail("cannot create queue session: " + e.getMessage());
- }
- init(session, _queue);
- }
- }
-
- /** -------------------------------------------------------------------------------------- **/
- /** ----------------------------- Test Suite -------------------------------------------- **/
- /** -------------------------------------------------------------------------------------- **/
-
- /**
- * Uses two transactions respectively with xid1 and xid2 that are used to send a message
- * within xid1 and xid2. xid2 is committed and xid1 is used to receive the message that was sent within xid2.
- * Xid is then committed and a standard transaction is used to receive the message that was sent within xid1.
- */
- public void testProducer()
- {
- if (!isBroker08())
- {
- _logger.debug("running testProducer");
- Xid xid1 = getNewXid();
- Xid xid2 = getNewXid();
- // start the xaResource for xid1
- try
- {
- _xaResource.start(xid1, XAResource.TMNOFLAGS);
- }
- catch (XAException e)
- {
- e.printStackTrace();
- fail("cannot start the transaction with xid1: " + e.getMessage());
- }
- try
- {
- // start the connection
- _xaqueueConnection.start();
- // produce a message with sequence number 1
- _message.setLongProperty(_sequenceNumberPropertyName, 1);
- _producer.send(_message);
- }
- catch (JMSException e)
- {
- fail(" cannot send persistent message: " + e.getMessage());
- }
- // suspend the transaction
- try
- {
- _xaResource.end(xid1, XAResource.TMSUSPEND);
- }
- catch (XAException e)
- {
- fail("Cannot end the transaction with xid1: " + e.getMessage());
- }
- // start the xaResource for xid2
- try
- {
- _xaResource.start(xid2, XAResource.TMNOFLAGS);
- }
- catch (XAException e)
- {
- fail("cannot start the transaction with xid2: " + e.getMessage());
- }
- try
- {
- // produce a message
- _message.setLongProperty(_sequenceNumberPropertyName, 2);
- _producer.send(_message);
- }
- catch (JMSException e)
- {
- fail(" cannot send second persistent message: " + e.getMessage());
- }
- // end xid2 and start xid1
- try
- {
- _xaResource.end(xid2, XAResource.TMSUCCESS);
- _xaResource.start(xid1, XAResource.TMRESUME);
- }
- catch (XAException e)
- {
- fail("Exception when ending and starting transactions: " + e.getMessage());
- }
- // two phases commit transaction with xid2
- try
- {
- int resPrepare = _xaResource.prepare(xid2);
- if (resPrepare != XAResource.XA_OK)
- {
- fail("prepare returned: " + resPrepare);
- }
- _xaResource.commit(xid2, false);
- }
- catch (XAException e)
- {
- fail("Exception thrown when preparing transaction with xid2: " + e.getMessage());
- }
- // receive a message from queue test we expect it to be the second one
- try
- {
- TextMessage message = (TextMessage) _consumer.receive(1000);
- if (message == null)
- {
- fail("did not receive second message as expected ");
- }
- else
- {
- if (message.getLongProperty(_sequenceNumberPropertyName) != 2)
- {
- fail("receive wrong message its sequence number is: " + message
- .getLongProperty(_sequenceNumberPropertyName));
- }
- }
- }
- catch (JMSException e)
- {
- fail("Exception when receiving second message: " + e.getMessage());
- }
- // end and one phase commit the first transaction
- try
- {
- _xaResource.end(xid1, XAResource.TMSUCCESS);
- _xaResource.commit(xid1, true);
- }
- catch (XAException e)
- {
- fail("Exception thrown when commiting transaction with xid1");
- }
- // We should now be able to receive the first message
- try
- {
- _xaqueueConnection.close();
- Session nonXASession = _nonXASession;
- MessageConsumer nonXAConsumer = nonXASession.createConsumer(_queue);
- _queueConnection.start();
- TextMessage message1 = (TextMessage) nonXAConsumer.receive(1000);
- if (message1 == null)
- {
- fail("did not receive first message as expected ");
- }
- else
- {
- if (message1.getLongProperty(_sequenceNumberPropertyName) != 1)
- {
- fail("receive wrong message its sequence number is: " + message1
- .getLongProperty(_sequenceNumberPropertyName));
- }
- }
- // commit that transacted session
- nonXASession.commit();
- // the queue should be now empty
- message1 = (TextMessage) nonXAConsumer.receive(1000);
- if (message1 != null)
- {
- fail("receive an unexpected message ");
- }
- }
- catch (JMSException e)
- {
- fail("Exception thrown when emptying the queue: " + e.getMessage());
- }
- }
- }
-
- /**
- * strategy: Produce a message within Tx1 and prepare tx1. crash the server then commit tx1 and consume the message
- */
- public void testSendAndRecover()
- {
- if (!isBroker08())
- {
- _logger.debug("running testSendAndRecover");
- Xid xid1 = getNewXid();
- // start the xaResource for xid1
- try
- {
- _xaResource.start(xid1, XAResource.TMNOFLAGS);
- }
- catch (XAException e)
- {
- fail("cannot start the transaction with xid1: " + e.getMessage());
- }
- try
- {
- // start the connection
- _xaqueueConnection.start();
- // produce a message with sequence number 1
- _message.setLongProperty(_sequenceNumberPropertyName, 1);
- _producer.send(_message);
- }
- catch (JMSException e)
- {
- fail(" cannot send persistent message: " + e.getMessage());
- }
- // suspend the transaction
- try
- {
- _xaResource.end(xid1, XAResource.TMSUCCESS);
- }
- catch (XAException e)
- {
- fail("Cannot end the transaction with xid1: " + e.getMessage());
- }
- // prepare the transaction with xid1
- try
- {
- _xaResource.prepare(xid1);
- }
- catch (XAException e)
- {
- fail("Exception when preparing xid1: " + e.getMessage());
- }
-
- /////// stop the server now !!
- try
- {
- _logger.debug("stopping broker");
- restartBroker();
- init();
- }
- catch (Exception e)
- {
- fail("Exception when stopping and restarting the server");
- }
-
- // get the list of in doubt transactions
- try
- {
- Xid[] inDoubt = _xaResource.recover(XAResource.TMSTARTRSCAN);
- if (inDoubt == null)
- {
- fail("the array of in doubt transactions should not be null ");
- }
- // At that point we expect only two indoubt transactions:
- if (inDoubt.length != 1)
- {
- fail("in doubt transaction size is diffenrent thatn 2, there are " + inDoubt.length + "in doubt transactions");
- }
-
- // commit them
- for (Xid anInDoubt : inDoubt)
- {
- if (anInDoubt.equals(xid1))
- {
- System.out.println("commit xid1 ");
- try
- {
- _xaResource.commit(anInDoubt, false);
- }
- catch (Exception e)
- {
- System.out.println("PB when aborted xid1");
- }
- }
- else
- {
- fail("did not receive right xid ");
- }
- }
- }
- catch (XAException e)
- {
- e.printStackTrace();
- fail("exception thrown when recovering transactions " + e.getMessage());
- }
- // the queue should contain the first message!
- try
- {
- _xaqueueConnection.close();
- Session nonXASession = _nonXASession;
- MessageConsumer nonXAConsumer = nonXASession.createConsumer(_queue);
- _queueConnection.start();
- TextMessage message1 = (TextMessage) nonXAConsumer.receive(1000);
-
- if (message1 == null)
- {
- fail("queue does not contain any message!");
- }
- if (message1.getLongProperty(_sequenceNumberPropertyName) != 1)
- {
- fail("Wrong message returned! Sequence number is " + message1
- .getLongProperty(_sequenceNumberPropertyName));
- }
- nonXASession.commit();
- }
- catch (JMSException e)
- {
- fail("Exception thrown when testin that queue test is not empty: " + e.getMessage());
- }
- }
- }
-
- /**
- * strategy: Produce a message within Tx1 and prepare tx1. Produce a standard message and consume
- * it within tx2 and prepare tx2. Shutdown the server and get the list of in doubt transactions:
- * we expect tx1 and tx2! Then, Tx1 is aborted and tx2 is committed so we expect the test's queue to be empty!
- */
- public void testRecover()
- {
- if (!isBroker08())
- {
- _logger.debug("running testRecover");
- Xid xid1 = getNewXid();
- Xid xid2 = getNewXid();
- // start the xaResource for xid1
- try
- {
- _xaResource.start(xid1, XAResource.TMNOFLAGS);
- }
- catch (XAException e)
- {
- fail("cannot start the transaction with xid1: " + e.getMessage());
- }
- try
- {
- // start the connection
- _xaqueueConnection.start();
- // produce a message with sequence number 1
- _message.setLongProperty(_sequenceNumberPropertyName, 1);
- _producer.send(_message);
- }
- catch (JMSException e)
- {
- fail(" cannot send persistent message: " + e.getMessage());
- }
- // suspend the transaction
- try
- {
- _xaResource.end(xid1, XAResource.TMSUCCESS);
- }
- catch (XAException e)
- {
- fail("Cannot end the transaction with xid1: " + e.getMessage());
- }
- // prepare the transaction with xid1
- try
- {
- _xaResource.prepare(xid1);
- }
- catch (XAException e)
- {
- fail("Exception when preparing xid1: " + e.getMessage());
- }
-
- // send a message using the standard session
- try
- {
- Session nonXASession = _nonXASession;
- MessageProducer nonXAProducer = nonXASession.createProducer(_queue);
- TextMessage message2 = nonXASession.createTextMessage();
- message2.setText("non XA ");
- message2.setLongProperty(_sequenceNumberPropertyName, 2);
- nonXAProducer.setDeliveryMode(DeliveryMode.PERSISTENT);
- nonXAProducer.send(message2);
- // commit that transacted session
- nonXASession.commit();
- }
- catch (Exception e)
- {
- fail("Exception thrown when emptying the queue: " + e.getMessage());
- }
- // start the xaResource for xid2
- try
- {
- _xaResource.start(xid2, XAResource.TMNOFLAGS);
- }
- catch (XAException e)
- {
- fail("cannot start the transaction with xid1: " + e.getMessage());
- }
- // receive a message from queue test we expect it to be the second one
- try
- {
- TextMessage message = (TextMessage) _consumer.receive(1000);
- if (message == null || message.getLongProperty(_sequenceNumberPropertyName) != 2)
- {
- fail("did not receive second message as expected ");
- }
- }
- catch (JMSException e)
- {
- fail("Exception when receiving second message: " + e.getMessage());
- }
- // suspend the transaction
- try
- {
- _xaResource.end(xid2, XAResource.TMSUCCESS);
- }
- catch (XAException e)
- {
- fail("Cannot end the transaction with xid2: " + e.getMessage());
- }
- // prepare the transaction with xid1
- try
- {
- _xaResource.prepare(xid2);
- }
- catch (XAException e)
- {
- fail("Exception when preparing xid2: " + e.getMessage());
- }
-
- /////// stop the server now !!
- try
- {
- _logger.debug("stopping broker");
- restartBroker();
- init();
- }
- catch (Exception e)
- {
- fail("Exception when stopping and restarting the server");
- }
-
- // get the list of in doubt transactions
- try
- {
- Xid[] inDoubt = _xaResource.recover(XAResource.TMSTARTRSCAN);
- if (inDoubt == null)
- {
- fail("the array of in doubt transactions should not be null ");
- }
- // At that point we expect only two indoubt transactions:
- if (inDoubt.length != 2)
- {
- fail("in doubt transaction size is diffenrent thatn 2, there are " + inDoubt.length + "in doubt transactions");
- }
-
- // commit them
- for (Xid anInDoubt : inDoubt)
- {
- if (anInDoubt.equals(xid1))
- {
- _logger.debug("rollback xid1 ");
- try
- {
- _xaResource.rollback(anInDoubt);
- }
- catch (Exception e)
- {
- System.out.println("PB when aborted xid1");
- }
- }
- else if (anInDoubt.equals(xid2))
- {
- _logger.debug("commit xid2 ");
- try
- {
- _xaResource.commit(anInDoubt, false);
- }
- catch (Exception e)
- {
- System.out.println("PB when commiting xid2");
- }
- }
- }
- }
- catch (XAException e)
- {
- e.printStackTrace();
- fail("exception thrown when recovering transactions " + e.getMessage());
- }
- // the queue should be empty
- try
- {
- _xaqueueConnection.close();
- Session nonXASession = _nonXASession;
- MessageConsumer nonXAConsumer = nonXASession.createConsumer(_queue);
- _queueConnection.start();
- TextMessage message1 = (TextMessage) nonXAConsumer.receive(1000);
- if (message1 != null)
- {
- fail("The queue is not empty! ");
- }
- }
- catch (JMSException e)
- {
- fail("Exception thrown when testin that queue test is empty: " + e.getMessage());
- }
- }
- }
-
- /** -------------------------------------------------------------------------------------- **/
- /** ----------------------------- Utility methods --------------------------------------- **/
- /** -------------------------------------------------------------------------------------- **/
-
- /**
- * get a new queue connection
- *
- * @return a new queue connection
- * @throws JMSException If the JMS provider fails to create the queue connection
- * due to some internal error or in case of authentication failure
- */
- private XAQueueConnection getNewQueueXAConnection() throws JMSException
- {
- return _queueFactory.createXAQueueConnection("guest", "guest");
- }
-
-
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/unit/xa/TopicTest.java b/java/systests/src/main/java/org/apache/qpid/test/unit/xa/TopicTest.java
deleted file mode 100644
index 99d0f0a075..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/unit/xa/TopicTest.java
+++ /dev/null
@@ -1,1711 +0,0 @@
-/* Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.qpid.test.unit.xa;
-
-import javax.jms.*;
-import javax.transaction.xa.XAResource;
-import javax.transaction.xa.Xid;
-import javax.transaction.xa.XAException;
-
-import junit.framework.TestSuite;
-
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- *
- *
- */
-public class TopicTest extends AbstractXATestCase
-{
- /* this clas logger */
- private static final Logger _logger = LoggerFactory.getLogger(TopicTest.class);
-
- /**
- * the topic use by all the tests
- */
- private static Topic _topic = null;
-
- /**
- * the topic connection factory used by all tests
- */
- private static XATopicConnectionFactory _topicFactory = null;
-
- /**
- * standard topic connection
- */
- private static XATopicConnection _topicConnection = null;
-
- /**
- * standard topic session created from the standard connection
- */
- private static XATopicSession _session = null;
-
- private static TopicSession _nonXASession = null;
-
- /**
- * the topic name
- */
- private static final String TOPICNAME = "xaTopic";
-
- /**
- * Indicate that a listenere has failed
- */
- private static boolean _failure = false;
-
- /** -------------------------------------------------------------------------------------- **/
- /** ----------------------------- JUnit support ----------------------------------------- **/
- /** -------------------------------------------------------------------------------------- **/
-
- /**
- * Gets the test suite tests
- *
- * @return the test suite tests
- */
- public static TestSuite getSuite()
- {
- return new TestSuite(TopicTest.class);
- }
-
- /**
- * Run the test suite.
- *
- * @param args Any command line arguments specified to this class.
- */
- public static void main(String args[])
- {
- junit.textui.TestRunner.run(getSuite());
- }
-
- public void tearDown() throws Exception
- {
- if (!isBroker08())
- {
- try
- {
- _topicConnection.stop();
- _topicConnection.close();
- }
- catch (Exception e)
- {
- fail("Exception thrown when cleaning standard connection: " + e.getStackTrace());
- }
- }
- super.tearDown();
- }
-
- /**
- * Initialize standard actors
- */
- public void init()
- {
- if (!isBroker08())
- {
- // lookup test queue
- try
- {
- _topic = (Topic) getInitialContext().lookup(TOPICNAME);
- }
- catch (Exception e)
- {
- fail("cannot lookup test topic " + e.getMessage());
- }
- // lookup connection factory
- try
- {
- _topicFactory = getConnectionFactory();
- }
- catch (Exception e)
- {
- fail("enable to lookup connection factory ");
- }
- // create standard connection
- try
- {
- _topicConnection = getNewTopicXAConnection();
- }
- catch (JMSException e)
- {
- fail("cannot create queue connection: " + e.getMessage());
- }
- // create standard session
- try
- {
- _session = _topicConnection.createXATopicSession();
- }
- catch (JMSException e)
- {
- fail("cannot create queue session: " + e.getMessage());
- }
- // create a standard session
- try
- {
- _nonXASession = _topicConnection.createTopicSession(true, Session.AUTO_ACKNOWLEDGE);
- }
- catch (JMSException e)
- {
- e.printStackTrace(); //To change body of catch statement use Options | File Templates.
- }
- init(_session, _topic);
- }
- }
-
- /** -------------------------------------------------------------------------------------- **/
- /** ----------------------------- Test Suite -------------------------------------------- **/
- /** -------------------------------------------------------------------------------------- **/
-
-
- /**
- * Uses two transactions respectively with xid1 and xid2 that are use to send a message
- * within xid1 and xid2. xid2 is committed and xid1 is used to receive the message that was sent within xid2.
- * Xid is then committed and a standard transaction is used to receive the message that was sent within xid1.
- */
- public void testProducer()
- {
- if (!isBroker08())
- {
- _logger.debug("testProducer");
- Xid xid1 = getNewXid();
- Xid xid2 = getNewXid();
- try
- {
- Session nonXASession = _nonXASession;
- MessageConsumer nonXAConsumer = nonXASession.createConsumer(_topic);
- _producer.setDeliveryMode(DeliveryMode.PERSISTENT);
- // start the xaResource for xid1
- try
- {
- _logger.debug("starting tx branch xid1");
- _xaResource.start(xid1, XAResource.TMNOFLAGS);
- }
- catch (XAException e)
- {
- e.printStackTrace();
- fail("cannot start the transaction with xid1: " + e.getMessage());
- }
- try
- {
- // start the connection
- _topicConnection.start();
- _logger.debug("produce a message with sequence number 1");
- _message.setLongProperty(_sequenceNumberPropertyName, 1);
- _producer.send(_message);
- }
- catch (JMSException e)
- {
- fail(" cannot send persistent message: " + e.getMessage());
- }
- _logger.debug("suspend the transaction branch xid1");
- try
- {
- _xaResource.end(xid1, XAResource.TMSUSPEND);
- }
- catch (XAException e)
- {
- fail("Cannot end the transaction with xid1: " + e.getMessage());
- }
- _logger.debug("start the xaResource for xid2");
- try
- {
- _xaResource.start(xid2, XAResource.TMNOFLAGS);
- }
- catch (XAException e)
- {
- fail("cannot start the transaction with xid2: " + e.getMessage());
- }
- try
- {
- _logger.debug("produce a message");
- _message.setLongProperty(_sequenceNumberPropertyName, 2);
- _producer.send(_message);
- }
- catch (JMSException e)
- {
- fail(" cannot send second persistent message: " + e.getMessage());
- }
- _logger.debug("end xid2 and start xid1");
- try
- {
- _xaResource.end(xid2, XAResource.TMSUCCESS);
- _xaResource.start(xid1, XAResource.TMRESUME);
- }
- catch (XAException e)
- {
- fail("Exception when ending and starting transactions: " + e.getMessage());
- }
- _logger.debug("two phases commit transaction with xid2");
- try
- {
- int resPrepare = _xaResource.prepare(xid2);
- if (resPrepare != XAResource.XA_OK)
- {
- fail("prepare returned: " + resPrepare);
- }
- _xaResource.commit(xid2, false);
- }
- catch (XAException e)
- {
- fail("Exception thrown when preparing transaction with xid2: " + e.getMessage());
- }
- _logger.debug("receiving a message from topic test we expect it to be the second one");
- try
- {
- TextMessage message = (TextMessage) _consumer.receive(1000);
- if (message == null)
- {
- fail("did not receive second message as expected ");
- }
- else
- {
- if (message.getLongProperty(_sequenceNumberPropertyName) != 2)
- {
- fail("receive wrong message its sequence number is: " + message
- .getLongProperty(_sequenceNumberPropertyName));
- }
- }
- }
- catch (JMSException e)
- {
- fail("Exception when receiving second message: " + e.getMessage());
- }
- _logger.debug("end and one phase commit the first transaction");
- try
- {
- _xaResource.end(xid1, XAResource.TMSUCCESS);
- _xaResource.commit(xid1, true);
- }
- catch (XAException e)
- {
- fail("Exception thrown when commiting transaction with xid1");
- }
- _logger.debug("We should now be able to receive the first and second message");
- try
- {
- TextMessage message1 = (TextMessage) nonXAConsumer.receive(1000);
- if (message1 == null)
- {
- fail("did not receive first message as expected ");
- }
- else
- {
- if (message1.getLongProperty(_sequenceNumberPropertyName) != 2)
- {
- fail("receive wrong message its sequence number is: " + message1
- .getLongProperty(_sequenceNumberPropertyName));
- }
- }
- message1 = (TextMessage) nonXAConsumer.receive(1000);
- if (message1 == null)
- {
- fail("did not receive first message as expected ");
- }
- else
- {
- if (message1.getLongProperty(_sequenceNumberPropertyName) != 1)
- {
- fail("receive wrong message its sequence number is: " + message1
- .getLongProperty(_sequenceNumberPropertyName));
- }
- }
- _logger.debug("commit transacted session");
- nonXASession.commit();
- _logger.debug("Test that the topic is now empty");
- message1 = (TextMessage) nonXAConsumer.receive(1000);
- if (message1 != null)
- {
- fail("receive an unexpected message ");
- }
- }
- catch (JMSException e)
- {
- fail("Exception thrown when emptying the queue: " + e.getMessage());
- }
- }
- catch (JMSException e)
- {
- fail("cannot create standard consumer: " + e.getMessage());
- }
- }
- }
-
-
- /**
- * strategy: Produce a message within Tx1 and commit tx1. consume this message within tx2 and abort tx2.
- * Consume the same message within tx3 and commit it. Check that no more message is available.
- */
- public void testDurSub()
- {
- if (!isBroker08())
- {
- Xid xid1 = getNewXid();
- Xid xid2 = getNewXid();
- Xid xid3 = getNewXid();
- Xid xid4 = getNewXid();
- String durSubName = "xaSubDurable";
- try
- {
- TopicSubscriber xaDurSub = _session.createDurableSubscriber(_topic, durSubName);
- try
- {
- _topicConnection.start();
- _logger.debug("start xid1");
- _xaResource.start(xid1, XAResource.TMNOFLAGS);
- // start the connection
- _topicConnection.start();
- _logger.debug("produce a message with sequence number 1");
- _message.setLongProperty(_sequenceNumberPropertyName, 1);
- _producer.send(_message);
- _logger.debug("2 phases commit xid1");
- _xaResource.end(xid1, XAResource.TMSUCCESS);
- if (_xaResource.prepare(xid1) != XAResource.XA_OK)
- {
- fail("Problem when preparing tx1 ");
- }
- _xaResource.commit(xid1, false);
- }
- catch (Exception e)
- {
- e.printStackTrace();
- fail("Exception when working with xid1: " + e.getMessage());
- }
- try
- {
- _logger.debug("start xid2");
- _xaResource.start(xid2, XAResource.TMNOFLAGS);
- _logger.debug("receive the previously produced message");
- TextMessage message = (TextMessage) xaDurSub.receive(1000);
- if (message == null)
- {
- fail("no message received ");
- }
- else if (message.getLongProperty(_sequenceNumberPropertyName) != 1)
- {
- fail("wrong sequence number: " + message.getLongProperty(_sequenceNumberPropertyName));
- }
- _logger.debug("rollback xid2");
- boolean rollbackOnFailure = false;
- try
- {
- _xaResource.end(xid2, XAResource.TMFAIL);
- }
- catch (XAException e)
- {
- if (e.errorCode != XAException.XA_RBROLLBACK)
- {
- fail("Exception when working with xid2: " + e.getMessage());
- }
- rollbackOnFailure = true;
- }
- if (!rollbackOnFailure)
- {
- if (_xaResource.prepare(xid2) != XAResource.XA_OK)
- {
- fail("Problem when preparing tx2 ");
- }
- _xaResource.rollback(xid2);
- }
- }
- catch (Exception e)
- {
- e.printStackTrace();
- fail("Exception when working with xid2: " + e.getMessage());
- }
- try
- {
- _logger.debug("start xid3");
- _xaResource.start(xid3, XAResource.TMNOFLAGS);
- _logger.debug(" receive the previously aborted consumed message");
- TextMessage message = (TextMessage) xaDurSub.receive(1000);
- if (message == null)
- {
- fail("no message received ");
- }
- else if (message.getLongProperty(_sequenceNumberPropertyName) != 1)
- {
- fail("wrong sequence number: " + message.getLongProperty(_sequenceNumberPropertyName));
- }
- _logger.debug("commit xid3");
- _xaResource.end(xid3, XAResource.TMSUCCESS);
- if (_xaResource.prepare(xid3) != XAResource.XA_OK)
- {
- fail("Problem when preparing tx3 ");
- }
- _xaResource.commit(xid3, false);
- }
- catch (Exception e)
- {
- e.printStackTrace();
- fail("Exception when working with xid3: " + e.getMessage());
- }
- try
- {
- _logger.debug("start xid4");
- _xaResource.start(xid4, XAResource.TMNOFLAGS);
- _logger.debug("check that topic is empty");
- TextMessage message = (TextMessage) xaDurSub.receive(1000);
- if (message != null)
- {
- fail("An unexpected message was received ");
- }
- _logger.debug("commit xid4");
- _xaResource.end(xid4, XAResource.TMSUCCESS);
- _xaResource.commit(xid4, true);
- }
- catch (Exception e)
- {
- e.printStackTrace();
- fail("Exception when working with xid4: " + e.getMessage());
- }
- }
- catch (Exception e)
- {
- e.printStackTrace();
- fail("problem when creating dur sub: " + e.getMessage());
- }
- finally
- {
- try
- {
- _session.unsubscribe(durSubName);
- }
- catch (JMSException e)
- {
- e.printStackTrace();
- fail("problem when unsubscribing dur sub: " + e.getMessage());
- }
- }
- }
- }
-
- /**
- * strategy: create a XA durable subscriber dusSub, produce 7 messages with the standard session,
- * consume 2 messages respectively with tx1, tx2 and tx3
- * abort tx2, we now expect to receive messages 3 and 4 first! Receive 3 messages within tx1 i.e. 34 and 7!
- * commit tx3
- * abort tx1: we now expect that only messages 5 and 6 are definitly consumed!
- * start tx4 and consume messages 1 - 4 and 7
- * commit tx4
- * Now the topic should be empty!
- */
- public void testMultiMessagesDurSub()
- {
- if (!isBroker08())
- {
- Xid xid1 = getNewXid();
- Xid xid2 = getNewXid();
- Xid xid3 = getNewXid();
- Xid xid4 = getNewXid();
- Xid xid6 = getNewXid();
- String durSubName = "xaSubDurable";
- TextMessage message;
- try
- {
- TopicSubscriber xaDurSub = _session.createDurableSubscriber(_topic, durSubName);
- try
- {
- Session txSession = _nonXASession;
- MessageProducer txProducer = txSession.createProducer(_topic);
- _logger.debug("produce 10 persistent messages");
- txProducer.setDeliveryMode(DeliveryMode.PERSISTENT);
- _topicConnection.start();
- for (int i = 1; i <= 7; i++)
- {
- _message.setLongProperty(_sequenceNumberPropertyName, i);
- txProducer.send(_message);
- }
- // commit txSession
- txSession.commit();
- }
- catch (JMSException e)
- {
- e.printStackTrace();
- fail("Exception thrown when producing messages: " + e.getMessage());
- }
-
- try
- {
- _logger.debug(" consume 2 messages respectively with tx1, tx2 and tx3");
- //----- start xid1
- _xaResource.start(xid1, XAResource.TMNOFLAGS);
- // receive the 2 first messages
- for (int i = 1; i <= 2; i++)
- {
- message = (TextMessage) xaDurSub.receive(1000);
- if (message == null)
- {
- fail("no message received! expected: " + i);
- }
- else if (message.getLongProperty(_sequenceNumberPropertyName) != i)
- {
- fail("wrong sequence number: " + message.getLongProperty(_sequenceNumberPropertyName));
- }
- }
- _xaResource.end(xid1, XAResource.TMSUSPEND);
- //----- start xid2
- _xaResource.start(xid2, XAResource.TMNOFLAGS);
- // receive the 2 first messages
- for (int i = 3; i <= 4; i++)
- {
- message = (TextMessage) xaDurSub.receive(1000);
- if (message == null)
- {
- fail("no message received! expected: " + i);
- }
- else if (message.getLongProperty(_sequenceNumberPropertyName) != i)
- {
- fail("wrong sequence number: " + message.getLongProperty(_sequenceNumberPropertyName));
- }
- }
- _xaResource.end(xid2, XAResource.TMSUSPEND);
- //----- start xid3
- _xaResource.start(xid3, XAResource.TMNOFLAGS);
- // receive the 2 first messages
- for (int i = 5; i <= 6; i++)
- {
- message = (TextMessage) xaDurSub.receive(1000);
- if (message == null)
- {
- fail("no message received! expected: " + i);
- }
- else if (message.getLongProperty(_sequenceNumberPropertyName) != i)
- {
- fail("wrong sequence number: " + message.getLongProperty(_sequenceNumberPropertyName));
- }
- }
- _xaResource.end(xid3, XAResource.TMSUCCESS);
- }
- catch (Exception e)
- {
- e.printStackTrace();
- fail("Exception thrown when consumming 6 first messages: " + e.getMessage());
- }
- try
- {
- _logger.debug("abort tx2, we now expect to receive messages 3, 4 and 7");
- _xaResource.start(xid2, XAResource.TMRESUME);
- _xaResource.end(xid2, XAResource.TMSUCCESS);
- _xaResource.prepare(xid2);
- _xaResource.rollback(xid2);
- // receive 3 message within tx1: 3, 4 and 7
- _xaResource.start(xid1, XAResource.TMRESUME);
- _logger.debug(" 3, 4 and 7");
- for (int i = 1; i <= 3; i++)
- {
- message = (TextMessage) xaDurSub.receive(1000);
- if (message == null)
- {
- fail("no message received! expected: " + 3);
- }
- else if (message.getLongProperty(_sequenceNumberPropertyName) <= 2 || 5 == message
- .getLongProperty(_sequenceNumberPropertyName) || message
- .getLongProperty(_sequenceNumberPropertyName) == 6)
- {
- fail("wrong sequence number: " + message
- .getLongProperty(_sequenceNumberPropertyName));
- }
- }
- }
- catch (Exception e)
- {
- e.printStackTrace();
- fail("Exception thrown when consumming message: 3, 4 and 7: " + e.getMessage());
- }
-
- try
- {
- _xaResource.end(xid1, XAResource.TMSUCCESS);
- _logger.debug(" commit tx3");
- _xaResource.commit(xid3, true);
- _logger.debug("abort tx1");
- _xaResource.prepare(xid1);
- _xaResource.rollback(xid1);
- }
- catch (XAException e)
- {
- e.printStackTrace();
- fail("XAException thrown when committing tx3 or aborting tx1: " + e.getMessage());
- }
-
- try
- {
- // consume messages 1 - 4 + 7
- //----- start xid1
- _xaResource.start(xid4, XAResource.TMNOFLAGS);
- for (int i = 1; i <= 5; i++)
- {
-
- message = (TextMessage) xaDurSub.receive(1000);
- _logger.debug(" received message: " + message.getLongProperty(_sequenceNumberPropertyName));
- if (message == null)
- {
- fail("no message received! expected: " + i);
- }
- else if (message.getLongProperty(_sequenceNumberPropertyName) == 5 || message
- .getLongProperty(_sequenceNumberPropertyName) == 6)
- {
- fail("wrong sequence number: " + message.getLongProperty(_sequenceNumberPropertyName));
- }
- }
- _xaResource.end(xid4, XAResource.TMSUCCESS);
- _xaResource.prepare(xid4);
- _xaResource.commit(xid4, false);
- }
- catch (Exception e)
- {
- e.printStackTrace();
- fail("Exception thrown in last phase: " + e.getMessage());
- }
- // now the topic should be empty!!
- try
- {
- // start xid6
- _xaResource.start(xid6, XAResource.TMNOFLAGS);
- // should now be empty
- message = (TextMessage) xaDurSub.receive(1000);
- if (message != null)
- {
- fail("An unexpected message was received " + message
- .getLongProperty(_sequenceNumberPropertyName));
- }
- // commit xid6
- _xaResource.end(xid6, XAResource.TMSUCCESS);
- _xaResource.commit(xid6, true);
- }
- catch (Exception e)
- {
- e.printStackTrace();
- fail("Exception when working with xid6: " + e.getMessage());
- }
- }
- catch (Exception e)
- {
- e.printStackTrace();
- fail("problem when creating dur sub: " + e.getMessage());
- }
- finally
- {
- try
- {
- _session.unsubscribe(durSubName);
- }
- catch (JMSException e)
- {
- e.printStackTrace();
- fail("problem when unsubscribing dur sub: " + e.getMessage());
- }
- }
- }
- }
-
- /**
- * strategy: create a XA durable subscriber dusSub, produce 10 messages with the standard session,
- * consume 2 messages respectively with tx1, tx2 and tx3
- * prepare xid2 and xid3
- * crash the server
- * Redo the job for xid1 that has been aborted by server crash
- * abort tx2, we now expect to receive messages 3 and 4 first! Receive 3 messages within tx1 i.e. 34 and 7!
- * commit tx3
- * abort tx1: we now expect that only messages 5 and 6 are definitly consumed!
- * start tx4 and consume messages 1 - 4
- * start tx5 and consume messages 7 - 10
- * abort tx4
- * consume messages 1-4 with tx5
- * commit tx5
- * Now the topic should be empty!
- */
- public void testMultiMessagesDurSubCrash()
- {
- if (!isBroker08())
- {
- Xid xid1 = getNewXid();
- Xid xid2 = getNewXid();
- Xid xid3 = getNewXid();
- Xid xid4 = getNewXid();
- Xid xid5 = getNewXid();
- Xid xid6 = getNewXid();
- String durSubName = "xaSubDurable";
- TextMessage message;
- try
- {
- TopicSubscriber xaDurSub = _session.createDurableSubscriber(_topic, durSubName);
- try
- {
- Session txSession = _nonXASession;
- MessageProducer txProducer = txSession.createProducer(_topic);
- // produce 10 persistent messages
- txProducer.setDeliveryMode(DeliveryMode.PERSISTENT);
- _topicConnection.start();
- for (int i = 1; i <= 10; i++)
- {
- _message.setLongProperty(_sequenceNumberPropertyName, i);
- txProducer.send(_message);
- }
- // commit txSession
- txSession.commit();
- }
- catch (JMSException e)
- {
- e.printStackTrace();
- fail("Exception thrown when producing messages: " + e.getMessage());
- }
- try
- {
- // consume 2 messages respectively with tx1, tx2 and tx3
- //----- start xid1
- _xaResource.start(xid1, XAResource.TMNOFLAGS);
- // receive the 2 first messages
- for (int i = 1; i <= 2; i++)
- {
- message = (TextMessage) xaDurSub.receive(1000);
- if (message == null)
- {
- fail("no message received! expected: " + i);
- }
- else if (message.getLongProperty(_sequenceNumberPropertyName) != i)
- {
- fail("wrong sequence number: " + message.getLongProperty(_sequenceNumberPropertyName));
- }
- }
- _xaResource.end(xid1, XAResource.TMSUCCESS);
- //----- start xid2
- _xaResource.start(xid2, XAResource.TMNOFLAGS);
- // receive the 2 first messages
- for (int i = 3; i <= 4; i++)
- {
- message = (TextMessage) xaDurSub.receive(1000);
- if (message == null)
- {
- fail("no message received! expected: " + i);
- }
- else if (message.getLongProperty(_sequenceNumberPropertyName) != i)
- {
- fail("wrong sequence number: " + message.getLongProperty(_sequenceNumberPropertyName));
- }
- }
- _xaResource.end(xid2, XAResource.TMSUCCESS);
- //----- start xid3
- _xaResource.start(xid3, XAResource.TMNOFLAGS);
- // receive the 2 first messages
- for (int i = 5; i <= 6; i++)
- {
- message = (TextMessage) xaDurSub.receive(1000);
- if (message == null)
- {
- fail("no message received! expected: " + i);
- }
- else if (message.getLongProperty(_sequenceNumberPropertyName) != i)
- {
- fail("wrong sequence number: " + message.getLongProperty(_sequenceNumberPropertyName));
- }
- }
- _xaResource.end(xid3, XAResource.TMSUCCESS);
- // prepare tx2 and tx3
-
- _xaResource.prepare(xid2);
- _xaResource.prepare(xid3);
- }
- catch (Exception e)
- {
- e.printStackTrace();
- fail("Exception thrown when consumming 6 first messages: " + e.getMessage());
- }
- /////// stop the broker now !!
- try
- {
- restartBroker();
- init();
- }
- catch (Exception e)
- {
- fail("Exception when stopping and restarting the server");
- }
- // get the list of in doubt transactions
- try
- {
- _topicConnection.start();
- // reconnect to dursub!
- xaDurSub = _session.createDurableSubscriber(_topic, durSubName);
- Xid[] inDoubt = _xaResource.recover(XAResource.TMSTARTRSCAN);
- if (inDoubt == null)
- {
- fail("the array of in doubt transactions should not be null ");
- }
- // At that point we expect only two indoubt transactions:
- if (inDoubt.length != 2)
- {
- fail("in doubt transaction size is diffenrent than 2, there are " + inDoubt.length + "in doubt transactions");
- }
- }
- catch (XAException e)
- {
- e.printStackTrace();
- fail("exception thrown when recovering transactions " + e.getMessage());
- }
- try
- {
- // xid1 has been aborted redo the job!
- // consume 2 messages with tx1
- //----- start xid1
- _xaResource.start(xid1, XAResource.TMNOFLAGS);
- // receive the 2 first messages
- for (int i = 1; i <= 2; i++)
- {
- message = (TextMessage) xaDurSub.receive(1000);
- if (message == null)
- {
- fail("no message received! expected: " + i);
- }
- else if (message.getLongProperty(_sequenceNumberPropertyName) != i)
- {
- fail("wrong sequence number: " + message.getLongProperty(_sequenceNumberPropertyName));
- }
- }
- _xaResource.end(xid1, XAResource.TMSUSPEND);
- // abort tx2, we now expect to receive messages 3 and 4 first!
- _xaResource.rollback(xid2);
-
- // receive 3 message within tx1: 3, 4 and 7
- _xaResource.start(xid1, XAResource.TMRESUME);
- // receive messages 3, 4 and 7
- message = (TextMessage) xaDurSub.receive(1000);
- if (message == null)
- {
- fail("no message received! expected: " + 3);
- }
- else if (message.getLongProperty(_sequenceNumberPropertyName) != 3)
- {
- fail("wrong sequence number: " + message
- .getLongProperty(_sequenceNumberPropertyName) + " 3 was expected");
- }
- message = (TextMessage) xaDurSub.receive(1000);
- if (message == null)
- {
- fail("no message received! expected: " + 4);
- }
- else if (message.getLongProperty(_sequenceNumberPropertyName) != 4)
- {
- fail("wrong sequence number: " + message
- .getLongProperty(_sequenceNumberPropertyName) + " 4 was expected");
- }
- message = (TextMessage) xaDurSub.receive(1000);
- if (message == null)
- {
- fail("no message received! expected: " + 7);
- }
- else if (message.getLongProperty(_sequenceNumberPropertyName) != 7)
- {
- fail("wrong sequence number: " + message
- .getLongProperty(_sequenceNumberPropertyName) + " 7 was expected");
- }
- }
- catch (Exception e)
- {
- e.printStackTrace();
- fail("Exception thrown when consumming message: 3, 4 and 7: " + e.getMessage());
- }
-
- try
- {
- _xaResource.end(xid1, XAResource.TMSUSPEND);
- // commit tx3
- _xaResource.commit(xid3, false);
- // abort tx1
- _xaResource.prepare(xid1);
- _xaResource.rollback(xid1);
- }
- catch (XAException e)
- {
- e.printStackTrace();
- fail("XAException thrown when committing tx3 or aborting tx1: " + e.getMessage());
- }
-
- try
- {
- // consume messages 1 - 4
- //----- start xid1
- _xaResource.start(xid4, XAResource.TMNOFLAGS);
- for (int i = 1; i <= 4; i++)
- {
- message = (TextMessage) xaDurSub.receive(1000);
- if (message == null)
- {
- fail("no message received! expected: " + i);
- }
- else if (message.getLongProperty(_sequenceNumberPropertyName) != i)
- {
- fail("wrong sequence number: " + message.getLongProperty(_sequenceNumberPropertyName));
- }
- }
- _xaResource.end(xid4, XAResource.TMSUSPEND);
- // consume messages 8 - 10
- _xaResource.start(xid5, XAResource.TMNOFLAGS);
- for (int i = 7; i <= 10; i++)
- {
- message = (TextMessage) xaDurSub.receive(1000);
- if (message == null)
- {
- fail("no message received! expected: " + i);
- }
- else if (message.getLongProperty(_sequenceNumberPropertyName) != i)
- {
- fail("wrong sequence number: " + message.getLongProperty(_sequenceNumberPropertyName));
- }
- }
- _xaResource.end(xid5, XAResource.TMSUSPEND);
- // abort tx4
- _xaResource.prepare(xid4);
- _xaResource.rollback(xid4);
- // consume messages 1-4 with tx5
- _xaResource.start(xid5, XAResource.TMRESUME);
- for (int i = 1; i <= 4; i++)
- {
- message = (TextMessage) xaDurSub.receive(1000);
- if (message == null)
- {
- fail("no message received! expected: " + i);
- }
- else if (message.getLongProperty(_sequenceNumberPropertyName) != i)
- {
- fail("wrong sequence number: " + message.getLongProperty(_sequenceNumberPropertyName));
- }
- }
- _xaResource.end(xid5, XAResource.TMSUSPEND);
- // commit tx5
- _xaResource.prepare(xid5);
- _xaResource.commit(xid5, false);
- }
- catch (Exception e)
- {
- e.printStackTrace();
- fail("Exception thrown in last phase: " + e.getMessage());
- }
- // now the topic should be empty!!
- try
- {
- // start xid6
- _xaResource.start(xid6, XAResource.TMNOFLAGS);
- // should now be empty
- message = (TextMessage) xaDurSub.receive(1000);
- if (message != null)
- {
- fail("An unexpected message was received " + message
- .getLongProperty(_sequenceNumberPropertyName));
- }
- // commit xid6
- _xaResource.end(xid6, XAResource.TMSUSPEND);
- _xaResource.commit(xid6, true);
- }
- catch (Exception e)
- {
- e.printStackTrace();
- fail("Exception when working with xid6: " + e.getMessage());
- }
- }
- catch (Exception e)
- {
- e.printStackTrace();
- fail("problem when creating dur sub: " + e.getMessage());
- }
- finally
- {
- try
- {
- _session.unsubscribe(durSubName);
- }
- catch (JMSException e)
- {
- e.printStackTrace();
- fail("problem when unsubscribing dur sub: " + e.getMessage());
- }
- }
- }
- }
-
-
- /**
- * strategy: Produce a message within Tx1 and commit tx1. a durable subscriber then receives that message within tx2
- * that is then prepared.
- * Shutdown the server and get the list of in doubt transactions:
- * we expect tx2, Tx2 is aborted and the message consumed within tx3 that is committed we then check that the topic is empty.
- */
- public void testDurSubCrash()
- {
- if (!isBroker08())
- {
- Xid xid1 = getNewXid();
- Xid xid2 = getNewXid();
- Xid xid3 = getNewXid();
- Xid xid4 = getNewXid();
- String durSubName = "xaSubDurable";
- try
- {
- TopicSubscriber xaDurSub = _session.createDurableSubscriber(_topic, durSubName);
- try
- {
- _topicConnection.start();
- //----- start xid1
- _xaResource.start(xid1, XAResource.TMNOFLAGS);
- // start the connection
- _topicConnection.start();
- // produce a message with sequence number 1
- _message.setLongProperty(_sequenceNumberPropertyName, 1);
- _producer.send(_message);
- // commit
- _xaResource.end(xid1, XAResource.TMSUCCESS);
- if (_xaResource.prepare(xid1) != XAResource.XA_OK)
- {
- fail("Problem when preparing tx1 ");
- }
- _xaResource.commit(xid1, false);
- }
- catch (Exception e)
- {
- e.printStackTrace();
- fail("Exception when working with xid1: " + e.getMessage());
- }
- try
- {
- // start xid2
- _xaResource.start(xid2, XAResource.TMNOFLAGS);
- // receive the previously produced message
- TextMessage message = (TextMessage) xaDurSub.receive(1000);
- if (message == null)
- {
- fail("no message received ");
- }
- else if (message.getLongProperty(_sequenceNumberPropertyName) != 1)
- {
- fail("wrong sequence number: " + message.getLongProperty(_sequenceNumberPropertyName));
- }
- // prepare xid2
- _xaResource.end(xid2, XAResource.TMSUCCESS);
- if (_xaResource.prepare(xid2) != XAResource.XA_OK)
- {
- fail("Problem when preparing tx2 ");
- }
- }
- catch (Exception e)
- {
- e.printStackTrace();
- fail("Exception when working with xid2: " + e.getMessage());
- }
-
- /////// stop the server now !!
- try
- {
- restartBroker();
- init();
- }
- catch (Exception e)
- {
- fail("Exception when stopping and restarting the server");
- }
-
- // get the list of in doubt transactions
- try
- {
- _topicConnection.start();
- // reconnect to dursub!
- xaDurSub = _session.createDurableSubscriber(_topic, durSubName);
- Xid[] inDoubt = _xaResource.recover(XAResource.TMSTARTRSCAN);
- if (inDoubt == null)
- {
- fail("the array of in doubt transactions should not be null ");
- }
- // At that point we expect only two indoubt transactions:
- if (inDoubt.length != 1)
- {
- fail("in doubt transaction size is diffenrent than 2, there are " + inDoubt.length + "in doubt transactions");
- }
-
- // commit them
- for (Xid anInDoubt : inDoubt)
- {
- if (anInDoubt.equals(xid2))
- {
- System.out.println("aborting xid2 ");
- try
- {
- _xaResource.rollback(anInDoubt);
- }
- catch (Exception e)
- {
- e.printStackTrace();
- fail("exception when aborting xid2 ");
- }
- }
- else
- {
- System.out.println("XID2 is not in doubt ");
- }
- }
- }
- catch (XAException e)
- {
- e.printStackTrace();
- fail("exception thrown when recovering transactions " + e.getMessage());
- }
-
- try
- {
- // start xid3
- _xaResource.start(xid3, XAResource.TMNOFLAGS);
- // receive the previously produced message and aborted
- TextMessage message = (TextMessage) xaDurSub.receive(1000);
- if (message == null)
- {
- fail("no message received ");
- }
- else if (message.getLongProperty(_sequenceNumberPropertyName) != 1)
- {
- fail("wrong sequence number: " + message.getLongProperty(_sequenceNumberPropertyName));
- }
- // commit xid3
- _xaResource.end(xid3, XAResource.TMSUCCESS);
- if (_xaResource.prepare(xid3) != XAResource.XA_OK)
- {
- fail("Problem when preparing tx3 ");
- }
- _xaResource.commit(xid3, false);
- }
- catch (Exception e)
- {
- e.printStackTrace();
- fail("Exception when working with xid3: " + e.getMessage());
- }
- try
- {
- // start xid4
- _xaResource.start(xid4, XAResource.TMNOFLAGS);
- // should now be empty
- TextMessage message = (TextMessage) xaDurSub.receive(1000);
- if (message != null)
- {
- fail("An unexpected message was received " + message
- .getLongProperty(_sequenceNumberPropertyName));
- }
- // commit xid4
- _xaResource.end(xid4, XAResource.TMSUCCESS);
- _xaResource.commit(xid4, true);
- }
- catch (Exception e)
- {
- e.printStackTrace();
- fail("Exception when working with xid4: " + e.getMessage());
- }
- }
- catch (Exception e)
- {
- e.printStackTrace();
- fail("problem when creating dur sub: " + e.getMessage());
- }
- finally
- {
- try
- {
- _session.unsubscribe(durSubName);
- }
- catch (JMSException e)
- {
- e.printStackTrace();
- fail("problem when unsubscribing dur sub: " + e.getMessage());
- }
- }
- }
- }
-
- /**
- * strategy: Produce a message within Tx1 and prepare tx1. Shutdown the server and get the list of indoubt transactions:
- * we expect tx1, Tx1 is committed so we expect the test topic not to be empty!
- */
- public void testRecover()
- {
- if (!isBroker08())
- {
- Xid xid1 = getNewXid();
- String durSubName = "test1";
- try
- {
- // create a dummy durable subscriber to be sure that messages are persisted!
- _nonXASession.createDurableSubscriber(_topic, durSubName);
- // start the xaResource for xid1
- try
- {
- _xaResource.start(xid1, XAResource.TMNOFLAGS);
- }
- catch (XAException e)
- {
- fail("cannot start the transaction with xid1: " + e.getMessage());
- }
- try
- {
- // start the connection
- _topicConnection.start();
- // produce a message with sequence number 1
- _message.setLongProperty(_sequenceNumberPropertyName, 1);
- _producer.send(_message);
- }
- catch (JMSException e)
- {
- fail(" cannot send persistent message: " + e.getMessage());
- }
- // suspend the transaction
- try
- {
- _xaResource.end(xid1, XAResource.TMSUCCESS);
- }
- catch (XAException e)
- {
- fail("Cannot end the transaction with xid1: " + e.getMessage());
- }
- // prepare the transaction with xid1
- try
- {
- _xaResource.prepare(xid1);
- }
- catch (XAException e)
- {
- fail("Exception when preparing xid1: " + e.getMessage());
- }
-
- /////// stop the server now !!
- try
- {
- restartBroker();
- init();
- }
- catch (Exception e)
- {
- fail("Exception when stopping and restarting the server");
- }
-
- try
- {
- MessageConsumer nonXAConsumer = _nonXASession.createDurableSubscriber(_topic, durSubName);
- _topicConnection.start();
- // get the list of in doubt transactions
- try
- {
- Xid[] inDoubt = _xaResource.recover(XAResource.TMSTARTRSCAN);
- if (inDoubt == null)
- {
- fail("the array of in doubt transactions should not be null ");
- }
- // At that point we expect only two indoubt transactions:
- if (inDoubt.length != 1)
- {
- fail("in doubt transaction size is diffenrent thatn 2, there are " + inDoubt.length + "in doubt transactions");
- }
- // commit them
- for (Xid anInDoubt : inDoubt)
- {
- if (anInDoubt.equals(xid1))
- {
- _logger.debug("committing xid1 ");
- try
- {
- _xaResource.commit(anInDoubt, false);
- }
- catch (Exception e)
- {
- _logger.debug("PB when aborted xid1");
- e.printStackTrace();
- fail("exception when committing xid1 ");
- }
- }
- else
- {
- _logger.debug("XID1 is not in doubt ");
- }
- }
- }
- catch (XAException e)
- {
- e.printStackTrace();
- fail("exception thrown when recovering transactions " + e.getMessage());
- }
- _logger.debug("the topic should not be empty");
- TextMessage message1 = (TextMessage) nonXAConsumer.receive(1000);
- if (message1 == null)
- {
- fail("The topic is empty! ");
- }
- }
- catch (Exception e)
- {
- e.printStackTrace();
- fail("Exception thrown when testin that queue test is empty: " + e.getMessage());
- }
- }
- catch (JMSException e)
- {
- e.printStackTrace();
- fail("cannot create dummy durable subscriber: " + e.getMessage());
- }
- finally
- {
- try
- {
- // unsubscribe the dummy durable subscriber
- TopicSession nonXASession = _nonXASession;
- nonXASession.unsubscribe(durSubName);
- }
- catch (JMSException e)
- {
- fail("cannot unsubscribe durable subscriber: " + e.getMessage());
- }
- }
- }
- }
-
- /**
- * strategy:
- * create a standard durable subscriber
- * produce 3 messages
- * consume the first message with that durable subscriber
- * close the standard session that deactivates the durable subscriber
- * migrate the durable subscriber to an xa one
- * consume the second message with that xa durable subscriber
- * close the xa session that deactivates the durable subscriber
- * reconnect to the durable subscriber with a standard session
- * consume the two remaining messages and check that the topic is empty!
- */
- public void testMigrateDurableSubscriber()
- {
- if (!isBroker08())
- {
- Xid xid1 = getNewXid();
- Xid xid2 = getNewXid();
- String durSubName = "DurableSubscriberMigrate";
- try
- {
- Session stSession = _nonXASession;
- MessageProducer producer = stSession.createProducer(_topic);
- _logger.debug("Create a standard durable subscriber!");
- TopicSubscriber durSub = stSession.createDurableSubscriber(_topic, durSubName);
- TopicSubscriber durSub1 = stSession.createDurableSubscriber(_topic, durSubName + "_second");
- TextMessage message;
- producer.setDeliveryMode(DeliveryMode.PERSISTENT);
- _topicConnection.start();
- _logger.debug("produce 3 messages");
- for (int i = 1; i <= 3; i++)
- {
- _message.setLongProperty(_sequenceNumberPropertyName, i);
- //producer.send( _message );
- producer.send(_message, DeliveryMode.PERSISTENT, 9 - i, 0);
- stSession.commit();
- }
- _logger.debug("consume the first message with that durable subscriber");
- message = (TextMessage) durSub.receive(1000);
- if (message == null)
- {
- fail("no message received ");
- }
- else if (message.getLongProperty(_sequenceNumberPropertyName) != 1)
- {
- fail("wrong sequence number: " + message.getLongProperty(_sequenceNumberPropertyName));
- }
- // commit the standard session
- stSession.commit();
- _logger.debug("first message consumed ");
- // close the session that deactivates the durable subscriber
- stSession.close();
- _logger.debug("migrate the durable subscriber to an xa one");
- _xaResource.start(xid1, XAResource.TMNOFLAGS);
- durSub = _session.createDurableSubscriber(_topic, durSubName);
- _logger.debug(" consume the second message with that xa durable subscriber and abort it");
- message = (TextMessage) durSub.receive(1000);
- if (message == null)
- {
- fail("no message received ");
- }
- else if (message.getLongProperty(_sequenceNumberPropertyName) != 2)
- {
- System.out.println("wrong sequence number, 2 expected, received: " + message
- .getLongProperty(_sequenceNumberPropertyName));
- }
- _xaResource.end(xid1, XAResource.TMSUCCESS);
- _xaResource.prepare(xid1);
- _xaResource.rollback(xid1);
- _logger.debug("close the session that deactivates the durable subscriber");
- _session.close();
- _logger.debug("create a new standard session");
- stSession = _topicConnection.createTopicSession(true, 1);
- _logger.debug("reconnect to the durable subscriber");
- durSub = stSession.createDurableSubscriber(_topic, durSubName);
- durSub1 = stSession.createDurableSubscriber(_topic, durSubName + "_second");
- _logger.debug("Reconnected to durablse subscribers");
- _logger.debug(" consume the 2 remaining messages");
- message = (TextMessage) durSub.receive(1000);
- if (message == null)
- {
- fail("no message received ");
- }
- else if (message.getLongProperty(_sequenceNumberPropertyName) != 2)
- {
- System.out.println("wrong sequence number, 2 expected, received: " + message
- .getLongProperty(_sequenceNumberPropertyName));
- }
- // consume the third message with that xa durable subscriber
- message = (TextMessage) durSub.receive(1000);
- if (message == null)
- {
- fail("no message received ");
- }
- else if (message.getLongProperty(_sequenceNumberPropertyName) != 3)
- {
- System.out.println("wrong sequence number, 3 expected, received: " + message
- .getLongProperty(_sequenceNumberPropertyName));
- }
- stSession.commit();
- _logger.debug("the topic should be empty now");
- message = (TextMessage) durSub.receive(1000);
- if (message != null)
- {
- fail("Received unexpected message ");
- }
- stSession.commit();
- _logger.debug(" use dursub1 to receive all the 3 messages");
- for (int i = 1; i <= 3; i++)
- {
- message = (TextMessage) durSub1.receive(1000);
- if (message == null)
- {
- _logger.debug("no message received ");
- }
- else if (message.getLongProperty(_sequenceNumberPropertyName) != i)
- {
- fail("wrong sequence number, " + i + " expected, received: " + message
- .getLongProperty(_sequenceNumberPropertyName));
- }
- }
- stSession.commit();
- // send a non persistent message to check that all persistent messages are deleted
- producer = stSession.createProducer(_topic);
- producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
- producer.send(_message);
- stSession.commit();
- message = (TextMessage) durSub.receive(1000);
- if (message == null)
- {
- fail("message not received ");
- }
- message = (TextMessage) durSub1.receive(1000);
- if (message == null)
- {
- fail("message not received ");
- }
- stSession.commit();
- stSession.close();
- _logger.debug(" now create a standard non transacted session and reconnect to the durable xubscriber");
- TopicConnection stConnection =
- _topicConnection; //_topicFactory.createTopicConnection("guest", "guest");
- TopicSession autoAclSession = stConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
- TopicPublisher publisher = autoAclSession.createPublisher(_topic);
- durSub = autoAclSession.createDurableSubscriber(_topic, durSubName);
- stConnection.start();
- // produce 3 persistent messages
- for (int i = 1; i <= 3; i++)
- {
- _message.setLongProperty(_sequenceNumberPropertyName, i);
- //producer.send( _message );
- publisher.send(_message, DeliveryMode.PERSISTENT, 9 - i, 0);
- }
- _logger.debug(" use dursub to receive all the 3 messages");
- for (int i = 1; i <= 3; i++)
- {
- message = (TextMessage) durSub.receive(1000);
- if (message == null)
- {
- System.out.println("no message received ");
- }
- else if (message.getLongProperty(_sequenceNumberPropertyName) != i)
- {
- System.out.println("wrong sequence number, " + i + " expected, received: " + message
- .getLongProperty(_sequenceNumberPropertyName));
- }
- }
-
- _logger.debug("now set a message listener");
- AtomicBoolean lock = new AtomicBoolean(true);
- reset();
- stConnection.stop();
- durSub.setMessageListener(new TopicListener(1, 3, lock));
- _logger.debug(" produce 3 persistent messages");
- for (int i = 1; i <= 3; i++)
- {
- _message.setLongProperty(_sequenceNumberPropertyName, i);
- //producer.send( _message );
- publisher.send(_message, DeliveryMode.PERSISTENT, 9 - i, 0);
- }
- // start the connection
- stConnection.start();
- while (lock.get())
- {
- synchronized (lock)
- {
- lock.wait();
- }
- }
- if (getFailureStatus())
- {
- fail("problem with message listener");
- }
- stConnection.stop();
- durSub.setMessageListener(null);
- _logger.debug(" do the same with an xa session");
- // produce 3 persistent messages
- for (int i = 1; i <= 3; i++)
- {
- _message.setLongProperty(_sequenceNumberPropertyName, i);
- //producer.send( _message );
- publisher.send(_message, DeliveryMode.PERSISTENT, 9 - i, 0);
- }
- //stConnection.close();
- autoAclSession.close();
- _logger.debug(" migrate the durable subscriber to an xa one");
- _session = _topicConnection.createXATopicSession();
- _xaResource = _session.getXAResource();
- _xaResource.start(xid2, XAResource.TMNOFLAGS);
- durSub = _session.createDurableSubscriber(_topic, durSubName);
- lock = new AtomicBoolean();
- reset();
- _topicConnection.stop();
- durSub.setMessageListener(new TopicListener(1, 3, lock));
- // start the connection
- _topicConnection.start();
- while (lock.get())
- {
- synchronized (lock)
- {
- lock.wait();
- }
- }
- if (getFailureStatus())
- {
- fail("problem with XA message listener");
- }
- _xaResource.end(xid2, XAResource.TMSUCCESS);
- _xaResource.commit(xid2, true);
- }
- catch (Exception e)
- {
- e.printStackTrace();
- fail("Exception thrown: " + e.getMessage());
- }
- finally
- {
- try
- {
- _topicConnection.createXASession().unsubscribe(durSubName);
- _topicConnection.createXASession().unsubscribe(durSubName + "_second");
- }
- catch (JMSException e)
- {
- fail("Exception thrown when unsubscribing durable subscriber " + e.getMessage());
- }
- }
- }
- }
-
- /** -------------------------------------------------------------------------------------- **/
- /** ----------------------------- Utility methods --------------------------------------- **/
- /** -------------------------------------------------------------------------------------- **/
-
- /**
- * get a new queue connection
- *
- * @return a new queue connection
- * @throws javax.jms.JMSException If the JMS provider fails to create the queue connection
- * due to some internal error or in case of authentication failure
- */
- private XATopicConnection getNewTopicXAConnection() throws JMSException
- {
- return _topicFactory.createXATopicConnection("guest", "guest");
- }
-
- public static void failure()
- {
- _failure = true;
- }
-
- public static void reset()
- {
- _failure = false;
- }
-
- public static boolean getFailureStatus()
- {
- return _failure;
- }
-
- private class TopicListener implements MessageListener
- {
- private long _counter;
- private long _end;
- private final AtomicBoolean _lock;
-
- public TopicListener(long init, long end, AtomicBoolean lock)
- {
- _counter = init;
- _end = end;
- _lock = lock;
- }
-
- public void onMessage(Message message)
- {
- long seq = 0;
- try
- {
- seq = message.getLongProperty(TopicTest._sequenceNumberPropertyName);
- }
- catch (JMSException e)
- {
- e.printStackTrace();
- TopicTest.failure();
- _lock.set(false);
- synchronized (_lock)
- {
- _lock.notifyAll();
- }
- }
- if (seq != _counter)
- {
- System.out.println("received message " + seq + " expected " + _counter);
- TopicTest.failure();
- _lock.set(false);
- synchronized (_lock)
- {
- _lock.notifyAll();
- }
- }
- _counter++;
- if (_counter > _end)
- {
- _lock.set(false);
- synchronized (_lock)
- {
- _lock.notifyAll();
- }
- }
- }
- }
-
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/utils/ConversationFactory.java b/java/systests/src/main/java/org/apache/qpid/test/utils/ConversationFactory.java
deleted file mode 100644
index e153b2e0f5..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/utils/ConversationFactory.java
+++ /dev/null
@@ -1,476 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.utils;
-
-import org.apache.log4j.Logger;
-import org.apache.qpid.test.utils.ReflectionUtils;
-
-import javax.jms.*;
-
-import java.util.*;
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.LinkedBlockingQueue;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicLong;
-
-/**
- * A conversation helper, uses a message correlation id pattern to match up sent and received messages as a conversation
- * over JMS messaging. Incoming message traffic is divided up by correlation id. Each id has a queue (behaviour dependant
- * on the queue implementation). Clients of this de-multiplexer can wait on messages, defined by message correlation ids.
- *
- * <p/>One use of this is as a conversation synchronizer where multiple threads are carrying out conversations over a
- * multiplexed messaging route. This can be usefull, as JMS sessions are not multi-threaded. Setting up the conversation
- * with synchronous queues will allow these threads to be written in a synchronous style, but with their execution order
- * governed by the asynchronous message flow. For example, something like the following code could run a multi-threaded
- * conversation (the conversation methods can be called many times in parallel):
- *
- * <p/><pre>
- * class Initiator
- * {
- * ConversationHelper conversation = new ConversationHelper(connection, null,
- * java.util.concurrent.LinkedBlockingQueue.class);
- *
- * initiateConversation()
- * {
- * try {
- * // Exchange greetings.
- * conversation.send(sendDestination, conversation.getSession().createTextMessage("Hello."));
- * Message greeting = conversation.receive();
- *
- * // Exchange goodbyes.
- * conversation.send(conversation.getSession().createTextMessage("Goodbye."));
- * Message goodbye = conversation.receive();
- * } finally {
- * conversation.end();
- * }
- * }
- * }
- *
- * class Responder
- * {
- * ConversationHelper conversation = new ConversationHelper(connection, receiveDestination,
- * java.util.concurrent.LinkedBlockingQueue.class);
- *
- * respondToConversation()
- * {
- * try {
- * // Exchange greetings.
- * Message greeting = conversation.receive();
- * conversation.send(conversation.getSession().createTextMessage("Hello."));
- *
- * // Exchange goodbyes.
- * Message goodbye = conversation.receive();
- * conversation.send(conversation.getSession().createTextMessage("Goodbye."));
- * } finally {
- * conversation.end();
- * }
- * }
- * }
- * </pre>
- *
- * <p/>Conversation correlation id's are generated on a per thread basis.
- *
- * <p/>The same controlSession is shared amongst all conversations. Calls to send are therefore synchronized because JMS
- * sessions are not multi-threaded.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Associate messages to an ongoing conversation using correlation ids.
- * <tr><td> Auto manage sessions for conversations.
- * <tr><td> Store messages not in a conversation in dead letter box.
- * </table>
- */
-public class ConversationFactory
-{
- /** Used for debugging. */
- private static final Logger log = Logger.getLogger(ConversationFactory.class);
-
- /** Holds a map from correlation id's to queues. */
- private Map<Long, BlockingQueue<Message>> idsToQueues = new HashMap<Long, BlockingQueue<Message>>();
-
- /** Holds the connection over which the conversation is conducted. */
- private Connection connection;
-
- /** Holds the controlSession over which the conversation is conduxted. */
- private Session session;
-
- /** The message consumer for incoming messages. */
- MessageConsumer consumer;
-
- /** The message producer for outgoing messages. */
- MessageProducer producer;
-
- /** The well-known or temporary destination to receive replies on. */
- Destination receiveDestination;
-
- /** Holds the queue implementation class for the reply queue. */
- Class<? extends BlockingQueue> queueClass;
-
- /** Used to hold any replies that are received outside of the context of a conversation. */
- BlockingQueue<Message> deadLetterBox = new LinkedBlockingQueue<Message>();
-
- /* Used to hold conversation state on a per thread basis. */
- /*
- ThreadLocal<Conversation> threadLocals =
- new ThreadLocal<Conversation>()
- {
- protected Conversation initialValue()
- {
- Conversation settings = new Conversation();
- settings.conversationId = conversationIdGenerator.getAndIncrement();
-
- return settings;
- }
- };
- */
-
- /** Generates new coversation id's as needed. */
- AtomicLong conversationIdGenerator = new AtomicLong();
-
- /**
- * Creates a conversation helper on the specified connection with the default sending destination, and listening
- * to the specified receiving destination.
- *
- * @param connection The connection to build the conversation helper on.
- * @param receiveDestination The destination to listen to for incoming messages. This may be null to use a temporary
- * queue.
- * @param queueClass The queue implementation class.
- *
- * @throws JMSException All underlying JMSExceptions are allowed to fall through.
- */
- public ConversationFactory(Connection connection, Destination receiveDestination,
- Class<? extends BlockingQueue> queueClass) throws JMSException
- {
- log.debug("public ConversationFactory(Connection connection, Destination receiveDestination = " + receiveDestination
- + ", Class<? extends BlockingQueue> queueClass = " + queueClass + "): called");
-
- this.connection = connection;
- this.queueClass = queueClass;
-
- session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- // Check if a well-known receive destination has been provided, or use a temporary queue if not.
- this.receiveDestination = (receiveDestination != null) ? receiveDestination : session.createTemporaryQueue();
-
- consumer = session.createConsumer(receiveDestination);
- producer = session.createProducer(null);
-
- consumer.setMessageListener(new Receiver());
- }
-
- /**
- * Creates a new conversation context.
- *
- * @return A new conversation context.
- */
- public Conversation startConversation()
- {
- log.debug("public Conversation startConversation(): called");
-
- Conversation conversation = new Conversation();
- conversation.conversationId = conversationIdGenerator.getAndIncrement();
-
- return conversation;
- }
-
- /**
- * Ensures that the reply queue for a conversation exists.
- *
- * @param conversationId The conversation correlation id.
- */
- private void initQueueForId(long conversationId)
- {
- if (!idsToQueues.containsKey(conversationId))
- {
- idsToQueues.put(conversationId, ReflectionUtils.<BlockingQueue>newInstance(queueClass));
- }
- }
-
- /**
- * Clears the dead letter box, returning all messages that were in it.
- *
- * @return All messages in the dead letter box.
- */
- public Collection<Message> emptyDeadLetterBox()
- {
- log.debug("public Collection<Message> emptyDeadLetterBox(): called");
-
- Collection<Message> result = new ArrayList<Message>();
- deadLetterBox.drainTo(result);
-
- return result;
- }
-
- /**
- * Gets the controlSession over which the conversation is conducted.
- *
- * @return The controlSession over which the conversation is conducted.
- */
- public Session getSession()
- {
- // Conversation settings = threadLocals.get();
-
- return session;
- }
-
- /**
- * Used to hold a conversation context. This consists of a correlating id for the conversation, and a reply
- * destination automatically updated to the last received reply-to destination.
- */
- public class Conversation
- {
- /** Holds the correlation id for the context. */
- long conversationId;
-
- /**
- * Holds the send destination for the context. This will automatically be updated to the most recently received
- * reply-to destination.
- */
- Destination sendDestination;
-
- /**
- * Sends a message to the default sending location. The correlation id of the message will be assigned by this
- * method, overriding any previously set value.
- *
- * @param sendDestination The destination to send to. This may be null to use the last received reply-to
- * destination.
- * @param message The message to send.
- *
- * @throws JMSException All undelying JMSExceptions are allowed to fall through. This will also be thrown if no
- * send destination is specified and there is no most recent reply-to destination available
- * to use.
- */
- public void send(Destination sendDestination, Message message) throws JMSException
- {
- log.debug("public void send(Destination sendDestination = " + sendDestination + ", Message message = "
- + message.getJMSMessageID() + "): called");
-
- // Conversation settings = threadLocals.get();
- // long conversationId = conversationId;
- message.setJMSCorrelationID(Long.toString(conversationId));
- message.setJMSReplyTo(receiveDestination);
-
- // Ensure that the reply queue for this conversation exists.
- initQueueForId(conversationId);
-
- // Check if an overriding send to destination has been set or use the last reply-to if not.
- Destination sendTo = null;
-
- if (sendDestination != null)
- {
- sendTo = sendDestination;
- }
- else
- {
- throw new JMSException("The send destination was specified, and no most recent reply-to available to use.");
- }
-
- // Send the message.
- synchronized (this)
- {
- producer.send(sendTo, message);
- }
- }
-
- /**
- * Gets the next message in an ongoing conversation. This method may block until such a message is received.
- *
- * @return The next incoming message in the conversation.
- *
- * @throws JMSException All undelying JMSExceptions are allowed to fall through. Thrown if the received message
- * did not have its reply-to destination set up.
- */
- public Message receive() throws JMSException
- {
- log.debug("public Message receive(): called");
-
- // Conversation settings = threadLocals.get();
- // long conversationId = settings.conversationId;
-
- // Ensure that the reply queue for this conversation exists.
- initQueueForId(conversationId);
-
- BlockingQueue<Message> queue = idsToQueues.get(conversationId);
-
- try
- {
- Message result = queue.take();
-
- // Keep the reply-to destination to send replies to.
- sendDestination = result.getJMSReplyTo();
-
- return result;
- }
- catch (InterruptedException e)
- {
- return null;
- }
- }
-
- /**
- * Gets many messages in an ongoing conversation. If a limit is specified, then once that many messages are
- * received they will be returned. If a timeout is specified, then all messages up to the limit, received within
- * that timespan will be returned. At least one of the message count or timeout should be set to a value of
- * 1 or greater.
- *
- * @param num The number of messages to receive, or all if this is less than 1.
- * @param timeout The timeout in milliseconds to receive the messages in, or forever if this is less than 1.
- *
- * @return All messages received within the count limit and the timeout.
- *
- * @throws JMSException All undelying JMSExceptions are allowed to fall through.
- */
- public Collection<Message> receiveAll(int num, long timeout) throws JMSException
- {
- log.debug("public Collection<Message> receiveAll(int num = " + num + ", long timeout = " + timeout
- + "): called");
-
- // Check that a timeout or message count was set.
- if ((num < 1) && (timeout < 1))
- {
- throw new IllegalArgumentException("At least one of message count (num) or timeout must be set.");
- }
-
- // Ensure that the reply queue for this conversation exists.
- initQueueForId(conversationId);
- BlockingQueue<Message> queue = idsToQueues.get(conversationId);
-
- // Used to collect the received messages in.
- Collection<Message> result = new ArrayList<Message>();
-
- // Used to indicate when the timeout or message count has expired.
- boolean receiveMore = true;
-
- int messageCount = 0;
-
- // Receive messages until the timeout or message count expires.
- do
- {
- try
- {
- Message next = null;
-
- // Try to receive the message with a timeout if one has been set.
- if (timeout > 0)
- {
- next = queue.poll(timeout, TimeUnit.MILLISECONDS);
-
- // Check if the timeout expired, and stop receiving if so.
- if (next == null)
- {
- receiveMore = false;
- }
- }
- // Receive the message without a timeout.
- else
- {
- next = queue.take();
- }
-
- // Increment the message count if a message was received.
- messageCount += (next != null) ? 1 : 0;
-
- // Check if all the requested messages were received, and stop receiving if so.
- if ((num > 0) && (messageCount >= num))
- {
- receiveMore = false;
- }
-
- // Keep the reply-to destination to send replies to.
- sendDestination = (next != null) ? next.getJMSReplyTo() : sendDestination;
-
- if (next != null)
- {
- result.add(next);
- }
- }
- catch (InterruptedException e)
- {
- // Restore the threads interrupted status.
- Thread.currentThread().interrupt();
-
- // Stop receiving but return the messages received so far.
- receiveMore = false;
- }
- }
- while (receiveMore);
-
- return result;
- }
-
- /**
- * Completes the conversation. Any correlation id's pertaining to the conversation are no longer valid, and any
- * incoming messages using them will go to the dead letter box.
- */
- public void end()
- {
- log.debug("public void end(): called");
-
- // Ensure that the thread local for the current thread is cleaned up.
- // Conversation settings = threadLocals.get();
- // long conversationId = settings.conversationId;
- // threadLocals.remove();
-
- // Ensure that its queue is removed from the queue map.
- BlockingQueue<Message> queue = idsToQueues.remove(conversationId);
-
- // Move any outstanding messages on the threads conversation id into the dead letter box.
- queue.drainTo(deadLetterBox);
- }
- }
-
- /**
- * Implements the message listener for this conversation handler.
- */
- protected class Receiver implements MessageListener
- {
- /**
- * Handles all incoming messages in the ongoing conversations. These messages are split up by correaltion id
- * and placed into queues.
- *
- * @param message The incoming message.
- */
- public void onMessage(Message message)
- {
- log.debug("public void onMessage(Message message = " + message + "): called");
-
- try
- {
- Long conversationId = Long.parseLong(message.getJMSCorrelationID());
-
- // Find the converstaion queue to place the message on. If there is no conversation for the message id,
- // the the dead letter box queue is used.
- BlockingQueue<Message> queue = idsToQueues.get(conversationId);
- queue = (queue == null) ? deadLetterBox : queue;
-
- queue.put(message);
- }
- catch (JMSException e)
- {
- throw new RuntimeException(e);
- }
- catch (InterruptedException e)
- {
- throw new RuntimeException(e);
- }
- }
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/utils/FailoverBaseCase.java b/java/systests/src/main/java/org/apache/qpid/test/utils/FailoverBaseCase.java
deleted file mode 100644
index d3b429e315..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/utils/FailoverBaseCase.java
+++ /dev/null
@@ -1,115 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.utils;
-
-import org.apache.qpid.util.FileUtils;
-
-import javax.naming.NamingException;
-import javax.jms.JMSException;
-import javax.naming.NamingException;
-
-import org.apache.qpid.client.AMQConnectionFactory;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class FailoverBaseCase extends QpidBrokerTestCase
-{
- protected static final Logger _logger = LoggerFactory.getLogger(FailoverBaseCase.class);
-
- public static int FAILING_VM_PORT = 2;
- public static int FAILING_PORT = Integer.parseInt(System.getProperty("test.port.alt"));
- public static final long DEFAULT_FAILOVER_TIME = 10000L;
-
- protected int failingPort;
-
- protected int getFailingPort()
- {
- if (_broker.equals(VM))
- {
- return FAILING_VM_PORT;
- }
- else
- {
- return FAILING_PORT;
- }
- }
-
- protected void setUp() throws java.lang.Exception
- {
- super.setUp();
- startBroker(getFailingPort());
- }
-
- /**
- * We are using failover factories
- *
- * @return a connection
- * @throws Exception
- */
- @Override
- public AMQConnectionFactory getConnectionFactory() throws NamingException
- {
- _logger.info("get ConnectionFactory");
- if (_connectionFactory == null)
- {
- if (Boolean.getBoolean("profile.use_ssl"))
- {
- _connectionFactory = getConnectionFactory("failover.ssl");
- }
- else
- {
- _connectionFactory = getConnectionFactory("failover");
- }
- }
- return _connectionFactory;
- }
-
-
- public void tearDown() throws Exception
- {
- try
- {
- super.tearDown();
- }
- finally
- {
- // Ensure we shutdown any secondary brokers, even if we are unable
- // to cleanly tearDown the QTC.
- stopBroker(getFailingPort());
- FileUtils.deleteDirectory(System.getProperty("QPID_WORK") + "/" + getFailingPort());
- }
- }
-
-
- public void failBroker(int port)
- {
- try
- {
- stopBroker(port);
- }
- catch (Exception e)
- {
- throw new RuntimeException(e);
- }
- }
-
-
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/utils/JMXTestUtils.java b/java/systests/src/main/java/org/apache/qpid/test/utils/JMXTestUtils.java
deleted file mode 100644
index 1fde6c7c73..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/utils/JMXTestUtils.java
+++ /dev/null
@@ -1,435 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.utils;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Set;
-
-import javax.management.JMException;
-import javax.management.MBeanException;
-import javax.management.MBeanServerConnection;
-import javax.management.MBeanServerInvocationHandler;
-import javax.management.ObjectName;
-import javax.management.MalformedObjectNameException;
-import javax.management.remote.JMXConnector;
-
-import junit.framework.TestCase;
-
-import org.apache.commons.configuration.ConfigurationException;
-import org.apache.qpid.management.common.JMXConnnectionFactory;
-import org.apache.qpid.management.common.mbeans.ManagedBroker;
-import org.apache.qpid.management.common.mbeans.ManagedConnection;
-import org.apache.qpid.management.common.mbeans.ManagedExchange;
-import org.apache.qpid.management.common.mbeans.LoggingManagement;
-import org.apache.qpid.management.common.mbeans.ConfigurationManagement;
-import org.apache.qpid.management.common.mbeans.ManagedQueue;
-import org.apache.qpid.management.common.mbeans.ServerInformation;
-import org.apache.qpid.management.common.mbeans.UserManagement;
-
-/**
- * JMX access for tests.
- */
-public class JMXTestUtils
-{
- QpidBrokerTestCase _test;
- MBeanServerConnection _mbsc;
- JMXConnector _jmxc;
-
- private String USER;
- private String PASSWORD;
-
- public JMXTestUtils(QpidBrokerTestCase test, String user, String password)
- {
- _test = test;
- USER = user;
- PASSWORD = password;
- }
-
- public void setUp() throws IOException, ConfigurationException, Exception
- {
- _test.setConfigurationProperty("management.enabled", "true");
- }
-
- public void open() throws Exception
- {
- _jmxc = JMXConnnectionFactory.getJMXConnection(5000, "127.0.0.1",
- _test.getManagementPort(_test.getPort()), USER, PASSWORD);
-
- _mbsc = _jmxc.getMBeanServerConnection();
- }
-
- public void close() throws IOException
- {
- if(_jmxc != null)
- {
- _jmxc.close();
- }
- }
-
- /**
- * Create a non-durable exchange with the requested name
- *
- * @throws JMException if a exchange with this name already exists
- * @throws IOException if there is a problem with the JMX Connection
- * @throws MBeanException if there is another problem creating the exchange
- */
- public void createExchange(String virtualHostName, String name, String type, boolean durable)
- throws JMException, IOException, MBeanException
- {
- ManagedBroker managedBroker = getManagedBroker(virtualHostName);
-
- managedBroker.createNewExchange(name, type, durable);
- }
-
- /**
- * Create a non-durable queue (with no owner) that is named after the
- * creating test.
- *
- * @throws JMException if a queue with this name already exists
- * @throws IOException if there is a problem with the JMX Connection
- * @throws MBeanException if there is another problem creating the exchange
- */
- public void createQueue(String virtualHostName, String name, String owner, boolean durable)
- throws JMException, MBeanException, IOException
- {
- ManagedBroker managedBroker = getManagedBroker(virtualHostName);
-
- managedBroker.createNewQueue(name, owner, durable);
- }
-
- /**
- * Unregisters all the channels, queuebindings etc and unregisters
- * this exchange from managed objects.
- *
- * @throws JMException if an exchange with this name does not exist
- * @throws IOException if there is a problem with the JMX Connection
- * @throws MBeanException if there is another problem creating the exchange
- */
- public void unregisterExchange(String virtualHostName, String exchange)
- throws IOException, JMException, MBeanException
- {
- ManagedBroker managedBroker = getManagedBroker(virtualHostName);
-
- managedBroker.unregisterExchange(exchange);
- }
-
- /**
- * Unregisters the Queue bindings, removes the subscriptions and unregisters
- * from the managed objects.
- *
- * @throws JMException if a queue with this name does not exist
- * @throws IOException if there is a problem with the JMX Connection
- * @throws MBeanException if there is another problem creating the exchange
- */
- public void deleteQueue(String virtualHostName, String queueName)
- throws IOException, JMException, MBeanException
- {
- ManagedBroker managedBroker = getManagedBroker(virtualHostName);
-
- managedBroker.deleteQueue(queueName);
- }
-
- /**
- * Sets the logging level.
- *
- * @throws JMException
- * @throws IOException if there is a problem with the JMX Connection
- * @throws MBeanException
- */
- public void setRuntimeLoggerLevel(String logger, String level)
- throws IOException, JMException, MBeanException
- {
- LoggingManagement loggingManagement = getLoggingManagement();
-
- loggingManagement.setRuntimeLoggerLevel(logger, level);
- }
-
- /**
- * Reload logging config file.
- *
- * @throws JMException
- * @throws IOException if there is a problem with the JMX Connection
- * @throws MBeanException
- */
- public void reloadConfigFile()
- throws IOException, JMException, MBeanException
- {
- LoggingManagement loggingManagement = getLoggingManagement();
-
- loggingManagement.reloadConfigFile();
- }
-
- /**
- * Get list of available logger levels.
- *
- * @throws JMException
- * @throws IOException if there is a problem with the JMX Connection
- * @throws MBeanException
- */
- public String[] getAvailableLoggerLevels()
- throws IOException, JMException, MBeanException
- {
- LoggingManagement loggingManagement = getLoggingManagement();
-
- return loggingManagement.getAvailableLoggerLevels();
- }
-
- /**
- * Set root logger level.
- *
- * @throws JMException
- * @throws IOException if there is a problem with the JMX Connection
- * @throws MBeanException
- */
- public void setRuntimeRootLoggerLevel(String level)
- throws IOException, JMException, MBeanException
- {
- LoggingManagement loggingManagement = getLoggingManagement();
-
- loggingManagement.setRuntimeRootLoggerLevel(level);
- }
-
- /**
- * Get root logger level.
- *
- * @throws JMException
- * @throws IOException if there is a problem with the JMX Connection
- * @throws MBeanException
- */
- public String getRuntimeRootLoggerLevel()
- throws IOException, JMException, MBeanException
- {
- LoggingManagement loggingManagement = getLoggingManagement();
-
- return loggingManagement.getRuntimeRootLoggerLevel();
- }
-
- /**
- * Retrive the ObjectName for a Virtualhost.
- *
- * This is then used to create a proxy to the ManagedBroker MBean.
- *
- * @param virtualHostName the VirtualHost to retrieve
- * @return the ObjectName for the VirtualHost
- */
- @SuppressWarnings("static-access")
- public ObjectName getVirtualHostManagerObjectName(String vhostName)
- {
- // Get the name of the test manager
- String query = "org.apache.qpid:type=VirtualHost.VirtualHostManager,VirtualHost="
- + ObjectName.quote(vhostName) + ",*";
-
- Set<ObjectName> objectNames = queryObjects(query);
-
- _test.assertNotNull("Null ObjectName Set returned", objectNames);
- _test.assertEquals("Incorrect number test vhosts returned", 1, objectNames.size());
-
- // We have verified we have only one value in objectNames so return it
- ObjectName objectName = objectNames.iterator().next();
- _test.getLogger().info("Loading: " + objectName);
- return objectName;
- }
-
- /**
- * Retrive the ObjectName for the given Queue on a Virtualhost.
- *
- * This is then used to create a proxy to the ManagedQueue MBean.
- *
- * @param virtualHostName the VirtualHost the Queue is on
- * @param queue The Queue to retireve
- * @return the ObjectName for the given queue on the VirtualHost
- */
- @SuppressWarnings("static-access")
- public ObjectName getQueueObjectName(String virtualHostName, String queue)
- {
- // Get the name of the test manager
- String query = "org.apache.qpid:type=VirtualHost.Queue,VirtualHost="
- + ObjectName.quote(virtualHostName) + ",name="
- + ObjectName.quote(queue) + ",*";
-
- Set<ObjectName> objectNames = queryObjects(query);
-
- _test.assertNotNull("Null ObjectName Set returned", objectNames);
- _test.assertEquals("Incorrect number of queues with name '" + queue + "' returned", 1, objectNames.size());
-
- // We have verified we have only one value in objectNames so return it
- ObjectName objectName = objectNames.iterator().next();
- _test.getLogger().info("Loading: " + objectName);
- return objectName;
- }
-
- /**
- * Retrive the ObjectName for the given Exchange on a VirtualHost.
- *
- * This is then used to create a proxy to the ManagedExchange MBean.
- *
- * @param virtualHostName the VirtualHost the Exchange is on
- * @param exchange the Exchange to retireve e.g. 'direct'
- * @return the ObjectName for the given Exchange on the VirtualHost
- */
- @SuppressWarnings("static-access")
- public ObjectName getExchangeObjectName(String virtualHostName, String exchange)
- {
- // Get the name of the test manager
- String query = "org.apache.qpid:type=VirtualHost.Exchange,VirtualHost="
- + ObjectName.quote(virtualHostName) + ",name="
- + ObjectName.quote(exchange) + ",*";
-
- Set<ObjectName> objectNames = queryObjects(query);
-
- _test.assertNotNull("Null ObjectName Set returned", objectNames);
- _test.assertEquals("Incorrect number of exchange with name '" + exchange + "' returned", 1, objectNames.size());
-
- // We have verified we have only one value in objectNames so return it
- ObjectName objectName = objectNames.iterator().next();
- _test.getLogger().info("Loading: " + objectName);
- return objectName;
- }
-
- @SuppressWarnings("static-access")
- public <T> T getManagedObject(Class<T> managedClass, String query)
- {
- Set<ObjectName> objectNames = queryObjects(query);
-
- _test.assertNotNull("Null ObjectName Set returned", objectNames);
- _test.assertEquals("More than one " + managedClass + " returned", 1, objectNames.size());
-
- ObjectName objectName = objectNames.iterator().next();
- _test.getLogger().info("Loading: " + objectName);
- return getManagedObject(managedClass, objectName);
- }
-
- public <T> T getManagedObject(Class<T> managedClass, ObjectName objectName)
- {
- return MBeanServerInvocationHandler.newProxyInstance(_mbsc, objectName, managedClass, false);
- }
-
- public <T> List<T> getManagedObjectList(Class<T> managedClass, Set<ObjectName> objectNames)
- {
- List<T> objects = new ArrayList<T>();
- for (ObjectName name : objectNames)
- {
- objects.add(getManagedObject(managedClass, name));
- }
- return objects;
- }
-
- public ManagedBroker getManagedBroker(String virtualHost)
- {
- return getManagedObject(ManagedBroker.class, getVirtualHostManagerObjectName(virtualHost));
- }
-
- public ManagedExchange getManagedExchange(String exchangeName)
- {
- ObjectName objectName = getExchangeObjectName("test", exchangeName);
- return MBeanServerInvocationHandler.newProxyInstance(_mbsc, objectName, ManagedExchange.class, false);
- }
-
- public ManagedQueue getManagedQueue(String queueName)
- {
- ObjectName objectName = getQueueObjectName("test", queueName);
- return getManagedObject(ManagedQueue.class, objectName);
- }
-
- public LoggingManagement getLoggingManagement() throws MalformedObjectNameException
- {
- ObjectName objectName = new ObjectName("org.apache.qpid:type=LoggingManagement,name=LoggingManagement");
- return getManagedObject(LoggingManagement.class, objectName);
- }
-
- public ConfigurationManagement getConfigurationManagement() throws MalformedObjectNameException
- {
- ObjectName objectName = new ObjectName("org.apache.qpid:type=ConfigurationManagement,name=ConfigurationManagement");
- return getManagedObject(ConfigurationManagement.class, objectName);
- }
-
- public UserManagement getUserManagement() throws MalformedObjectNameException
- {
- ObjectName objectName = new ObjectName("org.apache.qpid:type=UserManagement,name=UserManagement");
- return getManagedObject(UserManagement.class, objectName);
- }
-
- /**
- * Retrive {@link ServerInformation} JMX MBean.
- */
- public ServerInformation getServerInformation()
- {
- // Get the name of the test manager
- String query = "org.apache.qpid:type=ServerInformation,name=ServerInformation,*";
-
- Set<ObjectName> objectNames = queryObjects(query);
-
- TestCase.assertNotNull("Null ObjectName Set returned", objectNames);
- TestCase.assertEquals("Incorrect number of objects returned", 1, objectNames.size());
-
- // We have verified we have only one value in objectNames so return it
- return getManagedObject(ServerInformation.class, objectNames.iterator().next());
- }
-
- /**
- * Retrive all {@link ManagedConnection} objects.
- */
- public List<ManagedConnection> getAllManagedConnections()
- {
- // Get the name of the test manager
- String query = "org.apache.qpid:type=VirtualHost.Connection,VirtualHost=*,name=*";
-
- Set<ObjectName> objectNames = queryObjects(query);
-
- TestCase.assertNotNull("Null ObjectName Set returned", objectNames);
-
- return getManagedObjectList(ManagedConnection.class, objectNames);
- }
-
- /**
- * Retrive all {@link ManagedConnection} objects for a particular virtual host.
- */
- public List<ManagedConnection> getManagedConnections(String vhost)
- {
- // Get the name of the test manager
- String query = "org.apache.qpid:type=VirtualHost.Connection,VirtualHost=" + ObjectName.quote(vhost) + ",name=*";
-
- Set<ObjectName> objectNames = queryObjects(query);
-
- TestCase.assertNotNull("Null ObjectName Set returned", objectNames);
-
- return getManagedObjectList(ManagedConnection.class, objectNames);
- }
-
- /**
- * Returns the Set of ObjectNames returned by the broker for the given query,
- * or null if there is problem while performing the query.
- */
- private Set<ObjectName> queryObjects(String query)
- {
- try
- {
- return _mbsc.queryNames(new ObjectName(query), null);
- }
- catch (Exception e)
- {
- e.printStackTrace();
- return null;
- }
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/utils/QpidBrokerTestCase.java b/java/systests/src/main/java/org/apache/qpid/test/utils/QpidBrokerTestCase.java
deleted file mode 100644
index 6fcde7e185..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/utils/QpidBrokerTestCase.java
+++ /dev/null
@@ -1,1363 +0,0 @@
-/* Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.qpid.test.utils;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.LineNumberReader;
-import java.io.PrintStream;
-import java.net.MalformedURLException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-import javax.jms.BytesMessage;
-import javax.jms.Connection;
-import javax.jms.Destination;
-import javax.jms.JMSException;
-import javax.jms.MapMessage;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-import javax.jms.ObjectMessage;
-import javax.jms.Queue;
-import javax.jms.Session;
-import javax.jms.StreamMessage;
-import javax.jms.TextMessage;
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-
-import org.apache.commons.configuration.ConfigurationException;
-import org.apache.commons.configuration.XMLConfiguration;
-import org.apache.commons.lang.StringUtils;
-import org.apache.log4j.Level;
-import org.apache.log4j.Logger;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQConnectionFactory;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.client.transport.TransportConnection;
-import org.apache.qpid.exchange.ExchangeDefaults;
-import org.apache.qpid.jms.BrokerDetails;
-import org.apache.qpid.jms.ConnectionURL;
-import org.apache.qpid.management.common.mbeans.ConfigurationManagement;
-import org.apache.qpid.server.configuration.ServerConfiguration;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-import org.apache.qpid.server.registry.ConfigurationFileApplicationRegistry;
-import org.apache.qpid.server.store.DerbyMessageStore;
-import org.apache.qpid.url.URLSyntaxException;
-import org.apache.qpid.util.FileUtils;
-import org.apache.qpid.util.LogMonitor;
-
-/**
- * Qpid base class for system testing test cases.
- */
-public class QpidBrokerTestCase extends QpidTestCase
-{
- protected final String QpidHome = System.getProperty("QPID_HOME");
- protected File _configFile = new File(System.getProperty("broker.config"));
-
- protected static final Logger _logger = Logger.getLogger(QpidBrokerTestCase.class);
- protected static final int LOGMONITOR_TIMEOUT = 5000;
-
- protected long RECEIVE_TIMEOUT = 1000l;
-
- private Map<String, String> _propertiesSetForTestOnly = new HashMap<String, String>();
- private Map<String, String> _propertiesSetForBroker = new HashMap<String, String>();
- private Map<Logger, Level> _loggerLevelSetForTest = new HashMap<Logger, Level>();
-
- private XMLConfiguration _testConfiguration = new XMLConfiguration();
- private XMLConfiguration _testVirtualhosts = new XMLConfiguration();
-
- protected static final String INDEX = "index";
- protected static final String CONTENT = "content";
-
- private static final String DEFAULT_INITIAL_CONTEXT = "org.apache.qpid.jndi.PropertiesFileInitialContextFactory";
-
- static
- {
- String initialContext = System.getProperty(InitialContext.INITIAL_CONTEXT_FACTORY);
-
- if (initialContext == null || initialContext.length() == 0)
- {
- System.setProperty(InitialContext.INITIAL_CONTEXT_FACTORY, DEFAULT_INITIAL_CONTEXT);
- }
- }
-
- // system properties
- private static final String BROKER_LANGUAGE = "broker.language";
- private static final String BROKER = "broker";
- private static final String BROKER_CLEAN = "broker.clean";
- private static final String BROKER_CLEAN_BETWEEN_TESTS = "broker.clean.between.tests";
- private static final String BROKER_EXISTING_QPID_WORK = "broker.existing.qpid.work";
- private static final String BROKER_VERSION = "broker.version";
- protected static final String BROKER_READY = "broker.ready";
- private static final String BROKER_STOPPED = "broker.stopped";
- private static final String TEST_OUTPUT = "test.output";
- private static final String BROKER_LOG_INTERLEAVE = "broker.log.interleave";
- private static final String BROKER_LOG_PREFIX = "broker.log.prefix";
- private static final String BROKER_PERSITENT = "broker.persistent";
-
- // values
- protected static final String JAVA = "java";
- protected static final String CPP = "cpp";
- protected static final String VM = "vm";
- protected static final String EXTERNAL = "external";
- private static final String VERSION_08 = "0-8";
- private static final String VERSION_010 = "0-10";
-
- protected static final String QPID_HOME = "QPID_HOME";
-
- public static final int DEFAULT_VM_PORT = 1;
- public static final int DEFAULT_PORT = Integer.getInteger("test.port", ServerConfiguration.DEFAULT_PORT);
- public static final int DEFAULT_MANAGEMENT_PORT = Integer.getInteger("test.mport", ServerConfiguration.DEFAULT_JMXPORT);
- public static final int DEFAULT_SSL_PORT = Integer.getInteger("test.sslport", ServerConfiguration.DEFAULT_SSL_PORT);
-
- protected String _brokerLanguage = System.getProperty(BROKER_LANGUAGE, JAVA);
- protected String _broker = System.getProperty(BROKER, VM);
- private String _brokerClean = System.getProperty(BROKER_CLEAN, null);
- private Boolean _brokerCleanBetweenTests = Boolean.getBoolean(BROKER_CLEAN_BETWEEN_TESTS);
- private String _brokerVersion = System.getProperty(BROKER_VERSION, VERSION_08);
- protected String _output = System.getProperty(TEST_OUTPUT);
- protected Boolean _brokerPersistent = Boolean.getBoolean(BROKER_PERSITENT);
-
- protected static String _brokerLogPrefix = System.getProperty(BROKER_LOG_PREFIX,"BROKER: ");
- protected static boolean _interleaveBrokerLog = Boolean.getBoolean(BROKER_LOG_INTERLEAVE);
-
- protected File _outputFile;
-
- protected PrintStream _brokerOutputStream;
-
- protected Map<Integer, Process> _brokers = new HashMap<Integer, Process>();
-
- protected InitialContext _initialContext;
- protected AMQConnectionFactory _connectionFactory;
-
- protected String _testName;
-
- // the connections created for a given test
- protected List<Connection> _connections = new ArrayList<Connection>();
- public static final String QUEUE = "queue";
- public static final String TOPIC = "topic";
-
- /** Map to hold test defined environment properties */
- private Map<String, String> _env;
-
- /** Ensure our messages have some sort of size */
- protected static final int DEFAULT_MESSAGE_SIZE = 1024;
-
- /** Size to create our message*/
- private int _messageSize = DEFAULT_MESSAGE_SIZE;
- /** Type of message*/
- protected enum MessageType
- {
- BYTES,
- MAP,
- OBJECT,
- STREAM,
- TEXT
- }
- private MessageType _messageType = MessageType.TEXT;
-
- public QpidBrokerTestCase(String name)
- {
- super(name);
- }
-
- public QpidBrokerTestCase()
- {
- super();
- }
-
- public Logger getLogger()
- {
- return QpidBrokerTestCase._logger;
- }
-
- public void runBare() throws Throwable
- {
- _testName = getClass().getSimpleName() + "." + getName();
- String qname = getClass().getName() + "." + getName();
-
- // Initialize this for each test run
- _env = new HashMap<String, String>();
-
- PrintStream oldOut = System.out;
- PrintStream oldErr = System.err;
- PrintStream out = null;
- PrintStream err = null;
-
- boolean redirected = _output != null && _output.length() > 0;
- if (redirected)
- {
- _outputFile = new File(String.format("%s/TEST-%s.out", _output, qname));
- out = new PrintStream(_outputFile);
- err = new PrintStream(String.format("%s/TEST-%s.err", _output, qname));
- System.setOut(out);
- System.setErr(err);
-
- if (_interleaveBrokerLog)
- {
- _brokerOutputStream = out;
- }
- else
- {
- _brokerOutputStream = new PrintStream(new FileOutputStream(String
- .format("%s/TEST-%s.broker.out", _output, qname)), true);
- }
- }
-
- _logger.info("========== start " + _testName + " ==========");
- try
- {
- super.runBare();
- }
- catch (Exception e)
- {
- _logger.error("exception", e);
- throw e;
- }
- finally
- {
- try
- {
- stopBroker();
- }
- catch (Exception e)
- {
- _logger.error("exception stopping broker", e);
- }
-
- if(_brokerCleanBetweenTests)
- {
- try
- {
- cleanBroker();
- }
- catch (Exception e)
- {
- _logger.error("exception cleaning up broker", e);
- }
- }
-
- _logger.info("========== stop " + _testName + " ==========");
-
- if (redirected)
- {
- System.setErr(oldErr);
- System.setOut(oldOut);
- err.close();
- out.close();
- if (!_interleaveBrokerLog)
- {
- _brokerOutputStream.close();
- }
- }
- }
- }
-
- @Override
- protected void setUp() throws Exception
- {
- if (!_configFile.exists())
- {
- fail("Unable to test without config file:" + _configFile);
- }
-
- String existingQpidWorkPath = System.getProperty(BROKER_EXISTING_QPID_WORK);
- if(existingQpidWorkPath != null && !existingQpidWorkPath.equals(""))
- {
- cleanBroker();
-
- File existing = new File(existingQpidWorkPath);
- File qpidWork = new File(getQpidWork(_broker, getPort()));
- FileUtils.copyRecursive(existing, qpidWork);
- }
-
- startBroker();
- }
-
- private static final class Piper extends Thread
- {
-
- private LineNumberReader in;
- private PrintStream out;
- private String ready;
- private CountDownLatch latch;
- private boolean seenReady;
- private String stopped;
- private String stopLine;
-
- public Piper(InputStream in, PrintStream out, String ready)
- {
- this(in, out, ready, null);
- }
-
- public Piper(InputStream in, PrintStream out, String ready, String stopped)
- {
- this.in = new LineNumberReader(new InputStreamReader(in));
- this.out = out;
- this.ready = ready;
- this.stopped = stopped;
- this.seenReady = false;
-
- if (this.ready != null && !this.ready.equals(""))
- {
- this.latch = new CountDownLatch(1);
- }
- else
- {
- this.latch = null;
- }
- }
-
- public Piper(InputStream in, PrintStream out)
- {
- this(in, out, null);
- }
-
- public boolean await(long timeout, TimeUnit unit) throws InterruptedException
- {
- if (latch == null)
- {
- return true;
- }
- else
- {
- latch.await(timeout, unit);
- return seenReady;
- }
- }
-
- public void run()
- {
- try
- {
- String line;
- while ((line = in.readLine()) != null)
- {
- if (_interleaveBrokerLog)
- {
- line = _brokerLogPrefix + line;
- }
- out.println(line);
-
- if (latch != null && line.contains(ready))
- {
- seenReady = true;
- latch.countDown();
- }
-
- if (!seenReady && line.contains(stopped))
- {
- stopLine = line;
- }
- }
- }
- catch (IOException e)
- {
- // this seems to happen regularly even when
- // exits are normal
- }
- finally
- {
- if (latch != null)
- {
- latch.countDown();
- }
- }
- }
-
- public String getStopLine()
- {
- return stopLine;
- }
- }
-
- public void startBroker() throws Exception
- {
- startBroker(0);
- }
-
- /**
- * Return the management portin use by the broker on this main port
- *
- * @param mainPort the broker's main port.
- *
- * @return the management port that corresponds to the broker on the given port
- */
- protected int getManagementPort(int mainPort)
- {
- return mainPort + (DEFAULT_MANAGEMENT_PORT - (_broker.equals(VM) ? DEFAULT_VM_PORT : DEFAULT_PORT));
- }
-
- /**
- * Get the Port that is use by the current broker
- *
- * @return the current port
- */
- protected int getPort()
- {
- return getPort(0);
- }
-
- protected int getPort(int port)
- {
- if (_broker.equals(VM))
- {
- return port == 0 ? DEFAULT_VM_PORT : port;
- }
- else if (!_broker.equals(EXTERNAL))
- {
- return port == 0 ? DEFAULT_PORT : port;
- }
- else
- {
- return port;
- }
- }
-
- protected String getBrokerCommand(int port) throws MalformedURLException
- {
- return _broker
- .replace("@PORT", "" + port)
- .replace("@SSL_PORT", "" + (port - 1))
- .replace("@MPORT", "" + getManagementPort(port))
- .replace("@CONFIG_FILE", _configFile.toString());
- }
-
- public void startBroker(int port) throws Exception
- {
- port = getPort(port);
-
- // Save any configuration changes that have been made
- saveTestConfiguration();
- saveTestVirtualhosts();
-
- Process process = null;
- if (_broker.equals(VM))
- {
- setConfigurationProperty("management.jmxport", String.valueOf(getManagementPort(port)));
- setConfigurationProperty(ServerConfiguration.MGMT_CUSTOM_REGISTRY_SOCKET, String.valueOf(false));
- saveTestConfiguration();
-
- // create an in_VM broker
- final ConfigurationFileApplicationRegistry registry = new ConfigurationFileApplicationRegistry(_configFile);
- try
- {
- ApplicationRegistry.initialise(registry, port);
- }
- catch (Exception e)
- {
- _logger.error("Broker initialise failed due to:",e);
- try
- {
- registry.close();
- }
- catch (Throwable closeE)
- {
- closeE.printStackTrace();
- }
- throw e;
- }
- TransportConnection.createVMBroker(port);
- }
- else if (!_broker.equals(EXTERNAL))
- {
- String cmd = getBrokerCommand(port);
- _logger.info("starting broker: " + cmd);
- ProcessBuilder pb = new ProcessBuilder(cmd.split("\\s+"));
- pb.redirectErrorStream(true);
-
- Map<String, String> env = pb.environment();
-
- String qpidHome = System.getProperty(QPID_HOME);
- env.put(QPID_HOME, qpidHome);
-
- //Augment Path with bin directory in QPID_HOME.
- env.put("PATH", env.get("PATH").concat(File.pathSeparator + qpidHome + "/bin"));
-
- //Add the test name to the broker run.
- // DON'T change PNAME, qpid.stop needs this value.
- env.put("QPID_PNAME", "-DPNAME=QPBRKR -DTNAME=\"" + _testName + "\"");
- // Add the port to QPID_WORK to ensure unique working dirs for multi broker tests
- env.put("QPID_WORK", getQpidWork(_broker, port));
-
-
- // Use the environment variable to set amqj.logging.level for the broker
- // The value used is a 'server' value in the test configuration to
- // allow a differentiation between the client and broker logging levels.
- if (System.getProperty("amqj.server.logging.level") != null)
- {
- setBrokerEnvironment("AMQJ_LOGGING_LEVEL", System.getProperty("amqj.server.logging.level"));
- }
-
- // Add all the environment settings the test requested
- if (!_env.isEmpty())
- {
- for (Map.Entry<String, String> entry : _env.entrySet())
- {
- env.put(entry.getKey(), entry.getValue());
- }
- }
-
-
- // Add default test logging levels that are used by the log4j-test
- // Use the convenience methods to push the current logging setting
- // in to the external broker's QPID_OPTS string.
- if (System.getProperty("amqj.protocol.logging.level") != null)
- {
- setSystemProperty("amqj.protocol.logging.level");
- }
- if (System.getProperty("root.logging.level") != null)
- {
- setSystemProperty("root.logging.level");
- }
-
-
- String QPID_OPTS = " ";
- // Add all the specified system properties to QPID_OPTS
- if (!_propertiesSetForBroker.isEmpty())
- {
- for (String key : _propertiesSetForBroker.keySet())
- {
- QPID_OPTS += "-D" + key + "=" + _propertiesSetForBroker.get(key) + " ";
- }
-
- if (env.containsKey("QPID_OPTS"))
- {
- env.put("QPID_OPTS", env.get("QPID_OPTS") + QPID_OPTS);
- }
- else
- {
- env.put("QPID_OPTS", QPID_OPTS);
- }
- }
-
- process = pb.start();
-
- Piper p = new Piper(process.getInputStream(),
- _brokerOutputStream,
- System.getProperty(BROKER_READY),
- System.getProperty(BROKER_STOPPED));
-
- p.start();
-
- if (!p.await(30, TimeUnit.SECONDS))
- {
- _logger.info("broker failed to become ready (" + p.ready + "):" + p.getStopLine());
- //Ensure broker has stopped
- process.destroy();
- cleanBroker();
- throw new RuntimeException("broker failed to become ready:"
- + p.getStopLine());
- }
-
- try
- {
- int exit = process.exitValue();
- _logger.info("broker aborted: " + exit);
- cleanBroker();
- throw new RuntimeException("broker aborted: " + exit);
- }
- catch (IllegalThreadStateException e)
- {
- // this is expect if the broker started succesfully
- }
- }
-
- _brokers.put(port, process);
- }
-
- private String getQpidWork(String broker, int port)
- {
- if (broker.equals(VM))
- {
- return System.getProperty("QPID_WORK");
- }
- else if (!broker.equals(EXTERNAL))
- {
- return System.getProperty("QPID_WORK")+ "/" + port;
- }
-
- return System.getProperty("QPID_WORK");
- }
-
- public String getTestConfigFile()
- {
- String path = _output == null ? System.getProperty("java.io.tmpdir") : _output;
- return path + "/" + getTestQueueName() + "-config.xml";
- }
-
- public String getTestVirtualhostsFile()
- {
- String path = _output == null ? System.getProperty("java.io.tmpdir") : _output;
- return path + "/" + getTestQueueName() + "-virtualhosts.xml";
- }
-
- protected void saveTestConfiguration() throws ConfigurationException
- {
- // Specifiy the test config file
- String testConfig = getTestConfigFile();
- setSystemProperty("test.config", testConfig);
-
- // Create the file if configuration does not exist
- if (_testConfiguration.isEmpty())
- {
- _testConfiguration.addProperty("__ignore", "true");
- }
- _testConfiguration.save(testConfig);
- }
-
- protected void saveTestVirtualhosts() throws ConfigurationException
- {
- // Specifiy the test virtualhosts file
- String testVirtualhosts = getTestVirtualhostsFile();
- setSystemProperty("test.virtualhosts", testVirtualhosts);
-
- // Create the file if configuration does not exist
- if (_testVirtualhosts.isEmpty())
- {
- _testVirtualhosts.addProperty("__ignore", "true");
- }
- _testVirtualhosts.save(testVirtualhosts);
- }
-
- public void cleanBroker()
- {
- if (_brokerClean != null)
- {
- _logger.info("clean: " + _brokerClean);
-
- try
- {
- ProcessBuilder pb = new ProcessBuilder(_brokerClean.split("\\s+"));
- pb.redirectErrorStream(true);
- Process clean = pb.start();
- new Piper(clean.getInputStream(),_brokerOutputStream).start();
-
- clean.waitFor();
-
- _logger.info("clean exited: " + clean.exitValue());
- }
- catch (IOException e)
- {
- throw new RuntimeException(e);
- }
- catch (InterruptedException e)
- {
- throw new RuntimeException(e);
- }
- }
- }
-
- public void stopBroker() throws Exception
- {
- stopBroker(0);
- }
-
- public void stopBroker(int port) throws Exception
- {
- port = getPort(port);
-
- _logger.info("stopping broker: " + getBrokerCommand(port));
- Process process = _brokers.remove(port);
- if (process != null)
- {
- process.destroy();
- process.waitFor();
- _logger.info("broker exited: " + process.exitValue());
- }
- else if (_broker.equals(VM))
- {
- TransportConnection.killVMBroker(port);
- ApplicationRegistry.remove(port);
- }
- }
-
- /**
- * Attempt to set the Java Broker to use the BDBMessageStore for persistence
- * Falling back to the DerbyMessageStore if
- *
- * @param virtualhost - The virtualhost to modify
- *
- * @throws ConfigurationException - when reading/writing existing configuration
- * @throws IOException - When creating a temporary file.
- */
- protected void makeVirtualHostPersistent(String virtualhost)
- throws ConfigurationException, IOException
- {
- Class<?> storeClass = null;
- try
- {
- // Try and lookup the BDB class
- storeClass = Class.forName("org.apache.qpid.server.store.berkeleydb.BDBMessageStore");
- }
- catch (ClassNotFoundException e)
- {
- // No BDB store, we'll use Derby instead.
- storeClass = DerbyMessageStore.class;
- }
-
-
- setConfigurationProperty("virtualhosts.virtualhost." + virtualhost + ".store.class",
- storeClass.getName());
- setConfigurationProperty("virtualhosts.virtualhost." + virtualhost + ".store." + DerbyMessageStore.ENVIRONMENT_PATH_PROPERTY,
- "${QPID_WORK}/" + virtualhost);
- }
-
- /**
- * Get a property value from the current configuration file.
- *
- * @param property the property to lookup
- *
- * @return the requested String Value
- *
- * @throws org.apache.commons.configuration.ConfigurationException
- *
- */
- protected String getConfigurationStringProperty(String property) throws ConfigurationException
- {
- // Call save Configuration to be sure we have saved the test specific
- // file. As the optional status
- saveTestConfiguration();
- saveTestVirtualhosts();
-
- ServerConfiguration configuration = new ServerConfiguration(_configFile);
- // Don't need to configuration.configure() here as we are just pulling
- // values directly by String.
- return configuration.getConfig().getString(property);
- }
-
- /**
- * Set a configuration Property for this test run.
- *
- * This creates a new configuration based on the current configuration
- * with the specified property change.
- *
- * Multiple calls to this method will result in multiple temporary
- * configuration files being created.
- *
- * @param property the configuration property to set
- * @param value the new value
- *
- * @throws ConfigurationException when loading the current config file
- * @throws IOException when writing the new config file
- */
- protected void setConfigurationProperty(String property, String value)
- throws ConfigurationException, IOException
- {
- // Choose which file to write the property to based on prefix.
- if (property.startsWith("virtualhosts"))
- {
- _testVirtualhosts.setProperty(StringUtils.substringAfter(property, "virtualhosts."), value);
- }
- else
- {
- _testConfiguration.setProperty(property, value);
- }
- }
-
- /**
- * Set a System property that is to be applied only to the external test
- * broker.
- *
- * This is a convenience method to enable the setting of a -Dproperty=value
- * entry in QPID_OPTS
- *
- * This is only useful for the External Java Broker tests.
- *
- * @param property the property name
- * @param value the value to set the property to
- */
- protected void setBrokerOnlySystemProperty(String property, String value)
- {
- if (!_propertiesSetForBroker.containsKey(property))
- {
- _propertiesSetForBroker.put(property, value);
- }
-
- }
-
- /**
- * Set a System (-D) property for this test run.
- *
- * This convenience method copies the current VMs System Property
- * for the external VM Broker.
- *
- * @param property the System property to set
- */
- protected void setSystemProperty(String property)
- {
- setSystemProperty(property, System.getProperty(property));
- }
-
- /**
- * Set a System property for the duration of this test.
- *
- * When the test run is complete the value will be reverted.
- *
- * The values set using this method will also be propogated to the external
- * Java Broker via a -D value defined in QPID_OPTS.
- *
- * If the value should not be set on the broker then use
- * setTestClientSystemProperty().
- *
- * @param property the property to set
- * @param value the new value to use
- */
- protected void setSystemProperty(String property, String value)
- {
- // Record the value for the external broker
- _propertiesSetForBroker.put(property, value);
-
- //Set the value for the test client vm aswell.
- setTestClientSystemProperty(property, value);
- }
-
- /**
- * Set a System (-D) property for the external Broker of this test.
- *
- * @param property The property to set
- * @param value the value to set it to.
- */
- protected void setTestClientSystemProperty(String property, String value)
- {
- if (!_propertiesSetForTestOnly.containsKey(property))
- {
- // Record the current value so we can revert it later.
- _propertiesSetForTestOnly.put(property, System.getProperty(property));
- }
-
- System.setProperty(property, value);
- }
-
- /**
- * Restore the System property values that were set before this test run.
- */
- protected void revertSystemProperties()
- {
- for (String key : _propertiesSetForTestOnly.keySet())
- {
- String value = _propertiesSetForTestOnly.get(key);
- if (value != null)
- {
- System.setProperty(key, value);
- }
- else
- {
- System.clearProperty(key);
- }
- }
-
- _propertiesSetForTestOnly.clear();
-
- // We don't change the current VMs settings for Broker only properties
- // so we can just clear this map
- _propertiesSetForBroker.clear();
- }
-
- /**
- * Add an environtmen variable for the external broker environment
- *
- * @param property the property to set
- * @param value the value to set it to
- */
- protected void setBrokerEnvironment(String property, String value)
- {
- _env.put(property, value);
- }
-
- /**
- * Adjust the VMs Log4j Settings just for this test run
- *
- * @param logger the logger to change
- * @param level the level to set
- */
- protected void setLoggerLevel(Logger logger, Level level)
- {
- assertNotNull("Cannot set level of null logger", logger);
- assertNotNull("Cannot set Logger("+logger.getName()+") to null level.",level);
-
- if (!_loggerLevelSetForTest.containsKey(logger))
- {
- // Record the current value so we can revert it later.
- _loggerLevelSetForTest.put(logger, logger.getLevel());
- }
-
- logger.setLevel(level);
- }
-
- /**
- * Restore the logging levels defined by this test.
- */
- protected void revertLoggingLevels()
- {
- for (Logger logger : _loggerLevelSetForTest.keySet())
- {
- logger.setLevel(_loggerLevelSetForTest.get(logger));
- }
-
- _loggerLevelSetForTest.clear();
-
- }
-
- /**
- * Check whether the broker is an 0.8
- *
- * @return true if the broker is an 0_8 version, false otherwise.
- */
- public boolean isBroker08()
- {
- return _brokerVersion.equals(VERSION_08);
- }
-
- public boolean isBroker010()
- {
- return _brokerVersion.equals(VERSION_010);
- }
-
- protected boolean isJavaBroker()
- {
- return _brokerLanguage.equals("java") || _broker.equals("vm");
- }
-
- protected boolean isCppBroker()
- {
- return _brokerLanguage.equals("cpp");
- }
-
- protected boolean isExternalBroker()
- {
- return !_broker.equals("vm");
- }
-
- protected boolean isBrokerStorePersistent()
- {
- return _brokerPersistent;
- }
-
- public void restartBroker() throws Exception
- {
- restartBroker(0);
- }
-
- public void restartBroker(int port) throws Exception
- {
- stopBroker(port);
- startBroker(port);
- }
-
- /**
- * we assume that the environment is correctly set
- * i.e. -Djava.naming.provider.url="..//example010.properties"
- * TODO should be a way of setting that through maven
- *
- * @return an initial context
- *
- * @throws NamingException if there is an error getting the context
- */
- public InitialContext getInitialContext() throws NamingException
- {
- _logger.info("get InitialContext");
- if (_initialContext == null)
- {
- _initialContext = new InitialContext();
- }
- return _initialContext;
- }
-
- /**
- * Get the default connection factory for the currently used broker
- * Default factory is "local"
- *
- * @return A conection factory
- *
- * @throws Exception if there is an error getting the tactory
- */
- public AMQConnectionFactory getConnectionFactory() throws NamingException
- {
- _logger.info("get ConnectionFactory");
- if (_connectionFactory == null)
- {
- if (Boolean.getBoolean("profile.use_ssl"))
- {
- _connectionFactory = getConnectionFactory("default.ssl");
- }
- else
- {
- _connectionFactory = getConnectionFactory("default");
- }
- }
- return _connectionFactory;
- }
-
- /**
- * Get a connection factory for the currently used broker
- *
- * @param factoryName The factory name
- *
- * @return A conection factory
- *
- * @throws Exception if there is an error getting the tactory
- */
- public AMQConnectionFactory getConnectionFactory(String factoryName) throws NamingException
- {
- if (_broker.equals(VM))
- {
- factoryName += ".vm";
- }
-
- return (AMQConnectionFactory) getInitialContext().lookup(factoryName);
- }
-
- public Connection getConnection() throws JMSException, NamingException
- {
- return getConnection("guest", "guest");
- }
-
- public Connection getConnection(ConnectionURL url) throws JMSException
- {
- _logger.info(url.getURL());
- Connection connection = new AMQConnectionFactory(url).createConnection(url.getUsername(), url.getPassword());
-
- _connections.add(connection);
-
- return connection;
- }
-
- /**
- * Get a connection (remote or in-VM)
- *
- * @param username The user name
- * @param password The user password
- *
- * @return a newly created connection
- *
- * @throws Exception if there is an error getting the connection
- */
- public Connection getConnection(String username, String password) throws JMSException, NamingException
- {
- _logger.info("get connection");
- Connection con = getConnectionFactory().createConnection(username, password);
- //add the connection in the lis of connections
- _connections.add(con);
- return con;
- }
-
- public Connection getClientConnection(String username, String password, String id) throws JMSException, URLSyntaxException, AMQException, NamingException
- {
- _logger.info("get Connection");
- Connection con;
- if (_broker.equals(VM))
- {
- con = new AMQConnection("vm://:1", username, password, id, "test");
- }
- else
- {
- con = getConnectionFactory().createConnection(username, password, id);
- }
- //add the connection in the lis of connections
- _connections.add(con);
- return con;
- }
-
- /**
- * Return a uniqueName for this test.
- * In this case it returns a queue Named by the TestCase and TestName
- *
- * @return String name for a queue
- */
- protected String getTestQueueName()
- {
- return getClass().getSimpleName() + "-" + getName();
- }
-
- /**
- * Return a Queue specific for this test.
- * Uses getTestQueueName() as the name of the queue
- * @return
- */
- public Queue getTestQueue()
- {
- return new AMQQueue(ExchangeDefaults.DIRECT_EXCHANGE_NAME, getTestQueueName());
- }
-
-
- protected void tearDown() throws java.lang.Exception
- {
- try
- {
- // close all the connections used by this test.
- for (Connection c : _connections)
- {
- c.close();
- }
- }
- finally{
- // Ensure any problems with close does not interfer with property resets
- revertSystemProperties();
- revertLoggingLevels();
- }
- }
-
- /**
- * Consume all the messages in the specified queue. Helper to ensure
- * persistent tests don't leave data behind.
- *
- * @param queue the queue to purge
- *
- * @return the count of messages drained
- *
- * @throws Exception if a problem occurs
- */
- protected int drainQueue(Queue queue) throws Exception
- {
- Connection connection = getConnection();
-
- Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- MessageConsumer consumer = session.createConsumer(queue);
-
- connection.start();
-
- int count = 0;
- while (consumer.receive(1000) != null)
- {
- count++;
- }
-
- connection.close();
-
- return count;
- }
-
- /**
- * Send messages to the given destination.
- *
- * If session is transacted then messages will be commited before returning
- *
- * @param session the session to use for sending
- * @param destination where to send them to
- * @param count no. of messages to send
- *
- * @return the sent messges
- *
- * @throws Exception
- */
- public List<Message> sendMessage(Session session, Destination destination,
- int count) throws Exception
- {
- return sendMessage(session, destination, count, 0, 0);
- }
-
- /**
- * Send messages to the given destination.
- *
- * If session is transacted then messages will be commited before returning
- *
- * @param session the session to use for sending
- * @param destination where to send them to
- * @param count no. of messages to send
- *
- * @param batchSize the batchSize in which to commit, 0 means no batching,
- * but a single commit at the end
- * @return the sent messgse
- *
- * @throws Exception
- */
- public List<Message> sendMessage(Session session, Destination destination,
- int count, int batchSize) throws Exception
- {
- return sendMessage(session, destination, count, 0, batchSize);
- }
-
- /**
- * Send messages to the given destination.
- *
- * If session is transacted then messages will be commited before returning
- *
- * @param session the session to use for sending
- * @param destination where to send them to
- * @param count no. of messages to send
- *
- * @param offset offset allows the INDEX value of the message to be adjusted.
- * @param batchSize the batchSize in which to commit, 0 means no batching,
- * but a single commit at the end
- * @return the sent messgse
- *
- * @throws Exception
- */
- public List<Message> sendMessage(Session session, Destination destination,
- int count, int offset, int batchSize) throws Exception
- {
- List<Message> messages = new ArrayList<Message>(count);
-
- MessageProducer producer = session.createProducer(destination);
-
- int i = offset;
- for (; i < (count + offset); i++)
- {
- Message next = createNextMessage(session, i);
-
- producer.send(next);
-
- if (session.getTransacted() && batchSize > 0)
- {
- if (i % batchSize == 0)
- {
- session.commit();
- }
-
- }
-
- messages.add(next);
- }
-
- // Ensure we commit the last messages
- // Commit the session if we are transacted and
- // we have no batchSize or
- // our count is not divible by batchSize.
- if (session.getTransacted() &&
- ( batchSize == 0 || (i-1) % batchSize != 0))
- {
- session.commit();
- }
-
- return messages;
- }
-
- public Message createNextMessage(Session session, int msgCount) throws JMSException
- {
- Message message = createMessage(session, _messageSize);
- message.setIntProperty(INDEX, msgCount);
-
- return message;
-
- }
-
- public Message createMessage(Session session, int messageSize) throws JMSException
- {
- String payload = new String(new byte[messageSize]);
-
- Message message;
-
- switch (_messageType)
- {
- case BYTES:
- message = session.createBytesMessage();
- ((BytesMessage) message).writeUTF(payload);
- break;
- case MAP:
- message = session.createMapMessage();
- ((MapMessage) message).setString(CONTENT, payload);
- break;
- default: // To keep the compiler happy
- case TEXT:
- message = session.createTextMessage();
- ((TextMessage) message).setText(payload);
- break;
- case OBJECT:
- message = session.createObjectMessage();
- ((ObjectMessage) message).setObject(payload);
- break;
- case STREAM:
- message = session.createStreamMessage();
- ((StreamMessage) message).writeString(payload);
- break;
- }
-
- return message;
- }
-
- protected int getMessageSize()
- {
- return _messageSize;
- }
-
- protected void setMessageSize(int byteSize)
- {
- _messageSize = byteSize;
- }
-
- public ConnectionURL getConnectionURL() throws NamingException
- {
- return getConnectionFactory().getConnectionURL();
- }
-
- public BrokerDetails getBroker()
- {
- try
- {
- if (getConnectionFactory().getConnectionURL().getBrokerCount() > 0)
- {
- return getConnectionFactory().getConnectionURL().getBrokerDetails(0);
- }
- else
- {
- fail("No broker details are available.");
- }
- }
- catch (NamingException e)
- {
- fail(e.getMessage());
- }
-
- //keep compiler happy
- return null;
- }
-
- /**
- * Reloads the broker security configuration using the ApplicationRegistry (InVM brokers) or the
- * ConfigurationManagementMBean via the JMX interface (Standalone brokers, management must be
- * enabled before calling the method).
- */
- public void reloadBrokerSecurityConfig() throws Exception
- {
- if (_broker.equals(VM))
- {
- ApplicationRegistry.getInstance().getConfiguration().reparseConfigFileSecuritySections();
- }
- else
- {
- JMXTestUtils jmxu = new JMXTestUtils(this, "admin" , "admin");
- jmxu.open();
-
- try
- {
- ConfigurationManagement configMBean = jmxu.getConfigurationManagement();
- configMBean.reloadSecurityConfiguration();
- }
- finally
- {
- jmxu.close();
- }
-
- LogMonitor _monitor = new LogMonitor(_outputFile);
- assertTrue("The expected server security configuration reload did not occur",
- _monitor.waitForMessage(ServerConfiguration.SECURITY_CONFIG_RELOADED, LOGMONITOR_TIMEOUT));
-
- }
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/utils/QpidClientConnection.java b/java/systests/src/main/java/org/apache/qpid/test/utils/QpidClientConnection.java
deleted file mode 100644
index 16f7bfd305..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/utils/QpidClientConnection.java
+++ /dev/null
@@ -1,289 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.qpid.test.utils;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.JMSAMQException;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.jms.Connection;
-import javax.jms.ExceptionListener;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-import javax.jms.Queue;
-import javax.jms.Session;
-import javax.jms.TextMessage;
-
-public class QpidClientConnection extends QpidBrokerTestCase implements ExceptionListener
-{
- private static final Logger _logger = LoggerFactory.getLogger(QpidClientConnection.class);
-
- private boolean transacted = true;
- private int ackMode = Session.CLIENT_ACKNOWLEDGE;
- private Connection connection;
-
- private String virtualHost;
- private String brokerlist;
- private int prefetch;
- protected Session session;
- protected boolean connected;
-
- public QpidClientConnection(String broker)
- {
- super();
- setVirtualHost("/test");
- setBrokerList(broker);
- setPrefetch(5000);
- }
-
-
- public Connection getConnection()
- {
- return connection;
- }
-
- public void connect() throws JMSException
- {
- if (!connected)
- {
- /*
- * amqp://[user:pass@][clientid]/virtualhost?
- * brokerlist='[transport://]host[:port][?option='value'[&option='value']];'
- * [&failover='method[?option='value'[&option='value']]']
- * [&option='value']"
- */
- String brokerUrl = "amqp://guest:guest@" + virtualHost + "?brokerlist='" + brokerlist + "'";
- try
- {
- _logger.info("connecting to Qpid :" + brokerUrl);
- connection = getConnection("guest", "guest") ;
- // register exception listener
- connection.setExceptionListener(this);
-
- session = ((AMQConnection) connection).createSession(transacted, ackMode, prefetch);
-
- _logger.info("starting connection");
- connection.start();
-
- connected = true;
- }
- catch (Exception e)
- {
- throw new JMSAMQException("URL syntax error in [" + brokerUrl + "]: " + e.getMessage(), e);
- }
- }
- }
-
- public void disconnect() throws Exception
- {
- if (connected)
- {
- session.commit();
- session.close();
- connection.close();
- connected = false;
- _logger.info("disconnected");
- }
- }
-
- public void disconnectWithoutCommit() throws JMSException
- {
- if (connected)
- {
- session.close();
- connection.close();
- connected = false;
- _logger.info("disconnected without commit");
- }
- }
-
- public String getBrokerList()
- {
- return brokerlist;
- }
-
- public void setBrokerList(String brokerlist)
- {
- this.brokerlist = brokerlist;
- }
-
- public String getVirtualHost()
- {
- return virtualHost;
- }
-
- public void setVirtualHost(String virtualHost)
- {
- this.virtualHost = virtualHost;
- }
-
- public void setPrefetch(int prefetch)
- {
- this.prefetch = prefetch;
- }
-
- /** override as necessary */
- public void onException(JMSException exception)
- {
- _logger.info("ExceptionListener event: error " + exception.getErrorCode() + ", message: " + exception.getMessage());
- }
-
- public boolean isConnected()
- {
- return connected;
- }
-
- public Session getSession()
- {
- return session;
- }
-
- /**
- * Put a String as a text messages, repeat n times. A null payload will result in a null message.
- *
- * @param queueName The queue name to put to
- * @param payload the content of the payload
- * @param copies the number of messages to put
- *
- * @throws javax.jms.JMSException any exception that occurs
- */
- public void put(String queueName, String payload, int copies) throws JMSException
- {
- if (!connected)
- {
- connect();
- }
-
- _logger.info("putting to queue " + queueName);
- Queue queue = session.createQueue(queueName);
-
- final MessageProducer sender = session.createProducer(queue);
-
- for (int i = 0; i < copies; i++)
- {
- Message m = session.createTextMessage(payload + i);
- m.setIntProperty("index", i + 1);
- sender.send(m);
- }
-
- session.commit();
- sender.close();
- _logger.info("put " + copies + " copies");
- }
-
- /**
- * GET the top message on a queue. Consumes the message. Accepts timeout value.
- *
- * @param queueName The quename to get from
- * @param readTimeout The timeout to use
- *
- * @return the content of the text message if any
- *
- * @throws javax.jms.JMSException any exception that occured
- */
- public Message getNextMessage(String queueName, long readTimeout) throws JMSException
- {
- if (!connected)
- {
- connect();
- }
-
- Queue queue = session.createQueue(queueName);
-
- final MessageConsumer consumer = session.createConsumer(queue);
-
- Message message = consumer.receive(readTimeout);
- session.commit();
- consumer.close();
-
- Message result;
-
- // all messages we consume should be TextMessages
- if (message instanceof TextMessage)
- {
- result = ((TextMessage) message);
- }
- else if (null == message)
- {
- result = null;
- }
- else
- {
- _logger.info("warning: received non-text message");
- result = message;
- }
-
- return result;
- }
-
- /**
- * GET the top message on a queue. Consumes the message.
- *
- * @param queueName The Queuename to get from
- *
- * @return The string content of the text message, if any received
- *
- * @throws javax.jms.JMSException any exception that occurs
- */
- public Message getNextMessage(String queueName) throws JMSException
- {
- return getNextMessage(queueName, 0);
- }
-
- /**
- * Completely clears a queue. For readTimeout behaviour see Javadocs for javax.jms.MessageConsumer.
- *
- * @param queueName The Queue name to consume from
- * @param readTimeout The timeout for each consume
- *
- * @throws javax.jms.JMSException Any exception that occurs during the consume
- * @throws InterruptedException If the consume thread was interrupted during a consume.
- */
- public void consume(String queueName, int readTimeout) throws JMSException, InterruptedException
- {
- if (!connected)
- {
- connect();
- }
-
- _logger.info("consuming queue " + queueName);
- Queue queue = session.createQueue(queueName);
-
- final MessageConsumer consumer = session.createConsumer(queue);
- int messagesReceived = 0;
-
- _logger.info("consuming...");
- while ((consumer.receive(readTimeout)) != null)
- {
- messagesReceived++;
- }
-
- session.commit();
- consumer.close();
- _logger.info("consumed: " + messagesReceived);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/utils/QpidClientConnectionHelper.java b/java/systests/src/main/java/org/apache/qpid/test/utils/QpidClientConnectionHelper.java
deleted file mode 100644
index 72003ed7d7..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/utils/QpidClientConnectionHelper.java
+++ /dev/null
@@ -1,295 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.qpid.test.utils;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQConnectionFactory;
-import org.apache.qpid.client.AMQConnectionURL;
-import org.apache.qpid.client.JMSAMQException;
-import org.apache.qpid.url.URLSyntaxException;
-
-import javax.jms.Connection;
-import javax.jms.ExceptionListener;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-import javax.jms.Queue;
-import javax.jms.Session;
-import javax.jms.TextMessage;
-
-/**
- * @todo This was originally cut and paste from the client module leading to a duplicate class, then altered very
- * slightly. To avoid the duplicate class the name was altered slightly to have 'Helper' on the end in order
- * to distinguish it from the original. Delete this class and use the original instead, just upgrade it to
- * provide the new features needed.
- */
-public class QpidClientConnectionHelper implements ExceptionListener
-{
-
- private static final Logger _logger = Logger.getLogger(QpidClientConnectionHelper.class);
-
- private boolean transacted = true;
- private int ackMode = Session.CLIENT_ACKNOWLEDGE;
- private Connection connection;
-
- private String virtualHost;
- private String brokerlist;
- private int prefetch;
- protected Session session;
- protected boolean connected;
-
- public QpidClientConnectionHelper(String broker)
- {
- super();
- setVirtualHost("/test");
- setBrokerList(broker);
- setPrefetch(5000);
- }
-
- public void connect() throws JMSException
- {
- if (!connected)
- {
- /*
- * amqp://[user:pass@][clientid]/virtualhost?
- * brokerlist='[transport://]host[:port][?option='value'[&option='value']];'
- * [&failover='method[?option='value'[&option='value']]']
- * [&option='value']"
- */
- String brokerUrl = "amqp://guest:guest@" + virtualHost + "?brokerlist='" + brokerlist + "'";
- try
- {
- AMQConnectionFactory factory = new AMQConnectionFactory(new AMQConnectionURL(brokerUrl));
- _logger.info("connecting to Qpid :" + brokerUrl);
- connection = factory.createConnection();
-
- // register exception listener
- connection.setExceptionListener(this);
-
- session = ((AMQConnection) connection).createSession(transacted, ackMode, prefetch);
-
- _logger.info("starting connection");
- connection.start();
-
- connected = true;
- }
- catch (URLSyntaxException e)
- {
- throw new JMSAMQException("URL syntax error in [" + brokerUrl + "]: " + e.getMessage(), e);
- }
- }
- }
-
- public void disconnect() throws JMSException
- {
- if (connected)
- {
- session.commit();
- session.close();
- connection.close();
- connected = false;
- _logger.info("disconnected");
- }
- }
-
- public void disconnectWithoutCommit() throws JMSException
- {
- if (connected)
- {
- session.close();
- connection.close();
- connected = false;
- _logger.info("disconnected without commit");
- }
- }
-
- public String getBrokerList()
- {
- return brokerlist;
- }
-
- public void setBrokerList(String brokerlist)
- {
- this.brokerlist = brokerlist;
- }
-
- public String getVirtualHost()
- {
- return virtualHost;
- }
-
- public void setVirtualHost(String virtualHost)
- {
- this.virtualHost = virtualHost;
- }
-
- public void setPrefetch(int prefetch)
- {
- this.prefetch = prefetch;
- }
-
- /** override as necessary */
- public void onException(JMSException exception)
- {
- _logger.info("ExceptionListener event: error " + exception.getErrorCode() + ", message: " + exception.getMessage());
- }
-
- public boolean isConnected()
- {
- return connected;
- }
-
- public Session getSession()
- {
- return session;
- }
-
- /**
- * Put a String as a text messages, repeat n times. A null payload will result in a null message.
- *
- * @param queueName The queue name to put to
- * @param payload the content of the payload
- * @param copies the number of messages to put
- *
- * @throws javax.jms.JMSException any exception that occurs
- */
- public void put(String queueName, String payload, int copies, int deliveryMode) throws JMSException
- {
- if (!connected)
- {
- connect();
- }
-
- _logger.info("putting to queue " + queueName);
- Queue queue = session.createQueue(queueName);
-
- final MessageProducer sender = session.createProducer(queue);
-
- sender.setDeliveryMode(deliveryMode);
-
- for (int i = 0; i < copies; i++)
- {
- Message m = session.createTextMessage(payload + i);
- m.setIntProperty("index", i + 1);
- sender.send(m);
- }
-
- session.commit();
- sender.close();
- _logger.info("put " + copies + " copies");
- }
-
- /**
- * GET the top message on a queue. Consumes the message. Accepts timeout value.
- *
- * @param queueName The quename to get from
- * @param readTimeout The timeout to use
- *
- * @return the content of the text message if any
- *
- * @throws javax.jms.JMSException any exception that occured
- */
- public Message getNextMessage(String queueName, long readTimeout) throws JMSException
- {
- if (!connected)
- {
- connect();
- }
-
- Queue queue = session.createQueue(queueName);
-
- final MessageConsumer consumer = session.createConsumer(queue);
-
- Message message = consumer.receive(readTimeout);
- session.commit();
- consumer.close();
-
- Message result;
-
- // all messages we consume should be TextMessages
- if (message instanceof TextMessage)
- {
- result = ((TextMessage) message);
- }
- else if (null == message)
- {
- result = null;
- }
- else
- {
- _logger.info("warning: received non-text message");
- result = message;
- }
-
- return result;
- }
-
- /**
- * GET the top message on a queue. Consumes the message.
- *
- * @param queueName The Queuename to get from
- *
- * @return The string content of the text message, if any received
- *
- * @throws javax.jms.JMSException any exception that occurs
- */
- public Message getNextMessage(String queueName) throws JMSException
- {
- return getNextMessage(queueName, 0);
- }
-
- /**
- * Completely clears a queue. For readTimeout behaviour see Javadocs for javax.jms.MessageConsumer.
- *
- * @param queueName The Queue name to consume from
- * @param readTimeout The timeout for each consume
- *
- * @throws javax.jms.JMSException Any exception that occurs during the consume
- * @throws InterruptedException If the consume thread was interrupted during a consume.
- */
- public void consume(String queueName, int readTimeout) throws JMSException, InterruptedException
- {
- if (!connected)
- {
- connect();
- }
-
- _logger.info("consuming queue " + queueName);
- Queue queue = session.createQueue(queueName);
-
- final MessageConsumer consumer = session.createConsumer(queue);
- int messagesReceived = 0;
-
- _logger.info("consuming...");
- while ((consumer.receive(readTimeout)) != null)
- {
- messagesReceived++;
- }
-
- session.commit();
- consumer.close();
- _logger.info("consumed: " + messagesReceived);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/utils/ReflectionUtils.java b/java/systests/src/main/java/org/apache/qpid/test/utils/ReflectionUtils.java
deleted file mode 100644
index 7946c6a6d1..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/utils/ReflectionUtils.java
+++ /dev/null
@@ -1,228 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.utils;
-
-import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-
-/**
- * Provides helper methods for operating on classes and methods using reflection. Reflection methods tend to return
- * a lot of checked exception so writing code to use them can be tedious and harder to read, especially when such errors
- * are not expected to occur. This class always works with {@link ReflectionUtilsException}, which is a runtime exception,
- * to wrap the checked exceptions raised by the standard Java reflection methods. Code using it does not normally
- * expect these errors to occur, usually does not have a recovery mechanism for them when they do, but is cleaner,
- * quicker to write and easier to read in the majority of cases.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Look up Classes by name.
- * <tr><td> Instantiate Classes by no-arg constructor.
- * </table>
- */
-public class ReflectionUtils
-{
- /**
- * Gets the Class object for a named class.
- *
- * @param className The class to get the Class object for.
- *
- * @return The Class object for the named class.
- */
- public static Class<?> forName(String className)
- {
- try
- {
- return Class.forName(className);
- }
- catch (ClassNotFoundException e)
- {
- throw new ReflectionUtilsException("ClassNotFoundException whilst finding class.", e);
- }
- }
-
- /**
- * Creates an instance of a Class, instantiated through its no-args constructor.
- *
- * @param cls The Class to instantiate.
- * @param <T> The Class type.
- *
- * @return An instance of the class.
- */
- public static <T> T newInstance(Class<? extends T> cls)
- {
- try
- {
- return cls.newInstance();
- }
- catch (InstantiationException e)
- {
- throw new ReflectionUtilsException("InstantiationException whilst instantiating class.", e);
- }
- catch (IllegalAccessException e)
- {
- throw new ReflectionUtilsException("IllegalAccessException whilst instantiating class.", e);
- }
- }
-
- /**
- * Calls a named method on an object with a specified set of parameters, any Java access modifier are overridden.
- *
- * @param o The object to call.
- * @param method The method name to call.
- * @param params The parameters to pass.
- * @param paramClasses The argument types.
- *
- * @return The return value from the method call.
- */
- public static Object callMethodOverridingIllegalAccess(Object o, String method, Object[] params, Class[] paramClasses)
- {
- // Get the objects class.
- Class cls = o.getClass();
-
- // Get the classes of the parameters.
- /*Class[] paramClasses = new Class[params.length];
-
- for (int i = 0; i < params.length; i++)
- {
- paramClasses[i] = params[i].getClass();
- }*/
-
- try
- {
- // Try to find the matching method on the class.
- Method m = cls.getDeclaredMethod(method, paramClasses);
-
- // Make it accessible.
- m.setAccessible(true);
-
- // Invoke it with the parameters.
- return m.invoke(o, params);
- }
- catch (NoSuchMethodException e)
- {
- throw new ReflectionUtilsException("NoSuchMethodException.", e);
- }
- catch (IllegalAccessException e)
- {
- throw new ReflectionUtilsException("IllegalAccessException.", e);
- }
- catch (InvocationTargetException e)
- {
- throw new ReflectionUtilsException("InvocationTargetException", e);
- }
- }
-
- /**
- * Calls a named method on an object with a specified set of parameters.
- *
- * @param o The object to call.
- * @param method The method name to call.
- * @param params The parameters to pass.
- *
- * @return The return value from the method call.
- */
- public static Object callMethod(Object o, String method, Object[] params)
- {
- // Get the objects class.
- Class cls = o.getClass();
-
- // Get the classes of the parameters.
- Class[] paramClasses = new Class[params.length];
-
- for (int i = 0; i < params.length; i++)
- {
- paramClasses[i] = params[i].getClass();
- }
-
- try
- {
- // Try to find the matching method on the class.
- Method m = cls.getMethod(method, paramClasses);
-
- // Invoke it with the parameters.
- return m.invoke(o, params);
- }
- catch (NoSuchMethodException e)
- {
- throw new ReflectionUtilsException("NoSuchMethodException.", e);
- }
- catch (IllegalAccessException e)
- {
- throw new ReflectionUtilsException("IllegalAccessException", e);
- }
- catch (InvocationTargetException e)
- {
- throw new ReflectionUtilsException("InvocationTargetException", e);
- }
- }
-
- /**
- * Calls a constuctor witht the specified arguments.
- *
- * @param constructor The constructor.
- * @param args The arguments.
- * @param <T> The Class type.
- *
- * @return An instance of the class that the constructor is for.
- */
- public static <T> T newInstance(Constructor<T> constructor, Object[] args)
- {
- try
- {
- return constructor.newInstance(args);
- }
- catch (InstantiationException e)
- {
- throw new ReflectionUtilsException("InstantiationException", e);
- }
- catch (IllegalAccessException e)
- {
- throw new ReflectionUtilsException("IllegalAccessException", e);
- }
- catch (InvocationTargetException e)
- {
- throw new ReflectionUtilsException("InvocationTargetException", e);
- }
- }
-
- /**
- * Gets the constructor of a class that takes the specified set of arguments if any matches. If no matching
- * constructor is found then a runtime exception is raised.
- *
- * @param cls The class to get a constructor from.
- * @param args The arguments to match.
- * @param <T> The class type.
- *
- * @return The constructor.
- */
- public static <T> Constructor<T> getConstructor(Class<T> cls, Class[] args)
- {
- try
- {
- return cls.getConstructor(args);
- }
- catch (NoSuchMethodException e)
- {
- throw new ReflectionUtilsException("NoSuchMethodException", e);
- }
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/utils/ReflectionUtilsException.java b/java/systests/src/main/java/org/apache/qpid/test/utils/ReflectionUtilsException.java
deleted file mode 100644
index 838828598b..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/utils/ReflectionUtilsException.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.utils;
-
-/**
- * Wraps a checked exception that occurs when {@link ReflectionUtils} encounters checked exceptions using standard
- * Java reflection methods.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Wrap a checked reflection exception.
- * </table>
- */
-public class ReflectionUtilsException extends RuntimeException
-{
- /**
- * Creates a runtime reflection exception, from a checked one.
- *
- * @param message The message.
- * @param cause The causing exception.
- */
- public ReflectionUtilsException(String message, Throwable cause)
- {
- super(message, cause);
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/test/utils/protocol/TestIoSession.java b/java/systests/src/main/java/org/apache/qpid/test/utils/protocol/TestIoSession.java
deleted file mode 100644
index f1eb8159b6..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/test/utils/protocol/TestIoSession.java
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.utils.protocol;
-
-import java.net.InetSocketAddress;
-import java.net.SocketAddress;
-
-import org.apache.mina.common.IoFilterChain;
-import org.apache.mina.common.IoHandler;
-import org.apache.mina.common.IoService;
-import org.apache.mina.common.IoServiceConfig;
-import org.apache.mina.common.IoSessionConfig;
-import org.apache.mina.common.TransportType;
-import org.apache.mina.common.support.BaseIoSession;
-
-public class TestIoSession extends BaseIoSession {
-
- private String _stringLocalAddress;
- private int _localPort;
-
- public SocketAddress getLocalAddress()
- {
- //create a new address for testing purposes using member variables
- return new InetSocketAddress(_stringLocalAddress,_localPort);
- }
-
- protected void updateTrafficMask() {
- //dummy
- }
-
- public IoService getService() {
- return null;
- }
-
- public IoServiceConfig getServiceConfig() {
- return null;
- }
-
- public IoHandler getHandler() {
- return null;
- }
-
- public IoSessionConfig getConfig() {
- return null;
- }
-
- public IoFilterChain getFilterChain() {
- return null;
- }
-
- public TransportType getTransportType() {
- return null;
- }
-
- public SocketAddress getRemoteAddress() {
- return null;
- }
-
- public SocketAddress getServiceAddress() {
- return null;
- }
-
- public int getScheduledWriteRequests() {
- return 0;
- }
-
- public int getScheduledWriteBytes() {
- return 0;
- }
-
- public String getStringLocalAddress() {
- return _stringLocalAddress;
- }
-
- public void setStringLocalAddress(String _stringLocalAddress) {
- this._stringLocalAddress = _stringLocalAddress;
- }
-
- public int getLocalPort() {
- return _localPort;
- }
-
- public void setLocalPort(int _localPort) {
- this._localPort = _localPort;
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/util/ClasspathScanner.java b/java/systests/src/main/java/org/apache/qpid/util/ClasspathScanner.java
deleted file mode 100644
index 8cae846a39..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/util/ClasspathScanner.java
+++ /dev/null
@@ -1,234 +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.util;
-
-import java.io.File;
-import java.util.*;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import org.apache.log4j.Logger;
-
-/**
- * An ClasspathScanner scans the classpath for classes that implement an interface or extend a base class and have names
- * that match a regular expression.
- *
- * <p/>In order to test whether a class implements an interface or extends a class, the class must be loaded (unless
- * the class files were to be scanned directly). Using this collector can cause problems when it scans the classpath,
- * because loading classes will initialize their statics, which in turn may cause undesired side effects. For this
- * reason, the collector should always be used with a regular expression, through which the class file names are
- * filtered, and only those that pass this filter will be tested. For example, if you define tests in classes that
- * end with the keyword "Test" then use the regular expression "Test$" to match this.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Find all classes matching type and name pattern on the classpath.
- * </table>
- *
- * @todo Add logic to scan jars as well as directories.
- */
-public class ClasspathScanner
-{
- private static final Logger log = Logger.getLogger(ClasspathScanner.class);
-
- /**
- * Scans the classpath and returns all classes that extend a specified class and match a specified name.
- * There is an flag that can be used to indicate that only Java Beans will be matched (that is, only those classes
- * that have a default constructor).
- *
- * @param matchingClass The class or interface to match.
- * @param matchingRegexp The regular expression to match against the class name.
- * @param beanOnly Flag to indicate that onyl classes with default constructors should be matched.
- *
- * @return All the classes that match this collector.
- */
- public static <T> Collection<Class<? extends T>> getMatches(Class<T> matchingClass, String matchingRegexp,
- boolean beanOnly)
- {
- log.debug("public static <T> Collection<Class<? extends T>> getMatches(Class<T> matchingClass = " + matchingClass
- + ", String matchingRegexp = " + matchingRegexp + ", boolean beanOnly = " + beanOnly + "): called");
-
- // Build a compiled regular expression from the pattern to match.
- Pattern matchPattern = Pattern.compile(matchingRegexp);
-
- String classPath = System.getProperty("java.class.path");
- Map<String, Class<? extends T>> result = new HashMap<String, Class<? extends T>>();
-
- log.debug("classPath = " + classPath);
-
- // Find matching classes starting from all roots in the classpath.
- for (String path : splitClassPath(classPath))
- {
- gatherFiles(new File(path), "", result, matchPattern, matchingClass);
- }
-
- return result.values();
- }
-
- /**
- * Finds all matching classes rooted at a given location in the file system. If location is a directory it
- * is recursively examined.
- *
- * @param classRoot The root of the current point in the file system being examined.
- * @param classFileName The name of the current file or directory to examine.
- * @param result The accumulated mapping from class names to classes that match the scan.
- *
- * @todo Recursion ok as file system depth is not likely to exhaust the stack. Might be better to replace with
- * iteration.
- */
- private static <T> void gatherFiles(File classRoot, String classFileName, Map<String, Class<? extends T>> result,
- Pattern matchPattern, Class<? extends T> matchClass)
- {
- log.debug("private static <T> void gatherFiles(File classRoot = " + classRoot + ", String classFileName = "
- + classFileName + ", Map<String, Class<? extends T>> result, Pattern matchPattern = " + matchPattern
- + ", Class<? extends T> matchClass = " + matchClass + "): called");
-
- File thisRoot = new File(classRoot, classFileName);
-
- // If the current location is a file, check if it is a matching class.
- if (thisRoot.isFile())
- {
- // Check that the file has a matching name.
- if (matchesName(thisRoot.getName(), matchPattern))
- {
- String className = classNameFromFile(thisRoot.getName());
-
- // Check that the class has matching type.
- try
- {
- Class<?> candidateClass = Class.forName(className);
-
- Class matchedClass = matchesClass(candidateClass, matchClass);
-
- if (matchedClass != null)
- {
- result.put(className, matchedClass);
- }
- }
- catch (ClassNotFoundException e)
- {
- // Ignore this. The matching class could not be loaded.
- log.debug("Got ClassNotFoundException, ignoring.", e);
- }
- }
-
- return;
- }
- // Otherwise the current location is a directory, so examine all of its contents.
- else
- {
- String[] contents = thisRoot.list();
-
- if (contents != null)
- {
- for (String content : contents)
- {
- gatherFiles(classRoot, classFileName + File.separatorChar + content, result, matchPattern, matchClass);
- }
- }
- }
- }
-
- /**
- * Checks if the specified class file name corresponds to a class with name matching the specified regular expression.
- *
- * @param classFileName The class file name.
- * @param matchPattern The regular expression pattern to match.
- *
- * @return <tt>true</tt> if the class name matches, <tt>false</tt> otherwise.
- */
- private static boolean matchesName(String classFileName, Pattern matchPattern)
- {
- String className = classNameFromFile(classFileName);
- Matcher matcher = matchPattern.matcher(className);
-
- return matcher.matches();
- }
-
- /**
- * Checks if the specified class to compare extends the base class being scanned for.
- *
- * @param matchingClass The base class to match against.
- * @param toMatch The class to match against the base class.
- *
- * @return The class to check, cast as an instance of the class to match if the class extends the base class, or
- * <tt>null</tt> otherwise.
- */
- private static <T> Class<? extends T> matchesClass(Class<?> matchingClass, Class<? extends T> toMatch)
- {
- try
- {
- return matchingClass.asSubclass(toMatch);
- }
- catch (ClassCastException e)
- {
- return null;
- }
- }
-
- /**
- * Takes a classpath (which is a series of paths) and splits it into its component paths.
- *
- * @param classPath The classpath to split.
- *
- * @return A list of the component paths that make up the class path.
- */
- private static List<String> splitClassPath(String classPath)
- {
- List<String> result = new LinkedList<String>();
- String separator = System.getProperty("path.separator");
- StringTokenizer tokenizer = new StringTokenizer(classPath, separator);
-
- while (tokenizer.hasMoreTokens())
- {
- result.add(tokenizer.nextToken());
- }
-
- return result;
- }
-
- /**
- * Translates from the filename of a class to its fully qualified classname. Files are named using forward slash
- * seperators and end in ".class", whereas fully qualified class names use "." sperators and no ".class" ending.
- *
- * @param classFileName The filename of the class to translate to a class name.
- *
- * @return The fully qualified class name.
- */
- private static String classNameFromFile(String classFileName)
- {
- log.debug("private static String classNameFromFile(String classFileName = " + classFileName + "): called");
-
- // Remove the .class ending.
- String s = classFileName.substring(0, classFileName.length() - ".class".length());
-
- // Turn / seperators in . seperators.
- String s2 = s.replace(File.separatorChar, '.');
-
- // Knock off any leading . caused by a leading /.
- if (s2.startsWith("."))
- {
- return s2.substring(1);
- }
-
- return s2;
- }
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/util/LogMonitor.java b/java/systests/src/main/java/org/apache/qpid/util/LogMonitor.java
deleted file mode 100644
index a5e2b80f64..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/util/LogMonitor.java
+++ /dev/null
@@ -1,238 +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.util;
-
-import org.apache.log4j.FileAppender;
-import org.apache.log4j.Logger;
-import org.apache.log4j.SimpleLayout;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.FileReader;
-import java.io.IOException;
-import java.io.OutputStreamWriter;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.LinkedList;
-
-/**
- * Utility to simplify the monitoring of Log4j file output
- *
- * Monitoring of a given log file can be done alternatively the Monitor will
- * add a new log4j FileAppender to the root Logger to gather all the available
- * logging for monitoring
- */
-public class LogMonitor
-{
- // The file that the log statements will be written to.
- private File _logfile;
-
- // The appender we added to the get messages
- private FileAppender _appender;
-
- /**
- * Create a new LogMonitor that creates a new Log4j Appender and monitors
- * all log4j output via the current configuration.
- *
- * @throws IOException if there is a problem creating the temporary file.
- */
- public LogMonitor() throws IOException
- {
- this(null);
- }
-
- /**
- * Create a new LogMonitor on the specified file if the file does not exist
- * or the value is null then a new Log4j appender will be added and
- * monitoring set up on that appender.
- *
- * NOTE: for the appender to receive any value the RootLogger will need to
- * have the level correctly configured.ng
- *
- * @param file the file to monitor
- *
- * @throws IOException if there is a problem creating a temporary file
- */
- public LogMonitor(File file) throws IOException
- {
- if (file != null && file.exists())
- {
- _logfile = file;
- }
- else
- {
- // This is mostly for running the test outside of the ant setup
- _logfile = File.createTempFile("LogMonitor", ".log");
- _appender = new FileAppender(new SimpleLayout(),
- _logfile.getAbsolutePath());
- _appender.setFile(_logfile.getAbsolutePath());
- _appender.setImmediateFlush(true);
- Logger.getRootLogger().addAppender(_appender);
- }
- }
-
- /**
- * Checks the log file for a given message to appear and returns all
- * instances of that appearance.
- *
- * @param message the message to wait for in the log
- * @param wait the time in ms to wait for the message to occur
- * @return true if the message was found
- *
- * @throws java.io.FileNotFoundException if the Log file can nolonger be found
- * @throws IOException thrown when reading the log file
- */
- public List<String> waitAndFindMatches(String message, long wait)
- throws FileNotFoundException, IOException
- {
- if (waitForMessage(message, wait, true))
- {
- return findMatches(message);
- }
- else
- {
- return new LinkedList<String>();
- }
- }
-
- /**
- * Checks the log for instances of the search string.
- *
- * The pattern parameter can take any valid argument used in String.contains()
- *
- * {@see String.contains(CharSequences)}
- *
- * @param pattern the search string
- *
- * @return a list of matching lines from the log
- *
- * @throws IOException if there is a problem with the file
- */
- public List<String> findMatches(String pattern) throws IOException
- {
- return FileUtils.searchFile(_logfile, pattern);
- }
-
- /**
- * Checks the log file for a given message to appear.
- *
- * @param message the message to wait for in the log
- * @param wait the time in ms to wait for the message to occur
- *
- * @param printFileOnFailure should we print the contents that have been
- * read if we fail ot find the message.
- * @return true if the message was found
- *
- * @throws java.io.FileNotFoundException if the Log file can nolonger be found
- * @throws IOException thrown when reading the log file
- */
- public boolean waitForMessage(String message, long wait, boolean printFileOnFailure)
- throws FileNotFoundException, IOException
- {
- // Loop through alerts until we're done or wait ms seconds have passed,
- // just in case the logfile takes a while to flush.
- BufferedReader reader = new BufferedReader(new FileReader(_logfile));
- boolean found = false;
- long endtime = System.currentTimeMillis() + wait;
- ArrayList<String> contents = new ArrayList<String>();
- while (!found && System.currentTimeMillis() < endtime)
- {
- while (reader.ready())
- {
- String line = reader.readLine();
- contents.add(line);
- if (line.contains(message))
- {
- found = true;
- }
- }
- }
- if (!found && printFileOnFailure)
- {
- for (String line : contents)
- {
- System.out.println(line);
- }
- }
- return found;
- }
-
-
- public boolean waitForMessage(String message, long alertLogWaitPeriod) throws FileNotFoundException, IOException
- {
- return waitForMessage(message, alertLogWaitPeriod, true);
- }
-
-
- /**
- * Read the log file in to memory as a String
- *
- * @return the current contents of the log file
- *
- * @throws java.io.FileNotFoundException if the Log file can nolonger be found
- * @throws IOException thrown when reading the log file
- */
- public String readFile() throws FileNotFoundException, IOException
- {
- return FileUtils.readFileAsString(_logfile);
- }
-
- /**
- * Return a File reference to the monitored file
- *
- * @return the file being monitored
- */
- public File getMonitoredFile()
- {
- return _logfile;
- }
-
- /**
- * Clears the log file and writes: 'Log Monitor Reset' at the start of the file
- *
- * @throws java.io.FileNotFoundException if the Log file can nolonger be found
- * @throws IOException thrown if there is a problem with the log file
- */
- public void reset() throws FileNotFoundException, IOException
- {
- new FileOutputStream(_logfile).getChannel().truncate(0);
- }
-
- /**
- * Stop monitoring this file.
- *
- * This is required to be called incase we added a new logger.
- *
- * If we don't call close then the new logger will continue to get log entries
- * after our desired test has finished.
- */
- public void close()
- {
- //Remove the custom appender we added for this logger
- if (_appender != null)
- {
- Logger.getRootLogger().removeAppender(_appender);
- }
- }
-
-}
diff --git a/java/systests/src/main/java/org/apache/qpid/util/LogMonitorTest.java b/java/systests/src/main/java/org/apache/qpid/util/LogMonitorTest.java
deleted file mode 100644
index a99abe4b94..0000000000
--- a/java/systests/src/main/java/org/apache/qpid/util/LogMonitorTest.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.util;
-
-import junit.framework.TestCase;
-import org.apache.log4j.Logger;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.List;
-
-public class LogMonitorTest extends TestCase
-{
-
- private LogMonitor _monitor;
-
- @Override
- public void setUp() throws Exception
- {
- _monitor = new LogMonitor();
- _monitor.getMonitoredFile().deleteOnExit(); // Make sure we clean up
- }
-
- /**
- * Test that a new file is created when attempting to set up a monitor with
- * the default constructor.
- */
- public void testMonitor()
- {
- //Validate that the monitor is now running on a new file
- assertTrue("New file does not have correct name:" + _monitor.
- getMonitoredFile().getName(),
- _monitor.getMonitoredFile().getName().contains("LogMonitor"));
- }
-
- /**
- * Test that creation of a monitor on an existing file is possible
- *
- * This also tests taht getMonitoredFile works
- *
- * @throws IOException if there is a problem creating the temporary file
- */
- public void testMonitorNormalFile() throws IOException
- {
- File testFile = File.createTempFile("testMonitorFile", ".log");
- testFile.deleteOnExit();
-
- //Ensure that we can create a monitor on a file
- try
- {
- _monitor = new LogMonitor(testFile);
- assertEquals(testFile, _monitor.getMonitoredFile());
- }
- catch (IOException ioe)
- {
- fail("IOE thrown:" + ioe);
- }
-
- }
-
- /**
- * Test that a new file is created when attempting to set up a monitor on
- * a null input value.
- */
- public void testMonitorNullFile()
- {
- // Validate that a NPE is thrown with null input
- try
- {
- LogMonitor montior = new LogMonitor(null);
- //Validte that the monitor is now running on a new file
- assertTrue("New file does not have correct name:" + montior.
- getMonitoredFile().getName(),
- montior.getMonitoredFile().getName().contains("LogMonitor"));
- }
- catch (IOException ioe)
- {
- fail("IOE thrown:" + ioe);
- }
- }
-
- /**
- * Test that a new file is created when attempting to set up a monitor on
- * a non existing file.
- *
- * @throws IOException if there is a problem setting up the nonexistent file
- */
- public void testMonitorNonExistentFile() throws IOException
- {
- //Validate that we get a FileNotFound if the file does not exist
-
- File nonexist = File.createTempFile("nonexist", ".out");
-
- assertTrue("Unable to delete file for our test", nonexist.delete());
-
- assertFalse("Unable to test as our test file exists.", nonexist.exists());
-
- try
- {
- LogMonitor montior = new LogMonitor(nonexist);
- //Validte that the monitor is now running on a new file
- assertTrue("New file does not have correct name:" + montior.
- getMonitoredFile().getName(),
- montior.getMonitoredFile().getName().contains("LogMonitor"));
- }
- catch (IOException ioe)
- {
- fail("IOE thrown:" + ioe);
- }
- }
-
- /**
- * Test that Log file matches logged messages.
- *
- * @throws java.io.IOException if there is a problem creating LogMontior
- */
- public void testFindMatches_Match() throws IOException
- {
-
- String message = getName() + ": Test Message";
-
- Logger.getRootLogger().warn(message);
-
- validateLogContainsMessage(_monitor, message);
- }
-
- /**
- * Test that Log file does not match a message not logged.
- *
- * @throws java.io.IOException if there is a problem creating LogMontior
- */
- public void testFindMatches_NoMatch() throws IOException
- {
- String message = getName() + ": Test Message";
-
- Logger.getRootLogger().warn(message);
-
- String notLogged = "This text was not logged";
-
- validateLogDoesNotContainsMessage(_monitor, notLogged);
- }
-
- public void testWaitForMessage_Timeout() throws IOException
- {
- String message = getName() + ": Test Message";
-
- long TIME_OUT = 2000;
-
- logMessageWithDelay(message, TIME_OUT);
-
- // Verify that we can time out waiting for a message
- assertFalse("Message was logged ",
- _monitor.waitForMessage(message, TIME_OUT / 2, false));
-
- // Verify that the message did eventually get logged.
- assertTrue("Message was never logged.",
- _monitor.waitForMessage(message, TIME_OUT));
- }
-
- public void testReset() throws IOException
- {
- String message = getName() + ": Test Message";
-
- Logger.getRootLogger().warn(message);
-
- validateLogContainsMessage(_monitor, message);
-
- String LOG_RESET_TEXT = "Log Monitor Reset";
-
- validateLogDoesNotContainsMessage(_monitor, LOG_RESET_TEXT);
-
- _monitor.reset();
-
- assertEquals("", _monitor.readFile());
- }
-
- public void testRead() throws IOException
- {
- String message = getName() + ": Test Message";
-
- Logger.getRootLogger().warn(message);
-
- String fileContents = _monitor.readFile();
-
- assertTrue("Logged message not found when reading file.",
- fileContents.contains(message));
- }
-
- /****************** Helpers ******************/
-
- /**
- * Validate that the LogMonitor does not match the given string in the log
- *
- * @param log The LogMonitor to check
- * @param message The message to check for
- *
- * @throws IOException if a problems occurs
- */
- protected void validateLogDoesNotContainsMessage(LogMonitor log, String message)
- throws IOException
- {
- List<String> results = log.findMatches(message);
-
- assertNotNull("Null results returned.", results);
-
- assertEquals("Incorrect result set size", 0, results.size());
- }
-
- /**
- * Validate that the LogMonitor can match the given string in the log
- *
- * @param log The LogMonitor to check
- * @param message The message to check for
- *
- * @throws IOException if a problems occurs
- */
- protected void validateLogContainsMessage(LogMonitor log, String message)
- throws IOException
- {
- List<String> results = log.findMatches(message);
-
- assertNotNull("Null results returned.", results);
-
- assertEquals("Incorrect result set size", 1, results.size());
-
- assertTrue("Logged Message'" + message + "' not present in results:"
- + results.get(0), results.get(0).contains(message));
- }
-
- /**
- * Create a new thread to log the given message after the set delay
- *
- * @param message the messasge to log
- * @param delay the delay (ms) to wait before logging
- */
- private void logMessageWithDelay(final String message, final long delay)
- {
- new Thread(new Runnable()
- {
-
- public void run()
- {
- try
- {
- Thread.sleep(delay);
- }
- catch (InterruptedException e)
- {
- //ignore
- }
-
- Logger.getRootLogger().warn(message);
- }
- }).start();
- }
-
-}
diff --git a/java/systests/src/main/java/systests.log4j b/java/systests/src/main/java/systests.log4j
deleted file mode 100644
index 6d596d1d19..0000000000
--- a/java/systests/src/main/java/systests.log4j
+++ /dev/null
@@ -1,28 +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.
-#
-log4j.rootLogger=${root.logging.level}
-
-
-log4j.logger.org.apache.qpid=${amqj.logging.level}, console
-log4j.additivity.org.apache.qpid=false
-
-log4j.appender.console=org.apache.log4j.ConsoleAppender
-log4j.appender.console.Threshold=all
-log4j.appender.console.layout=org.apache.log4j.PatternLayout
-log4j.appender.console.layout.ConversionPattern=%t %d %p [%c{4}] %m%n
diff --git a/java/tasks/src/org/apache/qpid/tasks/BaseTask.java b/java/tasks/src/org/apache/qpid/tasks/BaseTask.java
deleted file mode 100644
index be604b14cf..0000000000
--- a/java/tasks/src/org/apache/qpid/tasks/BaseTask.java
+++ /dev/null
@@ -1,74 +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.tasks;
-
-import org.apache.tools.ant.BuildException;
-import org.apache.tools.ant.Task;
-
-import java.util.HashSet;
-import java.util.Set;
-
-/**
- * BaseTask -- an abstract base task for blaze specific tasks.
- **/
-
-public abstract class BaseTask extends Task {
-
- private static Set EMPTY = new HashSet();
- {
- EMPTY.add(0);
- EMPTY.add("");
- }
-
- public static class Validator {
-
- private String name;
- private Object value;
-
- private Validator(String name, Object value) {
- this.name = name;
- this.value = value;
- }
-
- public Validator required() {
- if (value == null) {
- error("value is required");
- }
- return this;
- }
-
- public Validator nonempty() {
- if (EMPTY.contains(value)) {
- error("value is empty");
- }
- return this;
- }
-
- private void error(String msg) {
- throw new BuildException(name + ": " + msg);
- }
- }
-
- public Validator validate(String name, Object value) {
- return new Validator(name, value);
- }
-
-}
diff --git a/java/tasks/src/org/apache/qpid/tasks/Foreach.java b/java/tasks/src/org/apache/qpid/tasks/Foreach.java
deleted file mode 100644
index 91b8a25ce2..0000000000
--- a/java/tasks/src/org/apache/qpid/tasks/Foreach.java
+++ /dev/null
@@ -1,84 +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.tasks;
-
-import org.apache.tools.ant.BuildException;
-import org.apache.tools.ant.Task;
-import org.apache.tools.ant.TaskContainer;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Foreach -- an ant task that allows iteration.
- **/
-
-public class Foreach extends BaseTask implements TaskContainer {
-
- private String property;
- private String list;
- private String delim = "\\s+";
- private String stop;
- private List<Task> tasks = new ArrayList<Task>();
-
- public void setProperty(String p) {
- property = p;
- }
-
- public void setList(String l) {
- list = l;
- }
-
- public void setDelim(String d) {
- delim = d;
- }
-
- public void setStop(String s) {
- stop = s;
- }
-
- public void addTask(Task t) {
- tasks.add(t);
- }
-
- public void execute() {
- validate("property", property).required().nonempty();
- validate("list", property).required();
-
- if (list.length() == 0) {
- return;
- }
-
- String[] values = list.split(delim);
- for (int i = 0; i < values.length; i++) {
- String value = values[i];
- if (stop != null && stop.length() > 0 &&
- value.equals(stop)) {
- break;
- }
- getProject().setProperty(property, value);
- for (Task t : tasks) {
- t.perform();
- }
- }
- }
-
-}
diff --git a/java/tasks/src/org/apache/qpid/tasks/Map.java b/java/tasks/src/org/apache/qpid/tasks/Map.java
deleted file mode 100644
index e66f34b319..0000000000
--- a/java/tasks/src/org/apache/qpid/tasks/Map.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.tasks;
-
-import org.apache.tools.ant.BuildException;
-import org.apache.tools.ant.util.ChainedMapper;
-import org.apache.tools.ant.util.FileNameMapper;
-
-/** Map -- an ant task that allows arbitrary use of FileNameMappers */
-
-public class Map extends BaseTask {
-
- private String property;
- private String value;
- private String split = "\\s+";
- private String join = " ";
- private boolean setonempty = true;
- private ChainedMapper mapper = new ChainedMapper();
-
- public void setProperty(String p) {
- property = p;
- }
-
- public void setValue(String v) {
- value = v;
- }
-
- public void setSplit(String s) {
- split = s;
- }
-
- public void setJoin(String j) {
- join = j;
- }
-
- public void setSetonempty(boolean b) {
- setonempty = b;
- }
-
- public void add(FileNameMapper m) {
- mapper.add(m);
- }
-
- public void execute() {
- validate("property", property).required().nonempty();
- validate("value", value).required();
-
- if (mapper.getMappers().size() == 0) {
- throw new BuildException("at least one mapper must is required");
- }
-
- String[] parts = value.split(split);
- StringBuffer buf = new StringBuffer();
- for (int i = 0; i < parts.length; i++)
- {
- if (parts[i].length() == 0)
- {
- continue;
- }
- String[] names = mapper.mapFileName(parts[i]);
-
- //Mappers can return null.
- if (names != null)
- {
- for (int j = 0; j < names.length; j++)
- {
- if (buf.length() > 0)
- {
- buf.append(join);
- }
- buf.append(names[j]);
- }
- }
- }
-
- if (buf.length() > 0 || setonempty) {
- getProject().setNewProperty(property, buf.toString());
- }
- }
-
-}
diff --git a/java/tasks/src/org/apache/qpid/tasks/PropertyMapper.java b/java/tasks/src/org/apache/qpid/tasks/PropertyMapper.java
deleted file mode 100644
index cc741380fd..0000000000
--- a/java/tasks/src/org/apache/qpid/tasks/PropertyMapper.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.tasks;
-
-import org.apache.tools.ant.Project;
-import org.apache.tools.ant.util.GlobPatternMapper;
-
-public class PropertyMapper extends GlobPatternMapper
-{
-
- Project _project;
-
- public PropertyMapper(Project project)
- {
- super();
- _project = project;
- }
-
- public String[] mapFileName(String sourceFileName)
- {
- String[] fixed = super.mapFileName(sourceFileName);
-
- if (fixed == null)
- {
- return null;
- }
-
- return new String[]{ _project.getProperty(fixed[0]) };
- }
-
-
-}
diff --git a/java/tasks/src/org/apache/qpid/tasks/Require.java b/java/tasks/src/org/apache/qpid/tasks/Require.java
deleted file mode 100644
index 84870c90e4..0000000000
--- a/java/tasks/src/org/apache/qpid/tasks/Require.java
+++ /dev/null
@@ -1,80 +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.tasks;
-
-import org.apache.tools.ant.taskdefs.Ant;
-
-import java.io.File;
-import java.util.HashSet;
-import java.util.Set;
-
-/**
- * Require
- *
- * @author Rafael H. Schloming &lt;rhs@mit.edu&gt;
- **/
-
-public class Require extends BaseTask {
-
- private File file;
- private String target = "";
- private Ant ant = null;
- private String key = "";
-
- public void setFile(File f) {
- file = f;
- }
-
- public void setTarget(String t) {
- target = t;
- }
-
- public void setKey(String k) {
- key = k;
- }
-
- public void execute() {
- validate("file", file).required();
-
- String path = file.getAbsolutePath();
- String hash = Require.class.getName() + ":" +
- path + ":" + target + ":" + key;
-
- synchronized (System.class) {
- if (System.getProperty(hash) != null) {
- return;
- }
-
- Ant ant = (Ant) getProject().createTask("ant");
- ant.setInheritAll(false);
- ant.setOwningTarget(getOwningTarget());
- ant.setTaskName(getTaskName());
- ant.init();
- if (target.length() > 0) {
- ant.setTarget(target);
- }
- ant.setAntfile(path);
- ant.setDir(file.getParentFile());
- ant.execute();
-
- System.setProperty(hash, "done");
- }
- }
-
-}
diff --git a/java/test-profiles/08StandaloneExcludes b/java/test-profiles/08StandaloneExcludes
deleted file mode 100644
index 43eb1f8ee5..0000000000
--- a/java/test-profiles/08StandaloneExcludes
+++ /dev/null
@@ -1,41 +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.
-//
-
-//======================================================================
-//Exclude the following from brokers defaulting to the 0-8 protocol
-//======================================================================
-
-// This test requires a broker capable of 0-8/9 and 0-10
-org.apache.qpid.test.client.message.JMSDestinationTest#testReceiveResend
-
-// QPID-2478 test fails when run against broker using 0-8/9
-org.apache.qpid.test.client.message.JMSDestinationTest#testGetDestinationWithCustomExchange
-
-// The new addressing based sytanx is not supported for AMQP 0-8/0-9 versions
-org.apache.qpid.test.client.destination.AddressBasedDestinationTest#*
-org.apache.qpid.test.client.queue.QueuePolicyTest#testRingPolicy
-org.apache.qpid.test.client.queue.QueuePolicyTest#testRejectPolicy
-
-// Those tests are written against the 0.10 path
-org.apache.qpid.test.unit.message.UTF8Test#*
-org.apache.qpid.client.MessageListenerTest#testSynchronousReceiveNoWait
-
-org.apache.qpid.test.unit.client.connection.ConnectionTest#testUnsupportedSASLMechanism
-
-org.apache.qpid.test.unit.message.JMSPropertiesTest#testGetPropertyNames
diff --git a/java/test-profiles/CPPExcludes b/java/test-profiles/CPPExcludes
deleted file mode 100755
index 4127682208..0000000000
--- a/java/test-profiles/CPPExcludes
+++ /dev/null
@@ -1,175 +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.
-//
-
-org.apache.qpid.test.unit.client.channelclose.ChannelCloseTest#*
-org.apache.qpid.client.ResetMessageListenerTest#*
-
-// This test is not finished
-org.apache.qpid.test.testcases.TTLTest#*
-org.apache.qpid.test.client.failover.FailoverTest#test4MinuteFailover
-
-// Those tests are testing 0.8 specific semantics
-org.apache.qpid.test.testcases.ImmediateMessageTest#test_QPID_517_ImmediateFailsConsumerDisconnectedNoTxP2P
-org.apache.qpid.test.testcases.ImmediateMessageTest#test_QPID_517_ImmediateFailsConsumerDisconnectedTxP2P
-org.apache.qpid.test.testcases.ImmediateMessageTest#test_QPID_517_ImmediateFailsNoRouteNoTxP2P
-org.apache.qpid.test.testcases.ImmediateMessageTest#test_QPID_517_ImmediateFailsNoRouteTxP2P
-org.apache.qpid.test.testcases.ImmediateMessageTest#test_QPID_517_ImmediateFailsConsumerDisconnectedNoTxPubSub
-org.apache.qpid.test.testcases.ImmediateMessageTest#test_QPID_517_ImmediateFailsConsumerDisconnectedTxPubSub
-org.apache.qpid.test.testcases.ImmediateMessageTest#test_QPID_517_ImmediateFailsNoRouteNoTxPubSub
-org.apache.qpid.test.testcases.ImmediateMessageTest#test_QPID_517_ImmediateFailsNoRouteTxPubSub
-org.apache.qpid.test.testcases.MandatoryMessageTest#test_QPID_508_MandatoryFailsNoRouteNoTxP2P
-org.apache.qpid.test.testcases.MandatoryMessageTest#test_QPID_508_MandatoryFailsNoRouteTxP2P
-org.apache.qpid.test.testcases.MandatoryMessageTest#test_QPID_508_MandatoryFailsNoRouteNoTxPubSub
-org.apache.qpid.test.testcases.MandatoryMessageTest#test_QPID_508_MandatoryFailsNoRouteTxPubSub
-
-// the 0.10 c++ broker does not implement forget
-org.apache.qpid.test.unit.xa.FaultTest#testForget
-
-// the 0-10 c++ broker does not implement priority / this test depends on a Java broker extension for queue creation
-org.apache.qpid.server.queue.PriorityTest#*
-org.apache.qpid.server.queue.AMQPriorityQueueTest#*
-
-// the 0-10 c++ broker does not implement the extended LVQ semantics which the Java Broker does
-org.apache.qpid.server.queue.ConflationQueueTest#*
-
-//this test checks explicitly for 0-8 flow control semantics
-org.apache.qpid.test.client.FlowControlTest#*
-
-// 0-10 c++ broker doesn't implement virtual hosts, or those wackhy exchanges
-org.apache.qpid.test.unit.client.connection.ConnectionTest#testUnresolvedVirtualHostFailure
-org.apache.qpid.test.unit.client.connection.ConnectionTest#testDefaultExchanges
-
-// 0-10 c++ broker in cpp.testprofile is started with no auth so won't pass this test
-org.apache.qpid.test.unit.client.connection.ConnectionTest#testPasswordFailureConnection
-
-// c++ broker doesn't do selectors, so this will fail
-org.apache.qpid.test.unit.topic.TopicSessionTest#testNonMatchingMessagesDoNotFillQueue
-
-// InVM Broker tests
-org.apache.qpid.test.client.timeouts.SyncWaitDelayTest#*
-
-// QPID-1262, QPID-1119 : This test fails occasionally due to potential protocol issue.
-org.apache.qpid.test.client.timeouts.SyncWaitTimeoutDelayTest#*
-
-// c++ broker doesn't support message bouncing
-org.apache.qpid.server.exchange.ReturnUnroutableMandatoryMessageTest#*
-
-// c++ broker expires messages on delivery or when the queue cleaner thread runs.
-org.apache.qpid.server.queue.TimeToLiveTest#testActiveTTL
-org.apache.qpid.server.queue.TimeToLiveTest#testActiveTTLwithDurableSubscription
-
-// QPID-1727 , QPID-1726 :c++ broker does not support flow to disk on transient queues. Also it requries a persistent store impl. for Apache
-org.apache.qpid.test.client.QueueBrowsingFlowToDiskTest#*
-
-// This test currently does not pick up the runtime location of the nonVm queueBacking store.
-org.apache.qpid.test.unit.close.FlowToDiskBackingQueueDeleteTest#*
-
-// This test may use QpidTestCase but it is not using the getConnection and is hardwired to InVM
-org.apache.qpid.test.unit.client.connection.CloseAfterConnectionFailureTest#*
-
-//QPID-1818 : 0-10 Client code path does not correctly restore a transacted session after failover.
-org.apache.qpid.server.persistent.NoLocalAfterRecoveryTest#*
-
-// QPID-1730: the C++ server has a totally different logging mechanism. We should split this file differently
-org.apache.qpid.server.AlertingTest#*
-
-// The C++ server has a totally different persistence mechanism
-org.apache.qpid.server.store.PersistentStoreTest#*
-
-// These tests are for the Java broker persistent store modules
-org.apache.qpid.server.store.MessageStoreTest#testMessagePersistence
-org.apache.qpid.server.store.MessageStoreTest#testMessageRemoval
-org.apache.qpid.server.store.MessageStoreTest#testBindingPersistence
-org.apache.qpid.server.store.MessageStoreTest#testDurableBindingRemoval
-org.apache.qpid.server.store.MessageStoreTest#testQueuePersistence
-org.apache.qpid.server.store.MessageStoreTest#testDurableQueueRemoval
-org.apache.qpid.server.store.MessageStoreTest#testExchangePersistence
-org.apache.qpid.server.store.MessageStoreTest#testDurableExchangeRemoval
-
-// CPP Broker does not follow the same Logging convention as the Java broker
-org.apache.qpid.server.BrokerStartupTest#*
-org.apache.qpid.server.logging.*
-org.apache.qpid.server.logging.messages.*
-org.apache.qpid.server.logging.subjects.*
-org.apache.qpid.server.logging.actors.*
-
-// CPP Broker does not have a JMX interface to test
-org.apache.qpid.management.jmx.*
-org.apache.qpid.server.queue.AMQQueueMBeanTest#*
-org.apache.qpid.server.exchange.ExchangeMBeanTest#*
-org.apache.qpid.server.AMQBrokerManagerMBeanTest#*
-org.apache.qpid.server.protocol.AMQProtocolSessionMBeanTest#*
-
-// JMX is used in this test for validation
-org.apache.qpid.server.queue.ModelTest#*
-
-// 0-10 is not supported by the MethodRegistry
-org.apache.qpid.test.unit.close.JavaServerCloseRaceConditionTest#*
-
-// QPID-2084 : this test needs more work for 0-10
-org.apache.qpid.test.unit.client.DynamicQueueExchangeCreateTest#*
-
-// QPID-2118 : 0-10 Java client has differrent error handling to 0-8 code path
-org.apache.qpid.test.client.message.SelectorTest#testRuntimeSelectorError
-
-//QPID-942 : Implemented Channel.Flow based Producer Side flow control to the Java Broker (not in CPP Broker)
-org.apache.qpid.server.queue.ProducerFlowControlTest#*
-
-//QPID-1950 : Commit to test this failure. This is a MINA only failure so it cannot be tested when using 010.
-org.apache.qpid.server.failover.MessageDisappearWithIOExceptionTest#*
-
-// These are recent test additions that are failing with the c++ broker
-// Temporarily disabling until properly investigated.
-org.apache.qpid.test.unit.publish.DirtyTransactedPublishTest#*
-org.apache.qpid.test.unit.ack.FailoverBeforeConsumingRecoverTest#*
-
-org.apache.qpid.test.client.RollbackOrderTest#testOrderingAfterRollbackOnMessage#*
-
-// Temporarily adding the following until the issues are sorted out.
-org.apache.qpid.test.unit.client.AMQConnectionTest#testHeartBeat
-
-//Excluded due to QPID-1447 : CPP broker does not have SlowConsumer Disconnection
-org.apache.qpid.systest.GlobalQueuesTest#*
-org.apache.qpid.systest.GlobalTopicsTest#*
-org.apache.qpid.systest.MergeConfigurationTest#*
-org.apache.qpid.systest.SubscriptionTest#*
-org.apache.qpid.systest.TopicTest#*
-
-// Excluded because Java plugins not used in CPP broker
-org.apache.qpid.server.virtualhost.plugin.*
-org.apache.qpid.server.virtualhost.plugin.policies.*
-org.apache.qpid.info.systest.InfoPluginTest#*
-org.apache.qpid.info.test.*
-org.apache.qpid.server.security.access.*
-org.apache.qpid.server.security.access.plugins.*
-org.apache.qpid.server.security.acl.*
-org.apache.qpid.server.configuration.*
-org.apache.qpid.server.configuration.plugins.*
-org.apache.qpid.server.security.firewall.FirewallConfigTest#*
-org.apache.qpid.server.security.firewall.FirewallConfigurationTest#*
-org.apache.qpid.server.plugins.PluginTest#*
-
-// Transacion timeouts not implemented in CPP broker
-org.apache.qpid.test.unit.transacted.TransactionTimeoutDisabledTest#*
-org.apache.qpid.test.unit.transacted.TransactionTimeoutConfigurationTest#*
-org.apache.qpid.test.unit.transacted.TransactionTimeoutTest#*
-
-// Java broker only
-org.apache.qpid.server.logging.management.LoggingManagementMBeanTest#*
-org.apache.qpid.server.management.AMQUserManagementMBeanTest#*
diff --git a/java/test-profiles/CPPNoPrefetchExcludes b/java/test-profiles/CPPNoPrefetchExcludes
deleted file mode 100644
index ebcd430161..0000000000
--- a/java/test-profiles/CPPNoPrefetchExcludes
+++ /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.
-//
-
-org.apache.qpid.test.unit.transacted.TransactedTest#testRollback
-
-org.apache.qpid.test.client.QueueBrowserAutoAckTest#testFailoverWithQueueBrowser
-org.apache.qpid.test.client.QueueBrowserClientAckTest#testFailoverWithQueueBrowser
-org.apache.qpid.test.client.QueueBrowserDupsOkTest#testFailoverWithQueueBrowser
-org.apache.qpid.test.client.QueueBrowserNoAckTest#testFailoverWithQueueBrowser
-org.apache.qpid.test.client.QueueBrowserPreAckTest#testFailoverWithQueueBrowser
-org.apache.qpid.test.client.QueueBrowserTransactedTest#testFailoverWithQueueBrowser
-
-org.apache.qpid.test.unit.topic.DurableSubscriptionTest#testDurabilityNOACK
-org.apache.qpid.test.unit.topic.DurableSubscriptionTest#testDurabilityNOACKSessionPerConnection
-org.apache.qpid.test.unit.xa.TopicTest#testMigrateDurableSubscriber
diff --git a/java/test-profiles/CPPPrefetchExcludes b/java/test-profiles/CPPPrefetchExcludes
deleted file mode 100644
index 7ef52f89c7..0000000000
--- a/java/test-profiles/CPPPrefetchExcludes
+++ /dev/null
@@ -1,23 +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.
-//
-
-// those tests should be run with prefetch off
-org.apache.qpid.client.MessageListenerMultiConsumerTest#testRecieveC2Only
-org.apache.qpid.client.MessageListenerMultiConsumerTest#testRecieveBoth
-org.apache.qpid.test.unit.xa.TopicTest#testMigrateDurableSubscriber
diff --git a/java/test-profiles/CPPTransientExcludes b/java/test-profiles/CPPTransientExcludes
deleted file mode 100644
index 47f24db19c..0000000000
--- a/java/test-profiles/CPPTransientExcludes
+++ /dev/null
@@ -1,29 +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.
-//
-
-// those tests need durable subscribe states to be persisted
-org.apache.qpid.test.unit.topic.DurableSubscriptionTest#testDurSubRestoredAfterNonPersistentMessageSent
-
-// those tests require broker recovery
-org.apache.qpid.test.unit.ct.DurableSubscriberTest#*
-org.apache.qpid.test.unit.xa.TopicTest#testDurSubCrash
-org.apache.qpid.test.unit.xa.TopicTest#testMultiMessagesDurSubCrash
-org.apache.qpid.test.unit.xa.TopicTest#testRecover
-org.apache.qpid.test.unit.xa.QueueTest#testRecover
-org.apache.qpid.test.unit.xa.QueueTest#testSendAndRecover
diff --git a/java/test-profiles/Excludes b/java/test-profiles/Excludes
deleted file mode 100644
index ff6993fa0b..0000000000
--- a/java/test-profiles/Excludes
+++ /dev/null
@@ -1,53 +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.
-//
-
-org.apache.qpid.client.MultipleJCAProviderRegistrationTest#test
-// QPID-1715, QPID-1715 : Client Error Handling on close is still broken
-org.apache.qpid.server.queue.QueueCreateTest#testCreatePriorityString
-org.apache.qpid.server.queue.QueueCreateTest#testCreateFlowToDiskValidNoSize
-org.apache.qpid.server.queue.QueueCreateTest#testCreateFlowToDiskInvalid
-org.apache.qpid.server.queue.QueueCreateTest#testCreateFlowToDiskInvalidSize
-
-//
-// QPID-2031 : Broker is not cleanly shutdown by QpidTestCase
-//
-org.apache.qpid.server.logging.BrokerLoggingTest#testBrokerShutdownListeningTCPDefault
-org.apache.qpid.server.logging.BrokerLoggingTest#testBrokerShutdownListeningTCPSSL
-org.apache.qpid.server.logging.BrokerLoggingTest#testBrokerShutdownStopped
-org.apache.qpid.server.logging.VirtualHostLoggingTest#testVirtualhostClosure
-org.apache.qpid.server.logging.MemoryMessageStoreLoggingTest#testMessageStoreClose
-
-// QPID-XXX : Test fails to start external broker due to Derby Exception.
-org.apache.qpid.server.logging.DerbyMessageStoreLoggingTest#*
-
-// QPID-1816 : Client Ack has not been addressed
-org.apache.qpid.test.unit.ack.AcknowledgeAfterFailoverOnMessageTest#testDirtyClientAck
-org.apache.qpid.test.unit.ack.AcknowledgeAfterFailoverOnMessageTest#testClientAck
-org.apache.qpid.test.unit.ack.AcknowledgeAfterFailoverTest#testDirtyClientAck
-org.apache.qpid.test.unit.ack.AcknowledgeAfterFailoverTest#testClientAck
-
-
-// QPID-143 : Failover can occur between receive and ack but we don't stop the ack.
-// Just fully disable both tests as they are highlighting to many Java Client race conditions
-org.apache.qpid.test.unit.ack.AcknowledgeAfterFailoverOnMessageTest#*
-org.apache.qpid.test.unit.ack.AcknowledgeAfterFailoverTest#*
-
-// QPID-2418 : The queue backing the dur sub is not currently deleted at subscription change, so the test will fail.
-org.apache.qpid.test.unit.ct.DurableSubscriberTest#testResubscribeWithChangedSelectorAndRestart
-
diff --git a/java/test-profiles/Java010Excludes b/java/test-profiles/Java010Excludes
deleted file mode 100755
index c05aad0cb1..0000000000
--- a/java/test-profiles/Java010Excludes
+++ /dev/null
@@ -1,82 +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.
-//
-
-// Those tests are testing 0.8 specific semantics
-org.apache.qpid.test.testcases.ImmediateMessageTest#test_QPID_517_ImmediateFailsConsumerDisconnectedNoTxP2P
-org.apache.qpid.test.testcases.ImmediateMessageTest#test_QPID_517_ImmediateFailsConsumerDisconnectedTxP2P
-org.apache.qpid.test.testcases.ImmediateMessageTest#test_QPID_517_ImmediateFailsNoRouteNoTxP2P
-org.apache.qpid.test.testcases.ImmediateMessageTest#test_QPID_517_ImmediateFailsNoRouteTxP2P
-org.apache.qpid.test.testcases.ImmediateMessageTest#test_QPID_517_ImmediateFailsConsumerDisconnectedNoTxPubSub
-org.apache.qpid.test.testcases.ImmediateMessageTest#test_QPID_517_ImmediateFailsConsumerDisconnectedTxPubSub
-org.apache.qpid.test.testcases.ImmediateMessageTest#test_QPID_517_ImmediateFailsNoRouteNoTxPubSub
-org.apache.qpid.test.testcases.ImmediateMessageTest#test_QPID_517_ImmediateFailsNoRouteTxPubSub
-org.apache.qpid.test.testcases.MandatoryMessageTest#test_QPID_508_MandatoryFailsNoRouteNoTxP2P
-org.apache.qpid.test.testcases.MandatoryMessageTest#test_QPID_508_MandatoryFailsNoRouteTxP2P
-org.apache.qpid.test.testcases.MandatoryMessageTest#test_QPID_508_MandatoryFailsNoRouteNoTxPubSub
-org.apache.qpid.test.testcases.MandatoryMessageTest#test_QPID_508_MandatoryFailsNoRouteTxPubSub
-
-//this test checks explicitly for 0-8 flow control semantics
-org.apache.qpid.test.client.FlowControlTest#*
-
-// 0-10 protocol doesn't support message bouncing
-org.apache.qpid.server.exchange.ReturnUnroutableMandatoryMessageTest#*
-
-// QPID-1727 , QPID-1726 :c++ broker does not support flow to disk on transient queues. Also it requries a persistent store impl. for Apache
-org.apache.qpid.test.client.QueueBrowsingFlowToDiskTest#*
-
-// 0-10 and 0-9 connections dont generate the exact same logging due to protocol differences
-org.apache.qpid.server.logging.ChannelLoggingTest#testChannelStartsFlowStopped
-org.apache.qpid.server.logging.ChannelLoggingTest#testChannelStartConsumerFlowStarted
-org.apache.qpid.server.logging.SubscriptionLoggingTest#testSubscriptionSuspend
-
-// 0-10 Broker does not have a JMX connection MBean
-org.apache.qpid.management.jmx.ManagementActorLoggingTest#testConnectionCloseViaManagement
-org.apache.qpid.management.jmx.MessageConnectionStatisticsTest#*
-
-// 0-10 has different ideas about clientid and ownership of queues
-org.apache.qpid.server.queue.ModelTest#*
-
-// 0-10 is not supported by the MethodRegistry
-org.apache.qpid.test.unit.close.JavaServerCloseRaceConditionTest#*
-
-//QPID-942 : Implemented Channel.Flow based Producer Side flow control to the Java Broker (not in CPP Broker)
-org.apache.qpid.server.queue.ProducerFlowControlTest#*
-
-//QPID-1950 : Commit to test this failure. This is a MINA only failure so it cannot be tested when using 010.
-org.apache.qpid.server.failover.MessageDisappearWithIOExceptionTest#*
-
-//QPID-2471 : Issues with 0-10 recovery
-org.apache.qpid.test.unit.ack.RecoverTest#testRecoverInAutoAckListener
-org.apache.qpid.test.unit.ack.FailoverBeforeConsumingRecoverTest#testRecoverInAutoAckListener
-
-// Temporarily disabling until properly investigated.
-org.apache.qpid.test.unit.publish.DirtyTransactedPublishTest#*
-
-//rollback with subscriptions does not work in 0-10 yet
-org.apache.qpid.test.client.RollbackOrderTest#testOrderingAfterRollbackOnMessage
-org.apache.qpid.test.unit.ack.RecoverTest#testRecoverInAutoAckListener
-
-// This test uses 0-8 channel frames
-org.apache.qpid.test.unit.client.channelclose.ChannelCloseTest#*
-
-//Temporarily adding the following until the issues are sorted out.
-//Should probably raise JIRAs for them.
-org.apache.qpid.transport.network.mina.MINANetworkDriverTest#*
-org.apache.qpid.test.client.destination.AddressBasedDestinationTest#testCreateExchange
-org.apache.qpid.test.client.destination.AddressBasedDestinationTest#testBrowseMode
diff --git a/java/test-profiles/JavaExcludes b/java/test-profiles/JavaExcludes
deleted file mode 100644
index c38a250abc..0000000000
--- a/java/test-profiles/JavaExcludes
+++ /dev/null
@@ -1,54 +0,0 @@
-//
-// Licensed to the Apache Software Foundation (ASF) under one
-// or more contributor license agreements. See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership. The ASF licenses this file
-// to you under the Apache License, Version 2.0 (the
-// "License"); you may not use this file except in compliance
-// with the License. You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing,
-// software distributed under the License is distributed on an
-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations
-// under the License.
-//
-
-// Those tests are not finished
-org.apache.qpid.test.testcases.TTLTest#*
-org.apache.qpid.test.testcases.FailoverTest#*
-
-// This is a long running test so should exclude from normal runs
-org.apache.qpid.test.client.failover.FailoverTest#test4MinuteFailover
-
-//QPID-1818 : Client code path does not correctly restore a transacted session after failover.
-org.apache.qpid.server.persistent.NoLocalAfterRecoveryTest#*
-
-// QPID-1823: this takes ages to run
-org.apache.qpid.client.SessionCreateTest#*
-
-// related to QPID-2471. Temporarily disabling these tests until I figure out why they are failing with the Java broker.
-org.apache.qpid.test.unit.ack.RecoverTest#testRecoverResendsMsgs
-org.apache.qpid.test.unit.ack.RecoverTest#testRecoverResendsMsgsAckOnEarlier
-org.apache.qpid.test.unit.ack.RecoverTest#testAcknowledgePerConsumer
-org.apache.qpid.test.unit.ack.FailoverBeforeConsumingRecoverTest#testRecoverResendsMsgs
-org.apache.qpid.test.unit.ack.FailoverBeforeConsumingRecoverTest#testRecoverResendsMsgsAckOnEarlier
-org.apache.qpid.test.unit.ack.FailoverBeforeConsumingRecoverTest#testAcknowledgePerConsumer
-
-// related to QPID-2471. These are new test cases and fail with the Java broker.
-org.apache.qpid.test.unit.ack.RecoverTest#testOderingWithAsyncConsumer
-org.apache.qpid.test.unit.ack.RecoverTest#testOderingWithSyncConsumer
-org.apache.qpid.test.unit.ack.FailoverBeforeConsumingRecoverTest#testOderingWithAsyncConsumer
-org.apache.qpid.test.unit.ack.FailoverBeforeConsumingRecoverTest#testOderingWithSyncConsumer
-
-org.apache.qpid.test.client.queue.LVQTest#*
-
-// Session resume is not supported in the Java client
-org.apache.qpid.transport.ConnectionTest#testResumeNonemptyReplayBuffer
-
-//QPID-2845: The queue policy types used by the C++ broker are not currently supported by the Java broker
-org.apache.qpid.test.client.queue.QueuePolicyTest#testRingPolicy
-org.apache.qpid.test.client.queue.QueuePolicyTest#testRejectPolicy
diff --git a/java/test-profiles/JavaInVMExcludes b/java/test-profiles/JavaInVMExcludes
deleted file mode 100644
index 7960b28d81..0000000000
--- a/java/test-profiles/JavaInVMExcludes
+++ /dev/null
@@ -1,45 +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.
-//
-
-//======================================================================
-//Exclude the following tests when running the InVM default test profile
-//======================================================================
-
-// The FirewallPlugin only operates for TCP connections, the tests NO-OP when run InVM
-org.apache.qpid.server.security.firewall.FirewallConfigTest#*
-
-// This test requires a broker capable of 0-8/9 and 0-10
-org.apache.qpid.test.client.message.JMSDestinationTest#testReceiveResend
-
-// QPID-2478 test fails when run against broker using 0-8/9
-org.apache.qpid.test.client.message.JMSDestinationTest#testGetDestinationWithCustomExchange
-
-// related to QPID-2471. Temporarily disabling these tests until I figure out why they are failing with the Java broker.
-org.apache.qpid.test.unit.ack.RecoverTest#testRecoverResendsMsgs
-org.apache.qpid.test.unit.ack.RecoverTest#testRecoverResendsMsgsAckOnEarlier
-org.apache.qpid.test.unit.ack.RecoverTest#testAcknowledgePerConsumer
-
-// related to QPID-2471. These are new test cases and fail with the Java broker.
-org.apache.qpid.test.unit.ack.RecoverTest#testOderingWithAsyncConsumer
-org.apache.qpid.test.unit.ack.RecoverTest#testOderingWithSyncConsumer
-
-//The VM broker does not export the logging management JMX MBean
-org.apache.qpid.server.security.acl.ExternalAdminACLTest#*
-
-org.apache.qpid.test.unit.message.JMSPropertiesTest#testGetPropertyNames
diff --git a/java/test-profiles/JavaPersistentExcludes b/java/test-profiles/JavaPersistentExcludes
deleted file mode 100644
index 240f6dc330..0000000000
--- a/java/test-profiles/JavaPersistentExcludes
+++ /dev/null
@@ -1,21 +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.
-//
-
-//These tests require the MemoryMessageStore
-org.apache.qpid.server.logging.MemoryMessageStoreLoggingTest#*
diff --git a/java/test-profiles/JavaStandaloneExcludes b/java/test-profiles/JavaStandaloneExcludes
deleted file mode 100644
index d208a20d15..0000000000
--- a/java/test-profiles/JavaStandaloneExcludes
+++ /dev/null
@@ -1,55 +0,0 @@
-//
-// Licensed to the Apache Software Foundation (ASF) under one
-// or more contributor license agreements. See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership. The ASF licenses this file
-// to you under the Apache License, Version 2.0 (the
-// "License"); you may not use this file except in compliance
-// with the License. You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing,
-// software distributed under the License is distributed on an
-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations
-// under the License.
-//
-
-// This is a long running test so should exclude from normal runs
-org.apache.qpid.test.client.failover.FailoverTest#test4MinuteFailover
-
-// Those tests require failover support
-org.apache.qpid.test.client.QueueBrowserAutoAckTest#testFailoverAsQueueBrowserCreated
-org.apache.qpid.test.client.QueueBrowserAutoAckTest#testFailoverWithQueueBrowser
-org.apache.qpid.test.client.QueueBrowserClientAckTest#testFailoverAsQueueBrowserCreated
-org.apache.qpid.test.client.QueueBrowserClientAckTest#testFailoverWithQueueBrowser
-org.apache.qpid.test.client.QueueBrowserDupsOkTest#testFailoverAsQueueBrowserCreated
-org.apache.qpid.test.client.QueueBrowserDupsOkTest#testFailoverWithQueueBrowser
-org.apache.qpid.test.client.QueueBrowserNoAckTest#testFailoverAsQueueBrowserCreated
-org.apache.qpid.test.client.QueueBrowserNoAckTest#testFailoverWithQueueBrowser
-org.apache.qpid.test.client.QueueBrowserPreAckTest#testFailoverAsQueueBrowserCreated
-org.apache.qpid.test.client.QueueBrowserPreAckTest#testFailoverWithQueueBrowser
-org.apache.qpid.test.client.QueueBrowserTransactedTest#testFailoverAsQueueBrowserCreated
-org.apache.qpid.test.client.QueueBrowserTransactedTest#testFailoverWithQueueBrowser
-org.apache.qpid.test.testcases.FailoverTest#*
-org.apache.qpid.test.client.failover.FailoverTest#*
-
-// InVM Broker tests awaiting resolution of QPID-1103
-org.apache.qpid.test.client.timeouts.SyncWaitDelayTest#*
-org.apache.qpid.test.client.timeouts.SyncWaitTimeoutDelayTest#*
-
-// This test currently does not pick up the runtime location of the nonVm queueBacking store.
-org.apache.qpid.test.unit.close.FlowToDiskBackingQueueDeleteTest#*
-
-// This test may use QpidTestCase but it is not using the getConnection and is hardwired to InVM
-org.apache.qpid.test.unit.client.connection.CloseAfterConnectionFailureTest#*
-
-//QPID-1818 : Client code path does not correctly restore a transacted session after failover.
-org.apache.qpid.server.persistent.NoLocalAfterRecoveryTest#*
-
-// This test requires the standard configuration file for validation.
-// Excluding here does not reduce test coverage.
-org.apache.qpid.server.configuration.ServerConfigurationFileTest#*
-
diff --git a/java/test-profiles/JavaTransientExcludes b/java/test-profiles/JavaTransientExcludes
deleted file mode 100644
index 2ea46795d9..0000000000
--- a/java/test-profiles/JavaTransientExcludes
+++ /dev/null
@@ -1,32 +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.
-//
-
-//These tests require a persistent store
-org.apache.qpid.server.store.PersistentStoreTest#*
-
-org.apache.qpid.test.unit.ct.DurableSubscriberTest#*
-
-org.apache.qpid.server.store.MessageStoreTest#testMessagePersistence
-org.apache.qpid.server.store.MessageStoreTest#testMessageRemoval
-org.apache.qpid.server.store.MessageStoreTest#testBindingPersistence
-org.apache.qpid.server.store.MessageStoreTest#testDurableBindingRemoval
-org.apache.qpid.server.store.MessageStoreTest#testQueuePersistence
-org.apache.qpid.server.store.MessageStoreTest#testDurableQueueRemoval
-org.apache.qpid.server.store.MessageStoreTest#testExchangePersistence
-org.apache.qpid.server.store.MessageStoreTest#testDurableExchangeRemoval
diff --git a/java/test-profiles/XAExcludes b/java/test-profiles/XAExcludes
deleted file mode 100644
index 907864a730..0000000000
--- a/java/test-profiles/XAExcludes
+++ /dev/null
@@ -1,22 +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.
-//
-
-org.apache.qpid.test.unit.xa.QueueTest#*
-org.apache.qpid.test.unit.xa.TopicTest#*
-org.apache.qpid.test.unit.xa.FaultTest#*
diff --git a/java/test-profiles/clean-dir b/java/test-profiles/clean-dir
deleted file mode 100755
index 4d6141b4ab..0000000000
--- a/java/test-profiles/clean-dir
+++ /dev/null
@@ -1,25 +0,0 @@
-
-#!/bin/bash
-#
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-#
-#
-
-
-rm -rf $@; mkdir $@
diff --git a/java/test-profiles/cpp.async.excludes b/java/test-profiles/cpp.async.excludes
deleted file mode 100644
index d700538345..0000000000
--- a/java/test-profiles/cpp.async.excludes
+++ /dev/null
@@ -1,21 +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.
-//
-
-// the C++ broker doesn't guarantee the order of messages on recovery
-org.apache.qpid.test.unit.xa.TopicTest#testMultiMessagesDurSubCrash
diff --git a/java/test-profiles/cpp.async.testprofile b/java/test-profiles/cpp.async.testprofile
deleted file mode 100644
index c3d47f0ce6..0000000000
--- a/java/test-profiles/cpp.async.testprofile
+++ /dev/null
@@ -1,21 +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.
-#
-include=cpp
-profile.excludes=CPPPrefetchExcludes
-broker.modules=--load-module ${broker.module.store}
diff --git a/java/test-profiles/cpp.cluster.testprofile b/java/test-profiles/cpp.cluster.testprofile
deleted file mode 100644
index 22a082e85b..0000000000
--- a/java/test-profiles/cpp.cluster.testprofile
+++ /dev/null
@@ -1,28 +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.
-#
-include=cpp
-
-broker.modules=--load-module ${broker.module.cluster} --cluster-name cpp-java-test-cluster
-
-profile.excludes=XAExcludes CPPPrefetchExcludes CPPTransientExcludes
-
-profile.clustered=true
-profile.failoverMsgCount=10
-profile.failoverIterations=10
-profile.failoverRandomSeed=20080921
diff --git a/java/test-profiles/cpp.excludes b/java/test-profiles/cpp.excludes
deleted file mode 100644
index c8fae1797e..0000000000
--- a/java/test-profiles/cpp.excludes
+++ /dev/null
@@ -1,29 +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.
-//
-
-//======================================================================
-//Exclude the following tests when running all cpp test profilies
-//======================================================================
-
-// This test requires JMX interface to move messages
-org.apache.qpid.test.client.message.JMSDestinationTest#testMovedToQueue
-
-// This test requires a broker capable of 0-8/9 and 0-10
-org.apache.qpid.test.client.message.JMSDestinationTest#testReceiveResend
-
diff --git a/java/test-profiles/cpp.noprefetch.testprofile b/java/test-profiles/cpp.noprefetch.testprofile
deleted file mode 100644
index 4764cb576b..0000000000
--- a/java/test-profiles/cpp.noprefetch.testprofile
+++ /dev/null
@@ -1,21 +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.
-#
-include=cpp
-profile.excludes=CPPTransientExcludes CPPNoPrefetchExcludes
-max_prefetch=0
diff --git a/java/test-profiles/cpp.ssl.excludes b/java/test-profiles/cpp.ssl.excludes
deleted file mode 100644
index 4d499c57b9..0000000000
--- a/java/test-profiles/cpp.ssl.excludes
+++ /dev/null
@@ -1,20 +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.
-//
-
-#org.apache.qpid.test.client.failover.FailoverTest#*
diff --git a/java/test-profiles/cpp.ssl.testprofile b/java/test-profiles/cpp.ssl.testprofile
deleted file mode 100644
index bf71384835..0000000000
--- a/java/test-profiles/cpp.ssl.testprofile
+++ /dev/null
@@ -1,29 +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.
-#
-include=cpp
-
-broker.modules=--load-module ${broker.module.ssl} --ssl-cert-name localhost.localdomain --ssl-cert-password-file ${test.profiles}/test_resources/ssl/pfile --ssl-cert-db ${test.profiles}/test_resources/ssl/server_db/ --ssl-require-client-authentication --ssl-port @SSL_PORT
-
-profile.use_ssl=true
-broker.ready= Listening for SSL connections
-
-javax.net.ssl.keyStore=${test.profiles}/test_resources/ssl/keystore.jks
-javax.net.ssl.keyStorePassword=password
-javax.net.ssl.trustStore=${test.profiles}/test_resources/ssl/certstore.jks
-javax.net.ssl.trustStorePassword=password
diff --git a/java/test-profiles/cpp.testprofile b/java/test-profiles/cpp.testprofile
deleted file mode 100644
index 694e22f48c..0000000000
--- a/java/test-profiles/cpp.testprofile
+++ /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.
-#
-broker.version=0-10
-broker.language=cpp
-
-broker.dir=${project.root}/../cpp/src
-module.dir=${broker.dir}/.libs
-store.module.dir=${project.root}/../../cppStore/cpp/lib/.libs
-
-broker.executable=${broker.dir}/qpidd
-broker.module.ssl=${module.dir}/ssl.so
-broker.module.cluster=${module.dir}/cluster.so
-broker.module.store=${store.module.dir}/msgstore.so
-broker.stopped=Exception constructed
-
-broker.modules=
-broker.args=
-
-broker=${broker.executable} -p @PORT --data-dir ${build.data}/@PORT -t --auth no --no-module-dir ${broker.modules} ${broker.args}
-
-profile.excludes=CPPPrefetchExcludes CPPTransientExcludes
-test.excludes=Excludes CPPExcludes ${profile}.excludes ${profile.excludes} cpp.excludes
diff --git a/java/test-profiles/default.testprofile b/java/test-profiles/default.testprofile
deleted file mode 100644
index df8148f787..0000000000
--- a/java/test-profiles/default.testprofile
+++ /dev/null
@@ -1,61 +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.
-#
-java.naming.factory.initial=org.apache.qpid.jndi.PropertiesFileInitialContextFactory
-java.naming.provider.url=${test.profiles}/test-provider.properties
-
-broker.version=0-8
-broker=vm
-broker.clean=${test.profiles}/clean-dir ${build.data} ${project.root}/build/work
-broker.ready=Listening on TCP port
-broker.start=${test.profiles}/start-broker
-broker.kill=${test.profiles}/kill-broker
-broker.config=${project.root}/build/etc/config-systests.xml
-messagestore.class.name=org.apache.qpid.server.store.MemoryMessageStore
-
-max_prefetch=1000
-qpid.dest_syntax=BURL
-
-log=debug
-amqj.logging.level=${log}
-amqj.server.logging.level=${log}
-amqj.protocol.logging.level=${log}
-root.logging.level=warn
-log4j.configuration=file:///${test.profiles}/log4j-test.xml
-log4j.debug=false
-
-# Note test-provider.properties also has variables of same name.
-# Keep in sync
-test.port=15672
-test.mport=18999
-#Note : Management will start open second port on: mport + 100 : 19099
-test.port.ssl=15671
-test.port.alt=25672
-test.port.alt.ssl=25671
-
-test.exclude=true
-profile.excludes=JavaTransientExcludes JavaInVMExcludes 08StandaloneExcludes
-test.excludes=Excludes XAExcludes JavaExcludes ${profile}.excludes ${profile.excludes}
-test.fork=no
-test.mem=512M
-test=*Test
-haltonfailure=no
-haltonerror=no
-exclude.modules=none
-
-profile.clustered=false
diff --git a/java/test-profiles/java-derby.0.10.testprofile b/java/test-profiles/java-derby.0.10.testprofile
deleted file mode 100644
index ca9115d30d..0000000000
--- a/java/test-profiles/java-derby.0.10.testprofile
+++ /dev/null
@@ -1,29 +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.
-#
-broker.language=java
-broker.version=0-10
-broker=${project.root}/build/bin/qpid-server -p @PORT -m @MPORT -c @CONFIG_FILE -l ${test.profiles}/log4j-test.xml
-broker.clean=${test.profiles}/clean-dir ${build.data} ${project.root}/build/work
-broker.ready=BRK-1004
-broker.stopped=Exception
-broker.config=${project.root}/build/etc/config-systests-derby.xml
-messagestore.class.name=org.apache.qpid.server.store.DerbyMessageStore
-profile.excludes=JavaStandaloneExcludes JavaPersistentExcludes Java010Excludes
-broker.clean.between.tests=true
-broker.persistent=true
diff --git a/java/test-profiles/java-derby.testprofile b/java/test-profiles/java-derby.testprofile
deleted file mode 100644
index d22e35f07e..0000000000
--- a/java/test-profiles/java-derby.testprofile
+++ /dev/null
@@ -1,33 +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.
-#
-broker.language=java
-broker=${project.root}/build/bin/qpid-server -p @PORT -m @MPORT --exclude-0-10 @PORT -c @CONFIG_FILE -l ${test.profiles}/log4j-test.xml
-broker.clean=${test.profiles}/clean-dir ${build.data} ${project.root}/build/work
-broker.ready=BRK-1004
-broker.stopped=Exception
-broker.config=${project.root}/build/etc/config-systests-derby.xml
-messagestore.class.name=org.apache.qpid.server.store.DerbyMessageStore
-profile.excludes=JavaStandaloneExcludes JavaPersistentExcludes 08StandaloneExcludes
-broker.clean.between.tests=true
-broker.persistent=true
-#
-# Do not enable. Allow client to attempt 0-10 and negotiate downwards
-#
-#qpid.amqp.version=0-91
-
diff --git a/java/test-profiles/java.0.10.testprofile b/java/test-profiles/java.0.10.testprofile
deleted file mode 100644
index fa87b22e92..0000000000
--- a/java/test-profiles/java.0.10.testprofile
+++ /dev/null
@@ -1,26 +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.
-#
-broker.language=java
-broker.version=0-10
-broker=${project.root}/build/bin/qpid-server -p @PORT -m @MPORT -c @CONFIG_FILE -l ${test.profiles}/log4j-test.xml
-broker.clean=${test.profiles}/clean-dir ${build.data} ${project.root}/build/work
-broker.ready=BRK-1004
-broker.stopped=Exception
-
-profile.excludes=JavaTransientExcludes JavaStandaloneExcludes Java010Excludes
diff --git a/java/test-profiles/java.testprofile b/java/test-profiles/java.testprofile
deleted file mode 100644
index c8c776d3e1..0000000000
--- a/java/test-profiles/java.testprofile
+++ /dev/null
@@ -1,28 +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.
-#
-broker.language=java
-broker=${project.root}/build/bin/qpid-server -p @PORT -m @MPORT --exclude-0-10 @PORT -c @CONFIG_FILE -l ${test.profiles}/log4j-test.xml
-broker.clean=${test.profiles}/clean-dir ${build.data} ${project.root}/build/work
-broker.ready=BRK-1004
-broker.stopped=Exception
-#
-# Do not enable. Allow client to attempt 0-10 and negotiate downwards
-#
-#qpid.amqp.version=0-91
-profile.excludes=JavaTransientExcludes JavaStandaloneExcludes 08StandaloneExcludes
diff --git a/java/test-profiles/kill-broker b/java/test-profiles/kill-broker
deleted file mode 100755
index 8078fa755e..0000000000
--- a/java/test-profiles/kill-broker
+++ /dev/null
@@ -1,26 +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.
-#
-#
-
-kill -CONT $1
-kill -9 $1
-rm /tmp/broker.log
diff --git a/java/test-profiles/log4j-test.xml b/java/test-profiles/log4j-test.xml
deleted file mode 100644
index 9adfd68202..0000000000
--- a/java/test-profiles/log4j-test.xml
+++ /dev/null
@@ -1,70 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<!--
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
--->
-
-<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
-
-<!-- ===================================================================== -->
-<!-- -->
-<!-- Log4j configuration for unit tests -->
-<!-- -->
-<!-- ===================================================================== -->
-
-<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
- <appender name="console" class="org.apache.log4j.ConsoleAppender">
- <param name="Target" value="System.out"/>
- <param name="ImmediateFlush" value="true"/>
- <layout class="org.apache.log4j.PatternLayout">
- <param name="ConversionPattern" value="%t %d %p [%c{4}] %m%n"/>
- </layout>
- </appender>
-
- <logger name="org.apache.qpid">
- <level value="${amqj.logging.level}"/>
- </logger>
-
- <logger name="qpid.message">
- <level value="INFO"/>
- </logger>
-
- <logger name="qpid.protocol">
- <level value="${amqj.protocol.logging.level}"/>
- </logger>
-
- <logger name="org.apache.qpid.test.utils.QpidTestCase">
- <level value="ALL"/>
- </logger>
-
- <logger name="org.apache.commons">
- <level value="WARN"/>
- </logger>
-
- <logger name="apache.commons.configuration.ConfigurationFactory">
- <level value="ERROR"/>
- </logger>
-
- <logger name="org.apache.qpid.server.virtualhost.VirtualHostImpl$1HouseKeepingTask">
- <level value="WARN"/>
- </logger>
-
- <root>
- <level value="${root.logging.level}"/>
- <appender-ref ref="console" />
- </root>
-</log4j:configuration>
diff --git a/java/test-profiles/start-broker b/java/test-profiles/start-broker
deleted file mode 100755
index e0bbb89d87..0000000000
--- a/java/test-profiles/start-broker
+++ /dev/null
@@ -1,37 +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.
-#
-#
-
-# The entire broker command is passed as an argument.
-
-waitfor() {
- until grep -a -l "$2" $1 >/dev/null 2>&1
- do
- if [ $count == 10 ]; then return; fi;
- sleep 1 ;
- count=`expr $count + 1`;
- done
- }
-
-sh $BROKER_CMD --log-to-file /tmp/broker.log &
-waitfor /tmp/broker.log $BROKER_READY
-
diff --git a/java/test-profiles/test-provider.properties b/java/test-profiles/test-provider.properties
deleted file mode 100644
index 8cea012c1d..0000000000
--- a/java/test-profiles/test-provider.properties
+++ /dev/null
@@ -1,51 +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.
-#
-#
-
-# Copied from default.testprofile
-test.port=15672
-test.mport=18999
-#Note : Java Management will start open second port on: mport + 100 : 19099
-test.port.ssl=15671
-test.port.alt=25672
-test.port.alt.ssl=25671
-
-
-connectionfactory.default = amqp://username:password@clientid/test?brokerlist='tcp://localhost:${test.port}'
-connectionfactory.default.ssl = amqp://username:password@clientid/test?brokerlist='tcp://localhost:${test.port.ssl}?ssl='true''
-connectionfactory.default.vm = amqp://username:password@clientid/test?brokerlist='vm://:1'
-
-connectionfactory.failover = amqp://username:password@clientid/test?brokerlist='tcp://localhost:${test.port.alt};tcp://localhost:${test.port}'&sync_ack='true'&sync_publish='all'&failover='roundrobin?cyclecount='20''
-connectionfactory.failover.ssl = amqp://username:password@clientid/test?brokerlist='tcp://localhost:${test.port.alt.ssl}?ssl='true';tcp://localhost:${test.port.ssl}?ssl='true''&sync_ack='true'&sync_publish='all'&failover='roundrobin?cyclecount='20''
-connectionfactory.failover.vm = amqp://username:password@clientid/test?brokerlist='vm://:2;vm://:1'&failover='roundrobin?cyclecount='20''
-
-connectionfactory.connection1 = amqp://username:password@clientid/test?brokerlist='tcp://localhost:${test.port}'
-connectionfactory.connection2 = amqp://username:password@clientid/test?brokerlist='tcp://localhost:${test.port.alt}'
-connectionfactory.connection1.vm = amqp://username:password@clientid/test?brokerlist='vm://:1'
-connectionfactory.connection2.vm = amqp://username:password@clientid/test?brokerlist='vm://:2'
-
-
-queue.MyQueue = example.MyQueue
-queue.queue = example.queue
-queue.xaQueue = xaQueue
-
-topic.topic = topic
-topic.xaTopic = xaTopic
-topic.durableSubscriberTopic = durableSubscriberTopic
diff --git a/java/test-profiles/test_resources/ssl/CA_db/cert8.db b/java/test-profiles/test_resources/ssl/CA_db/cert8.db
deleted file mode 100644
index 846e59e82d..0000000000
--- a/java/test-profiles/test_resources/ssl/CA_db/cert8.db
+++ /dev/null
Binary files differ
diff --git a/java/test-profiles/test_resources/ssl/CA_db/key3.db b/java/test-profiles/test_resources/ssl/CA_db/key3.db
deleted file mode 100644
index dd60e1e05e..0000000000
--- a/java/test-profiles/test_resources/ssl/CA_db/key3.db
+++ /dev/null
Binary files differ
diff --git a/java/test-profiles/test_resources/ssl/CA_db/rootca.crt b/java/test-profiles/test_resources/ssl/CA_db/rootca.crt
deleted file mode 100644
index d9cdd9891c..0000000000
--- a/java/test-profiles/test_resources/ssl/CA_db/rootca.crt
+++ /dev/null
@@ -1,13 +0,0 @@
------BEGIN CERTIFICATE-----
-MIICDDCCAXWgAwIBAgIFAJBNP3QwDQYJKoZIhvcNAQEFBQAwQTELMAkGA1UEBhMC
-Q0ExEDAOBgNVBAgTB09udGFyaW8xDTALBgNVBAoTBEFDTUUxETAPBgNVBAMTCE15
-Um9vdENBMB4XDTEwMDMyMjIxMDAyMloXDTE1MDMyMjIxMDAyMlowQTELMAkGA1UE
-BhMCQ0ExEDAOBgNVBAgTB09udGFyaW8xDTALBgNVBAoTBEFDTUUxETAPBgNVBAMT
-CE15Um9vdENBMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDICe+SkXU9NRCk
-s+Tmai/j+3uDfJ4mVEt4PRkRWTVVHvuMvbPfKhdBRYRM5wmQmSCOi25Xd9jnh3PF
-BwE+pfaSgVqQiilUYqYak56ZR1Ll0nGwyXZQnW3lTf9VboEl0p67qckcd8SmaJf2
-0lAlTu2W7kJ8whYYyYRqaw+3yA6dGQIDAQABoxAwDjAMBgNVHRMEBTADAQH/MA0G
-CSqGSIb3DQEBBQUAA4GBADUbCNoxvFbPv+vqfQJ59p8P0cArEPajHR51omE1BbLc
-TfouOIidiBORf1n8DzE7k2Pf//nUHWhJLBP7J7CMs18UYsDD+0aa9A3BZi4wcsYX
-AW9EiXAIhnCk2+yyZyI1gdOnRS/9aOBRFSa1ngCb9GLm4kFzakiDQ1iX7k9dk17p
------END CERTIFICATE-----
diff --git a/java/test-profiles/test_resources/ssl/CA_db/secmod.db b/java/test-profiles/test_resources/ssl/CA_db/secmod.db
deleted file mode 100644
index a13e3e602c..0000000000
--- a/java/test-profiles/test_resources/ssl/CA_db/secmod.db
+++ /dev/null
Binary files differ
diff --git a/java/test-profiles/test_resources/ssl/app1.crt b/java/test-profiles/test_resources/ssl/app1.crt
deleted file mode 100644
index c04b07fce8..0000000000
--- a/java/test-profiles/test_resources/ssl/app1.crt
+++ /dev/null
@@ -1,15 +0,0 @@
------BEGIN CERTIFICATE-----
-MIICPjCCAaegAwIBAgIFAJJRUVUwDQYJKoZIhvcNAQEFBQAwQTELMAkGA1UEBhMC
-Q0ExEDAOBgNVBAgTB09udGFyaW8xDTALBgNVBAoTBEFDTUUxETAPBgNVBAMTCE15
-Um9vdENBMB4XDTEwMTAxNDAyMzM1NloXDTE1MTAxNDAyMzM1NlowYTELMAkGA1UE
-BhMCQ0ExCzAJBgNVBAgTAk9OMRAwDgYDVQQHEwdUb3JvbnRvMQ0wCwYDVQQKEwRh
-Y21lMQwwCgYDVQQLEwNhcnQxFjAUBgNVBAMMDWFwcDFAYWNtZS5vcmcwgZ8wDQYJ
-KoZIhvcNAQEBBQADgY0AMIGJAoGBAIlYzFnmAsv/Ci4rgp3sWwkFGFYEBwiXx0Xz
-auZ10nrOUz6Ce2FGVQBYFA09zi79iUyn86oLuTY0Kc/1emCZEPkmOW+hw1uk/TxG
-5MqpEOZdsDv4xIqBHgtWv/d3kGubwSS5lia1l6EPvnzHvsQSM//xhkrJaF0fAHx5
-FMkilnvfAgMBAAGjIjAgMAkGA1UdEwQCMAAwEwYDVR0lBAwwCgYIKwYBBQUHAwIw
-DQYJKoZIhvcNAQEFBQADgYEAJ47Q/4/hJMwTTpfcojv9KbZUTrve/wkabUrytNf3
-ogqhaIzgUr+vA9EMBc91Jg1WJC/0VMmTrTEggqrgd/prg4xcyATQOwNR1TiaWC4E
-r3pWEpZZnEJSd4vtcciNFNsbuAt2m4Nc90gPNXKgNoe0+3nuxPLs/TIauwOSDF+I
-oiw=
------END CERTIFICATE-----
diff --git a/java/test-profiles/test_resources/ssl/app1.req b/java/test-profiles/test_resources/ssl/app1.req
deleted file mode 100644
index b4f1ff9a2c..0000000000
--- a/java/test-profiles/test_resources/ssl/app1.req
+++ /dev/null
@@ -1,10 +0,0 @@
------BEGIN NEW CERTIFICATE REQUEST-----
-MIIBoTCCAQoCAQAwYTELMAkGA1UEBhMCQ0ExCzAJBgNVBAgTAk9OMRAwDgYDVQQHEwdUb3JvbnRv
-MQ0wCwYDVQQKEwRhY21lMQwwCgYDVQQLEwNhcnQxFjAUBgNVBAMMDWFwcDFAYWNtZS5vcmcwgZ8w
-DQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAIlYzFnmAsv/Ci4rgp3sWwkFGFYEBwiXx0XzauZ10nrO
-Uz6Ce2FGVQBYFA09zi79iUyn86oLuTY0Kc/1emCZEPkmOW+hw1uk/TxG5MqpEOZdsDv4xIqBHgtW
-v/d3kGubwSS5lia1l6EPvnzHvsQSM//xhkrJaF0fAHx5FMkilnvfAgMBAAGgADANBgkqhkiG9w0B
-AQQFAAOBgQADKx89mTCGIbrCE6lICLYDexGxexeaZaUDq7YgtyXVIs2wcVGcZJGolUARopMWgE+y
-ryHTC4nvNCaBULyXGrzwPfzTJaVBiY4V5BoTrmz6Ofd73ZO6ZYNhy9bVLrb5VtDyldCj0EWz2lBe
-+OzVUeII5KPopRtzXpMH3sB2OredUg==
------END NEW CERTIFICATE REQUEST-----
diff --git a/java/test-profiles/test_resources/ssl/app2.crt b/java/test-profiles/test_resources/ssl/app2.crt
deleted file mode 100644
index 5c889a4c31..0000000000
--- a/java/test-profiles/test_resources/ssl/app2.crt
+++ /dev/null
@@ -1,15 +0,0 @@
------BEGIN CERTIFICATE-----
-MIICPjCCAaegAwIBAgIFAJJRUXgwDQYJKoZIhvcNAQEFBQAwQTELMAkGA1UEBhMC
-Q0ExEDAOBgNVBAgTB09udGFyaW8xDTALBgNVBAoTBEFDTUUxETAPBgNVBAMTCE15
-Um9vdENBMB4XDTEwMTAxNDAyMzQxNVoXDTE1MTAxNDAyMzQxNVowYTELMAkGA1UE
-BhMCQ0ExCzAJBgNVBAgTAk9OMRAwDgYDVQQHEwdUb3JvbnRvMQ0wCwYDVQQKEwRh
-Y21lMQwwCgYDVQQLEwNhcnQxFjAUBgNVBAMMDWFwcDJAYWNtZS5vcmcwgZ8wDQYJ
-KoZIhvcNAQEBBQADgY0AMIGJAoGBAJcIo3TSYxDa1OfmnDEP4qzLxmgyXC3n0Evu
-2nJz0s5zljjItnwJ9UpOkYh/PQcpUWoM+qKeZYadXbGhp8M8nMrJtUPOAKgDmF6A
-DKS9WL7u8kVCcEvBzLRD7bftEm2IPaRu72wOQai76hj11rYWHHkdAPem+C4ODqVn
-y2NN3zDnAgMBAAGjIjAgMAkGA1UdEwQCMAAwEwYDVR0lBAwwCgYIKwYBBQUHAwIw
-DQYJKoZIhvcNAQEFBQADgYEAc5FG8sDbK+i1703rJEwjJ9dCVXljN2jYL1sGXO2o
-9O5Da0zKcQ+OMhLJUoJf38pJw+maYhtT0fKFLItXP/rlyWlaGRBjkcZjOZ2D/Hg5
-/8pEVwiyTYRoEnGKRawnedIbEyBAcgtnlbkTFWXtQmnmgVApSzTpALRn5/jUC1PU
-Y3g=
------END CERTIFICATE-----
diff --git a/java/test-profiles/test_resources/ssl/app2.req b/java/test-profiles/test_resources/ssl/app2.req
deleted file mode 100644
index 53f3494168..0000000000
--- a/java/test-profiles/test_resources/ssl/app2.req
+++ /dev/null
@@ -1,10 +0,0 @@
------BEGIN NEW CERTIFICATE REQUEST-----
-MIIBoTCCAQoCAQAwYTELMAkGA1UEBhMCQ0ExCzAJBgNVBAgTAk9OMRAwDgYDVQQHEwdUb3JvbnRv
-MQ0wCwYDVQQKEwRhY21lMQwwCgYDVQQLEwNhcnQxFjAUBgNVBAMMDWFwcDJAYWNtZS5vcmcwgZ8w
-DQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAJcIo3TSYxDa1OfmnDEP4qzLxmgyXC3n0Evu2nJz0s5z
-ljjItnwJ9UpOkYh/PQcpUWoM+qKeZYadXbGhp8M8nMrJtUPOAKgDmF6ADKS9WL7u8kVCcEvBzLRD
-7bftEm2IPaRu72wOQai76hj11rYWHHkdAPem+C4ODqVny2NN3zDnAgMBAAGgADANBgkqhkiG9w0B
-AQQFAAOBgQAGNtSvXwdyujmMTaVQj2M2jZkgnVFtMBjDDmdz+wgzu8fKaej7e+fJi5owf31wJUUP
-0Zi/6mBNj+blmqHjNQ9U3w9Rns0z3+1DbO3Yj48d75IuxQJJd+lXXjCFi2qSBhaNUwyOpzaI1AQo
-JJTC1/WMaPENU9bgYYsOrmIhnbt5rQ==
------END NEW CERTIFICATE REQUEST-----
diff --git a/java/test-profiles/test_resources/ssl/certstore.jks b/java/test-profiles/test_resources/ssl/certstore.jks
deleted file mode 100644
index 2af95f21f8..0000000000
--- a/java/test-profiles/test_resources/ssl/certstore.jks
+++ /dev/null
Binary files differ
diff --git a/java/test-profiles/test_resources/ssl/keystore.jks b/java/test-profiles/test_resources/ssl/keystore.jks
deleted file mode 100644
index e3a850a248..0000000000
--- a/java/test-profiles/test_resources/ssl/keystore.jks
+++ /dev/null
Binary files differ
diff --git a/java/test-profiles/test_resources/ssl/pfile b/java/test-profiles/test_resources/ssl/pfile
deleted file mode 100644
index f3097ab130..0000000000
--- a/java/test-profiles/test_resources/ssl/pfile
+++ /dev/null
@@ -1 +0,0 @@
-password
diff --git a/java/test-profiles/test_resources/ssl/server_db/cert8.db b/java/test-profiles/test_resources/ssl/server_db/cert8.db
deleted file mode 100644
index d55f529c52..0000000000
--- a/java/test-profiles/test_resources/ssl/server_db/cert8.db
+++ /dev/null
Binary files differ
diff --git a/java/test-profiles/test_resources/ssl/server_db/key3.db b/java/test-profiles/test_resources/ssl/server_db/key3.db
deleted file mode 100644
index 12f3c394c5..0000000000
--- a/java/test-profiles/test_resources/ssl/server_db/key3.db
+++ /dev/null
Binary files differ
diff --git a/java/test-profiles/test_resources/ssl/server_db/secmod.db b/java/test-profiles/test_resources/ssl/server_db/secmod.db
deleted file mode 100644
index 97a5b9b2fe..0000000000
--- a/java/test-profiles/test_resources/ssl/server_db/secmod.db
+++ /dev/null
Binary files differ
diff --git a/java/test-profiles/test_resources/ssl/server_db/server.crt b/java/test-profiles/test_resources/ssl/server_db/server.crt
deleted file mode 100644
index 4f1c007d16..0000000000
--- a/java/test-profiles/test_resources/ssl/server_db/server.crt
+++ /dev/null
@@ -1,14 +0,0 @@
------BEGIN CERTIFICATE-----
-MIICKzCCAZSgAwIBAgIFAJBNUhEwDQYJKoZIhvcNAQEFBQAwQTELMAkGA1UEBhMC
-Q0ExEDAOBgNVBAgTB09udGFyaW8xDTALBgNVBAoTBEFDTUUxETAPBgNVBAMTCE15
-Um9vdENBMB4XDTEwMDMyMjIxNDE0OVoXDTE1MDMyMjIxNDE0OVowTjELMAkGA1UE
-BhMCQ0ExEDAOBgNVBAgTB09udGFyaW8xDTALBgNVBAoTBEFDTUUxHjAcBgNVBAMT
-FWxvY2FsaG9zdC5sb2NhbGRvbWFpbjCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkC
-gYEAtmFy+0IIn6otWu2TCJ3fN2UDA//EVDWpiozzvd/My31XpPQ8jhuvsZ2//xvG
-OKqDfgQ80OE6BiGmR2zxPKFfsgxhU+0g8132focOzd0MhmGpyhdQdogXQ2cCcvjB
-CvgaugIjTmk3MX9njD7np8TQQ7wW1Wuk/c99tuvlexjEoWkCAwEAAaMiMCAwCQYD
-VR0TBAIwADATBgNVHSUEDDAKBggrBgEFBQcDATANBgkqhkiG9w0BAQUFAAOBgQDH
-iOxUWKllSUgCcAij0Gb4qDo/YDoatWyzE8pNZR7OgSOJ8zEVJcB/7YW//frd2dMS
-lz6c38vqbGwyblw+b64SvBKI3WK0jyO4Ft9FGpNIEfc9Q5G0MFiGilv+GDIZ/asE
-KnsZNy4z4gs3KFSf96k1AV1YQ1tVpFcUrI+3QqdWfQ==
------END CERTIFICATE-----
diff --git a/java/test-profiles/test_resources/ssl/server_db/server.req b/java/test-profiles/test_resources/ssl/server_db/server.req
deleted file mode 100644
index 5551516586..0000000000
--- a/java/test-profiles/test_resources/ssl/server_db/server.req
+++ /dev/null
@@ -1,21 +0,0 @@
-
-Certificate request generated by Netscape certutil
-Phone: (not specified)
-
-Common Name: localhost.localdomain
-Email: (not specified)
-Organization: ACME
-State: Ontario
-Country: CA
-
------BEGIN NEW CERTIFICATE REQUEST-----
-MIIBjTCB9wIBADBOMQswCQYDVQQGEwJDQTEQMA4GA1UECBMHT250YXJpbzENMAsG
-A1UEChMEQUNNRTEeMBwGA1UEAxMVbG9jYWxob3N0LmxvY2FsZG9tYWluMIGfMA0G
-CSqGSIb3DQEBAQUAA4GNADCBiQKBgQC2YXL7Qgifqi1a7ZMInd83ZQMD/8RUNamK
-jPO938zLfVek9DyOG6+xnb//G8Y4qoN+BDzQ4ToGIaZHbPE8oV+yDGFT7SDzXfZ+
-hw7N3QyGYanKF1B2iBdDZwJy+MEK+Bq6AiNOaTcxf2eMPuenxNBDvBbVa6T9z322
-6+V7GMShaQIDAQABoAAwDQYJKoZIhvcNAQEFBQADgYEAJGqdJVTScR4rzusrf6dE
-Snz/PtKcl8ZqXfHMPhj5uqUACcj3AxvlerIrpIGG9YT5cX4cOa92plpearMAC1TW
-fksbpsJR174WnAbBETrNbOX55igS/KDkW+RJCn7GGOvcSza+nJ880/lZ0iC63bgY
-SmvSnp3ub1CBX0grWl4bzTw=
------END NEW CERTIFICATE REQUEST-----
diff --git a/java/testkit/README.txt b/java/testkit/README.txt
deleted file mode 100644
index df7996f471..0000000000
--- a/java/testkit/README.txt
+++ /dev/null
@@ -1,6 +0,0 @@
-Introduction
-============
-
-The Test kit for the JMS client is based on a multi-broker python framework.
-So far it could only be used with the c++ broker.
-
diff --git a/java/testkit/bin/run_soak_client.sh b/java/testkit/bin/run_soak_client.sh
deleted file mode 100644
index ea1721d988..0000000000
--- a/java/testkit/bin/run_soak_client.sh
+++ /dev/null
@@ -1,70 +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.
-#
-
-# This is a sample script for a soak test on
-# linux environment.
-# This will start n of Producers processors and record their CPU and memory stats.
-# Also the Producer out will be saved to a file as well.
-
-if [ "$JAR_PATH" = "" ] ; then
- echo "ERROR: Please set JAR_PATH to point to the Qpid libraries ...."
- exit 1
-fi
-
-#1 PID, $2 freq, $3 count
-calc_stats(){
-
-for (( i = 0 ; i <= $3; i++ ))
- do
- cpu=`ps auxw | grep $1 | grep -v 'grep' | awk '{print $3}'`
- mem=`pmap $1 | grep total | grep -v 'grep' | awk '{print substr($2,0,length($2)-1)}'`
- echo $i","$mem","$cpu
- sleep $2
- cpu="0.0"
- mem="0"
- done
- kill -9 $1
-}
-
-# Num of producer processors to start
-num=$1
-# Log frequency in seconds
-log_freq=$2
-# Num of iterations
-log_iter=$3
-
-class_name=$4
-log_file_name=`echo $class_name | cut -d. -f6`
-
-# The total time for the test is determined by the
-# log_freq * log_iter.
-
-shift 4
-CLASSPATH=`find $JAR_PATH -name '*.jar' | tr '\n' ":"`
-
-JVM_ARGS="-Xmx1500M $@"
-echo "Starting $log_file_name with the following params $JVM_ARGS"
-
-for (( c = 1 ; c <= $num; c++ ))
-do
- $JAVA_HOME/bin/java $JVM_ARGS -cp $CLASSPATH $class_name > ${log_file_name}_${c}.log &
- pid=`jobs -l %% | awk '{print $2}'`
- calc_stats $pid $log_freq $log_iter > ${log_file_name}_process_${c}.log &
-done
diff --git a/java/testkit/bin/soak_report.sh b/java/testkit/bin/soak_report.sh
deleted file mode 100644
index 9da8bfa234..0000000000
--- a/java/testkit/bin/soak_report.sh
+++ /dev/null
@@ -1,161 +0,0 @@
-#!/bin/sh
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-#
-
-# Sample script to run a soak test with MultiThreadedProducer/Consumer.
-# You need to provide the log freq and no of iterations
-# Ex to run 10 hours and collect 1 second samples
-# soak_report.sh 1 36000
-
-# This script assumes that a suitable broker instance is started.
-
-log_freq=$1
-log_iter=$2
-shift 2
-JVM_ARGS=$@
-
-if [ "$QPID_TEST_HOME" = "" ] ; then
- echo "ERROR: Please set QPID_TEST_HOME ...."
- exit 1
-fi
-
-print_rates()
-{
- cat $1 | awk '{
- FS = ",";
- count = 0;
- total_latency = 0;
- min_latency = 9223372036854775807;
- max_latency = 0;
-
- total_tp = 0;
- min_tp = 50000;
- max_tp = 0;
-
- while ((getline) == 1)
- {
- total_latency = total_latency + $3
- total_tp = total_tp + $2
-
- if ($3 > 0)
- {
- min_latency = (($3 < min_latency) ? $3 : min_latency);
- max_latency = (($3 > max_latency) ? $3 : max_latency);
- }
- if ($2 > 0)
- {
- min_tp = (($2 < min_tp) ? $2 : min_tp);
- max_tp = (($2 > max_tp) ? $2 : max_tp);
- }
-
- count = count + 1
- }
-
- print "Avg Latency (ms) : " total_latency/count
- print "Max Latency (ms) : " max_latency
- print "Min Latency (ms) : " min_latency
-
- print ""
- print "Avg Throughput (msg/sec) : " total_tp/count
- print "Max Throughput (msg/sec) : " max_tp
- print "Min Throughput (msg/sec) : " min_tp
-
- print ""
- print "Total Iteratons " count
-
- }'
-}
-
-print_system_stats()
-{
- cat $1 | awk '{
- FS = ",";
- count = 0;
- total_memory = 0;
- min_memory = 9223372036854775807;
- max_memory = 0;
-
- total_cp = 0;
- min_cp = 50000;
- max_cp = 0;
-
- while ((getline) == 1)
- {
- total_memory = total_memory + $2
- total_cp = total_cp + $3
-
- if ($2 > 0)
- {
- min_memory = (($2 < min_memory) ? $2 : min_memory);
- max_memory = (($2 > max_memory) ? $2 : max_memory);
- }
- if ($3 > 0)
- {
- min_cp = (($3 < min_cp) ? $3 : min_cp);
- max_cp = (($3 > max_cp) ? $3 : max_cp);
- }
-
- count = count + 1
- }
-
- print "Avg Memory (MB) : " total_memory/(count*1024)
- print "Max Memory (MB) : " max_memory/1024
- print "Min Memory (MB) : " min_memory/1024
-
- print ""
- print "Avg CPU : " total_cp/count
- print "Max CPU : " max_cp
- print "Min CPU : " min_cp
-
- print ""
- print "Total Iteratons " count
-
- }'
-}
-
-
-cleanup()
-{
- kill -9 `ps aux | grep java | grep soak | awk '{ print $2 }'`
-}
-
-print_results()
-{
- printf "\n======================================================= \n"
- print_rates MultiThreadedConsumer_1.log
- printf "\nConsumer process stats "
- printf "\n----------------------- \n"
- print_system_stats MultiThreadedConsumer_process_1.log
- printf "\nProducer process stats "
- printf "\n----------------------- \n"
- print_system_stats MultiThreadedProducer_process_1.log
- printf "\n------------------------------------------------------- \n"
-}
-
-trap cleanup EXIT
-
-# runs a single instance of the MultiThreadedConsumer and MultiThreadedProducer
-sh $QPID_TEST_HOME/bin/run_soak_client.sh 1 $log_freq $log_iter org.apache.qpid.testkit.soak.MultiThreadedConsumer $JVM_ARGS
-sh $QPID_TEST_HOME/bin/run_soak_client.sh 1 $log_freq $log_iter org.apache.qpid.testkit.soak.MultiThreadedProducer $JVM_ARGS
-
-sleep_time=$((log_freq * log_iter))
-echo "sleep time : " $sleep_time
-sleep $((log_freq * log_iter))
-
-print_results
diff --git a/java/testkit/build.xml b/java/testkit/build.xml
deleted file mode 100644
index 80a3373379..0000000000
--- a/java/testkit/build.xml
+++ /dev/null
@@ -1,27 +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.
- -
- -->
-<project name="Test Kit" default="build">
-
- <property name="module.depends" value="client common tools"/>
-
- <import file="../module.xml"/>
-
-</project>
diff --git a/java/testkit/src/main/java/org/apache/qpid/testkit/soak/ResourceLeakTest.java b/java/testkit/src/main/java/org/apache/qpid/testkit/soak/ResourceLeakTest.java
deleted file mode 100644
index c240ecdf2e..0000000000
--- a/java/testkit/src/main/java/org/apache/qpid/testkit/soak/ResourceLeakTest.java
+++ /dev/null
@@ -1,180 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.testkit.soak;
-
-
-import java.util.Random;
-
-import javax.jms.BytesMessage;
-import javax.jms.Destination;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-import javax.jms.Session;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.client.BasicMessageConsumer;
-import org.apache.qpid.client.BasicMessageProducer;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.testkit.TestLauncher;
-import org.apache.qpid.thread.Threading;
-
-/**
- * Test Description
- * ================
- * This test will open x number of connections where each
- * connection will create a session and a producer/consumer pair,
- * and then a randomly selected set of connections (about 1/4th)
- * will send a configurable no of messages and try to receive them.
- * It will then sleep for configurable time interval and
- * tear down the connections/sessions/consumers.
- * It will then repeat the process again until the test is stopped.
- *
- * Purpose of the test
- * ===================
- * To find if the broker has leaks when cleaning resources.
- * To find if the client has leaks with resources.
- */
-public class ResourceLeakTest extends TestLauncher
-{
- /* protected long connection_idle_time = 5000;
- protected Random rand = new Random();
-
- public ResourceLeakTest()
- {
- super();
- }
-
- public void test()
- {
- try
- {
-
- AMQConnection[] cons = new AMQConnection[connection_count];
- Session[] sessions = new Session[connection_count];
- MessageConsumer[] msgCons = new MessageConsumer[connection_count];
- MessageProducer [] msgProds = new MessageProducer[connection_count];
-
- while (true)
- {
- for (int i = 0; i < connection_count; i++)
- {
- AMQConnection con = new AMQConnection(url);
- con.start();
- cons[i] = con;
- Session ssn = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
- sessions[i] = ssn;
- Destination dest = new AMQQueue(new AMQShortString(exchange_name),
- new AMQShortString(routing_key + i),
- new AMQShortString(queue_name + i),
- true, //exclusive
- true // auto delete
- );
- MessageConsumer msgCon = ssn.createConsumer(dest);
- msgCons[i] = msgCon;
- MessageProducer msgProd = ssn.createProducer(dest);
- msgProds[i] = msgProd;
- }
-
- // Select some connections randomly and send/recv messages
- // Exercise around quarter of the connections
- for (int i=0; i < connection_count/4; i++)
- {
- int k = rand.nextInt(connection_count);
-
- BytesMessage msg = sessions[k].createBytesMessage();
- msg.writeBytes("Test Msg".getBytes());
-
- for (int j = 0; j < msg_count;j++)
- {
- msgProds[k].send(msg);
- }
-
- int j = 0;
- while (j < msg_count)
- {
- msgCons[k].receive();
- j++;
- }
- }
- System.out.println(df.format(System.currentTimeMillis()));
- Thread.sleep(connection_idle_time);
-
- try
- {
- for (int i = 0; i < connection_count; i++)
- {
- if (!((BasicMessageConsumer)msgCons[i]).isClosed())
- {
- msgCons[i].close();
- }
-
- if (!((BasicMessageProducer)msgProds[i]).isClosed())
- {
- msgProds[i].close();
- }
-
- if (!((AMQSession)sessions[i]).isClosed())
- {
- sessions[i].close();
- }
- if (!((AMQConnection)cons[i]).isClosed())
- {
- cons[i].close();
- }
- }
- }
- catch (Exception e)
- {
- handleError(e,"Exception closing resources");
- }
- }
- }
- catch (Exception e)
- {
- handleError(e,"Exception in setting up the test");
- }
-
- }
-
- public static void main(String[] args)
- {
- final ResourceLeakTest test = new ResourceLeakTest();
- Runnable r = new Runnable(){
- public void run()
- {
- test.test();
- }
- };
-
- Thread t;
- try
- {
- t = Threading.getThreadFactory().createThread(r);
- }
- catch(Exception e)
- {
- throw new Error("Error creating test thread",e);
- }
- }*/
-
-}
diff --git a/java/tools/README.txt b/java/tools/README.txt
deleted file mode 100644
index fdde734027..0000000000
--- a/java/tools/README.txt
+++ /dev/null
@@ -1,153 +0,0 @@
-Introduction
-============
-
-The Test kit for the java client consists of 2 components.
-
-1) A Simple Perf Test that can be used to,
- a) Run a predefined perf report consisting of 8 use cases (see below)
- b) Run a producer and a consumer with a number of different options
-
-2) Soak tests that can be run for longer durations (hours or days).
-
-I am planning to add some stress tests to this module as well.
-Please note this is not a replacement for the existing perf/systests etc.
-But rather a small test kit thats focused on providing a packaged set of tests that can be quickly deployed on an environment to do quick smoke testing or easily setup a soak test.
-
-Table of Contents
-=================
-1. Perf Kit
-2. Soak Kit
-3. Perf Test use cases
-4. Soak Test use cases
-5. Running the sample perf test report
-6. Running the sample soak test report
-
-1.0 Perf Kit
-------------
-1.1 The perf kit can be packaged as an RPM or a tar file and deploy on a target environment and run the perf report.
-Or else a perf report can be automated to run every day or so an record numbers to catch perf regressions.
-
-1.2 It calculates the following results in msg/sec.
-
- System throuhgput : no_of_msgs / (time_last_msg_rcvd - time_first_msg_send)
-
- Producer rate : no_of_msgs / (time_after_sending - time_before_sending)
-
- Producer rate : no_of_msgs / (time_last_msg_rcvd - time_first_msg_rcvd)
-
- Latency : time_msg_rcvd - time_msg_sent
-
-The test will print min, max and avg latency.
-
-1.3 The test assume that both producer and consumer are run on the same machine or different machines that are time synced.
-
-1.4 You can also use run_sub.sh and run_pub.sh to run different use cases with several options.
- Please look at TestParams.java for all the configurable options.
-
-1.5 You can also use the test kit to benchmark against any vendor.
-
-
-2.0 Soak tests
---------------
-2.0 This includes a set of soak tests that can be run for a longer duration.
-
-2.1 A typical test will send x-1 messages and the xth message will contain an "End" marker.
- The producer will print the timestamp as soon as it sends the xth message.
- The consumer will reply with an empty message to the replyTo destination given in the xth message.
- The consumer prints the throuhgput for the iteration and the latency for the xth message.
- A typical value for x is 100k
-
-2.2 The feedback loop prevents the producer from overrunning the consumer.
- And the printout for every xth message will let you know how many iterations been completed at any given time.
- (Ex a simple cat log | wc -l will give you the how many iterations have been completed so far).
-
-2.2 The following results can be calculated for these tests.
-
- Memory, CPU for each producer/consumer - look at testkit/bin/run_soak_client.sh for an example
-
- You can find the Avg, Min & Max for throughput, latency, CPU and memory for the entire test run.
- (look at testkit/bin/soak_report.sh) for an example).
-
- You could also graph throughput, latency, CPU and memory using the comma separated log files.
-
-2.2 If you use different machines for producer and consumer the machines have to be time synced to have meaningful latency samples.
-
-3.0 Perf Test report use cases
--------------------------------
-3.1 Please check testkit/bin/perf_report.sh for more details
-
-3.2 A typical test run will send 1000 msgs during warmup and 200k msgs for result calculation.
-
-Test 1 Trans Queue
-
-Test 2 Dura Queue
-
-Test 3 Dura Queue Sync
-
-Test 4 Topic
-
-Test 5 Durable Topic
-
-Test 6 Fanout
-
-Test 7 Small TX (about 2 msgs per tx)
-
-Test 8 Large TX (about 1000 msgs per tx)
-
-
-4.0 Soak tests use cases
--------------------------
-4.1 Following are the current tests available in the test kit.
-
-4.2 Please refer to the source to see the javadoc and options
-
-
-1. SimpleProducer/Consumer sends X messages at a time and will wait for confirmation from producer before proceeding with the next iteration. A no of options can be configured.
-
-2. MultiThreadedProducer/Consumer does the same thing as above but runs each session in a separate thread.
- It can also send messages transactionally. Again a no of options can be configured.
-
-3. ResourceLeakTest will setup consumer/producers sends x messages and then teard down everything and continue again.
-
-
-5.0 Running the sample perf test report
----------------------------------------
-The testkit/bin contains perf_report.sh.
-It runs the above 8 use cases against a broker and print the results in a tabular format.
-
-For example
-================================================================================================
-|Test |System throuput|Producer rate|Consumer Rate|Avg Latency|Min Latency|Max Latency|
-------------------------------------------------------------------------------------------------
-|Trans_Queue | xxxxx.xx| xxxxx.xx| xxxxx.xx| xx.xx| x| xx|
-
-
-5.1 running perf_report.sh
-
-5.1.1 set JAVA_HOME to point to Java 1.5 and above
-5.1.2 set QPID_TEST_HOME to point to the testkit dir
-5.1.3 set VENDOR_LIB to point to the Qpid (or other JMS providers) jar files.
-5.1.4 start a broker
-5.1.5 update the testkit/etc/jndi.properties to point to the correct broker
-5.1.6 execute perf_report.sh
-
-
-6.0 Running the sample soak test report
----------------------------------------
-The testkit/bin contains soak_report.sh
-It runs MultiThreadedProducer/Consumer for the duration specified and prints a report for the following stats.
-Avg, Min and Max for System Throughput, letency, CPU and memory.
-
-6.1 running soak_report.sh
-
-5.1.1 set JAVA_HOME to point to Java 1.5 and above
-5.1.2 set QPID_TEST_HOME to point to the testkit dir
-5.1.3 set JAR_PATH to point to the Qpid jars
-5.1.4 start a broker
-5.1.5 execute soak_report.sh with correct params.
- Ex sh soak_report.sh 1 36000 will run for 10 hours colllecting CPU, memory every second.
-
-5.1.6 Please note the total duration for the test is log_freq * log_iterations
- So if you want to run the test for 10 hours and collect 10 second samples then do the following
- sh soak_report.sh 10 3600
-
diff --git a/java/tools/bin/perf_report.sh b/java/tools/bin/perf_report.sh
deleted file mode 100755
index e6b4c987e5..0000000000
--- a/java/tools/bin/perf_report.sh
+++ /dev/null
@@ -1,140 +0,0 @@
-#!/bin/sh
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-#
-
-# This will run the 8 use cases defined below and produce
-# a report in tabular format. Refer to the documentation
-# for more details.
-
-SUB_MEM=-Xmx1024M
-PUB_MEM=-Xmx1024M
-LOG_CONFIG="-Damqj.logging.level=WARN"
-QUEUE="queue;{create:always,node:{x-declare:{auto-delete:true}}}"
-DURA_QUEUE="dqueue;{create:always,node:{durable:true,x-declare:{auto-delete:true}}}"
-TOPIC="amq.topic/test"
-DURA_TOPIC="amq.topic/test;{create:always,link:{durable:true}}"
-
-. setenv.sh
-
-waitfor() { until grep -a -l "$2" $1 >/dev/null 2>&1 ; do sleep 1 ; done ; }
-cleanup()
-{
- pids=`ps aux | grep java | grep Perf | awk '{print $2}'`
- if [ "$pids" != "" ]; then
- kill -3 $pids
- kill -9 $pids >/dev/null 2>&1
- fi
-}
-
-# $1 test name
-# $2 consumer options
-# $3 producer options
-run_testcase()
-{
- sh run_sub.sh $LOG_CONFIG $SUB_MEM $2 > sub.out &
- waitfor sub.out "Warming up"
- sh run_pub.sh $LOG_CONFIG $PUB_MEM $3 > pub.out &
- waitfor sub.out "Completed the test"
- waitfor pub.out "Consumer has completed the test"
- sleep 2 #give a grace period to shutdown
- print_result $1
-}
-
-print_result()
-{
- prod_rate=`cat pub.out | grep "Producer rate" | awk '{print $3}'`
- sys_rate=`cat sub.out | grep "System Throughput" | awk '{print $4}'`
- cons_rate=`cat sub.out | grep "Consumer rate" | awk '{print $4}'`
- avg_latency=`cat sub.out | grep "Avg Latency" | awk '{print $4}'`
- min_latency=`cat sub.out | grep "Min Latency" | awk '{print $4}'`
- max_latency=`cat sub.out | grep "Max Latency" | awk '{print $4}'`
-
- printf "|%-15s|%15.2f|%13.2f|%13.2f|%11.2f|%11d|%11d|\n" $1 $sys_rate $prod_rate $cons_rate $avg_latency $min_latency $max_latency
- echo "------------------------------------------------------------------------------------------------"
-}
-
-trap cleanup EXIT
-
-echo "Test report on " `date +%F`
-echo "================================================================================================"
-echo "|Test |System throuput|Producer rate|Consumer Rate|Avg Latency|Min Latency|Max Latency|"
-echo "------------------------------------------------------------------------------------------------"
-
-# The message counts and warmup counts are set to very low values for quick testing of the script.
-# For a real performance run I recommend setting warmup count to 10k and message count in excess of 100k
-# However for transactions, sync_publish and especially small durable transactions (which is quite slow) I recommend
-# setting very low values to start with and experiment while increasing them slowly.
-
-# Test 1 Trans Queue
-#run_testcase "Trans_Queue" "-Daddress=$QUEUE" "-Daddress=$QUEUE -Dwarmup_count=1 -Dmsg_count=10"
-
-# Test 2 Dura Queue
-run_testcase "Dura_Queue" "-Daddress=$DURA_QUEUE -Ddurable=true" "-Daddress=$DURA_QUEUE -Ddurable=true -Dwarmup_count=1 -Dmsg_count=10"
-
-# Test 3 Dura Queue Sync
-run_testcase "Dura_Queue_Sync" "-Daddress=$DURA_QUEUE -Ddurable=true" "-Daddress=$DURA_QUEUE -Ddurable=true -Dwarmup_count=1 -Dmsg_count=10 -Dsync_publish=persistent"
-
-# Test 4 Dura Queue Sync Publish and Ack
-run_testcase "Dura_SyncPubAck" "-Daddress=$DURA_QUEUE -Ddurable=true -Dsync_ack=true" "-Daddress=$DURA_QUEUE -Ddurable=true -Dwarmup_count=1 -Dmsg_count=10 -Dsync_publish=persistent"
-
-# Test 5 Topic
-run_testcase "Topic" "-Daddress=$TOPIC" "-Daddress=$TOPIC -Dwarmup_count=1 -Dmsg_count=10"
-
-# Test 6 Durable Topic
-run_testcase "Dura_Topic" "-Daddress=$DURA_TOPIC -Ddurable=true" "-Daddress=$DURA_TOPIC -Ddurable=true -Dwarmup_count=1 -Dmsg_count=10"
-
-# Test 7 Fanout
-run_testcase "Fanout" "-Daddress=amq.fanout" "-Daddress=amq.fanout -Dwarmup_count=1 -Dmsg_count=10"
-
-# Test 8 Small TX
-run_testcase "Small_Txs_2" "-Daddress=$DURA_QUEUE -Ddurable=true -Dtransacted=true -Dtrans_size=1" \
- "-Daddress=$DURA_QUEUE -Ddurable=true -Dwarmup_count=1 -Dmsg_count=10 -Dtransacted=true -Dtrans_size=1"
-
-# Test 9 Large TX
-run_testcase "Large_Txs_1000" "-Daddress=$DURA_QUEUE -Ddurable=true -Dtransacted=true -Dtrans_size=10" \
- "-Daddress=$DURA_QUEUE -Ddurable=true -Dwarmup_count=1 -Dmsg_count=10 -Dtransacted=true -Dtrans_size=10"
-
-# Test 10 256 MSG
-run_testcase "Msg_256b" "-Daddress=$QUEUE" "-Daddress=$QUEUE -Dmsg_size=256 -Dwarmup_count=1 -Dmsg_count=10"
-
-# Test 11 512 MSG
-run_testcase "Msg_512b" "-Daddress=$QUEUE" "-Daddress=$QUEUE -Dmsg_size=512 -Dwarmup_count=1 -Dmsg_count=10"
-
-# Test 12 2048 MSG
-run_testcase "Msg_2048b" "-Daddress=$QUEUE" "-Daddress=$QUEUE -Dmsg_size=2048 -Dwarmup_count=1 -Dmsg_count=10"
-
-# Test 13 Random size MSG
-run_testcase "Random_Msg_Size" "-Daddress=$QUEUE" "-Daddress=$QUEUE -Drandom_msg_size=true -Dwarmup_count=1 -Dmsg_count=10"
-
-# Test 14 Random size MSG Durable
-run_testcase "Rand_Msg_Dura" "-Daddress=$DURA_QUEUE -Ddurable=true" "-Daddress=$DURA_QUEUE -Ddurable=true -Drandom_msg_size=true -Dwarmup_count=1 -Dmsg_count=10"
-
-# Test 15 64K MSG
-run_testcase "Msg_64K" "-Daddress=$QUEUE -Damqj.tcpNoDelay=true" "-Daddress=$QUEUE -Damqj.tcpNoDelay=true -Dmsg_size=64000 -Dwarmup_count=1 -Dmsg_count=10"
-
-# Test 16 Durable 64K MSG
-run_testcase "Msg_Durable_64K" "-Daddress=$DURA_QUEUE -Ddurable=true -Damqj.tcpNoDelay=true" \
- "-Daddress=$DURA_QUEUE -Damqj.tcpNoDelay=true -Dmsg_size=64000 -Ddurable=true -Dwarmup_count=1 -Dmsg_count=10"
-
-# Test 17 500K MSG
-run_testcase "Msg_500K" "-Daddress=$QUEUE -Damqj.tcpNoDelay=true" "-Daddress=$QUEUE -Damqj.tcpNoDelay=true -Dmsg_size=500000 -Dwarmup_count=1 -Dmsg_count=10"
-
-# Test 18 Durable 500K MSG
-run_testcase "Msg_Dura_500K" "-Daddress=$DURA_QUEUE -Damqj.tcpNoDelay=true -Ddurable=true" \
- "-Daddress=$DURA_QUEUE -Damqj.tcpNoDelay=true -Dmsg_size=500000 -Ddurable=true -Dwarmup_count=1 -Dmsg_count=10"
diff --git a/java/tools/bin/qpid-bench b/java/tools/bin/qpid-bench
deleted file mode 100644
index c982e64efd..0000000000
--- a/java/tools/bin/qpid-bench
+++ /dev/null
@@ -1,35 +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.
-#
-
-if [ -z "$QPID_HOME" ]; then
- export QPID_HOME=$(dirname $(dirname $(readlink -f $0)))
- export PATH=${PATH}:${QPID_HOME}/bin
-fi
-
-# Set classpath to include Qpid jar with all required jars in manifest
-QPID_LIBS=$QPID_HOME/lib/qpid-all.jar
-
-# Set other variables used by the qpid-run script before calling
-export JAVA=java \
- JAVA_VM=-server \
- JAVA_MEM=-Xmx1024m \
- QPID_CLASSPATH=$QPID_LIBS
-
-. qpid-run org.apache.qpid.tools.QpidBench "$@"
diff --git a/java/tools/bin/qpid-python-testkit b/java/tools/bin/qpid-python-testkit
deleted file mode 100755
index cbe7972421..0000000000
--- a/java/tools/bin/qpid-python-testkit
+++ /dev/null
@@ -1,30 +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.
-#
-
-# This is wrapper script to run the tests defined in testkit.py
-# via the python test runner. The defaults are set for a running
-# from an svn checkout
-
-. ./set-testkit-env.sh
-
-export PYTHONPATH=./:$PYTHONPATH
-rm -rf $OUTDIR
-qpid-python-test -DOUTDIR=$OUTDIR -m testkit "$@"
-
diff --git a/java/tools/bin/run_pub.sh b/java/tools/bin/run_pub.sh
deleted file mode 100644
index 91b9287dea..0000000000
--- a/java/tools/bin/run_pub.sh
+++ /dev/null
@@ -1,24 +0,0 @@
-#!/bin/sh
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-#
-
-. $QPID_TEST_HOME/bin/setenv.sh
-
-echo "$@"
-$JAVA_HOME/bin/java -cp $CLASSPATH $@ org.apache.qpid.tools.PerfProducer
diff --git a/java/tools/bin/run_sub.sh b/java/tools/bin/run_sub.sh
deleted file mode 100644
index c9ad2fed74..0000000000
--- a/java/tools/bin/run_sub.sh
+++ /dev/null
@@ -1,25 +0,0 @@
-#!/bin/sh
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-#
-
-. $QPID_TEST_HOME/bin/setenv.sh
-
-echo "$@"
-$JAVA_HOME/bin/java -cp $CLASSPATH $@ org.apache.qpid.tools.PerfConsumer
-
diff --git a/java/tools/bin/set-testkit-env.sh b/java/tools/bin/set-testkit-env.sh
deleted file mode 100644
index 051dad8179..0000000000
--- a/java/tools/bin/set-testkit-env.sh
+++ /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.
-#
-
-# If QPIDD_EXEC ..etc is not set, it will first check to see
-# if this is run from a qpid svn check out, if not it will look
-# for installed rpms.
-
-abs_path()
-{
- D=`dirname "$1"`
- B=`basename "$1"`
- echo "`cd \"$D\" 2>/dev/null && pwd || echo \"$D\"`/$B"
-}
-
-# Environment for python tests
-
-if [ -d ../../../python ] ; then
- PYTHON_DIR=../../../python
- PYTHONPATH=$PYTHON_DIR:$PYTHON_DIR/qpid
-elif [ -z `echo $PYTHONPATH | awk '$0 ~ /qpid/'` ]; then
- echo "WARNING: skipping test, no qpid python scripts found ."; exit 0;
-fi
-
-
-if [ "$QPIDD_EXEC" = "" ] ; then
- if [ -x ../../../cpp/src/qpidd ]; then
- QPIDD_EXEC=`abs_path "../../../cpp/src/qpidd"`
- elif [ -n "$(which qpidd)" ] ; then
- QPIDD_EXEC=$(which qpidd)
- else
- echo "WARNING: skipping test, QPIDD_EXEC not set and qpidd not found."; exit 0;
- fi
-fi
-
-if [ "$CLUSTER_LIB" = "" ] ; then
- if [ -x ../../../cpp/src/.libs/cluster.so ]; then
- CLUSTER_LIB=`abs_path "../../../cpp/src/.libs/cluster.so"`
- elif [ -e /usr/lib64/qpid/daemon/cluster.so ] ; then
- CLUSTER_LIB="/usr/lib64/qpid/daemon/cluster.so"
- elif [ -e /usr/lib/qpid/daemon/cluster.so ] ; then
- CLUSTER_LIB="/usr/lib/qpid/daemon/cluster.so"
- else
- echo "WARNING: skipping test, CLUSTER_LIB not set and cluster.so not found."; exit 0;
- fi
-fi
-
-if [ "$STORE_LIB" = "" ] ; then
- if [ -e /usr/lib64/qpid/daemon/msgstore.so ] ; then
- STORE_LIB="/usr/lib64/qpid/daemon/msgstore.so"
- elif [ -e /usr/lib/qpid/daemon/msgstore.so ] ; then
- STORE_LIB="/usr/lib/qpid/daemon/msgstore.so"
- #else
- # echo "WARNING: skipping test, STORE_LIB not set and msgstore.so not found."; exit 0;
- fi
-fi
-
-if [ "$QP_CP" = "" ] ; then
- if [ -d ../../build/lib/ ]; then
- QP_JAR_PATH=`abs_path "../../build/lib/"`
- elif [ -d /usr/share/java/qpid-deps ]; then
- QP_JAR_PATH=`abs_path "/usr/share/java"`
- else
- "WARNING: skipping test, QP_CP not set and the Qpid jars are not present."; exit 0;
- fi
- QP_CP=`find $QP_JAR_PATH -name '*.jar' | tr '\n' ':'`
-fi
-
-if [ "$OUTDIR" = "" ] ; then
- OUTDIR=`abs_path "./output"`
-fi
-
-export PYTHONPATH PYTHON_DIR QPIDD_EXEC CLUSTER_LIB QP_CP OUTDIR
diff --git a/java/tools/bin/setenv.sh b/java/tools/bin/setenv.sh
deleted file mode 100644
index 24135e711b..0000000000
--- a/java/tools/bin/setenv.sh
+++ /dev/null
@@ -1,49 +0,0 @@
-#!/bin/sh
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-#
-
-# Compiles the test classes and sets the CLASSPATH
-
-# check for QPID_TEST_HOME
-if [ "$QPID_TEST_HOME" = "" ] ; then
- echo "ERROR: Please set QPID_TEST_HOME ...."
- exit 1
-fi
-
-# check for JAVA_HOME
-if [ "$JAVA_HOME" = "" ] ; then
- echo "ERROR: Please set JAVA_HOME ...."
- exit 1
-fi
-
-# VENDOR_LIB path needs to be set
-# for Qpid set this to {qpid_checkout}/java/build/lib
-if [ "$VENDOR_LIB" = "" ] ; then
- echo "ERROR: Please set VENDOR_LIB path in the script ...."
- exit 1
-fi
-
-
-[ -d $QPID_TEST_HOME/classes ] || mkdir $QPID_TEST_HOME/classes
-
-CLASSPATH=`find $VENDOR_LIB -name *.jar* | tr '\n' ":"`
-$JAVA_HOME/bin/javac -cp $CLASSPATH -d $QPID_TEST_HOME/classes -sourcepath $QPID_TEST_HOME/src `find $QPID_TEST_HOME/src -name '*.java'`
-
-export CLASSPATH=$QPID_TEST_HOME/classes:$CLASSPATH
-
diff --git a/java/tools/bin/testkit.py b/java/tools/bin/testkit.py
deleted file mode 100755
index 1c2ad598b8..0000000000
--- a/java/tools/bin/testkit.py
+++ /dev/null
@@ -1,278 +0,0 @@
-#!/usr/bin/env python
-
-#
-# 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 time, string, traceback
-from brokertest import *
-from qpid.messaging import *
-
-
-try:
- import java.lang.System
- _cp = java.lang.System.getProperty("java.class.path");
-except ImportError:
- _cp = checkenv("QP_CP")
-
-class Formatter:
-
- def __init__(self, message):
- self.message = message
- self.environ = {"M": self.message,
- "P": self.message.properties,
- "C": self.message.content}
-
- def __getitem__(self, st):
- return eval(st, self.environ)
-
-# The base test case has support for launching the generic
-# receiver and sender through the TestLauncher with all the options.
-#
-class JavaClientTest(BrokerTest):
- """Base Case for Java Test cases"""
-
- client_class = "org.apache.qpid.testkit.TestLauncher"
-
- # currently there is no transparent reconnection.
- # temp hack: just creating the queue here and closing it.
- def start_error_watcher(self,broker=None):
- ssn = broker.connect().session()
- err_watcher = ssn.receiver("control; {create:always}", capacity=1)
- ssn.close()
-
- def store_module_args(self):
- if BrokerTest.store_lib:
- return ["--load-module", BrokerTest.store_lib]
- else:
- print "Store module not present."
- return [""]
-
- def client(self,**options):
- cmd = ["java","-cp",_cp]
-
- cmd += ["-Dtest_name=" + options.get("test_name", "UNKNOWN")]
- cmd += ["-Dhost=" + options.get("host","127.0.0.1")]
- cmd += ["-Dport=" + str(options.get("port",5672))]
- cmd += ["-Dcon_count=" + str(options.get("con_count",1))]
- cmd += ["-Dssn_per_con=" + str(options.get("ssn_per_con",1))]
- cmd += ["-Duse_unique_dests=" + str(options.get("use_unique_dests",False))]
- cmd += ["-Dcheck_for_dups=" + str(options.get("check_for_dups",False))]
- cmd += ["-Ddurable=" + str(options.get("durable",False))]
- cmd += ["-Dtransacted=" + str(options.get("transacted",False))]
- cmd += ["-Dreceiver=" + str(options.get("receiver",False))]
- cmd += ["-Dsync_rcv=" + str(options.get("sync_rcv",False))]
- cmd += ["-Dsender=" + str(options.get("sender",False))]
- cmd += ["-Dmsg_size=" + str(options.get("msg_size",256))]
- cmd += ["-Dtx_size=" + str(options.get("tx_size",10))]
- cmd += ["-Dmsg_count=" + str(options.get("msg_count",1000))]
- cmd += ["-Dmax_prefetch=" + str(options.get("max_prefetch",500))]
- cmd += ["-Dsync_ack=" + str(options.get("sync_ack",False))]
- cmd += ["-Dsync_persistence=" + str(options.get("sync_pub",False))]
- cmd += ["-Dsleep_time=" + str(options.get("sleep_time",1000))]
- cmd += ["-Dfailover=" + options.get("failover", "failover_exchange")]
- cmd += ["-Djms_durable_sub=" + str(options.get("jms_durable_sub", False))]
- cmd += ["-Dlog.level=" + options.get("log.level", "warn")]
- cmd += [self.client_class]
- cmd += [options.get("address", "my_queue; {create: always}")]
-
- #print str(options.get("port",5672))
- return cmd
-
- # currently there is no transparent reconnection.
- # temp hack: just creating a receiver and closing session soon after.
- def monitor_clients(self,broker=None,run_time=600,error_ck_freq=60):
- ssn = broker.connect().session()
- err_watcher = ssn.receiver("control; {create:always}", capacity=1)
- i = run_time/error_ck_freq
- is_error = False
- for j in range(i):
- not_empty = True
- while not_empty:
- try:
- m = err_watcher.fetch(timeout=error_ck_freq)
- ssn.acknowledge()
- print "Java process notified of an error"
- self.print_error(m)
- is_error = True
- except messaging.Empty, e:
- not_empty = False
-
- ssn.close()
- return is_error
-
- def print_error(self,msg):
- print msg.properties.get("exception-trace")
-
- def verify(self, receiver,sender):
- sender_running = receiver.is_running()
- receiver_running = sender.is_running()
-
- self.assertTrue(receiver_running,"Receiver has exited prematually")
- self.assertTrue(sender_running,"Sender has exited prematually")
-
- def start_sender_and_receiver(self,**options):
-
- receiver_opts = options
- receiver_opts["receiver"]=True
- receiver = self.popen(self.client(**receiver_opts),
- expect=EXPECT_RUNNING)
-
- sender_opts = options
- sender_opts["sender"]=True
- sender = self.popen(self.client(**sender_opts),
- expect=EXPECT_RUNNING)
-
- return receiver, sender
-
- def start_cluster(self,count=2,expect=EXPECT_RUNNING,**options):
- if options.get("durable",False)==True:
- cluster = Cluster(self, count=count, expect=expect, args=self.store_module_args())
- else:
- cluster = Cluster(self, count=count)
- return cluster
-
-class ConcurrencyTest(JavaClientTest):
- """A concurrency test suite for the JMS client"""
- skip = False
-
- def base_case(self,**options):
- if self.skip :
- print "Skipping test"
- return
-
- cluster = self.start_cluster(count=2,**options)
- self.start_error_watcher(broker=cluster[0])
- options["port"] = port=cluster[0].port()
-
- options["use_unique_dests"]=True
- options["address"]="amq.topic"
- receiver, sender = self.start_sender_and_receiver(**options)
- self.monitor_clients(broker=cluster[0],run_time=180)
- self.verify(receiver,sender)
-
- def test_multiplexing_con(self):
- """Tests multiple sessions on a single connection"""
-
- self.base_case(ssn_per_con=25,test_name=self.id())
-
- def test_multiplexing_con_with_tx(self):
- """Tests multiple transacted sessions on a single connection"""
-
- self.base_case(ssn_per_con=25,transacted=True,test_name=self.id())
-
- def test_multiplexing_con_with_sync_rcv(self):
- """Tests multiple sessions with sync receive"""
-
- self.base_case(ssn_per_con=25,sync_rcv=True,test_name=self.id())
-
- def test_multiplexing_con_with_durable_sub(self):
- """Tests multiple sessions with durable subs"""
-
- self.base_case(ssn_per_con=25,durable=True,jms_durable_sub=True,test_name=self.id())
-
- def test_multiplexing_con_with_sync_ack(self):
- """Tests multiple sessions with sync ack"""
-
- self.base_case(ssn_per_con=25,sync_ack=True,test_name=self.id())
-
- def test_multiplexing_con_with_sync_pub(self):
- """Tests multiple sessions with sync pub"""
-
- self.base_case(ssn_per_con=25,sync_pub=True,durable=True,test_name=self.id())
-
- def test_multiple_cons_and_ssns(self):
- """Tests multiple connections and sessions"""
-
- self.base_case(con_count=10,ssn_per_con=25,test_name=self.id())
-
-
-class SoakTest(JavaClientTest):
- """A soak test suite for the JMS client"""
-
- def base_case(self,**options):
- cluster = self.start_cluster(count=4, expect=EXPECT_EXIT_FAIL,**options)
- options["port"] = port=cluster[0].port()
- self.start_error_watcher(broker=cluster[0])
- options["use_unique_dests"]=True
- options["address"]="amq.topic"
- receiver,sender = self.start_sender_and_receiver(**options)
- is_error = self.monitor_clients(broker=cluster[0],run_time=30,error_ck_freq=30)
-
- if (is_error):
- print "The sender or receiver didn't start properly. Exiting test."
- return
- else:
- "Print no error !"
-
- # grace period for java clients to get the failover properly setup.
- time.sleep(30)
- error_msg= None
- # Kill original brokers, start new ones.
- try:
- for i in range(8):
- cluster[i].kill()
- b=cluster.start()
- self.monitor_clients(broker=b,run_time=30,error_ck_freq=30)
- print "iteration : " + str(i)
- except ConnectError, e1:
- error_msg = "Unable to connect to new cluster node : " + traceback.format_exc(e1)
-
- except SessionError, e2:
- error_msg = "Session error while connected to new cluster node : " + traceback.format_exc(e2)
-
- self.verify(receiver,sender)
- if error_msg:
- raise Exception(error_msg)
-
-
- def test_failover(self) :
- """Test basic failover"""
-
- self.base_case(test_name=self.id())
-
-
- def test_failover_with_durablesub(self):
- """Test failover with durable subscriber"""
-
- self.base_case(durable=True,jms_durable_sub=True,test_name=self.id())
-
-
- def test_failover_with_sync_rcv(self):
- """Test failover with sync receive"""
-
- self.base_case(sync_rcv=True,test_name=self.id())
-
-
- def test_failover_with_sync_ack(self):
- """Test failover with sync ack"""
-
- self.base_case(sync_ack=True,test_name=self.id())
-
-
- def test_failover_with_noprefetch(self):
- """Test failover with no prefetch"""
-
- self.base_case(max_prefetch=1,test_name=self.id())
-
-
- def test_failover_with_multiple_cons_and_ssns(self):
- """Test failover with multiple connections and sessions"""
-
- self.base_case(use_unique_dests=True,address="amq.topic",
- con_count=10,ssn_per_con=25,test_name=self.id())
diff --git a/java/tools/build.xml b/java/tools/build.xml
deleted file mode 100644
index 7cd1b1172c..0000000000
--- a/java/tools/build.xml
+++ /dev/null
@@ -1,27 +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.
- -
- -->
-<project name="Qpid Tools" default="build">
-
- <property name="module.depends" value="client common"/>
-
- <import file="../module.xml"/>
-
-</project>
diff --git a/java/tools/etc/test.log4j b/java/tools/etc/test.log4j
deleted file mode 100644
index b574a7b5b7..0000000000
--- a/java/tools/etc/test.log4j
+++ /dev/null
@@ -1,28 +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.
-#
-log4j.rootLogger=${root.logging.level}
-
-log4j.logger.org.apache.qpid=ERROR, console
-log4j.additivity.org.apache.qpid=false
-
-log4j.appender.console=org.apache.log4j.ConsoleAppender
-log4j.appender.console.Threshold=all
-log4j.appender.console.layout=org.apache.log4j.PatternLayout
-log4j.appender.console.layout.ConversionPattern=%t %d %p [%c{4}] %m%n
-
diff --git a/java/tools/src/main/java/org/apache/qpid/testkit/Client.java b/java/tools/src/main/java/org/apache/qpid/testkit/Client.java
deleted file mode 100644
index b10129d855..0000000000
--- a/java/tools/src/main/java/org/apache/qpid/testkit/Client.java
+++ /dev/null
@@ -1,154 +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.testkit;
-
-
-import java.text.DateFormat;
-import java.text.DecimalFormat;
-import java.text.NumberFormat;
-import java.text.SimpleDateFormat;
-
-import javax.jms.Connection;
-import javax.jms.Destination;
-import javax.jms.ExceptionListener;
-import javax.jms.JMSException;
-import javax.jms.Session;
-
-public abstract class Client implements ExceptionListener
-{
- private Connection con;
- private Session ssn;
- private boolean durable = false;
- private boolean transacted = false;
- private int txSize = 10;
- private int ack_mode = Session.AUTO_ACKNOWLEDGE;
- private String contentType = "application/octet-stream";
-
- private long reportFrequency = 60000; // every min
-
- private DateFormat df = new SimpleDateFormat("yyyy.MM.dd 'at' HH:mm:ss");
- private NumberFormat nf = new DecimalFormat("##.00");
-
- private long startTime = System.currentTimeMillis();
- private ErrorHandler errorHandler = null;
-
- public Client(Connection con) throws Exception
- {
- this.con = con;
- this.con.setExceptionListener(this);
- durable = Boolean.getBoolean("durable");
- transacted = Boolean.getBoolean("transacted");
- txSize = Integer.getInteger("tx_size",10);
- contentType = System.getProperty("content_type","application/octet-stream");
- reportFrequency = Long.getLong("report_frequency", 60000);
- }
-
- public void close()
- {
- try
- {
- con.close();
- }
- catch (Exception e)
- {
- handleError("Error closing connection",e);
- }
- }
-
- public void onException(JMSException e)
- {
- handleError("Connection error",e);
- }
-
- public void setErrorHandler(ErrorHandler h)
- {
- this.errorHandler = h;
- }
-
- public void handleError(String msg,Exception e)
- {
- if (errorHandler != null)
- {
- errorHandler.handleError(msg, e);
- }
- else
- {
- System.err.println(msg);
- e.printStackTrace();
- }
- }
-
- protected Session getSsn()
- {
- return ssn;
- }
-
- protected void setSsn(Session ssn)
- {
- this.ssn = ssn;
- }
-
- protected boolean isDurable()
- {
- return durable;
- }
-
- protected boolean isTransacted()
- {
- return transacted;
- }
-
- protected int getTxSize()
- {
- return txSize;
- }
-
- protected int getAck_mode()
- {
- return ack_mode;
- }
-
- protected String getContentType()
- {
- return contentType;
- }
-
- protected long getReportFrequency()
- {
- return reportFrequency;
- }
-
- protected long getStartTime()
- {
- return startTime;
- }
-
- protected void setStartTime(long startTime)
- {
- this.startTime = startTime;
- }
-
- public DateFormat getDf()
- {
- return df;
- }
-
-}
diff --git a/java/tools/src/main/java/org/apache/qpid/testkit/ErrorHandler.java b/java/tools/src/main/java/org/apache/qpid/testkit/ErrorHandler.java
deleted file mode 100644
index dbc73c404f..0000000000
--- a/java/tools/src/main/java/org/apache/qpid/testkit/ErrorHandler.java
+++ /dev/null
@@ -1,27 +0,0 @@
-package org.apache.qpid.testkit;
-/*
- *
- * 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 interface ErrorHandler {
-
- public void handleError(String msg,Exception e);
-}
diff --git a/java/tools/src/main/java/org/apache/qpid/testkit/Receiver.java b/java/tools/src/main/java/org/apache/qpid/testkit/Receiver.java
deleted file mode 100644
index b4294ee4cc..0000000000
--- a/java/tools/src/main/java/org/apache/qpid/testkit/Receiver.java
+++ /dev/null
@@ -1,216 +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.testkit;
-
-
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.jms.Connection;
-import javax.jms.Destination;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageListener;
-import javax.jms.MessageProducer;
-import javax.jms.TextMessage;
-
-import org.apache.qpid.client.AMQAnyDestination;
-import org.apache.qpid.client.AMQConnection;
-
-/**
- * A generic receiver which consumes messages
- * from a given address in a broker (host/port)
- * until told to stop by killing it.
- *
- * It participates in a feedback loop to ensure the producer
- * doesn't fill up the queue. If it receives an "End" msg
- * it sends a reply to the replyTo address in that msg.
- *
- * It doesn't check for correctness or measure anything
- * leaving those concerns to another entity.
- * However it prints a timestamp every x secs(-Dreport_frequency)
- * as checkpoint to figure out how far the test has progressed if
- * a failure occurred.
- *
- * It also takes in an optional Error handler to
- * pass out any error in addition to writing them to std err.
- *
- * This is intended more as building block to create
- * more complex test cases. However there is a main method
- * provided to use this standalone.
- *
- * The following options are available and configurable
- * via jvm args.
- *
- * sync_rcv - Whether to consume sync (instead of using a listener).
- * report_frequency - how often a timestamp is printed
- * durable
- * transacted
- * tx_size - size of transaction batch in # msgs. *
- * check_for_dups - check for duplicate messages and out of order messages.
- * jms_durable_sub - create a durable subscription instead of a regular subscription.
- */
-public class Receiver extends Client implements MessageListener
-{
- long msg_count = 0;
- int sequence = 0;
- boolean syncRcv = Boolean.getBoolean("sync_rcv");
- boolean jmsDurableSub = Boolean.getBoolean("jms_durable_sub");
- boolean checkForDups = Boolean.getBoolean("check_for_dups");
- MessageConsumer consumer;
- List<Integer> duplicateMessages = new ArrayList<Integer>();
-
- public Receiver(Connection con,String addr) throws Exception
- {
- super(con);
- setSsn(con.createSession(isTransacted(), getAck_mode()));
- consumer = getSsn().createConsumer(new AMQAnyDestination(addr));
- if (!syncRcv)
- {
- consumer.setMessageListener(this);
- }
-
- System.out.println("Receiving messages from : " + addr);
- }
-
- public void onMessage(Message msg)
- {
- handleMessage(msg);
- }
-
- public void run() throws Exception
- {
- long sleepTime = getReportFrequency();
- while(true)
- {
- if(syncRcv)
- {
- long t = sleepTime;
- while (t > 0)
- {
- long start = System.currentTimeMillis();
- Message msg = consumer.receive(t);
- t = t - (System.currentTimeMillis() - start);
- handleMessage(msg);
- }
- }
- Thread.sleep(sleepTime);
- System.out.println(getDf().format(System.currentTimeMillis())
- + " - messages received : " + msg_count);
- }
- }
-
- private void handleMessage(Message m)
- {
- if (m == null) { return; }
-
- try
- {
- if (m instanceof TextMessage && ((TextMessage) m).getText().equals("End"))
- {
- MessageProducer temp = getSsn().createProducer(m.getJMSReplyTo());
- Message controlMsg = getSsn().createTextMessage();
- temp.send(controlMsg);
- if (isTransacted())
- {
- getSsn().commit();
- }
- temp.close();
- }
- else
- {
-
- int seq = m.getIntProperty("sequence");
- if (checkForDups)
- {
- if (seq == 0)
- {
- sequence = 0; // wrap around for each iteration
- System.out.println("Received " + duplicateMessages.size() + " duplicate messages during the iteration");
- duplicateMessages.clear();
- }
-
- if (seq < sequence)
- {
- duplicateMessages.add(seq);
- }
- else if (seq == sequence)
- {
- sequence++;
- msg_count ++;
- }
- else
- {
- // Multiple publishers are not allowed in this test case.
- // So out of order messages are not allowed.
- throw new Exception(": Received an out of order message (expected="
- + sequence + ",received=" + seq + ")" );
- }
- }
- else
- {
- msg_count ++;
- }
-
- // Please note that this test case doesn't expect duplicates
- // When testing for transactions.
- if (isTransacted() && msg_count % getTxSize() == 0)
- {
- getSsn().commit();
- }
- }
- }
- catch (Exception e)
- {
- e.printStackTrace();
- handleError("Exception receiving messages",e);
- }
- }
-
- // Receiver host port address
- public static void main(String[] args) throws Exception
- {
- String host = "127.0.0.1";
- int port = 5672;
- String addr = "message_queue";
-
- if (args.length > 0)
- {
- host = args[0];
- }
- if (args.length > 1)
- {
- port = Integer.parseInt(args[1]);
- }
- if (args.length > 2)
- {
- addr = args[2];
- }
-
- AMQConnection con = new AMQConnection(
- "amqp://username:password@topicClientid/test?brokerlist='tcp://"
- + host + ":" + port + "'");
-
- Receiver rcv = new Receiver(con,addr);
- rcv.run();
- }
-
-}
diff --git a/java/tools/src/main/java/org/apache/qpid/testkit/Sender.java b/java/tools/src/main/java/org/apache/qpid/testkit/Sender.java
deleted file mode 100644
index 14b9b7302f..0000000000
--- a/java/tools/src/main/java/org/apache/qpid/testkit/Sender.java
+++ /dev/null
@@ -1,197 +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.testkit;
-
-
-import java.text.DateFormat;
-import java.text.DecimalFormat;
-import java.text.NumberFormat;
-import java.text.SimpleDateFormat;
-import java.util.Random;
-
-import javax.jms.Connection;
-import javax.jms.DeliveryMode;
-import javax.jms.Destination;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-import javax.jms.Session;
-import javax.jms.TextMessage;
-
-import org.apache.qpid.client.AMQAnyDestination;
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.tools.MessageFactory;
-
-/**
- * A generic sender which sends a stream of messages
- * to a given address in a broker (host/port)
- * until told to stop by killing it.
- *
- * It has a feedback loop to ensure it doesn't fill
- * up queues due to a slow consumer.
- *
- * It doesn't check for correctness or measure anything
- * leaving those concerns to another entity.
- * However it prints a timestamp every x secs(-Dreport_frequency)
- * as checkpoint to figure out how far the test has progressed if
- * a failure occurred.
- *
- * It also takes in an optional Error handler to
- * pass out any error in addition to writing them to std err.
- *
- * This is intended more as building block to create
- * more complex test cases. However there is a main method
- * provided to use this standalone.
- *
- * The following options are available and configurable
- * via jvm args.
- *
- * msg_size (256)
- * msg_count (10) - # messages before waiting for feedback
- * sleep_time (1000 ms) - sleep time btw each iteration
- * report_frequency - how often a timestamp is printed
- * durable
- * transacted
- * tx_size - size of transaction batch in # msgs.
- */
-public class Sender extends Client
-{
- protected int msg_size = 256;
- protected int msg_count = 10;
- protected int iterations = -1;
- protected long sleep_time = 1000;
-
- protected Destination dest = null;
- protected Destination replyTo = null;
- protected DateFormat df = new SimpleDateFormat("yyyy.MM.dd 'at' HH:mm:ss");
- protected NumberFormat nf = new DecimalFormat("##.00");
-
- protected MessageProducer producer;
- Random gen = new Random(19770905);
-
- public Sender(Connection con,String addr) throws Exception
- {
- super(con);
- this.msg_size = Integer.getInteger("msg_size", 100);
- this.msg_count = Integer.getInteger("msg_count", 10);
- this.iterations = Integer.getInteger("iterations", -1);
- this.sleep_time = Long.getLong("sleep_time", 1000);
- this.setSsn(con.createSession(isTransacted(),Session.AUTO_ACKNOWLEDGE));
- this.dest = new AMQAnyDestination(addr);
- this.producer = getSsn().createProducer(dest);
- this.replyTo = getSsn().createTemporaryQueue();
-
- System.out.println("Sending messages to : " + addr);
- }
-
- /*
- * If msg_size not specified it generates a message
- * between 500-1500 bytes.
- */
- protected Message getNextMessage() throws Exception
- {
- int s = msg_size == -1 ? 500 + gen.nextInt(1000) : msg_size;
- Message msg = (getContentType().equals("text/plain")) ?
- MessageFactory.createTextMessage(getSsn(), s):
- MessageFactory.createBytesMessage(getSsn(), s);
-
- msg.setJMSDeliveryMode((isDurable()) ? DeliveryMode.PERSISTENT
- : DeliveryMode.NON_PERSISTENT);
- return msg;
- }
-
- public void run()
- {
- try
- {
- boolean infinite = (iterations == -1);
- for (int x=0; infinite || x < iterations; x++)
- {
- long now = System.currentTimeMillis();
- if (now - getStartTime() >= getReportFrequency())
- {
- System.out.println(df.format(now) + " - iterations : " + x);
- setStartTime(now);
- }
-
- for (int i = 0; i < msg_count; i++)
- {
- Message msg = getNextMessage();
- msg.setIntProperty("sequence",i);
- producer.send(msg);
- if (isTransacted() && msg_count % getTxSize() == 0)
- {
- getSsn().commit();
- }
- }
- TextMessage m = getSsn().createTextMessage("End");
- m.setJMSReplyTo(replyTo);
- producer.send(m);
-
- if (isTransacted())
- {
- getSsn().commit();
- }
-
- MessageConsumer feedbackConsumer = getSsn().createConsumer(replyTo);
- feedbackConsumer.receive();
- feedbackConsumer.close();
- if (isTransacted())
- {
- getSsn().commit();
- }
- Thread.sleep(sleep_time);
- }
- }
- catch (Exception e)
- {
- handleError("Exception sending messages",e);
- }
- }
-
- // Receiver host port address
- public static void main(String[] args) throws Exception
- {
- String host = "127.0.0.1";
- int port = 5672;
- String addr = "message_queue";
-
- if (args.length > 0)
- {
- host = args[0];
- }
- if (args.length > 1)
- {
- port = Integer.parseInt(args[1]);
- }
- if (args.length > 2)
- {
- addr = args[2];
- }
-
- AMQConnection con = new AMQConnection(
- "amqp://username:password@topicClientid/test?brokerlist='tcp://"
- + host + ":" + port + "'");
-
- Sender sender = new Sender(con,addr);
- sender.run();
- }
-}
diff --git a/java/tools/src/main/java/org/apache/qpid/testkit/TestLauncher.java b/java/tools/src/main/java/org/apache/qpid/testkit/TestLauncher.java
deleted file mode 100644
index 72ca48e1c9..0000000000
--- a/java/tools/src/main/java/org/apache/qpid/testkit/TestLauncher.java
+++ /dev/null
@@ -1,370 +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.testkit;
-
-
-import java.io.ByteArrayOutputStream;
-import java.io.PrintStream;
-import java.text.DateFormat;
-import java.text.DecimalFormat;
-import java.text.NumberFormat;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.jms.Destination;
-import javax.jms.JMSException;
-import javax.jms.MessageProducer;
-import javax.jms.Session;
-import javax.jms.TextMessage;
-
-import org.apache.log4j.BasicConfigurator;
-import org.apache.log4j.ConsoleAppender;
-import org.apache.log4j.Level;
-import org.apache.log4j.Logger;
-import org.apache.log4j.PatternLayout;
-import org.apache.qpid.client.AMQAnyDestination;
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.client.AMQTopic;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.thread.Threading;
-
-/**
- * A basic test case class that could launch a Sender/Receiver
- * or both, each on it's own separate thread.
- *
- * If con_count == ssn_count, then each entity created will have
- * it's own Connection. Else if con_count < ssn_count, then
- * a connection will be shared by ssn_count/con_count # of entities.
- *
- * The if both sender and receiver options are set, it will
- * share a connection.
- *
- * The following options are available as jvm args
- * host, port
- * con_count,ssn_count
- * con_idle_time - which determines heartbeat
- * sender, receiver - booleans which indicate which entity to create.
- * Setting them both is also a valid option.
- */
-public class TestLauncher implements ErrorHandler
-{
- protected String host = "127.0.0.1";
- protected int port = 5672;
- protected int sessions_per_con = 1;
- protected int connection_count = 1;
- protected long heartbeat = 5000;
- protected boolean sender = false;
- protected boolean receiver = false;
- protected boolean useUniqueDests = false;
- protected String url;
-
- protected String address = "my_queue; {create: always}";
- protected boolean durable = false;
- protected String failover = "";
- protected AMQConnection controlCon;
- protected Destination controlDest = null;
- protected Session controlSession = null;
- protected MessageProducer statusSender;
- protected List<AMQConnection> clients = new ArrayList<AMQConnection>();
- protected DateFormat df = new SimpleDateFormat("yyyy.MM.dd 'at' HH:mm:ss");
- protected NumberFormat nf = new DecimalFormat("##.00");
- protected String testName;
-
- public TestLauncher()
- {
- testName = System.getProperty("test_name","UNKNOWN");
- host = System.getProperty("host", "127.0.0.1");
- port = Integer.getInteger("port", 5672);
- sessions_per_con = Integer.getInteger("ssn_per_con", 1);
- connection_count = Integer.getInteger("con_count", 1);
- heartbeat = Long.getLong("heartbeat", 5);
- sender = Boolean.getBoolean("sender");
- receiver = Boolean.getBoolean("receiver");
- useUniqueDests = Boolean.getBoolean("use_unique_dests");
-
- failover = System.getProperty("failover", "");
- durable = Boolean.getBoolean("durable");
-
- url = "amqp://username:password@topicClientid/test?brokerlist='tcp://"
- + host + ":" + port + "?heartbeat='" + heartbeat+ "''";
-
- if (failover.equalsIgnoreCase("failover_exchange"))
- {
- url += "&failover='failover_exchange'";
-
- System.out.println("Failover exchange " + url );
- }
-
- configureLogging();
- }
-
- protected void configureLogging()
- {
- PatternLayout layout = new PatternLayout();
- layout.setConversionPattern("%t %d %p [%c{4}] %m%n");
- BasicConfigurator.configure(new ConsoleAppender(layout));
-
- String logLevel = System.getProperty("log.level","warn");
- String logComponent = System.getProperty("log.comp","org.apache.qpid");
-
- Logger logger = Logger.getLogger(logComponent);
- logger.setLevel(Level.toLevel(logLevel, Level.WARN));
-
- System.out.println("Level " + logger.getLevel());
-
- }
-
- public void setUpControlChannel()
- {
- try
- {
- controlCon = new AMQConnection(url);
- controlCon.start();
-
- controlDest = new AMQAnyDestination("control; {create: always}"); // durable
-
- // Create the session to setup the messages
- controlSession = controlCon.createSession(false, Session.AUTO_ACKNOWLEDGE);
- statusSender = controlSession.createProducer(controlDest);
-
- }
- catch (Exception e)
- {
- handleError("Error while setting up the test",e);
- }
- }
-
- public void cleanup()
- {
- try
- {
- controlSession.close();
- controlCon.close();
- for (AMQConnection con : clients)
- {
- con.close();
- }
- }
- catch (Exception e)
- {
- handleError("Error while tearing down the test",e);
- }
- }
-
- public void start(String addr)
- {
- try
- {
- if (addr == null)
- {
- addr = address;
- }
-
- int ssn_per_con = sessions_per_con;
- String addrTemp = addr;
- for (int i = 0; i< connection_count; i++)
- {
- AMQConnection con = new AMQConnection(url);
- con.start();
- clients.add(con);
- for (int j = 0; j< ssn_per_con; j++)
- {
- String index = createPrefix(i,j);
- if (useUniqueDests)
- {
- addrTemp = modifySubject(index,addr);
- }
-
- if (sender)
- {
- createSender(index,con,addrTemp,this);
- }
-
- if (receiver)
- {
- System.out.println("########## Creating receiver ##################");
-
- createReceiver(index,con,addrTemp,this);
- }
- }
- }
- }
- catch (Exception e)
- {
- handleError("Exception while setting up the test",e);
- }
-
- }
-
- protected void createReceiver(String index,final AMQConnection con, final String addr, final ErrorHandler h)
- {
- Runnable r = new Runnable()
- {
- public void run()
- {
- try
- {
- Receiver rcv = new Receiver(con,addr);
- rcv.setErrorHandler(h);
- rcv.run();
- }
- catch (Exception e)
- {
- h.handleError("Error Starting Receiver", e);
- }
- }
- };
-
- Thread t = null;
- try
- {
- t = Threading.getThreadFactory().createThread(r);
- }
- catch(Exception e)
- {
- handleError("Error creating Receive thread",e);
- }
-
- t.setName("ReceiverThread-" + index);
- t.start();
- }
-
- protected void createSender(String index,final AMQConnection con, final String addr, final ErrorHandler h)
- {
- Runnable r = new Runnable()
- {
- public void run()
- {
- try
- {
- Sender sender = new Sender(con, addr);
- sender.setErrorHandler(h);
- sender.run();
- }
- catch (Exception e)
- {
- h.handleError("Error Starting Sender", e);
- }
- }
- };
-
- Thread t = null;
- try
- {
- t = Threading.getThreadFactory().createThread(r);
- }
- catch(Exception e)
- {
- handleError("Error creating Sender thread",e);
- }
-
- t.setName("SenderThread-" + index);
- t.start();
- }
-
- public synchronized void handleError(String msg,Exception e)
- {
- // In case sending the message fails
- StringBuilder sb = new StringBuilder();
- sb.append(msg);
- sb.append(" @ ");
- sb.append(df.format(new Date(System.currentTimeMillis())));
- sb.append(" ");
- sb.append(e.getMessage());
- System.err.println(sb.toString());
- e.printStackTrace();
-
- try
- {
- TextMessage errorMsg = controlSession.createTextMessage();
- errorMsg.setStringProperty("status", "error");
- errorMsg.setStringProperty("desc", msg);
- errorMsg.setStringProperty("time", df.format(new Date(System.currentTimeMillis())));
- errorMsg.setStringProperty("exception-trace", serializeStackTrace(e));
-
- System.out.println("Msg " + errorMsg);
-
- statusSender.send(errorMsg);
- }
- catch (JMSException e1)
- {
- e1.printStackTrace();
- }
- }
-
- private String serializeStackTrace(Exception e)
- {
- ByteArrayOutputStream bOut = new ByteArrayOutputStream();
- PrintStream printStream = new PrintStream(bOut);
- e.printStackTrace(printStream);
- printStream.close();
- return bOut.toString();
- }
-
- private String createPrefix(int i, int j)
- {
- return String.valueOf(i).concat(String.valueOf(j));
- }
-
- /**
- * A basic helper function to modify the subjects by
- * appending an index.
- */
- private String modifySubject(String index,String addr)
- {
- if (addr.indexOf("/") > 0)
- {
- addr = addr.substring(0,addr.indexOf("/")+1) +
- index +
- addr.substring(addr.indexOf("/")+1,addr.length());
- }
- else if (addr.indexOf(";") > 0)
- {
- addr = addr.substring(0,addr.indexOf(";")) +
- "/" + index +
- addr.substring(addr.indexOf(";"),addr.length());
- }
- else
- {
- addr = addr + "/" + index;
- }
-
- return addr;
- }
-
- public static void main(String[] args)
- {
- final TestLauncher test = new TestLauncher();
- test.setUpControlChannel();
- System.out.println("args.length " + args.length);
- System.out.println("args [0] " + args [0]);
- test.start(args.length > 0 ? args [0] : null);
- Runtime.getRuntime().addShutdownHook(new Thread() {
- public void run() { test.cleanup(); }
- });
-
- }
-}
diff --git a/java/tools/src/main/java/org/apache/qpid/tools/JNDICheck.java b/java/tools/src/main/java/org/apache/qpid/tools/JNDICheck.java
deleted file mode 100644
index 2390516ef0..0000000000
--- a/java/tools/src/main/java/org/apache/qpid/tools/JNDICheck.java
+++ /dev/null
@@ -1,200 +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.tools;
-
-import org.apache.qpid.client.AMQDestination;
-import org.apache.qpid.client.AMQConnectionFactory;
-import org.apache.qpid.jms.FailoverPolicy;
-
-import javax.naming.Context;
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-import java.util.Properties;
-import java.util.Hashtable;
-import java.util.Enumeration;
-import java.util.List;
-import java.util.LinkedList;
-import java.io.IOException;
-import java.io.File;
-import java.io.FileInputStream;
-
-public class JNDICheck
-{
- private static final String QUEUE = "queue.";
- private static final String TOPIC = "topic.";
- private static final String DESTINATION = "destination.";
- private static final String CONNECTION_FACTORY = "connectionfactory.";
-
- public static void main(String[] args)
- {
-
- if (args.length != 1)
- {
- usage();
- }
-
- String propertyFile = args[0];
-
- new JNDICheck(propertyFile);
- }
-
- private static void usage()
- {
- exit("Usage: JNDICheck <JNDI Config file>", 0);
- }
-
- private static void exit(String message, int exitCode)
- {
- System.err.println(message);
- System.exit(exitCode);
- }
-
- private static String JAVA_NAMING = "java.naming.factory.initial";
-
- Context _context = null;
- Hashtable _environment = null;
-
- public JNDICheck(String propertyFile)
- {
-
- // Load JNDI properties
- Properties properties = new Properties();
-
- try
- {
- properties.load(new FileInputStream(new File(propertyFile)));
- }
- catch (IOException e)
- {
- exit("Unable to open property file:" + propertyFile + ". Due to:" + e.getMessage(), 1);
- }
-
- //Create the initial context
- try
- {
-
- System.setProperty(JAVA_NAMING, properties.getProperty(JAVA_NAMING));
-
- _context = new InitialContext(properties);
-
- _environment = _context.getEnvironment();
-
- Enumeration keys = _environment.keys();
-
- List<String> queues = new LinkedList<String>();
- List<String> topics = new LinkedList<String>();
- List<String> destinations = new LinkedList<String>();
- List<String> connectionFactories = new LinkedList<String>();
-
- while (keys.hasMoreElements())
- {
- String key = keys.nextElement().toString();
-
- if (key.startsWith(QUEUE))
- {
- queues.add(key);
- }
- else if (key.startsWith(TOPIC))
- {
- topics.add(key);
- }
- else if (key.startsWith(DESTINATION))
- {
- destinations.add(key);
- }
- else if (key.startsWith(CONNECTION_FACTORY))
- {
- connectionFactories.add(key);
- }
- }
-
- printHeader(propertyFile);
- printEntries(QUEUE, queues);
- printEntries(TOPIC, topics);
- printEntries(DESTINATION, destinations);
- printEntries(CONNECTION_FACTORY, connectionFactories);
-
- }
- catch (NamingException e)
- {
- exit("Unable to load JNDI Context due to:" + e.getMessage(), 1);
- }
-
- }
-
- private void printHeader(String file)
- {
- print("JNDI file :" + file);
- }
-
- private void printEntries(String type, List<String> list)
- {
- if (list.size() > 0)
- {
- String name = type.substring(0, 1).toUpperCase() + type.substring(1, type.length() - 1);
- print(name + " elements in file:");
- printList(list);
- print("");
- }
- }
-
- private void printList(List<String> list)
- {
- for (String item : list)
- {
- String key = item.substring(item.indexOf('.') + 1);
-
- try
- {
- print(key, _context.lookup(key));
- }
- catch (NamingException e)
- {
- exit("Error: item " + key + " no longer in context.", 1);
- }
- }
- }
-
- private void print(String key, Object object)
- {
- if (object instanceof AMQDestination)
- {
- print(key + ":" + object);
- }
- else if (object instanceof AMQConnectionFactory)
- {
- AMQConnectionFactory factory = (AMQConnectionFactory) object;
- print(key + ":Connection");
- print("ConnectionURL:");
- print(factory.getConnectionURL().toString());
- print("FailoverPolicy");
- print(new FailoverPolicy(factory.getConnectionURL(),null).toString());
- print("");
- }
- }
-
- private void print(String msg)
- {
- System.out.println(msg);
- }
-
-}
diff --git a/java/tools/src/main/java/org/apache/qpid/tools/LatencyTest.java b/java/tools/src/main/java/org/apache/qpid/tools/LatencyTest.java
deleted file mode 100644
index b88b242e6d..0000000000
--- a/java/tools/src/main/java/org/apache/qpid/tools/LatencyTest.java
+++ /dev/null
@@ -1,349 +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.tools;
-
-import java.io.FileOutputStream;
-import java.io.PrintWriter;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.locks.Condition;
-import java.util.concurrent.locks.Lock;
-import java.util.concurrent.locks.ReentrantLock;
-
-import javax.jms.BytesMessage;
-import javax.jms.DeliveryMode;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageListener;
-import javax.jms.MessageProducer;
-import javax.jms.TextMessage;
-
-import org.apache.qpid.thread.Threading;
-
-/**
- * Latency test sends an x number of messages in warmup mode and wait for a confirmation
- * from the consumer that it has successfully consumed them and ready to start the
- * test. It will start sending y number of messages and each message will contain a time
- * stamp. This will be used at the receiving end to measure the latency.
- *
- * It is important to have a sufficiently large number for the warmup count to
- * ensure the system is in steady state before the test is started.
- *
- * If you plan to plot the latencies then msg_count should be a smaller number (ex 500 or 1000)
- * You also need to specify a file name using -Dfile=/home/rajith/latency.log.1
- *
- * The idea is to get a latency sample for the system once it achieves steady state.
- *
- */
-
-public class LatencyTest extends PerfBase implements MessageListener
-{
- MessageProducer producer;
- MessageConsumer consumer;
- Message msg;
- byte[] payload;
- long maxLatency = 0;
- long minLatency = Long.MAX_VALUE;
- long totalLatency = 0; // to calculate avg latency.
- int rcvdMsgCount = 0;
- double stdDev = 0;
- double avgLatency = 0;
- boolean warmup_mode = true;
- boolean transacted = false;
- int transSize = 0;
-
- final List<Long> latencies;
- final Lock lock = new ReentrantLock();
- final Condition warmedUp;
- final Condition testCompleted;
-
- public LatencyTest()
- {
- super();
- warmedUp = lock.newCondition();
- testCompleted = lock.newCondition();
- // Storing the following two for efficiency
- transacted = params.isTransacted();
- transSize = params.getTransactionSize();
- latencies = new ArrayList <Long>(params.getMsgCount());
- }
-
- public void setUp() throws Exception
- {
- super.setUp();
- consumer = session.createConsumer(dest);
- consumer.setMessageListener(this);
-
- // if message caching is enabled we pre create the message
- // else we pre create the payload
- if (params.isCacheMessage())
- {
- msg = MessageFactory.createBytesMessage(session, params.getMsgSize());
- msg.setJMSDeliveryMode(params.isDurable()?
- DeliveryMode.PERSISTENT :
- DeliveryMode.NON_PERSISTENT
- );
- }
- else
- {
- payload = MessageFactory.createMessagePayload(params.getMsgSize()).getBytes();
- }
-
- producer = session.createProducer(dest);
- producer.setDisableMessageID(params.isDisableMessageID());
- producer.setDisableMessageTimestamp(params.isDisableTimestamp());
- }
-
- protected Message getNextMessage() throws Exception
- {
- if (params.isCacheMessage())
- {
- return msg;
- }
- else
- {
- msg = session.createBytesMessage();
- ((BytesMessage)msg).writeBytes(payload);
- return msg;
- }
- }
-
- public void warmup()throws Exception
- {
- System.out.println("Warming up......");
- int count = params.getWarmupCount();
- for (int i=0; i < count; i++)
- {
- producer.send(getNextMessage());
- }
- Message msg = session.createTextMessage("End");
- producer.send(msg);
-
- if (params.isTransacted())
- {
- session.commit();
- }
-
- try
- {
- lock.lock();
- warmedUp.await();
- }
- finally
- {
- lock.unlock();
- }
- }
-
- public void onMessage(Message msg)
- {
- try
- {
- if (msg instanceof TextMessage && ((TextMessage)msg).getText().equals("End"))
- {
- if (warmup_mode)
- {
- warmup_mode = false;
- try
- {
- lock.lock();
- warmedUp.signal();
- }
- finally
- {
- lock.unlock();
- }
- }
- else
- {
- computeStats();
- }
- }
- else if (!warmup_mode)
- {
- long time = System.currentTimeMillis();
- rcvdMsgCount ++;
-
- if (transacted && (rcvdMsgCount % transSize == 0))
- {
- session.commit();
- }
-
- long latency = time - msg.getJMSTimestamp();
- latencies.add(latency);
- totalLatency = totalLatency + latency;
- }
-
- }
- catch(Exception e)
- {
- handleError(e,"Error when receiving messages");
- }
-
- }
-
- private void computeStats()
- {
- avgLatency = (double)totalLatency/(double)rcvdMsgCount;
- double sigma = 0;
-
- for (long latency: latencies)
- {
- maxLatency = Math.max(maxLatency, latency);
- minLatency = Math.min(minLatency, latency);
- sigma = sigma + Math.pow(latency - avgLatency,2);
- }
-
- stdDev = Math.sqrt(sigma/(rcvdMsgCount -1));
-
- try
- {
- lock.lock();
- testCompleted.signal();
- }
- finally
- {
- lock.unlock();
- }
- }
-
- public void writeToFile() throws Exception
- {
- String fileName = System.getProperty("file");
- PrintWriter writer = new PrintWriter(new FileOutputStream(fileName));
- for (long latency: latencies)
- {
- writer.println(String.valueOf(latency));
- }
- writer.flush();
- writer.close();
- }
-
- public void printToConsole()
- {
- System.out.println(new StringBuilder("Total Msgs Received : ").append(rcvdMsgCount).toString());
- System.out.println(new StringBuilder("Standard Deviation : ").
- append(df.format(stdDev)).
- append(" ms").toString());
- System.out.println(new StringBuilder("Avg Latency : ").
- append(df.format(avgLatency)).
- append(" ms").toString());
- System.out.println(new StringBuilder("Min Latency : ").
- append(minLatency).
- append(" ms").toString());
- System.out.println(new StringBuilder("Max Latency : ").
- append(maxLatency).
- append(" ms").toString());
- System.out.println("Completed the test......\n");
- }
-
- public void startTest() throws Exception
- {
- System.out.println("Starting test......");
- int count = params.getMsgCount();
-
- for(int i=0; i < count; i++ )
- {
- Message msg = getNextMessage();
- msg.setJMSTimestamp(System.currentTimeMillis());
- producer.send(msg);
- if ( transacted && ((i+1) % transSize == 0))
- {
- session.commit();
- }
- }
- Message msg = session.createTextMessage("End");
- producer.send(msg);
- if (params.isTransacted())
- {
- session.commit();
- }
- }
-
- public void tearDown() throws Exception
- {
- try
- {
- lock.lock();
- testCompleted.await();
- }
- finally
- {
- lock.unlock();
- }
-
- producer.close();
- consumer.close();
- session.close();
- con.close();
- }
-
- public void test()
- {
- try
- {
- setUp();
- warmup();
- startTest();
- tearDown();
- }
- catch(Exception e)
- {
- handleError(e,"Error when running test");
- }
- }
-
-
- public static void main(String[] args)
- {
- final LatencyTest latencyTest = new LatencyTest();
- Runnable r = new Runnable()
- {
- public void run()
- {
- latencyTest.test();
- latencyTest.printToConsole();
- if (System.getProperty("file") != null)
- {
- try
- {
- latencyTest.writeToFile();
- }
- catch(Exception e)
- {
- e.printStackTrace();
- }
- }
- }
- };
-
- Thread t;
- try
- {
- t = Threading.getThreadFactory().createThread(r);
- }
- catch(Exception e)
- {
- throw new Error("Error creating latency test thread",e);
- }
- t.start();
- }
-} \ No newline at end of file
diff --git a/java/tools/src/main/java/org/apache/qpid/tools/MessageFactory.java b/java/tools/src/main/java/org/apache/qpid/tools/MessageFactory.java
deleted file mode 100644
index 8ab1379fce..0000000000
--- a/java/tools/src/main/java/org/apache/qpid/tools/MessageFactory.java
+++ /dev/null
@@ -1,64 +0,0 @@
-package org.apache.qpid.tools;
-/*
- *
- * 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 javax.jms.BytesMessage;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.Session;
-import javax.jms.TextMessage;
-
-public class MessageFactory
-{
- public static Message createBytesMessage(Session ssn, int size) throws JMSException
- {
- BytesMessage msg = ssn.createBytesMessage();
- msg.writeBytes(createMessagePayload(size).getBytes());
- return msg;
- }
-
- public static Message createTextMessage(Session ssn, int size) throws JMSException
- {
- TextMessage msg = ssn.createTextMessage();
- msg.setText(createMessagePayload(size));
- return msg;
- }
-
- public static String createMessagePayload(int size)
- {
- String msgData = "Qpid Test Message";
-
- StringBuffer buf = new StringBuffer(size);
- int count = 0;
- while (count <= (size - msgData.length()))
- {
- buf.append(msgData);
- count += msgData.length();
- }
- if (count < size)
- {
- buf.append(msgData, 0, size - count);
- }
-
- return buf.toString();
- }
-}
diff --git a/java/tools/src/main/java/org/apache/qpid/tools/PerfBase.java b/java/tools/src/main/java/org/apache/qpid/tools/PerfBase.java
deleted file mode 100644
index ac597d17de..0000000000
--- a/java/tools/src/main/java/org/apache/qpid/tools/PerfBase.java
+++ /dev/null
@@ -1,78 +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.tools;
-
-import java.text.DecimalFormat;
-import java.util.Hashtable;
-
-import javax.jms.Connection;
-import javax.jms.ConnectionFactory;
-import javax.jms.Destination;
-import javax.jms.Session;
-import javax.naming.Context;
-import javax.naming.InitialContext;
-
-import org.apache.qpid.client.AMQAnyDestination;
-import org.apache.qpid.client.AMQConnection;
-
-public class PerfBase
-{
- TestParams params;
- Connection con;
- Session session;
- Destination dest;
- Destination feedbackDest;
- DecimalFormat df = new DecimalFormat("###.##");
-
- public PerfBase()
- {
- params = new TestParams();
- }
-
- public void setUp() throws Exception
- {
-
- if (params.getHost().equals("") || params.getPort() == -1)
- {
- con = new AMQConnection(params.getUrl());
- }
- else
- {
- con = new AMQConnection(params.getHost(),params.getPort(),"guest","guest","test","test");
- }
- con.start();
- session = con.createSession(params.isTransacted(),
- params.isTransacted()? Session.SESSION_TRANSACTED:params.getAckMode());
-
- dest = new AMQAnyDestination(params.getAddress());
- }
-
- public void handleError(Exception e,String msg)
- {
- StringBuilder sb = new StringBuilder();
- sb.append(msg);
- sb.append(" ");
- sb.append(e.getMessage());
- System.err.println(sb.toString());
- e.printStackTrace();
- }
-}
-
diff --git a/java/tools/src/main/java/org/apache/qpid/tools/PerfConsumer.java b/java/tools/src/main/java/org/apache/qpid/tools/PerfConsumer.java
deleted file mode 100644
index 0ef0455a64..0000000000
--- a/java/tools/src/main/java/org/apache/qpid/tools/PerfConsumer.java
+++ /dev/null
@@ -1,267 +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.tools;
-
-import javax.jms.Destination;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageListener;
-import javax.jms.MessageProducer;
-import javax.jms.TextMessage;
-
-import org.apache.qpid.thread.Threading;
-
-/**
- * PerfConsumer will receive x no of messages in warmup mode.
- * Once it receives the Start message it will then signal the PerfProducer.
- * It will start recording stats from the first message it receives after
- * the warmup mode is done.
- *
- * The following calculations are done.
- * The important numbers to look at is
- * a) Avg Latency
- * b) System throughput.
- *
- * Latency.
- * =========
- * Currently this test is written with the assumption that either
- * a) The Perf Producer and Consumer are on the same machine
- * b) They are on separate machines that have their time synced via a Time Server
- *
- * In order to calculate latency the producer inserts a timestamp
- * hen the message is sent. The consumer will note the current time the message is
- * received and will calculate the latency as follows
- * latency = rcvdTime - msg.getJMSTimestamp()
- *
- * Through out the test it will keep track of the max and min latency to show the
- * variance in latencies.
- *
- * Avg latency is measured by adding all latencies and dividing by the total msgs.
- * You can also compute this by (rcvdTime - testStartTime)/rcvdMsgCount
- *
- * Throughput
- * ===========
- * System throughput is calculated as follows
- * rcvdMsgCount/(rcvdTime - testStartTime)
- *
- * Consumer rate is calculated as
- * rcvdMsgCount/(rcvdTime - startTime)
- *
- * Note that the testStartTime referes to when the producer sent the first message
- * and startTime is when the consumer first received a message.
- *
- * rcvdTime keeps track of when the last message is received.
- *
- * All throughput rates are given as msg/sec so the rates are multiplied by 1000.
- *
- */
-
-public class PerfConsumer extends PerfBase implements MessageListener
-{
- MessageConsumer consumer;
- long maxLatency = 0;
- long minLatency = Long.MAX_VALUE;
- long totalLatency = 0; // to calculate avg latency.
- int rcvdMsgCount = 0;
- long testStartTime = 0; // to measure system throughput
- long startTime = 0; // to measure consumer throughput
- long rcvdTime = 0;
- boolean transacted = false;
- int transSize = 0;
-
- final Object lock = new Object();
-
- public PerfConsumer()
- {
- super();
- }
-
- public void setUp() throws Exception
- {
- super.setUp();
- consumer = session.createConsumer(dest);
-
- // Storing the following two for efficiency
- transacted = params.isTransacted();
- transSize = params.getTransactionSize();
- }
-
- public void warmup()throws Exception
- {
- System.out.println("Warming up......");
-
- boolean start = false;
- while (!start)
- {
- Message msg = consumer.receive();
- if (msg instanceof TextMessage)
- {
- if (((TextMessage)msg).getText().equals("End"))
- {
- start = true;
- MessageProducer temp = session.createProducer(msg.getJMSReplyTo());
- temp.send(session.createMessage());
- if (params.isTransacted())
- {
- session.commit();
- }
- temp.close();
- }
- }
- }
- }
-
- public void startTest() throws Exception
- {
- System.out.println("Starting test......");
- consumer.setMessageListener(this);
- }
-
- public void printResults() throws Exception
- {
- synchronized (lock)
- {
- lock.wait();
- }
-
- double avgLatency = (double)totalLatency/(double)rcvdMsgCount;
- double throughput = ((double)rcvdMsgCount/(double)(rcvdTime - testStartTime))*1000;
- double consRate = ((double)rcvdMsgCount/(double)(rcvdTime - startTime))*1000;
- System.out.println(new StringBuilder("Total Msgs Received : ").append(rcvdMsgCount).toString());
- System.out.println(new StringBuilder("Consumer rate : ").
- append(df.format(consRate)).
- append(" msg/sec").toString());
- System.out.println(new StringBuilder("System Throughput : ").
- append(df.format(throughput)).
- append(" msg/sec").toString());
- System.out.println(new StringBuilder("Avg Latency : ").
- append(df.format(avgLatency)).
- append(" ms").toString());
- System.out.println(new StringBuilder("Min Latency : ").
- append(minLatency).
- append(" ms").toString());
- System.out.println(new StringBuilder("Max Latency : ").
- append(maxLatency).
- append(" ms").toString());
- System.out.println("Completed the test......\n");
- }
-
- public void notifyCompletion(Destination replyTo) throws Exception
- {
- MessageProducer tmp = session.createProducer(replyTo);
- Message endMsg = session.createMessage();
- tmp.send(endMsg);
- if (params.isTransacted())
- {
- session.commit();
- }
- tmp.close();
- }
-
- public void tearDown() throws Exception
- {
- consumer.close();
- session.close();
- con.close();
- }
-
- public void onMessage(Message msg)
- {
- try
- {
- if (msg instanceof TextMessage && ((TextMessage)msg).getText().equals("End"))
- {
- notifyCompletion(msg.getJMSReplyTo());
-
- synchronized (lock)
- {
- lock.notifyAll();
- }
- }
- else
- {
- rcvdTime = System.currentTimeMillis();
- rcvdMsgCount ++;
-
- if (rcvdMsgCount == 1)
- {
- startTime = rcvdTime;
- testStartTime = msg.getJMSTimestamp();
- }
-
- if (transacted && (rcvdMsgCount % transSize == 0))
- {
- session.commit();
- }
-
- long latency = rcvdTime - msg.getJMSTimestamp();
- maxLatency = Math.max(maxLatency, latency);
- minLatency = Math.min(minLatency, latency);
- totalLatency = totalLatency + latency;
- }
-
- }
- catch(Exception e)
- {
- handleError(e,"Error when receiving messages");
- }
-
- }
-
- public void test()
- {
- try
- {
- setUp();
- warmup();
- startTest();
- printResults();
- tearDown();
- }
- catch(Exception e)
- {
- handleError(e,"Error when running test");
- }
- }
-
- public static void main(String[] args)
- {
- final PerfConsumer cons = new PerfConsumer();
- Runnable r = new Runnable()
- {
- public void run()
- {
- cons.test();
- }
- };
-
- Thread t;
- try
- {
- t = Threading.getThreadFactory().createThread(r);
- }
- catch(Exception e)
- {
- throw new Error("Error creating consumer thread",e);
- }
- t.start();
- }
-} \ No newline at end of file
diff --git a/java/tools/src/main/java/org/apache/qpid/tools/PerfProducer.java b/java/tools/src/main/java/org/apache/qpid/tools/PerfProducer.java
deleted file mode 100644
index 015d1e6205..0000000000
--- a/java/tools/src/main/java/org/apache/qpid/tools/PerfProducer.java
+++ /dev/null
@@ -1,262 +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.tools;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Random;
-
-import javax.jms.BytesMessage;
-import javax.jms.DeliveryMode;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-
-import org.apache.qpid.thread.Threading;
-
-/**
- * PerfProducer sends an x no of messages in warmup mode and wait for a confirmation
- * from the consumer that it has successfully consumed them and ready to start the
- * test. It will start sending y no of messages and each message will contain a time
- * stamp. This will be used at the receiving end to measure the latency.
- *
- * This is done with the assumption that both consumer and producer are running on
- * the same machine or different machines which have time synced using a time server.
- *
- * This test also calculates the producer rate as follows.
- * rate = msg_count/(time_before_sending_msgs - time_after_sending_msgs)
- *
- * All throughput rates are given as msg/sec so the rates are multiplied by 1000.
- *
- * Rajith - Producer rate is not an accurate perf metric IMO.
- * It is heavily inlfuenced by any in memory buffering.
- * System throughput and latencies calculated by the PerfConsumer are more realistic
- * numbers.
- *
- */
-public class PerfProducer extends PerfBase
-{
- MessageProducer producer;
- Message msg;
- byte[] payload;
- List<byte[]> payloads;
- boolean cacheMsg = false;
- boolean randomMsgSize = false;
- boolean durable = false;
- Random random;
- int msgSizeRange = 1024;
-
- public PerfProducer()
- {
- super();
- }
-
- public void setUp() throws Exception
- {
- super.setUp();
- feedbackDest = session.createTemporaryQueue();
-
- durable = params.isDurable();
-
- // if message caching is enabled we pre create the message
- // else we pre create the payload
- if (params.isCacheMessage())
- {
- cacheMsg = true;
-
- msg = MessageFactory.createBytesMessage(session, params.getMsgSize());
- msg.setJMSDeliveryMode(durable?
- DeliveryMode.PERSISTENT :
- DeliveryMode.NON_PERSISTENT
- );
- }
- else if (params.isRandomMsgSize())
- {
- random = new Random(20080921);
- randomMsgSize = true;
- msgSizeRange = params.getMsgSize();
- payloads = new ArrayList<byte[]>(msgSizeRange);
-
- for (int i=0; i < msgSizeRange; i++)
- {
- payloads.add(MessageFactory.createMessagePayload(i).getBytes());
- }
- }
- else
- {
- payload = MessageFactory.createMessagePayload(params.getMsgSize()).getBytes();
- }
-
- producer = session.createProducer(dest);
- producer.setDisableMessageID(params.isDisableMessageID());
- producer.setDisableMessageTimestamp(params.isDisableTimestamp());
- }
-
- protected Message getNextMessage() throws Exception
- {
- if (cacheMsg)
- {
- return msg;
- }
- else
- {
- msg = session.createBytesMessage();
-
- if (!randomMsgSize)
- {
- ((BytesMessage)msg).writeBytes(payload);
- }
- else
- {
- ((BytesMessage)msg).writeBytes(payloads.get(random.nextInt(msgSizeRange)));
- }
- msg.setJMSDeliveryMode(durable?
- DeliveryMode.PERSISTENT :
- DeliveryMode.NON_PERSISTENT
- );
- return msg;
- }
- }
-
- public void warmup()throws Exception
- {
- System.out.println("Warming up......");
- MessageConsumer tmp = session.createConsumer(feedbackDest);
-
- for (int i=0; i < params.getWarmupCount() -1; i++)
- {
- producer.send(getNextMessage());
- }
- Message msg = session.createTextMessage("End");
- msg.setJMSReplyTo(feedbackDest);
- producer.send(msg);
-
- if (params.isTransacted())
- {
- session.commit();
- }
-
- tmp.receive();
-
- if (params.isTransacted())
- {
- session.commit();
- }
-
- tmp.close();
- }
-
- public void startTest() throws Exception
- {
- System.out.println("Starting test......");
- int count = params.getMsgCount();
- boolean transacted = params.isTransacted();
- int tranSize = params.getTransactionSize();
-
- long start = System.currentTimeMillis();
- for(int i=0; i < count; i++ )
- {
- Message msg = getNextMessage();
- msg.setJMSTimestamp(System.currentTimeMillis());
- producer.send(msg);
- if ( transacted && ((i+1) % tranSize == 0))
- {
- session.commit();
- }
- }
- long time = System.currentTimeMillis() - start;
- double rate = ((double)count/(double)time)*1000;
- System.out.println(new StringBuilder("Producer rate: ").
- append(df.format(rate)).
- append(" msg/sec").
- toString());
- }
-
- public void waitForCompletion() throws Exception
- {
- MessageConsumer tmp = session.createConsumer(feedbackDest);
- Message msg = session.createTextMessage("End");
- msg.setJMSReplyTo(feedbackDest);
- producer.send(msg);
-
- if (params.isTransacted())
- {
- session.commit();
- }
-
- tmp.receive();
-
- if (params.isTransacted())
- {
- session.commit();
- }
-
- tmp.close();
- System.out.println("Consumer has completed the test......");
- }
-
- public void tearDown() throws Exception
- {
- producer.close();
- session.close();
- con.close();
- }
-
- public void test()
- {
- try
- {
- setUp();
- warmup();
- startTest();
- waitForCompletion();
- tearDown();
- }
- catch(Exception e)
- {
- handleError(e,"Error when running test");
- }
- }
-
-
- public static void main(String[] args)
- {
- final PerfProducer prod = new PerfProducer();
- Runnable r = new Runnable()
- {
- public void run()
- {
- prod.test();
- }
- };
-
- Thread t;
- try
- {
- t = Threading.getThreadFactory().createThread(r);
- }
- catch(Exception e)
- {
- throw new Error("Error creating producer thread",e);
- }
- t.start();
- }
-} \ No newline at end of file
diff --git a/java/tools/src/main/java/org/apache/qpid/tools/QpidBench.java b/java/tools/src/main/java/org/apache/qpid/tools/QpidBench.java
deleted file mode 100644
index 602fcc6321..0000000000
--- a/java/tools/src/main/java/org/apache/qpid/tools/QpidBench.java
+++ /dev/null
@@ -1,904 +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.tools;
-
-import static org.apache.qpid.tools.QpidBench.Mode.BOTH;
-import static org.apache.qpid.tools.QpidBench.Mode.CONSUME;
-import static org.apache.qpid.tools.QpidBench.Mode.PUBLISH;
-
-import java.lang.reflect.Field;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.nio.ByteBuffer;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.jms.DeliveryMode;
-import javax.jms.Destination;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageListener;
-import javax.jms.MessageProducer;
-import javax.jms.TextMessage;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.thread.Threading;
-import org.apache.qpid.transport.DeliveryProperties;
-import org.apache.qpid.transport.ExchangeBind;
-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.MessageDeliveryMode;
-import org.apache.qpid.transport.MessageFlowMode;
-import org.apache.qpid.transport.MessageProperties;
-import org.apache.qpid.transport.MessageSubscribe;
-import org.apache.qpid.transport.MessageTransfer;
-import org.apache.qpid.transport.QueueDeclare;
-import org.apache.qpid.transport.SessionException;
-import org.apache.qpid.transport.SessionListener;
-import org.apache.qpid.util.UUIDGen;
-import org.apache.qpid.util.UUIDs;
-
-/**
- * QpidBench
- *
- */
-
-public class QpidBench
-{
-
- static enum Mode
- {
- PUBLISH, CONSUME, BOTH
- }
-
- private static class Options
- {
- private StringBuilder usage = new StringBuilder("qpid-bench <options>");
-
- void usage(String name, String description, Object def)
- {
- String defval = "";
- if (def != null)
- {
- defval = String.format(" (%s)", def);
- }
- usage.append(String.format("\n %-15s%-14s %s", name, defval, description));
- }
-
- public String broker = "localhost";
- public int port = 5672;
- public long count = 1000000;
- public long window = 100000;
- public long sample = window;
- public int size = 1024;
- public Mode mode = BOTH;
- public boolean timestamp = false;
- public boolean message_id = false;
- public boolean message_cache = false;
- public boolean persistent = false;
- public boolean jms_publish = false;
- public boolean jms_consume = false;
- public boolean help = false;
-
- {
- usage("-b, --broker", "the broker hostname", broker);
- }
-
- public void parse__broker(String b)
- {
- this.broker = b;
- }
-
- public void parse_b(String b)
- {
- parse__broker(b);
- }
-
- {
- usage("-p, --port", "the broker port", port);
- }
-
- public void parse__port(String p)
- {
- this.port = Integer.parseInt(p);
- }
-
- public void parse_p(String p)
- {
- parse__port(p);
- }
-
- {
- usage("-c, --count", "the number of messages to send/receive, 0 means no limit", count);
- }
-
- public void parse__count(String c)
- {
- this.count = Long.parseLong(c);
- }
-
- public void parse_c(String c)
- {
- parse__count(c);
- }
-
- {
- usage("-w, --window", "the number of messages to send before blocking, 0 disables", window);
- }
-
- public void parse__window(String w)
- {
- this.window = Long.parseLong(w);
- }
-
- public void parse_w(String w)
- {
- parse__window(w);
- }
-
- {
- usage("--sample", "print stats after this many messages, 0 disables", sample);
- }
-
- public void parse__sample(String s)
- {
- this.sample = Long.parseLong(s);
- }
-
- {
- usage("-i, --interval", "sets both --window and --sample", window);
- }
-
- public void parse__interval(String i)
- {
- this.window = Long.parseLong(i);
- this.sample = window;
- }
-
- public void parse_i(String i)
- {
- parse__interval(i);
- }
-
- {
- usage("-s, --size", "the message size", size);
- }
-
- public void parse__size(String s)
- {
- this.size = Integer.parseInt(s);
- }
-
- public void parse_s(String s)
- {
- parse__size(s);
- }
-
- {
- usage("-m, --mode", "one of publish, consume, or both", mode);
- }
-
- public void parse__mode(String m)
- {
- if (m.equalsIgnoreCase("publish"))
- {
- this.mode = PUBLISH;
- }
- else if (m.equalsIgnoreCase("consume"))
- {
- this.mode = CONSUME;
- }
- else if (m.equalsIgnoreCase("both"))
- {
- this.mode = BOTH;
- }
- else
- {
- throw new IllegalArgumentException
- ("must be one of 'publish', 'consume', or 'both'");
- }
- }
-
- public void parse_m(String m)
- {
- parse__mode(m);
- }
-
- {
- usage("--timestamp", "set timestamps on each message if true", timestamp);
- }
-
- public void parse__timestamp(String t)
- {
- this.timestamp = Boolean.parseBoolean(t);
- }
-
- {
- usage("--mesage-id", "set the message-id on each message if true", message_id);
- }
-
- public void parse__message_id(String m)
- {
- this.message_id = Boolean.parseBoolean(m);
- }
-
- {
- usage("--message-cache", "reuse the same message for each send if true", message_cache);
- }
-
- public void parse__message_cache(String c)
- {
- this.message_cache = Boolean.parseBoolean(c);
- }
-
- {
- usage("--persistent", "set the delivery-mode to persistent if true", persistent);
- }
-
- public void parse__persistent(String p)
- {
- this.persistent = Boolean.parseBoolean(p);
- }
-
- {
- usage("--jms-publish", "use the jms client for publish", jms_publish);
- }
-
- public void parse__jms_publish(String jp)
- {
- this.jms_publish = Boolean.parseBoolean(jp);
- }
-
- {
- usage("--jms-consume", "use the jms client for consume", jms_consume);
- }
-
- public void parse__jms_consume(String jc)
- {
- this.jms_consume = Boolean.parseBoolean(jc);
- }
-
- {
- usage("--jms", "sets both --jms-publish and --jms-consume", false);
- }
-
- public void parse__jms(String j)
- {
- this.jms_publish = this.jms_consume = Boolean.parseBoolean(j);
- }
-
- {
- usage("-h, --help", "prints this message", null);
- }
-
- public void parse__help()
- {
- this.help = true;
- }
-
- public void parse_h()
- {
- parse__help();
- }
-
- public String parse(String ... args)
- {
- Class klass = getClass();
- List<String> arguments = new ArrayList<String>();
- for (int i = 0; i < args.length; i++)
- {
- String option = args[i];
-
- if (!option.startsWith("-"))
- {
- arguments.add(option);
- continue;
- }
-
- String method = "parse" + option.replace('-', '_');
- try
- {
- try
- {
- Method parser = klass.getMethod(method);
- parser.invoke(this);
- }
- catch (NoSuchMethodException e)
- {
- try
- {
- Method parser = klass.getMethod(method, String.class);
-
- String value = null;
- if (i + 1 < args.length)
- {
- value = args[i+1];
- i++;
- }
- else
- {
- return option + " requires a value";
- }
-
- parser.invoke(this, value);
- }
- catch (NoSuchMethodException e2)
- {
- return "no such option: " + option;
- }
- }
- }
- catch (InvocationTargetException e)
- {
- Throwable t = e.getCause();
- return String.format
- ("error parsing %s: %s: %s", option, t.getClass().getName(),
- t.getMessage());
- }
- catch (IllegalAccessException e)
- {
- throw new RuntimeException
- ("unable to access parse method: " + option, e);
- }
- }
-
- return parseArguments(arguments);
- }
-
- public String parseArguments(List<String> arguments)
- {
- if (arguments.size() > 0)
- {
- String args = arguments.toString();
- return "unrecognized arguments: " + args.substring(1, args.length() - 1);
- }
- else
- {
- return null;
- }
- }
-
- public String toString()
- {
- Class klass = getClass();
- Field[] fields = klass.getFields();
- StringBuilder str = new StringBuilder();
- for (int i = 0; i < fields.length; i++)
- {
- if (i > 0)
- {
- str.append("\n");
- }
-
- String name = fields[i].getName();
- str.append(name);
- str.append(" = ");
- Object value;
- try
- {
- value = fields[i].get(this);
- }
- catch (IllegalAccessException e)
- {
- throw new RuntimeException
- ("unable to access field: " + name, e);
- }
- str.append(value);
- }
-
- return str.toString();
- }
- }
-
- public static final void main(String[] args) throws Exception
- {
- final Options opts = new Options();
- String error = opts.parse(args);
- if (error != null)
- {
- System.err.println(error);
- System.exit(-1);
- return;
- }
-
- if (opts.help)
- {
- System.out.println(opts.usage);
- return;
- }
-
- System.out.println(opts);
-
- switch (opts.mode)
- {
- case CONSUME:
- case BOTH:
- Runnable r = new Runnable()
- {
- public void run()
- {
- try
- {
- if (opts.jms_consume)
- {
- jms_consumer(opts);
- }
- else
- {
- native_consumer(opts);
- }
- }
- catch (Exception e)
- {
- throw new RuntimeException(e);
- }
- System.out.println("Consumer Completed");
- }
- };
-
- Thread t;
- try
- {
- t = Threading.getThreadFactory().createThread(r);
- }
- catch(Exception e)
- {
- throw new Error("Error creating consumer thread",e);
- }
- t.start();
- break;
- }
-
- switch (opts.mode)
- {
- case PUBLISH:
- case BOTH:
- Runnable r = new Runnable()
- {
- public void run()
- {
- try
- {
- if (opts.jms_publish)
- {
- jms_publisher(opts);
- }
- else
- {
- native_publisher(opts);
- }
- }
- catch (Exception e)
- {
- throw new RuntimeException(e);
- }
- System.out.println("Producer Completed");
- }
- };
- Thread t;
- try
- {
- t = Threading.getThreadFactory().createThread(r);
- }
- catch(Exception e)
- {
- throw new Error("Error creating publisher thread",e);
- }
- t.start();
- break;
- }
- }
-
- private static enum Column
- {
- LEFT, RIGHT
- }
-
- private static final void sample(Options opts, Column col, String name, long count,
- long start, long time, long lastTime)
- {
- String pfx = "";
- String sfx = "";
- if (opts.mode == BOTH)
- {
- if (col == Column.RIGHT)
- {
- pfx = " -- ";
- }
- else
- {
- sfx = " --";
- }
- }
-
- if (count == 0)
- {
- String stats = String.format("%s: %tc", name, start);
- System.out.println(String.format("%s%-36s%s", pfx, stats, sfx));
- return;
- }
-
- double cumulative = 1000 * (double) count / (double) (time - start);
- double interval = 1000 * ((double) opts.sample / (double) (time - lastTime));
-
- String stats = String.format
- ("%s: %d %.2f %.2f", name, count, cumulative, interval);
- System.out.println(String.format("%s%-36s%s", pfx, stats, sfx));
- }
-
- private static final javax.jms.Connection getJMSConnection(Options opts) throws Exception
- {
- String url = String.format
- ("amqp://guest:guest@clientid/test?brokerlist='tcp://%s:%d'",
- opts.broker, opts.port);
- return new AMQConnection(url);
- }
-
- private static final void jms_publisher(Options opts) throws Exception
- {
- javax.jms.Connection conn = getJMSConnection(opts);
-
- javax.jms.Session ssn = conn.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
- Destination dest = ssn.createQueue("test-queue");
- Destination echo_dest = ssn.createQueue("echo-queue");
- MessageProducer prod = ssn.createProducer(dest);
- MessageConsumer cons = ssn.createConsumer(echo_dest);
- prod.setDisableMessageID(!opts.message_id);
- prod.setDisableMessageTimestamp(!opts.timestamp);
- prod.setDeliveryMode(opts.persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT);
-
- StringBuilder str = new StringBuilder();
- for (int i = 0; i < opts.size; i++)
- {
- str.append((char) (i % 128));
- }
-
- String body = str.toString();
-
- TextMessage cached = ssn.createTextMessage();
- cached.setText(body);
-
- conn.start();
-
- long count = 0;
- long lastTime = 0;
- long start = System.currentTimeMillis();
- while (opts.count == 0 || count < opts.count)
- {
- if (opts.window > 0 && (count % opts.window) == 0 && count > 0)
- {
- Message echo = cons.receive();
- }
-
- if (opts.sample > 0 && (count % opts.sample) == 0)
- {
- long time = System.currentTimeMillis();
- sample(opts, Column.LEFT, "JP", count, start, time, lastTime);
- lastTime = time;
- }
-
- TextMessage m;
- if (opts.message_cache)
- {
- m = cached;
- }
- else
- {
- m = ssn.createTextMessage();
- m.setText(body);
- }
-
- prod.send(m);
- count++;
- }
-
- conn.close();
- }
-
- private static final void jms_consumer(final Options opts) throws Exception
- {
- final javax.jms.Connection conn = getJMSConnection(opts);
- javax.jms.Session ssn = conn.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
- Destination dest = ssn.createQueue("test-queue");
- Destination echo_dest = ssn.createQueue("echo-queue");
- MessageConsumer cons = ssn.createConsumer(dest);
- final MessageProducer prod = ssn.createProducer(echo_dest);
- prod.setDisableMessageID(true);
- prod.setDisableMessageTimestamp(true);
- prod.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
- final TextMessage echo = ssn.createTextMessage();
- echo.setText("ECHO");
-
- final Object done = new Object();
- cons.setMessageListener(new MessageListener()
- {
- private long count = 0;
- private long lastTime = 0;
- private long start;
-
- public void onMessage(Message m)
- {
- if (count == 0)
- {
- start = System.currentTimeMillis();
- }
-
- try
- {
- boolean sample = opts.sample > 0 && (count % opts.sample) == 0;
- long time = sample ? System.currentTimeMillis() : 0;
-
- if (opts.window > 0 && (count % opts.window) == 0)
- {
- prod.send(echo);
- }
-
- if (sample)
- {
- sample(opts, Column.RIGHT, "JC", count, start, time, lastTime);
- lastTime = time;
- }
- }
- catch (JMSException e)
- {
- throw new RuntimeException(e);
- }
- count++;
-
- if (opts.count > 0 && count >= opts.count)
- {
- synchronized (done)
- {
- done.notify();
- }
- }
- }
- });
-
- conn.start();
- synchronized (done)
- {
- done.wait();
- }
- conn.close();
- }
-
- private static final org.apache.qpid.transport.Connection getConnection
- (Options opts)
- {
- org.apache.qpid.transport.Connection conn =
- new org.apache.qpid.transport.Connection();
- conn.connect(opts.broker, opts.port, null, "guest", "guest",false);
- return conn;
- }
-
- private static abstract class NativeListener implements SessionListener
- {
-
- public void opened(org.apache.qpid.transport.Session ssn) {}
-
- public void resumed(org.apache.qpid.transport.Session ssn) {}
-
- public void exception(org.apache.qpid.transport.Session ssn,
- SessionException exc)
- {
- exc.printStackTrace();
- }
-
- public void closed(org.apache.qpid.transport.Session ssn) {}
-
- }
-
- private static final void native_publisher(Options opts) throws Exception
- {
- final long[] echos = { 0 };
- org.apache.qpid.transport.Connection conn = getConnection(opts);
- org.apache.qpid.transport.Session ssn = conn.createSession();
- ssn.setSessionListener(new NativeListener()
- {
- public void message(org.apache.qpid.transport.Session ssn,
- MessageTransfer xfr)
- {
- synchronized (echos)
- {
- echos[0]++;
- echos.notify();
- }
- ssn.processed(xfr);
- }
- });
-
- ssn.invoke(new QueueDeclare().queue("test-queue").durable(false));
- ssn.invoke(new QueueDeclare().queue("echo-queue").durable(false));
- ssn.invoke(new ExchangeBind().exchange("amq.direct").queue("test-queue").bindingKey("test-queue"));
- ssn.invoke(new ExchangeBind().exchange("amq.direct").queue("echo-queue").bindingKey("echo-queue"));
-
- MessageProperties cached_mp = new MessageProperties();
- DeliveryProperties cached_dp = new DeliveryProperties();
- cached_dp.setRoutingKey("test-queue");
- cached_dp.setDeliveryMode
- (opts.persistent ? MessageDeliveryMode.PERSISTENT : MessageDeliveryMode.NON_PERSISTENT);
-
- int size = opts.size;
- ByteBuffer body = ByteBuffer.allocate(size);
- for (int i = 0; i < size; i++)
- {
- body.put((byte) i);
- }
- body.flip();
-
- ssn.invoke(new MessageSubscribe()
- .queue("echo-queue")
- .destination("echo-queue")
- .acceptMode(MessageAcceptMode.NONE)
- .acquireMode(MessageAcquireMode.PRE_ACQUIRED));
- ssn.messageSetFlowMode("echo-queue", MessageFlowMode.WINDOW);
- ssn.messageFlow("echo-queue", MessageCreditUnit.MESSAGE, 0xFFFFFFFF);
- ssn.messageFlow("echo-queue", MessageCreditUnit.BYTE, 0xFFFFFFFF);
-
- UUIDGen gen = UUIDs.newGenerator();
-
- long count = 0;
- long lastTime = 0;
- long start = System.currentTimeMillis();
- while (opts.count == 0 || count < opts.count)
- {
- if (opts.window > 0 && (count % opts.window) == 0 && count > 0)
- {
- synchronized (echos)
- {
- while (echos[0] < (count/opts.window))
- {
- echos.wait();
- }
- }
- }
-
- if (opts.sample > 0 && (count % opts.sample) == 0)
- {
- long time = System.currentTimeMillis();
- sample(opts, Column.LEFT, "NP", count, start, time, lastTime);
- lastTime = time;
- }
-
- MessageProperties mp;
- DeliveryProperties dp;
- if (opts.message_cache)
- {
- mp = cached_mp;
- dp = cached_dp;
- }
- else
- {
- mp = new MessageProperties();
- dp = new DeliveryProperties();
- dp.setRoutingKey("test-queue");
- dp.setDeliveryMode
- (opts.persistent ? MessageDeliveryMode.PERSISTENT : MessageDeliveryMode.NON_PERSISTENT);
-
- }
-
- if (opts.message_id)
- {
- mp.setMessageId(gen.generate());
- }
-
- if (opts.timestamp)
- {
- dp.setTimestamp(System.currentTimeMillis());
- }
-
- ssn.messageTransfer("amq.direct", MessageAcceptMode.NONE, MessageAcquireMode.PRE_ACQUIRED,
- new Header(dp, mp), body.slice());
- count++;
- }
-
- ssn.messageCancel("echo-queue");
-
- ssn.sync();
- ssn.close();
- conn.close();
- }
-
- private static final void native_consumer(final Options opts) throws Exception
- {
- final DeliveryProperties dp = new DeliveryProperties();
- final byte[] echo = new byte[0];
- dp.setRoutingKey("echo-queue");
- dp.setDeliveryMode(MessageDeliveryMode.NON_PERSISTENT);
- final MessageProperties mp = new MessageProperties();
- final Object done = new Object();
- org.apache.qpid.transport.Connection conn = getConnection(opts);
- org.apache.qpid.transport.Session ssn = conn.createSession();
- ssn.setSessionListener(new NativeListener()
- {
- private long count = 0;
- private long lastTime = 0;
- private long start;
-
- public void message(org.apache.qpid.transport.Session ssn,
- MessageTransfer xfr)
- {
- if (count == 0)
- {
- start = System.currentTimeMillis();
- }
-
- boolean sample = opts.sample > 0 && (count % opts.sample) == 0;
- long time = sample ? System.currentTimeMillis() : 0;
-
- if (opts.window > 0 && (count % opts.window) == 0)
- {
- ssn.messageTransfer("amq.direct",
- MessageAcceptMode.NONE,
- MessageAcquireMode.PRE_ACQUIRED,
- new Header(dp, mp),
- echo);
- }
-
- if (sample)
- {
- sample(opts, Column.RIGHT, "NC", count, start, time, lastTime);
- lastTime = time;
- }
- ssn.processed(xfr);
- count++;
-
- if (opts.count > 0 && count >= opts.count)
- {
- synchronized (done)
- {
- done.notify();
- }
- }
- }
- });
-
- ssn.invoke(new QueueDeclare().queue("test-queue").durable(false));
- ssn.invoke(new QueueDeclare().queue("echo-queue").durable(false));
- ssn.invoke(new ExchangeBind().exchange("amq.direct").queue("test-queue").bindingKey("test-queue"));
- ssn.invoke(new ExchangeBind().exchange("amq.direct").queue("echo-queue").bindingKey("echo-queue"));
-
- ssn.invoke(new MessageSubscribe()
- .queue("test-queue")
- .destination("test-queue")
- .acceptMode(MessageAcceptMode.NONE)
- .acquireMode(MessageAcquireMode.PRE_ACQUIRED));
- ssn.messageSetFlowMode("test-queue", MessageFlowMode.WINDOW);
- ssn.messageFlow("test-queue", MessageCreditUnit.MESSAGE, 0xFFFFFFFF);
- ssn.messageFlow("test-queue", MessageCreditUnit.BYTE, 0xFFFFFFFF);
-
- synchronized (done)
- {
- done.wait();
- }
-
- ssn.messageCancel("test-queue");
-
- ssn.sync();
- ssn.close();
- conn.close();
- }
-
-}
diff --git a/java/tools/src/main/java/org/apache/qpid/tools/TestParams.java b/java/tools/src/main/java/org/apache/qpid/tools/TestParams.java
deleted file mode 100644
index 89d6462a39..0000000000
--- a/java/tools/src/main/java/org/apache/qpid/tools/TestParams.java
+++ /dev/null
@@ -1,170 +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.tools;
-
-import javax.jms.Session;
-
-public class TestParams
-{
- /*
- * By default the connection URL is used.
- * This allows a user to easily specify a fully fledged URL any given property.
- * Ex. SSL parameters
- *
- * By providing a host & port allows a user to simply override the URL.
- * This allows to create multiple clients in test scripts easily,
- * without having to deal with the long URL format.
- */
- private String url = "amqp://guest:guest@clientid/testpath?brokerlist='tcp://localhost:5672'";
-
- private String host = "";
-
- private int port = -1;
-
- private String address = "queue; {create : always}";
-
- private int msg_size = 1024;
-
- private int msg_type = 1; // not used yet
-
- private boolean cacheMessage = false;
-
- private boolean disableMessageID = false;
-
- private boolean disableTimestamp = false;
-
- private boolean durable = false;
-
- private boolean transacted = false;
-
- private int transaction_size = 1000;
-
- private int ack_mode = Session.AUTO_ACKNOWLEDGE;
-
- private int msg_count = 10;
-
- private int warmup_count = 1;
-
- private boolean random_msg_size = false;
-
- public TestParams()
- {
-
- url = System.getProperty("url",url);
- host = System.getProperty("host","");
- port = Integer.getInteger("port", -1);
- address = System.getProperty("address","queue");
-
- msg_size = Integer.getInteger("msg_size", 1024);
- msg_type = Integer.getInteger("msg_type",1);
- cacheMessage = Boolean.getBoolean("cache_msg");
- disableMessageID = Boolean.getBoolean("disableMessageID");
- disableTimestamp = Boolean.getBoolean("disableTimestamp");
- durable = Boolean.getBoolean("durable");
- transacted = Boolean.getBoolean("transacted");
- transaction_size = Integer.getInteger("trans_size",1000);
- ack_mode = Integer.getInteger("ack_mode",Session.AUTO_ACKNOWLEDGE);
- msg_count = Integer.getInteger("msg_count",msg_count);
- warmup_count = Integer.getInteger("warmup_count",warmup_count);
- random_msg_size = Boolean.getBoolean("random_msg_size");
- }
-
- public String getUrl()
- {
- return url;
- }
-
- public String getHost()
- {
- return host;
- }
-
- public int getPort()
- {
- return port;
- }
-
- public String getAddress()
- {
- return address;
- }
-
- public int getAckMode()
- {
- return ack_mode;
- }
-
- public int getMsgCount()
- {
- return msg_count;
- }
-
- public int getMsgSize()
- {
- return msg_size;
- }
-
- public int getMsgType()
- {
- return msg_type;
- }
-
- public boolean isDurable()
- {
- return durable;
- }
-
- public boolean isTransacted()
- {
- return transacted;
- }
-
- public int getTransactionSize()
- {
- return transaction_size;
- }
-
- public int getWarmupCount()
- {
- return warmup_count;
- }
-
- public boolean isCacheMessage()
- {
- return cacheMessage;
- }
-
- public boolean isDisableMessageID()
- {
- return disableMessageID;
- }
-
- public boolean isDisableTimestamp()
- {
- return disableTimestamp;
- }
-
- public boolean isRandomMsgSize()
- {
- return random_msg_size;
- }
-
-}
diff --git a/java/upload.xml b/java/upload.xml
deleted file mode 100644
index 9f2fd6819b..0000000000
--- a/java/upload.xml
+++ /dev/null
@@ -1,90 +0,0 @@
-<?xml version="1.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.
--->
-<project name="upload" default="upload" xmlns:ivy="antlib:org.apache.ivy.ant">
- <description>Targets for uploading releases to ASF's Nexus instance</description>
-
- <property name="nexus.organisation" value="org.apache"/>
- <property name="nexus.host" value="repository.apache.org"/>
- <property name="nexus.upload.url" value="https://repository.apache.org/service/local/staging/deploy/maven2"/>
-
- <!-- properties for downloading ivy if required -->
- <property name="ivy.jar.dir" value="lib/ivy" />
- <property name="ivy.install.version" value="2.2.0" />
- <property name="ivy.jar.file" value="${ivy.jar.dir}/ivy-${ivy.install.version}.jar" />
- <property name="ivy.repo.url" value="http://repo1.maven.org/maven2/org/apache/ivy/ivy"/>
-
- <target name="download-ivy">
- <mkdir dir="${ivy.jar.dir}"/>
- <!-- download Ivy from web site so that it can be used without any special installation -->
- <echo message="Downloading ivy..."/>
- <get src="${ivy.repo.url}/${ivy.install.version}/ivy-${ivy.install.version}.jar"
- dest="${ivy.jar.file}" usetimestamp="true"/>
- </target>
-
- <target name="load-ivy">
- <!-- Try to load Ivy from local ivy dir, in case the user has not already dropped it into
- Ant's lib dir (note that the latter copy will always take precedence). Won't
- fail so long as Ivy is in at least one of the locations. -->
- <mkdir dir="${ivy.jar.dir}"/>
- <path id="ivy.lib.path">
- <fileset dir="${ivy.jar.dir}" includes="*.jar"/>
- </path>
- <taskdef resource="org/apache/ivy/ant/antlib.xml"
- uri="antlib:org.apache.ivy.ant" classpathref="ivy.lib.path"/>
- </target>
-
- <!-- check the following properties which must be specified by the user-->
- <target name="check-props-exist" description="check that the required properties have been set">
- <fail unless="nexus.user" message="You must supply the 'nexus.user' property"/>
- <fail unless="nexus.password" message="You must supply the 'nexus.password' property"/>
- <fail unless="maven.artifact.dir" message="You must supply the 'maven.artifact.dir' property"/>
- </target>
-
- <target name="perform-nexus-upload" description="really requires the prepare-upload target to be run first">
- <ivy:configure file="ivysettings-nexus.xml"/>
- <ivy:resolve file="ivy.xml"/>
- <ivy:retrieve/>
- <ivy:deliver/>
- <ivy:publish publishivy="false" resolver="nexus"
- artifactspattern="${maven.artifact.dir}/[organisation]/[module]/[artifact]/[revision]/[artifact]-[revision](-[classifier]).[ext]"/>
- </target>
-
- <target name="upload" depends="load-ivy, check-props-exist, perform-nexus-upload"/>
-
- <target name="help" description="display detailed build documentation">
- <echo>
-Ivy can be leveraged either by installing it in the Ant lib dir yourself,
-or by running the following command in qpid/java to place it in the
-qpid/java/lib/ivy lib folder:
-
- ant -buildfile upload.xml download-ivy
-
-The publishing task should be run once the release process has otherwise
-been completed and the artifacts signed. It can be performed from the
-qpid/java directory with a command as follows:
-
- ant -buildfile upload.xml -Dnexus.user=&lt;apache_username&gt; -Dnexus.password=&lt;password&gt;
- -Dmaven.artifact.dir=&lt;path to maven repo structure from release process&gt;
-
-Note: if you are behind a proxy server it is necessary to give Ant the
-proxy settings by doing something like:
-
-export ANT_OPTS=&quot;-Dhttp.proxyHost=&lt;host&gt; -Dhttp.proxyPort=&lt;port&gt; -Dhttps.proxyHost=&lt;host&gt; -Dhttps.proxyPort=&lt;port&gt;&quot;
- </echo>
- </target>
-</project>